diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/approve.rs | 37 | ||||
| -rw-r--r-- | tests/common/mod.rs | 53 | ||||
| -rw-r--r-- | tests/config.rs | 64 | ||||
| -rw-r--r-- | tests/crash.rs | 24 | ||||
| -rw-r--r-- | tests/db.rs | 9 | ||||
| -rw-r--r-- | tests/detect.rs | 13 | ||||
| -rw-r--r-- | tests/dispatch.rs | 50 | ||||
| -rw-r--r-- | tests/failure_modes.rs | 23 | ||||
| -rw-r--r-- | tests/hash.rs | 22 | ||||
| -rw-r--r-- | tests/http.rs | 39 | ||||
| -rw-r--r-- | tests/invariants.rs | 41 | ||||
| -rw-r--r-- | tests/kata.rs | 37 | ||||
| -rw-r--r-- | tests/layers.rs | 22 | ||||
| -rw-r--r-- | tests/live.rs | 31 | ||||
| -rw-r--r-- | tests/notices.rs | 17 | ||||
| -rw-r--r-- | tests/ops.rs | 50 | ||||
| -rw-r--r-- | tests/pipeline.rs | 55 | ||||
| -rw-r--r-- | tests/production_surface.rs | 36 | ||||
| -rw-r--r-- | tests/remote_agent.rs | 40 | ||||
| -rw-r--r-- | tests/schema_ownership.rs | 20 | ||||
| -rw-r--r-- | tests/shims.rs | 50 | ||||
| -rw-r--r-- | tests/staleness.rs | 28 | ||||
| -rw-r--r-- | tests/state_machine.rs | 51 | ||||
| -rw-r--r-- | tests/surfaces.rs | 5 | ||||
| -rw-r--r-- | tests/time.rs | 9 | ||||
| -rw-r--r-- | tests/vcs.rs | 45 | ||||
| -rw-r--r-- | tests/versions.rs | 60 | ||||
| -rw-r--r-- | tests/world.rs | 25 |
28 files changed, 296 insertions, 660 deletions
diff --git a/tests/approve.rs b/tests/approve.rs index f1fc762..86dcf46 100644 --- a/tests/approve.rs +++ b/tests/approve.rs @@ -1,9 +1,3 @@ -//! Approval semantics (§7.1, §7.1a, §7.2) and the CLI approval path (P0). -//! -//! The rule these tests exist to protect: **we build exactly what was displayed, -//! or nothing.** An approval that does not match the hashes of what the reviewer -//! was shown is refused, never retargeted. - mod common; use aur_build::db::model::*; @@ -111,13 +105,12 @@ fn approving_twice_is_refused_not_duplicated() { fn a_broken_database_is_not_reported_as_a_stale_review() { // What this pins: every failure inside the approval transaction used to be // mapped into `Stale::NotPending`, so a SQLite error reached the reviewer as - // "review is no longer pending (state: sqlite: …)" — the one message that - // tells them to look again when the truth is that the write failed (§6 M-3). + // "review is no longer pending" — the one message telling them to look again + // when the truth is that the write failed (§6 M-3). let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); - // Make the write impossible halfway through the transaction: the approval - // row and the candidate update succeed, then the audit append has nowhere - // to go. + // Make the write impossible halfway through: the approval row and the + // candidate update succeed, then the audit append has nowhere to go. env.exec("DROP TABLE audit", &[]); let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); assert!(matches!(err, ApproveError::System(_)), "a broken database was reported as a stale review: {err:?}"); @@ -131,8 +124,7 @@ fn a_broken_database_is_not_reported_as_a_stale_review() { #[test] fn bulk_refusals_are_their_own_reasons() { // Bulk used to bend `Stale::NotPending` into "high risk", "unknown decision" - // and "the database failed", and to hand back a fabricated `Approval { id: 0 }` - // for a rejection that recorded no approval at all (§6 M-3). + // and "the database failed" (§6 M-3). let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); candidates::set_risk(&env.db, c.id, "high", &["new source host".into()]).unwrap(); @@ -168,8 +160,7 @@ fn a_bulk_rejection_hands_back_no_invented_approval() { let (c, dd) = open_review(&env, "plain-make"); let out = bulk(&env.db, "tester", &[(c.id, c.identity_hash.clone(), dd)], "reject", &[]).unwrap(); assert!(matches!(out[0].outcome, BulkOutcome::Rejected), "{:?}", out[0].outcome); - // A rejection records a `rejected` row; there is no approval to return, and - // the old `Approval { id: 0 }` sentinel is gone. + // A rejection records a `rejected` row; there is no approval to return. assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1)); assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='approved'", &[]), Some(0)); } @@ -209,8 +200,8 @@ fn once_viewed_a_new_state_freezes_the_old_one_as_superseded() { assert_ne!(open[0].id, c.id, "a fresh review was opened"); let frozen = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); assert_eq!(frozen.state, CandidateState::Superseded); - // The frozen one can no longer be approved: approving it would build a - // version nobody is looking at. + // The frozen one can no longer be approved: approving it would build a version + // nobody is looking at. let err = approve(&env.db, "tester", c.id, &frozen.identity_hash, &frozen.diff_digest, None).unwrap_err(); assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })), "{err:?}"); } @@ -246,9 +237,7 @@ fn reject_requires_a_reason_and_records_it() { .unwrap(); assert!(note.contains("license"), "{note}"); - // And the audit row says *which review* was rejected, not only why (§6 m-4): - // the three review actions each hand-built their own `detail`, and two of - // them recorded no identity at all. + // And the audit row says *which review* was rejected, not only why (§6 m-4). let (actor_kind, detail): (String, String) = env .db .read(|c| { @@ -268,8 +257,8 @@ fn reject_requires_a_reason_and_records_it() { // ------------------------------------------------------------- the CLI path -- -/// Drive the real binary the way an operator would. This is the P0 approval -/// path: `init`, `subscribe`, `detect`, `show`, `approve --yes`. +/// Drive the real binary the way an operator would: `init`, `subscribe`, +/// `detect`, `show`, `approve --yes`. #[test] fn cli_end_to_end_approves_and_queues_a_build() { let tmp = tempfile::tempdir().unwrap(); @@ -291,8 +280,8 @@ fn cli_end_to_end_approves_and_queues_a_build() { let out = cli(bin, &root, &["reviews"]); assert!(out.stdout.contains("#1"), "reviews: {}", out.stdout); - // `show` renders the panels and the hashes; `approve` without --yes refuses - // to act, which is the CLI's version of "look before you approve". + // `show` renders the panels and the hashes; `approve` without --yes refuses to + // act. let out = cli(bin, &root, &["show", "1"]); assert!(out.stdout.contains("identity_hash"), "show: {}", out.stdout); let shown = out.stdout.clone(); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 426f44d..b1a50ac 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,6 +1,3 @@ -//! Shared test scaffolding: an isolated server root in a tempdir with a migrated -//! database and a running writer actor. - #![allow(dead_code)] use std::path::{Path, PathBuf}; @@ -78,8 +75,7 @@ impl Env { } /// Stand in for the build+publish path: turn an approved candidate into a - /// published release and move the accepted pointer. The real path lives in - /// `pipeline`; detection tests need an accepted base without a build. + /// published release and move the accepted pointer. pub fn accept_as_release(&self, candidate_id: i64) -> i64 { let at = "2026-01-01T00:00:00Z"; self.db @@ -227,9 +223,9 @@ pub fn shim_dir() -> PathBuf { .to_path_buf() } -/// An environment wired to one corpus fixture: the fixture is committed into a -/// real git repo standing in for AUR, an optional local upstream git repo exists -/// for VCS sources, and the shims are told to obey the fixture manifest. +/// An environment wired to one corpus fixture: the fixture is committed into a real +/// git repo standing in for AUR, an optional local upstream git repo exists for VCS +/// sources, and the shims obey the fixture manifest. pub fn env_with_fixture(name: &str) -> (Env, Fixture) { let tmp = tempfile::tempdir().expect("tempdir"); let fx = materialize_fixture(tmp.path(), name); @@ -252,8 +248,7 @@ pub fn env_with_fixture(name: &str) -> (Env, Fixture) { } /// Two fixtures sharing one server root, so a test can talk about packages that -/// depend on each other. The second fixture's manifest wins for the shim, which -/// is what you want when the second one is the dependent. +/// depend on each other. pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) { let tmp = tempfile::tempdir().expect("tempdir"); let fa = materialize_fixture(tmp.path(), a); @@ -277,17 +272,17 @@ pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) { (env, fa, fb) } -/// Copy a corpus fixture into a server root: recipe files into a git repo that -/// stands in for AUR, payload files beside it so their bytes can be swapped, -/// and a local upstream repo when the recipe references one. +/// Copy a corpus fixture into a server root: recipe files into a git repo standing +/// in for AUR, payload files beside it so their bytes can be swapped, and a local +/// upstream repo when the recipe references one. pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { let src = corpus_root().join(name); assert!(src.exists(), "no fixture {name} in {}", corpus_root().display()); let manifest = root.join("manifest.json"); std::fs::copy(src.join("manifest.json"), &manifest).expect("copy manifest"); - // Data files that a source URL points at live outside the recipe so a test - // can swap their bytes (the digest-drift case) without touching git. + // Data files a source URL points at live outside the recipe so a test can swap + // their bytes (the digest-drift case) without touching git. let data = root.join(format!("fixture/{name}")); std::fs::create_dir_all(&data).unwrap(); let aur = root.join(format!("aur/{name}.git")); @@ -473,8 +468,8 @@ pub fn git(dir: &Path, args: &[&str]) -> String { // ------------------------------------------------------------- web driver -- -/// A tiny HTTP client for the surface tests: keeps the session cookie and the -/// CSRF token, and hands back status + body. +/// A tiny HTTP client for the surface tests: keeps the session cookie and the CSRF +/// token, and hands back status + body. pub struct Web { pub env: Env, pub fx: Fixture, @@ -526,8 +521,8 @@ impl Web { aur_build::review::candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap() } - /// Approve through the library and run the build to publication, so a test - /// can talk about "what the index serves" without re-implementing P0. + /// Approve through the library and run the build to publication, so a test can + /// talk about "what the index serves". pub fn publish(&self, name: &str) { let c = self.open_review(name); aur_build::review::approve::approve(&self.env.db, "test", c.id, &c.identity_hash, &c.diff_digest, None) @@ -550,8 +545,8 @@ impl Web { }; let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default(); let mut headers = vec![("set-cookie".to_string(), cookie)]; - // ureq 2 will not hand out the whole header map, but it will answer for a - // named one, which is all the assertions below need. + // ureq 2 will not hand out the whole header map, but it answers for a named + // one, which is all the assertions below need. for name in ["content-type", "content-encoding", "location"] { if let Some(v) = r.header(name) { headers.push((name.to_string(), v.to_string())); @@ -577,10 +572,9 @@ impl Web { self.finish(resp, path) } - /// Send a request over a bare socket: no cookie jar, no redirect following, - /// so the test sees the 303 a browser would have swallowed. The session - /// gate is only meaningful at this level — a client that follows redirects - /// turns "you are not signed in" into the login page's 200. + /// Send a request over a bare socket: no cookie jar, no redirect following, so + /// the test sees the 303 a browser would have swallowed. The session gate is + /// only meaningful at this level. pub fn raw_request(&self, method: &str, path: &str, headers: &[(&str, String)], body: Option<&str>) -> Raw { use std::io::{Read, Write}; let addr = self.server.addr.clone(); @@ -604,9 +598,8 @@ impl Web { Raw::parse(&raw) } - /// Log in and adopt the session cookie the server issued, refreshing the - /// CSRF token with it — the token is derived from the sid, so a login that - /// rotates the session invalidates the one captured before it. + /// Log in and adopt the session cookie the server issued, refreshing the CSRF + /// token with it — the token is derived from the sid. pub fn login(&mut self, password: &str) -> Raw { let raw = self.raw_request("POST", "/login", &[], Some(&format!("password={}", url_encode(password)))); if let Some(cookie) = raw.cookie() { @@ -673,8 +666,8 @@ fn url_encode(s: &str) -> String { .collect() } -/// Pull an attribute or meta value out of rendered HTML and undo the escaping -/// the templates applied — a page is the contract here, so we read it as one. +/// Pull an attribute or meta value out of rendered HTML and undo the escaping the +/// templates applied — a page is the contract here, so we read it as one. pub fn extract(hay: &str, open: &str, close: &str) -> Option<String> { let i = hay.find(open)? + open.len(); let rest = &hay[i..]; diff --git a/tests/config.rs b/tests/config.rs index 20010a7..3737045 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -1,21 +1,10 @@ -//! The server root: one directory, named once. -//! -//! `--root` selects the directory and `config.json` lives inside it, so the root -//! *is* wherever the config was found; the `root` field in the file is a record -//! of that, not a second knob. Re-joining a relative field onto the config's own -//! directory is what made `--root runtime` become `runtime/runtime/…`: `init` -//! created and migrated one tree, and every command after it ran against a -//! second one with its own empty database. - use std::path::{Path, PathBuf}; use std::process::Command; use aur_build::config::Config; /// The exact shape of the bug: a relative `--root`, saved verbatim, read back by -/// the next command. Relative to the crate root here, which is the cwd cargo -/// gives a test — the same situation as running `--root runtime` from a directory -/// that is not `/`. +/// the next command. #[test] fn a_relative_root_is_absolutized_once_and_never_doubled() { let rel = PathBuf::from("target").join("config-root-test").join("runtime"); @@ -47,8 +36,8 @@ fn a_relative_root_is_absolutized_once_and_never_doubled() { std::fs::remove_dir_all(&rel).unwrap(); } -/// The legacy shape on disk: a config written by an `init` that saved -/// `--root runtime` verbatim. Loading it must not resurrect the doubled tree. +/// The legacy shape on disk: a config written by an `init` that saved `--root +/// runtime` verbatim. Loading it must not resurrect the doubled tree. #[test] fn a_stale_relative_root_in_the_file_is_ignored() { let tmp = tempfile::tempdir().unwrap(); @@ -72,9 +61,8 @@ fn a_root_with_no_config_is_an_error_not_a_fresh_server() { ); } -/// The CLI half of the same rule. The old fallback invented a default config for -/// *any* command, so a typo'd `--root` quietly produced an empty server whose -/// commands reported success against a database with nothing in it. +/// The CLI half of the same rule: the old fallback invented a default config for +/// *any* command, so a typo'd `--root` quietly produced an empty server. #[test] fn the_cli_refuses_a_root_that_was_never_initialized() { let tmp = tempfile::tempdir().unwrap(); @@ -95,8 +83,7 @@ fn the_cli_refuses_a_root_that_was_never_initialized() { assert!(err.contains("init"), "{err}"); } -/// …and `init` is still allowed to run where there is no config yet, which is the -/// only reason the fallback existed. +/// …and `init` is still allowed to run where there is no config yet. #[test] fn init_still_runs_where_there_is_no_config_yet() { let tmp = tempfile::tempdir().unwrap(); @@ -133,15 +120,9 @@ fn an_absolute_root_is_used_verbatim() { assert_eq!(Config::load(dir).unwrap().root, dir); } -// --------------------------------------------------------------------------- -// The sandbox configuration: three kinds, and only three. -// -// This used to be `sandbox_backend: String` matched with a `_ =>` arm that -// produced loopback, so `"kata"` — a real, intended backend — silently meant -// "run the untrusted PKGBUILD as the hub's own user". The kinds are an enum -// now, so the invalid configurations do not parse, and the error says which -// field or which value was wrong. -// --------------------------------------------------------------------------- +// The sandbox configuration: three kinds, and only three. The kinds are an enum +// now, so a configuration that would silently mean "run the untrusted PKGBUILD as +// the hub's own user" does not parse. /// Write a config carrying exactly this `sandbox` value and load it. fn load_sandbox(sandbox: &str) -> Result<Config, String> { @@ -244,7 +225,7 @@ fn an_unknown_kind_names_the_value_and_the_valid_set() { #[test] fn a_config_with_no_sandbox_object_is_the_local_backend() { // The contract with every config.json already on disk: saying nothing means - // loopback, exactly as before. + // loopback. let cfg = load_raw("{\n \"repo_name\": \"aur\"\n}\n").unwrap(); assert!(matches!(cfg.sandbox, aur_build::config::Sandbox::Loopback)); assert_eq!(cfg.repo_name, "aur", "the rest of the config is untouched"); @@ -252,10 +233,8 @@ fn a_config_with_no_sandbox_object_is_the_local_backend() { assert!(cfg.sandbox.shared_workspace(), "loopback shares the filesystem by construction"); } -/// The file an older `aur-build init` wrote, verbatim. It carries the retired -/// keys, but they say `loopback` and three empty strings — which is what the -/// default already means — so it must still load rather than strand a working -/// local deployment on a syntax change. +/// The file an older `aur-build init` wrote, verbatim. It carries the retired keys, +/// but they say what the default already means, so it must still load. #[test] fn a_config_init_wrote_before_the_enum_still_loads() { let cfg = load_raw( @@ -290,9 +269,8 @@ fn a_config_init_wrote_before_the_enum_still_loads() { assert_eq!(cfg.lease_secs, 90); } -/// …but retired keys that *would* have changed behaviour are refused, not -/// quietly reinterpreted. A retired `"remote"` becoming loopback is the exact -/// silent substitution the enum was introduced to make impossible. +/// …but retired keys that *would* have changed behaviour are refused, not quietly +/// reinterpreted. #[test] fn retired_sandbox_keys_that_mean_something_are_refused() { let err = load_raw(r#"{ "sandbox_backend": "remote", "agent_listen": "0.0.0.0:1", "agent_token": "t" }"#) @@ -323,11 +301,9 @@ fn the_rendezvous_secrets_never_reach_debug() { assert!(shown.contains("builds"), "the non-secret fields are still visible: {shown}"); } -// --------------------------------------------------------------------------- -// The startup guard. The enum makes the impossible unrepresentable; this -// refuses what a type cannot see — a field present but empty, and a remote -// backend that was never told the workspace is shared. -// --------------------------------------------------------------------------- +// The startup guard: the enum makes the impossible unrepresentable, this refuses +// what a type cannot see — a field present but empty, and a remote backend that +// was never told the workspace is shared. /// A config that parses but cannot work must be refused by `validate`, not /// discovered at the step that needed the thing it is missing. @@ -362,10 +338,8 @@ fn a_field_that_is_present_but_empty_is_refused() { } } -/// The workspace gap, made impossible to hit by accident. The build workspace -/// is not shipped to a remote sandbox, so "remote" without this assertion would -/// silently build on the hub — the exact substitution this whole enum exists to -/// prevent, one layer down. +/// The workspace gap: the build workspace is not shipped to a remote sandbox, so +/// "remote" without this assertion would silently build on the hub. #[test] fn a_remote_backend_must_assert_the_shared_workspace() { let cfg = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t"}"#).unwrap(); diff --git a/tests/crash.rs b/tests/crash.rs index e1f856f..68cac5c 100644 --- a/tests/crash.rs +++ b/tests/crash.rs @@ -1,11 +1,3 @@ -//! Crash, cancellation and the failure UI (§8.2, §8.4, I5). -//! -//! The difference between this file and the in-process fault hooks elsewhere is -//! that here the process actually dies. A shim sends `SIGKILL` to its parent in -//! the middle of the build step: no `Drop`, no unwinding, no chance to clean up. -//! That is the only way to prove the checkpoint story, because every in-process -//! simulation of a crash can be caught and tidied by accident. - mod common; use std::os::unix::process::ExitStatusExt; @@ -78,8 +70,8 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work ); assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none(), "nothing was published"); - // Time passes; the lease expires. A fresh process's dispatcher reaps it — - // the same code path as any other expired lease, with no special recovery. + // Time passes; the lease expires. A fresh process's dispatcher reaps it — the + // same code path as any other expired lease. env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", ¶ms(vec![id.as_str()])); assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); assert_eq!( @@ -87,8 +79,7 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work Some(StepState::Interrupted) ); - // Resume. The completed steps are not repeated; only the interrupted one and - // what follows run. + // Resume: the completed steps are not repeated. env.cfg.hooks.shim_kill_parent = None; env.cfg.save().unwrap(); let out = run_cli(&env, &["run", &id]); @@ -117,8 +108,8 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work #[test] fn a_cancelled_build_stops_at_a_step_boundary_and_publishes_nothing() { - // §8.2: cancellation is cooperative at a step boundary. A worker never kills - // a step halfway through, because that is exactly the state a crash leaves. + // §8.2: cancellation is cooperative at a step boundary. A worker never kills a + // step halfway through, because that is the state a crash leaves. let (env, _fx) = env_with_fixture("plain-make"); let id = queued(&env, "plain-make"); builds::request_cancel(&env.db, &id).unwrap(); @@ -137,7 +128,7 @@ fn a_cancelled_build_stops_at_a_step_boundary_and_publishes_nothing() { fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { // §8.4: "v2 approved, build failed, index still serving v1". The dangerous // failure mode is a package that looks healthy while the new version never - // arrived, so the state has to be visible, not inferable. + // arrived. let (mut env, fx) = env_with_fixture("plain-make"); // Publish v1 for real. let c = approved(&env, "plain-make"); @@ -153,8 +144,7 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { let out = pipeline::run(&env.cfg, &env.db, &id2).unwrap(); assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}"); - // The index still serves v1 — that is correct — and the system knows the - // approved v2 never landed. + // The index still serves v1 — correct — and the system knows v2 never landed. assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1")); let unbuilt = db::approved_but_unbuilt(&env.db).unwrap(); assert_eq!(unbuilt.len(), 1, "the failed approval must be surfaced: {unbuilt:?}"); diff --git a/tests/db.rs b/tests/db.rs index d750b5a..31f4326 100644 --- a/tests/db.rs +++ b/tests/db.rs @@ -1,8 +1,3 @@ -//! Schema and writer-actor tests (DESIGN.md §11, §11a). -//! -//! These are the parts of the §2 invariant set that are database guarantees -//! rather than code conventions. - mod common; use common::{params, Env, P}; @@ -240,9 +235,7 @@ fn i1_query_flags_index_entries_without_approval() { #[test] fn a_setting_that_is_absent_is_the_default_and_one_that_is_nonsense_falls_back() { - // m-9: the policy is now stated — absent means default, nonsense means - // default *and a complaint*, because a typo in a knob that silently does - // nothing is worse than a knob that refuses to apply. + // m-9: absent means default, nonsense means default *and a complaint*. let env = Env::new(); assert_eq!(db::setting_i64(&env.db, "stage_b_cooldown", 86400), 86400); db::set_setting(&env.db.writer, "stage_b_cooldown", "86400x").unwrap(); diff --git a/tests/detect.rs b/tests/detect.rs index e674c8a..6284b31 100644 --- a/tests/detect.rs +++ b/tests/detect.rs @@ -1,8 +1,3 @@ -//! Detection tests (§5.1, §5.1a, §5.3, §7.1) against a local `file://` "AUR". -//! -//! The fixtures are real git repos so the mirror, the pin and `recipe_hash` are -//! exercised for real; only the network is replaced. - mod common; use common::{git_add_commit, make_git_repo, params, Env, P}; @@ -74,8 +69,8 @@ fn git_head(p: &std::path::Path) -> String { aur_build::git::head(p).unwrap() } -/// §3: `recipe_hash` covers the *entire* tree, because a shipped patch is part -/// of the recipe and is a classic silent-change vector. +/// §3: `recipe_hash` covers the *entire* tree, because a shipped patch is part of +/// the recipe and is a classic silent-change vector. #[test] fn recipe_hash_covers_shipped_patches() { let env = Env::new(); @@ -176,8 +171,8 @@ fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() { assert_eq!(c2.base_release_id, Some(rel1), "base is the accepted release"); assert_eq!(c2.version(), "2.0-1"); - // v3 and v4 arrive while nobody is looking: they collapse into the same - // review, and the base is *still* v1. The human sees v1 -> v4. + // v3 and v4 arrive while nobody is looking: they collapse into the same review, + // and the base is *still* v1. for v in ["3.0", "4.0"] { git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", v, "1", ""))], v); check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); diff --git a/tests/dispatch.rs b/tests/dispatch.rs index 5f65b6f..197d226 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -1,8 +1,3 @@ -//! The dispatcher, the worker pool and the reaper (§8.2), plus the retry policy -//! (§8.4). These drive the real threads and the real claim transaction — the -//! crash-recovery claims in §2 are only worth anything if the lease machinery is -//! actually exercised, not asserted in a comment. - mod common; use std::sync::atomic::AtomicBool; @@ -32,8 +27,7 @@ fn pass(env: &Env) -> Vec<String> { #[test] fn the_deterministic_build_id_makes_re_enqueue_a_noop() { - // §8.2: re-submitting the same intent is an INSERT OR IGNORE no-op, which is - // what makes a careless "rebuild that again" harmless. + // §8.2: re-submitting the same intent is an INSERT OR IGNORE no-op. let (env, _fx) = env_with_fixture("plain-make"); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -72,9 +66,7 @@ fn backpressure_admits_no_more_than_max_concurrent_builds() { fn disk_headroom_is_part_of_backpressure() { let (mut env, _fx) = env_with_fixture("plain-make"); queued_build(&env, "plain-make"); - // Ask for more free space than any machine has: nothing is admitted. A build - // that cannot fit on disk stays queued instead of filling the filesystem - // halfway through a compile (§8.2). + // Ask for more free space than any machine has: nothing is admitted (§8.2). env.cfg.min_free_disk_mb = u64::MAX / 2; assert_eq!(dispatch::admissible(&env.cfg, &env.db), 0); assert!(pass(&env).is_empty(), "claimed a build with no disk headroom"); @@ -89,8 +81,7 @@ fn disk_headroom_is_part_of_backpressure() { fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { // The reaper pass is the whole crash-recovery story: a worker that died // mid-step leaves a leased row and a running step, and the next pass turns - // that back into queued + interrupted so the checkpoint decides where it - // resumes (I5). + // that back into queued + interrupted (I5). let (env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); assert_eq!(pass(&env), vec![id.clone()]); @@ -117,8 +108,7 @@ fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { #[test] fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() { // §8.2 cancellation: a superseded candidate marks the running build - // cancel_requested; the worker stops at the next boundary rather than - // finishing work nobody asked for. + // cancel_requested; the worker stops at the next boundary. let (env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); pass(&env); @@ -134,9 +124,8 @@ fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() { #[test] fn a_deterministic_build_failure_is_not_retried() { - // §8.4: a build that fails for a deterministic reason stays failed at - // attempt 1. Burning another chroot to reproduce the same failure helps - // nobody; the release stays approved_but_unbuilt and the UI says so. + // §8.4: a build that fails for a deterministic reason stays failed at attempt + // 1; burning another chroot to reproduce the same failure helps nobody. let (env, _fx) = env_with_fixture("build-fails"); let id = queued_build(&env, "build-fails"); let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone()); @@ -153,10 +142,8 @@ fn a_deterministic_build_failure_is_not_retried() { #[test] fn a_transient_failure_is_retried_up_to_the_cap() { // §8.4: a failure the outside world caused is retried, up to a bound. This - // drives the real path: detection recorded a `SKIP` source's digest, then - // the bytes became unreachable and the cache was dropped, so the build's - // `sources` step has to fetch and gets an `Http` failure — the class a - // flaky mirror produces. + // drives the real path: the build's `sources` step has to fetch and gets an + // `Http` failure — the class a flaky mirror produces. let (mut env, fx) = env_with_fixture("skip-checksum"); let id = queued_build(&env, "skip-checksum"); std::fs::remove_file(fx.data.join("payload.bin")).expect("payload exists"); @@ -178,10 +165,9 @@ fn a_transient_failure_is_retried_up_to_the_cap() { #[test] fn a_missing_toolchain_is_not_retried() { - // m-14: this used to be the transient test. A missing `makepkg` - // surfaces as an `Io` error, and `Io` used to mean "retry" — so a - // misconfigured host or a full disk burned every attempt and then went - // quiet. It is deterministic: the tool is not going to appear. + // m-14: this used to be the transient test. A missing `makepkg` surfaces as + // an `Io` error, and `Io` used to mean "retry". It is deterministic: the tool + // is not going to appear. let (mut env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); env.cfg.makepkg_bin = "/nonexistent/makepkg-for-test".into(); @@ -215,9 +201,8 @@ fn the_pool_takes_a_queued_build_all_the_way_to_publication() { #[test] fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { - // I5 through the dispatcher rather than a direct run(): a build that dies - // late is requeued, re-claimed, and finishes from its checkpoints — the - // expensive steps are not done again. + // I5 through the dispatcher rather than a direct run(): a build that dies late + // is requeued, re-claimed, and finishes from its checkpoints. let (mut env, fx) = env_with_fixture("plain-make"); let c = queued_candidate(&env, "plain-make"); let first = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); @@ -233,13 +218,10 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { )); let builds_before = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); - // The worker "died" at publish: the row is leased with a lease nobody will - // extend. A fresh dispatcher reaps it and a worker finishes from the - // checkpoints. + // The worker "died" at publish: the row is leased to a worker that is no + // longer running, with a lease nobody will extend. A fresh dispatcher reaps it + // and a worker finishes from the checkpoints. env.clear_publish_fault(); - // The crash shape: the row is leased to a worker that is no longer running, - // with a lease nobody will extend. A fresh dispatcher reaps it and a worker - // finishes from the checkpoints. env.exec( "UPDATE build SET state='leased', lease_owner='dead-worker', lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", diff --git a/tests/failure_modes.rs b/tests/failure_modes.rs index bea00a2..74794b4 100644 --- a/tests/failure_modes.rs +++ b/tests/failure_modes.rs @@ -1,8 +1,3 @@ -//! The failure-mode tier: a `FakeBackend` decorator that breaks sandboxes on -//! purpose, so the recovery paths are executed rather than described. Every -//! scenario runs rootless, offline, against the real step machine — the same -//! philosophy as the shims (§16a), one layer up. - mod common; use std::sync::Arc; @@ -106,9 +101,8 @@ fn run_with_fault(env: &Env, id: &str, fault: Fault) -> pipeline::Outcome { #[test] fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_build() { - // I5 across the sandbox boundary: the box vanishes mid-build, the build - // fails its step, the lease expires, and a fresh worker resumes from the - // checkpoints with a healthy pool. + // I5 across the sandbox boundary: the box vanishes mid-build, the lease + // expires, and a fresh worker resumes from the checkpoints. let (env, _fx) = env_with_fixture("plain-make"); let id = approve_and_enqueue(&env, "plain-make"); @@ -120,8 +114,7 @@ fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_bu other => panic!("{other:?}"), } - // The crash shape the dispatcher reaper knows: leased to a worker that is - // gone, with a lease nobody will extend. + // The crash shape the dispatcher reaper knows: leased to a worker that is gone. env.exec( "UPDATE build SET state='leased', lease_owner='dead-worker', lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", @@ -129,8 +122,7 @@ fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_bu ); assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); - // Requeue and resume on a healthy pool: the completed steps do not re-run - // and the build lands. + // Requeue and resume on a healthy pool: the completed steps do not re-run. assert!(matches!( pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. } @@ -179,10 +171,9 @@ fn a_full_pool_blocks_the_build_instead_of_breaking_it() { #[test] fn an_incomplete_closure_fails_closed_as_a_world_mismatch() { - // dep-client's lease pins plain-make; the fake sandbox installs it but - // its `pacman -Q` comes back empty — the world lied. Provisioning must - // refuse with its own error class, not build against a world that is - // not the one the plan approved. + // dep-client's lease pins plain-make; the fake sandbox installs it but its + // `pacman -Q` comes back empty — the world lied. Provisioning must refuse with + // its own error class. let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); let id = approve_and_enqueue(&env, "plain-make"); assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. })); diff --git a/tests/hash.rs b/tests/hash.rs index 427f8ae..46ecdb4 100644 --- a/tests/hash.rs +++ b/tests/hash.rs @@ -1,19 +1,10 @@ -//! The digest helpers (§3, §5.1a). -//! -//! `sha256` hex is the currency of identity and provenance here, and one of -//! those digests — `Identity::hash` — is the value a reviewer's approval echoes -//! back. Everything that guards "we published what we reviewed" rests on that -//! digest being a function of the identity and of nothing else: not of the -//! order fields were declared in, and never of whether serialization happened -//! to fail. - use std::collections::HashMap; use aur_build::db::model::Identity; use aur_build::hash; -/// A value that refuses to be serialized, which is the input the old -/// implementation answered with `"{}"` — a digest every failed value shared. +/// A value that refuses to be serialized — the input the old implementation +/// answered with `"{}"`, a digest every failed value shared. struct Unserializable; impl serde::Serialize for Unserializable { @@ -26,16 +17,15 @@ impl serde::Serialize for Unserializable { fn a_value_that_cannot_be_serialized_is_an_error_not_an_empty_object() { let err = hash::canonical_json(&Unserializable).unwrap_err(); assert!(err.to_string().contains("cannot be serialized"), "the failure was swallowed: {err}"); - // The point of propagating: two different unserializable values now fail - // loudly instead of hashing to the same digest as each other. + // Two different unserializable values now fail loudly instead of hashing to + // the same digest. assert!(hash::canonical_json(&Unserializable).is_err()); } #[test] fn the_rendering_is_canonical_in_fact_not_in_name() { - // Same fields, different declaration order: routed through `Value`, both - // come out with the keys sorted, so the bytes — and any digest of them — - // are the same. + // Same fields, different declaration order: routed through `Value`, both come + // out with the keys sorted. #[derive(serde::Serialize)] struct Ab { alpha: String, diff --git a/tests/http.rs b/tests/http.rs index 0ca8a6b..068f999 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1,11 +1,3 @@ -//! The web surface (§12, §13): routes render, the CSRF gate holds, and a stale -//! approval comes back as a 409 with the current diff instead of a silent -//! retarget. -//! -//! These drive a real `tiny_http` server on an ephemeral loopback port over a -//! real fixture corpus — no mocked transport, because the transport is part of -//! what we are claiming works. - mod common; use aur_build::review::{candidates, diff}; @@ -37,8 +29,7 @@ fn every_surface_renders() { #[test] fn the_review_detail_shows_the_panels_and_the_hashes() { let web = Web::new("plain-make"); - // Publish a first version so the review has something to diff against; - // every panel compares the accepted release to the candidate (§6). + // Publish a first version so the review has something to diff against. let first = web.open_review("plain-make"); let page = web.get(&format!("/reviews/{}", first.id)); let dd = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap(); @@ -57,8 +48,7 @@ fn the_review_detail_shows_the_panels_and_the_hashes() { assert!(page.body.contains(want), "missing panel {want}"); } assert!(page.body.contains("previous accepted release"), "no base shown"); - // The approve form carries both hashes (§7.1a) and is a plain POST form, - // so it works with JavaScript switched off. + // The approve form carries both hashes (§7.1a) and works with JavaScript off. assert!(page.body.contains("name=\"identity_hash\"")); assert!(page.body.contains("name=\"diff_digest\"")); assert!(page.body.contains("<form method=\"post\"")); @@ -148,8 +138,8 @@ fn a_stale_approval_is_a_409_that_renders_the_current_diff() { ); assert_eq!(res.status, 409, "a stale approval must come back as 409"); assert!(res.body.contains("refused"), "no explanation: {}", &res.body[..200.min(res.body.len())]); - // Either way the reviewer is told the ground moved under them, and shown - // the review as it is NOW rather than the one they asked to approve. + // Either way the reviewer is told the ground moved, and shown the review as it + // is NOW rather than the one they asked to approve. assert!( res.body.contains("while you were looking") || res.body.contains("no longer pending"), "not a §7.1a explanation: {}", @@ -191,8 +181,7 @@ fn bulk_approve_refuses_high_risk_without_individual_confirmation() { assert!(res.body.contains("refused"), "bulk approve accepted a high-risk item: {}", &res.body[..300.min(res.body.len())]); assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); - // Confirming it individually lets it through — bulk is per-item, never - // "approve everything forever" (§7.4). + // Confirming it individually lets it through — bulk is per-item (§7.4). let res = web.post( "/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)], @@ -221,19 +210,16 @@ fn a_password_gate_redirects_anonymous_visitors() { #[test] fn a_forged_auth_cookie_is_not_a_session() { - // What this pins: the gate used to read `Cookie: auth=1`, a value login - // merely echoed, so any client that typed the cookie itself could read the - // reviews, the audit log and the build output without ever supplying the - // password. The session id is the credential now, and only this process - // can mint one. + // What this pins: the gate used to read `Cookie: auth=1`, a value login merely + // echoed, so any client that typed the cookie could read the reviews without + // ever supplying the password. The session id is the credential now. let web = Web::with_password("plain-make", "s3cret"); for path in ["/", "/reviews", "/audit", "/settings", "/builds", "/packages"] { let res = web.raw_request("GET", path, &[("Cookie", "auth=1".into())], None); assert_eq!(res.status, 303, "{path} let a forged cookie through ({}): {}", res.status, &res.body[..120.min(res.body.len())]); assert_eq!(res.header("location"), Some("/login"), "{path} did not redirect to the login page"); } - // A POST with the forged cookie is turned away at the gate too, before the - // CSRF step ever gets a chance to mint the attacker a session of their own. + // A POST with the forged cookie is turned away at the gate too. let res = web.raw_request("POST", "/logout", &[("Cookie", "auth=1".into())], Some("")); assert_eq!(res.status, 303, "a forged cookie reached a mutating route"); // And the word "auth" is not a cookie the server recognises anywhere. @@ -257,8 +243,7 @@ fn login_rotates_the_session_and_logout_ends_it() { if !anon.is_empty() { assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status, 303, "the pre-login sid still worked"); } - // Logout drops the sid server-side, which invalidates its CSRF token with - // it, so the same cookie is an anonymous visitor again. + // Logout drops the sid server-side, which invalidates its CSRF token with it. let out = web.raw_request("POST", "/logout", &[("Cookie", session.clone()), ("Content-Type", "application/x-www-form-urlencoded".into())], Some(&format!("csrf={}", web.csrf))); assert_eq!(out.status, 303, "logout did not redirect: {}", out.status); assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session)], None).status, 303, "the logged-out sid still worked"); @@ -266,8 +251,8 @@ fn login_rotates_the_session_and_logout_ends_it() { #[test] fn handlers_read_on_a_read_only_connection() { - // The claim under test: a handler can never take the write lock, because - // the connection it reads through is read-only at the SQLite level. + // The claim under test: a handler can never take the write lock, because the + // connection it reads through is read-only at the SQLite level. let web = Web::new("plain-make"); let err = web .env diff --git a/tests/invariants.rs b/tests/invariants.rs index 770966f..35f5b1a 100644 --- a/tests/invariants.rs +++ b/tests/invariants.rs @@ -1,13 +1,3 @@ -//! The §2 invariant index. -//! -//! Every invariant in DESIGN.md §2 gets a named test here, asserted as a -//! **post-condition on a real end-to-end run** rather than as a unit test of the -//! function that happens to maintain it. If one of these ever fails, the -//! property the whole design rests on is broken, not just some helper. -//! -//! Invariants whose mechanism lands in a later phase are named at the bottom -//! with the test that covers them once it does. - mod common; use aur_build::db::{self, builds, model::*}; @@ -72,8 +62,8 @@ fn i1_every_index_entry_traces_back_to_an_approval() { } /// **I2 — the diff base is the last accepted version, never the last seen one.** -/// Many detections arrive while nobody is looking; the review still compares -/// against the accepted release, not against whatever was polled last. +/// Many detections arrive while nobody is looking; the review still compares against +/// the accepted release. #[test] fn i2_base_is_the_last_accepted_version_after_many_detections() { let (env, fx) = env_with_fixture("plain-make"); @@ -175,8 +165,8 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() { ); // No duplicate side effects: one release row for the version, one artifact. assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1); - // Artifacts are content-addressed and persist across builds; what must not - // happen is the same bytes recorded twice. + // Artifacts are content-addressed; what must not happen is the same bytes + // recorded twice. assert_eq!( count(&env, "SELECT count(*) FROM artifact"), count(&env, "SELECT count(DISTINCT digest) FROM artifact"), @@ -224,8 +214,7 @@ fn i7_the_schema_refuses_a_second_open_review() { } /// **I8 — the served index is exactly the set of accepted pointers.** Not a -/// superset (nothing stale lingers) and not a subset (nothing published is -/// missing). Checked against the files on disk as well as the rows. +/// superset and not a subset. Checked against the files on disk as well as the rows. #[test] fn i8_index_equals_the_accepted_pointers() { let (env, fx) = env_with_fixture("plain-make"); @@ -304,8 +293,7 @@ fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() { /// n-5: a manual rebuild's identity used to be a hand-rolled /// `format!("{commit}|{hash}|manual}")` — a second, incompatible format for the /// same concept, with a delimiter that can occur inside the values. It is now -/// derived through the same canonical-JSON hash as every other identity, and -/// what the change must not disturb is the two properties the queue depends on. +/// derived through the same canonical-JSON hash as every other identity. #[test] fn a_manual_rebuild_is_deterministic_and_its_own_build() { let (env, _fx) = env_with_fixture("plain-make"); @@ -418,19 +406,12 @@ fn index_db_names(path: &std::path::Path) -> Vec<String> { names } -/// I9: build hosts are treated as untrusted — a malicious PKGBUILD must not -/// reach the control plane's data or smuggle foreign bytes into what we publish. +/// I9: build hosts are treated as untrusted — a malicious PKGBUILD must not reach +/// the control plane's data or smuggle foreign bytes into what we publish. /// -/// The real enforcement is the chroot, and that tier is gated. What is *not* -/// gated, and what this pins, is the pipeline's own hygiene: `collect` scans the -/// srcdir for `*.pkg.tar.zst` and `ingest` copies whatever those paths point at -/// into the content-addressed store, from where the bytes are served from our -/// repo and signed with our key. If a build could make one of those paths be a -/// symlink to the signing keyring or the database, isolation would be the only -/// thing standing between a hostile AUR recipe and a signed artifact of our own -/// secret files. It must not be. So the pipeline refuses symlinks and refuses -/// anything that resolves outside the build's own staging directory, and this -/// test acts the attack out rather than arguing it away. +/// `collect` scans the srcdir for `*.pkg.tar.zst` and `ingest` copies whatever those +/// paths point at into the store, from where the bytes are served and signed. So the +/// pipeline refuses symlinks and anything outside the build's own staging directory. #[test] fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() { let (mut env, _fx) = env_with_fixture("plain-make"); diff --git a/tests/kata.rs b/tests/kata.rs index 29a6f29..79bf9d6 100644 --- a/tests/kata.rs +++ b/tests/kata.rs @@ -1,9 +1,3 @@ -//! The kata backend, tested the way every gated tier here is tested: the -//! logic runs for real on a machine with neither root nor `/dev/kvm`, and -//! only the live-orchestrator tier skips — with a printed note, never -//! silently absent (the convention `versions::vercmp_matches_the_system_oracle` -//! set). - mod common; use std::path::Path; @@ -88,14 +82,8 @@ fn the_live_kata_tier_is_recorded_not_silently_absent() { sbx.destroy().unwrap(); } -// --------------------------------------------------------------------------- -// agent-sandbox as a configuration, not a wish. -// -// `sandbox_backend = "kata"` used to fall through to loopback. The kind is -// `agent-sandbox` now, it parses, and it produces a Kata backend — so the path -// from a config file to the CR that would boot a VM is worth asserting end to -// end, starting from parsed JSON rather than a hand-built request. -// --------------------------------------------------------------------------- +// agent-sandbox as a configuration, not a wish: the path from a config file to +// the CR that would boot a VM, asserted end to end from parsed JSON. /// A config file as an operator would write it, parsed by the real loader. fn agent_sandbox_config() -> Config { @@ -176,11 +164,9 @@ fn a_loopback_config_never_becomes_agent_sandbox_or_vice_versa() { assert!(!id.contains("remote@"), "loopback must not report remote: {id}"); } -/// The seam's whole claim, tested as one thing: a real package built and -/// published through the kata lease path — a real `sandbox-agent` process, a -/// real nonce-matched rendezvous, real frames — with a VM being the only thing -/// this host cannot provide. If the lease path and the loopback path disagree -/// about anything, this is where it shows. +/// The seam's whole claim, tested as one thing: a real package built and published +/// through the kata lease path, with a VM being the only thing this host cannot +/// provide. #[test] fn a_fixture_builds_and_publishes_through_the_kata_lease_path() { let (env, _fx) = env_with_fixture("plain-make"); @@ -210,18 +196,15 @@ fn a_fixture_builds_and_publishes_through_the_kata_lease_path() { "the index must serve what the kata build produced: {world:?}" ); - // And it ran inside the leased sandbox: the agent streamed the build output - // over the wire into the same log file the SSE tail reads, and the shim saw - // exactly one makepkg. + // And it ran inside the leased sandbox: the agent streamed the build output over + // the wire into the same log file the SSE tail reads. let log = std::fs::read_to_string(env.cfg.build_log_path(&id)).unwrap(); assert!(log.contains("Making package"), "agent output must reach the log:\n{log}"); let shimlog = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1); - // Deliberately no assertion that the sandbox is gone: the pipeline never - // calls `destroy`, and the design says the TTL is the guarantee and destroy - // is courtesy (wire.rs). The lease window bounds how long a box lives, not - // a teardown call — which is worth knowing, because it means a busy hub - // holds up to `steps x builds` sandboxes until their TTL bites. + // Deliberately no assertion that the sandbox is gone: the design says the TTL is + // the guarantee and destroy is courtesy (wire.rs). A busy hub holds up to + // `steps x builds` sandboxes until their TTL bites. } diff --git a/tests/layers.rs b/tests/layers.rs index 548f475..8566584 100644 --- a/tests/layers.rs +++ b/tests/layers.rs @@ -1,12 +1,3 @@ -//! The dependency direction between modules (§6 M-6, M-7). -//! -//! These are not style rules. The review found the persistence layer naming a -//! type from the VCS watcher, and the reviewer's risk scorer calling back into -//! the watcher for a recipe question — two edges pointing up the stack, which -//! makes `db` and `watch` mutually dependent and means any change to one is a -//! change to the other. A layering rule that is only written down gets violated -//! by the next reasonable-looking commit, so it is a test here. - use std::path::{Path, PathBuf}; fn src_root() -> PathBuf { @@ -57,9 +48,8 @@ fn edges(dir: &str, forbidden: &[&str]) -> Vec<String> { #[test] fn persistence_names_nothing_above_itself() { - // M-6: `db::stage_b_cache_get` used to return `watch::upstream::StageB`, so - // the storage layer could not be understood without the watcher. The row - // type is `db::model::StageBCacheRow` now and the watcher converts. + // M-6: `db::stage_b_cache_get` used to return `watch::upstream::StageB`, so the + // storage layer could not be understood without the watcher. let hits = edges("db", &["watch", "review", "pipeline", "http", "ops", "shims"]); assert!(hits.is_empty(), "src/db depends upward on the modules above it:\n{hits:#?}"); } @@ -67,9 +57,8 @@ fn persistence_names_nothing_above_itself() { #[test] fn review_does_not_call_back_into_the_watcher() { // M-7: `review::risk` called `watch::digests::skip_on_non_vcs` while - // `watch::detect` called `review::candidates` — a cycle. Whether a recipe - // skips verification is a recipe question, so `recipe::skip_on_non_vcs` is - // where it lives and both sides look down, not sideways. + // `watch::detect` called `review::candidates` — a cycle. It now lives in + // `recipe`, and both sides look down, not sideways. let hits = edges("review", &["watch", "pipeline", "http"]); assert!(hits.is_empty(), "src/review depends on modules beside or above it:\n{hits:#?}"); } @@ -82,8 +71,7 @@ fn the_watcher_does_not_reach_into_the_pipeline_or_the_ui() { #[test] fn the_recipe_leaf_depends_on_nothing_above_it() { - // `recipe` is a leaf: parsing and recipe-shaped questions. Everything else - // is allowed to ask it; it may ask nothing. + // `recipe` is a leaf: everything else may ask it; it may ask nothing. let text = std::fs::read_to_string(src_root().join("recipe.rs")).expect("read recipe.rs"); for m in ["watch", "review", "pipeline", "http", "ops", "shims"] { assert!( diff --git a/tests/live.rs b/tests/live.rs index 16b68c5..da0f7ec 100644 --- a/tests/live.rs +++ b/tests/live.rs @@ -1,7 +1,3 @@ -//! The live surfaces: the SSE log tail and the htmx-refreshed builds table -//! (§13). The budget matters here — the whole point of "htmx and thirty lines of -//! glue" is that a reviewer can audit everything the browser runs. - mod common; use std::io::Read; @@ -51,9 +47,8 @@ fn the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends() { std::fs::create_dir_all(log.parent().unwrap()).unwrap(); std::fs::write(&log, "==> step materialize\n").unwrap(); - // A producer appends while the stream is open, then finishes the build. If - // the endpoint buffered its response, everything would arrive only after the - // build ended and the "live" claim would be false. + // A producer appends while the stream is open, then finishes the build. If the + // endpoint buffered its response the "live" claim would be false. let db = web.env.db.clone(); let id2 = id.clone(); let log2 = log.clone(); @@ -101,20 +96,17 @@ fn the_builds_table_refreshes_via_htmx_and_still_works_without_js() { let web = Web::attach(env, fx); let base = web.url("/builds"); - // One queued build so the table has a row: the empty state is a paragraph, - // and asserting on it would prove nothing about server rendering. + // One queued build so the table has a row. queued(&web.env, "plain-make"); let page = ureq::get(&base).call().unwrap().into_string().unwrap(); // The refresh is an attribute on the table, not a script we wrote. assert!(page.contains("hx-trigger=\"every 3s\""), "no htmx refresh: {}", &page[..400.min(page.len())]); assert!(page.contains("hx-get=\"/builds?fragment=1\""), "the refresh has no target"); assert!(page.contains("<script src=\"/static/htmx.min.js\""), "htmx is not loaded"); - // And with JavaScript switched off the same HTML already contains the table: - // the refresh is an enhancement, not a requirement. + // And with JavaScript off the same HTML already contains the table. assert!(page.contains("<table>"), "no server-rendered table"); - // The fragment endpoint returns the table on its own, so htmx can swap it in - // without dragging the whole document along. + // The fragment endpoint returns the table on its own, so htmx can swap it in. let frag = ureq::get(&format!("{base}?fragment=1")).call().unwrap().into_string().unwrap(); assert!(frag.starts_with("<div id=\"builds\""), "fragment is not the table: {}", &frag[..120.min(frag.len())]); assert!(!frag.contains("<!doctype"), "the fragment is a whole page"); @@ -126,9 +118,8 @@ fn htmx_is_the_only_javascript_and_what_is_shipped_fits_the_budget() { let (env, fx) = env_with_fixture("plain-make"); let web = Web::attach(env, fx); // Served bytes are what a browser actually downloads, and that is the budget - // with any meaning: the file on disk is 48 KB, the wire copy is not. - // Read the wire bytes directly: an HTTP client would transparently - // decompress, which is exactly the thing this budget is about. + // with any meaning. An HTTP client would transparently decompress, which is + // exactly what this budget is about, so read the wire directly. let (headers, served) = raw_get(&web, "/static/htmx.min.js", true); assert!(headers.to_lowercase().contains("content-encoding: gzip"), "the vendored js is not compressed: {headers}"); assert!( @@ -159,13 +150,13 @@ fn the_stylesheet_is_served_and_the_review_surface_needs_no_javascript() { assert!(css.contains("body"), "app.css is a placeholder"); let page = web.get("/reviews").body; assert!(page.contains("<link rel=\"stylesheet\" href=\"/static/app.css\">"), "the page does not load it"); - // The review flow is the one that must work with scripting disabled, so it - // deliberately does not load htmx at all. + // The review flow is the one that must work with scripting disabled, so it does + // not load htmx at all. assert!(!page.contains("<script"), "the review surface ships JavaScript"); } -/// Ask for a path over a bare socket so the response is seen as it goes over the -/// wire, before any client-side content negotiation undoes it. +/// Ask for a path over a bare socket so the response is seen before any client-side +/// content negotiation undoes it. fn raw_get(web: &Web, path: &str, gzip: bool) -> (String, Vec<u8>) { use std::io::{BufRead, BufReader, Write}; let addr = web.server.addr.clone(); diff --git a/tests/notices.rs b/tests/notices.rs index 7051acf..1f2852e 100644 --- a/tests/notices.rs +++ b/tests/notices.rs @@ -1,11 +1,3 @@ -//! Non-publishable change handling (§5.2, §5.3) and advisory risk scoring (§6). -//! -//! I11 is the invariant here: **a change that cannot be published is still -//! recorded.** The tempting failure mode is "nothing to approve, so nothing to -//! say" — which is exactly how a silently swapped tarball becomes invisible. -//! Every non-publishable change becomes a `notice` row, and the index keeps -//! serving the artifact it has. - mod common; use aur_build::db::{self, model::*}; @@ -125,8 +117,8 @@ fn risk_scoring_compares_against_the_accepted_release() { assert_eq!(c.risk_level, risk::level::LOW, "signals: {:?}", c.risk_signals()); assert!(!c.risk_signals().iter().any(|s| s.starts_with("recipe-code-changed"))); - // Now change the build body and add a fetching makedep: that is the shape of - // a real supply-chain edit and it must say so. + // Now change the build body and add a fetching makedep: the shape of a real + // supply-chain edit. let path = fx.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); std::fs::write( @@ -158,9 +150,8 @@ fn a_first_introduction_is_flagged_as_its_own_kind_of_review() { #[test] fn i11_nothing_publishable_is_ever_silently_dropped() { - // Sweep every fixture through detection and assert the outcome is always - // one of: a review, a notice, an explicit no-change, or a recorded failure. - // There is no path where something moved and we said nothing. + // Sweep every fixture through detection and assert the outcome is always a + // review, a notice, an explicit no-change, or a recorded failure. let fixtures = [ "plain-make", "with-patch", "skip-checksum", "split-pkgbase", "epoch-bump", "pkgrel-reset", "downgrade", "git-sourced", "pin-drift", "digest-drift", "missing-dep", "build-fails", diff --git a/tests/ops.rs b/tests/ops.rs index 305976e..8fc6308 100644 --- a/tests/ops.rs +++ b/tests/ops.rs @@ -1,12 +1,3 @@ -//! Retention, metrics and backups (§15). -//! -//! These are the features that only get tested when something goes wrong, which -//! is why they are specified here as behaviour rather than as functions that -//! exist. The load-bearing claims: retention never evicts a byte the index is -//! serving, it treats a package and its log and its sources as one unit, and it -//! never deletes the history that explains the bytes. Metrics are computed from -//! live state, so they cannot drift. Backups are `VACUUM INTO`, so they restore. - mod common; use std::path::{Path, PathBuf}; @@ -85,9 +76,8 @@ fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() { assert!(!p.exists(), "an evicted artifact should be gone: {}", p.display()); } - // Nothing was forgotten: the rows are all still there, marked as purged - // rather than removed, so "which bytes produced this" stays answerable as - // history even once the bytes are gone. + // Nothing was forgotten: the rows are all still there, marked as purged rather + // than removed (§15). assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5)); assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5)); assert_eq!( @@ -118,10 +108,9 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { }) .unwrap(); let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap(); - // Compare against what the database says the release holds, rather than - // guessing from filename shapes: the store is content-addressed, so the - // package file is a bare hex name and "does it look like a package" is not - // a question the path can answer. + // Compare against what the database says the release holds: the store is + // content-addressed, so "does it look like a package" is not a question the + // path can answer. let held: Vec<(Option<String>, Option<String>, Option<String>)> = env .db .read(|c| { @@ -150,8 +139,8 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { assert!(Path::new(p).exists(), "the {what} should exist before eviction"); } - // Eviction removes them together. A package whose log is gone but whose bytes - // remain is the worst outcome: full price, no explanation. + // Eviction removes them together: a package whose log is gone but whose bytes + // remain is full price for no explanation. ops::retention(&env.cfg, &env.db, Some(1)).unwrap(); let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect(); assert!( @@ -162,9 +151,8 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { #[test] fn retention_never_evicts_the_version_the_index_is_serving() { - // The interesting case: the accepted release is *not* the newest one, because - // the newest build has not happened yet. A naive "keep the newest N" would - // delete the bytes the index is pointing at. + // The accepted release is *not* the newest one here; a naive "keep the newest + // N" would delete the bytes the index points at. let (env, fx) = env_with_fixture("plain-make"); publish_versions(&env, &fx, "plain-make", 2); let served = env @@ -248,8 +236,7 @@ fn metrics_reports_the_operating_numbers_in_prometheus_format() { let m = ops::metrics(&env.cfg, &env.db).unwrap(); let text = m.to_prometheus(); - // Every family the contract names, and each one parseable as a Prometheus - // sample: `name{labels} value`, preceded by its TYPE line. + // Every family the contract names, each parseable as a Prometheus sample. for family in [ "aurbuild_queue_depth", "aurbuild_pending_review_candidates", @@ -294,8 +281,8 @@ fn metrics_reports_the_operating_numbers_in_prometheus_format() { #[test] fn a_fresh_install_reports_a_clean_sheet_not_a_division_by_zero() { - // A brand-new install has no builds at all. Success rate has to be something - // an alert rule can read, not NaN and not 0% (which would page). + // A brand-new install has no builds at all: success rate has to be something an + // alert rule can read, not NaN and not 0%. let env = Env::new(); let m = ops::metrics(&env.cfg, &env.db).unwrap(); assert_eq!(m.succeeded + m.failed, 0); @@ -329,8 +316,7 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { let out = ops::backup(&env.db, &dest).unwrap(); assert_eq!(out, dest); - // A single file: `VACUUM INTO` produces a compacted database with no WAL, so - // the backup is one object that can be copied while the server keeps running. + // A single file: `VACUUM INTO` produces a compacted database with no WAL. assert!(dest.exists()); assert!(!Path::new(&format!("{}-wal", dest.display())).exists(), "a backup must not need a sidecar"); assert!(!Path::new(&format!("{}-shm", dest.display())).exists()); @@ -346,8 +332,7 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { assert_eq!(releases, 1); drop(probe); - // The live database is untouched and still in WAL mode — the backup did not - // checkpoint it out from under the running server. + // The live database is untouched and still in WAL mode. let mode: String = env .db .read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?)) @@ -358,8 +343,8 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { #[test] fn backup_refuses_to_overwrite_an_existing_snapshot() { - // A backup that silently replaces last week's backup is not a backup; it is a - // way of losing the only copy on the day you need it. + // A backup that silently replaces last week's backup is a way of losing the + // only copy on the day you need it. let (env, _fx) = env_with_fixture("plain-make"); approve_and_build(&env, "plain-make"); let dest = env.root().join("snap.db"); @@ -370,8 +355,7 @@ fn backup_refuses_to_overwrite_an_existing_snapshot() { assert!(std::fs::metadata(&dest).unwrap().len() > 0); } -/// Set a directory's mtime into the past, so the grace period can be exercised -/// without sleeping for an hour. +/// Set a directory's mtime into the past, so the grace period can be exercised. fn backdate(path: &Path, secs: u64) { let old = std::time::SystemTime::now() - std::time::Duration::from_secs(secs); for f in std::fs::read_dir(path).into_iter().flatten().flatten() { diff --git a/tests/pipeline.rs b/tests/pipeline.rs index d4ef724..6dd1df5 100644 --- a/tests/pipeline.rs +++ b/tests/pipeline.rs @@ -1,6 +1,3 @@ -//! End-to-end pipeline tests driven entirely by the toolchain shims (§16a): -//! no root, no network, no real chroot — but the *real* step machine runs. - mod common; use aur_build::db::{self, builds, model::*}; @@ -86,11 +83,9 @@ fn end_to_end_publishes_a_signed_index() { #[test] fn the_build_never_signs_ingest_does() { - // Signing moved hub-side: the build environment is a sandbox that must - // never hold the key, so the build command carries no `-si` and the - // signature over each artifact is made at ingest by the hub's own gpg. - // This is the property that makes a remote build sandbox safe to run at - // all — worst the sandbox ever returns is unsigned bytes. + // Signing moved hub-side: the build command carries no `-si` and the signature + // over each artifact is made at ingest by the hub's own gpg. Worst the sandbox + // ever returns is unsigned bytes. let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); @@ -119,10 +114,8 @@ fn the_build_never_signs_ingest_does() { #[test] fn a_tampered_store_artifact_fails_the_lease_closed() { - // dep-client depends on plain-make, so its lease pins plain-make's exact - // artifact. Corrupt the store bytes after publication: provisioning - // re-hashes everything it stages and must refuse, not build against bytes - // that are not what the index — and the review behind it — approved. + // Corrupt the store bytes after publication: provisioning re-hashes everything + // it stages and must refuse, not build against bytes the index never approved. let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); let c = approve_fixture(&env, "plain-make"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); @@ -152,9 +145,8 @@ fn a_tampered_store_artifact_fails_the_lease_closed() { other => panic!("{other:?}"), } - // Restore the bytes and resume: the lease verifies, the sandbox's own - // `pacman -Q` confirms the pinned world landed, and the build completes — - // which is the happy provisioning path proven end to end as well. + // Restore the bytes and resume: the lease verifies, the sandbox's `pacman -Q` + // confirms the pinned world landed, and the build completes. std::fs::write(&path, &original).unwrap(); assert!( matches!(pipeline::run(&env.cfg, &env.db, &id2).unwrap(), pipeline::Outcome::Succeeded { .. }), @@ -281,9 +273,8 @@ fn i4_kill_mid_publish_leaves_the_old_index_intact() { let out = run_for(&env, &c2); assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}"); - // The served database is byte-for-byte the old one, and the DB never - // recorded the new release: consumers saw either the old world or the new - // one, never a half-written index (I4). + // The served database is byte-for-byte the old one, and the DB never recorded + // the new release: consumers saw either the old world or the new one (I4). assert_eq!(std::fs::read(&v1).unwrap(), before); assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); assert_eq!( @@ -310,8 +301,8 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() { aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); assert_eq!(builds_after_crash, 2, "one real build before the crash"); - // "Restart": same build row, no fault. Steps 0-8 are checkpointed as - // succeeded, so only publish re-runs — the expensive step is not repeated. + // "Restart": same build row, no fault. Only publish re-runs; the expensive + // steps are checkpointed. env.clear_publish_fault(); match pipeline::run(&env.cfg, &env.db, &id).unwrap() { pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0), @@ -373,8 +364,8 @@ fn a_failed_build_leaves_the_previous_version_serving() { #[test] fn an_unresolvable_dependency_blocks_instead_of_failing() { let (env, _fx) = env_with_fixture("missing-dep"); - // We subscribe to `dep-partner` but have never published it: that is exactly - // "unresolvable" in §10.4, and the answer is to wait, not to fail. + // We subscribe to `dep-partner` but have never published it: "unresolvable" in + // §10.4 means wait, not fail. env.subscribe("dep-partner"); let c = approve_fixture(&env, "missing-dep"); let out = run_for(&env, &c); @@ -397,9 +388,8 @@ fn a_blocked_build_waits_until_its_dependency_actually_arrives() { let c = approve_fixture(&env, "missing-dep"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Blocked { .. })); assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1); - // The dispatcher sweeps blocked builds every pass. Requeueing one whose - // blocker is still missing would block again immediately — a busy loop that - // burns a claim and a plan step each tick — so it must stay put. + // The dispatcher sweeps blocked builds every pass. Requeueing one whose blocker + // is still missing would block again immediately, so it must stay put. let _ = publish::reconcile(&env.cfg, &env.db); assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked"); assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1); @@ -489,9 +479,8 @@ fn publish_refuses_without_an_approval_behind_it() { let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); run_for(&env, &c); - // Approval rows are immutable (I10 / §7.2), so we build the bad state from - // the other side: a release with nothing behind it. A rebuild of it must - // still refuse to publish — the guard is on publishing, not on noticing. + // Approval rows are immutable (I10 / §7.2), so the bad state is built from the + // other side: a release with nothing behind it. let rid = db::accepted_release(&env.db, "plain-make").unwrap().unwrap().id; env.exec("UPDATE release SET approval_id=NULL WHERE id=?1", ¶ms(vec![rid])); let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap(); @@ -531,8 +520,7 @@ fn a_stale_accepted_pointer_refuses_to_publish() { #[test] fn withdrawing_a_release_twice_is_refused_the_second_time() { - // m-10: the second withdraw used to report success while rewriting nothing, - // so an operator who clicked twice got a green result and no explanation. + // m-10: the second withdraw used to report success while rewriting nothing. let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); run_for(&env, &c); @@ -549,8 +537,7 @@ fn withdrawing_a_release_twice_is_refused_the_second_time() { #[test] fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() { // m-16: the artifacts are copied into the served tree before the DB commit, - // and when the commit refused, those bytes used to stay — files no index - // names, sitting in the directory consumers download from. + // and when the commit refused those bytes used to stay. let (mut env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); env.set_publish_fault("before-rename"); @@ -567,8 +554,8 @@ fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() { .collect(); assert!(stray.is_empty(), "a publish that did not land left files behind: {stray:?}"); - // And the retry still works: the artifacts come from the collect dir, not - // from the served tree, so cleaning up costs nothing but the copy. + // And the retry still works: the artifacts come from the collect dir, not the + // served tree. env.clear_publish_fault(); assert!( matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }), diff --git a/tests/production_surface.rs b/tests/production_surface.rs index e978a2c..e4e1346 100644 --- a/tests/production_surface.rs +++ b/tests/production_surface.rs @@ -1,17 +1,3 @@ -//! The production surface cannot see the test scaffolding (§6 M-4, M-9). -//! -//! The shim harness is load-bearing: the whole step machine is tested by driving -//! the real binaries with fakes for `makepkg`, `mkarchroot`, `gpg` and friends. -//! That is fine. What is not fine is production code reaching into it — the -//! publish path once read a package's name through the shim module's copy of the -//! `.PKGINFO` parser, which meant the bytes we signed and the bytes the tests -//! believed were parsed by two pieces of code that could drift apart. -//! -//! The compile-time half of this rule is real: `shims` is compiled out unless the -//! `test-support` feature is on, and only this crate's own dev-dependency turns -//! it on. This test covers the half the compiler cannot: a module in `src/` -//! naming the scaffolding directly. - use std::path::{Path, PathBuf}; fn read(rel: &str) -> String { @@ -64,9 +50,7 @@ fn no_production_module_references_the_shim_harness() { #[test] fn the_served_index_has_exactly_one_serialization_lock() { // §6 M-5: two mutexes in `publish.rs`, each documented as *the* "one publish - // per repo" guarantee, with `withdraw_package` taking only one of them, is - // worse than either answer — a reader cannot tell whether the guarantee is - // redundant or incomplete. There is one lock now, and this keeps it that way. + // per repo" guarantee, is worse than either answer. There is one lock now. let src = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/pipeline/publish.rs")) .expect("read publish.rs"); let mutexes = src @@ -104,10 +88,8 @@ fn the_shim_binaries_are_test_only() { #[test] fn the_test_hooks_are_a_gated_submodule_not_config_fields() { - // §6 M-9: fault injection in the publish hot path, shim environment - // variables and clock pinning were part of the production API surface — - // `Config` advertised `publish_fault` next to `signing_key_id`, and the - // branch that reads it sat in the middle of every real publish. + // §6 M-9: fault injection in the publish hot path, shim environment variables + // and clock pinning were part of the production API surface. let cfg_src = read("src/config.rs"); for field in [ "pub path_prepend", @@ -131,8 +113,8 @@ fn the_test_hooks_are_a_gated_submodule_not_config_fields() { #[test] fn the_publish_hot_path_has_no_ungated_test_branch() { - // The two fault-injection points in `publish()` are the ones that ran on - // every real publish. Each must sit behind the feature gate. + // The two fault-injection points in `publish()` must sit behind the feature + // gate. let src = read("src/pipeline/publish.rs"); let lines: Vec<&str> = src.lines().collect(); let mut gated = 0; @@ -162,10 +144,8 @@ fn a_default_config_has_no_hooks_attached() { #[test] fn the_review_modules_do_not_keep_private_copies_of_the_rules() { - // §6 m-2: `hosts` existed twice, verbatim, and the "did the executable part - // of the recipe change" rule existed twice with *different* semantics — the - // diff panel compared function header lines, the risk scorer compared the - // bodies. One question, one answer, in the module that owns the subject. + // §6 m-2: `hosts` existed twice, verbatim, and the "did the executable part of + // the recipe change" rule existed twice with *different* semantics. for (file, forbidden) in [ ("src/review/diff.rs", ["fn hosts(", "fn body_changed("]), ("src/review/risk.rs", ["fn hosts(", "fn body_changed("]), @@ -184,7 +164,7 @@ fn the_review_modules_do_not_keep_private_copies_of_the_rules() { #[test] fn audit_rows_are_built_by_the_constructors_not_by_hand() { // §6 m-4: three review sites hand-built `AuditEntry` literals, each with its - // own `detail` shape and its own spelling of `actor_kind`. + // own `detail` shape. let src = read("src/review/approve.rs"); assert!(!src.contains("db::AuditEntry {"), "audit rows must be built by AuditEntry::human/system"); assert_eq!(src.matches("AuditEntry::human(").count(), 3, "approve, reject and withdraw"); diff --git a/tests/remote_agent.rs b/tests/remote_agent.rs index 24e259e..af4ac60 100644 --- a/tests/remote_agent.rs +++ b/tests/remote_agent.rs @@ -1,8 +1,3 @@ -//! The remote-builder path, end to end: a real build driven over the real -//! agent protocol against the §16a shims. No root, no network beyond a -//! loopback socket, no container — but the frames, the rendezvous, the log -//! streaming and the blob transfer are the production ones. - mod common; use std::io::Read; @@ -44,8 +39,7 @@ fn a_full_build_runs_over_the_agent_protocol() { .expect("spawn sandbox-agent"); let out = pipeline::run_with(&ctx).unwrap(); - // Kill *and* reap: an unreaped child is a zombie the next test inherits, and - // clippy is right that a spawn nobody waits on is unfinished business. + // Kill *and* reap: an unreaped child is a zombie the next test inherits. let _ = agent.kill(); let _ = agent.wait(); assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}"); @@ -57,8 +51,8 @@ fn a_full_build_runs_over_the_agent_protocol() { "agent-streamed output must reach the build log:\n{log}" ); - // The build really ran as the agent's child, with the shim protocol - // applied from the Run frame's environment. + // The build really ran as the agent's child, with the shim protocol applied + // from the Run frame's environment. let shimlog = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1); } @@ -98,14 +92,9 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() { let _ = bad.wait(); } -// --------------------------------------------------------------------------- -// One listener per process. -// -// `Ctx::new` used to construct a backend for every build, and constructing a -// remote backend bound the agent listener. So a second concurrent build on a -// fixed `listen` died of EADDRINUSE — a build failing for a reason that had -// nothing to do with its package. The listener is a property of the process now. -// --------------------------------------------------------------------------- +// One listener per process. Constructing a remote backend bound the agent +// listener, so a second concurrent build on a fixed `listen` died of EADDRINUSE +// for a reason that had nothing to do with its package. fn remote_cfg(listen: &str, token: &str) -> aur_build::config::Config { aur_build::config::Config { @@ -119,7 +108,7 @@ fn remote_cfg(listen: &str, token: &str) -> aur_build::config::Config { } /// A port nothing is holding, so two backends can be asked for the *same* fixed -/// address — which is the only case where double-binding shows up. +/// address — the only case where double-binding shows up. fn free_port() -> u16 { let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); @@ -136,19 +125,17 @@ fn two_builds_share_one_agent_listener() { let (sa, sb) = (&a.status().unwrap()[0].id, &b.status().unwrap()[0].id); assert_eq!(sa, sb, "both must report the one listener: {sa} vs {sb}"); assert!(sa.contains(&addr), "and it must be the configured address: {sa}"); - // Why the sharing matters, asserted rather than assumed: a raw second bind - // on a listening address is EADDRINUSE (Rust binds and listens together, so - // SO_REUSEADDR does not rescue it). If this ever passes, the test above is - // vacuous and the regression it guards is back. + // Why the sharing matters, asserted rather than assumed: a raw second bind on a + // listening address is EADDRINUSE. If this ever passes, the test above is + // vacuous. assert!( std::net::TcpListener::bind(&addr).is_err(), "a second bind on {addr} must fail, or nothing here proves anything" ); } -/// Sharing the listener means sharing the queue of dial-ins, which is exactly -/// the semantics `remote` already has: an agent dials in when the operator -/// boots one, and whichever build is waiting takes it. +/// Sharing the listener means sharing the queue of dial-ins: an agent dials in when +/// the operator boots one, and whichever build is waiting takes it. #[test] fn a_dial_in_goes_to_whichever_backend_is_waiting() { let addr = format!("127.0.0.1:{}", free_port()); @@ -179,9 +166,6 @@ fn a_different_token_on_the_same_address_is_refused_not_shared() { } /// The contract in its literal shape: two workers, two builds, one listener. -/// Each worker builds a `Ctx`, and building a `Ctx` used to bind the listener — -/// so the second worker's build died of EADDRINUSE before it looked at its -/// package at all. #[test] fn two_concurrent_builds_do_not_fight_over_the_listener() { let addr = format!("127.0.0.1:{}", free_port()); diff --git a/tests/schema_ownership.rs b/tests/schema_ownership.rs index dac93d6..07345dd 100644 --- a/tests/schema_ownership.rs +++ b/tests/schema_ownership.rs @@ -1,15 +1,3 @@ -//! The schema has one owner (§6 M-1). -//! -//! `db/` is a boundary, not a directory, only if SQL cannot land anywhere else. -//! Part of that is a compile-time fact: `Writer::call`, `tx` and `send` are -//! `pub(crate)`, and the raw door the test harness uses exists only under the -//! `test-support` feature. What the compiler cannot express is the other half — -//! that no module *inside* this crate writes a statement of its own. This does. -//! -//! The rule it enforces: a SQL statement, or a rusqlite statement call, appears -//! in `src/db/` and nowhere else. A module that needs the database asks `db/` -//! for a typed query; if the query does not exist, that is the change to make. - use std::path::{Path, PathBuf}; /// String literals that begin a statement. Matched on the quote so a prose @@ -73,11 +61,9 @@ fn no_sql_statements_outside_the_db_module() { } /// m-18: the version a human reads is `pkgver::full_version`'s to produce — -/// `epoch:pkgver-pkgrel`, with the epoch omitted when it is `0` or empty. That -/// rule used to exist twice, once in Rust and once as a `CASE WHEN epoch='0'` -/// inside `approved_but_unbuilt`, where a change to one would silently make the -/// Attention page disagree with every other page about what a version looks -/// like. SQL selects the parts; Rust formats them. +/// `epoch:pkgver-pkgrel`, with the epoch omitted when it is `0` or empty. That rule +/// used to exist twice, once in Rust and once in SQL. SQL selects the parts; Rust +/// formats them. #[test] fn only_rust_formats_a_version() { let root = Path::new(env!("CARGO_MANIFEST_DIR")); diff --git a/tests/shims.rs b/tests/shims.rs index d512bd7..d06a81e 100644 --- a/tests/shims.rs +++ b/tests/shims.rs @@ -1,7 +1,3 @@ -//! The §16a test harness itself: toolchain shims and the fake-package corpus. -//! -//! If these tests fail, nothing above the harness can be trusted. - mod common; use std::path::{Path, PathBuf}; @@ -62,9 +58,7 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst"); assert!(pkg.exists(), "artifact left in the build dir like the real tool does"); let bytes = std::fs::read(&pkg).unwrap(); - // Read the artifact with the production parser, not a shim-only one: the - // harness is only a faithful stand-in if it reads a package the way the - // pipeline will (§6 M-4). + // Read the artifact with the production parser, not a shim-only one (§6 M-4). let pkginfo = aur_build::pkginfo::pkginfo_text(&bytes).unwrap(); assert!(pkginfo.contains("pkgname = plain-make")); assert!(pkginfo.contains("pkgver = 1.0-1")); @@ -86,8 +80,8 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { #[test] fn makechrootpkg_refuses_a_missing_pkgbuild() { - // Step 0 materializes from the mirror; if that silently produced nothing, - // the fake tool must notice rather than build an empty package. + // Step 0 materializes from the mirror; if that silently produced nothing, the + // fake tool must notice rather than build an empty package. let tmp = tempfile::tempdir().unwrap(); let build = tmp.path().join("build"); std::fs::create_dir_all(&build).unwrap(); @@ -176,9 +170,8 @@ fn repo_add_writes_a_pacman_database() { #[test] fn pacman_u_verifies_digests_and_q_reports_the_world() { - // The provisioning step's fail-closed world check runs against this fake: - // `-U` must refuse bytes that do not hash to the digest their name claims, - // and `-Q` must report exactly what landed. + // The provisioning step's fail-closed world check runs against this fake: `-U` + // must refuse bytes that do not hash to the digest their name claims. let tmp = tempfile::tempdir().unwrap(); let log = tmp.path().join("shimlog"); std::fs::create_dir_all(&log).unwrap(); @@ -208,8 +201,8 @@ fn pacman_u_verifies_digests_and_q_reports_the_world() { assert_eq!(code, 0); assert!(out.contains("plain-make 1.0-1"), "the world check reads -Q: {out}"); - // A blob whose bytes do not match the digest its name claims is refused - // like a bad signature: name it with some other digest's hex. + // A blob whose bytes do not match the digest its name claims is refused like a + // bad signature. let bad = tmp.path().join(aur_build::hash::hex(b"some other artifact")); std::fs::write(&bad, b"tampered").unwrap(); let (code, _, err) = shim( @@ -251,8 +244,8 @@ fn mkarchroot_creates_a_warm_root() { assert!(root.join("SHIM-ROOT").exists()); } -/// Every fixture in the corpus must be drivable through the shims. This is the -/// executable documentation of the §16 edge cases. +/// Every fixture in the corpus must be drivable through the shims: the executable +/// documentation of the §16 edge cases. #[test] fn every_fixture_is_drivable_through_the_shims() { let mut names = Vec::new(); @@ -359,16 +352,10 @@ fn shim_environment_reaches_child_processes_through_the_config() { assert!(s.contains("manifest.json"), "{s}"); } -// --------------------------------------------------------------------------- -// repo-add's database filename. -// -// The shim used to write the database wherever it was told to, and the pipeline -// took that literally: it rendered the index to `<db>.tar.gz.tmp` and renamed it -// into place. Real repo-add rejects that filename as a usage error, so every -// publish test in this suite passed while the first real package anyone tried to -// publish died at the last step. A shim must be as strict as the tool it stands -// in for, or it is not a test of the tool. -// --------------------------------------------------------------------------- +// repo-add's database filename. A shim must be as strict as the tool it stands in +// for: the pipeline used to render the index to `<db>.tar.gz.tmp`, real repo-add +// rejects that as a usage error, and every publish test passed while the first +// real package died at the last step. /// Names pacman's repo-add accepts as its database argument, measured against /// `repo-add (pacman) 7.1.0` rather than guessed from its docs. @@ -407,8 +394,7 @@ fn repo_add_shim_refuses_a_database_name_repo_add_refuses() { } /// The oracle, when the host has one: the shim's verdict must be the real tool's -/// verdict, name for name. Gated and noted rather than skipped silently, in the -/// shape of `versions::vercmp_matches_the_system_oracle`. +/// verdict, name for name. #[test] fn repo_add_db_names_match_the_real_repo_add() { if Command::new("repo-add").arg("--version").output().is_err() { @@ -431,8 +417,7 @@ fn repo_add_db_names_match_the_real_repo_add() { } /// The regression itself, asserted on the pipeline rather than on the shim: what -/// filename does publish actually hand repo-add, and does it clean up after -/// itself while doing it? +/// filename does publish actually hand repo-add? #[test] fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() { let web = Web::new("plain-make"); @@ -458,9 +443,8 @@ fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() { "publish passed {db}, which repo-add would refuse" ); - // The render happens in a scratch directory beside the live database, under - // the name a consumer will download, and is gone once the rename lands. A - // leftover would mean a publish that died on a path that never cleaned up. + // The render happens in a scratch directory beside the live database, under the + // name a consumer will download, and is gone once the rename lands. let arch = web.env.cfg.repo_arch_dir(); let leftovers: Vec<String> = std::fs::read_dir(&arch) .unwrap() diff --git a/tests/staleness.rs b/tests/staleness.rs index bebceb4..cadfc69 100644 --- a/tests/staleness.rs +++ b/tests/staleness.rs @@ -1,11 +1,3 @@ -//! Staleness, blocked builds and the dependents question (§10). -//! -//! The design's position is that staleness is a fact to be shown, not a state to -//! be stored: there is no automatic rebuild engine, and no `stale` column, because -//! a stored flag goes wrong the moment anything else is published and something -//! else always is. These tests pin that down — including the part that is easy to -//! fake, which is that the derivation is real and not a cached answer. - mod common; use aur_build::db::{builds, model::*}; @@ -46,8 +38,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { assert_eq!(stale[0].built_with, "1.0-1"); assert_eq!(stale[0].now, "2.0-1"); - // "Derived purely on read" has to mean there is nowhere for a stale answer to - // hide. No column on any table stores it. + // "Derived purely on read" means there is nowhere for a stale answer to hide. let cols: Vec<String> = env .db .read(|c| { @@ -62,7 +53,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { assert!(cols.is_empty(), "staleness must not be persisted anywhere: {cols:?}"); // The answer tracks the index, not any stored flag: withdrawing plain-make - // changes what is true about dep-client without touching dep-client at all. + // changes what is true about dep-client without touching it. pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap(); let after = staleness::stale_rows(&env.db).unwrap(); assert!( @@ -82,7 +73,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { fn a_missing_dependency_blocks_the_build_and_names_the_blocker_everywhere() { let (env, fx, _partner) = env_with_two_fixtures("missing-dep", "dep-partner"); // dep-partner is a package we intend to publish but have not yet: the build - // cannot run, and that is a fact to report rather than a failure to retry. + // cannot run, and that is a fact to report (§10.4). let c = approved(&env, "missing-dep"); assert_eq!(c.missing_deps(), vec!["dep-partner".to_string()], "the review must warn before approving"); let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); @@ -118,16 +109,14 @@ fn a_blocked_build_waits_and_is_requeued_only_when_the_blocker_arrives() { assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked"); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::BlockedMissingDep); - // Publishing dep-partner is what unblocks it. A build that was blocked and - // can now run is not a new decision — a human already approved it (§10). + // Publishing dep-partner is what unblocks it: a human already approved it. publish(&env, "dep-partner"); assert!( aur_build::db::our_package_names(&env.db).unwrap().contains("dep-partner"), "dep-partner should be in the index now: {:?}", aur_build::db::our_package_names(&env.db) ); - // Publishing the blocker requeues what was waiting on it — the publish path - // sweeps blocked builds itself, so an explicit call afterwards is a no-op. + // Publishing the blocker requeues what was waiting on it. assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued, "the blocker arrived and the build stayed blocked"); assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "nothing left to requeue"); @@ -152,8 +141,7 @@ fn the_review_page_warns_about_missing_deps_before_approval() { #[test] fn the_review_page_answers_what_approving_this_would_disturb() { - // §10.3: "approving this marks N packages stale". A reviewer approving a - // plain-make bump needs to know that dep-client is about to need a rebuild. + // §10.3: "approving this marks N packages stale". let (env, plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); publish(&env, "plain-make"); publish(&env, "dep-client"); @@ -182,8 +170,8 @@ fn a_dependency_we_stopped_publishing_shows_as_missing_not_outdated() { let (env, _plain, client) = env_with_two_fixtures("plain-make", "dep-client"); publish(&env, "plain-make"); publish(&env, "dep-client"); - // Withdraw plain-make from the index: dep-client was built against it and now - // depends on something we no longer serve. + // Withdraw plain-make from the index: dep-client now depends on something we + // no longer serve. pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap(); let stale = staleness::stale_rows(&env.db).unwrap(); diff --git a/tests/state_machine.rs b/tests/state_machine.rs index 1c05fff..a8d9b35 100644 --- a/tests/state_machine.rs +++ b/tests/state_machine.rs @@ -1,9 +1,3 @@ -//! The build state machine (§6 M-8). -//! -//! Before this was an enum, `set_state(&str)` wrote any string a caller -//! invented and the machine lived only in `WHERE state IN (...)` clauses. These -//! tests are the ones that would have failed then. - mod common; use aur_build::db::{builds, model::{BuildState, CandidateState, StepState}}; @@ -38,8 +32,7 @@ fn the_machine_refuses_a_transition_it_does_not_define() { let id = build(&env, "b1"); assert_eq!(state(&env, "b1"), BuildState::Queued); - // Queued → Succeeded: a build cannot finish without running. Before the - // enum this wrote happily and produced a succeeded build that never built. + // Queued → Succeeded: a build cannot finish without running. let err = builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap_err(); assert!(err.to_string().contains("illegal build transition"), "{err}"); assert_eq!(state(&env, "b1"), BuildState::Queued, "a refused transition writes nothing"); @@ -73,9 +66,9 @@ fn a_terminal_build_is_history_and_does_not_move() { #[test] fn a_zombie_worker_cannot_finish_a_build_it_no_longer_owns() { // The failure this pins: a worker's lease expires mid-step, the reaper hands - // the build back to the queue, and the original worker — still running — - // comes back and writes `succeeded` over whatever the new owner did. The - // compare-and-swap in `set_state` is what makes that an error. + // the build back, and the original worker comes back and writes `succeeded` + // over whatever the new owner did. The compare-and-swap in `set_state` makes + // that an error. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -92,25 +85,23 @@ fn a_zombie_worker_cannot_finish_a_build_it_no_longer_owns() { #[test] fn a_state_the_code_does_not_know_is_an_error_not_an_empty_string() { - // A row written by an older binary, a hand-edit, or a future migration the - // code has not caught up with must stop the process, not render as a build - // in no state at all. + // A row written by an older binary, a hand-edit, or a future migration must + // stop the process, not render as a build in no state at all. let env = Env::new(); let id = build(&env, "b1"); env.exec("UPDATE build SET state='exploded' WHERE id=?1", &[common::P::S(id.clone())]); let err = builds::get(&env.db, &id).unwrap_err(); assert!(err.to_string().contains("outside the state machine"), "{err}"); // The package page lists a pkgbase's builds with no state filter: an - // unreadable row must fail the query, not vanish from the list. + // unreadable row must fail the query, not vanish. let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).unwrap(); assert!(aur_build::db::builds_for_pkgbase(&env.db, pb, 10).is_err()); } #[test] fn the_transition_table_is_the_machine_the_code_actually_uses() { - // Every state may be re-written with its own name — that is a no-op, not a - // move (the step loop re-asserts Running at each boundary). What matters is - // what else is reachable, and this table is the whole machine. + // Every state may be re-written with its own name — a no-op, not a move. What + // matters is what else is reachable, and this table is the whole machine. let reachable = |from: BuildState| -> Vec<&'static str> { BuildState::ALL .iter() @@ -131,16 +122,14 @@ fn the_transition_table_is_the_machine_the_code_actually_uses() { // A failed build is resumed on its own row (I5) or requeued by a human (§8.4). assert_eq!(reachable(BuildState::Failed), ["queued", "running", "failed"]); assert_eq!(reachable(BuildState::Cancelled), ["queued", "cancelled"]); - // A published build is history. Nothing revives it; a new version is a new - // build id (§8.1), not a resurrection. + // A published build is history: a new version is a new build id (§8.1). assert_eq!(reachable(BuildState::Succeeded), ["succeeded"]); } #[test] fn requeueing_a_succeeded_build_is_refused_not_silently_requeued() { - // `builds::retry` resets the failed steps and moves the row back to the - // queue. On a build that already published there is nothing to retry, and - // the old unconditional UPDATE happily requeued it anyway. + // `builds::retry` resets the failed steps and moves the row back to the queue. + // On a build that already published there is nothing to retry. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -154,7 +143,7 @@ fn requeueing_a_succeeded_build_is_refused_not_silently_requeued() { #[test] fn a_failed_build_is_resumed_on_its_own_row() { // I5: the resume happens on the same row, because the step checkpoints say - // where to continue. The machine has to know that, or the resume is a bug. + // where to continue. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -171,8 +160,8 @@ fn a_failed_build_is_resumed_on_its_own_row() { // ---------------------------------------------------------- the other machines -- -/// A candidate row in `state`, inserted directly: these tests are about the -/// state column, not about how a candidate is discovered. +/// A candidate row in `state`, inserted directly: these tests are about the state +/// column, not about how a candidate is discovered. fn candidate(env: &Env, state: &str) -> i64 { env.exec( "INSERT OR IGNORE INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", @@ -210,8 +199,7 @@ fn a_decided_review_is_never_re_decided() { assert!(err.to_string().contains("illegal candidate transition approved"), "{err}"); assert_eq!(candidate_state(&env, id), CandidateState::Approved); - // Superseding a decided review is the one move it makes (§7.1), and a - // superseded review is history. + // Superseding a decided review is the one move it makes (§7.1). resolve(&env, id, CandidateState::Superseded).unwrap(); assert_eq!(candidate_state(&env, id), CandidateState::Superseded); assert!(resolve(&env, id, CandidateState::Approved).is_err()); @@ -229,8 +217,7 @@ fn only_an_open_review_can_be_approved() { #[test] fn a_completed_step_checkpoint_is_frozen() { - // I5: a resumed build reads these rows to decide what not to redo. A - // checkpoint that can be rewritten is not a checkpoint. + // I5: a resumed build reads these rows to decide what not to redo. let env = Env::new(); let id = build(&env, "b1"); builds::begin_step(&env.db, &id, "build", 1).unwrap(); @@ -261,8 +248,8 @@ fn an_interrupted_step_resumes_and_a_blocked_step_waits() { #[test] fn an_unnamed_state_in_any_row_is_an_error() { - // Every state column is parsed through `db::state_col`, so a value the code - // does not know stops the read instead of rendering as some other state. + // Every state column is parsed through `db::state_col`, so an unknown value + // stops the read instead of rendering as some other state. let env = Env::new(); let cid = candidate(&env, "approved"); env.exec( diff --git a/tests/surfaces.rs b/tests/surfaces.rs index b13cc9d..1df9f40 100644 --- a/tests/surfaces.rs +++ b/tests/surfaces.rs @@ -1,8 +1,3 @@ -//! The §13 surfaces driven by live state, not fixtures of HTML: Attention must -//! name outdated dependencies, downgrades and blocked builds; the package page -//! must answer "what does this depend on and what depends on it"; and a manual -//! rebuild must reuse the approved source identity without asking again (I6). - mod common; use aur_build::db::{self, builds, model::*}; diff --git a/tests/time.rs b/tests/time.rs index 281d78a..6ab0665 100644 --- a/tests/time.rs +++ b/tests/time.rs @@ -1,5 +1,3 @@ -//! The clock helpers (§16) and the pinned clock the lease tests depend on (§6 m-1). - mod common; use aur_build::db::{builds, BuildState}; @@ -8,10 +6,9 @@ use common::Env; #[test] fn a_pinned_clock_moves_relative_arithmetic_with_it() { - // The finding: `now()` honored the pinned clock but `secs_ago` and - // `secs_ahead` read the wall clock, so a pinned test computed real-clock - // lease expiries and deadlines while comparing them against the pinned - // "now" — the two never met, and the test proved nothing about expiry. + // The finding: `now()` honored the pinned clock but `secs_ago` and `secs_ahead` + // read the wall clock, so a pinned test computed real-clock expiries while + // comparing them against the pinned "now". time::pin("2026-01-01T00:00:00Z"); assert_eq!(time::now(), "2026-01-01T00:00:00Z"); assert_eq!(time::secs_ahead(90), "2026-01-01T00:01:30Z"); diff --git a/tests/vcs.rs b/tests/vcs.rs index b1edd51..62efe5f 100644 --- a/tests/vcs.rs +++ b/tests/vcs.rs @@ -1,10 +1,3 @@ -//! Stage A / Stage B: the VCS watcher (§5.2). -//! -//! The whole point of the two-stage funnel is that the expensive thing (clone + -//! run `pkgver()`) happens only when the cheap thing (`git ls-remote`) says -//! something moved. These tests assert both halves: that the answer is right, -//! and that it was paid for only once. - mod common; use aur_build::db::{self, model::*}; @@ -30,8 +23,7 @@ fn makepkg_calls(env: &Env) -> usize { #[test] fn stage_a_probes_every_vcs_source_not_just_the_first() { let (env, fx) = env_with_fixture("git-multi"); - // Two upstream repos, two pins — a pkgbase that builds from more than one - // upstream can have either one move alone (§5.2). + // Two upstream repos, two pins: either one can move alone (§5.2). let (outcome, c) = detect_and_take(&env, "git-multi"); assert!(matches!(outcome, detect::Outcome::Candidate { .. }), "{outcome:?}"); let c = c.unwrap(); @@ -74,8 +66,8 @@ fn stage_a_short_circuits_before_stage_b_when_nothing_moved() { let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); - // Now poll again with nothing changed. Stage A finds the same tip set, so - // Stage B must not run at all — this is the common case, every day. + // Now poll again with nothing changed. Stage A finds the same tip set, so Stage + // B must not run at all — the common case, every day. let before = makepkg_calls(&env); let cache_before = stage_b_rows(&env); let r = detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); @@ -93,12 +85,12 @@ fn stage_b_resolves_pkgver_and_captures_the_pins() { // The candidate's version is what `pkgver()` computed, not the frozen field. assert_eq!(c.pkgver, "r1.0"); assert_eq!(c.pkgrel, "1"); - // And the pins it will be built from are recorded now, while the clone is - // already there — not later, which would mean cloning again. + // The pins it will be built from are recorded now, while the clone is already + // there. let pins: Vec<UpstreamPin> = serde_json::from_str(&c.upstream_pins_json).unwrap(); assert_eq!(pins[0].commit, head); - // The pins are part of the identity: a different commit is a different - // thing to approve, even under the same version string. + // The pins are part of the identity: a different commit is a different thing to + // approve. let with_pins = Identity { aur_commit: "x".into(), epoch: "0".into(), @@ -124,9 +116,8 @@ fn stage_b_is_cached_on_pkgbase_recipe_and_tip() { assert_eq!(makepkg_calls(&env), calls, "cache miss on an unchanged key"); assert_eq!(stage_b_rows(&env), 1); - // A new tip is a new key, so it resolves again — but the cooldown window - // holds it back, which is what keeps a chatty upstream from turning - // detection into a build loop. + // A new tip is a new key, so it resolves again — but the cooldown window holds + // it back. fx.upstream_commit("upstream: new tip\n"); detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); assert_eq!(stage_b_rows(&env), 1, "cooldown should suppress the re-resolve"); @@ -139,9 +130,8 @@ fn stage_b_is_cached_on_pkgbase_recipe_and_tip() { #[test] fn stage_b_concurrency_cap_is_enforced() { - // The cap is a process-wide guard; with the default of 1 a second caller - // waits for the first. Two threads, one slot: the second must not enter - // until the first releases. + // The cap is a process-wide guard; with the default of 1 a second caller waits + // for the first. let (env, _fx) = env_with_fixture("git-sourced"); let slots = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); let s1 = slots.clone(); @@ -164,9 +154,8 @@ fn stage_b_concurrency_cap_is_enforced() { #[test] fn an_unprobeable_source_forces_stage_b_instead_of_claiming_no_change() { - // svn/hg have no cheap universal probe. The honest answer is "we do not - // know", which means Stage B runs; claiming "nothing moved" would be a lie - // that silently stops detection. + // svn/hg have no cheap universal probe. The honest answer is "we do not know", + // which means Stage B runs. let recipe = aur_build::recipe::parse_pkgbuild( &std::fs::read_to_string(corpus_root().join("git-sourced/PKGBUILD")).unwrap(), ) @@ -189,8 +178,8 @@ fn an_unprobeable_source_forces_stage_b_instead_of_claiming_no_change() { #[test] fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { - // §5.2: pins moved, version frozen — pacman cannot offer an upgrade, so - // there is nothing to approve. It becomes a notice, and is never dropped. + // §5.2: pins moved, version frozen — pacman cannot offer an upgrade, so it + // becomes a notice and is never dropped. let (env, fx) = env_with_fixture("pin-drift"); let (_outcome, c) = detect_and_take(&env, "pin-drift"); let c = c.unwrap(); @@ -199,8 +188,8 @@ fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); - // Upstream moves. The shim still reports the same pkgver (that is what a - // degenerate `pkgver()` does), so nothing is publishable. + // Upstream moves. The shim still reports the same pkgver, as a degenerate + // `pkgver()` does, so nothing is publishable. fx.upstream_commit("upstream: 14 more commits\n"); env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); let (outcome, new_candidate) = detect_and_take(&env, "pin-drift"); diff --git a/tests/versions.rs b/tests/versions.rs index 04866d0..ae6e877 100644 --- a/tests/versions.rs +++ b/tests/versions.rs @@ -1,15 +1,3 @@ -//! `vercmp` and the dependency-string grammar (§4, §6). -//! -//! Version comparison is the one place where a subtle bug is invisible until it -//! publishes the wrong thing: a downgrade that reads as an upgrade gets served to -//! every consumer, and an epoch bump that reads as a downgrade gets refused. So -//! this is a table, not a story — the vectors are the ones pacman's own test -//! suite uses, plus the shapes that only appear in AUR recipes (epoch on one side -//! only, `pkgrel` reset to 1 under a new `pkgver`, alpha/numeric boundaries like -//! `1.0a` vs `1.0.1`). -//! -//! The hand-written implementation is deliberate (§14): no libalpm, no FFI. - mod common; use std::cmp::Ordering; @@ -20,13 +8,9 @@ use aur_build::pkgver::{self, Dep, DepOp}; use aur_build::review::{candidates, diff}; use common::*; -/// Ordering pairs, each `a` strictly older than `b`. -/// -/// These are not hand-derived: every pair was checked against pacman's own -/// `vercmp` on this machine, because the interesting cases (alpha suffixes, -/// alpha-vs-numeric at the same position, a shorter version beating a longer one) -/// are exactly the ones that are easy to misremember. `vercmp_matches_the_system_oracle` -/// below re-checks them whenever the binary is present. +/// Ordering pairs, each `a` strictly older than `b`. Every pair was checked +/// against pacman's own `vercmp`, because the interesting cases are exactly the +/// ones that are easy to misremember. const ORDERED: &[(&str, &str)] = &[ ("v1.2.3", "v1.2.4"), ("1.0", "1.1"), @@ -94,10 +78,8 @@ fn vercmp_orders_the_canonical_vectors() { } /// The strongest version of this test: compare the hand-written implementation -/// against pacman's own `vercmp` over a cross-product of the shapes that appear -/// in real recipes. It is skipped with a note when the binary is absent, so the -/// suite still runs on a machine without pacman — but on a real host this is the -/// test that would catch a chunking bug a hand-typed table would miss. +/// against pacman's own `vercmp` over a cross-product of the shapes that appear in +/// real recipes. Skipped with a note when the binary is absent. #[test] fn vercmp_matches_the_system_oracle() { if std::process::Command::new("vercmp").arg("1").arg("2").output().is_err() { @@ -105,8 +87,7 @@ fn vercmp_matches_the_system_oracle() { return; } // No `-` here: pacman's `vercmp` binary compares two raw version strings and - // does not split an epoch/pkgrel triple out of them, so the EVR-aware - // `vercmp` is not the right side of this comparison. `vercmp_string` is. + // does not split an epoch/pkgrel triple, so `vercmp_string` is the right side. let fragments = [ "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1", "1.0.2.a", "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5", @@ -170,13 +151,11 @@ fn a_pkgrel_reset_under_a_newer_pkgver_is_still_an_upgrade() { #[test] fn alpha_numeric_boundaries_follow_the_chunk_rule() { - // A numeric chunk is always NEWER than an alphabetic one at the same - // position — the rule that reads backwards and that this project got wrong - // until it was checked against pacman's own binary. + // A numeric chunk is always newer than an alphabetic one at the same position. assert_eq!(pkgver::vercmp("1.0.1", "1.0.a"), Ordering::Greater); assert_eq!(pkgver::vercmp("1.0.a", "1.0.1"), Ordering::Less); - // A shorter version is newer when the extra chunk is numeric, older when it - // is alphabetic — the part everyone gets wrong. + // A shorter version is newer when the extra chunk is numeric, older when it is + // alphabetic. assert_eq!(pkgver::vercmp("1.0", "1.0.1"), Ordering::Less); assert_eq!(pkgver::vercmp("1.0", "1.0a"), Ordering::Greater); assert_eq!(pkgver::vercmp("1.0rc1", "1.0"), Ordering::Less); @@ -203,8 +182,7 @@ fn dependency_strings_parse_with_their_constraints() { assert_eq!(d.op, op, "{src:?} operator"); assert_eq!(d.version.as_deref(), ver, "{src:?} version"); } - // Malformed input is dropped, not fatal: one odd optdepends line must not - // break detection for the whole recipe. + // Malformed input is dropped, not fatal. assert!(Dep::parse("").is_none()); assert!(Dep::parse(">=1.0").is_none()); assert_eq!(pkgver::dep_names(&["python>=3.11".into(), "gcc".into()]), vec!["python", "gcc"]); @@ -227,8 +205,7 @@ fn version_constraints_are_satisfied_by_the_right_versions() { #[test] fn provides_and_conflicts_use_the_same_grammar() { - // provides/conflicts entries carry versions with the same syntax; the - // dependency delta panel compares them by name. + // provides/conflicts entries carry versions with the same syntax. for src in ["aur-build", "aur-build=0.1-1", "virtual-thing>=1.0"] { let d = Dep::parse(src).expect(src); assert!(!d.name().is_empty()); @@ -243,7 +220,7 @@ fn provides_and_conflicts_use_the_same_grammar() { #[test] fn a_downgrade_in_the_aur_is_flagged_not_silently_served() { // A maintainer reverting a version is a mistake far more often than a - // deliberate rollback, and a naive string compare would not notice at all. + // deliberate rollback. let (env, fx) = env_with_fixture("plain-make"); publish(&env, "plain-make"); fx.bump(&[("pkgver", "0.9")]); @@ -258,15 +235,13 @@ fn a_downgrade_in_the_aur_is_flagged_not_silently_served() { ); assert!(version.body.contains("1.0-1 -> 0.9-1"), "{:?}", version.body); assert!(pkgver::is_downgrade("1.0-1", "0.9-1")); - // A downgrade is a decision, not an automatic rebuild: it is shown, and the - // index keeps serving the higher version until a human says otherwise. + // A downgrade is a decision, not an automatic rebuild. assert_eq!(aur_build::db::index_version(&env.db, "plain-make").unwrap().unwrap(), "1.0-1"); } #[test] fn an_epoch_bump_is_an_upgrade_even_though_the_version_went_down() { - // The classic "reset the version, add an epoch" move. String comparison - // calls 0.9 older than 1.0 and would refuse it; vercmp must not. + // The classic "reset the version, add an epoch" move. let (env, fx) = env_with_fixture("epoch-bump"); publish(&env, "epoch-bump"); append_line(&fx, "epoch=1"); @@ -301,7 +276,7 @@ fn full_version_round_trips_through_split() { // --- helpers ------------------------------------------------------------- /// Detect, render the diff, approve and build, so the next candidate has a real -/// accepted release behind it (§2 I1: nothing is published without approval). +/// accepted release behind it (I1). fn publish(env: &Env, name: &str) { let c = detect_raw(env, name); let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); @@ -336,9 +311,8 @@ fn panel<'a>(panels: &'a [diff::Panel], name: &str) -> &'a diff::Panel { } /// Add a top-level declaration the fixture did not ship with (an `epoch=` line) -/// and commit it, so detection sees a recipe that genuinely gained an epoch. -/// It has to go with the other top-level assignments: after a `package_*()` -/// function it would be inside the function body and mean nothing. +/// and commit it. It has to go with the other top-level assignments: after a +/// `package_*()` function it would be inside the function body and mean nothing. fn append_line(fx: &Fixture, line: &str) { let path = fx.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); diff --git a/tests/world.rs b/tests/world.rs index 8229d62..3a7dd54 100644 --- a/tests/world.rs +++ b/tests/world.rs @@ -1,14 +1,3 @@ -//! `.PKGINFO` / `.BUILDINFO` parsing and the world snapshot (§10.1, I12). -//! -//! The world snapshot is the whole basis of staleness: "would rebuilding this -//! change what a consumer gets?" only means something if we recorded, at build -//! time, the exact set of our packages the build saw. Two properties matter and -//! are tested here — that the record comes from the archive rather than from -//! anything the build asserted about itself, and that it is intersected with our -//! own index **at ingest time**, because an unfiltered `.BUILDINFO` would make -//! every package permanently stale (Arch never stops moving) and the Attention -//! page would be noise forever. - mod common; use aur_build::db; @@ -17,8 +6,7 @@ use aur_build::pkginfo; use common::*; /// Build a real `.pkg.tar.zst`: zstd-compressed tar with the two metadata files -/// inside, exactly as makepkg lays them out. `None` for either means the file is -/// absent from the archive. +/// inside, as makepkg lays them out. `None` means the file is absent. fn make_archive(dir: &std::path::Path, name: &str, pkginfo: Option<&str>, buildinfo: Option<&str>) -> std::path::PathBuf { let path = dir.join(format!("{name}.pkg.tar.zst")); let enc = std::io::BufWriter::new(std::fs::File::create(&path).unwrap()); @@ -132,15 +120,13 @@ fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() { // §10.1 / I12. The fixture's build root contains glibc, pacman, binutils and // plain-make; only plain-make is ours, and only plain-make may be recorded. let (env, fx) = env_with_fixture("plain-make"); - // The first build has no world of ours to record — nothing we publish exists - // yet. That is the honest answer, not an empty lie about glibc. + // The first build has no world of ours to record — the honest answer, not an + // empty lie about glibc. publish(&env, "plain-make"); let first = world_of_last_build(&env); assert!(first.is_empty(), "nothing of ours existed for the first build: {first:?}"); - // Now plain-make is in the index, so a later build records it and nothing - // else. A real chroot with our repo enabled has the previous version of the - // package installed; the manifest says the same. + // Now plain-make is in the index, so a later build records it and nothing else. let mut manifest = fx.manifest_json(); manifest["installed"] = serde_json::json!([ { "name": "glibc", "version": "2.39-1", "arch": "x86_64" }, @@ -169,8 +155,7 @@ fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() { #[test] fn a_split_pkgbase_is_one_approval_and_many_index_rows() { - // §3: one recipe, several packages, one human decision. Every package the - // build produced gets its own index entry and its own artifact. + // §3: one recipe, several packages, one human decision. let (env, _fx) = env_with_fixture("split-pkgbase"); publish(&env, "split-pkgbase"); let rows: Vec<String> = env |
