From bcd42f50e9592b11d7fe9444c8f9928ed1f1c786 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:55:55 +0100 Subject: [PATCH] cargo horizon-mod test: server mods' scripts A test script drives a server mod as a server would: join = "Alex" brings a player in (ids stable per name, so a rejoin is the same player), as = "Steve" picks who acts (the first player on otherwise), and player, chat, command, break and place are that player's doing; leave = "Alex" lets them go. Server expectations: told (every players.tell, "Name: text") and broadcast; feedback and error read the reply to the player who typed the command. Ticks call both kinds of tick hooks, so one script format serves client and server mods. The welcome example gets two scripts (greeting, a newcomer announced once even after a reload, /online across dimensions, /mined per player), run by the sandbox tests with coords-hud's; docs/mods.md lists the server keys. Co-Authored-By: Claude Opus 5.5 --- .../examples/welcome/tests/commands.toml | 31 +++ .../examples/welcome/tests/welcome.toml | 21 ++ crates/horizon-mods/src/testing.rs | 251 +++++++++++++++++- crates/horizon-mods/tests/sandbox.rs | 32 ++- docs/mods.md | 14 +- 5 files changed, 323 insertions(+), 26 deletions(-) create mode 100644 crates/horizon-mod-sdk/examples/welcome/tests/commands.toml create mode 100644 crates/horizon-mod-sdk/examples/welcome/tests/welcome.toml diff --git a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml new file mode 100644 index 000000000..5f0018346 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml @@ -0,0 +1,31 @@ +# /online lists the players and their dimension; /mined counts the acting player's blocks. + +[[step]] +join = "Alex" +expect.commands = ["online", "mined"] + +[[step]] +join = "Steve" +as = "Steve" +player = { dimension = "minecraft:the_nether" } +command = "online" +expect.feedback = "Alex (overworld), Steve (the_nether)" + +[[step]] +as = "Alex" +break = { x = 1, y = 63, z = 0, state = "minecraft:stone" } + +[[step]] +as = "Alex" +break = { x = 2, y = 63, z = 0, state = "minecraft:dirt" } + +# A step's command comes before its break and place. +[[step]] +as = "Alex" +command = "mined" +expect.feedback = "You broke 2 block(s)" + +[[step]] +as = "Steve" +command = "mined" +expect.feedback = "You broke 0 block(s)" diff --git a/crates/horizon-mod-sdk/examples/welcome/tests/welcome.toml b/crates/horizon-mod-sdk/examples/welcome/tests/welcome.toml new file mode 100644 index 000000000..c8a1836db --- /dev/null +++ b/crates/horizon-mod-sdk/examples/welcome/tests/welcome.toml @@ -0,0 +1,21 @@ +# Joins are greeted; a newcomer is announced once, even after a reload (storage). + +[[step]] +join = "Alex" +expect.told = ["Alex: Welcome, Alex! 0 other player(s) online."] +expect.broadcast = ["Alex is here for the first time"] + +[[step]] +join = "Steve" +expect.told = ["Steve: Welcome, Steve! 1 other player(s) online."] +expect.broadcast = ["Steve is here for the first time"] + +[[step]] +leave = "Alex" +expect.told = [] + +[[step]] +reload = true +join = "Alex" +expect.told = ["Alex: Welcome, Alex! 1 other player(s) online."] +expect.broadcast = [] diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs index 4fcb595a0..31ff27227 100644 --- a/crates/horizon-mods/src/testing.rs +++ b/crates/horizon-mods/src/testing.rs @@ -2,10 +2,14 @@ //! //! [`TestGame`] loads one `.hmod` from a scratch copy (its `storage` lives and //! dies with the run) into the same sandbox the game uses, and plays the game's -//! part: the snapshot, ticks, frames, chat lines and commands. [`Script`] is a +//! part: the snapshot, ticks, frames, chat lines and commands, and for a +//! server mod the players joining, leaving, chatting and breaking or placing +//! blocks. [`Script`] is a //! test written in TOML, `tests/.toml` in the mod's folder: steps, each //! saying what happens and what the mod must have shown by then. -use crate::{Clock, Corner, Mods, Output, Panel, Player, Snapshot, Status}; +use crate::{ + BlockPos, Clock, Corner, GameMode, Mods, Output, Panel, Player, ServerPlayer, Snapshot, Status, +}; use serde::Deserialize; use std::{ path::{Path, PathBuf}, @@ -20,6 +24,10 @@ pub struct TestGame { /// What the mod reads with `game-read`; ticks move the clock as the game does. pub player: Option, pub clock: Option, + /// The players on the server, for a server mod, in join order. + pub players: Vec, + /// Every name that joined, for their id. + names: Vec, tick: u64, } @@ -60,6 +68,8 @@ impl TestGame { game_time: 0, day_time: 0, }), + players: Vec::new(), + names: Vec::new(), tick: 0, }; copy_mod(hmod, ©)?; @@ -87,9 +97,13 @@ impl TestGame { self.mods.set_snapshot(Snapshot { player: self.player.clone(), clock: self.clock, - ..Snapshot::default() + players: self.players.clone(), }); } + /// Whether the mod is a server mod. + pub fn server(&self) -> bool { + self.mods.runs_server() + } /// `n` game ticks; each moves the clock one tick on, as the game does. pub fn tick(&mut self, n: u64) { @@ -101,6 +115,7 @@ impl TestGame { } self.snapshot(); self.mods.tick(self.tick); + self.mods.server_tick(self.tick); } } /// `n` frames, 1/60 s apart. @@ -122,13 +137,76 @@ impl TestGame { self.mods.command(line) } + /// A player named `name` joins the server, standing where a script starts + /// in survival. Their id is `00000000-0000-4000-8000-000000000001` for + /// the first name that joined, `...0002` for the second, and so on. + pub fn join(&mut self, name: &str) -> ServerPlayer { + let n = match self.names.iter().position(|n| n == name) { + Some(i) => i + 1, + None => { + self.names.push(name.to_owned()); + self.names.len() + } + }; + let p = default_player(); + let player = ServerPlayer { + id: format!("00000000-0000-4000-8000-{n:012x}"), + name: name.to_owned(), + x: p.x, + y: p.y, + z: p.z, + dimension: p.dimension, + game_mode: GameMode::Survival, + health: p.health, + }; + self.players.push(player.clone()); + self.snapshot(); + self.mods.player_joined(&player); + player + } + /// The player named `name` leaves; false when no such player is on. + pub fn leave(&mut self, name: &str) -> bool { + let Some(i) = self.players.iter().position(|p| p.name == name) else { + return false; + }; + let player = self.players.remove(i); + self.snapshot(); + self.mods.player_left(&player); + true + } + /// A chat message `player` sends, for a server mod. + pub fn player_chat(&mut self, player: &ServerPlayer, line: &str) { + self.snapshot(); + self.mods.player_chat(player, line); + } + /// `/line` typed by `player`, for a server mod; false when the mod owns + /// no such command. + pub fn player_command(&mut self, player: &ServerPlayer, line: &str) -> bool { + self.snapshot(); + self.mods.server_command(player, line) + } + /// `player` breaks (or places) `state` at `pos`. + pub fn block(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str, placed: bool) { + self.snapshot(); + if placed { + self.mods.block_placed(player, pos, state); + } else { + self.mods.block_broken(player, pos, state); + } + } + /// The scratch copy the mod runs from; its `storage` is beside it. pub fn hmod(&self) -> &Path { &self.hmod } /// The commands the mod registered. pub fn commands(&self) -> Vec { - self.mods.commands().map(str::to_owned).collect() + let server = self.mods.server_commands(); + self.mods + .commands() + .chain(server) + .map(str::to_owned) + .collect() } pub fn panel(&self) -> Option<&Panel> { self.mods.panels().next() @@ -164,7 +242,7 @@ fn copy_mod(from: &Path, to: &Path) -> Result<(), String> { Ok(()) } -/// A test in TOML: where the player starts, then steps run in order. +/// A test in TOML: where a client mod's player starts, then steps run in order. #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct Script { @@ -176,9 +254,11 @@ pub struct Script { pub steps: Vec, } -/// Fields of the player to change; the others keep their values. +/// Fields of the player to change; the others keep their values. A server +/// mod's players have no `yaw`, `pitch` or `food`, and a client mod's player +/// no `game-mode`. #[derive(Debug, Default, Deserialize)] -#[serde(deny_unknown_fields)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct PlayerSet { x: Option, y: Option, @@ -188,6 +268,37 @@ pub struct PlayerSet { health: Option, food: Option, dimension: Option, + game_mode: Option, +} + +/// `players.game-mode` as a script spells it. +#[derive(Clone, Copy, Debug, Deserialize)] +#[serde(rename_all = "lowercase")] +enum Mode { + Survival, + Creative, + Adventure, + Spectator, +} +impl From for GameMode { + fn from(m: Mode) -> GameMode { + match m { + Mode::Survival => GameMode::Survival, + Mode::Creative => GameMode::Creative, + Mode::Adventure => GameMode::Adventure, + Mode::Spectator => GameMode::Spectator, + } + } +} + +/// A block a player breaks or places. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BlockSet { + x: i32, + y: i32, + z: i32, + state: String, } #[derive(Debug, Default, Deserialize)] @@ -198,8 +309,11 @@ pub struct ClockSet { } /// One step. Its parts happen in this order: `reload`, `title-screen`, -/// `player`, `clock`, `ticks`, `frames`, `chat`, `command`; then `expect` is -/// checked against what the mod showed during the step. +/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`, +/// `place`, `leave`; then `expect` is checked against what the mod showed +/// during the step. For a server mod, `player`, `chat`, `command`, `break` +/// and `place` are the doing of the player named by `as`, or of the first +/// player on. #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct Step { @@ -216,6 +330,14 @@ pub struct Step { frames: u64, chat: Option, command: Option, + /// Server mods: a player joins, leaves, breaks or places a block. + join: Option, + leave: Option, + #[serde(rename = "as")] + actor: Option, + #[serde(rename = "break")] + broken: Option, + place: Option, #[serde(default)] expect: Expect, } @@ -231,6 +353,10 @@ pub struct Expect { /// The command's feedback, and its red error. feedback: Option, error: Option, + /// Server mods: every `players.tell` as `"Name: text"`, and every + /// `players.broadcast`, in order. + told: Option>, + broadcast: Option>, /// The panel's lines (`[]`: no panel) and its corner. panel: Option>, corner: Option, @@ -274,6 +400,17 @@ impl PlayerSet { p.dimension.clone_from(d); } } + fn apply_server(&self, p: &mut ServerPlayer) { + let set = |to: &mut f64, v: Option| *to = v.unwrap_or(*to); + set(&mut p.x, self.x); + set(&mut p.y, self.y); + set(&mut p.z, self.z); + p.health = self.health.unwrap_or(p.health); + p.game_mode = self.game_mode.map_or(p.game_mode, GameMode::from); + if let Some(d) = &self.dimension { + p.dimension.clone_from(d); + } + } } impl ClockSet { @@ -302,6 +439,17 @@ impl Step { if let Some(line) = &self.command { parts.push(format!("/{line}")); } + if let Some(name) = &self.join { + parts.insert(0, format!("{name} joins")); + } + for (what, b) in [("breaks", &self.broken), ("places", &self.place)] { + if let Some(b) = b { + parts.push(format!("{what} {} at {} {} {}", b.state, b.x, b.y, b.z)); + } + } + if let Some(name) = &self.leave { + parts.push(format!("{name} leaves")); + } if parts.is_empty() { parts.push("checks".into()); } @@ -316,8 +464,35 @@ impl Step { game.player = None; game.clock = None; } + if let Some(name) = &self.join { + game.join(name); + } + let server = game.server(); + let actor = |game: &TestGame| match &self.actor { + Some(name) => game + .players + .iter() + .position(|p| p.name == *name) + .ok_or_else(|| format!("{name} is not on the server")), + None => (!game.players.is_empty()) + .then_some(0) + .ok_or_else(|| "no player is on the server: add join = \"Name\"".to_string()), + }; + let acts = self.player.is_some() + || self.chat.is_some() + || self.command.is_some() + || self.broken.is_some() + || self.place.is_some(); + let actor = if server && acts { + Some(actor(game)?) + } else { + None + }; if let Some(set) = &self.player { - set.apply(game.player.get_or_insert_with(default_player)); + match actor { + Some(i) => set.apply_server(&mut game.players[i]), + None => set.apply(game.player.get_or_insert_with(default_player)), + } } if let Some(set) = &self.clock { set.apply(game.clock.get_or_insert(Clock { @@ -327,10 +502,32 @@ impl Step { } game.tick(self.ticks); game.frames(self.frames); + let who = actor.map(|i| game.players[i].clone()); if let Some(line) = &self.chat { - game.chat(line); + match &who { + Some(p) => game.player_chat(p, line), + None => game.chat(line), + } + } + let owned = self.command.as_ref().map(|line| match &who { + Some(p) => game.player_command(p, line), + None => game.command(line), + }); + for (b, placed) in [(&self.broken, false), (&self.place, true)] { + if let (Some(b), Some(p)) = (b, &who) { + let pos = BlockPos { + x: b.x, + y: b.y, + z: b.z, + }; + game.block(p, pos, &b.state, placed); + } + } + if let Some(name) = &self.leave + && !game.leave(name) + { + return Err(format!("{name} is not on the server")); } - let owned = self.command.as_ref().map(|line| game.command(line)); let out = game.drain(); let stopped = out.iter().find_map(|o| match o { Output::Stopped { reason, .. } => Some(reason.as_str()), @@ -370,10 +567,38 @@ impl Step { } let feedback = |error: bool| { out.iter().rev().find_map(|o| match o { - Output::Feedback { text, error: e } if *e == error => Some(text.clone()), + Output::Feedback { text, error: e } | Output::Reply { text, error: e, .. } + if *e == error => + { + Some(text.clone()) + } _ => None, }) }; + if let Some(want) = &e.told { + let name = |id: &str| { + let p = game.players.iter().find(|p| p.id == id); + p.map_or(id.to_owned(), |p| p.name.clone()) + }; + let got: Vec = out + .iter() + .filter_map(|o| match o { + Output::Tell { player, text, .. } => Some(format!("{}: {text}", name(player))), + _ => None, + }) + .collect(); + same("told", want, &got)?; + } + if let Some(want) = &e.broadcast { + let got: Vec = out + .iter() + .filter_map(|o| match o { + Output::Broadcast { text, .. } => Some(text.clone()), + _ => None, + }) + .collect(); + same("broadcast", want, &got)?; + } if let Some(want) = &e.feedback { same("feedback", &Some(want.clone()), &feedback(false))?; } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index dd74591d6..ca2b8896e 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -407,22 +407,23 @@ capabilities = ["registries"] assert!(!mods.is_running()); } -/// `cargo horizon-mod test` on the example: its own `tests/*.toml` pass. +/// `cargo horizon-mod test` on the examples: their own `tests/*.toml` pass. #[test] fn the_examples_test_scripts_pass() { - let tests = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples/coords-hud/tests"); + let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples"); let mut ran = 0; - for entry in std::fs::read_dir(tests).unwrap() { - let path = entry.unwrap().path(); - let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(); - let mut game = TestGame::load(&mods_dir().join("coords_hud.hmod")).unwrap(); - script - .run(&mut game) - .unwrap_or_else(|e| panic!("{}: {e}", path.display())); - ran += 1; + for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] { + for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() { + let path = entry.unwrap().path(); + let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(); + let mut game = TestGame::load(&mods_dir().join(format!("{hmod}.hmod"))).unwrap(); + script + .run(&mut game) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); + ran += 1; + } } - assert_eq!(ran, 2); + assert_eq!(ran, 4); } #[test] @@ -446,6 +447,13 @@ fn a_test_script_says_which_step_failed_and_why() { Script::parse("[[step]]\ntick = 1").is_err(), "a typo is an error" ); + + let mut game = TestGame::load(&mods_dir().join("welcome.hmod")).unwrap(); + let script = "[[step]]\njoin = \"Alex\"\n\n[[step]]\nas = \"Steve\"\ncommand = \"mined\""; + assert_eq!( + Script::parse(script).unwrap().run(&mut game).unwrap_err(), + "step 2 (/mined): Steve is not on the server" + ); } #[test] diff --git a/docs/mods.md b/docs/mods.md index ffe64e88e..6a095adba 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -244,7 +244,8 @@ key> --signature .minisig`. `cargo horizon-mod test` builds the mod, then runs each `tests/.toml` in the sandbox the game uses, with no game and no window: the test plays the game's part (the player and the clock the mod reads, ticks, frames, chat lines, -commands) and checks what the mod showed. A script fails at its first wrong +commands; for a server mod, players joining, chatting, typing commands, +breaking and placing blocks and leaving) and checks what the mod showed. A script fails at its first wrong step, with what it expected and what it got; the command fails if any script does. `--debug` builds without optimizing, `--hmod ` tests a `.hmod` already built, and a name runs only the scripts whose path holds it. Each @@ -281,6 +282,16 @@ A step's parts happen in this order: | `ticks = n`, `frames = n` | that many ticks (the game's tick counter and the clock move on), then frames 1/60 s apart | | `chat = " hi"` | a chat line the player receives | | `command = "where north"` | the player types `/where north`; a command the mod doesn't own fails the step | +| `break = { x = 1, y = 63, z = 0, state = "minecraft:stone" }`, `place = { ... }` | server mods: the player breaks or places that block | +| `leave = "Alex"` | server mods: that player leaves | + +A server mod starts with nobody on: `join = "Alex"` (after `reload` and `title-screen`) brings a +player in at the defaults, in survival, with the id +`00000000-0000-4000-8000-000000000001` for the first name that joined, `...2` +for the second, the same id when a name joins again. `player`, `chat`, +`command`, `break` and `place` are then that player's doing: the one named by +`as = "Steve"`, or the first one on. `player` takes `game-mode` there, and the +script's own `[player]` and `[clock]` are a client mod's. Then `expect` checks what the mod did during the step; a key left out is not checked: @@ -291,6 +302,7 @@ checked: | `chat = ["..."]` | every chat line it showed, in order (`[]`: none) | | `feedback = "..."`, `error = "..."` | the command's answer, shown plain or in red | | `panel = ["..."]`, `corner = "top-left"` | its HUD panel's lines (`[]`: no panel) and corner | +| `told = ["Alex: Welcome!"]`, `broadcast = ["..."]` | server mods: every `players.tell` (as `name: text`) and `players.broadcast`, in order | | `stopped = "panic"` | the mod was turned off, for a reason holding this text; without it, a mod that traps, panics or overruns fails the test | Unknown keys are errors, so a typo never passes silently. The same runner is