diff --git a/tests/Aetheria.Shared.Tests/LoadoutTests.cs b/tests/Aetheria.Shared.Tests/LoadoutTests.cs index f95d67047..acb54ac95 100644 --- a/tests/Aetheria.Shared.Tests/LoadoutTests.cs +++ b/tests/Aetheria.Shared.Tests/LoadoutTests.cs @@ -312,38 +312,6 @@ public sealed class LoadoutTests : IDisposable Assert.Contains("slot 0,0: Crate does not fit", failure); } - // Two new makers, each with one Lamp product, upserted into the live cache so its enumeration order (z before a) - // disagrees with record-key order; a reopened snapshot could already hand them back sorted. Each gets its own - // maker rather than sharing "Maker". - [Fact] - public void FirstAvailableProductInKeyOrderBuildsTheSlot() - { - using var cache = AetheriaStores.Open(Catalog, catalogWritable: true); - var lamp = new CultRecordRef(cache.RefOf(cache.GetByName("Lamp")).Key); - var zMaker = cache.Upsert(new Faction { Name = "Zeta", ShortName = "ZET" }); - var aMaker = cache.Upsert(new Faction { Name = "Alpha", ShortName = "ALP" }); - cache.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData { Name = "lamp-z", Design = lamp, Manufacturer = zMaker }, new CultRecordKey("lamp-z"))); - cache.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData { Name = "lamp-a", Design = lamp, Manufacturer = aMaker }, new CultRecordKey("lamp-a"))); - Assert.Equal(new[] { "lamp-z", "lamp-a" }, cache.GetAll().Select(p => p.Name).Where(name => name.StartsWith("lamp-"))); - - var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); - var hand = HandBuilt(cache); - string LampProduct(Predicate available, List failures) - { - var ship = Loadouts.Materialize(items, null, hand, available, failures); - if (ship == null) return null; - var unit = ship.Equipment.Single(item => item.EquippableItem != ship.Hull && item.Position.Equals(HardpointCell)).EquippableItem; - return items.Brand(unit).Product.Name; - } - - var failures = new List(); - Assert.Equal("lamp-a", LampProduct(p => p.Name != "Lamp by Maker", failures)); - Assert.Equal("lamp-z", LampProduct(p => p.Name != "Lamp by Maker" && p.Name != "lamp-a", failures)); - Assert.Empty(failures); - Assert.Null(LampProduct(p => !p.Name.StartsWith("Lamp") && !p.Name.StartsWith("lamp"), failures)); - Assert.Contains("slot 0,0: no available product of Lamp", Assert.Single(failures)); - } - // Scenarios Q3 (docs/scenarios-cut.md): a design no product makes is outside the economy, and a preset builds it // unbranded -- no maker -- at the one named quality. "Orphan" has no product in this catalog. [Fact] @@ -368,7 +336,7 @@ public sealed class LoadoutTests : IDisposable using var cache = Open(); var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); var failures = new List(); - Assert.Null(Loadouts.Materialize(items, null, HandBuilt(cache), p => p.Name != "Lamp by Maker", failures)); + Assert.Null(Loadouts.Materialize(items, null, HandBuilt(cache), _ => null, failures)); Assert.Equal("slot 0,0: no available product of Lamp", Assert.Single(failures)); } @@ -918,9 +886,17 @@ public sealed class LoadoutTests : IDisposable Assert.Equal(originalThreshold, template.ShutdownPerformance); } - // Everything available: for tests about placement and failure lists. + // The deterministic chooser for tests about placement and failure lists: the design's only product, and nothing (so a + // failure) when it has several. + internal static Func SoleProduct(CultCache cache) => design => + { + var key = cache.RefOf(design).Key; + var made = cache.GetAll().Where(p => p.Design.Key.Equals(key)).Take(2).ToArray(); + return made.Length == 1 ? made[0] : null; + }; + private static Entity Build(ItemManager items, Loadout loadout, List failures) => - Loadouts.Materialize(items, null, loadout, _ => true, failures); + Loadouts.Materialize(items, null, loadout, SoleProduct(items.ItemData), failures); private static (int2, ItemRotation, CultRecordKey) Describe(LoadoutSlot slot) => (slot.Position, slot.Rotation, slot.Design.Key); diff --git a/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs new file mode 100644 index 000000000..95659cd54 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using CultMath; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; +using Random = CultMath.Random; + +// Ruling loadout-product-optional-context-chooses: a slot or fit may name a product; a design-only slot is chosen by +// the outfitter (LoadoutGenerator.ChooseProduct), never by record-key order. +public sealed class ProductChoiceTests : IDisposable +{ + private static readonly int2 HardpointCell = new int2(0, 0); + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-productchoice-" + Guid.NewGuid().ToString("N")); + private readonly List _caches = new List(); + private int _catalogs; + + public ProductChoiceTests() => Directory.CreateDirectory(_root); + + public void Dispose() + { + foreach (var cache in _caches) cache.Dispose(); + Directory.Delete(_root, true); + } + + // One Skiff (made by Alpha only) and one Lamp with a product from each of Alpha and Zeta. Two outfitting factions: + // OutA's allegiance names only Alpha, OutZ's only Zeta. lampKeys are the Lamp products' record keys in insertion + // order [lamp-z, lamp-a], so a permutation shuffles both keys and enumeration. + private sealed class Rig + { + public CultCache Cache; + public ItemManager Items; + public Galaxy Galaxy; + public Faction OutA, OutZ; + + public LoadoutGenerator Outfitter(Faction faction, uint seed) + { + var random = new Random(seed); + return new LoadoutGenerator(ref random, Items, faction == null ? null : Galaxy, null, faction, .5f); + } + + public FactionProductData Product(string name) => Cache.GetAll().Single(p => p.Name == name); + public CultRecordRef ProductRef(string name) => Cache.RefOf(Product(name)); + + public Loadout Fit(CultRecordRef lamp = default) => new Loadout + { + Name = "Lamp skiff", + Hull = Cache.RefOf(Cache.GetByName("Skiff")), + HullProduct = ProductRef("Skiff by Alpha"), + Slots = { new LoadoutSlot { Position = HardpointCell, Design = Cache.RefOf(Cache.GetByName("Lamp")), Product = lamp } }, + WeaponGroups = new int[0][] + }; + + public string LampBrand(Entity ship) + { + var unit = ship.Equipment.Single(item => item.EquippableItem != ship.Hull && item.Position.Equals(HardpointCell)).EquippableItem; + return Items.Brand(unit).Product.Name; + } + } + + private Rig Build(params string[] lampOrder) + { + var root = Path.Combine(_root, "rig" + _catalogs++); + Directory.CreateDirectory(root); + var catalog = Path.Combine(root, "Aetheria.cc"); + using (var seed = AetheriaStores.Open(catalog, catalogWritable: true)) + { + seed.Upsert(new VerseGrammar { Revision = 1 }); + var alpha = seed.Upsert(new Faction { Name = "Alpha", ShortName = "ALP" }); + var zeta = seed.Upsert(new Faction { Name = "Zeta", ShortName = "ZET" }); + var mu = seed.Upsert(new Faction { Name = "Mu", ShortName = "MU" }); + seed.Upsert(new Faction { Name = "OutA", ShortName = "OTA", Allegiance = { { alpha, 1f } } }); + seed.Upsert(new Faction { Name = "OutZ", ShortName = "OTZ", Allegiance = { { zeta, 1f } } }); + var shape = new Shape(3, 3); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var skiff = seed.Upsert(new HullData + { + Name = "Skiff", HullType = HullType.Ship, Shape = shape, Price = 100, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() } } + }); + var lamp = seed.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10 }); + void Sell(string name, CultRecordKey design, CultRecordRef maker, string key) => + seed.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData + { Name = name, Design = new CultRecordRef(design), Manufacturer = maker }, new CultRecordKey(key))); + Sell("Skiff by Alpha", skiff.Key, alpha, "skiff-a"); + var makers = new Dictionary> { ["lamp-a"] = alpha, ["lamp-z"] = zeta, ["lamp-m"] = mu }; + // lampOrder holds product names; the record key of the i-th inserted is "k" + i, so keys and insertion order + // both follow the permutation. + for (var i = 0; i < lampOrder.Length; i++) Sell(lampOrder[i], lamp.Key, makers[lampOrder[i]], "k" + i); + seed.FlushAsync().Wait(); + } + + var cache = AetheriaStores.Open(catalog, Path.Combine(root, "run.cc"), Path.Combine(root, "player.cc")); + _caches.Add(cache); + var outA = cache.GetByName("OutA"); + var outZ = cache.GetByName("OutZ"); + var game = new SavedGame + { + Factions = new[] { cache.RefOf(outA), cache.RefOf(outZ) }, + Relationships = new[] { FactionRelationship.Neutral, FactionRelationship.Neutral }, + HomeZones = new Dictionary { { 0, 0 }, { 1, 0 } }, + BossZones = new Dictionary(), + DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], + Exit = -1 + }; + var zones = new[] + { + new SavedZone { Name = "Zone 0", Position = new float2(0, 0), AdjacentZones = Array.Empty(), Factions = new[] { 0, 1 }, Owner = 0, Contents = null } + }; + RunSave.Commit(cache, game, zones, new ProvenanceLedger()); + return new Rig + { + Cache = cache, OutA = outA, OutZ = outZ, + Items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }), + Galaxy = new Galaxy(cache, cache.GetGlobal(), _ => { }) + }; + } + + private static Entity Materialize(Rig rig, Loadout loadout, Func choose, List failures) => + Loadouts.Materialize(rig.Items, null, loadout, choose, failures); + + [Fact] + public void ADifferentOutfitterChoosesADifferentProduct() + { + var rig = Build("lamp-z", "lamp-a"); + var failures = new List(); + Assert.Equal("lamp-a", rig.LampBrand(Materialize(rig, rig.Fit(), rig.Outfitter(rig.OutA, 1).ChooseProduct, failures))); + Assert.Equal("lamp-z", rig.LampBrand(Materialize(rig, rig.Fit(), rig.Outfitter(rig.OutZ, 1).ChooseProduct, failures))); + Assert.Empty(failures); + } + + [Fact] + public void ANullFactionDrawIsSeededAndReachesEveryMaker() + { + var rig = Build("lamp-z", "lamp-a"); + var lamp = rig.Cache.GetByName("Lamp"); + Assert.Equal(rig.Outfitter(null, 7).ChooseProduct(lamp).Name, rig.Outfitter(null, 7).ChooseProduct(lamp).Name); + var seen = Enumerable.Range(1, 64).Select(seed => rig.Outfitter(null, (uint) seed).ChooseProduct(lamp).Name).Distinct().OrderBy(name => name).ToArray(); + Assert.Equal(new[] { "lamp-a", "lamp-z" }, seen); + } + + [Fact] + public void APinnedProductIsBuiltInEveryContext() + { + var rig = Build("lamp-z", "lamp-a"); + var failures = new List(); + var pinned = rig.Fit(rig.ProductRef("lamp-z")); + Assert.Equal("lamp-z", rig.LampBrand(Materialize(rig, pinned, rig.Outfitter(rig.OutA, 1).ChooseProduct, failures))); + Assert.Equal("lamp-z", rig.LampBrand(Materialize(rig, pinned, _ => null, failures))); + Assert.Empty(failures); + + var foreign = rig.Fit(rig.ProductRef("Skiff by Alpha")); + Assert.Null(Materialize(rig, foreign, rig.Outfitter(null, 1).ChooseProduct, failures)); + Assert.Equal("slot 0,0: product Skiff by Alpha is not a product of Lamp", Assert.Single(failures)); + } + + [Fact] + public void ShuffledKeysDoNotChangeTheChoice() + { + var orders = new[] { new[] { "lamp-a", "lamp-m", "lamp-z" }, new[] { "lamp-z", "lamp-a", "lamp-m" }, new[] { "lamp-m", "lamp-z", "lamp-a" } }; + var rigs = orders.Select(order => Build(order)).ToArray(); + foreach (var faction in new Func[] { _ => null, rig => rig.OutA }) + for (uint seed = 1; seed <= 16; seed++) + { + var chosen = rigs.Select(rig => rig.Outfitter(faction(rig), seed).ChooseProduct(rig.Cache.GetByName("Lamp"))?.Name).Distinct().ToArray(); + Assert.Single(chosen); + } + } + + [Fact] + public void CaptureKeepsTheLotsProduct() + { + var rig = Build("lamp-z", "lamp-a"); + var failures = new List(); + var ship = Materialize(rig, rig.Fit(rig.ProductRef("lamp-z")), rig.Outfitter(rig.OutA, 1).ChooseProduct, failures); + var captured = Loadouts.Capture(rig.Items, ship, "captured"); + Assert.Equal(rig.ProductRef("lamp-z").Key, captured.Slots.Single().Product.Key); + Assert.Equal(rig.ProductRef("Skiff by Alpha").Key, captured.HullProduct.Key); + + var rebuilt = Materialize(rig, captured, _ => null, failures); + Assert.Empty(failures); + Assert.Equal("lamp-z", rig.LampBrand(rebuilt)); + Assert.Equal("Skiff by Alpha", rig.Items.Brand(rebuilt.Hull).Product.Name); + } + + [Fact] + public void AChooserOfAnotherDesignIsRefused() + { + var rig = Build("lamp-z", "lamp-a"); + var failures = new List(); + Assert.Null(Materialize(rig, rig.Fit(), _ => rig.Product("Skiff by Alpha"), failures)); + Assert.Equal("slot 0,0: product Skiff by Alpha is not a product of Lamp", Assert.Single(failures)); + } + + // The wire positions of the new fields: a preset written by one build is read by the next. + [Fact] + public void TheProductRefsSitAtTheirWirePositions() + { + Assert.Equal(4, typeof(Loadout).GetField(nameof(Loadout.HullProduct)).GetCustomAttribute().IntKey); + Assert.Equal(3, typeof(LoadoutSlot).GetField(nameof(LoadoutSlot.Product)).GetCustomAttribute().IntKey); + } +} diff --git a/tests/Aetheria.Shared.Tests/RigBrandTests.cs b/tests/Aetheria.Shared.Tests/RigBrandTests.cs new file mode 100644 index 000000000..fe063107f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/RigBrandTests.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using System.Linq; +using Xunit; + +// Ruling loadout-product-optional-context-chooses: a rig whose test reads stats names the brand it was measured on, and +// staging builds exactly that brand whatever the stage's seed draws for open designs. The fixture is RunStartTests'. +public sealed partial class RunStartTests +{ + private string ProductOf(EquippableItem item) => _items.Brand(item).Product.Name; + + private IEnumerable FittedBrands(Entity entity, string design) => + entity.Equipment.Where(item => _items.GetData(item.EquippableItem).Name == design).Select(item => ProductOf(item.EquippableItem)); + + [Fact] + public void TheRigsKeepTheirBrands() + { + var pursuit = Launch(new Pursuit(), Inputs(() => GalaxySeed)); + Assert.Empty(pursuit.failures); + Assert.Equal(new[] { "parting gift" }, FittedBrands(pursuit.staged.Player, "Mine Launcher")); + Assert.Equal(new[] { "Leonid" }, FittedBrands(pursuit.staged.Player, "Swarm Rocket Pod")); + + var duel = Launch(new Duel(), Inputs(() => GalaxySeed)); + Assert.Empty(duel.failures); + var rival = Assert.Single(duel.staged.Entities); + Assert.Equal(new[] { "Spectra" }, Held(rival).Select(item => _items.Brand(item).Product.Name)); + + var arcs = Launch(new Arcs(), Inputs(() => GalaxySeed)); + Assert.Empty(arcs.failures); + Assert.Equal(new[] { "🫳🔫" }, FittedBrands(arcs.staged.Player, "Autocannon")); + } +} diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index 5ad89c639..18286649d 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -662,7 +662,7 @@ public sealed partial class RunStartTests : IDisposable foreach (var hull in new[] { Hull("Djinni"), Hull("Longinus"), TurretHull() }) { var failures = new List(); - var entity = Loadouts.Materialize(_items, null, BareLoadout(hull), available.IsAvailable, failures); + var entity = Loadouts.Materialize(_items, null, BareLoadout(hull), available.ChooseProduct, failures); Assert.Empty(failures); Assert.NotNull(_items.Brand(entity.Hull).Maker); } @@ -681,7 +681,7 @@ public sealed partial class RunStartTests : IDisposable Assert.True(ships.Count > 1); foreach (var ship in ships) Assert.Equal(ship.IsPlayerShip ? 0 : 1, AgentsOf(zone, ship)); - var arriving = (Ship) Loadouts.Materialize(_items, zone, BareLoadout(Hull("Djinni")), _ => true, new List()); + var arriving = (Ship) Loadouts.Materialize(_items, zone, BareLoadout(Hull("Djinni")), new LoadoutGenerator(ref _items.Random, _items, _galaxy, _galaxy.Entrance, null, 2).ChooseProduct, new List()); var agents = zone.Agents.Count; zone.Admit(arriving, piloted: false); SafeAssert.In(zone, arriving, "the arrival is admitted");