// Every test binary compiles this file, so a helper that one of them uses is // dead code in the other twenty — 46 of the items below warn that way, and an // item-scoped allowance on each would say the same thing 46 times. The check // that does the work is `the_test_helpers_are_used` in tests/architecture.rs: // it reads this file and fails on any item, `pub` or private, that no test // names, so the allowance hides noise and cannot hide dead weight. #![allow(dead_code)] use std::collections::HashMap; use std::fmt::Write as _; use std::path::{Path, PathBuf}; use std::sync::{LazyLock, Mutex, OnceLock}; use aur_build::config::{Config, TestHooks}; use aur_build::db::{self, Db}; pub struct Env { pub tmp: tempfile::TempDir, pub cfg: Config, pub db: Db, } impl Env { pub fn new() -> Self { let tmp = tempfile::tempdir().expect("tempdir"); let cfg = Config { root: tmp.path().to_path_buf(), signing_key_id: "TESTKEY".into(), ..Config::default() }; Self::with_cfg(tmp, cfg) } pub fn with_cfg(tmp: tempfile::TempDir, cfg: Config) -> Self { cfg.ensure_dirs().expect("ensure_dirs"); db::migrate(&cfg.db_path()).expect("migrate"); let db = Db::open_migrated(&cfg.db_path()).expect("open db"); let rid = db::ensure_repo( &db.writer, &cfg.repo_name, &cfg.repo_arch_dir().display().to_string(), &cfg.arch, &cfg.signing_key_id, ) .expect("repo row"); assert!(rid > 0); Self { tmp, cfg, db } } pub fn root(&self) -> &Path { self.tmp.path() } pub fn path(&self, p: &str) -> PathBuf { self.tmp.path().join(p) } pub fn subscribe(&self, name: &str) -> i64 { let rid = db::repo_id(&self.db).unwrap(); let url = format!("file://{}/aur/{}.git", self.root().display(), name); db::subscribe(&self.db.writer, rid, name, &url).unwrap(); db::get_pkgbase(&self.db, name).unwrap().unwrap().id } pub fn exec(&self, sql: &str, params: &[P]) -> usize { let sql = sql.to_string(); let params: Vec
= params.to_vec();
self.db
.writer
.tx_for_tests(move |tx| {
let refs: Vec<&dyn rusqlite::ToSql> = params
.iter()
.map(|p| match p {
P::I(i) => i as &dyn rusqlite::ToSql,
P::S(s) => s as &dyn rusqlite::ToSql,
})
.collect();
Ok(tx.execute(&sql, rusqlite::params_from_iter(refs.iter()))?)
})
.unwrap()
}
pub fn accept_as_release(&self, candidate_id: i64) -> i64 {
let at = "2026-01-01T00:00:00Z";
self.db
.writer
.tx_for_tests(move |tx| {
tx.execute(
"INSERT INTO approval (candidate_id, base_release_id, decided_at, decision,
risk_level, diff_digest, identity_hash)
SELECT id, base_release_id, ?2, 'approved', risk_level, diff_digest, identity_hash
FROM candidate WHERE id=?1",
rusqlite::params![candidate_id, at],
)?;
let approval_id = tx.last_insert_rowid();
tx.execute(
"INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash,
upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel,
state, published_at, created_at)
SELECT c.pkgbase_id, c.id, ?2, s.aur_commit, s.recipe_hash, c.upstream_pins_json,
c.source_digests_json, c.epoch, c.pkgver, c.pkgrel,
'published', ?3, ?3
FROM candidate c JOIN snapshot s ON s.id = c.snapshot_id WHERE c.id=?1",
rusqlite::params![candidate_id, approval_id, at],
)?;
let release_id = tx.last_insert_rowid();
tx.execute(
"UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2",
rusqlite::params![at, candidate_id],
)?;
tx.execute(
"INSERT INTO package (repo_id, release_id, name, arch, version, state)
SELECT (SELECT id FROM repo ORDER BY id LIMIT 1), ?1,
b.name, 'x86_64', c.pkgver || '-' || c.pkgrel, 'in_index'
FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?2",
rusqlite::params![release_id, candidate_id],
)?;
tx.execute(
"UPDATE pkgbase SET current_accepted_release_id=?1
WHERE id=(SELECT pkgbase_id FROM candidate WHERE id=?2)",
rusqlite::params![release_id, candidate_id],
)?;
Ok(release_id)
})
.unwrap()
}
pub fn set_publish_fault(&mut self, at: &str) {
self.cfg.hooks.publish_fault = Some(at.to_string());
}
pub fn clear_publish_fault(&mut self) {
self.cfg.hooks.publish_fault = None;
}
pub fn set_shim_fail(&mut self, tool: &str) {
self.cfg.hooks.shim_fail = Some(tool.to_string());
}
/// Run a statement the library deliberately does not expose.
///
/// Fixtures use this to put a row in a state production would take a long
/// way to reach — forcing a risk level, say — rather than the library
/// growing a public setter that exists only for tests.
pub fn execute(&self, sql: &str, params: &[P]) {
let c = rusqlite::Connection::open(self.cfg.db_path()).unwrap();
let refs: Vec<&dyn rusqlite::ToSql> = params
.iter()
.map(|p| match p {
P::I(i) => i as &dyn rusqlite::ToSql,
P::S(s) => s as &dyn rusqlite::ToSql,
})
.collect();
c.execute(sql, rusqlite::params_from_iter(refs)).unwrap();
}
pub fn query_i64(&self, sql: &str, params: &[P]) -> Option = params.to_vec();
self.db
.read(move |c| {
let refs: Vec<&dyn rusqlite::ToSql> = params
.iter()
.map(|p| match p {
P::I(i) => i as &dyn rusqlite::ToSql,
P::S(s) => s as &dyn rusqlite::ToSql,
})
.collect();
use rusqlite::OptionalExtension;
Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0)).optional()?)
})
.unwrap()
}
pub fn query_str(&self, sql: &str, params: &[P]) -> Option = params.to_vec();
self.db
.read(move |c| {
let refs: Vec<&dyn rusqlite::ToSql> = params
.iter()
.map(|p| match p {
P::I(i) => i as &dyn rusqlite::ToSql,
P::S(s) => s as &dyn rusqlite::ToSql,
})
.collect();
use rusqlite::OptionalExtension;
Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, String>(0)).optional()?)
})
.unwrap()
}
}
#[derive(Debug, Clone)]
pub enum P {
I(i64),
S(String),
}
impl From {
v.into_iter().map(Into::into).collect()
}
impl Drop for Env {
fn drop(&mut self) {
self.db.writer.shutdown();
}
}
pub fn corpus_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testcorpus")
}
pub fn shim_dir() -> PathBuf {
Path::new(&env!("CARGO_BIN_EXE_makechrootpkg")).parent().unwrap().to_path_buf()
}
pub fn env_with_fixture(name: &str) -> (Env, Fixture) {
let tmp = tempfile::tempdir().expect("tempdir");
let fx = materialize_fixture(tmp.path(), name);
let cfg = Config {
root: tmp.path().to_path_buf(),
signing_key_id: "TESTKEY".into(),
hooks: TestHooks {
path_prepend: Some(shim_dir()),
shim_manifest: Some(fx.manifest.clone()),
shim_dir: Some(tmp.path().join("shimlog")),
..TestHooks::default()
},
..Config::default()
};
std::fs::create_dir_all(cfg.hooks.shim_dir.as_ref().unwrap()).unwrap();
cfg.ensure_dirs().unwrap();
let env = Env::with_cfg(tmp, cfg);
env.subscribe(name);
(env, fx)
}
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);
let fb = materialize_fixture(tmp.path(), b);
let cfg = Config {
root: tmp.path().to_path_buf(),
signing_key_id: "TESTKEY".into(),
hooks: TestHooks {
path_prepend: Some(shim_dir()),
shim_manifest: Some(fb.manifest.clone()),
shim_dir: Some(tmp.path().join("shimlog")),
..TestHooks::default()
},
..Config::default()
};
std::fs::create_dir_all(cfg.hooks.shim_dir.as_ref().unwrap()).unwrap();
cfg.ensure_dirs().unwrap();
let env = Env::with_cfg(tmp, cfg);
env.subscribe(a);
env.subscribe(b);
(env, fa, fb)
}
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");
let data = root.join(format!("fixture/{name}"));
std::fs::create_dir_all(&data).unwrap();
let aur = root.join(format!("aur/{name}.git"));
let upstream = root.join(format!("upstream/{name}"));
let upstream2 = root.join(format!("upstream/{name}-2"));
let subs = [
("@AUR_DIR@".to_string(), data.display().to_string()),
("@UPSTREAM_DIR@".to_string(), upstream.display().to_string()),
("@UPSTREAM2_DIR@".to_string(), upstream2.display().to_string()),
];
let pristine = pristine_fixture(name);
for (fname, body) in &pristine.data_files {
std::fs::write(data.join(fname), substitute(body, &subs)).unwrap();
}
copy_tree(&pristine.aur, &aur);
if pristine.upstream.exists() {
copy_tree(&pristine.upstream, &upstream);
}
if pristine.upstream2.exists() {
copy_tree(&pristine.upstream2, &upstream2);
}
if pristine.path_dependent {
// The recipe names directories this test owns, so the copied commit
// still speaks the cache's paths. Rewrite the work tree and fold it into
// the single commit rather than rebuilding the repo from nothing.
for (fname, body) in &pristine.recipe_files {
std::fs::write(aur.join(fname), substitute(body, &subs)).unwrap();
}
git(&aur, &["add", "-A"]);
git(&aur, &["commit", "-q", "--amend", "-m", "initial"]);
}
Fixture {
name: name.to_string(),
src,
aur,
data,
manifest,
upstream: pristine.upstream.exists().then_some(upstream),
upstream2: pristine.upstream2.exists().then_some(upstream2),
}
}
/// A corpus entry as it sits on disk, placeholders intact.
struct Corpus {
recipe_files: Vec<(String, String)>,
data_files: Vec<(String, String)>,
upstream: bool,
upstream2: bool,
}
fn read_corpus(name: &str) -> Corpus {
let src = corpus_root().join(name);
let mut corpus = Corpus { recipe_files: Vec::new(), data_files: Vec::new(), upstream: false, upstream2: false };
for entry in std::fs::read_dir(&src).unwrap() {
let path = entry.unwrap().path();
let fname = path.file_name().unwrap().to_string_lossy().to_string();
if fname == "manifest.json" {
continue;
}
let body = std::fs::read_to_string(&path).unwrap_or_default();
corpus.upstream |= body.contains("@UPSTREAM_DIR@");
corpus.upstream2 |= body.contains("@UPSTREAM2_DIR@");
if matches!(fname.as_str(), "payload.bin" | "data.bin") {
corpus.data_files.push((fname, body));
} else {
corpus.recipe_files.push((fname, body));
}
}
corpus
}
/// The fixture repos, built once per test binary rather than once per test.
/// Everything in them is path-independent except a recipe that names its own
/// directories, so a test copies the trees and only rewrites when it must.
#[derive(Clone)]
struct Pristine {
aur: PathBuf,
upstream: PathBuf,
upstream2: PathBuf,
recipe_files: Vec<(String, String)>,
data_files: Vec<(String, String)>,
path_dependent: bool,
}
static PRISTINE: LazyLock