Merge nibu/ammo-tail into nibu/suite-honest

This commit is contained in:
Nibu 2026-11-11 05:15:55 +00:00
commit 663d054b02
15 changed files with 252 additions and 39 deletions

View file

@ -166,4 +166,32 @@ public sealed partial class RunStartTests
}
Assert.True(fed > 0, "fixture: some new-run player ship carries an ammunition-fed weapon");
}
// The HUD's ammunition label (Weapon.AmmoReadout): a magazine gun reads "magazine/reserve", a beam that names an AmmoType has no magazine (it
// draws a crate per interval) and reads its reserve alone, a weapon that draws nothing reads empty. Kills: a label that prints the beam's
// never-filled magazine as "0/N", or one that drops the magazine from a gun's.
[Fact]
public void TheAmmoLabelShowsAMagazineOnlyForAWeaponThatHasOne()
{
var (hull, _) = FedFit(bay: true);
var rounds = _cache.GetAll<WeaponItemData>().Single(item => item.Name == "Fed Gun").Behaviors.OfType<WeaponData>().Single().AmmoType;
_cache.Upsert(new WeaponItemData
{
Name = "Fed Beam", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1,
Behaviors = { new ConstantWeaponData { AmmoType = rounds } }
});
EquippableItemData Design(string name) => _cache.GetAll<EquippableItemData>().Single(item => item.Name == name);
var loadout = new Loadout { Name = "label", Hull = _cache.RefOf(_cache.GetAll<HullData>().Single(h => h.Name == hull)), WeaponGroups = new int[0][] };
foreach (var (name, x) in new[] { ("Fed Gun", 3), ("Fed Beam", 2), ("Plain Gun", 1), ("Fed Bay", 4) })
loadout.Slots.Add(new LoadoutSlot { Position = int2(x, 3), Rotation = ItemRotation.None, Design = _cache.RefOf(Design(name)) });
var failures = new List<string>();
var ship = Loadouts.Materialize(_items, null, loadout, _ => null, failures);
Assert.True(failures.Count == 0, string.Join("; ", failures));
string Label(string name) => ship.Weapons.Single(weapon => _items.GetData(weapon.Item.EquippableItem).Name == name).AmmoReadout;
var reserve = LoadoutGenerator.AmmunitionCrates;
Assert.Equal(reserve.ToString(), Label("Fed Beam"));
Assert.Equal($"{ship.Weapons.Single(w => _items.GetData(w.Item.EquippableItem).Name == "Fed Gun").Ammo}/{reserve}", Label("Fed Gun"));
Assert.Equal("", Label("Plain Gun"));
}
}

View file

@ -5,6 +5,38 @@ using System.Linq;
using GameCult.Caching;
using Xunit;
// What the calling thread writes to Console while an action runs. Console is process-global and tests run in parallel, so a plain
// SetOut capture also collects other tests' diagnostic prints (the race that failed these tests in full-suite runs): the probe
// keeps only writes made on the thread that runs the action, and the gate keeps two probes from restoring each other's writer.
internal static class ConsoleProbe
{
private static readonly object Gate = new object();
public static string WrittenBy(Action act)
{
lock (Gate)
{
var previous = Console.Out;
var probe = new ThreadWriter(Environment.CurrentManagedThreadId);
Console.SetOut(probe);
try { act(); }
finally { Console.SetOut(previous); }
return probe.Mine.ToString();
}
}
private sealed class ThreadWriter : TextWriter
{
private readonly int _thread;
public readonly System.Text.StringBuilder Mine = new System.Text.StringBuilder();
public ThreadWriter(int thread) => _thread = thread;
public override System.Text.Encoding Encoding => System.Text.Encoding.UTF8;
public override void Write(char value) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(value); }
public override void Write(string value) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(value); }
public override void Write(char[] buffer, int index, int count) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(buffer, index, count); }
}
}
public sealed class EconomyCommandTests
{
private sealed class Lambda : EconomyBatch
@ -146,10 +178,19 @@ public sealed class EconomyCommandTests
public void TheTrialCopyIsRemoved()
{
using var f = EconomyFixture.Healthy();
var before = Directory.GetDirectories(Path.GetTempPath(), "aetherdb-economy-*").Length;
Author(f, false, out _, a => Good(f, a, "coal"));
Author(f, true, out _, a => Good(f, a, "tar", lore: ""));
Assert.Equal(before, Directory.GetDirectories(Path.GetTempPath(), "aetherdb-economy-*").Length);
// A private scratch root: the temp folder is shared with every parallel test that runs the command, so counting it races.
var scratchRoot = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-economy-audit-" + Guid.NewGuid().ToString("N"))).FullName;
try
{
foreach (var apply in new[] { false, true })
{
Flush(f);
var batch = new Lambda(a => Good(f, a, apply ? "tar" : "coal", lore: apply ? "" : "a good"));
EconomyCommand.Author(f.CatalogPath, new EconomyBatch[] { batch }, apply, new StringWriter(), TestCatalog.Registry(), scratchRoot);
}
Assert.Empty(Directory.GetFileSystemEntries(scratchRoot));
}
finally { Directory.Delete(scratchRoot, true); }
}
[Fact]
@ -286,17 +327,13 @@ public sealed class EconomyCommandTests
using var db = AetherDb.Open();
var expected = new StringWriter();
var expectedCode = EconomyCommand.Report(db.Cache, expected);
var console = new StringWriter();
var previous = Console.Out;
Console.SetOut(console);
var output = new StringWriter();
int code;
try { code = EconomyCommand.Run(new[] { "report" }, output); }
finally { Console.SetOut(previous); }
int code = 0;
var console = ConsoleProbe.WrittenBy(() => code = EconomyCommand.Run(new[] { "report" }, output));
Assert.Equal(expectedCode, code);
Assert.NotEmpty(expected.ToString());
Assert.Equal(expected.ToString(), output.ToString());
Assert.Empty(console.ToString());
Assert.Empty(console);
}
[Fact]
@ -306,17 +343,13 @@ public sealed class EconomyCommandTests
var before = File.ReadAllBytes(path);
var expected = new StringWriter();
var expectedCode = EconomyCommand.Author(path, new EconomyBatch[] { new Munitions() }, false, expected);
var console = new StringWriter();
var previous = Console.Out;
Console.SetOut(console);
var output = new StringWriter();
int code;
try { code = EconomyCommand.Run(new[] { "author", "Munitions" }, output); }
finally { Console.SetOut(previous); }
int code = 0;
var console = ConsoleProbe.WrittenBy(() => code = EconomyCommand.Run(new[] { "author", "Munitions" }, output));
Assert.Equal(expectedCode, code);
Assert.NotEmpty(expected.ToString());
Assert.Equal(expected.ToString(), output.ToString());
Assert.Empty(console.ToString());
Assert.Empty(console);
Assert.Equal(before, File.ReadAllBytes(path));
}

View file

@ -0,0 +1,67 @@
using System.Collections.Generic;
using System.Linq;
using UniRx;
using Xunit;
// Scenarios that author a weapon's ammunition-fed crates in a hold (ruling ballistics-real-ammo): the staged hold is what the weapon reloads from, so a
// scenario whose check rests on a weapon firing past its first magazine states the crates it needs. Each test launches through the production path.
public sealed partial class RunStartTests
{
// The Arcs turret fits two Light Machine Guns of a hundred rounds and a bay of Ammo: its hold holds what the scenario states, and across a minute
// in range of the player it fires past both first magazines, each reload taking a crate. Kills: a turret fit without a bay or with no authored
// crates (silent after one magazine), and Cargo failing to admit a commodity.
[Fact]
public void TheArcsTurretKeepsFiringPastItsFirstMagazine()
{
var (_, arena, staged, failures) = Launch(new Arcs(), Inputs(() => GalaxySeed));
Assert.Empty(failures);
var player = staged.Player;
var turret = Assert.IsType<OrbitalEntity>(staged.Entities[2]);
var guns = turret.Weapons.ToList();
Assert.Equal(2, guns.Count);
var ammo = guns[0].WeaponData.AmmoType.Key;
Assert.Equal(Arcs.TurretAmmoCrates, turret.CountItemsInCargo(ammo));
// The guns are Auto weapons: they fire on a hostile inside their range (400 m) with no pilot. The player starts 775 m off, so it flies up to 200 m.
arena.Update(0);
player.Position = turret.Position + new CultMath.float3(-200, 0, 0);
var shots = 0;
using var sub = arena.ShotCommitted.Subscribe(outcome => { if (ReferenceEquals(outcome.Source, turret)) shots++; });
for (var tick = 0; tick < System.MathF.Round(60f / SimClock.GameStep); tick++) arena.Update(SimClock.GameStep);
var firstMagazines = guns.Sum(gun => gun.WeaponData.MagazineSize);
Assert.True(shots > firstMagazines, $"the turret fired {shots} rounds, no more than its two first magazines of {firstMagazines}");
Assert.True(turret.CountItemsInCargo(ammo) < Arcs.TurretAmmoCrates, "the turret reloaded without taking a crate");
}
// The Pursuit player's Mine Launcher draws its magazine of six from crates of Mines it carries beside the consumables: it lays past six, and the
// crate count falls by one per reload. Kills: authored cargo with no Mines (at most six mines), a reload that takes no crate.
[Fact]
public void ThePursuitPlayerLaysMoreThanOneMagazineOfMinesFromItsCrates()
{
var (_, arena, staged, failures) = Launch(new Pursuit(), Inputs(() => GalaxySeed));
Assert.Empty(failures);
var player = staged.Player;
var launcher = player.Weapons.Single(weapon => weapon.WeaponData is MineLayerData);
var mines = launcher.WeaponData.AmmoType.Key;
Assert.Equal(Pursuit.MineCrates, player.CountItemsInCargo(mines));
Assert.Equal(3, HeldOf(player, "Coolant Vent"));
arena.Update(0);
var laid = 0;
using var sub = arena.Mines.ObserveAdd().Subscribe(_ => laid++);
var reloaded = new List<int>();
var last = Pursuit.MineCrates;
for (var tick = 0; tick < System.MathF.Round(120f / SimClock.GameStep) && laid <= 18; tick++)
{
launcher.Activate();
arena.Update(SimClock.GameStep);
var crates = player.CountItemsInCargo(mines);
if (crates != last) { reloaded.Add(last - crates); last = crates; }
}
Assert.True(laid > launcher.WeaponData.MagazineSize, $"the player laid {laid} mines, no more than one magazine of {launcher.WeaponData.MagazineSize}");
Assert.NotEmpty(reloaded);
Assert.All(reloaded, step => Assert.Equal(1, step));
}
}

View file

@ -0,0 +1,37 @@
using System.Linq;
using GameCult.Caching;
using Xunit;
// A station kind's description is what a player and a planner read of what it does; the recipes at the kind are what it does.
public sealed class StationKindDescriptionTests
{
// Every good the shipped catalog extracts at a station kind (a commodity recipe with no inputs; a gear recipe is a design on offer, not raw) is named in that kind's description.
// Kills: a kind that gains an extraction recipe (Diamond at mining, Ammonia at volatiles) while its description still lists the old set.
[Fact]
public void EveryRawGoodAKindExtractsIsNamedInItsDescription()
{
using var db = AetherDb.Open();
var cache = db.Cache;
var unnamed = cache.GetAll<RecipeData>().Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet())
.Select(recipe => (Kind: cache.Get(recipe.StationKind), Output: cache.Get(recipe.Output)))
.Where(pair => pair.Kind != null && (pair.Output is SimpleCommodityData || pair.Output is CompoundCommodityData) && !pair.Kind.Description.Contains(pair.Output.Name))
.Select(pair => $"{pair.Kind.Name} extracts {pair.Output.Name}, which its description omits")
.Distinct().OrderBy(line => line).ToList();
Assert.True(unnamed.Count == 0, string.Join("\n", unnamed));
}
// The two kinds the rule was cut for, by name, so the rule cannot pass by the catalog having lost the recipes.
[Fact]
public void MiningExtractsDiamondAndVolatilesAmmonia()
{
using var db = AetherDb.Open();
var cache = db.Cache;
string Extracted(string kindId) => string.Join(",", cache.GetAll<RecipeData>()
.Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet() && recipe.StationKind.Key.Equals(StationKindData.KeyOf(kindId)))
.Select(recipe => cache.Get(recipe.Output).Name));
Assert.Contains("Diamond", Extracted("mining"));
Assert.Contains("Ammonia", Extracted("volatiles"));
Assert.Contains("Diamond", cache.Get<StationKindData>(StationKindData.KeyOf("mining")).Description);
Assert.Contains("Ammonia", cache.Get<StationKindData>(StationKindData.KeyOf("volatiles")).Description);
}
}