CI / build (push) Successful in 57s
BotHost.Decisions is the default decision maker for seats without a Decisions= token (builtin overrides it). 'first' answers from the request's JSON alone, sums and counters included. MSG_SORT_CHAIN, the field-first card prompt and the effect prompt of an unknown card now ask the maker too (built-in answers unchanged); only prompts with no choice are answered without asking, and seats with a maker log their counts per duel. Tests: the built-in --seed 7 report equals the v0.1.0 release's (tests/fixture/expected, clocks aside); first vs first, 100 duels: 15952 prompts asked, 0 handed back, 0 errors, unasked only 'chain: nothing to chain'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
218 lines
12 KiB
C#
218 lines
12 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using Newtonsoft.Json.Linq;
|
|
using NUnit.Framework;
|
|
|
|
namespace YGOLegacy.Bots.Tests
|
|
{
|
|
/// The published Linux arena, end to end: `--host local` on the pinned engine, on tests/fixture/game.
|
|
[TestFixture, NonParallelizable]
|
|
public class ArenaTests
|
|
{
|
|
private const int Duels = 100;
|
|
private const int Seed = 7;
|
|
|
|
// What differs between two runs of the same duels: clocks, the worker count and where the report went.
|
|
private static readonly HashSet<string> Clocks = new()
|
|
{
|
|
"startedAt", "totalSeconds", "wallClockSeconds", "durationSeconds", "coreMs", "summary", "reportPath",
|
|
"workers", "outPath",
|
|
};
|
|
|
|
private static string Exe
|
|
{
|
|
get
|
|
{
|
|
var exe = Environment.GetEnvironmentVariable("BOTARENA_EXE");
|
|
if (string.IsNullOrEmpty(exe)) Assert.Ignore("BOTARENA_EXE is not set (the Docker test stage sets it)");
|
|
return exe;
|
|
}
|
|
}
|
|
|
|
private static (int code, string stdout, string stderr) Run(string root, params string[] args)
|
|
{
|
|
var psi = new ProcessStartInfo(Exe)
|
|
{
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
UseShellExecute = false,
|
|
};
|
|
psi.ArgumentList.Add("--root");
|
|
psi.ArgumentList.Add(root);
|
|
foreach (var a in args) psi.ArgumentList.Add(a);
|
|
using var p = Process.Start(psi);
|
|
var stderr = p.StandardError.ReadToEndAsync();
|
|
var stdout = p.StandardOutput.ReadToEnd();
|
|
if (!p.WaitForExit(600_000)) { p.Kill(true); Assert.Fail("the arena did not finish in 10 minutes"); }
|
|
TestContext.Progress.WriteLine(stdout.Trim());
|
|
return (p.ExitCode, stdout, stderr.Result);
|
|
}
|
|
|
|
private static JObject Duel(string root, int n, int parallel, int seed, string outFile, params string[] more)
|
|
{
|
|
var args = new List<string> { "--deckA", "AI_OldSchool", "--deckB", "AI_OldSchool",
|
|
"--n", n.ToString(), "--parallel", parallel.ToString(), "--seed", seed.ToString(), "--host", "local",
|
|
"--out", outFile };
|
|
args.AddRange(more);
|
|
var (code, stdout, stderr) = Run(root, args.ToArray());
|
|
Assert.That(code, Is.EqualTo(0), "exit code; stderr:\n" + stderr);
|
|
return JObject.Parse(File.ReadAllText(outFile));
|
|
}
|
|
|
|
private static JToken WithoutClocks(JToken token)
|
|
{
|
|
var copy = token.DeepClone();
|
|
foreach (var p in copy.SelectTokens("$..*").OfType<JValue>().Select(v => v.Parent).OfType<JProperty>().ToList())
|
|
if (Clocks.Contains(p.Name)) p.Remove();
|
|
return copy;
|
|
}
|
|
|
|
[Test]
|
|
public void HundredDuelsOfABotDeckAgainstItselfHaveNoErrors()
|
|
{
|
|
var root = Fixture.CopyRoot();
|
|
var report = Duel(root, Duels, 4, Seed, Path.Combine(root, "run-1.json"));
|
|
TestContext.Progress.WriteLine("winsA " + report["winsA"] + ", winsB " + report["winsB"] + ", draws " + report["draws"]
|
|
+ ", errors " + report["errors"] + ", average turns " + report["averageTurns"]);
|
|
Assert.That((string)report["status"], Is.EqualTo("done"));
|
|
Assert.That((int)report["completed"], Is.EqualTo(Duels));
|
|
Assert.That((int)report["errors"], Is.EqualTo(0), string.Join("\n", report["duels"].Where(d => d["error"]?.Type == JTokenType.String).Select(d => d["index"] + ": " + d["error"])));
|
|
Assert.That((int)report["winsA"] + (int)report["winsB"] + (int)report["draws"], Is.EqualTo(Duels));
|
|
Assert.That((string)report["nameA"], Is.EqualTo("Old School A"), "the deck's owning character names the seat");
|
|
Assert.That((string)report["commandA"], Does.Contain("Deck=Smart"), "and its brain plays it");
|
|
Assert.That(Directory.GetFiles(Path.Combine(root, "Data", "BotArena"), "*.json"), Has.Length.EqualTo(1), "the canonical report");
|
|
}
|
|
|
|
[Test]
|
|
public void TheSameSeedGivesTheSameReport()
|
|
{
|
|
var root = Fixture.CopyRoot();
|
|
var first = Duel(root, Duels, 4, Seed, Path.Combine(root, "seed-1.json"));
|
|
var second = Duel(root, Duels, 2, Seed, Path.Combine(root, "seed-2.json"));
|
|
Assert.That((int)first["completed"], Is.EqualTo(Duels));
|
|
var a = WithoutClocks(first);
|
|
var b = WithoutClocks(second);
|
|
Assert.That(JToken.DeepEquals(a, b), Is.True, "reports differ:\n" + a + "\n----\n" + b);
|
|
var other = WithoutClocks(Duel(root, Duels, 4, Seed + 1, Path.Combine(root, "seed-3.json")));
|
|
Assert.That(JToken.DeepEquals(a["duels"], other["duels"]), Is.False, "another seed plays other duels");
|
|
}
|
|
|
|
private static IEnumerable<string> WorkerLog(string root)
|
|
=> Directory.GetFiles(Path.Combine(root, "Data", "BotArena", "logs"), "worker-*.log", SearchOption.AllDirectories)
|
|
.SelectMany(File.ReadLines);
|
|
|
|
private static string[] SeamWarnings(string root)
|
|
=> WorkerLog(root).Where(l => l.Contains("[warn] [YGOL decisions]")).ToArray();
|
|
|
|
// "[YGOL decisions] counts <seat>: asked=N (kind xN, ...) handedBack=N unasked=N (kind: reason xN, ...)",
|
|
// one line per seat with a decision maker, at the end of each duel.
|
|
private static (int asked, int handedBack, Dictionary<string, int> askedKinds, Dictionary<string, int> unasked) SeamCounts(string root)
|
|
{
|
|
int asked = 0, handedBack = 0;
|
|
var askedKinds = new Dictionary<string, int>();
|
|
var unasked = new Dictionary<string, int>();
|
|
var line = new System.Text.RegularExpressions.Regex(@"\[YGOL decisions\] counts .*?: asked=(\d+)(?: \(([^)]*)\))? handedBack=(\d+) unasked=\d+(?: \(([^)]*)\))?$");
|
|
void Add(Dictionary<string, int> into, string list)
|
|
{
|
|
if (string.IsNullOrEmpty(list)) return;
|
|
foreach (var part in list.Split(", "))
|
|
{
|
|
var cut = part.LastIndexOf(" x", StringComparison.Ordinal);
|
|
into.TryGetValue(part.Substring(0, cut), out var n);
|
|
into[part.Substring(0, cut)] = n + int.Parse(part.Substring(cut + 2));
|
|
}
|
|
}
|
|
foreach (var l in WorkerLog(root))
|
|
{
|
|
var m = line.Match(l);
|
|
if (!m.Success) continue;
|
|
asked += int.Parse(m.Groups[1].Value);
|
|
Add(askedKinds, m.Groups[2].Value);
|
|
handedBack += int.Parse(m.Groups[3].Value);
|
|
Add(unasked, m.Groups[4].Value);
|
|
}
|
|
return (asked, handedBack, askedKinds, unasked);
|
|
}
|
|
|
|
// Prompts the seam answers without asking: they offer no choice at all.
|
|
private static readonly HashSet<string> NoChoice = new()
|
|
{
|
|
"chain: nothing to chain", "chain: one forced activation", "position: one position", "rockPaperScissors: fixed by Hand=",
|
|
};
|
|
|
|
[Test]
|
|
public void TheBuiltInBrainPlaysExactlyAsInV010()
|
|
{
|
|
// tests/fixture/expected/v0.1.0-seed7-n100.json is the v0.1.0 release arena's report for this command line.
|
|
var root = Fixture.CopyRoot();
|
|
var now = Duel(root, Duels, 4, Seed, Path.Combine(root, "now.json"));
|
|
var then = JObject.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(Fixture.Source), "expected", "v0.1.0-seed7-n100.json")));
|
|
Assert.That(JToken.DeepEquals(WithoutClocks(now), WithoutClocks(then)), Is.True, "the report differs from v0.1.0's beyond its clocks");
|
|
}
|
|
|
|
[Test]
|
|
public void EveryChoiceGoesThroughTheSeam()
|
|
{
|
|
// Both seats answered by `first`, which reads only each request's JSON. Every prompt with a choice is
|
|
// asked; none is handed back; the only prompts not asked are ones with no choice.
|
|
var root = Fixture.CopyRoot();
|
|
var report = Duel(root, Duels, 4, Seed, Path.Combine(root, "first.json"), "--decisionsA", "first", "--decisionsB", "first");
|
|
Assert.That((int)report["completed"], Is.EqualTo(Duels));
|
|
Assert.That((int)report["errors"], Is.EqualTo(0));
|
|
Assert.That(SeamWarnings(root), Is.Empty);
|
|
var (asked, handedBack, askedKinds, unasked) = SeamCounts(root);
|
|
TestContext.Progress.WriteLine("first vs first: asked " + asked + " (" + string.Join(", ", askedKinds.Select(p => p.Key + " " + p.Value)) + "), handed back "
|
|
+ handedBack + ", not asked " + string.Join(", ", unasked.Select(p => p.Key + " " + p.Value)));
|
|
Assert.That(asked, Is.GreaterThan(1000));
|
|
Assert.That(handedBack, Is.EqualTo(0));
|
|
Assert.That(unasked.Keys.Where(k => !NoChoice.Contains(k)), Is.Empty, "a prompt with a choice bypassed the seam");
|
|
}
|
|
|
|
[Test]
|
|
public void TheDecisionSeamAnswersEveryPromptFromPlainData()
|
|
{
|
|
// Both seats answered by the random maker, which reads only each request's JSON: every prompt of 100
|
|
// duels goes through the seam, and every answer it gives is legal.
|
|
var root = Fixture.CopyRoot();
|
|
var report = Duel(root, Duels, 4, Seed, Path.Combine(root, "random.json"), "--decisionsA", "random", "--decisionsB", "random");
|
|
Assert.That((int)report["completed"], Is.EqualTo(Duels));
|
|
Assert.That((int)report["errors"], Is.EqualTo(0));
|
|
Assert.That((string)report["commandA"], Does.EndWith(" Decisions=random"));
|
|
Assert.That(SeamWarnings(root), Is.Empty, "no prompt fell back to the brain over a bad request or answer");
|
|
Assert.That(SeamCounts(root).unasked.Keys.Where(k => !NoChoice.Contains(k)), Is.Empty);
|
|
var again = Duel(root, Duels, 2, Seed, Path.Combine(root, "random-2.json"), "--decisionsA", "random", "--decisionsB", "random");
|
|
Assert.That(JToken.DeepEquals(WithoutClocks(report), WithoutClocks(again)), Is.True, "a seeded run with makers repeats too");
|
|
}
|
|
|
|
[Test]
|
|
public void TheSeamDecidesAndTheBuiltInBrainIsUnchanged()
|
|
{
|
|
var root = Fixture.CopyRoot();
|
|
var plain = Duel(root, Duels, 4, Seed, Path.Combine(root, "plain.json"));
|
|
var builtIn = Duel(root, Duels, 4, Seed, Path.Combine(root, "builtin.json"), "--decisionsA", "builtin");
|
|
Assert.That(JToken.DeepEquals(WithoutClocks(plain)["duels"], WithoutClocks(builtIn)["duels"]), Is.True,
|
|
"Decisions=builtin is the executor: the same duels");
|
|
var mixed = Duel(root, Duels, 4, Seed, Path.Combine(root, "mixed.json"), "--decisionsA", "random");
|
|
TestContext.Progress.WriteLine("random A vs Smart B: " + mixed["winsA"] + " - " + mixed["winsB"]);
|
|
Assert.That((int)mixed["errors"], Is.EqualTo(0));
|
|
Assert.That((int)mixed["winsB"], Is.GreaterThan((int)mixed["winsA"] * 3), "the Smart brain beats random answers");
|
|
}
|
|
|
|
[Test]
|
|
public void HelpAndBadArguments()
|
|
{
|
|
var root = Fixture.CopyRoot();
|
|
Assert.That(Run(root, "--help").code, Is.EqualTo(0));
|
|
Assert.That(Run(root, "--deckA", "AI_OldSchool").code, Is.EqualTo(2), "--deckB missing");
|
|
Assert.That(Run(root, "--deckA", "AI_OldSchool", "--deckB", "AI_OldSchool", "--host", "wasm").code, Is.EqualTo(2));
|
|
Assert.That(Run(root, "--deckA", "AI_OldSchool", "--deckB", "AI_OldSchool", "--host", "server").code, Is.EqualTo(2), "server is Windows only");
|
|
var (code, stdout, _) = Run(root, "--deckA", "No Such Deck", "--deckB", "AI_OldSchool", "--n", "1");
|
|
Assert.That(code, Is.EqualTo(1), "nothing played");
|
|
Assert.That(stdout, Does.Contain("bad deck A"));
|
|
}
|
|
}
|
|
}
|