test: fix shared state, CI-vacuous tests and harness duplication (#2722)

Follow-up to #2721. It fixes how the remaining tests behave and changes no production code.

## CI
- Both `dotnet test` steps pass `--filter "Category!=Manual"`. Before this, Manual-tagged tests ran on CI anyway.
- The one surviving movement-throttle latency test is the only coverage of burst forgiveness over a full, wrapped history. It loses its Manual tag, so it runs on CI.

## Tests that passed on CI without testing anything
- **Corpse and throwing tests.** They relied on tiledata for the weapon `Layer`, so on CI the equip silently failed and they asserted against empty lists. They now set `Layer` explicitly and assert the equip took effect. `TestThrown` also pins its own strength and range values, so a shard retuning SoulGlaive no longer breaks them.
- **Healthbar poison rows.** Server.Tests registers no poisons, so every row tested `null`. They now use real poison levels.
- **Account packet tests.** The mock accounts reported `Length` 0, so the character-list tests only ever encoded empty slots. They now encode the real characters.
- **Pathing and AI tests that only mean something on real Trammel/Felucca terrain** are now guarded with `TileDataRequirement.SkipIfMissing()`: Britain desk and clutter scenes, house footprints (no MultiData on CI) and fingerprints. Tests that are valid on flat blank terrain stay unguarded. (A synthetic tiledata fixture to run these on CI is a planned follow-up.)
- **Assertions that couldn't fail now check their claim.** Affected tests include the `DefaultWalker` cache use, cache on/off parity requiring a path, the recorder capability flags, the idle-pet gate, the monthly DST recurrence, the AdvancedSearch `Record.Exception` wrappers, `CanFitItem` with no branch-guarded assert, the Firewall callback, and `Import_NoMap`. The Geometry Parse asserts also now use the same input as their TryParse.

## Shared state
Every test that changes process-wide state now restores it, even when an assert fails:
- **The clock.** A new `TimerWheelScope` saves and restores `Core._tickCount`, `Core._now` and the timer wheel. `SimulatedClockScope` covers decay tests.
- **StepCache settings and caches**, via `StepCacheStateScope`.
- **Network state.** The ManualAllowlist, LoginAllowlist, firewall and BanChannel reporters are restored. Global packet handlers are now registered per test and removed afterwards, so they no longer stay registered for later tests.
- **Data and config tables.** `ArchiveJournal` statics, `TileData.ItemTable`, `ObjectPropertyList.Enabled`, `Core.Expansion` and the localization table are restored. One `MobileStatusVersion` restore was resetting a different expansion than the one the test changed.
- **Entities.** Tests with fixed serials now delete what they create. Fixed mobile serials moved to `World.NewMobile`, because deleting a hard-coded serial could unregister a live entity.
- **Collection race.** `SpiralScanTests` no longer clears the spawn cache from a separate collection that could run in parallel with the cache-manager tests.
- **Shared statics.** Classes reading shared static allowlists joined the sequential collection.

## Duplication
New shared helpers replace copy-pasted harness code:
- **Server.Tests:** `PacketAssert.Sends`, used by about 130 packet tests; `TestClientHarness`, `PersistencePipelineScope`, `NetTestHelpers`, `EntityCleanup` and one `TestMulti`.
- **UOContent.Tests:** `TimerWheelScope`, which also holds one wraparound-safe `RunFor`/`RunUntil`; `AiTestStubs`, which merges six walker copies and five identical creature stubs; `MobileTestHarness`, `CommandTestHarness` and `TempDirectory`.

Dead oracle packet classes are removed.

## Cost
| Test | Before | After |
|---|---|---|
| `VirtualSerialTests` | 1.57s | 2ms (starts near the wrap via reflection instead of drawing ~17.9M serials) |
| Event scheduler recurrence loop | 473ms | 1ms |
| CrowdSec drain | 517ms | 16ms (event-driven instead of a fixed 500ms wait) |
| AuthId tests | 248ms | 99ms (SHA2 except the two GameLogin tests) |
| Container cap tests | 5,000 items | 3,449 / 3,277 (one past each protocol cap) |
| Bulk removal | 100k children | 20k children |
| OPL hash distribution | 60k builds | 10k builds |

## Shard-tuning decoupling
- AI assertions read `ReacquireDelay` and `FollowMoveSpeed` instead of hard-coding production tuning.
- The guard friendly-fire test uses an `AI_Mage` stub instead of WhiteWyrm.
- Argon2 assertions pin the `argon2id` variant and `v=19` but read the cost parameters from the configured hasher.

## Tests
| Run | Server.Tests | UOContent.Tests |
|---|---|---|
| With client files | 812 pass | 1,123 pass |
| Without client files (CI simulation) | 800 pass, 12 skip | 1,021 pass, 102 skip |

- The UOContent fixture reads `MODERNUO_TEST_DATA_DIR`; Server.Tests reads `MODERNUO_CLIENT_PATH`.
- The 15 new UOContent skips are the map-dependent guards above.
- Total run time with client files is about 5s, down from about 8s.
This commit is contained in:
Kamron Batman 2026-10-18 20:11:33 -07:00 • committed by GitHub
parent 79f736aa83
commit 00134cac33
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
135 changed files with 3164 additions and 4020 deletions

View file

@ -1,6 +1,7 @@
using System;
using Server.Accounting;
using Server.Accounting.Security;
using Server.Tests.Accounting.Security;
using Xunit;
namespace Server.Tests.Accounting;
@ -64,7 +65,9 @@ public class AccountPasswordTests : IDisposable
"$argon2i$v=19$m=8192,t=3,p=1$LD1XJz7P3wQmIJ+Tu6ScgA$NO5hBABsHQ172C5nDO2X4gWnB4jDef3x6WhLdVE2LFw";
Assert.True(account.CheckPassword(Password));
Assert.StartsWith("$argon2id$v=19$m=16384,t=1,p=1$", account.Password);
// The cost parameters are shard-tunable; the variant and version are not.
Assert.StartsWith("$argon2id$v=19$", account.Password);
Assert.StartsWith(Argon2TestParameters.CurrentPrefix, account.Password);
// Already current: verifying again must not rewrite the hash.
var afterFirst = account.Password;

View file

@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Threading;
using Server.Accounting;
using Server.Accounting.Security;
using Server.Tests.Accounting.Security;
using Xunit;
namespace Server.Tests.Accounting;
@ -13,12 +15,27 @@ public class PasswordWorkerTests : IDisposable
private readonly PasswordProtectionAlgorithm _originalAlgorithm = AccountSecurity.CurrentAlgorithm;
// The constructor registers each account in the process-wide Accounts table.
private readonly List<Account> _created = [];
public PasswordWorkerTests() => AccountSecurity.CurrentAlgorithm = PasswordProtectionAlgorithm.Argon2;
public void Dispose() => AccountSecurity.CurrentAlgorithm = _originalAlgorithm;
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
private static Account CreateAccount(string username) =>
Accounts.GetAccount(username) as Account ?? new Account(username, Password);
AccountSecurity.CurrentAlgorithm = _originalAlgorithm;
}
private Account CreateAccount(string username)
{
var account = new Account(username, Password);
_created.Add(account);
return account;
}
/// <summary>
/// Enqueues work, then pumps the loop context until <paramref name="complete"/> or the deadline.
@ -136,7 +153,8 @@ public class PasswordWorkerTests : IDisposable
var outcome = PasswordWorker.ComputeInline(JobFor(account, Password));
Assert.True(outcome.Verified);
Assert.StartsWith("$argon2id$v=19$m=16384,t=1,p=1$", outcome.Hash);
Assert.StartsWith("$argon2id$v=19$", outcome.Hash);
Assert.StartsWith(Argon2TestParameters.CurrentPrefix, outcome.Hash);
}
[Fact]

View file

@ -0,0 +1,55 @@
using System;
using Server.Accounting.Security;
namespace Server.Tests.Accounting.Security;
/// <summary>
/// The PHC parameter prefix the configured <see cref="Argon2PasswordProtection"/> writes, read from
/// a real hash so a shard that tunes the Argon2 cost does not break assertions about the format.
/// </summary>
internal static class Argon2TestParameters
{
/// <summary>For example <c>$argon2id$v=19$m=16384,t=1,p=1$</c>, ending at the salt.</summary>
public static readonly string CurrentPrefix = ReadPrefix();
public static string Type => CurrentPrefix.Split('$')[1];
public static string Version => CurrentPrefix.Split('$')[2];
public static int Memory => ReadCost('m');
public static int Time => ReadCost('t');
public static int Parallelism => ReadCost('p');
public static string BuildPrefix(string type, int memory, int time, int parallelism) =>
$"${type}${Version}$m={memory},t={time},p={parallelism}$";
private static string ReadPrefix()
{
var hash = Argon2PasswordProtection.Instance.EncryptPassword("prefix-probe");
// $type$version$params$salt$digest: the prefix runs through the fourth '$'.
var end = 0;
for (var i = 0; i < 4; i++)
{
end = hash.IndexOf('$', end) + 1;
}
return hash[..end];
}
private static int ReadCost(char key)
{
var costs = CurrentPrefix.Split('$')[3].Split(',');
for (var i = 0; i < costs.Length; i++)
{
if (costs[i][0] == key)
{
return int.Parse(costs[i].AsSpan(2));
}
}
return -1;
}
}

View file

@ -113,34 +113,60 @@ public class PasswordProtectionTest
Assert.False(Argon2PasswordProtection.Instance.ValidatePassword(LegacyArgon2iHash, "wrong"));
}
[Theory]
// type, memory, time, parallelism -> expected NeedsRehash
[InlineData("argon2id", 16384, 1, 1, false)] // current defaults
[InlineData("argon2i", 8192, 3, 1, true)] // the old shipping default
[InlineData("argon2id", 8192, 1, 1, true)] // right type, stale memory
[InlineData("argon2id", 16384, 3, 1, true)] // right type, stale iterations
[InlineData("argon2id", 16384, 1, 2, true)] // right type, stale parallelism
[InlineData("argon2i", 16384, 1, 1, true)] // right cost, stale type
public void Argon2_NeedsRehash_ComparesTypeAndCost(
string type, int memory, int time, int parallelism, bool expected
)
{
var hash = $"${type}$v=19$m={memory},t={time},p={parallelism}$" +
"LD1XJz7P3wQmIJ+Tu6ScgA$NO5hBABsHQ172C5nDO2X4gWnB4jDef3x6WhLdVE2LFw";
private const string SaltAndDigest = "LD1XJz7P3wQmIJ+Tu6ScgA$NO5hBABsHQ172C5nDO2X4gWnB4jDef3x6WhLdVE2LFw";
Assert.Equal(expected, Argon2PasswordProtection.Instance.NeedsRehash(hash));
[Fact]
public void Argon2_NeedsRehash_IsFalseForCurrentParameters()
{
var hash = Argon2TestParameters.CurrentPrefix + SaltAndDigest;
Assert.False(Argon2PasswordProtection.Instance.NeedsRehash(hash));
}
// Each case differs from the configured parameters in exactly one field, so the test holds
// whatever cost a shard configures.
[Theory]
[InlineData("type")]
[InlineData("memory")]
[InlineData("time")]
[InlineData("parallelism")]
public void Argon2_NeedsRehash_ComparesTypeAndCost(string staleField)
{
var type = Argon2TestParameters.Type;
var memory = Argon2TestParameters.Memory;
var time = Argon2TestParameters.Time;
var parallelism = Argon2TestParameters.Parallelism;
var otherType = type == "argon2id" ? "argon2i" : "argon2id";
(type, memory, time, parallelism) = staleField switch
{
"type" => (otherType, memory, time, parallelism),
"memory" => (type, memory * 2, time, parallelism),
"time" => (type, memory, time + 1, parallelism),
_ => (type, memory, time, parallelism + 1)
};
var hash = Argon2TestParameters.BuildPrefix(type, memory, time, parallelism) + SaltAndDigest;
Assert.True(Argon2PasswordProtection.Instance.NeedsRehash(hash));
}
[Fact]
public void Argon2_NeedsRehash_IsTrueForLegacyShippingDefault()
{
Assert.True(Argon2PasswordProtection.Instance.NeedsRehash(LegacyArgon2iHash));
}
// Digest and salt lengths are decoded base64 sizes rather than parameter-list entries, so they
// need their own literals. Current type and cost throughout; only a length differs.
[Theory]
// 16-byte digest: 22 base64 chars instead of the 43 a 32-byte digest encodes to.
[InlineData("$argon2id$v=19$m=16384,t=1,p=1$LD1XJz7P3wQmIJ+Tu6ScgA$NO5hBABsHQ172C5nDO2X4g")]
[InlineData("LD1XJz7P3wQmIJ+Tu6ScgA$NO5hBABsHQ172C5nDO2X4g")]
// 8-byte salt: 11 base64 chars instead of the 22 a 16-byte salt encodes to.
[InlineData("$argon2id$v=19$m=16384,t=1,p=1$LD1XJz7P3wQ$NO5hBABsHQ172C5nDO2X4gWnB4jDef3x6WhLdVE2LFw")]
public void Argon2_NeedsRehash_ComparesSaltAndDigestLengths(string hash)
[InlineData("LD1XJz7P3wQ$NO5hBABsHQ172C5nDO2X4gWnB4jDef3x6WhLdVE2LFw")]
public void Argon2_NeedsRehash_ComparesSaltAndDigestLengths(string saltAndDigest)
{
Assert.True(Argon2PasswordProtection.Instance.NeedsRehash(hash));
Assert.True(Argon2PasswordProtection.Instance.NeedsRehash(Argon2TestParameters.CurrentPrefix + saltAndDigest));
}
[Theory]

View file

@ -4,6 +4,7 @@ using Server;
using Server.Commands;
using Server.Commands.Generic;
using Server.Items;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Commands;
@ -14,31 +15,13 @@ namespace UOContent.Tests.Commands;
[Collection("Sequential UOContent Tests")]
public class ChainedBindingSortTests : IDisposable
{
private readonly List<Item> _items = [];
private readonly CommandTestHarness _harness = new();
public void Dispose()
{
for (var i = 0; i < _items.Count; i++)
{
_items[i].Delete();
}
public void Dispose() => _harness.Dispose();
_items.Clear();
}
private SkillTeleporter Teleporter(TextDefinition message) => _harness.Teleporter(message);
private SkillTeleporter Teleporter(TextDefinition message)
{
var tp = new SkillTeleporter { Message = message };
_items.Add(tp);
return tp;
}
private static Property Bind(string binding)
{
var prop = new Property(binding);
prop.BindTo(typeof(SkillTeleporter), PropertyAccess.Read);
return prop;
}
private static Property Bind(string binding) => CommandTestHarness.Bind(typeof(SkillTeleporter), binding);
private static IComparer<object> Sorter(string binding) =>
SortCompiler.Compile<object>(
@ -107,6 +90,4 @@ public class ChainedBindingSortTests : IDisposable
Assert.True(comparer.Compare(blank, valued) < 0);
Assert.True(comparer.Compare(valued, blank) > 0);
}
// An unchained binding never had the problem and must keep working untouched.
}

View file

@ -4,42 +4,25 @@ using Server;
using Server.Commands;
using Server.Commands.Generic;
using Server.Items;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Commands;
// Two shapes the IL emitter got wrong or could not express. A chained binding ending in a value
// type (Message.Number) reused a temp while its value was still live, so every pair compared
// equal and `sort by` was a no-op. A struct with no CompareTo fell through to a raw Ceq, which is
// not valid IL for a non-primitive struct. Both are pinned here against the expression-tree port.
// Two shapes the compiled comparers must handle. A chained binding ending in a value type
// (Message.Number) must order and separate by that value, or every pair compares equal and
// `sort by` does nothing. A struct with no CompareTo compares by value equality for == and !=,
// and the relational operators are rejected when the condition is compiled.
[Collection("Sequential UOContent Tests")]
public class ConditionalCompilerEdgeTests : IDisposable
{
private readonly List<Item> _items = [];
private readonly CommandTestHarness _harness = new();
public void Dispose()
{
for (var i = 0; i < _items.Count; i++)
{
_items[i].Delete();
}
public void Dispose() => _harness.Dispose();
_items.Clear();
}
private SkillTeleporter Teleporter(TextDefinition message) => _harness.Teleporter(message);
private SkillTeleporter Teleporter(TextDefinition message)
{
var tp = new SkillTeleporter { Message = message };
_items.Add(tp);
return tp;
}
private static Property Bind(Type type, string binding)
{
var prop = new Property(binding);
prop.BindTo(type, PropertyAccess.Read);
return prop;
}
private static Property Bind(Type type, string binding) => CommandTestHarness.Bind(type, binding);
[Fact]
public void SortingOnAChainedValueTypeOrdersValues()

View file

@ -4,6 +4,7 @@ using Server;
using Server.Commands;
using Server.Commands.Generic;
using Server.Items;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Commands;
@ -14,23 +15,14 @@ namespace UOContent.Tests.Commands;
[Collection("Sequential UOContent Tests")]
public class DistinctComparerTests : IDisposable
{
private readonly List<Item> _items = [];
private readonly CommandTestHarness _harness = new();
public void Dispose()
{
for (var i = 0; i < _items.Count; i++)
{
_items[i].Delete();
}
_items.Clear();
}
public void Dispose() => _harness.Dispose();
private SkillTeleporter Teleporter(Action<SkillTeleporter> setup = null)
{
var tp = new SkillTeleporter();
var tp = _harness.Track(new SkillTeleporter());
setup?.Invoke(tp);
_items.Add(tp);
return tp;
}
@ -40,8 +32,7 @@ public class DistinctComparerTests : IDisposable
for (var i = 0; i < bindings.Length; i++)
{
props[i] = new Property(bindings[i]);
props[i].BindTo(typeof(SkillTeleporter), PropertyAccess.Read);
props[i] = CommandTestHarness.Bind(typeof(SkillTeleporter), bindings[i]);
}
return (IEqualityComparer<object>)DistinctCompiler.Compile<object>(typeof(SkillTeleporter), props);

View file

@ -6,10 +6,8 @@ using Xunit;
namespace UOContent.Tests.Commands;
// The conditional compiler emits into a fresh dynamic assembly for every command invocation --
// there is no per-type cache, so `Run` (which can never be unloaded) grows the process by one
// assembly per `[global where`. And PropertyValue could only load a handful of primitive constant
// types, so a comparison against anything narrower or unsigned than int threw instead of running.
// A comparison constant is converted to the property's own type, however narrow or unsigned, so
// conditions on byte, sbyte, short, ushort, uint and ulong properties run and compare correctly.
public class EmitterRobustnessTests
{
public class Subject

View file

@ -3,37 +3,27 @@ using System.Collections.Generic;
using Server;
using Server.Commands.Generic;
using Server.Items;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Commands;
// `where` compiles conditions to IL. Two shapes were broken there: a property type with value
// equality but no IComparable fell through to a raw Ceq (reference equality, so never true), and
// a chained binding dereferenced every link with no null guard (so the first object with a null
// intermediate took the whole sweep down with an NRE).
// `where` compiles conditions into a delegate. A property type with value equality but no
// IComparable compares by value, not reference identity, and a chained binding with a null
// intermediate makes the condition false rather than throwing and ending the whole sweep.
[Collection("Sequential UOContent Tests")]
public class ObjectConditionalTests : IDisposable
{
private readonly List<Item> _items = [];
private readonly CommandTestHarness _harness = new();
private readonly Mobile _from = new() { AccessLevel = AccessLevel.Developer };
public void Dispose()
{
for (var i = 0; i < _items.Count; i++)
{
_items[i].Delete();
}
_items.Clear();
_harness.Dispose();
_from.Delete();
}
private SkillTeleporter Teleporter(TextDefinition message)
{
var tp = new SkillTeleporter { Message = message };
_items.Add(tp);
return tp;
}
private SkillTeleporter Teleporter(TextDefinition message) => _harness.Teleporter(message);
private bool Check(object target, params string[] condition)
{

View file

@ -58,8 +58,7 @@ public class AdvancedSearchConditionsTests
[InlineData("Hue")] // no operator
public void UnusableLeafIsNoMatchAndDoesNotThrow(string test)
{
var ex = Record.Exception(() => Assert.False(Check(test)));
Assert.Null(ex);
Assert.False(Check(test));
}
// The old evaluator negated a failed comparison, so `~Hue=abc` matched every entity.
@ -195,8 +194,7 @@ public class AdvancedSearchConditionsTests
[Fact]
public void ReferenceTypeOrderingIsNoMatchAndDoesNotThrow()
{
var ex = Record.Exception(() => Assert.False(Check("Reference>whatever")));
Assert.Null(ex);
Assert.False(Check("Reference>whatever"));
}
[Fact]

View file

@ -4,6 +4,7 @@ using Xunit;
namespace UOContent.Tests;
// Registers the poison table, which is process-wide, so this stays in the sequential collection.
[Collection("Sequential UOContent Tests")]
public class AdvancedSearchTypesTests
{
@ -15,7 +16,11 @@ public class AdvancedSearchTypesTests
[Fact]
public void Poison_ReferenceTypeParsedViaTypes()
{
PoisonKinds.Configure(); // idempotent; registers Lesser..Lethal now that Core.Expansion is set
// The fixture does not run PoisonKinds.Configure, and a second registration throws.
if (Poison.Poisons.Count == 0)
{
PoisonKinds.Configure();
}
// Poison is a reference type implementing ISpanParsable; its value routes through the shared
// Server.Types converter. Poison.Parse returns the registered singleton, so "= Lethal" is a
@ -26,8 +31,6 @@ public class AdvancedSearchTypesTests
Assert.True(AdvancedSearchConditions.Compile(typeof(Subject), "Venom=Lethal")(subject));
Assert.False(AdvancedSearchConditions.Compile(typeof(Subject), "Venom=Lesser")(subject));
var ex = Record.Exception(() =>
Assert.False(AdvancedSearchConditions.Compile(typeof(Subject), "Venom=notapoison")(subject)));
Assert.Null(ex);
Assert.False(AdvancedSearchConditions.Compile(typeof(Subject), "Venom=notapoison")(subject));
}
}

View file

@ -2,13 +2,19 @@ using System;
using System.Collections.Generic;
using Server;
using Server.Engines.Events;
using Server.Tests;
using Xunit;
namespace UOContent.Tests;
[Collection("Sequential UOContent Tests")]
public class EventSchedulerTests
public class EventSchedulerTests : IDisposable
{
// Init() pins the process-wide loop clock and timer wheel; every other test in the host reads them.
private readonly TimerWheelScope _clock = new();
public void Dispose() => _clock.Dispose();
// Test implementations for controlled testing
private class TestRecurrencePattern : IRecurrencePattern
{
@ -58,7 +64,6 @@ public class EventSchedulerTests
private static void Init()
{
Core._now = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc);
Timer.Init(0);
EventScheduler.Configure();
}
@ -148,39 +153,36 @@ public class EventSchedulerTests
[Fact]
public void Scheduler_HandlesRecurringEvents()
{
for (var i = 0; i < 100_000; i++)
Init();
try
{
Init();
var callCount = 0;
try
{
var callCount = 0;
// Create a recurrence pattern that fires every 10 seconds, up to 3 times
var recurrence = new TestRecurrencePattern(TimeSpan.FromSeconds(10), 3);
// Create a recurrence pattern that fires every 10 seconds, up to 3 times
var recurrence = new TestRecurrencePattern(TimeSpan.FromSeconds(10), 3);
var evt = new TestScheduledEvent(
TimeOnly.FromDateTime(Core._now),
() => callCount++,
recurrence
);
var evt = new TestScheduledEvent(
TimeOnly.FromDateTime(Core._now),
() => callCount++,
recurrence
);
evt.Schedule(Core._now);
evt.Schedule(Core._now);
// Advance time to after all occurrences should have happened
Core._now = Core._now.AddSeconds(50);
Timer.Slice(8);
// Advance time to after all occurrences should have happened
Core._now = Core._now.AddSeconds(50);
Timer.Slice(8);
// One call per occurrence the pattern yields
Assert.Equal(3, callCount);
Assert.Equal(3, evt.CallCount);
// Should have fired 4 times (3 recurrences)
Assert.Equal(3, callCount);
Assert.Equal(3, evt.CallCount);
evt.Cancel();
}
finally
{
Finish();
}
evt.Cancel();
}
finally
{
Finish();
}
}

View file

@ -225,10 +225,13 @@ public class RecurrencePatternTests
}
[Theory]
[InlineData("America/New_York", 2024, 3, 10, 2, 30)] // Spring forward - 2:30 AM doesn't exist
[InlineData("America/New_York", 2024, 11, 3, 1, 30)] // Fall back - 1:30 AM happens twice
// 2:30 AM does not exist on the spring-forward day, so the occurrence moves to the next month.
[InlineData("America/New_York", 2024, 3, 10, 2, 30, 2024, 4, 10, 6, 30)]
// 1:30 AM happens twice on the fall-back day; LocalToUtc resolves it to the first (EDT) pass.
[InlineData("America/New_York", 2024, 11, 3, 1, 30, 2024, 11, 3, 5, 30)]
public void MonthlyRecurrencePattern_DSTTransitions_HandlesCorrectly(
string tzId, int year, int month, int day, int hour, int minute)
string tzId, int year, int month, int day, int hour, int minute,
int expectedYear, int expectedMonth, int expectedDay, int expectedHour, int expectedMinute)
{
// Arrange
var tz = TimeZoneInfo.FindSystemTimeZoneById(tzId);
@ -238,19 +241,14 @@ public class RecurrencePatternTests
var beforeUtc = localDateBefore.LocalToUtc(tz);
var timeOnly = new TimeOnly(hour, minute);
// Act - shouldn't throw exceptions
// Act
var result = pattern.GetNextOccurrence(beforeUtc, timeOnly, tz);
// Assert - just make sure we got a valid result
Assert.NotEqual(DateTime.MaxValue, result);
// For invalid times (spring forward), should skip to next valid time
var resultLocal = TimeZoneInfo.ConvertTimeFromUtc(result, tz);
if (month == 3) // Spring forward
{
// Should skip the invalid 2:30 AM time
Assert.True(resultLocal.Hour >= 3 || resultLocal > new DateTime(year, month, day));
}
// Assert
var expectedUtc = new DateTime(
expectedYear, expectedMonth, expectedDay, expectedHour, expectedMinute, 0, DateTimeKind.Utc
);
Assert.Equal(expectedUtc, result);
}
[Fact]

View file

@ -36,10 +36,8 @@ public class FishingTests
[InlineData(4.5, true)]
public void Give_SerpentGoesBackAfterFiveMinutesUnlessHitInTheLastTwo(double? hitAtMinutes, bool stays)
{
Core._tickCount = 0;
Timer.Init(0);
using var clock = new TimerWheelScope();
var previousNow = Core._now;
var previousHitsRate = Mobile.DefaultHitsRate;
var fisher = new PlayerMobile();
BaseCreature serpent = null;
@ -62,15 +60,15 @@ public class FishingTests
if (hitAtMinutes is { } minutes)
{
elapsed = TimeSpan.FromMinutes(minutes);
Advance(elapsed);
TimerWheelScope.Advance(elapsed);
serpent.Damage(20, fisher);
Assert.Same(fisher, serpent.FindMostRecentDamager(false));
}
Advance(TimeSpan.FromMinutes(4.9) - elapsed);
TimerWheelScope.Advance(TimeSpan.FromMinutes(4.9) - elapsed);
Assert.False(serpent.Deleted);
Advance(TimeSpan.FromMinutes(0.2));
TimerWheelScope.Advance(TimeSpan.FromMinutes(0.2));
Assert.Equal(!stays, serpent.Deleted);
Assert.Equal(!stays, bottle.Deleted);
}
@ -79,7 +77,6 @@ public class FishingTests
serpent?.Delete();
fisher.Delete();
Mobile.DefaultHitsRate = previousHitsRate;
Core._now = previousNow;
}
}
@ -125,13 +122,6 @@ public class FishingTests
}
}
private static void Advance(TimeSpan time)
{
Core._now += time;
Core._tickCount += (long)time.TotalMilliseconds;
Timer.Slice(Core.TickCount);
}
// Map.Internal skips FindLocation's search; the wreck is then where the fisher stands.
private static SOS AddSOS(Mobile fisher)
{

View file

@ -9,8 +9,9 @@ namespace UOContent.Tests;
[Collection("Sequential UOContent Tests")]
public class PartyPacketTests
{
// Without a party, the remove-member packet tells the removed member their list is now empty.
[Fact]
public void TestPartyEmptyList()
public void TestPartyRemoveMember_WithoutParty_SendsEmptyList()
{
var m = (Serial)0x1024u;
@ -26,43 +27,61 @@ public class PartyPacketTests
[Fact]
public void TestPartyRemoveMember()
{
var leader = new Mobile((Serial)0x1024u);
leader.DefaultMobileInit();
// Fresh serials: Delete removes by serial, and a fixed one could belong to a live entity.
var leader = new Mobile(World.NewMobile);
var member = new Mobile(World.NewMobile);
var member = new Mobile((Serial)0x2048u);
member.DefaultMobileInit();
try
{
leader.DefaultMobileInit();
member.DefaultMobileInit();
var p = new Party(leader);
p.Add(member);
var p = new Party(leader);
p.Add(member);
var expected = new PartyRemoveMember(member.Serial, p).Compile();
var expected = new PartyRemoveMember(member.Serial, p).Compile();
using var ns = PacketTestUtilities.CreateTestNetState();
ns.SendPartyRemoveMember(member.Serial, p);
using var ns = PacketTestUtilities.CreateTestNetState();
ns.SendPartyRemoveMember(member.Serial, p);
var result = ns.SendBuffer.GetReadSpan();
AssertThat.Equal(result, expected);
var result = ns.SendBuffer.GetReadSpan();
AssertThat.Equal(result, expected);
}
finally
{
member.Delete();
leader.Delete();
}
}
[Fact]
public void TestPartyMemberList()
{
var leader = new Mobile((Serial)0x1024u);
leader.DefaultMobileInit();
// Fresh serials: Delete removes by serial, and a fixed one could belong to a live entity.
var leader = new Mobile(World.NewMobile);
var member = new Mobile(World.NewMobile);
var member = new Mobile((Serial)0x2048u);
member.DefaultMobileInit();
try
{
leader.DefaultMobileInit();
member.DefaultMobileInit();
var p = new Party(leader);
p.Add(member);
var p = new Party(leader);
p.Add(member);
var expected = new PartyMemberList(p).Compile();
var expected = new PartyMemberList(p).Compile();
using var ns = PacketTestUtilities.CreateTestNetState();
ns.SendPartyMemberList(p);
using var ns = PacketTestUtilities.CreateTestNetState();
ns.SendPartyMemberList(p);
var result = ns.SendBuffer.GetReadSpan();
AssertThat.Equal(result, expected);
var result = ns.SendBuffer.GetReadSpan();
AssertThat.Equal(result, expected);
}
finally
{
member.Delete();
leader.Delete();
}
}
[Theory]

View file

@ -1,3 +1,4 @@
using System;
using Server.Engines.Pathing.Cache;
using Server.Mobiles;
using Server.PathAlgorithms;
@ -14,15 +15,18 @@ namespace Server.Tests.Pathfinding;
/// to "no path found" on reachable goals.
/// </summary>
[Collection("Sequential Pathfinding Tests")]
public class BitmapAStarAlgorithmTests
public class BitmapAStarAlgorithmTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly StepCacheStateScope _cacheState = new();
public BitmapAStarAlgorithmTests(ITestOutputHelper output)
{
_output = output;
}
public void Dispose() => _cacheState.Dispose();
[Theory]
// Pinned cell (1500, 1600, z=10): mask=0xC1 → N, W, NW walkable.
// Use start.Z for goal.Z so destNode lands in the same Z plane the algorithm reaches
@ -33,22 +37,27 @@ public class BitmapAStarAlgorithmTests
public void DefaultWalker_FindsPath_ViaCacheFastPath(int sx, int sy, int gx, int gy)
{
StepCache.Instance.Clear();
StepCache.Instance.MissPromotionThreshold = 1;
var map = Map.Maps[1];
Assert.NotNull(map);
var stub = new DefaultWalkerStub();
var stub = new WalkerStub();
map.GetAverageZ(sx, sy, out _, out var startZ, out _);
var start = new Point3D(sx, sy, (sbyte)startZ);
var goal = new Point3D(gx, gy, (sbyte)startZ);
stub.MoveToWorld(start, map);
var statsBefore = StepCache.Instance.GetStats();
var result = BitmapAStarAlgorithm.Instance.Find(stub, map, start, goal);
var statsAfter = StepCache.Instance.GetStats();
stub.Delete();
Assert.NotNull(result);
Assert.NotEmpty(result);
Assert.True(statsAfter.BuildsTotal > statsBefore.BuildsTotal,
"a default walker should expand through the cache, not the slow path");
_output.WriteLine($"default-walker ({sx},{sy})->({gx},{gy}): {result.Length} steps");
}
@ -62,7 +71,7 @@ public class BitmapAStarAlgorithmTests
var map = Map.Maps[1];
Assert.NotNull(map);
var stub = new SwimmingStub(World.NewMobile);
var stub = new BareCreatureStub(World.NewMobile);
stub.DefaultMobileInit();
stub.CanSwim = true; // overlay route — cache + (walkMask | wetMask&canSwim)
map.GetAverageZ(sx, sy, out _, out var startZ, out _);
@ -104,13 +113,13 @@ public class BitmapAStarAlgorithmTests
var start = new Point3D(sx, sy, (sbyte)startZ);
var goal = new Point3D(gx, gy, (sbyte)startZ);
var walker = new DefaultWalkerStub();
var walker = new WalkerStub();
walker.MoveToWorld(start, map);
// Living blocker on the only direct-line cell. CanMoveOver returns false for an
// alive non-staff mobile, so the dynamic-obstacle pass must reject this cell.
map.GetAverageZ(blockX, blockY, out _, out var blockZ, out _);
var blocker = new DefaultWalkerStub();
var blocker = new WalkerStub();
blocker.MoveToWorld(new Point3D(blockX, blockY, (sbyte)blockZ), map);
var result = BitmapAStarAlgorithm.Instance.Find(walker, map, start, goal);
@ -146,24 +155,14 @@ public class BitmapAStarAlgorithmTests
var blockX = 1499;
var blockY = 1599;
// Find any ItemID whose TileData has ImpassableSurface so the dynamic pass
// rejects the cell. Pinning to a specific ID would couple the test to UO art data.
ushort blockerItemId = 0;
for (ushort id = 1; id < TileData.MaxItemValue; id++)
{
if (TileData.ItemTable[id].ImpassableSurface)
{
blockerItemId = id;
break;
}
}
var blockerItemId = TestTiles.FirstImpassableItemId();
Assert.NotEqual<ushort>(0, blockerItemId);
map.GetAverageZ(sx, sy, out _, out var startZ, out _);
var start = new Point3D(sx, sy, (sbyte)startZ);
var goal = new Point3D(gx, gy, (sbyte)startZ);
var walker = new DefaultWalkerStub();
var walker = new WalkerStub();
walker.MoveToWorld(start, map);
map.GetAverageZ(blockX, blockY, out _, out var blockZ, out _);
@ -197,28 +196,20 @@ public class BitmapAStarAlgorithmTests
var map = Map.Maps[1];
Assert.NotNull(map);
var stub = new DefaultWalkerStub();
var stub = new WalkerStub();
map.GetAverageZ(1500, 1600, out _, out var startZ, out _);
var start = new Point3D(1500, 1600, (sbyte)startZ);
var goal = new Point3D(1498, 1598, (sbyte)startZ);
stub.MoveToWorld(start, map);
var statsBefore = StepCache.Instance.GetStats();
var prevFlag = ContentFeatureFlags.BitmapPathfindingCache;
try
{
ContentFeatureFlags.BitmapPathfindingCache = false;
var result = BitmapAStarAlgorithm.Instance.Find(stub, map, start, goal);
Assert.NotNull(result);
Assert.NotEmpty(result);
}
finally
{
ContentFeatureFlags.BitmapPathfindingCache = prevFlag;
}
ContentFeatureFlags.BitmapPathfindingCache = false;
var result = BitmapAStarAlgorithm.Instance.Find(stub, map, start, goal);
var statsAfter = StepCache.Instance.GetStats();
stub.Delete();
Assert.NotNull(result);
Assert.NotEmpty(result);
Assert.Equal(statsBefore.BuildsTotal, statsAfter.BuildsTotal);
}
@ -346,7 +337,7 @@ public class BitmapAStarAlgorithmTests
StepCache.Instance.MissPromotionThreshold = 2;
var map = Map.Maps[1];
var stub = new DefaultWalkerStub();
var stub = new WalkerStub();
map.GetAverageZ(1500, 1600, out _, out var startZ, out _);
var start = new Point3D(1500, 1600, (sbyte)startZ);
var goal = new Point3D(1498, 1598, (sbyte)startZ);
@ -376,7 +367,7 @@ public class BitmapAStarAlgorithmTests
StepCache.Instance.MissPromotionWindowMs = 30_000;
var map = Map.Maps[1];
var stub = new DefaultWalkerStub();
var stub = new WalkerStub();
map.GetAverageZ(1500, 1600, out _, out var startZ, out _);
var start = new Point3D(1500, 1600, (sbyte)startZ);
var goal = new Point3D(1498, 1598, (sbyte)startZ);
@ -401,18 +392,6 @@ public class BitmapAStarAlgorithmTests
);
}
/// <summary>
/// Plain Mobile — RequiresSlowPath returns false, the bitmap algorithm uses the cache
/// fast path on every expansion.
/// </summary>
private sealed class DefaultWalkerStub : Mobile
{
public DefaultWalkerStub()
{
Body = 0xC9;
}
}
/// <summary>
/// Mobile with Player=true and default AccessLevel (Player). Triggers the strict
/// AND-rule for diagonal corner-cut while still using the cache.
@ -426,20 +405,6 @@ public class BitmapAStarAlgorithmTests
}
}
/// <summary>
/// BaseCreature with CanSwim=true — uses the cache via capability overlay (walk OR
/// (wet AND canSwim)). Use the Serial constructor (deserialization path) to bypass
/// NPCSpeeds init, which requires the npc-speeds.json table loaded — not available
/// in tests.
/// </summary>
private sealed class SwimmingStub : BaseCreature
{
public SwimmingStub(Serial serial) : base(serial)
{
Body = 0xC9;
}
}
/// <summary>
/// BaseCreature with CanFly=true — RequiresSlowPath returns true (Z-jumping is beyond
/// the cache's static-only scope), so GetSuccessors short-circuits to the slow path.

View file

@ -1,3 +1,4 @@
using System;
using Server.Engines.Pathing.Cache;
using Server.Items;
using Server.Mobiles;
@ -9,25 +10,22 @@ using CalcMoves = Server.Movement.Movement;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class HousePathRoutingTests
public class HousePathRoutingTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly StepCacheStateScope _cacheState = new();
public HousePathRoutingTests(ITestOutputHelper output) => _output = output;
private const int MapId = 1;
public void Dispose() => _cacheState.Dispose();
private sealed class WalkerStub : Mobile
{
public WalkerStub() => Body = 0xC9;
}
private const int MapId = 1;
[SkippableFact]
public void PathAround_NeverTraversesAWallCell()
{
TileDataRequirement.SkipIfMissing();
StepCache.Instance.Clear();
var prevThreshold = StepCache.Instance.MissPromotionThreshold;
StepCache.Instance.MissPromotionThreshold = 1;
var map = Map.Maps[MapId];
Assert.NotNull(map);
@ -69,7 +67,6 @@ public class HousePathRoutingTests
}
finally
{
StepCache.Instance.MissPromotionThreshold = prevThreshold;
walker.Delete();
multi.Delete();
}

View file

@ -1,3 +1,4 @@
using System;
using Server.Engines.Pathing.Cache;
using Server.PathAlgorithms;
using Server.Systems.FeatureFlags;
@ -6,20 +7,25 @@ using Xunit;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class MultiCacheUsedTests
public class MultiCacheUsedTests : IDisposable
{
private const int MapId = 1; // Trammel
private const int GuildHouseId = 0x74;
[Fact]
private readonly StepCacheStateScope _cacheState = new();
public void Dispose() => _cacheState.Dispose();
[SkippableFact]
public void PathNearMulti_IncrementsMultiLocalHits()
{
// Without the client's multi data the house has no footprint for the path to skirt.
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[MapId];
map.GetAverageZ(1480, 1620, out _, out var z, out _);
var houseLoc = new Point3D(1480, 1620, (sbyte)z);
var multi = new TestMulti(GuildHouseId);
var cacheWas = ContentFeatureFlags.BitmapPathfindingCache;
ContentFeatureFlags.BitmapPathfindingCache = true;
var mover = MultiTestSupport.GetWalkerOracle(map, new Point3D(1480, 1630, (sbyte)z));
@ -44,7 +50,6 @@ public class MultiCacheUsedTests
{
mover.Delete();
multi.Delete();
ContentFeatureFlags.BitmapPathfindingCache = cacheWas;
}
}
}

View file

@ -1,3 +1,4 @@
using System;
using Server.Engines.Pathing.Cache;
using Server.Items;
using Xunit;
@ -5,13 +6,17 @@ using Xunit;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class MultiMaskCacheTests
public class MultiMaskCacheTests : IDisposable
{
private const int MapId = 1;
private const int GuildHouseId = 0x74;
private const int PlaceX = 1480;
private const int PlaceY = 1620;
private readonly StepCacheStateScope _cacheState = new();
public void Dispose() => _cacheState.Dispose();
[SkippableFact]
public void TryResolveCoveringMulti_FindsPlacedMulti_AndLocalIndices()
{
@ -99,7 +104,6 @@ public class MultiMaskCacheTests
map.GetAverageZ(CleanX, CleanY, out _, out var z, out _);
var houseLoc = new Point3D(CleanX, CleanY, (sbyte)z);
var multi = new TestMulti(GuildHouseId);
var cacheWas = Server.Systems.FeatureFlags.ContentFeatureFlags.BitmapPathfindingCache;
Server.Systems.FeatureFlags.ContentFeatureFlags.BitmapPathfindingCache = true;
var mover = MultiTestSupport.GetWalkerOracle(map, new Point3D(CleanX, CleanY + 10, (sbyte)z));
try
@ -124,17 +128,17 @@ public class MultiMaskCacheTests
{
mover.Delete();
multi.Delete();
Server.Systems.FeatureFlags.ContentFeatureFlags.BitmapPathfindingCache = cacheWas;
}
}
[Fact]
[SkippableFact]
public void ClutteredHouse_DoesNotServeCache_ButStillPaths()
{
// The clutter is Britain's statics; on a blank map the house has no footprint to dirty.
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[MapId];
map.GetAverageZ(PlaceX, PlaceY, out _, out var z, out _);
var multi = new TestMulti(GuildHouseId);
var cacheWas = Server.Systems.FeatureFlags.ContentFeatureFlags.BitmapPathfindingCache;
Server.Systems.FeatureFlags.ContentFeatureFlags.BitmapPathfindingCache = true;
var mover = MultiTestSupport.GetWalkerOracle(map, new Point3D(PlaceX, PlaceY + 10, (sbyte)z));
try
@ -159,7 +163,6 @@ public class MultiMaskCacheTests
{
mover.Delete();
multi.Delete();
Server.Systems.FeatureFlags.ContentFeatureFlags.BitmapPathfindingCache = cacheWas;
}
}

View file

@ -1,3 +1,4 @@
using System;
using Server.Engines.Pathing.Cache;
using Server.Items;
using Server.Mobiles;
@ -9,41 +10,33 @@ using Xunit.Abstractions;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class MultiPathInvariantTests
public class MultiPathInvariantTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly StepCacheStateScope _cacheState = new();
public MultiPathInvariantTests(ITestOutputHelper output) => _output = output;
private const int MapId = 1;
public void Dispose() => _cacheState.Dispose();
private sealed class WalkerStub : Mobile
{
public WalkerStub() => Body = 0xC9;
}
private const int MapId = 1;
private static Direction[] FindWithFlag(Mobile m, Map map, Point3D start, Point3D goal, bool cacheOn)
{
var prev = ContentFeatureFlags.BitmapPathfindingCache;
try
{
ContentFeatureFlags.BitmapPathfindingCache = cacheOn;
StepCache.Instance.Clear();
StepCache.Instance.MissPromotionThreshold = 1;
return BitmapAStarAlgorithm.Instance.Find(m, map, start, goal);
}
finally
{
ContentFeatureFlags.BitmapPathfindingCache = prev;
}
ContentFeatureFlags.BitmapPathfindingCache = cacheOn;
StepCache.Instance.Clear();
StepCache.Instance.MissPromotionThreshold = 1;
return BitmapAStarAlgorithm.Instance.Find(m, map, start, goal);
}
[Theory]
[SkippableTheory]
// start, goal: straddle a house placed between them (house at ~ midpoint).
[InlineData(1500, 1600, 1500, 1612)] // N-S across the footprint
[InlineData(1494, 1606, 1512, 1606)] // E-W across the footprint
public void Find_CacheOn_EqualsCacheOff_WithHousePresent(int sx, int sy, int gx, int gy)
{
// Without the client's multi data the house has no footprint and nothing stands in the way.
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[MapId];
Assert.NotNull(map);
@ -100,11 +93,11 @@ public class MultiPathInvariantTests
{
var on = FindWithFlag(walker, map, start, goal, cacheOn: true);
var off = FindWithFlag(walker, map, start, goal, cacheOn: false);
Assert.Equal(off == null, on == null);
if (on != null)
{
Assert.Equal(off, on);
}
// Two nulls would agree about nothing: the control route must exist.
Assert.NotNull(off);
Assert.NotNull(on);
Assert.Equal(off, on);
}
finally
{
@ -112,9 +105,10 @@ public class MultiPathInvariantTests
}
}
[Fact]
[SkippableFact]
public void Find_CacheOn_EqualsCacheOff_RoutesAroundHouse()
{
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[MapId];
Assert.NotNull(map);

View file

@ -1,3 +1,4 @@
using System;
using Server.Engines.Pathing.Cache;
using Server.Items;
using Xunit;
@ -6,12 +7,15 @@ using Xunit.Abstractions;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class MultiSplitRoutingTests
public class MultiSplitRoutingTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly StepCacheStateScope _cacheState = new();
public MultiSplitRoutingTests(ITestOutputHelper output) => _output = output;
public void Dispose() => _cacheState.Dispose();
// Open plain on Trammel used by existing pathfinding tests; room for a 7x7 house.
private const int MapId = 1;
private const int PlaceX = 1500;
@ -60,7 +64,6 @@ public class MultiSplitRoutingTests
public void CleanMap_AfterMultiRemoved_ServesStaticHitAgain()
{
StepCache.Instance.Clear();
var prevThreshold = StepCache.Instance.MissPromotionThreshold;
StepCache.Instance.MissPromotionThreshold = 1; // build on first touch
var map = Map.Maps[MapId];
Assert.NotNull(map);
@ -72,20 +75,13 @@ public class MultiSplitRoutingTests
var sector = map.GetRealSector(PlaceX >> 4, PlaceY >> 4);
Assert.True(sector.HasMultis, "placing a multi must set Sector.HasMultis");
try
{
multi.Delete();
Assert.False(sector.HasMultis, "removing the only multi must clear HasMultis");
multi.Delete();
Assert.False(sector.HasMultis, "removing the only multi must clear HasMultis");
// A cell that is NOT a static-fallthrough kind (e.g. off-map / multi) should now be
// eligible for a real static answer. Use the placement center, which is open plain.
var mask = StepCache.Instance.TryGetMask(map, PlaceX, PlaceY, (sbyte)z);
Assert.True(mask.IsHit, $"expected a real static answer after removal, got {mask.HitKind}");
_output.WriteLine($"post-removal hitKind at center: {mask.HitKind}");
}
finally
{
StepCache.Instance.MissPromotionThreshold = prevThreshold;
}
// A cell that is NOT a static-fallthrough kind (e.g. off-map / multi) should now be
// eligible for a real static answer. Use the placement center, which is open plain.
var mask = StepCache.Instance.TryGetMask(map, PlaceX, PlaceY, (sbyte)z);
Assert.True(mask.IsHit, $"expected a real static answer after removal, got {mask.HitKind}");
_output.WriteLine($"post-removal hitKind at center: {mask.HitKind}");
}
}

View file

@ -20,12 +20,6 @@ public sealed class TestMulti : BaseMulti
}
}
/// <summary>Default walker body, shared across pathfinding test fixtures.</summary>
public sealed class WalkerStub : Mobile
{
public WalkerStub() => Body = 0xC9;
}
/// <summary>
/// Stand-in for a customizable foundation: Components is a swappable MCL, exactly the
/// runtime-mutation shape HouseFoundation uses (it replaces its MCL wholesale on redesign

View file

@ -18,11 +18,6 @@ public class MultiWalkabilityTests
private const int PlaceX = 1500;
private const int PlaceY = 1600;
private sealed class WalkerStub : Mobile
{
public WalkerStub() => Body = 0xC9;
}
[SkippableFact]
public void WallCell_CannotBeEnteredFromAnyAdjacentCell()
{

View file

@ -19,7 +19,7 @@ public class PathfindRecorderTests
try
{
var stub = new RecorderStub(World.NewMobile);
var stub = new BareCreatureStub(World.NewMobile);
stub.DefaultMobileInit();
stub.MoveToWorld(new Point3D(1500, 1600, 0), Map.Maps[1]);
@ -48,7 +48,7 @@ public class PathfindRecorderTests
{
Assert.True(PathfindRecorder.Enabled);
var stub = new RecorderStub(World.NewMobile);
var stub = new BareCreatureStub(World.NewMobile);
stub.DefaultMobileInit();
stub.MoveToWorld(new Point3D(1500, 1600, 0), Map.Maps[1]);
@ -89,7 +89,7 @@ public class PathfindRecorderTests
try
{
var stub = new RecorderStub(World.NewMobile);
var stub = new BareCreatureStub(World.NewMobile);
stub.DefaultMobileInit();
stub.MoveToWorld(new Point3D(1500, 1600, 0), Map.Maps[1]);
stub.CanSwim = true;
@ -100,13 +100,17 @@ public class PathfindRecorderTests
);
PathfindRecorder.SetEnabled(false);
// BaseCreature's own defaults for these two; the recording must carry whatever they are.
var canOpenDoors = JsonBool(stub.CanOpenDoors);
var canMoveOverObstacles = JsonBool(stub.CanMoveOverObstacles);
stub.Delete();
var content = File.ReadAllText(path);
Assert.Contains("\"CanSwim\":true", content);
Assert.Contains("\"CanFly\":false", content);
Assert.Contains("\"CanOpenDoors\":", content); // value depends on BaseCreature defaults
Assert.Contains("\"CanMoveOverObstacles\":", content); // — same.
Assert.Contains($"\"CanOpenDoors\":{canOpenDoors}", content);
Assert.Contains($"\"CanMoveOverObstacles\":{canMoveOverObstacles}", content);
}
finally
{
@ -142,8 +146,5 @@ public class PathfindRecorderTests
}
}
private sealed class RecorderStub : Server.Mobiles.BaseCreature
{
public RecorderStub(Serial serial) : base(serial) => Body = 0xC9;
}
private static string JsonBool(bool value) => value ? "true" : "false";
}

View file

@ -4,8 +4,8 @@ using Server.Engines.Pathing.Cache;
namespace Server.Tests.Pathfinding;
/// <summary>
/// Shared fixtures for the step-cache tests: the walker the parity tests measure against, the
/// cell-index arithmetic, and builders for the chunk state several tests inject by hand.
/// Shared fixtures for the step-cache tests: the test map, the cell-index arithmetic, and builders
/// for the chunk state several tests inject by hand.
/// </summary>
internal static class PathingTestSupport
{
@ -53,17 +53,4 @@ internal static class PathingTestSupport
return data;
}
/// <summary>
/// The default static walker. Deriving straight from <see cref="Mobile"/> rather than
/// BaseCreature is the point: MovementImpl then sees no creature capabilities (no swim, no fly,
/// no door-opening), which is exactly the walker the cache bakes for.
/// </summary>
public sealed class StaticWalker : Mobile
{
public StaticWalker()
{
Body = 0xC9;
}
}
}

View file

@ -6,8 +6,12 @@ using Xunit;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class StepCacheFileTests
public class StepCacheFileTests : IDisposable
{
private readonly StepCacheStateScope _cacheState = new();
public void Dispose() => _cacheState.Dispose();
/// <summary>
/// Round-trip a populated cache through a .swb file under lazy loading: build chunks,
/// save, clear (closes lazy readers + drops residents), open as lazy backing store,
@ -363,23 +367,16 @@ public class StepCacheFileTests
cache.Clear();
cache.PreloadOnLazyOpen = true;
try
{
Assert.True(cache.TryOpenLazyReader(path, map.MapID));
Assert.True(cache.TryOpenLazyReader(path, map.MapID));
// Every chunk should be resident — no further queries needed.
Assert.Equal(coords.Length, cache.GetStats().ResidentChunks);
Assert.Equal(0L, cache.GetStats().BuildsTotal); // came from file, not baker
// Every chunk should be resident — no further queries needed.
Assert.Equal(coords.Length, cache.GetStats().ResidentChunks);
Assert.Equal(0L, cache.GetStats().BuildsTotal); // came from file, not baker
// Subsequent query is a clean Hit, not a Miss_NotBuilt.
var lookup = cache.TryGetMask(map, coords[0].Item1, coords[0].Item2, sourceZ: 10);
Assert.Equal(CacheHitKind.Hit, lookup.HitKind);
Assert.Equal(coords.Length, cache.GetStats().ResidentChunks);
}
finally
{
cache.PreloadOnLazyOpen = false;
}
// Subsequent query is a clean Hit, not a Miss_NotBuilt.
var lookup = cache.TryGetMask(map, coords[0].Item1, coords[0].Item2, sourceZ: 10);
Assert.Equal(CacheHitKind.Hit, lookup.HitKind);
Assert.Equal(coords.Length, cache.GetStats().ResidentChunks);
}
finally
{

View file

@ -15,9 +15,12 @@ public class StepCacheFingerprintTests
/// different one, marking the bake stale and re-baking on every boot. Hashing the file makes
/// the fingerprint a pure function of the client's tile data, immune to those mutations.
/// </summary>
[Fact]
[SkippableFact]
public void Fingerprint_IgnoresRuntimeTileDataMutation()
{
// Without tiledata.mul there is no file to hash, so the fingerprint is constant either way.
TileDataRequirement.SkipIfMissing();
const int mapId = 1; // Trammel — loaded by the test bootstrap.
var before = StepCacheFile.ComputeFingerprint(mapId);

View file

@ -17,11 +17,9 @@ namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class StepCacheLifecycleTests : IDisposable
{
// The window is a knob on the singleton and Clear() leaves it alone, so a test that narrows
// it would otherwise leak the narrow window into every later test in the collection.
private readonly uint _savedWindowMs = StepCache.Instance.MissPromotionWindowMs;
private readonly StepCacheStateScope _cacheState = new();
public void Dispose() => StepCache.Instance.MissPromotionWindowMs = _savedWindowMs;
public void Dispose() => _cacheState.Dispose();
/// <summary>Resets to a known state and returns the singleton.</summary>
private static StepCache FreshCache(int promotionThreshold)
@ -396,26 +394,19 @@ public class StepCacheLifecycleTests : IDisposable
var cache = FreshCache(promotionThreshold: 1);
cache.MaxResidentChunks = 4;
try
var map = TestMap;
// Five chunks into a cache that holds four. Which one goes doesn't matter here, only that
// the count comes down and the key list stays in step, so equal touch ticks are fine.
for (var i = 0; i < 5; i++)
{
var map = TestMap;
// Five chunks into a cache that holds four.
for (var i = 0; i < 5; i++)
{
cache.TryGetMask(map, PlainX + i * 16, PlainY, sourceZ: 10);
Thread.Sleep(2); // separate their LastTouchedTicks so LRU has something to order by
}
cache.EnforceLruCap();
Assert.Equal(4, cache.GetStats().ResidentChunks);
Assert.True(cache.GetStats().EvictionsByLruCap >= 1L);
Assert.True(cache.ResidentIndexInSync(), "eviction desynced the key list from the resident set");
}
finally
{
cache.MaxResidentChunks = 8192;
cache.TryGetMask(map, PlainX + i * 16, PlainY, sourceZ: 10);
}
cache.EnforceLruCap();
Assert.Equal(4, cache.GetStats().ResidentChunks);
Assert.True(cache.GetStats().EvictionsByLruCap >= 1L);
Assert.True(cache.ResidentIndexInSync(), "eviction desynced the key list from the resident set");
}
}

View file

@ -20,12 +20,15 @@ namespace Server.Tests.Pathfinding;
/// falls through on everything agrees with the slow path perfectly and is worthless.
/// </summary>
[Collection("Sequential Pathfinding Tests")]
public class StepCacheParityTests
public class StepCacheParityTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly StepCacheStateScope _cacheState = new();
public StepCacheParityTests(ITestOutputHelper output) => _output = output;
public void Dispose() => _cacheState.Dispose();
// ---- layer 1: the bake agrees with MovementImpl ----
/// <summary>
@ -43,7 +46,7 @@ public class StepCacheParityTests
var map = TestMap;
Assert.NotNull(map);
var walker = new StaticWalker();
var walker = new WalkerStub();
walker.MoveToWorld(new Point3D(xStart, yStart, 0), map);
var disagreements = 0;
@ -154,12 +157,16 @@ public class StepCacheParityTests
/// the land average instead would trip the source-Z guard on raised terrain (a causeway, a
/// walkway) and report a fallthrough that is correct behaviour rather than a fault.
/// </summary>
[Theory]
[SkippableTheory]
[InlineData("britain_inn_dense", 1480, 1610, 32)]
[InlineData("trammel_open_plain", 1500, 1600, 32)]
[InlineData("britain_causeway", 1475, 1641, 32)]
public void CacheMatchesProbe(string label, int xStart, int yStart, int size)
{
// A storage fault (crossed cell index, swapped Z array) only shows against varied terrain;
// on a blank map every cell bakes the same answer.
TileDataRequirement.SkipIfMissing();
var cache = StepCache.Instance;
cache.Clear();
cache.MissPromotionThreshold = 1; // build on first touch: every cell should get a real answer
@ -253,7 +260,7 @@ public class StepCacheParityTests
/// Cardinals only: the cache stores raw masks and applies the corner-cut at query time, so a
/// raw diagonal bit legitimately differs from MovementImpl's diagonal answer.
/// </summary>
[Theory]
[SkippableTheory]
// Seeds chosen for the terrain classes the standable-surface bake has to get right. Each one
// floods across a wide local area, so a handful covers thousands of states without a map walk.
[InlineData("brit_sewer_walkway", 6034, 1476, 5, 2500)] // static walkway over impassable land
@ -262,6 +269,8 @@ public class StepCacheParityTests
[InlineData("trammel_open_plain", 1500, 1600, 10, 2500)] // flat ground: catches clearance false-positives
public void CacheServesReachableWalkStates(string label, int sx, int sy, int sz, int maxStates)
{
TileDataRequirement.SkipIfMissing();
var cache = StepCache.Instance;
cache.Clear();
cache.MissPromotionThreshold = 1; // build on first touch: every reached state should be answered
@ -269,7 +278,7 @@ public class StepCacheParityTests
var map = TestMap;
Assert.NotNull(map);
var walker = new StaticWalker();
var walker = new WalkerStub();
walker.MoveToWorld(new Point3D(sx, sy, sz), map);
var startIsWalkable = false;

View file

@ -20,10 +20,9 @@ public class AllSpawnFilesLoadTests
public void EverySpawnFile_DeserializesAndBuildsSpawners()
{
var root = Path.Combine(Core.BaseDirectory, "Data", "Spawns");
if (!Directory.Exists(root))
{
return; // distribution data not present in this checkout
}
// Data/ is copied into the test output by the build; a missing folder means the build was run
// without SolutionDir, and passing would hide that nothing was checked.
Assert.True(Directory.Exists(root), $"Spawn data not found at {root}");
var failures = new List<string>();
var fileCount = 0;
@ -64,6 +63,7 @@ public class AllSpawnFilesLoadTests
}
}
Assert.NotEqual(0, fileCount);
Assert.True(
failures.Count == 0,
$"Loaded {fileCount} files, built {spawnerCount} spawners. Failures:\n{string.Join("\n", failures)}"

View file

@ -3,22 +3,24 @@ using System.Collections.Generic;
using System.IO;
using Server;
using Server.Engines.Spawners;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Engines.Spawners.Json;
[Collection("Sequential UOContent Tests")]
public class ImportCleanupTests
public class ImportCleanupTests : IDisposable
{
private const string SpawnerGuid = "11111111-1111-1111-1111-111111111111";
private readonly TempDirectory _dir = new("muo-spawner-import");
public void Dispose() => _dir.Dispose();
[Fact]
public void Import_ValidFile_PlacesSpawner()
{
var dir = Path.Combine(Path.GetTempPath(), "muo-spawner-import-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, "test.json");
File.WriteAllText(path, """
var path = _dir.WriteFile("test.json", """
[
{
"$type": "Spawner",
@ -53,22 +55,15 @@ public class ImportCleanupTests
finally
{
placedSpawner?.Delete();
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
}
}
// A DTO with no map entry deserializes with map == null. The importer rejects it before building
// a spawner, so nothing is registered and nothing lands on any live map.
[Fact]
public void Import_NoMap_DeletesOrphanedSpawner()
public void Import_NoMap_SkipsTheSpawner()
{
// A spawner with no map entry deserialized by STJ will have map == null (or Map.Internal).
// Verify it does NOT end up on any live map.
var dir = Path.Combine(Path.GetTempPath(), "muo-spawner-import-nomap-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, "test-nomap.json");
File.WriteAllText(path, """
var path = _dir.WriteFile("test-nomap.json", """
[
{
"$type": "Spawner",
@ -81,45 +76,28 @@ public class ImportCleanupTests
]
""");
try
{
var all = new Dictionary<Guid, ISpawner>();
ImportSpawnersCommand.ImportFile(new FileInfo(path), all);
var guid = new Guid("22222222-2222-2222-2222-222222222222");
var all = new Dictionary<Guid, ISpawner>();
ImportSpawnersCommand.ImportFile(new FileInfo(path), all);
// The spawner must NOT be in allSpawners (rejected due to missing map).
Assert.DoesNotContain(new Guid("22222222-2222-2222-2222-222222222222"), all.Keys);
}
finally
Assert.DoesNotContain(guid, all.Keys);
var maps = Map.AllMaps;
for (var i = 0; i < maps.Count; i++)
{
if (Directory.Exists(dir))
foreach (var spawner in maps[i].GetItemsAt<BaseSpawner>(new Point3D(400, 400, 0)))
{
Directory.Delete(dir, true);
Assert.NotEqual(guid, spawner.Guid);
}
}
}
private static int CountSpawnersNear(Point3D p)
{
var n = 0;
foreach (var _ in Map.Felucca.GetItemsAt<BaseSpawner>(p))
{
n++;
}
return n;
}
[Fact]
public void Import_DuplicateLocation_ReplacesExistingSpawner()
{
// Verifies that an existing spawner at the same location and type is removed and replaced.
var dir = Path.Combine(Path.GetTempPath(), "muo-spawner-import-dup-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, "test-dup.json");
var newGuid = new Guid("33333333-3333-3333-3333-333333333333");
// Use a non-interpolated raw string literal; the guid is a known constant so hardcode it.
File.WriteAllText(path, """
var path = _dir.WriteFile("test-dup.json", """
[
{
"$type": "Spawner",
@ -133,13 +111,13 @@ public class ImportCleanupTests
]
""");
// Place a pre-existing spawner at the same location.
var existing = new Spawner(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
existing.MoveToWorld(new Point3D(310, 310, 0), Map.Felucca);
BaseSpawner placedSpawner = null;
try
{
existing.MoveToWorld(new Point3D(310, 310, 0), Map.Felucca);
var all = new Dictionary<Guid, ISpawner> { [existing.Guid] = existing };
ImportSpawnersCommand.ImportFile(new FileInfo(path), all);
@ -160,15 +138,8 @@ public class ImportCleanupTests
}
finally
{
if (!existing.Deleted)
{
existing.Delete();
}
existing.Delete();
placedSpawner?.Delete();
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
}
}
}

View file

@ -15,15 +15,21 @@ public class SpawnerDtoEntryTests
public void Export_WritesEntriesAtSameJsonPosition_WithDisabledOnlyWhenSet()
{
var spawner = new Spawner(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), 0, default, "Rabbit", "Bird");
spawner.Entries[1].Disabled = true;
var json = SpawnerJsonSerializer.SerializeCompact(new List<SpawnerDto> { spawner.ToDto() });
try
{
spawner.Entries[1].Disabled = true;
Assert.Contains("\"entries\": [\n { \"name\": \"Rabbit\"", json);
Assert.Contains("{ \"name\": \"Bird\"", json);
Assert.Equal(1, CountOccurrences(json, "\"disabled\": true"));
var json = SpawnerJsonSerializer.SerializeCompact(new List<SpawnerDto> { spawner.ToDto() });
spawner.Delete();
Assert.Contains("\"entries\": [\n { \"name\": \"Rabbit\"", json);
Assert.Contains("{ \"name\": \"Bird\"", json);
Assert.Equal(1, CountOccurrences(json, "\"disabled\": true"));
}
finally
{
spawner.Delete();
}
}
[Fact]
@ -35,11 +41,16 @@ public class SpawnerDtoEntryTests
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
var spawner = dtos![0].ToSpawner();
Assert.Single(spawner.Entries);
Assert.True(spawner.Entries[0].Disabled);
Assert.Same(dtos[0].EntryView[0], spawner.Entries[0]);
spawner.Delete();
try
{
Assert.Single(spawner.Entries);
Assert.True(spawner.Entries[0].Disabled);
Assert.Same(dtos[0].EntryView[0], spawner.Entries[0]);
}
finally
{
spawner.Delete();
}
}
private static int CountOccurrences(string source, string value)

View file

@ -260,14 +260,8 @@ public class SectorSpawnCacheManagerTests
}
}
[Collection("SectorSpawnCache")]
public class SpiralScanTests
{
public SpiralScanTests()
{
SectorSpawnCacheManager.ClearAll();
}
[Theory]
[InlineData(1, 0, -1, -1)] // Ring 1, position 0: top-left
[InlineData(1, 1, 0, -1)] // Ring 1, position 1: top

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
@ -11,26 +12,43 @@ using Xunit;
namespace UOContent.Tests.Engines.Spawners;
[Collection("Sequential UOContent Tests")]
public class SpawnerEntryOwnershipTests
public class SpawnerEntryOwnershipTests : IDisposable
{
// Deleted in Dispose so a failed assertion cannot leave spawners registered in the world.
private readonly List<Item> _created = [];
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
}
private T Track<T>(T item) where T : Item
{
_created.Add(item);
return item;
}
private Spawner NewSpawner(params string[] names) =>
Track(new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, names));
[Fact]
public void Disabled_DefaultsFalse_AndRoundTripsBinary()
{
var spawner = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird");
var spawner = NewSpawner("Rabbit", "Bird");
Assert.False(spawner.Entries[0].Disabled);
Assert.True(spawner.Entries[0].Enabled);
spawner.Entries[1].Disabled = true;
var bytes = SpawnerBlob.Write(spawner);
var loaded = SpawnerBlob.Read<Spawner>(bytes, (Serial)0x40001234);
var loaded = Track(SpawnerBlob.Read<Spawner>(bytes, (Serial)0x40001234));
Assert.Equal(2, loaded.Entries.Count);
Assert.False(loaded.Entries[0].Disabled);
Assert.True(loaded.Entries[1].Disabled);
spawner.Delete();
loaded.Delete();
}
[Fact]
@ -48,7 +66,7 @@ public class SpawnerEntryOwnershipTests
[Fact]
public void AddRemoveClear_OperateOnOwnerList()
{
var spawner = new Spawner();
var spawner = Track(new Spawner());
Assert.Empty(spawner.Entries);
var a = spawner.AddEntry("Rabbit", 100, 2, false);
@ -63,17 +81,15 @@ public class SpawnerEntryOwnershipTests
spawner.RemoveAllEntries();
Assert.Empty(spawner.Entries);
spawner.Delete();
}
[Fact]
public void Dupe_ClonesEntriesIntoIndependentList()
{
var source = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird");
var source = NewSpawner("Rabbit", "Bird");
source.Entries[1].Disabled = true;
var copy = new Spawner();
var copy = Track(new Spawner());
source.Dupe(copy);
Assert.Equal(2, copy.Entries.Count);
@ -84,31 +100,25 @@ public class SpawnerEntryOwnershipTests
source.AddEntry("Orc", 100, 1, false);
Assert.Equal(2, copy.Entries.Count);
source.Delete();
copy.Delete();
}
[Fact]
public void CopyEntriesTo_ReplacesTargetEntries()
{
var source = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit");
var target = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Orc", "Troll");
var source = NewSpawner("Rabbit");
var target = NewSpawner("Orc", "Troll");
source.CopyEntriesTo(target);
Assert.Single(target.Entries);
Assert.Equal("Rabbit", target.Entries[0].SpawnedName);
Assert.NotSame(source.Entries[0], target.Entries[0]);
source.Delete();
target.Delete();
}
[Fact]
public void CopyEntriesTo_Self_IsNoOp()
{
var spawner = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird");
var spawner = NewSpawner("Rabbit", "Bird");
var first = spawner.Entries[0];
var second = spawner.Entries[1];
@ -117,18 +127,16 @@ public class SpawnerEntryOwnershipTests
Assert.Equal(2, spawner.Entries.Count);
Assert.Same(first, spawner.Entries[0]);
Assert.Same(second, spawner.Entries[1]);
spawner.Delete();
}
[Fact]
public void RemoveEntry_ForeignEntry_IsIgnored()
{
var a = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit");
var b = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Bird");
var a = NewSpawner("Rabbit");
var b = NewSpawner("Bird");
var foreign = b.Entries[0];
var spawned = new Item(0x1f13);
var spawned = Track(new Item(0x1f13));
foreign.AddToSpawned(spawned);
a.RemoveEntry(foreign);
@ -140,10 +148,6 @@ public class SpawnerEntryOwnershipTests
Assert.False(spawned.Deleted);
Assert.Single(foreign.Spawned);
spawned.Delete();
a.Delete();
b.Delete();
}
// Manual: remove the Skip, run, and read the numbers from the thrown assertion.

View file

@ -17,30 +17,42 @@ public class CorpseChildPublicTests
private static VikingSword EquipSword(Mobile owner)
{
var sword = new VikingSword { Layer = Layer.OneHanded };
Assert.True(owner.EquipItem(sword));
var equipped = owner.EquipItem(sword);
if (!equipped)
{
sword.Delete();
}
Assert.True(equipped);
return sword;
}
private static Mobile NewOwner(int body)
{
var owner = new Mobile(World.NewMobile);
owner.DefaultMobileInit();
owner.Body = body;
return owner;
}
[Fact]
public void IsChildPublic_HumanCorpseWithWornGear_ReturnsTrue()
{
var owner = new Mobile((Serial)0x1);
owner.DefaultMobileInit();
owner.Body = 0x190;
var wornItem = EquipSword(owner);
var corpse = new Corpse(owner, owner.Items);
var owner = NewOwner(0x190);
Corpse corpse = null;
try
{
var wornItem = EquipSword(owner);
corpse = new Corpse(owner, owner.Items);
Assert.Equal(0x2006, corpse.ItemID);
Assert.True(((Body)corpse.Amount).IsHuman);
Assert.True(corpse.IsChildPublic(wornItem));
}
finally
{
corpse.Delete();
corpse?.Delete();
owner.Delete();
}
}
@ -48,26 +60,24 @@ public class CorpseChildPublicTests
[Fact]
public void IsChildPublic_HumanCorpseWithLootItem_ReturnsFalse()
{
var owner = new Mobile((Serial)0x1);
owner.DefaultMobileInit();
owner.Body = 0x190;
var wornItem = EquipSword(owner);
var corpse = new Corpse(owner, owner.Items);
var lootItem = new Gold(100);
corpse.DropItem(lootItem);
var owner = NewOwner(0x190);
Corpse corpse = null;
try
{
EquipSword(owner);
corpse = new Corpse(owner, owner.Items);
var lootItem = new Gold(100);
corpse.DropItem(lootItem);
Assert.Equal(0x2006, corpse.ItemID);
Assert.True(((Body)corpse.Amount).IsHuman);
Assert.False(corpse.IsChildPublic(lootItem));
}
finally
{
corpse.Delete();
corpse?.Delete();
owner.Delete();
}
}
@ -75,16 +85,14 @@ public class CorpseChildPublicTests
[Fact]
public void IsChildPublic_BoneCorpse_ReturnsFalse()
{
var owner = new Mobile((Serial)0x1);
owner.DefaultMobileInit();
owner.Body = 0x190;
var wornItem = EquipSword(owner);
var corpse = new Corpse(owner, owner.Items);
var owner = NewOwner(0x190);
Corpse corpse = null;
try
{
var wornItem = EquipSword(owner);
corpse = new Corpse(owner, owner.Items);
corpse.ItemID = 0xECA;
Assert.True(((Body)corpse.Amount).IsHuman);
@ -93,7 +101,7 @@ public class CorpseChildPublicTests
}
finally
{
corpse.Delete();
corpse?.Delete();
owner.Delete();
}
}
@ -101,23 +109,21 @@ public class CorpseChildPublicTests
[Fact]
public void IsChildPublic_NonHumanCorpse_ReturnsFalse()
{
var owner = new Mobile((Serial)0x1);
owner.DefaultMobileInit();
owner.Body = 0xC9;
var wornItem = EquipSword(owner);
var corpse = new Corpse(owner, owner.Items);
var owner = NewOwner(0xC9);
Corpse corpse = null;
try
{
var wornItem = EquipSword(owner);
corpse = new Corpse(owner, owner.Items);
Assert.Equal(0x2006, corpse.ItemID);
Assert.False(((Body)corpse.Amount).IsHuman);
Assert.False(corpse.IsChildPublic(wornItem));
}
finally
{
corpse.Delete();
corpse?.Delete();
owner.Delete();
}
}
@ -129,36 +135,48 @@ public class CorpseChildPublicTests
return ns.SendBuffer.GetReadSpan().IndexOf(expected) >= 0;
}
private static Mobile NewBystander(NetState ns, Point3D location)
{
ns.Account = new MockAccount();
var bystander = new Mobile(World.NewMobile);
bystander.DefaultMobileInit();
ns.Mobile = bystander;
bystander.NetState = ns;
bystander.MoveToWorld(location, Map.Felucca);
return bystander;
}
private static void DeleteBystander(NetState ns, Mobile bystander)
{
ns.Mobile = null;
ns.Dispose();
bystander?.Delete();
}
[Fact]
public void HumanCorpse_WornGearRemovalBroadcasts_LootRemovalDoesNot()
{
var corpseLoc = new Point3D(1500, 1500, 0);
var bystanderNs = PacketTestUtilities.CreateTestNetState();
bystanderNs.Account = new MockAccount();
var bystander = new Mobile(World.NewMobile);
bystander.DefaultMobileInit();
bystanderNs.Mobile = bystander;
bystander.NetState = bystanderNs;
bystander.MoveToWorld(new Point3D(corpseLoc.X + 1, corpseLoc.Y, corpseLoc.Z), Map.Felucca);
var owner = new Mobile((Serial)0x1);
owner.DefaultMobileInit();
owner.Body = 0x190;
var sword = new VikingSword();
var corpse = new Corpse(owner, [sword]);
corpse.AddItem(sword);
var lootItem = new Gold(100);
corpse.DropItem(lootItem);
corpse.MoveToWorld(corpseLoc, Map.Felucca);
Mobile bystander = null;
var owner = NewOwner(0x190);
Corpse corpse = null;
Container pouch = null;
try
{
bystander = NewBystander(bystanderNs, new Point3D(corpseLoc.X + 1, corpseLoc.Y, corpseLoc.Z));
var sword = new VikingSword();
corpse = new Corpse(owner, [sword]);
corpse.AddItem(sword);
var lootItem = new Gold(100);
corpse.DropItem(lootItem);
corpse.MoveToWorld(corpseLoc, Map.Felucca);
// A container not in the world is a valid destination; only the removal from the corpse matters here.
pouch = new Container(0xE75);
pouch.AddItem(sword);
@ -171,11 +189,9 @@ public class CorpseChildPublicTests
finally
{
pouch?.Delete();
corpse.Delete();
corpse?.Delete();
owner.Delete();
bystanderNs.Mobile = null;
bystanderNs.Dispose();
bystander.Delete();
DeleteBystander(bystanderNs, bystander);
}
}
@ -185,25 +201,20 @@ public class CorpseChildPublicTests
var corpseLoc = new Point3D(1500, 1500, 0);
var bystanderNs = PacketTestUtilities.CreateTestNetState();
bystanderNs.Account = new MockAccount();
var bystander = new Mobile(World.NewMobile);
bystander.DefaultMobileInit();
bystanderNs.Mobile = bystander;
bystander.NetState = bystanderNs;
bystander.MoveToWorld(new Point3D(corpseLoc.X + 1, corpseLoc.Y, corpseLoc.Z), Map.Felucca);
var owner = new Mobile(World.NewMobile);
owner.DefaultMobileInit();
owner.Body = 0x190;
owner.MoveToWorld(new Point3D(corpseLoc.X - 1, corpseLoc.Y, corpseLoc.Z), Map.Felucca);
Mobile bystander = null;
var owner = NewOwner(0x190);
var sword = new VikingSword { Layer = Layer.OneHanded };
var corpse = new Corpse(owner, [sword]);
corpse.AddItem(sword);
corpse.MoveToWorld(corpseLoc, Map.Felucca);
Corpse corpse = null;
try
{
bystander = NewBystander(bystanderNs, new Point3D(corpseLoc.X + 1, corpseLoc.Y, corpseLoc.Z));
owner.MoveToWorld(new Point3D(corpseLoc.X - 1, corpseLoc.Y, corpseLoc.Z), Map.Felucca);
corpse = new Corpse(owner, [sword]);
corpse.AddItem(sword);
corpse.MoveToWorld(corpseLoc, Map.Felucca);
// Lifting takes the piece off the worn list before the remove is sent; the remove must
// still reach everyone who was shown it worn.
owner.Lift(sword, sword.Amount, out var rejected, out _);
@ -216,11 +227,9 @@ public class CorpseChildPublicTests
{
owner.Holding = null;
sword.Delete();
corpse.Delete();
corpse?.Delete();
owner.Delete();
bystanderNs.Mobile = null;
bystanderNs.Dispose();
bystander.Delete();
DeleteBystander(bystanderNs, bystander);
}
}
}

View file

@ -1,4 +1,3 @@
using System.Collections.Generic;
using Server;
using Server.Items;
using Xunit;
@ -11,19 +10,22 @@ public class CorpseLootTests
[Fact]
public void LiftedWornGear_PutBack_StaysLoot()
{
var owner = new Mobile((Serial)0x1);
owner.DefaultMobileInit();
owner.Body = 0x190;
// Weapons take their layer from tiledata, which CI doesn't load.
var sword = new VikingSword { Layer = Layer.OneHanded };
Assert.True(owner.EquipItem(sword));
var corpse = new Corpse(owner, new List<Item> { sword });
corpse.DropItem(sword);
var owner = new Mobile(World.NewMobile);
VikingSword sword = null;
Corpse corpse = null;
try
{
owner.DefaultMobileInit();
owner.Body = 0x190;
// Weapons take their layer from tiledata, which CI doesn't load.
sword = new VikingSword { Layer = Layer.OneHanded };
Assert.True(owner.EquipItem(sword));
corpse = new Corpse(owner, [sword]);
corpse.DropItem(sword);
Assert.Contains(sword, corpse.EquipItems);
corpse.OnItemLifted(owner, sword);
@ -35,7 +37,8 @@ public class CorpseLootTests
}
finally
{
corpse.Delete();
corpse?.Delete();
sword?.Delete();
owner.Delete();
}
}

View file

@ -10,19 +10,34 @@ namespace UOContent.Tests;
[Collection("Sequential UOContent Tests")]
public class CorpsePacketTests
{
// Weapons take their layer from tiledata, which CI doesn't load; without an explicit layer the
// equip is refused and the packets would only cover an empty item list.
private static VikingSword EquipSword(Mobile m)
{
var sword = new VikingSword { Layer = Layer.OneHanded };
var equipped = m.EquipItem(sword);
if (!equipped)
{
sword.Delete();
}
Assert.True(equipped);
return sword;
}
[Fact]
public void TestCorpseEquipPacket()
{
var m = new Mobile((Serial)0x1);
m.DefaultMobileInit();
var weapon = new VikingSword();
m.EquipItem(weapon);
var c = new Corpse(m, m.Items);
var m = new Mobile(World.NewMobile);
VikingSword weapon = null;
Corpse c = null;
try
{
m.DefaultMobileInit();
weapon = EquipSword(m);
c = new Corpse(m, m.Items);
var expected = new CorpseEquip(m, c).Compile();
using var ns = PacketTestUtilities.CreateTestNetState();
@ -33,8 +48,9 @@ public class CorpsePacketTests
}
finally
{
c.Delete();
weapon.Delete();
c?.Delete();
weapon?.Delete();
m.Delete();
}
}
@ -43,16 +59,16 @@ public class CorpsePacketTests
[InlineData(ProtocolChanges.ContainerGridLines)]
public void TestCorpseContainerPacket(ProtocolChanges changes)
{
var m = new Mobile((Serial)0x1);
m.DefaultMobileInit();
var weapon = new VikingSword();
m.EquipItem(weapon);
var c = new Corpse(m, m.Items);
var m = new Mobile(World.NewMobile);
VikingSword weapon = null;
Corpse c = null;
try
{
m.DefaultMobileInit();
weapon = EquipSword(m);
c = new Corpse(m, m.Items);
using var ns = PacketTestUtilities.CreateTestNetState();
ns.ProtocolChanges = changes;
@ -65,8 +81,9 @@ public class CorpsePacketTests
}
finally
{
c.Delete();
weapon.Delete();
c?.Delete();
weapon?.Delete();
m.Delete();
}
}
}

View file

@ -87,14 +87,14 @@ public class VendorBuybackPackTests
var pack = new VendorBuybackPack();
var items = new Item[10];
for (var i = 0; i < items.Length; i++)
{
items[i] = new Item(0x1234);
pack.AddBuyback(items[i], 250);
}
try
{
for (var i = 0; i < items.Length; i++)
{
items[i] = new Item(0x1234);
pack.AddBuyback(items[i], 250);
}
pack.Purge();
Assert.Empty(pack.Items);

View file

@ -10,13 +10,19 @@ namespace UOContent.Tests;
[Collection("Sequential UOContent Tests")]
public class ThrowingTests
{
// Exposes protected ModifyHitChance so the math can be verified directly.
// Exposes protected ModifyHitChance so the math can be verified directly. The requirement and
// throw band are pinned here so retuning a shipped weapon cannot move these expectations.
private class TestThrown : BaseThrown
{
public TestThrown() : base(0x8FF) { }
// Weapons take their layer from tiledata, which CI doesn't load; without it AddItem is refused.
public TestThrown() : base(0x8FF) => Layer = Layer.OneHanded;
public override int AosStrengthReq => 60;
public override int MinThrowRange => 4;
public override int MaxThrowRange => 7;
public double TestModifyHitChance(Mobile attacker, Mobile defender, double chance) =>
ModifyHitChance(attacker, defender, chance);
@ -220,18 +226,19 @@ public class ThrowingTests
}
}
// DefMaxRange STR scaling (uses SoulGlaive: StrReq 60, Min 8, Max 11)
// DefMaxRange STR scaling (TestThrown: StrReq 60, Min 4, Max 7, so one tile per 26 Str)
[Fact]
public void DefMaxRange_AtStrReq_EqualsMinThrowRange()
{
var weapon = new SoulGlaive();
var weapon = new TestThrown();
var attacker = CreateMobile(Map.Felucca, new Point3D(5800, 500, 0));
try
{
attacker.RawStr = 60; // == AosStrengthReq
attacker.AddItem(weapon);
Assert.Equal(weapon.MinThrowRange, weapon.DefMaxRange); // 8
Assert.Same(attacker, weapon.Parent);
Assert.Equal(weapon.MinThrowRange, weapon.DefMaxRange); // 4
}
finally
{
@ -243,13 +250,14 @@ public class ThrowingTests
[Fact]
public void DefMaxRange_At140Str_EqualsMaxThrowRange()
{
var weapon = new SoulGlaive();
var weapon = new TestThrown();
var attacker = CreateMobile(Map.Felucca, new Point3D(5810, 500, 0));
try
{
attacker.RawStr = 140;
attacker.AddItem(weapon);
Assert.Equal(weapon.MaxThrowRange, weapon.DefMaxRange); // 11
Assert.Same(attacker, weapon.Parent);
Assert.Equal(weapon.MaxThrowRange, weapon.DefMaxRange); // 7
}
finally
{
@ -261,13 +269,14 @@ public class ThrowingTests
[Fact]
public void DefMaxRange_AboveMaxStr_IsCappedAtMaxThrowRange()
{
var weapon = new SoulGlaive();
var weapon = new TestThrown();
var attacker = CreateMobile(Map.Felucca, new Point3D(5820, 500, 0));
try
{
attacker.RawStr = 200; // uncapped formula would give 13
attacker.RawStr = 200; // uncapped formula would give 9
attacker.AddItem(weapon);
Assert.Equal(weapon.MaxThrowRange, weapon.DefMaxRange); // 11, not 13
Assert.Same(attacker, weapon.Parent);
Assert.Equal(weapon.MaxThrowRange, weapon.DefMaxRange); // 7, not 9
}
finally
{
@ -279,13 +288,14 @@ public class ThrowingTests
[Fact]
public void DefMaxRange_BelowStrReq_FlooredAtMinThrowRange()
{
var weapon = new SoulGlaive();
var weapon = new TestThrown();
var attacker = CreateMobile(Map.Felucca, new Point3D(5830, 500, 0));
try
{
attacker.RawStr = 10; // below StrReq 60
attacker.AddItem(weapon);
Assert.Equal(weapon.MinThrowRange, weapon.DefMaxRange); // 8, not 6
Assert.Same(attacker, weapon.Parent);
Assert.Equal(weapon.MinThrowRange, weapon.DefMaxRange); // 4, not 3
}
finally
{
@ -305,6 +315,7 @@ public class ThrowingTests
{
attacker.RawStr = 140; // MaxRange == MaxThrowRange == 7
attacker.AddItem(weapon);
Assert.Same(attacker, weapon.Parent);
var defender = CreateMobile(map, new Point3D(5907, 500, 0)); // distance 7 == MaxRange
try
{
@ -333,6 +344,7 @@ public class ThrowingTests
{
attacker.RawStr = 140; // MaxRange 7
attacker.AddItem(weapon);
Assert.Same(attacker, weapon.Parent);
var defender = CreateMobile(map, new Point3D(5925, 500, 0)); // distance 5 < 7
try
{

View file

@ -17,22 +17,23 @@ public class CorpseNotorietyTests
public void PlayerCorpseNotorietyIgnoresTransformedBody(int bodyMod, int expected, int kills = 0)
{
var victim = new PlayerMobile(World.NewMobile);
victim.DefaultMobileInit();
victim.Kills = kills;
victim.BodyMod = bodyMod;
var looter = new PlayerMobile(World.NewMobile);
looter.DefaultMobileInit();
var corpse = new Corpse(victim, []);
Corpse corpse = null;
try
{
victim.DefaultMobileInit();
victim.Kills = kills;
victim.BodyMod = bodyMod;
looter.DefaultMobileInit();
corpse = new Corpse(victim, []);
Assert.Equal(expected, NotorietyHandlers.CorpseNotoriety(looter, corpse));
}
finally
{
corpse.Delete();
corpse?.Delete();
victim.Delete();
looter.Delete();
}

View file

@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Reflection;
using Server.Configurations;
using Server.Misc;
using Xunit;
@ -7,13 +8,22 @@ using Xunit;
namespace UOContent.Tests;
[Collection("Sequential UOContent Tests")]
public class EmailTests
public class EmailTests : IDisposable
{
private static readonly PropertyInfo _emailEnabled =
typeof(EmailConfiguration).GetProperty(nameof(EmailConfiguration.EmailEnabled));
private readonly bool _savedEmailEnabled = EmailConfiguration.EmailEnabled;
// Pinned off rather than read from the host's email.json, so a developer config with email
// enabled cannot turn these into real sends.
public EmailTests() => _emailEnabled.SetValue(null, false);
public void Dispose() => _emailEnabled.SetValue(null, _savedEmailEnabled);
[Fact]
public void SendCrashEmailDoesNothingWhileEmailIsDisabled()
{
Assert.False(EmailConfiguration.EmailEnabled, "The test host never enables email");
// Missing input must be ignored while email is disabled.
var report = Path.Combine(Path.GetTempPath(), $"crash-email-test-{Guid.NewGuid():N}", "Crash.log");
@ -23,8 +33,7 @@ public class EmailTests
[Fact]
public void SendQueueEmailDoesNothingWhileEmailIsDisabled()
{
Assert.False(EmailConfiguration.EmailEnabled, "The test host never enables email");
// A null entry would throw on the enabled path, so returning cleanly shows the guard held.
Email.SendQueueEmail(null, "Other");
}

View file

@ -22,40 +22,55 @@ public class GuildSerializePurityTests
public void SerializeDoesNotRecalculateFealtyOrMutateState()
{
var leader = CreatePlayer();
var guild = new Guild(leader, "Purity Test Guild", "PTG");
var staleFealty = Core.Now - TimeSpan.FromDays(3);
guild.LastFealty = staleFealty;
Guild guild = null;
var writer = new BufferWriter(true);
guild.Serialize(writer);
try
{
guild = new Guild(leader, "Purity Test Guild", "PTG");
var staleFealty = Core.Now - TimeSpan.FromDays(3);
guild.LastFealty = staleFealty;
Assert.Equal(staleFealty, guild.LastFealty);
Assert.Same(leader, guild.Leader);
var writer = new BufferWriter(true);
guild.Serialize(writer);
var first = writer.Buffer.AsSpan(0, (int)writer.Position).ToArray();
writer.Seek(0, SeekOrigin.Begin);
guild.Serialize(writer);
var second = writer.Buffer.AsSpan(0, (int)writer.Position).ToArray();
Assert.Equal(staleFealty, guild.LastFealty);
Assert.Same(leader, guild.Leader);
Assert.Equal(first, second);
var first = writer.Buffer.AsSpan(0, (int)writer.Position).ToArray();
writer.Seek(0, SeekOrigin.Begin);
guild.Serialize(writer);
var second = writer.Buffer.AsSpan(0, (int)writer.Position).ToArray();
writer.Close();
guild.Disband();
leader.Delete();
Assert.Equal(first, second);
writer.Close();
}
finally
{
guild?.Disband();
leader.Delete();
}
}
[Fact]
public void RunMaintenanceRecalculatesStaleFealty()
{
var leader = CreatePlayer();
var guild = new Guild(leader, "Maintenance Test Guild", "MTG");
guild.LastFealty = Core.Now - TimeSpan.FromDays(3);
Guild guild = null;
guild.RunMaintenance();
try
{
guild = new Guild(leader, "Maintenance Test Guild", "MTG");
guild.LastFealty = Core.Now - TimeSpan.FromDays(3);
Assert.True(Core.Now - guild.LastFealty < TimeSpan.FromMinutes(1));
guild.RunMaintenance();
guild.Disband();
leader.Delete();
Assert.True(Core.Now - guild.LastFealty < TimeSpan.FromMinutes(1));
}
finally
{
guild?.Disband();
leader.Delete();
}
}
}

View file

@ -38,7 +38,7 @@ public class NameVerificationTests
[InlineData("Blacksmith 123")]
[InlineData("Baker-Smith")]
[InlineData("*Innkeeper*")]
public void ValidateVendorName_ValidNames_ReturnsFalse(string name)
public void ValidateVendorName_DisallowedCharacters_ReturnsFalse(string name)
{
Assert.False(NameVerification.ValidateVendorName(name));
}

View file

@ -60,9 +60,14 @@ public class AcquisitionTests : IDisposable
bc.NextReacquireTime = Core.TickCount;
Assert.False(bc.AIObject.AcquireFocusMob(bc.RangePerception, FightMode.Closest, false, false, true));
Assert.InRange(bc.NextReacquireTime - Core.TickCount, 5000, 10000);
Assert.Equal(ReacquireDelayMs(bc), bc.NextReacquireTime - Core.TickCount);
}
private static long ReacquireDelayMs(BaseCreature bc) => (long)bc.ReacquireDelay.TotalMilliseconds;
// A legal, fully armed deadline: as far out as a scan ever sets it. Movement can only pull it in.
private static void ArmFullDelay(BaseCreature bc) => bc.NextReacquireTime = Core.TickCount + ReacquireDelayMs(bc);
[Fact]
public void WedgedGate_SelfHeals()
{
@ -78,7 +83,7 @@ public class AcquisitionTests : IDisposable
_created.Add(target);
// Illegal deadline (beyond ReacquireDelay): must read as open, not block forever.
bc.NextReacquireTime = Core.TickCount + 60000;
bc.NextReacquireTime = Core.TickCount + ReacquireDelayMs(bc) * 6;
Assert.True(bc.AIObject.AcquireFocusMob(bc.RangePerception, FightMode.Closest, false, false, true));
Assert.Equal(target, bc.FocusMob);
@ -96,7 +101,8 @@ public class AcquisitionTests : IDisposable
map.GetAverageZ(1500, 1600, out _, out var z, out _);
var bc = Spawn(map, new Point3D(1500, 1600, (sbyte)z));
bc.NextReacquireTime = Core.TickCount + 8000;
ArmFullDelay(bc);
var armed = bc.NextReacquireTime;
Mobile mover;
if (wildMover)
@ -117,12 +123,12 @@ public class AcquisitionTests : IDisposable
if (notices)
{
// Clamped to the approach delay (2s), never opened outright.
// Clamped to the approach delay, never opened outright.
Assert.InRange(remaining, 1, (long)bc.AcquireOnApproachDelay.TotalMilliseconds);
}
else
{
Assert.True(remaining > 5000);
Assert.Equal(armed, bc.NextReacquireTime);
}
}
@ -150,7 +156,7 @@ public class AcquisitionTests : IDisposable
bc.MoveToWorld(new Point3D(1500, 1600, (sbyte)z), map);
bc.AIObject.AITimer?.Stop();
_created.Add(bc);
bc.NextReacquireTime = Core.TickCount + 8000;
ArmFullDelay(bc);
var mover = new TargetStub { Player = true };
mover.DefaultMobileInit();
@ -173,7 +179,7 @@ public class AcquisitionTests : IDisposable
map.GetAverageZ(1500, 1600, out _, out var z, out _);
var bc = Spawn(map, new Point3D(1500, 1600, (sbyte)z));
bc.NextReacquireTime = Core.TickCount + 8000;
ArmFullDelay(bc);
var mover = new TargetStub { Player = true };
mover.DefaultMobileInit();
@ -206,6 +212,6 @@ public class AcquisitionTests : IDisposable
Assert.True(bc.AIObject.AcquireFocusMob(bc.RangePerception, FightMode.Closest, false, false, true));
Assert.Equal(target, bc.FocusMob);
Assert.True(bc.NextReacquireTime - Core.TickCount > 5000);
Assert.Equal(ReacquireDelayMs(bc), bc.NextReacquireTime - Core.TickCount);
}
}

View file

@ -1,43 +1,47 @@
using System;
using System.Collections.Generic;
using Server;
using Server.Engines.Pathing.Cache;
using Server.Mobiles;
using Server.Tests;
using Server.Tests.Mobiles.AI;
using Xunit;
namespace UOContent.Tests.Mobiles.AI;
// Driven manually against live map statics; the pathfinder's buffers are not reentrant.
[Collection("Sequential Pathfinding Tests")]
public class ApproachOutcomeTests
public class ApproachOutcomeTests : IDisposable
{
private sealed class Stub : BaseCreature
private readonly List<IEntity> _created = [];
public void Dispose()
{
public Stub(Serial serial) : base(serial) => Body = 0xC9;
for (var i = _created.Count - 1; i >= 0; i--)
{
_created[i].Delete();
}
_created.Clear();
}
private sealed class Target : Mobile
{
public Target() => Body = 0xC9;
}
private static (Stub bc, BaseAI ai) NewFollower(Map map, int x, int y)
private (BareCreatureStub bc, BaseAI ai) NewFollower(Map map, int x, int y)
{
map.GetAverageZ(x, y, out _, out var z, out _);
var bc = new Stub(World.NewMobile);
var bc = new BareCreatureStub(World.NewMobile);
bc.DefaultMobileInit();
bc.MoveToWorld(new Point3D(x, y, (sbyte)z), map);
_created.Add(bc);
BaseAI ai = new AnimalAI(bc);
ai.AITimer?.Stop();
return (bc, ai);
}
private static Target NewTarget(Map map, int x, int y)
private WalkerStub NewTarget(Map map, int x, int y)
{
map.GetAverageZ(x, y, out _, out var z, out _);
var t = new Target();
var t = new WalkerStub();
t.MoveToWorld(new Point3D(x, y, (sbyte)z), map);
_created.Add(t);
return t;
}
@ -46,32 +50,24 @@ public class ApproachOutcomeTests
{
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[1];
var (bc, ai) = NewFollower(map, 1500, 1600);
var (_, ai) = NewFollower(map, 1500, 1600);
var target = NewTarget(map, 1497, 1600);
StepCache.Instance.Clear();
try
{
ai.NextMove = 0;
ai.MoveTo(target, 1);
Assert.Equal(ApproachOutcome.DirectProgress, ai.LastApproach);
ai.NextMove = 0;
ai.MoveTo(target, 1);
Assert.Equal(ApproachOutcome.DirectProgress, ai.LastApproach);
ai.MoveTo(target, 1); // budget consumed: no step
Assert.Equal(ApproachOutcome.Waiting, ai.LastApproach);
ai.MoveTo(target, 1); // budget consumed: no step
Assert.Equal(ApproachOutcome.Waiting, ai.LastApproach);
ai.NextMove = 0;
ai.MoveTo(target, 1); // lands adjacent: still a progress step
Assert.Equal(ApproachOutcome.DirectProgress, ai.LastApproach);
ai.NextMove = 0;
ai.MoveTo(target, 1); // lands adjacent: still a progress step
Assert.Equal(ApproachOutcome.DirectProgress, ai.LastApproach);
ai.NextMove = 0;
ai.MoveTo(target, 1);
Assert.Equal(ApproachOutcome.Arrived, ai.LastApproach);
}
finally
{
bc.Delete();
target.Delete();
}
ai.NextMove = 0;
ai.MoveTo(target, 1);
Assert.Equal(ApproachOutcome.Arrived, ai.LastApproach);
}
[SkippableFact]
@ -79,10 +75,9 @@ public class ApproachOutcomeTests
{
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[1];
var (bc, ai) = NewFollower(map, 1500, 1601);
var (_, ai) = NewFollower(map, 1500, 1601);
var target = NewTarget(map, 1500, 1596);
var ring = new List<Item>();
var id = ApproachTargetTests.FirstImpassableItemId();
var id = TestTiles.FirstImpassableItemId();
Assert.NotEqual<ushort>(0, id);
// Impassable ring around the target: unreachable.
@ -96,35 +91,22 @@ public class ApproachOutcomeTests
}
map.GetAverageZ(x, y, out _, out var rz, out _);
ring.Add(new Item(World.NewItem) { ItemID = id, Map = map, Location = new Point3D(x, y, (sbyte)rz) });
_created.Add(new Item(World.NewItem) { ItemID = id, Map = map, Location = new Point3D(x, y, (sbyte)rz) });
}
}
StepCache.Instance.Clear();
try
var sawRouting = false;
for (var i = 0; i < 120; i++)
{
var sawRouting = false;
for (var i = 0; i < 120; i++)
{
ai.NextMove = 0;
ai.MoveTo(target, 1);
sawRouting |= ai.LastApproach is ApproachOutcome.Routing or ApproachOutcome.Blocked;
}
Assert.True(sawRouting, "a walled target must route or block before giving up");
Assert.Equal(ApproachOutcome.GaveUp, ai.LastApproach);
ai.NextMove = 0;
ai.MoveTo(target, 1);
sawRouting |= ai.LastApproach is ApproachOutcome.Routing or ApproachOutcome.Blocked;
}
finally
{
bc.Delete();
target.Delete();
for (var i = 0; i < ring.Count; i++)
{
ring[i].Delete();
}
}
Assert.True(sawRouting, "a walled target must route or block before giving up");
Assert.Equal(ApproachOutcome.GaveUp, ai.LastApproach);
}
}

View file

@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using Server.Engines.Pathing.Cache;
using Server.Mobiles;
@ -9,29 +10,45 @@ namespace Server.Tests.Mobiles.AI;
// pathfinder uses non-reentrant static buffers, so we share the pathfinding sequential
// collection to avoid parallel interference.
[Collection("Sequential Pathfinding Tests")]
public class ApproachTargetTests
public class ApproachTargetTests : IDisposable
{
private sealed class FollowerStub : BaseCreature
private readonly List<IEntity> _created = [];
public void Dispose()
{
// Serial ctor + DefaultMobileInit bypasses NPCSpeeds JSON (absent in tests).
public FollowerStub(Serial serial) : base(serial) => Body = 0xC9;
for (var i = _created.Count - 1; i >= 0; i--)
{
_created[i].Delete();
}
_created.Clear();
}
private sealed class TargetStub : Mobile
private (BareCreatureStub bc, BaseAI ai) NewFollower(Map map, Point3D loc)
{
public TargetStub() => Body = 0xC9;
}
private static (FollowerStub bc, BaseAI ai) NewFollower(Map map, Point3D loc)
{
var bc = new FollowerStub(World.NewMobile);
var bc = new BareCreatureStub(World.NewMobile);
bc.DefaultMobileInit();
bc.MoveToWorld(loc, map);
_created.Add(bc);
BaseAI ai = new AnimalAI(bc);
ai.AITimer?.Stop(); // we drive movement manually; no background timer
return (bc, ai);
}
private WalkerStub NewTarget(Map map, Point3D loc)
{
var target = new WalkerStub();
target.MoveToWorld(loc, map);
_created.Add(target);
return target;
}
private void PlaceBlocker(Map map, ushort itemId, int x, int y)
{
map.GetAverageZ(x, y, out _, out var z, out _);
_created.Add(new Item(World.NewItem) { ItemID = itemId, Map = map, Location = new Point3D(x, y, (sbyte)z) });
}
// Drives the pet follow primitive once per tick; returns true once it reaches within
// arriveDist tiles. Uses InRange (Chebyshev) to match the game's own range semantics —
// a diagonal neighbor at Euclidean ~2.24 is "within 2" to the engine.
@ -49,18 +66,6 @@ public class ApproachTargetTests
return false;
}
internal static ushort FirstImpassableItemId()
{
for (ushort id = 1; id < TileData.MaxItemValue; id++)
{
if (TileData.ItemTable[id].ImpassableSurface)
{
return id;
}
}
return 0;
}
[Fact]
public void OpenTerrain_ReachesTarget_WithoutPathfinding()
{
@ -69,8 +74,7 @@ public class ApproachTargetTests
map.GetAverageZ(1500, 1600, out _, out var z, out _);
var (bc, ai) = NewFollower(map, new Point3D(1500, 1600, (sbyte)z));
var target = new TargetStub();
target.MoveToWorld(new Point3D(1495, 1600, (sbyte)z), map); // 5 tiles west, open
var target = NewTarget(map, new Point3D(1495, 1600, (sbyte)z)); // 5 tiles west, open
StepCache.Instance.Clear();
var buildsBefore = StepCache.Instance.GetStats().BuildsTotal;
@ -78,44 +82,40 @@ public class ApproachTargetTests
var arrived = DriveFollow(ai, bc, target, 2, 40);
var buildsAfter = StepCache.Instance.GetStats().BuildsTotal;
bc.Delete();
target.Delete();
Assert.True(arrived, "creature should reach an open-terrain target by stepping");
Assert.Equal(buildsBefore, buildsAfter); // greedy fast path: no chunk builds
}
[Fact]
// The desk is a Britain inn static; on a blank map the detour is a straight walk.
[SkippableFact]
public void BritainInnDesk_PetReachesMaster()
{
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[1];
Assert.NotNull(map);
// Exact in-game repro: pet south of the L-desk, master north of it.
var (bc, ai) = NewFollower(map, new Point3D(1493, 1614, 20));
var target = new TargetStub();
target.MoveToWorld(new Point3D(1494, 1605, 21), map);
var target = NewTarget(map, new Point3D(1494, 1605, 21));
StepCache.Instance.Clear();
// 200 ticks is generous for the ~17-step detour at one step per tick.
var arrived = DriveFollow(ai, bc, target, 2, 200);
bc.Delete();
target.Delete();
Assert.True(arrived, "pet must navigate around the L-desk to reach the master");
}
[Fact]
[SkippableFact]
public void MoveTo_ReachesTargetAroundDesk()
{
TileDataRequirement.SkipIfMissing();
var map = Map.Maps[1];
Assert.NotNull(map);
var (bc, ai) = NewFollower(map, new Point3D(1493, 1614, 20));
var target = new TargetStub();
target.MoveToWorld(new Point3D(1494, 1605, 21), map);
var target = NewTarget(map, new Point3D(1494, 1605, 21));
StepCache.Instance.Clear();
@ -131,9 +131,6 @@ public class ApproachTargetTests
}
}
bc.Delete();
target.Delete();
Assert.True(arrived, "MoveTo chaser must reach the target around the desk");
}
@ -145,8 +142,7 @@ public class ApproachTargetTests
map.GetAverageZ(1500, 1600, out _, out var z, out _);
var (bc, ai) = NewFollower(map, new Point3D(1500, 1600, (sbyte)z));
var target = new TargetStub();
target.MoveToWorld(new Point3D(1498, 1600, (sbyte)z), map);
var target = NewTarget(map, new Point3D(1498, 1600, (sbyte)z));
StepCache.Instance.Clear();
@ -170,9 +166,6 @@ public class ApproachTargetTests
}
}
bc.Delete();
target.Delete();
Assert.True(caught, "chaser must catch a target that walks away then stops");
}
@ -185,13 +178,11 @@ public class ApproachTargetTests
map.GetAverageZ(1500, 1601, out _, out var z, out _);
var (bc, ai) = NewFollower(map, new Point3D(1500, 1601, (sbyte)z));
var target = new TargetStub();
target.MoveToWorld(new Point3D(1500, 1596, (sbyte)z), map);
var target = NewTarget(map, new Point3D(1500, 1596, (sbyte)z));
// Full impassable ring around the target cell -> no path to within range 1.
var id = FirstImpassableItemId();
var id = TestTiles.FirstImpassableItemId();
Assert.NotEqual<ushort>(0, id);
var ring = new List<Item>();
for (var x = 1499; x <= 1501; x++)
{
for (var y = 1595; y <= 1597; y++)
@ -200,11 +191,8 @@ public class ApproachTargetTests
{
continue; // leave the target's own cell
}
map.GetAverageZ(x, y, out _, out var rz, out _);
ring.Add(new Item(World.NewItem)
{
ItemID = id, Map = map, Location = new Point3D(x, y, (sbyte)rz)
});
PlaceBlocker(map, id, x, y);
}
}
@ -231,16 +219,7 @@ public class ApproachTargetTests
}
}
var reached = bc.InRange(target, 1);
bc.Delete();
target.Delete();
foreach (var it in ring)
{
it.Delete();
}
Assert.False(reached, "walled-off target must not be reached");
Assert.False(bc.InRange(target, 1), "walled-off target must not be reached");
Assert.True(stayedIdle, "after giving up, the creature must idle, not shuffle");
}
@ -253,33 +232,20 @@ public class ApproachTargetTests
map.GetAverageZ(1500, 1600, out _, out var z, out _);
var (bc, ai) = NewFollower(map, new Point3D(1500, 1600, (sbyte)z));
var target = new TargetStub();
target.MoveToWorld(new Point3D(1500, 1595, (sbyte)z), map); // 5 tiles north
var target = NewTarget(map, new Point3D(1500, 1595, (sbyte)z)); // 5 tiles north
// Impassable wall on Y=1598 from X=1497..1503: blocks the straight line; ends open.
var id = FirstImpassableItemId();
var id = TestTiles.FirstImpassableItemId();
Assert.NotEqual<ushort>(0, id);
var wall = new List<Item>();
for (var x = 1497; x <= 1503; x++)
{
map.GetAverageZ(x, 1598, out _, out var wz, out _);
wall.Add(new Item(World.NewItem)
{
ItemID = id, Map = map, Location = new Point3D(x, 1598, (sbyte)wz)
});
PlaceBlocker(map, id, x, 1598);
}
StepCache.Instance.Clear();
var arrived = DriveFollow(ai, bc, target, 2, 200);
bc.Delete();
target.Delete();
foreach (var it in wall)
{
it.Delete();
}
Assert.True(arrived, "creature must route around the wall to reach the target");
}
}

View file

@ -1,6 +1,7 @@
using System;
using Server;
using Server.Mobiles;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Mobiles.AI;
@ -37,9 +38,8 @@ public class DetectHiddenTimerTests
public void DetectHidden_SchedulesBoundedCooldown_AndWaitsBeforeRetry(
int intelligence, long minDelay, long maxDelay)
{
Skip.If(!Server.Tests.TestServerInitializer.TileDataLoaded, "Requires UO client map data.");
Core._tickCount = 0;
Timer.Init(0);
Skip.If(!TestServerInitializer.TileDataLoaded, "Requires UO client map data.");
using var clock = new TimerWheelScope();
var creature = new DetectingCreature();
DetectingAI ai = null;
@ -63,12 +63,8 @@ public class DetectHiddenTimerTests
Assert.InRange(ai._nextDetectHidden - Core.TickCount, minDelay, maxDelay);
Assert.True(ai.AITimer.Running);
var deadline = ai._nextDetectHidden;
while (Core.TickCount + 8 < deadline)
{
Core._tickCount += 8;
Timer.Slice(Core.TickCount);
}
// Stop one wheel step short of the cooldown: no retry may have fired yet.
TimerWheelScope.RunFor(ai._nextDetectHidden - TimerWheelScope.Step - Core.TickCount);
Assert.Equal(1, ai.Detections);
AdvanceUntil(() => ai.Detections > 1, 1024);
@ -82,14 +78,9 @@ public class DetectHiddenTimerTests
}
}
private static void AdvanceUntil(Func<bool> condition, int milliseconds)
{
for (var elapsed = 0; !condition() && elapsed < milliseconds; elapsed += 8)
{
Core._tickCount += 8;
Timer.Slice(Core.TickCount);
}
Assert.True(condition(), "The AI timer did not reach the expected detection.");
}
private static void AdvanceUntil(Func<bool> condition, int milliseconds) =>
Assert.True(
TimerWheelScope.RunUntil(condition, milliseconds),
"The AI timer did not reach the expected detection."
);
}

View file

@ -4,8 +4,8 @@ using Server;
using Server.Items;
using Server.Mobiles;
using Server.Tests;
using Server.Tests.Mobiles.AI;
using Xunit;
using static Server.Tests.TimerWheelScope;
namespace UOContent.Tests.Mobiles.AI;
@ -50,12 +50,12 @@ public class FamiliarAITests : IDisposable
private static readonly Map _map = Map.Maps[1];
private readonly List<IEntity> _created = new();
private readonly TimerWheelScope _clock;
public FamiliarAITests()
{
TileDataRequirement.SkipIfMissing();
Core._tickCount = 0;
Timer.Init(0);
_clock = new TimerWheelScope();
}
public void Dispose()
@ -64,6 +64,8 @@ public class FamiliarAITests : IDisposable
{
_created[i].Delete();
}
_clock.Dispose();
}
private static Point3D At(int x, int y)
@ -109,36 +111,6 @@ public class FamiliarAITests : IDisposable
return e;
}
// 8ms lockstep keeps the wheel and Core.TickCount in sync.
private static void RunFor(long ms)
{
var deadline = Core._tickCount + ms;
while (Core._tickCount - deadline < 0)
{
Core._tickCount += 8;
Timer.Slice(Core._tickCount);
}
}
private static bool RunUntil(Func<bool> condition, long maxMs)
{
var deadline = Core._tickCount + maxMs;
while (Core._tickCount - deadline < 0)
{
if (condition())
{
return true;
}
Core._tickCount += 8;
Timer.Slice(Core._tickCount);
}
return condition();
}
[SkippableFact]
public void Follows_WithoutBacktracking()
{
@ -323,7 +295,7 @@ public class FamiliarAITests : IDisposable
var f = Familiar(0, p, 1500, 1602);
// 5x5 ring, open 3x3 interior: a landing tile exists, no route reaches it.
var id = ApproachTargetTests.FirstImpassableItemId();
var id = TestTiles.FirstImpassableItemId();
Assert.NotEqual<ushort>(0, id);
for (var x = 1498; x <= 1502; x++)

View file

@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using Server;
using Server.Mobiles;
@ -7,8 +8,20 @@ namespace UOContent.Tests.Mobiles.AI;
// Guard-following may pathfind, so this shares the pathfinding collection.
[Collection("Sequential Pathfinding Tests")]
public class GuardFollowTests
public class GuardFollowTests : IDisposable
{
private readonly List<Mobile> _created = [];
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
_created.Clear();
}
[Fact]
public void GuardFollow_StepsTowardMaster_AndRegistersMoveIntent()
{
@ -16,13 +29,14 @@ public class GuardFollowTests
Assert.NotNull(map);
map.GetAverageZ(1500, 1600, out _, out var z, out _);
var master = new PlayerMobile(World.NewMobile);
master.DefaultMobileInit();
master.MoveToWorld(new Point3D(1494, 1600, (sbyte)z), map);
var pet = new PetTestStub();
pet.MoveToWorld(new Point3D(1500, 1600, (sbyte)z), map); // 6 tiles east, open terrain
pet.SetControlMaster(master);
// Pet 6 tiles east of the master, open terrain.
var (master, pet) = PetTestSetup.SpawnControlledPet(
new Point3D(1494, 1600, (sbyte)z),
new Point3D(1500, 1600, (sbyte)z),
map
);
_created.Add(master);
_created.Add(pet);
var ai = pet.AIObject;
ai.AITimer?.Stop(); // drive manually
@ -33,21 +47,13 @@ public class GuardFollowTests
ai.NextMove = 0;
ai.Obey();
var moved = pet.Location != start;
var hasIntent = ai.TryGetMoveWake(out _);
var currentSpeed = pet.CurrentSpeed;
var currentMoveSpeed = pet.CurrentMoveSpeed;
pet.Delete();
master.Delete();
Assert.True(moved, "a guarding pet beyond guard range must step toward its master");
Assert.True(pet.Location != start, "a guarding pet beyond guard range must step toward its master");
// Without a move intent, guard-following only steps on the think grid.
Assert.True(hasIntent, "guard-following must register a move intent");
Assert.True(ai.TryGetMoveWake(out _), "guard-following must register a move intent");
// The return is paced by FollowMoveSpeed; the think clock stays on the active value
// and the per-step speed flip must not undo either.
Assert.Equal(0.2, currentSpeed);
Assert.Equal(0.1, currentMoveSpeed);
Assert.Equal(0.2, pet.CurrentSpeed);
Assert.Equal(pet.FollowMoveSpeed, pet.CurrentMoveSpeed);
}
}

View file

@ -11,10 +11,24 @@ public class GuardFriendlyFireTests : IDisposable
{
private readonly List<Mobile> _created = [];
// AI_Mage stands in for a shipped caster: MageAI's combat loop has its own reacquire path.
private sealed class MagePet : BaseCreature
{
public MagePet() : base(AIType.AI_Mage, FightMode.Closest, 10, 1) => Body = 0xC8;
public override void GetSpeeds(out double activeSpeed, out double passiveSpeed)
{
activeSpeed = 0.2;
passiveSpeed = 0.4;
}
}
private (PlayerMobile owner, PetTestStub pet) Spawn()
{
Skip.If(!Server.Tests.TestServerInitializer.TileDataLoaded, "Requires UO client map data.");
var z = Map.Felucca.GetAverageZ(1500, 1600);
// The constructed PlayerMobile, not PetTestSetup's deserialization-shaped one: the harmful
// checks read PermaFlags, which only the full constructor allocates.
var owner = new PlayerMobile();
owner.MoveToWorld(new Point3D(1500, 1600, z), Map.Felucca);
_created.Add(owner);
@ -192,28 +206,28 @@ public class GuardFriendlyFireTests : IDisposable
}
[SkippableFact]
public void ActualWhiteWyrmDoesNotTurnOnOwnerWhenEnemyDisappears()
public void GuardingMageDoesNotTurnOnOwnerWhenEnemyDisappears()
{
var (owner, _) = Spawn();
var wyrm = new WhiteWyrm();
_created.Add(wyrm);
wyrm.MoveToWorld(new Point3D(1498, 1600, owner.Z), owner.Map);
wyrm.SetControlMaster(owner);
wyrm.IssueOrder(OrderType.Guard, owner);
wyrm.AIObject.AITimer.Stop();
var mage = new MagePet();
_created.Add(mage);
mage.MoveToWorld(new Point3D(1498, 1600, owner.Z), owner.Map);
mage.SetControlMaster(owner);
mage.IssueOrder(OrderType.Guard, owner);
mage.AIObject.AITimer.Stop();
var enemy = new PetTestStub();
_created.Add(enemy);
enemy.MoveToWorld(new Point3D(1497, 1600, owner.Z), owner.Map);
enemy.AIObject.AITimer.Stop();
wyrm.Combatant = enemy;
mage.Combatant = enemy;
enemy.Hidden = true;
wyrm.NextReacquireTime = Core.TickCount - 1;
Assert.IsType<MageAI>(wyrm.AIObject);
wyrm.AIObject.DoActionCombat();
Assert.NotSame(owner, wyrm.Combatant);
Assert.Null(wyrm.FocusMob);
wyrm.AIObject.DoOrderGuard();
Assert.Null(wyrm.Combatant);
mage.NextReacquireTime = Core.TickCount - 1;
Assert.IsType<MageAI>(mage.AIObject);
mage.AIObject.DoActionCombat();
Assert.NotSame(owner, mage.Combatant);
Assert.Null(mage.FocusMob);
mage.AIObject.DoOrderGuard();
Assert.Null(mage.Combatant);
}
public void Dispose()

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using Server;
using Server.Mobiles;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Mobiles.AI;
@ -14,11 +15,6 @@ public class GuardOrderTests : IDisposable
{
private readonly List<Mobile> _created = new();
private sealed class AggressorStub : Mobile
{
public AggressorStub() => Body = 0xC9;
}
public void Dispose()
{
foreach (var m in _created)
@ -35,14 +31,12 @@ public class GuardOrderTests : IDisposable
Assert.NotNull(map);
map.GetAverageZ(1500, 1600, out _, out z, out _);
var master = new PlayerMobile(World.NewMobile);
master.DefaultMobileInit();
master.MoveToWorld(new Point3D(1500, 1600, (sbyte)z), map);
var (master, pet) = PetTestSetup.SpawnControlledPet(
new Point3D(1500, 1600, (sbyte)z),
new Point3D(1499, 1600, (sbyte)z),
map
);
_created.Add(master);
var pet = new PetTestStub();
pet.MoveToWorld(new Point3D(1499, 1600, (sbyte)z), map);
pet.SetControlMaster(master);
_created.Add(pet);
pet.AIObject.AITimer?.Stop(); // drive manually
@ -52,9 +46,9 @@ public class GuardOrderTests : IDisposable
return (master, pet);
}
private AggressorStub SpawnAggressor(PetTestStub pet, Point3D loc, Mobile attacking)
private WalkerStub SpawnAggressor(PetTestStub pet, Point3D loc, Mobile attacking)
{
var aggr = new AggressorStub();
var aggr = new WalkerStub();
aggr.MoveToWorld(loc, pet.Map);
_created.Add(aggr);

View file

@ -10,11 +10,6 @@ namespace UOContent.Tests.Mobiles.AI;
[Collection("Sequential Pathfinding Tests")]
public class HerdingTests
{
private sealed class Stub : BaseCreature
{
public Stub(Serial serial) : base(serial) => Body = 0xC9;
}
[SkippableFact]
public void HerdedCreature_ReachesTheTile_AndClearsTargetLocation()
{
@ -22,7 +17,7 @@ public class HerdingTests
var map = Map.Maps[1];
map.GetAverageZ(1500, 1600, out _, out var z, out _);
var bc = new Stub(World.NewMobile);
var bc = new BareCreatureStub(World.NewMobile);
bc.DefaultMobileInit();
bc.MoveToWorld(new Point3D(1500, 1600, (sbyte)z), map);
BaseAI ai = new AnimalAI(bc);

View file

@ -210,10 +210,10 @@ public class PetOrderTests : IDisposable
Assert.Equal(post, pet.Home); // anchor still the original post, not the corpse
}
// NOTE: the test fixture does not load tile data, so Mobile.Move is blocked and Location
// never changes here. DoMoveImpl still sets Mobile.Direction before the (blocked) move,
// so an *attempted* wander is observable via Direction. The subjective wander cadence is
// covered by manual QA; these tests verify the gate/frozen wiring deterministically.
// A step may be blocked by whatever terrain (1000, 1000) holds, but DoMoveImpl sets
// Mobile.Direction before attempting the move, so an *attempted* wander is observable via
// Direction either way. The subjective wander cadence is covered by manual QA; these tests
// verify the gate/frozen wiring deterministically.
[Fact]
public void IdlePet_DoesNotAttemptToMove_WhileResting()
{
@ -224,12 +224,18 @@ public class PetOrderTests : IDisposable
pet.ForceIdle = true; // CheckIdle() reports resting -> idle wander must be skipped
pet.Direction = Direction.North;
var start = pet.Location;
var ai = pet.AIObject;
for (var i = 0; i < 40; i++)
{
pet.AIObject.DoOrderNone();
// Reopen the move clock every pass, so CheckIdle is the only gate left standing.
ai.NextMove = Core.TickCount;
Assert.True(ai.CanMoveNow(out _));
ai.DoOrderNone();
}
Assert.Equal(Direction.North, pet.Direction); // gated by CheckIdle -> never attempts a step
Assert.Equal(start, pet.Location);
}
[Fact]

View file

@ -2,7 +2,9 @@ using System;
using System.Collections.Generic;
using Server;
using Server.Mobiles;
using Server.Tests;
using Xunit;
using static Server.Tests.TimerWheelScope;
namespace UOContent.Tests.Mobiles.AI;
@ -11,6 +13,7 @@ namespace UOContent.Tests.Mobiles.AI;
public class PetPacingTests : IDisposable
{
private readonly List<Mobile> _created = new();
private TimerWheelScope _clock;
private (PlayerMobile master, PetTestStub pet) Spawn(Point3D masterLoc, Point3D petLoc)
{
@ -28,6 +31,7 @@ public class PetPacingTests : IDisposable
}
_created.Clear();
_clock?.Dispose();
}
// Movement orders run active, resting orders run passive; the move clock follows.
@ -64,8 +68,8 @@ public class PetPacingTests : IDisposable
pet.ControlTarget = master;
pet.ControlOrder = OrderType.Follow; // fixture era is EJ
Assert.Equal(0.2, pet.CurrentSpeed); // active think, not the follow pace
Assert.Equal(0.1, pet.CurrentMoveSpeed); // capped at the follow pace
Assert.Equal(0.2, pet.CurrentSpeed); // active think, not the follow pace
Assert.Equal(pet.FollowMoveSpeed, pet.CurrentMoveSpeed); // capped at the follow pace
}
// A creature configured faster than the follow pace keeps its own.
@ -73,12 +77,13 @@ public class PetPacingTests : IDisposable
public void FollowMaster_KeepsAFasterConfiguredPace()
{
var (master, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
pet.SetMoveSpeed(0.05, 0.9);
var faster = pet.FollowMoveSpeed / 2;
pet.SetMoveSpeed(faster, 0.9);
pet.ControlTarget = master;
pet.ControlOrder = OrderType.Follow;
Assert.Equal(0.05, pet.CurrentMoveSpeed);
Assert.Equal(faster, pet.CurrentMoveSpeed);
}
// The move-clock override survives the order: it is capped while following, not overwritten.
@ -145,7 +150,7 @@ public class PetPacingTests : IDisposable
pet.ControlOrder = OrderType.Guard;
Assert.Equal(0.2, pet.CurrentSpeed);
Assert.Equal(0.1, pet.CurrentMoveSpeed);
Assert.Equal(pet.FollowMoveSpeed, pet.CurrentMoveSpeed);
}
// Obeying the follow order must not write the pace into either clock.
@ -161,7 +166,7 @@ public class PetPacingTests : IDisposable
pet.AIObject.Obey();
Assert.Equal(0.2, pet.CurrentSpeed);
Assert.Equal(0.1, pet.CurrentMoveSpeed);
Assert.Equal(pet.FollowMoveSpeed, pet.CurrentMoveSpeed);
}
// At the master's side a guarding pet stays active: no stale-warmode passive, no sprint.
@ -208,41 +213,10 @@ public class PetPacingTests : IDisposable
return (master, pet);
}
// Advances time in 8ms lockstep so the wheel and Core.TickCount stay in sync.
private static void RunFor(long ms)
{
var deadline = Core._tickCount + ms;
while (Core._tickCount < deadline)
{
Core._tickCount += 8;
Timer.Slice(Core._tickCount);
}
}
private static bool RunUntil(Func<bool> condition, long maxMs)
{
var deadline = Core._tickCount + maxMs;
while (Core._tickCount < deadline)
{
if (condition())
{
return true;
}
Core._tickCount += 8;
Timer.Slice(Core._tickCount);
}
return condition();
}
// Runs past the spawn stagger; returns right after a think with the next 0.4s away.
private ThinkProbe SettledProbe(out PlayerMobile master)
{
Core._tickCount = 0;
Timer.Init(0);
_clock = new TimerWheelScope();
var (m, pet) = SpawnProbe();
master = m;

View file

@ -35,16 +35,10 @@ public class PetRetaliationTests : IDisposable
private (PlayerMobile master, T pet) Spawn<T>() where T : BaseCreature, new()
{
var master = new PlayerMobile(World.NewMobile);
master.DefaultMobileInit();
master.MoveToWorld(new Point3D(1000, 1000, 0), Map.Felucca);
var (master, pet) = PetTestSetup.SpawnControlledPet<T>(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
_created.Add(master);
var pet = new T();
pet.MoveToWorld(new Point3D(1001, 1000, 0), Map.Felucca);
pet.SetControlMaster(master);
pet.AIObject.AITimer?.Stop();
_created.Add(pet);
pet.AIObject.AITimer?.Stop();
return (master, pet);
}

View file

@ -49,17 +49,21 @@ public class PetTestStub : BaseCreature
public static class PetTestSetup
{
// Places a player master and a controlled pet on Felucca and returns both.
// Places a player master and a controlled pet (on Felucca unless a map is given) and returns both.
public static (PlayerMobile master, PetTestStub pet) SpawnControlledPet(
Point3D masterLoc, Point3D petLoc)
Point3D masterLoc, Point3D petLoc, Map map = null) =>
SpawnControlledPet<PetTestStub>(masterLoc, petLoc, map);
public static (PlayerMobile master, T pet) SpawnControlledPet<T>(
Point3D masterLoc, Point3D petLoc, Map map = null) where T : BaseCreature, new()
{
var map = Map.Felucca;
map ??= Map.Felucca;
var master = new PlayerMobile(World.NewMobile);
master.DefaultMobileInit();
master.MoveToWorld(masterLoc, map);
var pet = new PetTestStub();
var pet = new T();
pet.MoveToWorld(petLoc, map);
pet.SetControlMaster(master); // sets Controlled, Home=Zero, ControlOrder=Come

View file

@ -3,6 +3,7 @@ using System.Collections.Generic;
using Server;
using Server.Items;
using Server.Mobiles;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Mobiles;
@ -15,60 +16,14 @@ namespace UOContent.Tests.Mobiles;
[Collection("Sequential UOContent Tests")]
public class BaseCreatureSerializationTests : IDisposable
{
private readonly List<Mobile> _created = new();
private readonly List<Item> _createdItems = new();
private readonly MobileTestHarness _harness = new();
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
public void Dispose() => _harness.Dispose();
for (var i = 0; i < _createdItems.Count; i++)
{
_createdItems[i].Delete();
}
}
private class CreatureStub : BaseCreature
{
public CreatureStub() : base(AIType.AI_Melee) => Body = 0xC9;
public CreatureStub(Serial serial) : base(serial) => Body = 0xC9;
public DateTime SummonEndValue => SummonEnd;
// Stands in for the npc-speeds table (unconfigured in the test fixture).
public override void GetSpeeds(out double activeSpeed, out double passiveSpeed)
{
activeSpeed = 0.3;
passiveSpeed = 0.6;
}
public override void GetMoveSpeeds(out double activeMoveSpeed, out double passiveMoveSpeed)
{
activeMoveSpeed = 0.6;
passiveMoveSpeed = 1.2;
}
}
private CreatureStub NewCreature()
{
var bc = new CreatureStub();
_created.Add(bc);
return bc;
}
private TestCreature NewCreature() => _harness.NewCreature();
// ReadEntity resolves references through the world table, so the master must be registered.
private PlayerMobile NewMaster()
{
var master = new PlayerMobile(World.NewMobile);
master.DefaultMobileInit();
World.AddEntity(master);
_created.Add(master);
return master;
}
private PlayerMobile NewMaster() => _harness.NewPlayer();
private static byte[] Snapshot(Mobile m)
{
@ -80,10 +35,10 @@ public class BaseCreatureSerializationTests : IDisposable
return buffer;
}
private CreatureStub Load(byte[] buffer)
private TestCreature Load(byte[] buffer)
{
var copy = new CreatureStub(World.NewMobile);
_created.Add(copy);
var copy = new TestCreature(World.NewMobile);
_harness.Track(copy);
var reader = new BufferReader(buffer);
copy.Deserialize(reader);
@ -219,7 +174,7 @@ public class BaseCreatureSerializationTests : IDisposable
var bc = NewCreature();
var friend = NewMaster();
var wayPoint = new WayPoint();
_createdItems.Add(wayPoint);
_harness.TrackItem(wayPoint);
bc.AddPetFriend(friend);
bc.CurrentWayPoint = wayPoint;
@ -245,49 +200,20 @@ public class BaseCreatureSerializationTests : IDisposable
Assert.InRange(copy.DeleteTimeLeft, TimeSpan.FromDays(3.0) - TimeSpan.FromSeconds(5), TimeSpan.FromDays(3.0));
}
private sealed class VendorStub : BaseVendor
{
private static readonly List<SBInfo> _sbInfos = [];
public VendorStub() : base("the stub")
{
}
public VendorStub(Serial serial) : base(serial)
{
}
protected override List<SBInfo> SBInfos => _sbInfos;
public override void InitSBInfo()
{
}
public override void InitOutfit()
{
}
public override void GetSpeeds(out double activeSpeed, out double passiveSpeed)
{
activeSpeed = 0.3;
passiveSpeed = 0.6;
}
}
// BaseVendor is generated on top of the generated BaseCreature; the chain must write
// and read both sections in order with exact consumption.
[Fact]
public void GeneratedVendorChain_RoundTrips()
{
var vendor = new VendorStub();
_created.Add(vendor);
var vendor = new TestVendor();
_harness.Track(vendor);
vendor.Home = new Point3D(1500, 1600, 0);
vendor.RangeHome = 2;
var buffer = Snapshot(vendor);
var copy = new VendorStub(World.NewMobile);
_created.Add(copy);
var copy = new TestVendor(World.NewMobile);
_harness.Track(copy);
var reader = new BufferReader(buffer);
copy.Deserialize(reader);
@ -378,7 +304,7 @@ public class BaseCreatureSerializationTests : IDisposable
writer.Write(0.0); // passive move speed (v22)
}
private CreatureStub LoadLegacyV22(
private TestCreature LoadLegacyV22(
bool controlled = false,
Mobile controlMaster = null,
bool summoned = false,
@ -390,7 +316,7 @@ public class BaseCreatureSerializationTests : IDisposable
// Mobile donor produces a byte-authentic one.
var donor = new MobileStub();
donor.DefaultMobileInit();
_created.Add(donor);
_harness.Track(donor);
var writer = new BufferWriter(true);
donor.Serialize(writer);
@ -399,8 +325,8 @@ public class BaseCreatureSerializationTests : IDisposable
var buffer = new byte[writer.Position];
writer.Buffer.AsSpan(0, (int)writer.Position).CopyTo(buffer);
var copy = new CreatureStub(World.NewMobile);
_created.Add(copy);
var copy = new TestCreature(World.NewMobile);
_harness.Track(copy);
var reader = new BufferReader(buffer);
copy.Deserialize(reader);
@ -499,7 +425,7 @@ public class BaseCreatureSerializationTests : IDisposable
var donor = new MobileStub();
donor.DefaultMobileInit();
_created.Add(donor);
_harness.Track(donor);
var writer = new BufferWriter(true);
donor.Serialize(writer);

View file

@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using Server;
using Server.Mobiles;
using Server.Spells.Necromancy;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Mobiles;
@ -11,40 +11,13 @@ namespace UOContent.Tests.Mobiles;
[Collection("Sequential UOContent Tests")]
public class DeletedMasterTests : IDisposable
{
private readonly List<Mobile> _created = [];
private readonly MobileTestHarness _harness = new();
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
}
public void Dispose() => _harness.Dispose();
private sealed class Stub : BaseCreature
{
public Stub() : base(AIType.AI_Melee) => Body = 0xC9;
private TestCreature NewCreature() => _harness.NewCreature();
public Stub(Serial serial) : base(serial)
{
}
}
private Stub NewCreature()
{
var bc = new Stub();
_created.Add(bc);
return bc;
}
private PlayerMobile NewPlayer()
{
var pm = new PlayerMobile(World.NewMobile);
pm.DefaultMobileInit();
World.AddEntity(pm);
_created.Add(pm);
return pm;
}
private PlayerMobile NewPlayer() => _harness.NewPlayer();
[Fact]
public void DeletingAPlayer_ReleasesAnUnbondedPet()

View file

@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using Server;
using Server.Mobiles;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Mobiles;
@ -10,40 +10,13 @@ namespace UOContent.Tests.Mobiles;
[Collection("Sequential UOContent Tests")]
public class MasterViewsTests : IDisposable
{
private readonly List<Mobile> _created = [];
private readonly MobileTestHarness _harness = new();
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
}
public void Dispose() => _harness.Dispose();
private sealed class Stub : BaseCreature
{
public Stub() : base(AIType.AI_Melee) => Body = 0xC9;
private TestCreature NewCreature() => _harness.NewCreature();
public Stub(Serial serial) : base(serial)
{
}
}
private Stub NewCreature()
{
var bc = new Stub();
_created.Add(bc);
return bc;
}
private PlayerMobile NewPlayer()
{
var pm = new PlayerMobile(World.NewMobile);
pm.DefaultMobileInit();
World.AddEntity(pm);
_created.Add(pm);
return pm;
}
private PlayerMobile NewPlayer() => _harness.NewPlayer();
public enum Shape
{

View file

@ -9,15 +9,9 @@ namespace Server.Tests.Mobiles;
[Collection("Sequential UOContent Tests")]
public class VendorBuybackTests : IDisposable
{
private readonly List<Mobile> _created = [];
private readonly MobileTestHarness _harness = new();
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
}
public void Dispose() => _harness.Dispose();
private sealed class BandageSB : SBInfo
{
@ -30,34 +24,9 @@ public class VendorBuybackTests : IDisposable
public override List<GenericBuyInfo> BuyInfo { get; } = [];
}
private sealed class VendorStub : BaseVendor
private sealed class BandageVendor : TestVendor
{
private readonly List<SBInfo> _sbInfos = [];
public VendorStub() : base("the stub")
{
}
public VendorStub(Serial serial) : base(serial)
{
}
protected override List<SBInfo> SBInfos => _sbInfos;
public override void InitSBInfo()
{
_sbInfos.Add(new BandageSB());
}
public override void InitOutfit()
{
}
public override void GetSpeeds(out double activeSpeed, out double passiveSpeed)
{
activeSpeed = 0.3;
passiveSpeed = 0.6;
}
protected override void AddSBInfos(List<SBInfo> sbInfos) => sbInfos.Add(new BandageSB());
}
// Same sell price as BandageSB, but a buy list at the 250-entry limit so buyback capacity is 0.
@ -81,55 +50,36 @@ public class VendorBuybackTests : IDisposable
public override List<GenericBuyInfo> BuyInfo => _buyInfo;
}
private sealed class FullStockVendorStub : BaseVendor
private sealed class FullStockVendor : TestVendor
{
private readonly List<SBInfo> _sbInfos = [];
public FullStockVendorStub() : base("the stub")
{
}
protected override List<SBInfo> SBInfos => _sbInfos;
public override void InitSBInfo()
{
_sbInfos.Add(new FullStockSB());
}
public override void InitOutfit()
{
}
public override void GetSpeeds(out double activeSpeed, out double passiveSpeed)
{
activeSpeed = 0.3;
passiveSpeed = 0.6;
}
protected override void AddSBInfos(List<SBInfo> sbInfos) => sbInfos.Add(new FullStockSB());
}
private VendorStub NewVendor()
{
var vendor = new VendorStub();
_created.Add(vendor);
return vendor;
}
private BandageVendor NewVendor() => _harness.Track(new BandageVendor());
private FullStockVendorStub NewFullStockVendor()
{
var vendor = new FullStockVendorStub();
_created.Add(vendor);
return vendor;
}
private FullStockVendor NewFullStockVendor() => _harness.Track(new FullStockVendor());
private Mobile NewSeller()
{
var seller = new Mobile(World.NewMobile);
var seller = _harness.Track(new Mobile(World.NewMobile));
seller.DefaultMobileInit();
seller.AddItem(new Backpack());
_created.Add(seller);
return seller;
}
// A fresh seller offers a stack of 10 bandages and sells <paramref name="amount"/> of them.
private Bandage SellBandages(BaseVendor vendor, int amount, out Mobile seller)
{
seller = NewSeller();
var bandages = new Bandage(10);
seller.Backpack.DropItem(bandages);
Assert.True(vendor.OnSellItems(seller, [new SellItemResponse(bandages, amount)]));
return bandages;
}
private Bandage SellBandages(BaseVendor vendor, int amount) => SellBandages(vendor, amount, out _);
[Theory]
[InlineData(0.25, 1.0)] // restocked 15m ago: next boundary is the regular one
[InlineData(5.0, 6.0)] // exactly on a boundary: strictly after now
@ -160,11 +110,7 @@ public class VendorBuybackTests : IDisposable
public void PartialStackSale_SplitGoesToBuyback_SellerKeepsRemainder()
{
var vendor = NewVendor();
var seller = NewSeller();
var bandages = new Bandage(10);
seller.Backpack.DropItem(bandages);
Assert.True(vendor.OnSellItems(seller, [new SellItemResponse(bandages, 4)]));
var bandages = SellBandages(vendor, 4, out var seller);
Assert.Equal(6, bandages.Amount);
Assert.Same(seller.Backpack, bandages.Parent);
@ -181,10 +127,7 @@ public class VendorBuybackTests : IDisposable
public void Restock_PurgesBuyback()
{
var vendor = NewVendor();
var seller = NewSeller();
var bandages = new Bandage(10);
seller.Backpack.DropItem(bandages);
vendor.OnSellItems(seller, [new SellItemResponse(bandages, 10)]);
var bandages = SellBandages(vendor, 10);
Assert.Single(vendor.BuyPack.Items);
vendor.Restock();
@ -197,20 +140,14 @@ public class VendorBuybackTests : IDisposable
public void Restock_ClearsPurgeSchedule_AndASubsequentSaleRearmsIt()
{
var vendor = NewVendor();
var seller = NewSeller();
var bandages = new Bandage(10);
seller.Backpack.DropItem(bandages);
vendor.OnSellItems(seller, [new SellItemResponse(bandages, 10)]);
SellBandages(vendor, 10);
Assert.True(vendor.BuybackPurgeScheduled);
vendor.Restock();
Assert.False(vendor.BuybackPurgeScheduled);
var seller2 = NewSeller();
var moreBandages = new Bandage(10);
seller2.Backpack.DropItem(moreBandages);
vendor.OnSellItems(seller2, [new SellItemResponse(moreBandages, 10)]);
SellBandages(vendor, 10);
Assert.True(vendor.BuybackPurgeScheduled);
}
@ -219,10 +156,7 @@ public class VendorBuybackTests : IDisposable
public void Delete_CancelsBuybackPurgeTimer()
{
var vendor = NewVendor();
var seller = NewSeller();
var bandages = new Bandage(10);
seller.Backpack.DropItem(bandages);
vendor.OnSellItems(seller, [new SellItemResponse(bandages, 10)]);
SellBandages(vendor, 10);
Assert.True(vendor.BuybackPurgeScheduled);
vendor.Delete();
@ -239,7 +173,8 @@ public class VendorBuybackTests : IDisposable
var legacy = new Backpack { Layer = Layer.ShopBuy, Movable = false, Visible = false };
vendor.AddItem(legacy);
var children = new Item[20_000];
// Several children, so a delete loop that skips entries as the list shrinks would show.
var children = new Item[3];
for (var i = 0; i < children.Length; i++)
{
children[i] = new Item(0x1234);
@ -261,11 +196,7 @@ public class VendorBuybackTests : IDisposable
public void SaleWithNoBuybackCapacity_ConsumesItem_AndStillPays()
{
var vendor = NewFullStockVendor();
var seller = NewSeller();
var bandages = new Bandage(10);
seller.Backpack.DropItem(bandages);
Assert.True(vendor.OnSellItems(seller, [new SellItemResponse(bandages, 10)]));
var bandages = SellBandages(vendor, 10, out var seller);
Assert.True(bandages.Deleted);
Assert.Empty(vendor.BuyPack.Items);

View file

@ -216,7 +216,8 @@ public sealed class DesignStateDetailed : Packet
if (deflatedLength == 0)
{
Console.WriteLine("Compression error");
// An oracle that silently emits a truncated plane would make the comparison meaningless.
throw new InvalidOperationException("Compression error");
}
Write((byte)(0x20 | i));
@ -248,7 +249,8 @@ public sealed class DesignStateDetailed : Packet
if (deflatedLength == 0)
{
Console.WriteLine("Compression error");
// An oracle that silently emits a truncated plane would make the comparison meaningless.
throw new InvalidOperationException("Compression error");
}
Write((byte)(9 + i));

View file

@ -13,7 +13,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Net;
using System.Reflection;
using System.Text;
using Server.Network;
using Server.Network.Bans;
@ -21,10 +23,18 @@ using Xunit;
namespace Server.Tests.Network.Exemptions;
// Addresses come from TEST-NET-1 (192.0.2.0/24) to stay clear of the other ban test classes if xUnit runs
// them concurrently.
public class BanExemptionsTests
// ManualAllowlist is process-wide and BlocklistFilter reads it, so this runs in the sequential collection
// and puts the original snapshot back. Addresses come from TEST-NET-1 (192.0.2.0/24).
[Collection("Sequential UOContent Tests")]
public class BanExemptionsTests : IDisposable
{
private static readonly FieldInfo _snapshotField =
typeof(ManualAllowlist).GetField("_snapshot", BindingFlags.Static | BindingFlags.NonPublic);
private readonly object _savedSnapshot = _snapshotField.GetValue(null);
public void Dispose() => ManualAllowlist.LoadForTesting((BlocklistSnapshot)_savedSnapshot);
private static readonly IPAddress _listed = IPAddress.Parse("192.0.2.10");
private static readonly IPAddress _unlisted = IPAddress.Parse("192.0.2.11");

View file

@ -21,14 +21,13 @@ using Xunit;
namespace Server.Tests.Network.Bans.Blocklist;
public class BlocklistFileTests
public class BlocklistFileTests : IDisposable
{
private static string WriteTemp(string content)
{
var p = Path.Combine(Path.GetTempPath(), "bl-" + Guid.NewGuid().ToString("N") + ".txt");
File.WriteAllText(p, content);
return p;
}
private readonly TempDirectory _temp = new("bl");
public void Dispose() => _temp.Dispose();
private string WriteTemp(string content) => _temp.WriteFile("blocklist.txt", content);
[Fact]
public void Reads_header_generated_and_count()
@ -38,13 +37,12 @@ public class BlocklistFileTests
Assert.True(h.Present);
Assert.Equal("2026-07-21T09:24:23Z", h.Generated);
Assert.Equal(2, h.Count);
File.Delete(p);
}
[Fact]
public void Missing_file_reports_absent_and_loads_empty()
{
var p = Path.Combine(Path.GetTempPath(), "does-not-exist-" + Guid.NewGuid().ToString("N"));
var p = _temp.Combine("does-not-exist.txt");
Assert.False(BlocklistFile.TryReadHeader(p, out var h));
Assert.False(h.Present);
var snap = BlocklistFile.Load(p, out _, out _);
@ -70,6 +68,5 @@ public class BlocklistFileTests
Assert.Equal(0, skipped);
Assert.True(snap.IsBanned(IPAddress.Parse("2.181.183.77")));
Assert.True(snap.IsBanned(IPAddress.Parse("223.169.4.9")));
File.Delete(p);
}
}

View file

@ -20,8 +20,10 @@ using Xunit;
namespace Server.Tests.Network.Bans.Blocklist;
// No [Collection] and no static reset hook: the filter is an instance, so each test owns its own
// snapshot and promote-guard. That is the point of it no longer being a static class.
// The filter is an instance, so each test owns its own snapshot and promote-guard. Evaluate still
// consults the process-wide ManualAllowlist and LoginAllowlist, which other tests rewrite, so this
// runs in the sequential collection.
[Collection("Sequential UOContent Tests")]
public class BlocklistFilterTests
{
private static BlocklistFilter WithList(string list, bool reportHits = true, long suppressionMs = 5000)

View file

@ -218,14 +218,18 @@ public class CrowdSecReporterTests
/// <summary>
/// The drain task must track the loop's lifetime, not just its first await — a ValueTask-returning
/// drain loop passed to Task.Run yields a Task&lt;ValueTask&gt; that completes immediately, which makes
/// Stop()'s drain-exited handshake a no-op. With an empty queue the loop parks on WaitToReadAsync,
/// so a correctly unwrapped task cannot win this race; a slow pool only under-detects.
/// drain loop passed to Task.Run yields a Task&lt;ValueTask&gt; that completes at the first await
/// that suspends, which makes Stop()'s drain-exited handshake a no-op. The flush delay always
/// suspends before the first post, so once the client sees a post a wrapped task is already done.
/// </summary>
[Fact]
public async Task Start_DrainTaskSpansLoopLifetime_NotJustTheFirstAwait()
{
var reporter = new CrowdSecReporter(new NullAlertClient(), Settings());
var settings = Settings();
settings.FlushInterval = TimeSpan.FromMilliseconds(1);
var client = new SignalingAlertClient();
var reporter = new CrowdSecReporter(client, settings);
using var cts = new CancellationTokenSource();
reporter.Start(cts.Token);
@ -233,14 +237,32 @@ public class CrowdSecReporterTests
var drain = reporter.DrainTaskForTesting;
Assert.NotNull(drain);
var first = await Task.WhenAny(drain, Task.Delay(TimeSpan.FromMilliseconds(500)));
Assert.False(ReferenceEquals(first, drain), "drain task completed while the loop was still running");
reporter.Report(IPAddress.Parse("9.9.9.9"), TimeSpan.FromHours(1), "rate-limit");
await client.Posted.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.False(drain.IsCompleted, "drain task completed while the loop was still running");
reporter.Stop();
Assert.True(drain.IsCompleted, "Stop() returned before the drain loop exited");
}
private sealed class SignalingAlertClient : ICrowdSecAlertClient
{
public TaskCompletionSource Posted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ValueTask PostAlertsAsync(IReadOnlyList<CrowdSecAlert> alerts, CancellationToken token)
{
Posted.TrySetResult();
return ValueTask.CompletedTask;
}
public ValueTask DeleteDecisionsAsync(string origin, IPAddress ip, CancellationToken token) =>
ValueTask.CompletedTask;
public void Dispose() { }
}
private sealed class NullAlertClient : ICrowdSecAlertClient
{
public ValueTask PostAlertsAsync(IReadOnlyList<CrowdSecAlert> alerts, CancellationToken token) =>

View file

@ -21,8 +21,11 @@ using Xunit;
namespace Server.Tests.Network.Firewall;
[Collection("Sequential UOContent Tests")]
public class FirewallPersistenceTests
public class FirewallPersistenceTests : IDisposable
{
// The test host never configures the firewall, so empty is the state every other test expects.
public void Dispose() => Server.Network.Firewall.ResetForTesting();
[Fact]
public void ToSettings_RoundTrips_PermanentAndTtl()
{

View file

@ -21,8 +21,11 @@ using Xunit;
namespace Server.Tests.Network.Firewall;
[Collection("Sequential UOContent Tests")]
public class FirewallTests
public class FirewallTests : IDisposable
{
// The test host never configures the firewall, so empty is the state every other test expects.
public void Dispose() => Server.Network.Firewall.ResetForTesting();
private static IPAddress Ip(string s) => IPAddress.Parse(s);
[Fact]

View file

@ -13,17 +13,74 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using Server.Network;
using Server.Network.Bans;
using Xunit;
namespace Server.Tests.Network.LoginAllowlists;
// The list is static, so every test resets it first. Addresses come from TEST-NET-3 (203.0.113.0/24) so they
// cannot collide with the blocklist tests if xUnit runs the two classes at the same time.
public class LoginAllowlistTests
// The list is static and the login path and BlocklistFilter both read it, so every test resets it first,
// the class runs in the sequential collection, and Dispose puts the original state back. Addresses come
// from TEST-NET-3 (203.0.113.0/24).
[Collection("Sequential UOContent Tests")]
public class LoginAllowlistTests : IDisposable
{
private readonly List<(FieldInfo Field, object Value, DictionaryEntry[] Entries)> _saved = [];
public LoginAllowlistTests()
{
var fields = typeof(LoginAllowlist).GetFields(BindingFlags.Static | BindingFlags.NonPublic);
for (var i = 0; i < fields.Length; i++)
{
var field = fields[i];
if (field.IsLiteral)
{
continue;
}
var value = field.GetValue(null);
// Readonly tables cannot be reassigned, so their contents are copied and refilled instead.
DictionaryEntry[] entries = null;
if (field.IsInitOnly && value is IDictionary table)
{
entries = new DictionaryEntry[table.Count];
table.CopyTo(entries, 0);
}
else if (field.IsInitOnly)
{
continue;
}
_saved.Add((field, value, entries));
}
}
public void Dispose()
{
for (var i = 0; i < _saved.Count; i++)
{
var (field, value, entries) = _saved[i];
if (entries == null)
{
field.SetValue(null, value);
continue;
}
var table = (IDictionary)value;
table.Clear();
for (var j = 0; j < entries.Length; j++)
{
table.Add(entries[j].Key, entries[j].Value);
}
}
}
private const long Ttl = 90 * 24 * 60 * 60; // 90 days, the shipped default
private const long Window = 3600;
private const long Now = 1_800_000_000;

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Net;
using Server.Accounting;
using Server.Accounting.Security;
@ -22,14 +23,43 @@ public class AuthIdTests : IDisposable
IncomingAccountPackets.ClearAuthIdWindow();
}
// The constructor registers each account in the process-wide Accounts table.
private readonly List<Account> _created = [];
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
IncomingAccountPackets.ClearAuthIdWindow();
AccountSecurity.CurrentAlgorithm = _originalAlgorithm;
}
private static IAccount CreateAccount(string username) =>
Accounts.GetAccount(username) ?? new Account(username, "hunter2");
// Auth ids never read the password, so these accounts skip the Argon2 cost.
private IAccount CreateAccount(string username)
{
AccountSecurity.CurrentAlgorithm = PasswordProtectionAlgorithm.SHA2;
try
{
return TrackNewAccount(username);
}
finally
{
AccountSecurity.CurrentAlgorithm = PasswordProtectionAlgorithm.Argon2;
}
}
// The game-login tests run the real password check, so they keep the configured algorithm.
private IAccount CreateArgon2Account(string username) => TrackNewAccount(username);
private Account TrackNewAccount(string username)
{
var account = new Account(username, "hunter2");
_created.Add(account);
return account;
}
private static int Register(IAccount account, IPAddress address) =>
IncomingAccountPackets.RegisterAuthId(account, address, new ClientVersion(7, 0, 0, 0));
@ -336,7 +366,7 @@ public class AuthIdTests : IDisposable
[Fact]
public void PreAuthenticatedGameLogin_SkipsThePasswordCheck()
{
var account = CreateAccount("authid-preauth-user");
var account = CreateArgon2Account("authid-preauth-user");
using var ns = PacketTestUtilities.CreateTestNetState();
// A wrong password is accepted only because the auth id already vouched for the account.
@ -349,7 +379,7 @@ public class AuthIdTests : IDisposable
[Fact]
public void GameLoginWithoutPreAuthentication_StillChecksThePassword()
{
var account = CreateAccount("authid-nopreauth-user");
var account = CreateArgon2Account("authid-nopreauth-user");
using var ns = PacketTestUtilities.CreateTestNetState();
var wrong = new GameServer.GameLoginEventArgs(ns, account.Username, "wrong-password", false);

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Server.Saves;
using Xunit;
@ -9,16 +10,32 @@ namespace Server.Tests;
[Collection("Sequential UOContent Tests")]
public class ArchiveJournalTests : IDisposable
{
private static readonly FieldInfo _dataField =
typeof(ArchiveJournal).GetField("_data", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly FieldInfo _journalPathField =
typeof(ArchiveJournal).GetField("_journalPath", BindingFlags.Static | BindingFlags.NonPublic);
private readonly object _savedData;
private readonly object _savedJournalPath;
private readonly string _testDir;
public ArchiveJournalTests()
{
// Configure() repoints the process-wide journal at the temp dir; restore it so no later
// caller writes into a deleted directory.
_savedData = _dataField.GetValue(null);
_savedJournalPath = _journalPathField.GetValue(null);
_testDir = Path.Combine(Path.GetTempPath(), $"modernuo-journal-test-{Guid.NewGuid():N}");
Directory.CreateDirectory(_testDir);
}
public void Dispose()
{
_dataField.SetValue(null, _savedData);
_journalPathField.SetValue(null, _savedJournalPath);
if (Directory.Exists(_testDir))
{
Directory.Delete(_testDir, true);