test: remove trivial, duplicate and content-value tests (#2721)

## Summary
Many tests proved a specific change when it landed but don't need to run on every CI build forever. This removes **202 test methods and 9 files: 313 test cases, 2,247 → 1,934**. UOContent.Tests drops from about 14s to about 5s locally.

Removed:
- **Tautologies.** Asserting a constant, a constructor readback or a trivial getter, or testing BCL behavior.
- **Exact duplicates** of a surviving test on the same code path.
- **Obsolete regressions** whose failure can no longer be expressed.
- **Game-content values** shard owners customize (era drop rates, loot and skill tables, single-creature tuning). Each customization would otherwise force a test fix.

## How it was decided
1. Every test was classified, with a reason, by a per-shard sweep over all 287 test files.
2. Each proposed deletion was then checked by a second, adversarial reviewer against the surviving tests and the production code.
3. Anything that was the only coverage of a separate code path was **kept**, even where it looked like a duplicate. Examples: the unsigned `SpanReader`/`SpanWriter` methods, the at-location versus bounds enumerators, null-map enumerables, the security filters, archive-journal state transitions. About 130 proposed deletions were rejected this way.

Whole files removed:
- `FishingTests`, apart from 3 tests: the map-edge scan, serpent cleanup, and SOS chest consumption. The SOS test now stops at the first chest instead of measuring a catch rate. The multi-million-cast rate simulations are gone.
- `LordOaksTests` and `MeerEnragedTests` (single-creature tests).
- `AutoArchiveHelperTests`, `JsonDiscoverableTypeAttributeTests`, `DecimalSerializationTests` and `EnumConversionTests` (tautologies, or tests of their own local helpers).
- `NetworkStatsTests`.
- `MigratedDataLoadTests` (a subset of `AllSpawnFilesLoadTests`).
- `SpawnerFixtureCapture`: a capture tool, not a test, and its `version == 12` assert can no longer pass. The `.bin` fixtures it produced stay.

## Tests
- Server.Tests: 811 pass.
- UOContent.Tests: 1,123 pass.

A follow-up PR, stacked on this one, fixes how the remaining tests behave: shared state, CI-vacuous tests, harness duplication.
This commit is contained in:
Kamron Batman 2026-10-18 20:08:19 -07:00 • committed by GitHub
parent 078be52777
commit 9a25054809
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
89 changed files with 11 additions and 4603 deletions

View file

@ -20,15 +20,4 @@ public class AccountHandlerTests
{
Assert.Equal(expected, AccountHandler.IsValidUsername(username));
}
[Theory]
[InlineData("", false)] // Empty password
[InlineData("ValidPass123!", true)] // Standard Password
[InlineData(" ", true)] // Single space
[InlineData("ValidPass!@#", true)] // Valid special characters
[InlineData("ValidPassWithLength1234567890", true)] // Long valid password
public void IsValidPassword_ValidatesCorrectly(string password, bool expected)
{
Assert.Equal(expected, AccountHandler.IsValidPassword(password));
}
}

View file

@ -152,18 +152,6 @@ public class PasswordWorkerTests : IDisposable
Assert.Null(outcome.Hash);
}
[Fact]
public void AppliesAWrite()
{
var account = CreateAccount("offloop-apply-user");
var upgraded = Argon2PasswordProtection.Instance.EncryptPassword(Password);
account.ApplyPasswordWrite(upgraded, PasswordProtectionAlgorithm.Argon2);
Assert.Equal(upgraded, account.Password);
Assert.True(account.CheckPassword(Password));
}
/// <summary>
/// Writes apply in dispatch order, which is what makes a guard unnecessary: dispatch is on the
/// loop, one worker drains FIFO, and results return through the loop context in that same order.
@ -217,13 +205,4 @@ public class PasswordWorkerTests : IDisposable
AccountSecurity.CurrentAlgorithm = PasswordProtectionAlgorithm.Argon2;
Assert.Equal(Password, account.GetRehashPhrase(Password));
}
[Fact]
public void UsesTheBarePasswordForArgon2Accounts()
{
var account = CreateAccount("offloop-phrase-argon2-user");
Assert.Equal(Password, account.GetVerifyPhrase(Password));
Assert.Equal(Password, account.GetRehashPhrase(Password));
}
}

View file

@ -150,13 +150,4 @@ public class PasswordProtectionTest
{
Assert.True(Argon2PasswordProtection.Instance.NeedsRehash(hash));
}
[Fact]
public void NonArgon2Protections_NeverNeedRehash()
{
Assert.False(PBKDF2PasswordProtection.Instance.NeedsRehash("anything"));
Assert.False(HashAlgorithmPasswordProtection.SHA2Instance.NeedsRehash("anything"));
Assert.False(HashAlgorithmPasswordProtection.SHA1Instance.NeedsRehash("anything"));
Assert.False(HashAlgorithmPasswordProtection.MD5Instance.NeedsRehash("anything"));
}
}

View file

@ -109,19 +109,4 @@ public class ChainedBindingSortTests : IDisposable
}
// An unchained binding never had the problem and must keep working untouched.
[Fact]
public void SortingOnAPlainBindingIsUnchanged()
{
var low = Teleporter(null);
low.Hue = 1;
var high = Teleporter(null);
high.Hue = 2;
var comparer = Sorter("Hue");
Assert.True(comparer.Compare(low, high) < 0);
Assert.True(comparer.Compare(high, low) > 0);
Assert.Equal(0, comparer.Compare(low, low));
}
}

View file

@ -79,25 +79,4 @@ public class EmitterRobustnessTests
Assert.True(Check("Big", ComparisonOperator.Greater, "2147483647"));
Assert.True(Check("Huge", ComparisonOperator.Greater, "9223372036854775807"));
}
[Fact]
public void EmittedAssembliesAreCollectible()
{
var prop = new Property("Tiny");
prop.BindTo(typeof(Subject), PropertyAccess.Read);
var compiled = ConditionalCompiler.Build(
typeof(Subject),
[TypeCondition.Default, new ComparisonCondition(prop, false, ComparisonOperator.Equal, "5")]
).Compile();
var method = compiled.Method;
Assert.True(
method.IsCollectible,
"The conditional compiler compiles one delegate per command invocation; code that is "
+ $"not collectible ({method.GetType().Name} in {method.Module}) can never be unloaded, "
+ "so every [global where would grow the process for good."
);
}
}

View file

@ -253,26 +253,6 @@ public class RecurrencePatternTests
}
}
[Fact]
public void MonthlyOrdinalRecurrencePattern_DST_FallBack_HandlesAmbiguousTimeCorrectly()
{
// This tests specifically the DST fall back case that was failing
var tz = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
var pattern = new MonthlyOrdinalRecurrencePattern(OrdinalDayOccurrence.First, DayOfWeek.Sunday);
// November 3, 2024 at 1:30 AM - First Sunday, falls on DST transition
var beforeDate = new DateTime(2024, 11, 2, 12, 0, 0);
var beforeUtc = beforeDate.LocalToUtc(tz);
var timeOnly = new TimeOnly(1, 30);
// Act
var result = pattern.GetNextOccurrence(beforeUtc, timeOnly, tz);
// Assert - should be November 3, 2024 at 1:30 AM
var resultLocal = TimeZoneInfo.ConvertTimeFromUtc(result, tz);
Assert.Equal(new DateTime(2024, 11, 3, 1, 30, 0), resultLocal);
}
[Fact]
public void MonthlyRecurrence_MonthWithoutDay_SkipsToNextValidMonth()
{

View file

@ -67,22 +67,6 @@ public class FactionRankTests
Assert.True(top.Rank.Rank > bottom.Rank.Rank);
}
[Fact]
public void ReadingRank_IsStableAndSideEffectFree()
{
var faction = NewFaction();
var owner = new List<PlayerState>();
var state = AddMember(faction, owner);
faction.ZeroRankOffset = 1;
state.RankIndex = 0;
var first = state.Rank;
var second = state.Rank;
Assert.Same(first, second);
}
[Fact]
public void RankIndexOutOfSyncWithZeroRankOffset_StillResolvesARank()
{

View file

@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using Server;
using Server.Engines.Harvest;
using Server.Items;
using Server.Mobiles;
using Server.Random;
using Server.Targeting;
using Server.Tests;
using Xunit;
@ -14,261 +12,9 @@ namespace UOContent.Tests;
[Collection("Sequential UOContent Tests")]
public class FishingTests
{
private const int Casts = 100_000;
// On land in Britain, so a cast there never counts as deep water.
private static readonly Point3D _shallow = new(1434, 1699, 0);
// Open sea with no land within 30 tiles: deep water once the client's map is loaded.
private static readonly Point3D _deep = new(1840, 1760, -5);
private static readonly Type[] _magicFish =
[typeof(PrizedFish), typeof(WondrousFish), typeof(TrulyRareFish), typeof(PeculiarFish)];
private static readonly Type[] _footwear = [typeof(Boots), typeof(Shoes), typeof(Sandals), typeof(ThighBoots)];
[Theory]
[InlineData(Expansion.None, 50.0, 0.0, 0.0)]
[InlineData(Expansion.T2A, 0.0, 0.0, 0.75)]
[InlineData(Expansion.T2A, 50.0, 0.0, 0.3877)]
[InlineData(Expansion.T2A, 100.0, 0.025, 0.0247)]
[InlineData(Expansion.UOTD, 80.0, 0.02, 0.1669)]
[InlineData(Expansion.LBR, 0.0, 0.0, 0.75)]
[InlineData(Expansion.LBR, 50.0, 0.025, 0.4519)]
[InlineData(Expansion.AOS, 100.0, 0.05, 0.095)]
[InlineData(Expansion.SA, 50.0, 0.025, 0.4519)]
[InlineData(Expansion.HS, 50.0, 0.0, 0.4635)]
[InlineData(Expansion.HS, 120.0, 0.06, 0.047)]
[InlineData(Expansion.EJ, 120.0, 0.06, 0.047)]
public void MutateType_MagicFishAndFootwear_FollowTheEra(
Expansion expansion, double skill, double magicFishRate, double footwearRate
)
{
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
var fisher = new PlayerMobile(World.NewMobile);
try
{
Core.Expansion = expansion;
BuiltInRng.Generator = new System.Random(1);
fisher.DefaultMobileInit();
fisher.Skills.Fishing.Base = skill;
Assert.Equal(skill, fisher.Skills.Fishing.Value);
Assert.False(SpecialFishingNet.FullValidation(Map.Felucca, _shallow.X, _shallow.Y));
var definition = Fishing.System.Definitions[0];
var magicFish = 0;
var footwear = 0;
for (var i = 0; i < Casts; i++)
{
var type = Fishing.System.MutateType(typeof(Fish), fisher, null, definition, Map.Felucca, _shallow, null);
if (Array.IndexOf(_magicFish, type) >= 0)
{
magicFish++;
}
else if (Array.IndexOf(_footwear, type) >= 0)
{
footwear++;
}
}
AssertRate(magicFishRate, magicFish);
AssertRate(footwearRate, footwear);
}
finally
{
fisher.Delete();
BuiltInRng.Generator = previousGenerator;
Core.Expansion = previousExpansion;
}
}
[Fact]
public void Leviathan_CarriesItsTreasureMapAQuarterOfTheTime()
{
var leviathan = new Leviathan();
var serpent = new SeaSerpent();
try
{
Assert.Equal(0.25, leviathan.TreasureMapChance);
Assert.Equal(TreasureMap.LootChance, serpent.TreasureMapChance);
}
finally
{
leviathan.Delete();
serpent.Delete();
}
}
[Theory]
[InlineData(Expansion.None, 0.0)]
[InlineData(Expansion.T2A, 100.0)]
[InlineData(Expansion.UOR, 50.0)]
[InlineData(Expansion.LBR, 0.0)]
[InlineData(Expansion.EJ, 120.0)]
public void MutateType_NeverComesBackEmpty(Expansion expansion, double skill)
{
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
var fisher = new PlayerMobile(World.NewMobile);
try
{
Core.Expansion = expansion;
BuiltInRng.Generator = new System.Random(1);
fisher.DefaultMobileInit();
fisher.Skills.Fishing.Base = skill;
var definition = Fishing.System.Definitions[0];
for (var i = 0; i < Casts; i++)
{
var type = Fishing.System.MutateType(typeof(Fish), fisher, null, definition, Map.Felucca, _shallow, null);
Assert.NotNull(type);
}
}
finally
{
fisher.Delete();
BuiltInRng.Generator = previousGenerator;
Core.Expansion = previousExpansion;
}
}
[SkippableTheory]
[InlineData(Expansion.T2A, 100.0, 0.005, 0.004975)]
[InlineData(Expansion.UOTD, 100.0, 0.00495, 0.004925)]
[InlineData(Expansion.LBR, 95.0, 0.0062, 0.0)]
[InlineData(Expansion.LBR, 100.0, 0.00825, 0.01309)]
[InlineData(Expansion.HS, 120.0, 0.016335, 0.0257)]
[InlineData(Expansion.EJ, 120.0, 0.016335, 0.0257)]
public void MutateType_DeepWaterMapsAndBottles_FollowTheEra(
Expansion expansion, double skill, double mapRate, double bottleRate
)
{
TileDataRequirement.SkipIfMissing();
Assert.True(SpecialFishingNet.FullValidation(Map.Felucca, _deep.X, _deep.Y));
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
var fisher = new PlayerMobile(World.NewMobile);
try
{
Core.Expansion = expansion;
BuiltInRng.Generator = new System.Random(1);
fisher.DefaultMobileInit();
fisher.Skills.Fishing.Base = skill;
var definition = Fishing.System.Definitions[0];
var maps = 0;
var bottles = 0;
for (var i = 0; i < Casts; i++)
{
var type = Fishing.System.MutateType(typeof(Fish), fisher, null, definition, Map.Felucca, _deep, null);
if (type == typeof(TreasureMap))
{
maps++;
}
else if (type == typeof(MessageInABottle))
{
bottles++;
}
}
AssertRate(mapRate, maps);
AssertRate(bottleRate, bottles);
}
finally
{
fisher.Delete();
BuiltInRng.Generator = previousGenerator;
Core.Expansion = previousExpansion;
}
}
[SkippableTheory]
[InlineData(Expansion.T2A, true, 0.0, 100.0)]
[InlineData(Expansion.UOR, false, 0.0, 100.0)]
[InlineData(Expansion.UOR, true, 65.0, 115.0)]
[InlineData(Expansion.EJ, true, 65.0, 115.0)]
public void MutateResource_DeepWaterIsHarderFromUOR(Expansion expansion, bool deep, double minSkill, double maxSkill)
{
if (deep)
{
TileDataRequirement.SkipIfMissing();
Assert.True(SpecialFishingNet.FullValidation(Map.Felucca, _deep.X, _deep.Y));
}
var previousExpansion = Core.Expansion;
var fisher = new PlayerMobile(World.NewMobile);
try
{
Core.Expansion = expansion;
fisher.DefaultMobileInit();
var definition = Fishing.System.Definitions[0];
var vein = definition.Veins[0];
var resource = Fishing.System.MutateResource(
fisher, null, definition, Map.Felucca, deep ? _deep : _shallow, vein, vein.PrimaryResource, null
);
Assert.Equal(minSkill, resource.MinSkill);
Assert.Equal(maxSkill, resource.MaxSkill);
}
finally
{
fisher.Delete();
Core.Expansion = previousExpansion;
}
}
[Theory]
[InlineData(Expansion.T2A, 0.0)]
[InlineData(Expansion.UOTD, 0.0)]
[InlineData(Expansion.LBR, 0.1)]
[InlineData(Expansion.EJ, 0.1)]
public void SpecialFishingNet_IsColoredOneTimeInTenFromLBR(Expansion expansion, double coloredRate)
{
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
try
{
Core.Expansion = expansion;
BuiltInRng.Generator = new System.Random(1);
var colored = 0;
for (var i = 0; i < Casts; i++)
{
var net = new SpecialFishingNet();
if (net.Hue != 0x8A0)
{
colored++;
}
net.Delete();
}
AssertRate(coloredRate, colored);
}
finally
{
BuiltInRng.Generator = previousGenerator;
Core.Expansion = previousExpansion;
}
}
[SkippableTheory]
[InlineData(1840, 1760, true)] // land 115 tiles away
[InlineData(1660, 1760, true)] // land 14 tiles away
@ -284,72 +30,6 @@ public class FishingTests
Assert.Equal(deep, SpecialFishingNet.FullValidation(Map.Felucca, x, y));
}
[SkippableFact]
public void SOS_FindLocation_PicksDeepWater()
{
TileDataRequirement.SkipIfMissing();
var previousGenerator = BuiltInRng.Generator;
try
{
BuiltInRng.Generator = new System.Random(1);
for (var i = 0; i < 100; i++)
{
var location = SOS.FindLocation(Map.Felucca);
Assert.NotEqual(Point3D.Zero, location);
Assert.True(SpecialFishingNet.FullValidation(Map.Felucca, location.X, location.Y));
}
}
finally
{
BuiltInRng.Generator = previousGenerator;
}
}
[Fact]
public void Give_SurfacesASerpentThatAttacksAndIsADeepSeaSerpentOneTimeInTen()
{
const int serpents = 2_000;
var previousGenerator = BuiltInRng.Generator;
var fisher = new PlayerMobile();
try
{
BuiltInRng.Generator = new System.Random(1);
fisher.MoveToWorld(_deep, Map.Felucca);
var deepSeaSerpents = 0;
for (var i = 0; i < serpents; i++)
{
var bottle = new MessageInABottle(Map.Felucca);
Assert.True(Fishing.System.Give(fisher, bottle, false));
var serpent = Assert.IsAssignableFrom<BaseCreature>(bottle.RootParent);
Assert.Same(fisher, serpent.Combatant);
if (serpent is DeepSeaSerpent)
{
deepSeaSerpents++;
}
serpent.Delete();
}
AssertRate(0.1, deepSeaSerpents, serpents);
}
finally
{
fisher.Delete();
BuiltInRng.Generator = previousGenerator;
}
}
[Theory]
[InlineData(null, false)]
[InlineData(2.5, false)]
@ -403,106 +83,39 @@ public class FishingTests
}
}
[SkippableTheory]
[InlineData(Expansion.None, 100.0, true, 0.0)]
[InlineData(Expansion.T2A, 79.9, true, 0.0)]
[InlineData(Expansion.T2A, 80.0, true, 0.01)]
[InlineData(Expansion.T2A, 100.0, false, 0.0)]
[InlineData(Expansion.EJ, 120.0, true, 0.01)]
public void OnHarvestFinished_SurfacesAnEmptySerpentOneCastInAHundred(
Expansion expansion, double skill, bool deep, double serpentRate
)
[Fact]
public void Construct_SOSChestCatchConsumesTheSOS()
{
TileDataRequirement.SkipIfMissing();
Assert.True(SpecialFishingNet.FullValidation(Map.Felucca, _deep.X, _deep.Y));
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
var fisher = new PlayerMobile();
try
{
Core.Expansion = expansion;
Core.Expansion = Expansion.UOR;
BuiltInRng.Generator = new System.Random(1);
fisher.Skills.Fishing.Base = skill;
fisher.MoveToWorld(_deep, Map.Felucca);
var definition = Fishing.System.Definitions[0];
var target = new LandTarget(deep ? _deep : _shallow, Map.Felucca);
var surfaced = new List<BaseCreature>();
var serpents = 0;
for (var i = 0; i < Casts; i++)
{
Fishing.System.OnHarvestFinished(fisher, null, definition, null, null, null, target);
foreach (var serpent in Map.Felucca.GetMobilesInRange<BaseCreature>(fisher.Location, 10))
{
surfaced.Add(serpent);
}
serpents += surfaced.Count;
foreach (var serpent in surfaced)
{
serpent.Delete();
}
surfaced.Clear();
}
AssertRate(serpentRate, serpents);
}
finally
{
fisher.Delete();
BuiltInRng.Generator = previousGenerator;
Core.Expansion = previousExpansion;
}
}
[Theory]
[InlineData(Expansion.T2A, 0.0)]
[InlineData(Expansion.UOR, 65.0)]
[InlineData(Expansion.EJ, 120.0)]
public void Construct_BringsUpTheSOSChestOneCatchInFour(Expansion expansion, double skill)
{
const int casts = 2_000;
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
var fisher = new PlayerMobile();
try
{
Core.Expansion = expansion;
BuiltInRng.Generator = new System.Random(1);
fisher.Skills.Fishing.Base = skill;
fisher.Skills.Fishing.Base = 65.0;
fisher.AddItem(new Backpack());
fisher.MoveToWorld(_deep, Map.Felucca);
var sos = AddSOS(fisher);
var chests = 0;
for (var i = 0; i < casts; i++)
for (var i = 0; i < 200; i++)
{
var item = Fishing.System.Construct(typeof(Fish), fisher);
var isChest = item is WoodenChest or MetalGoldenChest;
item.Delete();
if (item is WoodenChest or MetalGoldenChest)
if (isChest)
{
chests++;
Assert.True(sos.Deleted);
sos = AddSOS(fisher);
}
else
{
Assert.True(Assert.IsAssignableFrom<IShipwreckedItem>(item).IsShipwreckedItem);
return;
}
item.Delete();
Assert.False(sos.Deleted);
}
AssertRate(0.25, chests, casts);
Assert.Fail("No SOS chest surfaced in 200 casts");
}
finally
{
@ -512,283 +125,6 @@ public class FishingTests
}
}
[Theory]
[InlineData(Expansion.T2A, 0.0, true)]
[InlineData(Expansion.UOR, 64.9, false)]
[InlineData(Expansion.UOR, 65.0, true)]
[InlineData(Expansion.EJ, 64.9, false)]
public void SOS_Needs65SkillFromUOR(Expansion expansion, double skill, bool recovers)
{
var previousExpansion = Core.Expansion;
var definition = Fishing.System.Definitions[0];
var fisher = new PlayerMobile();
Item item = null;
try
{
Core.Expansion = expansion;
fisher.Skills.Fishing.Base = skill;
fisher.AddItem(new Backpack());
fisher.MoveToWorld(_deep, Map.Felucca);
AddSOS(fisher);
// With no fish left, only an SOS that works lets the cast go on.
var bank = definition.GetBank(Map.Felucca, _deep.X, _deep.Y);
bank.Consume(bank.Current, fisher);
Assert.Equal(recovers, Fishing.System.CheckResources(fisher, null, definition, Map.Felucca, _deep, false));
item = Fishing.System.Construct(typeof(Fish), fisher);
Assert.Equal(recovers, item is not Fish);
}
finally
{
item?.Delete();
fisher.Delete();
definition.Banks.GetValueOrDefault(Map.Felucca)
?.Remove(new Point2D(_deep.X / definition.BankWidth, _deep.Y / definition.BankHeight));
Core.Expansion = previousExpansion;
}
}
[Fact]
public void Construct_KeepsTheWhitePearlAtAnSOSSpot()
{
var previousExpansion = Core.Expansion;
var fisher = new PlayerMobile();
try
{
Core.Expansion = Expansion.ML;
fisher.Skills.Fishing.Base = 100.0;
fisher.AddItem(new Backpack());
fisher.MoveToWorld(_deep, Map.Felucca);
var sos = AddSOS(fisher);
for (var i = 0; i < 100; i++)
{
var item = Fishing.System.Construct(typeof(WhitePearl), fisher);
Assert.IsType<WhitePearl>(item);
item.Delete();
}
Assert.False(sos.Deleted);
}
finally
{
fisher.Delete();
Core.Expansion = previousExpansion;
}
}
[Theory]
[InlineData(Expansion.None, false)]
[InlineData(Expansion.T2A, true)]
[InlineData(Expansion.AOS, true)]
[InlineData(Expansion.ML, true)]
public void OnHarvestStartedAndFinished_RevealAHiddenFishermanFromT2A(Expansion expansion, bool reveals)
{
Core._tickCount = 0;
Timer.Init(0);
var previousExpansion = Core.Expansion;
var previousNow = Core._now;
var fisher = new PlayerMobile();
try
{
Core.Expansion = expansion;
fisher.MoveToWorld(_deep, Map.Felucca);
var definition = Fishing.System.Definitions[0];
var target = new LandTarget(_deep, Map.Felucca);
fisher.Hidden = true;
Fishing.System.OnHarvestStarted(fisher, null, definition, target);
Advance(TimeSpan.FromSeconds(2.0));
Assert.Equal(!reveals, fisher.Hidden);
fisher.Hidden = true;
Fishing.System.OnHarvestFinished(fisher, null, definition, null, null, null, target);
Assert.Equal(!reveals, fisher.Hidden);
}
finally
{
fisher.Delete();
Core._now = previousNow;
Core.Expansion = previousExpansion;
}
}
[Theory]
[InlineData(Expansion.UOR, true)]
[InlineData(Expansion.AOS, true)]
[InlineData(Expansion.SE, false)]
public void BigFish_WeighsAHundredStonesBeforeSE(Expansion expansion, bool weighsAHundred)
{
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
var weights = new HashSet<int>();
try
{
Core.Expansion = expansion;
BuiltInRng.Generator = new System.Random(1);
for (var i = 0; i < 100; i++)
{
var fish = new BigFish();
weights.Add((int)fish.Weight);
fish.Delete();
}
}
finally
{
BuiltInRng.Generator = previousGenerator;
Core.Expansion = previousExpansion;
}
Assert.All(weights, weight => Assert.InRange(weight, 3, 200));
Assert.Equal(weighsAHundred, weights.SetEquals([100]));
}
[Theory]
[InlineData(Expansion.AOS, 100, 25)]
[InlineData(Expansion.AOS, 12, 4)]
[InlineData(Expansion.SE, 100, 20)]
[InlineData(Expansion.SE, 200, 40)]
[InlineData(Expansion.SE, 12, 4)]
public void BigFish_GivesASteakPerFiveStonesFromSE(Expansion expansion, int weight, int steaks)
{
var previousExpansion = Core.Expansion;
var fisher = new PlayerMobile();
try
{
Core.Expansion = expansion;
fisher.AddItem(new Backpack());
var fish = new BigFish { Weight = weight };
fisher.Backpack.DropItem(fish);
fish.Carve(fisher, null);
Assert.True(fish.Deleted);
Assert.Equal(steaks, fisher.Backpack.FindItemByType<RawFishSteak>()?.Amount);
}
finally
{
fisher.Delete();
Core.Expansion = previousExpansion;
}
}
[Theory]
[InlineData(Expansion.AOS, 100.0, 0.0)]
[InlineData(Expansion.SE, 99.9, 0.0)]
[InlineData(Expansion.SE, 100.0, 0.25)]
public void Leviathan_GivesAGMNetThrowerAnArtifactOneTimeInFourFromSE(Expansion expansion, double skill, double rate)
{
const int leviathans = 400;
var previousExpansion = Core.Expansion;
var previousGenerator = BuiltInRng.Generator;
var fisher = new PlayerMobile();
try
{
Core.Expansion = expansion;
BuiltInRng.Generator = new System.Random(1);
fisher.Skills.Fishing.Base = skill;
fisher.AddItem(new Backpack());
fisher.MoveToWorld(_deep, Map.Felucca);
var pack = fisher.Backpack;
var artifacts = 0;
// Nobody damages it, so only the net thrower's own roll can give an artifact.
for (var i = 0; i < leviathans; i++)
{
var leviathan = new Leviathan(fisher);
leviathan.MoveToWorld(_deep, Map.Felucca);
leviathan.Kill();
artifacts += pack.Items.Count;
for (var j = pack.Items.Count - 1; j >= 0; j--)
{
pack.Items[j].Delete();
}
leviathan.Corpse?.Delete();
leviathan.Delete();
}
AssertRate(rate, artifacts, leviathans);
}
finally
{
fisher.Delete();
BuiltInRng.Generator = previousGenerator;
Core.Expansion = previousExpansion;
}
}
[Theory]
[InlineData(Expansion.AOS, 5, 60)]
[InlineData(Expansion.SE, 1, 12)]
[InlineData(Expansion.EJ, 1, 12)]
public void MagicFish_GiveAPointFor12SecondsFromSE(Expansion expansion, int bonus, int seconds)
{
Core._tickCount = 0;
Timer.Init(0);
var previousExpansion = Core.Expansion;
var previousNow = Core._now;
var fisher = new PlayerMobile();
BaseMagicFish[] fish = [new PrizedFish(), new WondrousFish(), new TrulyRareFish()];
try
{
Core.Expansion = expansion;
foreach (var magicFish in fish)
{
Assert.True(magicFish.Apply(fisher));
Assert.Equal(bonus, fisher.GetStatOffset(magicFish.Type));
}
Advance(TimeSpan.FromSeconds(seconds - 1));
Assert.All(fish, magicFish => Assert.Equal(bonus, fisher.GetStatOffset(magicFish.Type)));
Advance(TimeSpan.FromSeconds(1));
Assert.All(fish, magicFish => Assert.Equal(0, fisher.GetStatOffset(magicFish.Type)));
}
finally
{
foreach (var magicFish in fish)
{
magicFish.Delete();
}
fisher.Delete();
Core._now = previousNow;
Core.Expansion = previousExpansion;
}
}
// Within five standard deviations of the expected rate; a rate of zero must never happen.
private static void AssertRate(double expected, int count)
{
var tolerance = 5 * Math.Sqrt(expected * (1 - expected) / Casts);
Assert.InRange((double)count / Casts, expected - tolerance, expected + tolerance);
}
private static void AssertRate(double expected, int count, int trials)
{
var tolerance = 5 * Math.Sqrt(expected * (1 - expected) / trials);
Assert.InRange((double)count / trials, expected - tolerance, expected + tolerance);
}
private static void Advance(TimeSpan time)
{
Core._now += time;

View file

@ -45,31 +45,6 @@ public class BoatPathTests
}
}
[SkippableFact]
public void BoatDeck_FootprintShape_IsPositionInvariant()
{
TileDataRequirement.SkipIfMissing();
// The property Phase 2's local-frame, movement-invariant boat cache must preserve:
// the deck's covered-cell shape (in local coords) is identical at two world positions.
var map = Map.Maps[MapId];
var a = new TestMulti(0x0);
map.GetAverageZ(WaterX, WaterY, out _, out var za, out _);
a.MoveToWorld(new Point3D(WaterX, WaterY, (sbyte)za), map);
var shapeA = LocalShape(a);
a.Delete();
var b = new TestMulti(0x0);
map.GetAverageZ(WaterX + 5, WaterY + 3, out _, out var zb, out _);
b.MoveToWorld(new Point3D(WaterX + 5, WaterY + 3, (sbyte)zb), map);
var shapeB = LocalShape(b);
b.Delete();
Assert.Equal(shapeA, shapeB);
Assert.NotEmpty(shapeA);
_output.WriteLine($"boat local deck shape stable across positions: {shapeA.Count} cells");
}
private static System.Collections.Generic.HashSet<(int lx, int ly)> LocalShape(BaseMulti multi)
{
var mcl = multi.Components;

View file

@ -17,28 +17,6 @@ public class FoundationRedesignTests
private const int PlaceX = 1500;
private const int PlaceY = 1600;
[SkippableFact]
public void SwappingComponents_ChangesFootprint()
{
TileDataRequirement.SkipIfMissing();
var foundation = new SwappableFoundation(0x74); // GuildHouse footprint
try
{
var beforeCount = MultiArt.FootprintCells(foundation).Count;
Assert.True(beforeCount > 0, "non-vacuity: initial footprint must cover cells");
foundation.Redesign(MultiData.GetComponents(0x7A)); // Tower footprint (different shape)
var afterCount = MultiArt.FootprintCells(foundation).Count;
Assert.NotEqual(beforeCount, afterCount);
_output.WriteLine($"redesign footprint {beforeCount} -> {afterCount} cells");
}
finally
{
foundation.Delete();
}
}
[SkippableFact]
public void RedesignReRegistered_RoutesNewFootprintToLivePath()
{

View file

@ -130,33 +130,4 @@ public class MultiEdgeCaseTests
}
}
}
/// <summary>
/// Extensible slot for repo-owner-supplied gnarly placements. The assertion already covers
/// any (map,x,y) by construction — only the coordinates need filling in.
///
/// TODO(coords): repo owner to supply (map,x,y) for a static tree inside a footprint and a
/// dungeon cave-wall corner; add InlineData rows here — the assertion already covers them by
/// construction. (Left intentionally unhunted: do not invent tree/dungeon coords.)
/// </summary>
[SkippableTheory]
[InlineData(MapId, HouseX, HouseY)] // known-good open Trammel placement (passes today)
public void UserSuppliedScenarios_SynthesizerMatchesCheckMovement(int mapId, int x, int y)
{
TileDataRequirement.SkipIfMissing();
StepCache.Instance.Clear();
var map = Map.Maps[mapId];
var multi = new TestMulti(GuildHouseId);
map.GetAverageZ(x, y, out _, out var z, out _);
multi.MoveToWorld(new Point3D(x, y, (sbyte)z), map);
try
{
MultiTestSupport.AssertSynthesizerMatchesCheckMovement(multi, map);
}
finally
{
multi.Delete();
}
}
}

View file

@ -39,45 +39,6 @@ public class MultiMaskCacheTests
}
}
[SkippableFact]
public void IsInteriorLocalCell_TrueDeepInside_FalseAtEdge()
{
TileDataRequirement.SkipIfMissing();
var multi = new TestMulti(GuildHouseId);
try
{
var mcl = multi.Components;
var foundInterior = false;
var foundEdge = false;
for (var ly = 0; ly < mcl.Height && (!foundInterior || !foundEdge); ly++)
{
for (var lx = 0; lx < mcl.Width; lx++)
{
if (mcl.Tiles[lx][ly].Length == 0)
{
continue;
}
if (MultiMaskCache.IsInteriorLocalCell(mcl, lx, ly))
{
foundInterior = true;
}
else
{
foundEdge = true;
}
}
}
Assert.True(foundInterior, "a guild house must have at least one interior cell");
Assert.True(foundEdge, "a guild house must have at least one edge/perimeter cell");
}
finally
{
multi.Delete();
}
}
[Fact]
public void LocalWorldZ_RoundTrips_AndPreservesMasks()
{

View file

@ -228,17 +228,6 @@ public class StepCacheFileFormatTests
Assert.True(fileLength < 1100, $"expected every base Z array to elide; file was {fileLength} bytes");
}
[Fact]
public void CoastlineChunk_ElidesEveryZArray()
{
// Partial walkability with a non-zero SourceZ: the shape that defeats an unmasked predictor.
var src = FlatFullChunk(baseZ: 25);
var rt = RoundTrip(src, out var fileLength);
AssertIdentical(src, rt);
Assert.True(fileLength < 1100, $"masked predictor should elide every array; file was {fileLength} bytes");
}
[Fact]
public void SlopeInOneDirection_StoresOnlyThatZArray()
{

View file

@ -42,16 +42,6 @@ public class StepCacheLifecycleTests : IDisposable
return chunk;
}
[Fact]
public void Clear_OnEmptyCache_LeavesStatsZero()
{
var stats = FreshCache(2).GetStats();
Assert.Equal(0, stats.ResidentChunks);
Assert.Equal(0L, stats.Hits);
Assert.Equal(0L, stats.BuildsTotal);
}
// ---- promotion gate ----
/// <summary>

View file

@ -78,174 +78,4 @@ public class StepProbeTests
Assert.False(result.IsWalkable(Direction.South), "S should be off-map");
Assert.False(result.IsWalkable(Direction.Left), "SW should be off-map");
}
[Fact]
public void ComputeMaskAt_TrammelOpenPlain_HasFlatCellWithAllDirectionsWalkable()
{
// Invariant: somewhere in the open-plain region, there must be a fully-flat cell
// whose mask is 0xFF and all 8 destZ values equal sourceZ (no slope).
// This protects against a regression where the baker stops detecting flat cells.
var map = Map.Maps[1];
Assert.NotNull(map);
var found = false;
for (var x = 1500; x < 1532 && !found; x++)
{
for (var y = 1600; y < 1632 && !found; y++)
{
map.GetAverageZ(x, y, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
if (result.WalkMask != 0xFF)
{
continue;
}
var allSameZ = true;
for (var d = 0; d < 8; d++)
{
if (result.GetWalkZ((Direction)d) != sourceZ)
{
allSameZ = false;
break;
}
}
if (allSameZ)
{
found = true;
_output.WriteLine($"Flat-open cell found at ({x}, {y}, {sourceZ})");
}
}
}
Assert.True(found, "Expected at least one fully-flat open cell in (1500..1532, 1600..1632)");
}
[SkippableFact]
public void ComputeMaskAt_BritainInnDense_HasCellWithBlockedDirections()
{
TileDataRequirement.SkipIfMissing();
// Invariant: inside the dense Britain inn region, at least one cell must have
// at least one direction blocked by a static. Protects against a regression
// where the baker reports everything as walkable (the original false-pass bug).
var map = Map.Maps[1];
Assert.NotNull(map);
var blockedCellCount = 0;
for (var x = 1480; x < 1512; x++)
{
for (var y = 1610; y < 1642; y++)
{
map.GetAverageZ(x, y, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
if (result.WalkMask != 0xFF)
{
blockedCellCount++;
}
}
}
_output.WriteLine($"Cells with at least one blocked direction: {blockedCellCount} / 1024");
Assert.True(blockedCellCount > 0, "Expected at least one cell with a blocked direction in the dense region");
}
[Theory]
[InlineData(1500, 1600)]
[InlineData(1480, 1610)]
[InlineData(0, 0)]
public void ComputeMaskAt_IsDeterministic(int x, int y)
{
// Same inputs must always produce identical output. Catches accidental
// statefulness in the baker (e.g., a static cache that gets corrupted).
var map = Map.Maps[1];
Assert.NotNull(map);
map.GetAverageZ(x, y, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var first = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
var second = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
var third = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
Assert.Equal(first.WalkMask, second.WalkMask);
Assert.Equal(first.WalkMask, third.WalkMask);
for (var d = 0; d < 8; d++)
{
Assert.Equal(first.GetWalkZ((Direction)d), second.GetWalkZ((Direction)d));
Assert.Equal(first.GetWalkZ((Direction)d), third.GetWalkZ((Direction)d));
}
}
[SkippableFact]
public void ComputeMaskAt_PinnedCell_TrammelOpenPlainOrigin()
{
TileDataRequirement.SkipIfMissing();
// PINNING test: locks specific output for Trammel (1500, 1600).
// Cell at z=10 with mask 0xC1 (N + W + NW only walkable). The other five
// directions are blocked by water (E/SE/S/SW are wet tiles, NE is shore).
// If this changes, either the baker logic changed or the underlying tile
// data changed; re-run the parity test to confirm before updating expected values.
var map = Map.Maps[1];
Assert.NotNull(map);
map.GetAverageZ(1500, 1600, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, 1500, 1600, sourceZ);
Assert.Equal((sbyte)10, sourceZ);
Assert.Equal((byte)0xC1, result.WalkMask);
Assert.True(result.IsWalkable(Direction.North));
Assert.False(result.IsWalkable(Direction.Right));
Assert.False(result.IsWalkable(Direction.East));
Assert.False(result.IsWalkable(Direction.Down));
Assert.False(result.IsWalkable(Direction.South));
Assert.False(result.IsWalkable(Direction.Left));
Assert.True(result.IsWalkable(Direction.West));
Assert.True(result.IsWalkable(Direction.Up));
Assert.Equal((sbyte)10, result.GetWalkZ(Direction.North));
Assert.Equal((sbyte)10, result.GetWalkZ(Direction.West));
Assert.Equal((sbyte)10, result.GetWalkZ(Direction.Up));
}
[SkippableFact]
public void ComputeMaskAt_PinnedCell_BritainInnDenseOrigin()
{
TileDataRequirement.SkipIfMissing();
// PINNING test: locks specific output for Trammel (1480, 1610).
// Cell at z=20 with mask 0x3F (N/NE/E/SE/S/SW walkable, W/NW blocked by
// a wall to the west). All walkable directions stay flat at z=20.
var map = Map.Maps[1];
Assert.NotNull(map);
map.GetAverageZ(1480, 1610, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, 1480, 1610, sourceZ);
Assert.Equal((sbyte)20, sourceZ);
Assert.Equal((byte)0x3F, result.WalkMask);
Assert.True(result.IsWalkable(Direction.North));
Assert.True(result.IsWalkable(Direction.Right));
Assert.True(result.IsWalkable(Direction.East));
Assert.True(result.IsWalkable(Direction.Down));
Assert.True(result.IsWalkable(Direction.South));
Assert.True(result.IsWalkable(Direction.Left));
Assert.False(result.IsWalkable(Direction.West));
Assert.False(result.IsWalkable(Direction.Up));
for (var d = 0; d < 6; d++)
{
Assert.Equal((sbyte)20, result.GetWalkZ((Direction)d));
}
}
}

View file

@ -98,32 +98,6 @@ public class ImportCleanupTests
}
}
[Fact]
public void Import_MalformedFile_LeaksNoWorldItems()
{
// First entry is syntactically valid JSON for a Spawner, second entry is truncated/garbage.
// STJ throws a JsonException during array deserialization before any Items are created
// (the DTO path is GC-only), so zero new spawners should appear at the valid entry's location.
var dir = Path.Combine(Path.GetTempPath(), "muo-import-malformed-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, "bad.json"), """
[ { "$type": "Spawner", "location": [320, 320, 0], "map": "Felucca", "count": 1,
"entries": [ { "name": "Fisherman", "maxCount": 1, "probability": 100 } ] },
{ "$type": "Spawner", "location": [ THIS IS NOT JSON
""");
try
{
var before = CountSpawnersNear(new Point3D(320, 320, 0));
ImportSpawnersCommand.ImportFile(new FileInfo(Path.Combine(dir, "bad.json")), new Dictionary<Guid, ISpawner>());
// Malformed parse must construct zero Items (DTO is GC-only); nothing placed or orphaned.
Assert.Equal(before, CountSpawnersNear(new Point3D(320, 320, 0)));
}
finally
{
Directory.Delete(dir, true);
}
}
private static int CountSpawnersNear(Point3D p)
{
var n = 0;

View file

@ -1,47 +0,0 @@
// Regression guard: verifies that a real migrated spawn file (post-uoml/felucca/Vendors.json)
// can be deserialized as List<SpawnerDto> and each DTO produces a valid spawner via ToSpawner().
// Exercises the $type discriminator path introduced by the data migration.
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Server;
using Server.Engines.Spawners;
using Xunit;
namespace UOContent.Tests.Engines.Spawners.Json;
[Collection("Sequential UOContent Tests")]
public class MigratedDataLoadTests
{
[Fact]
public void MigratedFile_LoadsWithDollarType()
{
var path = Path.Combine(Core.BaseDirectory, "Data", "Spawns", "post-uoml", "felucca", "Vendors.json");
if (!File.Exists(path))
{
return; // distribution data not present in this checkout
}
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(File.ReadAllText(path), SpawnerJsonSerializer.Options);
Assert.NotEmpty(dtos);
var spawners = new List<BaseSpawner>(dtos.Count);
try
{
foreach (var dto in dtos)
{
spawners.Add(dto.ToSpawner());
}
Assert.Equal(dtos.Count, spawners.Count);
}
finally
{
foreach (var s in spawners)
{
s?.Delete();
}
}
}
}

View file

@ -44,33 +44,6 @@ public class SpawnerDtoRoundTripTests
}
}
[Fact]
public void Spawner_HomeRangeSquare_WritesHomeRange_RoundTrips()
{
Spawner original = null;
BaseSpawner rebuilt = null;
try
{
original = new Spawner("Fisherman");
original.MoveToWorld(new Point3D(200, 200, 0), Map.Felucca);
// Exactly what homeRange 5 reconstructs (centered square, standard z/depth).
original.SpawnBounds = new Rectangle3D(195, 195, -128, 11, 11, 256);
var json = JsonSerializer.Serialize(new List<SpawnerDto> { original.ToDto() }, SpawnerJsonSerializer.Options);
Assert.Contains("\"homeRange\": 5", json);
Assert.DoesNotContain("spawnBounds", json);
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
rebuilt = Assert.Single(dtos).ToSpawner();
Assert.Equal(new Rectangle3D(195, 195, -128, 11, 11, 256), rebuilt.SpawnBounds);
}
finally
{
rebuilt?.Delete();
original?.Delete();
}
}
[Fact]
public void Spawner_WritesMandatory_OmitsOptionalDefaults()
{

View file

@ -7,14 +7,6 @@ namespace UOContent.Tests;
public class BitMask256Tests
{
[Fact]
public void BitMask256_InitialState_AllBitsZero()
{
var mask = BitMask256.AllClear();
Assert.Equal(0, mask.PopCount());
}
[Theory]
[InlineData(0)]
[InlineData(63)]
@ -110,41 +102,6 @@ public class SectorSpawnCacheManagerTests
SectorSpawnCacheManager.ClearAll();
}
[Fact]
public void ClearAll_ResetsCache()
{
SectorSpawnCacheManager.ClearAll();
Assert.Equal(0, SectorSpawnCacheManager.CachedSectorCount);
Assert.Equal(0, SectorSpawnCacheManager.LandCacheCount);
Assert.Equal(0, SectorSpawnCacheManager.WaterCacheCount);
}
[Fact]
public void SetValid_CreatesSectorCache()
{
var map = Map.Felucca;
var pos = new Point3D(100, 100, 0);
SectorSpawnCacheManager.SetValid(map, pos, isWater: false);
Assert.Equal(1, SectorSpawnCacheManager.CachedSectorCount);
Assert.Equal(1, SectorSpawnCacheManager.LandCacheCount);
Assert.Equal(0, SectorSpawnCacheManager.WaterCacheCount);
}
[Fact]
public void SetValid_Water_CreatesWaterCache()
{
var map = Map.Felucca;
var pos = new Point3D(100, 100, 0);
SectorSpawnCacheManager.SetValid(map, pos, isWater: true);
Assert.Equal(1, SectorSpawnCacheManager.CachedSectorCount);
Assert.Equal(0, SectorSpawnCacheManager.LandCacheCount);
Assert.Equal(1, SectorSpawnCacheManager.WaterCacheCount);
}
[Fact]
public void SetValid_LandAndWater_SeparateCaches()
{
@ -251,19 +208,6 @@ public class SectorSpawnCacheManagerTests
Assert.False(result);
}
[Fact]
public void InvalidateSectors_RemovesCachedData()
{
var map = Map.Felucca;
SectorSpawnCacheManager.SetValid(map, new Point3D(50, 50, 0), isWater: false);
Assert.Equal(1, SectorSpawnCacheManager.CachedSectorCount);
SectorSpawnCacheManager.InvalidateSectors(map, new Rectangle2D(0, 0, 100, 100));
Assert.Equal(0, SectorSpawnCacheManager.CachedSectorCount);
}
[Fact]
public void InvalidateSectors_RemovesBothLandAndWater()
{
@ -341,54 +285,6 @@ public class SpiralScanTests
Assert.Equal(expectedDy, dy);
}
[Fact]
public void SpiralPattern_Ring1Has8Positions()
{
// Ring N has 8*N positions
const int ring1Positions = 1 * 8;
Assert.Equal(8, ring1Positions);
}
[Fact]
public void SpiralPattern_Ring2Has16Positions()
{
const int ring2Positions = 2 * 8;
Assert.Equal(16, ring2Positions);
}
[Fact]
public void SpiralPattern_Ring10Has80Positions()
{
const int ring10Positions = 10 * 8;
Assert.Equal(80, ring10Positions);
}
[Fact]
public void SpiralPattern_Ring1_CoversAllAdjacentTiles()
{
// Ring 1 should cover all 8 adjacent tiles
var expectedOffsets = new HashSet<(int dx, int dy)>
{
(-1, -1), (0, -1), (1, -1), // Top row
(1, 0), // Right
(1, 1), (0, 1), (-1, 1), // Bottom row
(-1, 0) // Left
};
var actualOffsets = new HashSet<(int dx, int dy)>();
for (var position = 0; position < 8; position++)
{
actualOffsets.Add(SectorSpawnCacheManager.GetSpiralOffset(1, position));
}
Assert.Equal(expectedOffsets.Count, actualOffsets.Count);
foreach (var expected in expectedOffsets)
{
Assert.Contains(expected, actualOffsets);
}
}
[Fact]
public void SpiralPattern_Ring2_CoversAllExpectedTiles()
{
@ -414,16 +310,6 @@ public class SpiralScanTests
public class SpawnPositionStateTests
{
[Fact]
public void SpawnPositionState_InitialState_ZeroCounts()
{
var state = new SpawnPositionState();
Assert.False(state.SpiralComplete);
Assert.Equal(0, state.SpiralRing);
Assert.Equal(0, state.SpiralRingPosition);
}
[Fact]
public void Reset_ClearsAllState()
{
@ -457,14 +343,6 @@ public class SpawnPositionStateTests
Assert.False(state.ShouldCachePositions(SpawnPositionMode.Disabled));
}
[Fact]
public void ShouldCachePositions_Automatic_FalseWithNoFailures()
{
var state = new SpawnPositionState();
Assert.False(state.ShouldCachePositions(SpawnPositionMode.Automatic));
}
[Fact]
public void ShouldCachePositions_Automatic_TrueAfterThresholdFailures()
{
@ -522,30 +400,6 @@ public class SpawnPositionStateTests
Assert.True(state.ShouldAbandon());
}
[Fact]
public void ShouldAbandon_FalseWithUsefulCacheHit()
{
var state = new SpawnPositionState();
state.SpiralComplete = true;
// Record 24 useless results
for (var i = 0; i < 24; i++)
{
state.RecordUselessResult();
}
// Record a useful cache hit - resets counter
state.RecordUsefulCacheHit();
// Record a few more useless results
for (var i = 0; i < 5; i++)
{
state.RecordUselessResult();
}
Assert.False(state.ShouldAbandon()); // Counter was reset, only 5 now
}
[Fact]
public void RecordUsefulCacheHit_ResetsUselessCounter()
{

View file

@ -67,18 +67,6 @@ public class SpawnerEntryOwnershipTests
spawner.Delete();
}
[Fact]
public void Start_WorksAfterStop_WhenOwnerHasEntries()
{
var spawner = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit");
Assert.True(spawner.Running);
spawner.Stop();
Assert.False(spawner.Running);
spawner.Start();
Assert.True(spawner.Running);
spawner.Delete();
}
[Fact]
public void Dupe_ClonesEntriesIntoIndependentList()
{
@ -159,85 +147,4 @@ public class SpawnerEntryOwnershipTests
}
// Manual: remove the Skip, run, and read the numbers from the thrown assertion.
[Fact(Skip = "manual benchmark")]
public void Benchmark_SpawnPath_Manual()
{
const int iterations = 100_000;
const int warmup = 1_000;
var report = new ValueStringBuilder(stackalloc char[512]);
report.Append('\n', 1);
foreach (var entryCount in new[] { 1, 10, 50 })
{
var spawner = new Spawner(1000, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
spawner.MoveToWorld(new Point3D(1500, 1500, 0), Map.Felucca);
// SpawnedMaxCount = 0 keeps every entry full, so Spawn() does selection only.
for (var i = 0; i < entryCount; i++)
{
spawner.AddEntry("Rabbit", 100, 0, false);
}
for (var i = 0; i < warmup; i++)
{
spawner.Spawn();
}
var sw = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
spawner.Spawn();
}
sw.Stop();
var nsPerCall = sw.Elapsed.TotalMilliseconds * 1_000_000.0 / iterations;
report.Append(
$"Spawn() entries={entryCount,2}: {nsPerCall,8:F1} ns/call ({iterations} iterations, {sw.ElapsedMilliseconds} ms total)\n"
);
spawner.Delete();
}
{
var spawner = new Spawner(1000, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
spawner.MoveToWorld(new Point3D(1500, 1500, 0), Map.Felucca);
for (var i = 0; i < 10; i++)
{
spawner.AddEntry("Rabbit", 100, 1, false);
}
spawner.Spawn();
Assert.Single(spawner.Spawned);
var rabbit = spawner.Spawned.Keys.First();
for (var i = 0; i < warmup; i++)
{
spawner.Remove(rabbit);
}
var sw = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
spawner.Remove(rabbit);
}
sw.Stop();
var nsPerCall = sw.Elapsed.TotalMilliseconds * 1_000_000.0 / iterations;
report.Append(
$"Remove(ISpawnable) entries=10: {nsPerCall,8:F1} ns/call ({iterations} iterations, {sw.ElapsedMilliseconds} ms total)\n"
);
(rabbit as Mobile)?.Delete();
spawner.Delete();
}
var summary = report.ToString();
report.Dispose();
throw new Xunit.Sdk.XunitException(summary);
}
}

View file

@ -1,50 +0,0 @@
using System;
using System.IO;
using System.Reflection;
using Server.Engines.Spawners;
using Server.Tests;
using Xunit;
namespace UOContent.Tests.Engines.Spawners;
[Collection("Sequential UOContent Tests")]
public class SpawnerFixtureCapture
{
// Freezes the BaseSpawner v12 save layout as test input; refuses to run against newer code.
[SkippableFact]
public void CaptureLegacyBlobs()
{
Skip.If(Environment.GetEnvironmentVariable("MODERNUO_CAPTURE_SPAWNER_FIXTURES") != "1");
var version = (int)typeof(BaseSpawner)
.GetField("SerializationVersion", BindingFlags.NonPublic | BindingFlags.Static)!
.GetRawConstantValue()!;
Assert.True(version == 12, $"Fixtures must be captured with BaseSpawner v12; current version is {version}.");
var dir = Path.Combine(AppContext.BaseDirectory, "Tests", "Engines", "Spawners", "Fixtures");
Directory.CreateDirectory(dir);
var spawner = new Spawner(2, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird")
{
Name = "FixtureSpawner"
};
spawner.Entries[1].Properties = "Hue 33";
File.WriteAllBytes(Path.Combine(dir, "spawner.v12-v1.bin"), SpawnerBlob.Write(spawner));
var proximity = new ProximitySpawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, 5, "boo", true, "Rat", "Bird")
{
Name = "FixtureProximity"
};
File.WriteAllBytes(Path.Combine(dir, "proximity.v12-v1-v0.bin"), SpawnerBlob.Write(proximity));
var region = new RegionSpawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, "Orc", "Troll")
{
Name = "FixtureRegion"
};
File.WriteAllBytes(Path.Combine(dir, "region.v12-v1-v0.bin"), SpawnerBlob.Write(region));
spawner.Delete();
proximity.Delete();
region.Delete();
}
}

View file

@ -103,45 +103,6 @@ public class GridLayoutTests
Assert.Equal(800, sizes[1]);
}
[Fact]
public void TestGridCell_Properties()
{
var cell = new GridCell(10, 20, 100, 50);
Assert.Equal(10, cell.X);
Assert.Equal(20, cell.Y);
Assert.Equal(100, cell.Width);
Assert.Equal(50, cell.Height);
Assert.Equal(110, cell.Right);
Assert.Equal(70, cell.Bottom);
Assert.Equal(60, cell.CenterX);
Assert.Equal(45, cell.CenterY);
}
[Fact]
public void TestGridCell_Inset()
{
var cell = new GridCell(10, 20, 100, 50);
var inset = cell.Inset(5);
Assert.Equal(15, inset.X);
Assert.Equal(25, inset.Y);
Assert.Equal(90, inset.Width);
Assert.Equal(40, inset.Height);
}
[Fact]
public void TestGridCell_Offset()
{
var cell = new GridCell(10, 20, 100, 50);
var offset = cell.Offset(5, 10);
Assert.Equal(15, offset.X);
Assert.Equal(30, offset.Y);
Assert.Equal(100, offset.Width);
Assert.Equal(50, offset.Height);
}
[Fact]
public void TestListViewLayout_Pagination()
{

View file

@ -73,34 +73,6 @@ public class T2AJewelGemCraftTests
}
}
[Fact]
public void OnCraft_WithUnsetGemContext_LeavesPlainPiece()
{
var map = Map.Felucca;
var player = CreatePlayerMobile(map, new Point3D(4120, 500, 0));
var ring = new GoldRing();
try
{
player.Backpack.AddItem(new IronIngot(10));
var system = GetOrInitTinkeringSystem();
var context = system.GetContext(player);
context.PendingGemType = GemType.None; // no gem targeted
context.PendingGemCount = 0;
ring.OnCraft(1, false, player, system, typeof(IronIngot), null, MakeRingRecipe(), 0);
Assert.Equal(GemType.None, ring.GemType);
Assert.Equal(0, ring.GemCount);
}
finally
{
ring.Delete();
player.Delete();
}
}
[Fact]
public void OnCraft_WhenGemsUnavailableAtCraftTime_CraftsPlainPiece()
{

View file

@ -45,15 +45,4 @@ public class CorpseHairMigrationTests
// The entire block must be consumed - the loader validates exact byte length.
Assert.Equal(buffer.Length, reader.Position);
}
[Fact]
public void LegacyHairTail_Absent_ConsumesOnlyPresenceBool()
{
var buffer = WriteLegacyHairTail(false, 0, 0);
var reader = new BufferReader(buffer);
Assert.False(reader.ReadBool());
// Absent case: nothing else to read, and the presence bool was the only byte.
Assert.Equal(buffer.Length, reader.Position);
}
}

View file

@ -19,27 +19,6 @@ public class TreasureChestDecayTests
// DecayScheduler reads ScheduledDecayTime repeatedly and needs the reads to agree, so the
// random interval must be rolled once per chest rather than per read.
[Theory]
[MemberData(nameof(ChestTypes))]
public void DecayTimeIsStableAcrossReads(Type chestType)
{
var chest = chestType.CreateInstance<LockableContainer>();
try
{
var expected = chest.DecayTime;
for (var i = 0; i < 100; i++)
{
Assert.Equal(expected, chest.DecayTime);
}
}
finally
{
chest.Delete();
}
}
[Theory]
[MemberData(nameof(ChestTypes))]
public void ScheduledDecayTimeIsStableAcrossReads(Type chestType)

View file

@ -16,15 +16,6 @@ public class NameVerificationTests
Assert.True(NameVerification.ValidatePlayerName(name));
}
[Theory]
[InlineData("Rex")]
[InlineData("MrWhiskers")]
[InlineData("Fido")]
public void ValidatePetName_ValidNames_ReturnsTrue(string name)
{
Assert.True(NameVerification.ValidatePetName(name));
}
[Theory]
[InlineData("Mrs-Smith")]
[InlineData("Mr. Whiskers")]
@ -128,10 +119,4 @@ public class NameVerificationTests
var exceptions = SearchValues.Create(' ', '-', '.');
Assert.False(NameVerification.Validate("-John", 2, 16, true, false, true, 1, exceptions));
}
[Fact]
public void Validate_DisallowedCharacters_ReturnsFalse()
{
Assert.False(NameVerification.Validate("John123", 2, 16, true, false));
}
}

View file

@ -139,18 +139,6 @@ public class FamiliarAITests : IDisposable
return condition();
}
[SkippableFact]
public void UsesFamiliarAI_AndStaysOnComeOrder()
{
var p = Master(1500, 1600);
var f = Familiar(0, p, 1500, 1600);
Assert.IsType<FamiliarAI>(f.AIObject);
Assert.Equal(OrderType.Come, f.ControlOrder);
Assert.Equal(0.1, f.ActiveSpeed);
Assert.Equal(0.1, f.PassiveSpeed);
}
[SkippableFact]
public void Follows_WithoutBacktracking()
{

View file

@ -50,48 +50,4 @@ public class GuardFollowTests
Assert.Equal(0.2, currentSpeed);
Assert.Equal(0.1, currentMoveSpeed);
}
[Fact]
public void GuardReturn_PreAOS_RunsActive()
{
var previous = Core.Expansion;
try
{
Core.Expansion = Expansion.UOR;
var map = Map.Maps[1];
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);
pet.SetControlMaster(master);
var ai = pet.AIObject;
ai.AITimer?.Stop();
pet.ControlOrder = OrderType.Guard;
ai.AITimer?.Stop();
pet.SetCurrentSpeedToPassive(); // a stale passive state must not persist
ai.NextMove = 0;
ai.Obey();
var currentSpeed = pet.CurrentSpeed;
pet.Delete();
master.Delete();
// No sprint pre-AOS: the return runs active.
Assert.Equal(0.2, currentSpeed);
}
finally
{
Core.Expansion = previous;
}
}
}

View file

@ -1,77 +0,0 @@
using System;
using System.Collections.Generic;
using Server;
using Server.Mobiles;
using Xunit;
namespace UOContent.Tests.Mobiles.AI;
// A meer mage fights FightMode.Evil and its enraged creatures carry -1000 karma, so the karma rules alone
// make each an enemy of the other.
[Collection("Sequential UOContent Tests")]
public class MeerEnragedTests : IDisposable
{
private readonly List<Mobile> _created = [];
public void Dispose()
{
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
}
private T Track<T>(T m) where T : Mobile
{
_created.Add(m);
return m;
}
private static void Place(BaseCreature bc, int x)
{
var map = Map.Felucca;
bc.MoveToWorld(new Point3D(x, 1600, map.GetAverageZ(x, 1600)), map); // flat, clear line of sight both ways
bc.AIObject.AITimer.Stop();
}
private static bool Acquire(BaseCreature creature)
{
creature.NextReacquireTime = Core.TickCount - 1;
return creature.AIObject.AcquireFocusMob(creature.RangePerception, creature.FightMode, false, false, true);
}
[Fact]
public void MeerAndItsEnragedCreature_AreNotEnemies()
{
var meer = Track(new MeerMage());
var enraged = Track(new EnragedRabbit(meer));
Assert.False(enraged.IsEnemy(meer));
Assert.False(meer.IsEnemy(enraged));
}
[Fact]
public void AnotherMeersEnragedCreature_StaysAnEnemy()
{
var meer = Track(new MeerMage());
var other = Track(new MeerMage());
var enraged = Track(new EnragedRabbit(other));
Assert.True(enraged.IsEnemy(meer));
Assert.True(meer.IsEnemy(enraged));
}
[SkippableFact]
public void MeerAndItsEnragedCreature_NeverAcquireEachOther()
{
Skip.If(!Server.Tests.TestServerInitializer.TileDataLoaded, "Requires UO client map data.");
var meer = Track(new MeerMage());
var enraged = Track(new EnragedBlackBear(meer));
Place(meer, 1600);
Place(enraged, 1601);
Assert.False(Acquire(enraged));
Assert.False(Acquire(meer));
}
}

View file

@ -265,21 +265,6 @@ public class PetOrderTests : IDisposable
Assert.Equal(pet.Location, pet.Home);
}
[Fact]
public void LoyaltyRelease_ClearsTheMaster_AndStartsTheDeleteCountdown()
{
var (master, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
var followers = master.Followers;
// What the loyalty drain assigns when loyalty reaches zero.
pet.ControlOrder = OrderType.Release;
Assert.False(pet.Controlled);
Assert.Null(pet.ControlMaster);
Assert.Equal(followers - pet.ControlSlots, master.Followers);
Assert.True(pet.PendingDeleteTimer?.Running);
}
[Fact]
public void Release_WithoutSpawner_AnchorsHomeToCurrentLocation()
{
@ -375,29 +360,6 @@ public class PetOrderTests : IDisposable
Assert.Same(master, pet.ControlTarget);
Assert.Equal(OrderType.Follow, pet.AIObject.PersistentOrder);
}
[Fact]
public void Stop_WhileFollowing_CancelsToIdle_NonML()
{
var previous = Core.Expansion;
try
{
Core.Expansion = Expansion.SE; // pre-ML: Core.ML is false
var (_, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1002, 1000, 0));
pet.ControlOrder = OrderType.Follow;
pet.ControlOrder = OrderType.Stop;
// Stop/idle resolution is era-independent.
Assert.Equal(OrderType.None, pet.ControlOrder);
Assert.Equal(OrderType.None, pet.AIObject.PersistentOrder);
Assert.Equal(pet.Location, pet.Home);
}
finally
{
Core.Expansion = previous;
}
}
// The parameterless ctor fully initializes a player; the Serial ctor leaves that to Deserialize.
private PlayerMobile SpawnPlayer(Point3D loc)
{
@ -991,19 +953,6 @@ public class PetOrderTests : IDisposable
Assert.Same(friend, pet.ControlTarget);
}
[Fact]
public void GMObey_TakesControlOfACommandablePet()
{
var (master, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
pet.Name = "Rex";
var gm = SpawnPlayer(new Point3D(1002, 1000, 0));
gm.AccessLevel = AccessLevel.GameMaster;
pet.AIObject.OnSpeech(new SpeechEventArgs(gm, "Rex obey", MessageType.Regular, 0x3B2, []));
Assert.Same(gm, pet.ControlMaster);
}
[Fact]
public void GMAllObey_DoesNotTakeControlledPets()
{
@ -1021,42 +970,5 @@ public class PetOrderTests : IDisposable
}
// Release is relinquishing control, not exerting it: no roll, so no loyalty either way.
[Fact]
public void MenuRelease_TouchesNoLoyalty()
{
var (master, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
pet.Loyalty = 50;
new InternalEntry(3006118, 14, OrderType.Release, true).OnClick(master, pet); // Release
Assert.Equal(50, pet.Loyalty); // no roll: neither the +1 for passing nor the -3 for failing
}
[Fact]
public void SpeechRelease_TouchesNoLoyalty()
{
var (master, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
pet.Name = "Rex";
pet.Loyalty = 50;
pet.AIObject.OnSpeech(new SpeechEventArgs(master, "Rex release", MessageType.Regular, 0x3B2, [0x16D]));
Assert.Equal(50, pet.Loyalty);
}
// A creature nobody can command is not released either.
[Fact]
public void MenuRelease_OnAnUncontrollablePet_IsRefusedWithoutCost()
{
var (master, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
pet.MinTameSkill = 120.0; // control chance at or below zero
master.Skills.AnimalTaming.Base = 0;
master.Skills.AnimalLore.Base = 0;
pet.Loyalty = 50;
new InternalEntry(3006118, 14, OrderType.Release, true).OnClick(master, pet);
Assert.Equal(50, pet.Loyalty); // refused, but never punished
Assert.True(pet.Controlled);
}
}

View file

@ -99,29 +99,6 @@ public class PetPacingTests : IDisposable
}
// Pre-AOS pets follow at their own pace; nothing caps them.
[Fact]
public void FollowMaster_PreAOS_KeepsItsOwnPace()
{
var previous = Core.Expansion;
try
{
Core.Expansion = Expansion.UOR;
var (master, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
pet.SetMoveSpeed(0.3, 0.9);
pet.ControlTarget = master;
pet.ControlOrder = OrderType.Follow;
Assert.Equal(0.2, pet.CurrentSpeed);
Assert.Equal(0.3, pet.CurrentMoveSpeed);
}
finally
{
Core.Expansion = previous;
}
}
private sealed class SprintingPet : PetTestStub
{
public override double FollowMoveSpeed => 0.125;
@ -204,35 +181,7 @@ public class PetPacingTests : IDisposable
}
// A pet chasing a combatant keeps the move table.
[Fact]
public void CombatChasingPet_KeepsMoveTable()
{
var (_, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
var target = new PetTestStub();
target.MoveToWorld(new Point3D(1003, 1000, 0), Map.Felucca);
_created.Add(target);
pet.SetMoveSpeed(0.3, 0.9);
pet.ControlOrder = OrderType.Guard;
pet.Combatant = target;
pet.SetCurrentSpeedToActive();
Assert.Equal(0.3, pet.CurrentMoveSpeed);
}
// Herding overrides order pacing.
[Fact]
public void HerdedObeyingPet_KeepsHerdingPace()
{
var (_, pet) = Spawn(new Point3D(1000, 1000, 0), new Point3D(1001, 1000, 0));
pet.SetMoveSpeed(0.45, 0.9);
pet.SetCurrentSpeedToPassive();
pet.TargetLocation = new Point2D(1010, 1010);
Assert.Equal(0.3, pet.CurrentMoveSpeed); // fixed herding pace
}
private sealed class ThinkProbe : PetTestStub
{
public int Thinks;

View file

@ -36,21 +36,6 @@ public class SummonAcquireRulesTests : IDisposable
return creature.AIObject.AcquireFocusMob(creature.RangePerception, creature.FightMode, false, false, true);
}
[SkippableTheory]
[InlineData(true)]
[InlineData(false)]
public void PreAosFeluccaVortexTurnsOnItsCaster(bool bladeSpirits)
{
Skip.If(!Server.Tests.TestServerInitializer.TileDataLoaded, "Requires UO client map data.");
Core.Expansion = Expansion.UOR;
var caster = Player(Map.Felucca, 1500, 100);
var summon = Summon(bladeSpirits ? new BladeSpirits() : new EnergyVortex(), caster, 1499);
Assert.True(Acquire(summon));
Assert.Same(caster, summon.FocusMob);
}
[SkippableFact]
public void PreAosFeluccaVortexPrefersAnyoneOverItsCaster()
{

View file

@ -78,34 +78,6 @@ public class LootingRightsTests
}
}
[Fact]
public void HitsMaxBand_MovesTheRightsThreshold()
{
var victim = new TestMobile();
var first = NewPlayer();
var second = NewPlayer();
try
{
victim.RegisterDamage(100, first);
victim.RegisterDamage(40, second);
// hitsMax >= 200 drops the bar to topDamage / 4 = 31, which 40 clears.
var rights = BaseCreature.GetLootingRights(victim.DamageEntries, 200);
Assert.Equal(2, rights.Count);
Assert.True(rights[0].m_HasRight);
Assert.True(rights[1].m_HasRight);
Assert.Same(second, rights[1].m_Mobile);
}
finally
{
victim.Delete();
first.Delete();
second.Delete();
}
}
[Fact]
public void PetDamage_CreditsTheMaster_NotThePet()
{

View file

@ -1,98 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Server;
using Server.Mobiles;
using Xunit;
namespace UOContent.Tests.Mobiles;
// Lord Oaks' abilities and spell shield depend on his queen, so the queen must spawn from combat,
// never from a query such as GetMonsterAbilities or a damage calculation.
[Collection("Sequential UOContent Tests")]
public class LordOaksTests : IDisposable
{
private readonly List<Mobile> _created = [];
public void Dispose()
{
foreach (var m in World.Mobiles.Values.OfType<Silvani>().ToList())
{
m.Delete();
}
for (var i = 0; i < _created.Count; i++)
{
_created[i].Delete();
}
}
private LordOaks NewOaks(Map map)
{
var oaks = new LordOaks();
_created.Add(oaks);
oaks.MoveToWorld(new Point3D(1000, 1000, 0), map);
return oaks;
}
private Mobile NewAttacker()
{
var attacker = new Mongbat();
_created.Add(attacker);
return attacker;
}
private static int SilvaniCount() => World.Mobiles.Values.Count(m => m is Silvani);
[Fact]
public void QueryingOrDeletingAnUnengagedOaks_SpawnsNoQueen()
{
var oaks = NewOaks(Map.Felucca);
var scalar = 1.0;
oaks.AlterDamageScalarFrom(null, ref scalar);
oaks.GetMonsterAbilities();
oaks.Delete();
Assert.Equal(1.0, scalar);
Assert.Equal(0, SilvaniCount());
}
[Fact]
public void Aggression_SpawnsTheQueenOnce_AndShieldsOaksWhileSheLives()
{
var oaks = NewOaks(Map.Felucca);
var attacker = NewAttacker();
oaks.AggressiveAction(attacker, false);
oaks.AggressiveAction(attacker, false);
var queen = World.Mobiles.Values.OfType<Silvani>().Single();
var shielded = 1.0;
oaks.AlterDamageScalarFrom(attacker, ref shielded);
Assert.Equal(0.1, shielded, 6);
Assert.True(oaks.CanUseAbility(MonsterAbilities.SummonPixiesCounter));
queen.Delete();
var exposed = 1.0;
oaks.AlterDamageScalarFrom(attacker, ref exposed);
oaks.AggressiveAction(attacker, false);
Assert.Equal(1.0, exposed);
Assert.False(oaks.CanUseAbility(MonsterAbilities.SummonPixiesCounter));
Assert.Equal(0, SilvaniCount());
}
[Fact]
public void AnOaksOnTheInternalMap_NeverSpawnsTheQueen()
{
var oaks = new LordOaks();
_created.Add(oaks);
oaks.AggressiveAction(NewAttacker(), false);
Assert.Equal(0, SilvaniCount());
}
}

View file

@ -74,15 +74,6 @@ public class BanExemptionsTests
Assert.False(BanExemptions.IsExempt(_listed, "some-future-reason", NeverCalled));
}
[Fact]
public void Manual_allowlist_does_not_spend_the_earned_lists_strikes()
{
WithManualAllowlist("192.0.2.10");
// Unconditional, so the revocable list must not be consulted -- that would burn a strike.
Assert.True(BanExemptions.IsExempt(_listed, BanReasons.RateLimit, NeverCalled));
}
[Fact]
public void Falls_through_to_the_login_allowlist_when_not_file_listed()
{

View file

@ -59,12 +59,6 @@ public class BlocklistConfigurationTests
}
// The point of the flag: a shard that never opts in must not start the reload poll.
[Fact]
public void Blocklist_is_off_by_default()
{
Assert.False(new BlocklistSettings().Enabled);
}
// The generator (tools/Export-IpBlocklist.ps1) writes to this path by default; if one side moves
// without the other, a shard silently enforces nothing.
[Fact]

View file

@ -72,14 +72,4 @@ public class BlocklistFileTests
Assert.True(snap.IsBanned(IPAddress.Parse("223.169.4.9")));
File.Delete(p);
}
[Fact]
public void Load_parses_body()
{
var p = WriteTemp("# generated=x count=1\n8.8.8.0/24\n");
var snap = BlocklistFile.Load(p, out var parsed, out _);
Assert.Equal(1, parsed);
Assert.True(snap.IsBanned(IPAddress.Parse("8.8.8.8")));
File.Delete(p);
}
}

View file

@ -54,12 +54,6 @@ public class BlocklistSnapshotTests
Assert.True(s.IsBanned(IPAddress.Parse("5.6.7.200")));
}
[Fact]
public void Empty_snapshot_matches_nothing()
{
Assert.False(BlocklistSnapshot.Empty.IsBanned(IPAddress.Parse("1.2.3.4")));
}
[Fact]
public void Ipv6_single_and_cidr_are_matched()
{

View file

@ -42,14 +42,6 @@ public class CrowdSecAlertClientTests
Assert.Equal("/v1/decisions?origin=modern%20uo%2Ftest%26x%3D1&ip=1.2.3.4", query);
}
[Fact]
public void BuildDeleteQuery_PlainOrigin_Ipv4()
{
var query = CrowdSecAlertClient.BuildDeleteQuery("modernuo", IPAddress.Parse("192.168.1.1"));
Assert.Equal("/v1/decisions?origin=modernuo&ip=192.168.1.1", query);
}
[Fact]
public void BuildDeleteQuery_Ipv6_IsEscaped()
{

View file

@ -76,14 +76,4 @@ public class FirewallTests
Assert.IsType<CidrFirewallEntry>(Server.Network.Firewall.ToFirewallEntry("10.0.0.0-10.0.0.255"));
Assert.Null(Server.Network.Firewall.ToFirewallEntry("not-an-ip"));
}
[Fact]
public void ReadFirewallSet_SurfacesAddedEntries()
{
Server.Network.Firewall.ResetForTesting();
var entry = new SingleIpFirewallEntry(Ip("1.2.3.4"));
Server.Network.Firewall.Add(entry);
Server.Network.Firewall.ReadFirewallSet(set => Assert.Contains(entry, set));
}
}

View file

@ -50,12 +50,6 @@ public class ManualAllowlistConfigurationTests
}
// The point of the flag: a shard that never opts in must not start the reload poll.
[Fact]
public void Manual_allowlist_is_off_by_default()
{
Assert.False(new ManualAllowlistSettings().Enabled);
}
// The generator creates ip-allowlist.txt beside the blocklist; the wildcard is what picks up a
// carve-out file (-RefreshCarveouts writes ip-allowlist-starlink.txt) with no config edit.
[Fact]

View file

@ -255,17 +255,6 @@ public class AuthIdTests : IDisposable
new ClientVersion(7, 0, 0, 0)
);
[Fact]
public void IssuesAnIdWhenTheConnectionHasNone()
{
var account = CreateAccount("authid-first-select-user");
var authId = Ensure(0, account, AddressX);
Assert.NotEqual(0, authId);
Assert.Equal(1, IncomingAccountPackets.AuthIdWindowCount);
}
// Handing the same id back rather than minting another is what makes an orphan impossible,
// instead of something to clean up afterwards.
[Fact]
@ -371,12 +360,4 @@ public class AuthIdTests : IDisposable
GameServer.GameServerLoginEvent(right);
Assert.True(right.Accepted);
}
[Fact]
public void GeneratesDistinctAuthIds()
{
var account = CreateAccount("authid-distinct-user");
Assert.NotEqual(Register(account, AddressX), Register(account, AddressX));
}
}

View file

@ -141,68 +141,6 @@ public class DetectHiddenTests
}
}
/// <summary>
/// TryDetectStealther is a no-op when the target is not actually hidden.
/// </summary>
[Fact]
public void TryDetectStealther_DoesNothing_WhenStealtherIsNotHidden()
{
using var rng = new PredictableRandom(10);
DetectHidden.ClearDebounceCache();
var map = Map.Felucca;
var detector = CreatePlayerMobile(map, new Point3D(1800, 500, 0));
var stealther = CreatePlayerMobile(map, new Point3D(1801, 500, 0));
try
{
detector.Skills.DetectHidden.BaseFixedPoint = 1000;
stealther.Hidden = false;
var result = DetectHidden.TryDetectStealther(detector, stealther);
Assert.False(result);
Assert.False(stealther.Hidden);
}
finally
{
detector.Delete();
stealther.Delete();
DetectHidden.ClearDebounceCache();
}
}
/// <summary>
/// Passive detection only works on Felucca. A stealther on Trammel
/// should never be revealed by passive detection.
/// </summary>
[Fact]
public void TryDetectStealther_DoesNotReveal_WhenNotOnFelucca()
{
using var rng = new PredictableRandom(10);
DetectHidden.ClearDebounceCache();
var map = Map.Trammel;
var detector = CreatePlayerMobile(map, new Point3D(2000, 500, 0));
var stealther = CreatePlayerMobile(map, new Point3D(2001, 500, 0));
try
{
detector.Skills.DetectHidden.BaseFixedPoint = 1000; // 100.0
stealther.Skills.Hiding.BaseFixedPoint = 0; // 0.0
stealther.Hidden = true;
var result = DetectHidden.TryDetectStealther(detector, stealther);
Assert.False(result);
Assert.True(stealther.Hidden);
}
finally
{
detector.Delete();
stealther.Delete();
DetectHidden.ClearDebounceCache();
}
}
private static PlayerMobile CreatePlayerMobile(Map map, Point3D location)
{
var mobile = new PlayerMobile(World.NewMobile);

View file

@ -81,44 +81,4 @@ public class SkillEventsTests
from.Delete();
}
}
[Fact]
public void CheckSkill_Direct_DoesNotRaise()
{
var from = new Mobile();
var skill = from.Skills[SkillName.Mining];
var recorder = new Recorder();
SkillEvents.SkillUsed += recorder.Handle;
try
{
SkillCheck.CheckSkill(from, skill, null, 1.0);
Assert.Equal(0, recorder.Calls);
}
finally
{
SkillEvents.SkillUsed -= recorder.Handle;
from.Delete();
}
}
[Fact]
public void NoSubscriber_DoesNotThrow()
{
var from = new Mobile();
var recorder = new Recorder();
try
{
SkillEvents.SkillUsed += recorder.Handle;
SkillEvents.SkillUsed -= recorder.Handle;
Assert.True(SkillCheck.Mobile_SkillCheckDirectLocation(from, SkillName.Mining, 1.0));
Assert.Equal(0, recorder.Calls);
}
finally
{
from.Delete();
}
}
}

View file

@ -19,24 +19,8 @@ public class BloodOathSpellTests
// ModernUO previously used /80 (matching the bugged in-game tooltip), which made
// Spirit Speak almost irrelevant to duration. RunUO/ServUO and the code's own
// fixed-point comment both use /8.
[Theory]
[InlineData(120.0, 0.0, 23.0)] // GM Spirit Speak, no resist
[InlineData(120.0, 120.0, 8.0)] // equal skills -> baseline 8s
[InlineData(100.0, 20.0, 18.0)] // (100-20)/8 + 8
[InlineData(20.0, 0.0, 10.5)] // minimum skill
public void GetDurationSeconds_UsesDivideByEight(double ss, double resist, double expected)
{
Assert.Equal(expected, BloodOathSpell.GetDurationSeconds(ss, resist), 3);
}
// Player caster: Publish 48 resist mitigation does NOT apply; the attacker takes the
// full reflected (original, un-bonused) damage.
[Fact]
public void ComputeReflectedDamage_NoMitigation_ReturnsOriginal()
{
Assert.Equal(40, BloodOathSpell.ComputeReflectedDamage(40, 120.0, applyResistMitigation: false));
}
// Creature caster (Publish 48 / SA+): ((Resist * 10) / 20) + 10 = % of reflected damage resisted.
[Theory]
[InlineData(40, 0.0, 36)] // 10% resisted -> 40 * 0.90
@ -82,14 +66,6 @@ public class BloodOathSpellTests
target.Delete();
}
[Fact]
public void RemoveCurse_NotCursed_ReturnsFalse()
{
var m = NewMobile();
Assert.False(BloodOathSpell.RemoveCurse(m));
m.Delete();
}
// Issue #1690: death/delete of either party must break the oath immediately. The oath is wired
// to the central PlayerMobile/BaseCreature death+delete events instead of a polling timer.
[Fact]

View file

@ -44,17 +44,6 @@ public class AnimalFormTests
}
// Talisman-gated forms are never selectable without the matching talisman, regardless of skill.
[Fact]
public void CanSelectEntry_TalismanGatedForm_RequiresTalisman()
{
var m = NewMobileWithNinjitsu(120.0);
Assert.False(AnimalForm.CanSelectEntry(m, AnimalForm.Entries[IndexOf(typeof(Squirrel))]));
Assert.False(AnimalForm.CanSelectEntry(m, AnimalForm.Entries[IndexOf(typeof(Ferret))]));
m.Delete();
}
// Issue #2452: attempting a form above your skill must report NoSkill (so the caller can
// refrain from charging mana) and must not actually transform the caster.
[Fact]
@ -70,19 +59,4 @@ public class AnimalFormTests
m.Delete();
}
[Fact]
public void Morph_SufficientSkill_TransformsCaster()
{
// >= ReqSkill + 37.5 guarantees the success-chance roll is skipped.
var m = NewMobileWithNinjitsu(60.0);
var result = AnimalForm.Morph(m, IndexOf(typeof(Rat))); // needs 20
Assert.Equal(AnimalForm.MorphResult.Success, result);
Assert.NotNull(AnimalForm.GetContext(m));
AnimalForm.RemoveContext(m); // stop the form timer / clear state
m.Delete();
}
}

View file

@ -5,21 +5,6 @@ namespace Server.Tests.Utility;
public class TryParseTests
{
[Theory]
[InlineData("True", null, true)]
[InlineData("False", null, false)]
[InlineData("Alakazam", "Not a valid boolean string.", true)]
public void TestTryParseBool(string value, string returned, bool parsedAs)
{
var actualReturned = Server.Types.TryParse(typeof(bool), value, out var constructed);
Assert.Equal(returned, actualReturned);
if (returned == null)
{
Assert.Equal(parsedAs, constructed);
}
}
[Theory]
// Parsed directly into the target type (INumber<T>.TryParse), not via ulong + Convert.ChangeType.
[InlineData(typeof(int), "42", true, 42)]

View file

@ -25,18 +25,6 @@ public class ArchiveJournalTests : IDisposable
}
}
[Fact]
public void Configure_LoadsCleanState()
{
// Arrange & Act
ArchiveJournal.Configure(_testDir);
// Assert - fresh directory should have no operations
// Note: ArchiveJournal is static, so we check the journal file doesn't exist
var journalPath = Path.Combine(_testDir, ".archive-journal.json");
Assert.False(File.Exists(journalPath));
}
[Fact]
public void BeginOperation_CreatesStartedEntry()
{

View file

@ -1,104 +0,0 @@
using System;
using Server.Saves;
using Xunit;
namespace Server.Tests;
[Collection("Sequential UOContent Tests")]
public class AutoArchiveHelperTests
{
[Fact]
public void ArchiveDestinationRegistry_RegisterAndRetrieve()
{
// Arrange
var dest = new LocalArchiveDestination(24, 30, 12);
// Act
ArchiveDestinationRegistry.Register(dest);
// Assert
Assert.Contains(dest, ArchiveDestinationRegistry.Destinations);
// Cleanup
ArchiveDestinationRegistry.Unregister(dest);
Assert.DoesNotContain(dest, ArchiveDestinationRegistry.Destinations);
}
[Fact]
public void LocalArchiveDestination_SendArchive_ReturnsTrue()
{
// Arrange
var dest = new LocalArchiveDestination(24, 30, 12);
// Act
var result = dest.SendArchive("/fake/path.tar.zst", ArchivePeriod.Hourly, DateTime.UtcNow);
// Assert
Assert.True(result);
}
[Theory]
[InlineData(ArchivePeriod.Hourly, 24)]
[InlineData(ArchivePeriod.Daily, 30)]
[InlineData(ArchivePeriod.Monthly, 12)]
public void LocalArchiveDestination_RetentionCounts(ArchivePeriod period, int expected)
{
// Arrange
var dest = new LocalArchiveDestination(24, 30, 12);
// Act & Assert
Assert.Equal(expected, dest.GetRetentionCount(period));
}
[Fact]
public void ArchiveCompletedEventArgs_StoresValues()
{
// Arrange & Act
var args = new ArchiveCompletedEventArgs(
"/archives/hourly/test.tar.zst",
ArchivePeriod.Hourly,
new DateTime(2026, 3, 22, 14, 0, 0, DateTimeKind.Utc),
1048576,
2.5
);
// Assert
Assert.Equal("/archives/hourly/test.tar.zst", args.ArchiveFilePath);
Assert.Equal(ArchivePeriod.Hourly, args.Period);
Assert.Equal(1048576, args.FileSizeBytes);
Assert.Equal(2.5, args.ElapsedSeconds);
}
[Fact]
public void ArchiveFailedEventArgs_StoresException()
{
// Arrange
var ex = new InvalidOperationException("disk full");
// Act
var args = new ArchiveFailedEventArgs(
ArchivePeriod.Daily,
new DateTime(2026, 3, 22, 0, 0, 0, DateTimeKind.Utc),
ex
);
// Assert
Assert.Equal(ArchivePeriod.Daily, args.Period);
Assert.Same(ex, args.Exception);
}
[Fact]
public void ArchiveJournalEntry_DefaultState()
{
// Arrange & Act
var entry = new ArchiveJournalEntry();
// Assert
Assert.NotNull(entry.SourceDirectories);
Assert.Empty(entry.SourceDirectories);
Assert.NotNull(entry.DestinationResults);
Assert.Empty(entry.DestinationResults);
Assert.Null(entry.FailureReason);
Assert.Equal(DateTime.MaxValue, entry.CompletedAt);
}
}

View file

@ -46,29 +46,6 @@ public class ManagedArchiveTests : IDisposable
return dir;
}
[Fact]
public void CreateTarZstd_SingleDirectory_RoundTrips()
{
// Arrange
var sourceDir = CreateTestDirectory("source",
("file1.txt", "Hello World"),
("file2.bin", "Binary content here"),
("subdir/nested.txt", "Nested file")
);
var archivePath = Path.Combine(_testDir, "test.tar.zst");
// Act
var entryCount = ManagedArchive.CreateTarZstd(
[sourceDir], archivePath, _testDir, compressionLevel: 1
);
// Assert
Assert.True(entryCount > 0);
Assert.True(File.Exists(archivePath));
Assert.True(new FileInfo(archivePath).Length > 0);
}
[Fact]
public void CreateTarZstd_MultipleDirectories_IncludesAll()
{
@ -224,30 +201,6 @@ public class ManagedArchiveTests : IDisposable
Assert.Equal(-1, count);
}
[Theory]
[InlineData(1)]
[InlineData(3)]
[InlineData(10)]
public void CreateTarZstd_DifferentCompressionLevels_AllWork(int level)
{
// Arrange
var sourceDir = CreateTestDirectory($"level-{level}", ("data.txt", new string('X', 10000)));
var archivePath = Path.Combine(_testDir, $"level-{level}.tar.zst");
// Act
var entryCount = ManagedArchive.CreateTarZstd(
[sourceDir], archivePath, _testDir, compressionLevel: level
);
// Assert
Assert.Equal(1, entryCount);
Assert.True(File.Exists(archivePath));
// Verify we can extract it back
var extractDir = Path.Combine(_testDir, $"extract-level-{level}");
Assert.True(ManagedArchive.ExtractTarZstd(archivePath, extractDir));
}
[Fact]
public void ExtractTarGz_RoundTrips()
{