From 05a6e719f69dc6052b21dfe6e83917f08f1eab26 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:51 +0100 Subject: [PATCH] test(e2e): share the end-to-end test helpers The sync tests will drive several users and a server, like the CLI and serve tests do on their own. `tests/common` now holds the helpers every end-to-end test shares: `User`, a configuration directory with its node key, `Repo`, a working copy of a user, with the crash helpers the CLI tests use, and `Server`, a running `origin serve` hosting `demo`. The CLI and serve tests use them instead of their own copies. --- AGENTS.md | 1 + apps/origin-src/tests/cli.rs | 211 ++----------------- apps/origin-src/tests/common/mod.rs | 307 ++++++++++++++++++++++++++++ apps/origin-src/tests/serve.rs | 50 +---- 4 files changed, 333 insertions(+), 236 deletions(-) create mode 100644 apps/origin-src/tests/common/mod.rs diff --git a/AGENTS.md b/AGENTS.md index f1b5eb93..f3e68fd7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,6 +42,7 @@ End-to-end tests run the `origin` binary with `ORIGIN_CONFIG_DIR` set to a temporary directory, which holds the user's `config.toml` and node key. The HTTP tests drive every SDK method against a real server. One fails while `docs/openapi.json` is stale: `just openapi` rewrites it. +`tests/common` holds the helpers every end-to-end test shares. ## Commits & Pull Requests diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 25547fda..516dc383 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -1,145 +1,24 @@ //! End-to-end tests of the change workflow and workspaces, driving the real //! `origin` binary. -use std::fs::{self, OpenOptions}; -use std::io::{BufRead, BufReader, Write}; +mod common; + +use std::fs; +use std::io::Write; use std::os::unix::fs::{MetadataExt, PermissionsExt}; -use std::path::{Path, PathBuf}; -use std::process::{Child, Command, Output, Stdio}; +use std::process::{Command, Stdio}; use std::slice; use std::sync::mpsc; use std::thread; -use std::time::{Duration, Instant}; +use std::time::Duration; +use common::Repo; use origin_platform::Native; use origin_shared::{ ChangeId, EncodedObject, Kind, Record, Revision, RevisionId, Statement, StatementId, Verdict, }; use origin_src::store::Store; -/// A temporary working copy, and a user configuration of its own. -struct Repo { - dir: tempfile::TempDir, - config: tempfile::TempDir, -} - -impl Repo { - fn new() -> Self { - let config = tempfile::tempdir().unwrap(); - fs::write(config.path().join("config.toml"), "user = \"ada\"\n").unwrap(); - let repo = Self { - dir: tempfile::tempdir().unwrap(), - config, - }; - repo.ok(&["init"]); - repo - } - - /// `origin` in `cwd` as the configured user. - fn command(&self, cwd: &Path, args: &[&str]) -> Command { - let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); - command - .args(args) - .current_dir(cwd) - .env("ORIGIN_CONFIG_DIR", self.config.path()); - command - } - - /// Runs `origin` in `cwd` as the configured user. - fn run(&self, cwd: &Path, args: &[&str]) -> Output { - self.command(cwd, args).output().unwrap() - } - - /// Starts a long-running command, such as `watch`, returning it and its - /// output lines as they come. - fn spawn(&self, args: &[&str]) -> (Child, mpsc::Receiver) { - let mut child = self - .command(self.dir.path(), args) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let stdout = BufReader::new(child.stdout.take().unwrap()); - let (send, receive) = mpsc::channel(); - thread::spawn(move || { - for line in stdout.lines() { - if send.send(line.unwrap()).is_err() { - break; - } - } - }); - (child, receive) - } - - /// The revision the working copy is, in full. - fn revision(&self) -> String { - self.read(".origin/workspace").trim_end().to_owned() - } - - /// Runs a command that must succeed, returning its output. - fn ok(&self, args: &[&str]) -> String { - self.ok_in(self.dir.path(), args) - } - - /// Runs a command in `cwd` that must succeed, returning its output. - fn ok_in(&self, cwd: &Path, args: &[&str]) -> String { - let output = self.run(cwd, args); - assert!( - output.status.success(), - "`origin {}` failed: {}", - args.join(" "), - String::from_utf8_lossy(&output.stderr) - ); - String::from_utf8(output.stdout).unwrap() - } - - /// Runs a command that must fail, returning its error. - fn fails(&self, args: &[&str]) -> String { - self.fails_in(self.dir.path(), args) - } - - /// Runs `origin` in `cwd`, which must fail, returning its errors. - fn fails_in(&self, cwd: &Path, args: &[&str]) -> String { - let output = self.run(cwd, args); - assert!( - !output.status.success(), - "`origin {}` succeeded", - args.join(" ") - ); - String::from_utf8(output.stderr).unwrap() - } - - fn path(&self, path: &str) -> std::path::PathBuf { - self.dir.path().join(path) - } - - fn write(&self, path: &str, content: &str) { - let path = self.path(path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, content).unwrap(); - } - - fn read(&self, path: &str) -> String { - fs::read_to_string(self.path(path)).unwrap() - } - - /// The short id of the working copy's change. - fn change(&self) -> String { - let status = self.ok(&["status"]); - let line = status.lines().next().unwrap(); - let headline = line.strip_prefix("Working copy: ").unwrap(); - headline.split(' ').next().unwrap().to_owned() - } - - /// Creates a workspace at `path`, returning its change. - fn workspace(&self, path: &Path, args: &[&str]) -> String { - let path = path.to_str().unwrap(); - let output = self.ok(&[&["workspace", "new", path], args].concat()); - let line = output.lines().nth(1).unwrap(); - let headline = line.strip_prefix("Working copy: ").unwrap(); - headline.split(' ').next().unwrap().to_owned() - } -} - #[test] fn the_working_copy_is_a_revision_of_the_current_change() { let repo = Repo::new(); @@ -597,8 +476,8 @@ fn a_statement_takes_its_details_as_text_or_from_stdin() { let mut piped = Command::new(env!("CARGO_BIN_EXE_origin")) .args(["annotate", "@", "ci.test", "--fail", "--payload", "-"]) - .current_dir(repo.dir.path()) - .env("ORIGIN_CONFIG_DIR", repo.config.path()) + .current_dir(repo.root()) + .env("ORIGIN_CONFIG_DIR", repo.config()) .stdin(Stdio::piped()) .spawn() .unwrap(); @@ -631,7 +510,7 @@ fn a_statement_takes_its_details_as_text_or_from_stdin() { #[test] fn init_with_a_malformed_key_leaves_no_repository() { let repo = Repo::new(); - fs::write(repo.config.path().join("node.key"), b"short").unwrap(); + fs::write(repo.config().join("node.key"), b"short").unwrap(); let other = tempfile::tempdir().unwrap(); assert!(!repo.run(other.path(), &["init"]).status.success()); assert!(!other.path().join(".origin").exists()); @@ -644,7 +523,7 @@ fn only_the_creator_of_a_change_abandons_it() { repo.ok(&["describe", "Ada's change"]); let change = repo.change(); // Eve takes the change over, then tries to give it up. - let config = repo.config.path().join("config.toml"); + let config = repo.config().join("config.toml"); fs::write(&config, "user = \"eve\"\n").unwrap(); repo.write("file", "eve's\n"); repo.ok(&["describe", "Eve's now"]); @@ -675,7 +554,7 @@ fn init_creates_policy_and_main_with_one_node_key() { ); assert!(repo.fails(&["init"]).contains("already has a repository")); - let key = repo.config.path().join("node.key"); + let key = repo.config().join("node.key"); let mode = fs::metadata(&key).unwrap().permissions().mode(); assert_eq!(mode & 0o777, 0o600); let before = fs::read(&key).unwrap(); @@ -725,10 +604,10 @@ fn a_closed_output_pipe_ends_quietly() { let repo = Repo::new(); let (reader, writer) = std::io::pipe().unwrap(); drop(reader); - let output = Command::new(env!("CARGO_BIN_EXE_origin")) + let output = std::process::Command::new(env!("CARGO_BIN_EXE_origin")) .arg("status") - .current_dir(repo.dir.path()) - .env("ORIGIN_CONFIG_DIR", repo.config.path()) + .current_dir(repo.root()) + .env("ORIGIN_CONFIG_DIR", repo.config()) .stdout(writer) .output() .unwrap(); @@ -929,7 +808,7 @@ fn an_argument_that_is_not_utf8_is_no_panic() { let repo = Repo::new(); let path = std::ffi::OsStr::from_bytes(b"gone\xff"); let output = repo - .command(repo.dir.path(), &["workspace", "rm"]) + .command(repo.root(), &["workspace", "rm"]) .arg(path) .output() .unwrap(); @@ -976,7 +855,7 @@ fn a_move_marker_that_cannot_be_read_is_kept_and_stops_moves() { let marker = repo.path(".origin/moving"); fs::create_dir(&marker).unwrap(); - let status = repo.run(repo.dir.path(), &["status"]); + let status = repo.run(repo.root(), &["status"]); let warning = String::from_utf8_lossy(&status.stderr); assert!(status.status.success(), "{warning}"); assert!(warning.starts_with("warning: cannot read "), "{warning}"); @@ -1834,7 +1713,7 @@ fn undo_moves_only_its_own_workspace() { "{log}" ); assert!(headers[1].starts_with("@ #") && headers[1].ends_with(": origin new Main work")); - assert!(headers[1].contains(&repo.dir.path().display().to_string())); + assert!(headers[1].contains(&repo.root().display().to_string())); assert!(log.contains(" undid #"), "{log}"); assert_eq!( repo.ok(&["op", "log", "-n", "1"]).lines().count(), @@ -1843,56 +1722,6 @@ fn undo_moves_only_its_own_workspace() { ); } -impl Repo { - /// The file the store keeps the object holding `content` in. - fn stored_object(&self, content: &[u8]) -> PathBuf { - let hex = origin_shared::EncodedObject::blob(content).id().to_hex(); - self.path(&format!( - ".origin/objects/loose/{}/{}", - &hex[..2], - &hex[2..] - )) - } - - /// Runs `origin ` in `cwd` until it reads the stored object - /// holding `content`, then once `ready`, kills it, as a crash would, - /// and stores the object again. - fn crash_reading(&self, cwd: &Path, content: &[u8], args: &[&str], ready: impl Fn() -> bool) { - let stored = self.stored_object(content); - let object = fs::read(&stored).unwrap(); - fs::remove_file(&stored).unwrap(); - let fifo = Command::new("mkfifo").arg(&stored).status().unwrap(); - assert!(fifo.success()); - let mut child = self - .command(cwd, args) - .stdout(Stdio::null()) - .spawn() - .unwrap(); - // Opening the pipe to write waits for the command to open it to - // read, which it then waits on, for as long as the pipe is open. - let (opened, open) = mpsc::channel(); - let pipe = stored.clone(); - thread::spawn(move || opened.send(OpenOptions::new().write(true).open(pipe))); - let deadline = Instant::now() + Duration::from_secs(20); - let _pipe = loop { - if let Ok(pipe) = open.recv_timeout(Duration::from_millis(20)) { - break pipe.unwrap(); - } - assert!(child.try_wait().unwrap().is_none(), "it never read it"); - assert!(Instant::now() < deadline, "it never read it in time"); - }; - while !ready() { - assert!(Instant::now() < deadline, "never ready"); - thread::sleep(Duration::from_millis(20)); - } - child.kill().unwrap(); - child.wait().unwrap(); - fs::remove_file(&stored).unwrap(); - fs::write(&stored, object).unwrap(); - fs::set_permissions(&stored, fs::Permissions::from_mode(0o444)).unwrap(); - } -} - #[test] fn a_move_cut_short_is_finished_without_losing_edits() { let repo = Repo::new(); @@ -1907,7 +1736,7 @@ fn a_move_cut_short_is_finished_without_losing_edits() { fs::remove_file(repo.path("ro/b")).unwrap(); // `edit` back to the first change crashes after writing `a`. - repo.crash_reading(repo.dir.path(), b"b\n", &["edit", &first], || { + repo.crash_reading(repo.root(), b"b\n", &["edit", &first], || { fs::read_to_string(repo.path("a")).is_ok_and(|a| a == "a\n") }); assert!(repo.path(".origin/moving").exists()); @@ -2047,7 +1876,7 @@ fn a_move_that_cannot_be_finished_leaves_the_files() { // `edit` crashes after writing `a`, and the content finishing it // needs can't be read. - repo.crash_reading(repo.dir.path(), b"b\n", &["edit", &first], || { + repo.crash_reading(repo.root(), b"b\n", &["edit", &first], || { fs::read_to_string(repo.path("a")).is_ok_and(|a| a == "a\n") }); assert!(repo.path(".origin/moving").exists()); diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs new file mode 100644 index 00000000..0f19e2cb --- /dev/null +++ b/apps/origin-src/tests/common/mod.rs @@ -0,0 +1,307 @@ +//! Helpers for the end-to-end tests, which run the real `origin` binary. + +// Each test binary uses its own subset of the helpers, and the others would +// warn as unused in it. +#![allow(dead_code)] + +use std::fs::{self, OpenOptions}; +use std::io::{BufRead, BufReader}; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Output, Stdio}; +use std::sync::Arc; +use std::sync::mpsc; +use std::thread; +use std::time::{Duration, Instant}; + +/// A user, with a configuration directory, and so a node key, of their +/// own. Clones share it. +#[derive(Clone)] +pub struct User { + config: Arc, +} + +impl User { + /// A user named `name`, whose node is named after them. + pub fn new(name: &str) -> Self { + let config = tempfile::tempdir().unwrap(); + fs::write( + config.path().join("config.toml"), + format!("user = \"{name}\"\n"), + ) + .unwrap(); + Self { + config: Arc::new(config), + } + } + + /// The configuration directory. + pub fn config(&self) -> &Path { + self.config.path() + } + + /// `origin` with `args`, run in `cwd` as this user. + pub fn command(&self, cwd: &Path, args: &[&str]) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + command + .args(args) + .current_dir(cwd) + .env("ORIGIN_CONFIG_DIR", self.config()); + command + } +} + +/// A temporary working copy, and its user. +pub struct Repo { + dir: tempfile::TempDir, + user: User, +} + +impl Repo { + /// A new repository of a user of its own, `ada`. + pub fn new() -> Self { + Self::init(&User::new("ada")) + } + + /// A new repository of `user`. + pub fn init(user: &User) -> Self { + let repo = Self::empty(user); + repo.ok(&["init"]); + repo + } + + fn empty(user: &User) -> Self { + Self { + dir: tempfile::tempdir().unwrap(), + user: user.clone(), + } + } + + /// The root of the working copy. + pub fn root(&self) -> &Path { + self.dir.path() + } + + /// The user's configuration directory. + pub fn config(&self) -> &Path { + self.user.config() + } + + /// Runs `origin` in `cwd` as the repository's user. + pub fn run(&self, cwd: &Path, args: &[&str]) -> Output { + self.command(cwd, args).output().unwrap() + } + + /// `origin` with `args`, to run in `cwd` as this repository's user. + pub fn command(&self, cwd: &Path, args: &[&str]) -> Command { + self.user.command(cwd, args) + } + + /// Starts a long-running command, such as `watch`, returning it and its + /// output lines as they come. + pub fn spawn(&self, args: &[&str]) -> (Child, mpsc::Receiver) { + let mut child = self + .user + .command(self.root(), args) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let stdout = BufReader::new(child.stdout.take().unwrap()); + let (send, receive) = mpsc::channel(); + thread::spawn(move || { + for line in stdout.lines() { + if send.send(line.unwrap()).is_err() { + break; + } + } + }); + (child, receive) + } + + /// The revision the working copy is, in full. + pub fn revision(&self) -> String { + self.read(".origin/workspace").trim_end().to_owned() + } + + /// Runs a command that must succeed, returning its output. + pub fn ok(&self, args: &[&str]) -> String { + self.ok_in(self.root(), args) + } + + /// Runs a command in `cwd` that must succeed, returning its output. + pub fn ok_in(&self, cwd: &Path, args: &[&str]) -> String { + let output = self.run(cwd, args); + assert!( + output.status.success(), + "`origin {}` failed: {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + /// Runs a command that must fail, returning its error. + pub fn fails(&self, args: &[&str]) -> String { + self.fails_in(self.root(), args) + } + + /// Runs `origin` in `cwd`, which must fail, returning its errors. + pub fn fails_in(&self, cwd: &Path, args: &[&str]) -> String { + let output = self.run(cwd, args); + assert!( + !output.status.success(), + "`origin {}` succeeded", + args.join(" ") + ); + String::from_utf8(output.stderr).unwrap() + } + + pub fn path(&self, path: &str) -> PathBuf { + self.root().join(path) + } + + pub fn write(&self, path: &str, content: &str) { + let path = self.path(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + + pub fn read(&self, path: &str) -> String { + fs::read_to_string(self.path(path)).unwrap() + } + + /// The short id of the working copy's change. + pub fn change(&self) -> String { + let status = self.ok(&["status"]); + let line = status.lines().next().unwrap(); + let headline = line.strip_prefix("Working copy: ").unwrap(); + headline.split(' ').next().unwrap().to_owned() + } + + /// Creates a workspace at `path`, returning its change. + pub fn workspace(&self, path: &Path, args: &[&str]) -> String { + let path = path.to_str().unwrap(); + let output = self.ok(&[&["workspace", "new", path], args].concat()); + let line = output.lines().nth(1).unwrap(); + let headline = line.strip_prefix("Working copy: ").unwrap(); + headline.split(' ').next().unwrap().to_owned() + } + + /// The file the store keeps the object holding `content` in. + pub fn stored_object(&self, content: &[u8]) -> PathBuf { + let hex = origin_shared::EncodedObject::blob(content).id().to_hex(); + self.path(&format!( + ".origin/objects/loose/{}/{}", + &hex[..2], + &hex[2..] + )) + } + + /// Runs `origin ` in `cwd` until it reads the stored object + /// holding `content`, then once `ready`, kills it, as a crash would, + /// and stores the object again. + pub fn crash_reading( + &self, + cwd: &Path, + content: &[u8], + args: &[&str], + ready: impl Fn() -> bool, + ) { + let stored = self.stored_object(content); + let object = fs::read(&stored).unwrap(); + fs::remove_file(&stored).unwrap(); + let fifo = Command::new("mkfifo").arg(&stored).status().unwrap(); + assert!(fifo.success()); + let mut child = self + .user + .command(cwd, args) + .stdout(Stdio::null()) + .spawn() + .unwrap(); + // Opening the pipe to write waits for the command to open it to + // read, which it then waits on, for as long as the pipe is open. + let (opened, open) = mpsc::channel(); + let pipe = stored.clone(); + thread::spawn(move || opened.send(OpenOptions::new().write(true).open(pipe))); + let deadline = Instant::now() + Duration::from_secs(20); + let _pipe = loop { + if let Ok(pipe) = open.recv_timeout(Duration::from_millis(20)) { + break pipe.unwrap(); + } + assert!(child.try_wait().unwrap().is_none(), "it never read it"); + assert!(Instant::now() < deadline, "it never read it in time"); + }; + while !ready() { + assert!(Instant::now() < deadline, "never ready"); + thread::sleep(Duration::from_millis(20)); + } + child.kill().unwrap(); + child.wait().unwrap(); + fs::remove_file(&stored).unwrap(); + fs::write(&stored, object).unwrap(); + fs::set_permissions(&stored, fs::Permissions::from_mode(0o444)).unwrap(); + } +} + +/// A running `origin serve` hosting one repository, `demo`, which its node, +/// `hosted`, orders. Killed when dropped. +pub struct Server { + dir: tempfile::TempDir, + child: Child, + /// The server's base URL. + pub base: String, +} + +impl Server { + pub fn start() -> Self { + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("origin-server.toml"); + fs::write( + &config, + "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n[repos]\ndemo = \"repos/demo\"\n", + ) + .unwrap(); + let origin = |args: &[&str]| { + let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + command.args(args).arg("--config").arg(&config); + command + }; + let created = origin(&["repo", "create"]) + .arg(dir.path().join("repos/demo")) + .output() + .unwrap(); + assert!( + created.status.success(), + "{}", + String::from_utf8_lossy(&created.stderr) + ); + let mut child = origin(&["serve"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut line = String::new(); + BufReader::new(child.stdout.take().unwrap()) + .read_line(&mut line) + .unwrap(); + let base = line + .trim() + .strip_prefix("Listening on ") + .unwrap() + .to_owned(); + Self { dir, child, base } + } + + /// The directory holding the server's configuration, key and + /// repositories. + pub fn dir(&self) -> &Path { + self.dir.path() + } +} + +impl Drop for Server { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} diff --git a/apps/origin-src/tests/serve.rs b/apps/origin-src/tests/serve.rs index 0ad82b58..0e10f73d 100644 --- a/apps/origin-src/tests/serve.rs +++ b/apps/origin-src/tests/serve.rs @@ -1,58 +1,18 @@ //! End to end: `origin repo create` and `origin serve`, running the real //! binary and talking to it through the SDK. -use std::fs; -use std::io::{BufRead, BufReader}; -use std::process::{Child, Command, Stdio}; +mod common; +use common::Server; use origin_client::Client; use origin_shared::api::RepoName; -/// A running `origin serve`, killed when dropped. -struct Serve(Child); - -impl Drop for Serve { - fn drop(&mut self) { - let _ = self.0.kill(); - let _ = self.0.wait(); - } -} - #[tokio::test] async fn serves_the_repositories_it_created() { - let dir = tempfile::tempdir().unwrap(); - let config = dir.path().join("origin-server.toml"); - fs::write( - &config, - "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n[repos]\ndemo = \"repos/demo\"\n", - ) - .unwrap(); - let origin = |args: &[&str]| { - let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); - command.args(args).arg("--config").arg(&config); - command - }; - - let created = origin(&["repo", "create"]) - .arg(dir.path().join("repos/demo")) - .output() - .unwrap(); - assert!( - created.status.success(), - "{}", - String::from_utf8_lossy(&created.stderr) - ); - assert!(dir.path().join("node.key").is_file(), "the server's key"); - - let mut child = origin(&["serve"]).stdout(Stdio::piped()).spawn().unwrap(); - let mut line = String::new(); - BufReader::new(child.stdout.take().unwrap()) - .read_line(&mut line) - .unwrap(); - let _serve = Serve(child); - let url = line.trim().strip_prefix("Listening on ").unwrap(); + let server = Server::start(); + assert!(server.dir().join("node.key").is_file(), "the server's key"); - let client = Client::new(url); + let client = Client::new(&server.base); let repos = client.repos().await.unwrap(); assert_eq!(repos.len(), 1); let targets = client