#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
use std::fs;
use std::path::PathBuf;
use super::config::TopsConfig;
use super::{check, load_config};
const CLASSES: &[&str] = &[
"library-core",
"parser-codec",
"no-std-embedded",
"unsafe-kernel",
"binary-cli",
];
fn golden_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/config")
}
fn canonical(value: serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Array(items) => {
serde_json::Value::Array(items.into_iter().map(canonical).collect())
}
serde_json::Value::Object(map) => {
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
let mut out = serde_json::Map::new();
for key in keys {
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let child = canonical(map[&key].clone());
out.insert(key, child);
}
serde_json::Value::Object(out)
}
other => other,
}
}
fn config_json(cfg: &TopsConfig) -> serde_json::Value {
canonical(serde_json::to_value(cfg).expect("config serializes to json"))
}
fn load_yaml(label: &str, yaml: &str) -> TopsConfig {
let dir = std::env::temp_dir().join(format!("cargo-tops-parse-{label}-{}", std::process::id()));
#[expect(
clippy::let_underscore_must_use,
reason = "already in this crate when the strict table was turned on"
)]
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap_or_else(|err| panic!("mkdir {label}: {err}"));
fs::write(dir.join("rust-tops.yaml"), yaml)
.unwrap_or_else(|err| panic!("write {label}: {err}"));
let cfg = load_config(&dir).unwrap_or_else(|err| panic!("parse {label}: {err:#}"));
check(&cfg).unwrap_or_else(|err| panic!("check {label}: {err:#}"));
#[expect(
clippy::let_underscore_must_use,
reason = "already in this crate when the strict table was turned on"
)]
let _ = fs::remove_dir_all(&dir);
cfg
}
fn without_protocol_1_1(mut value: serde_json::Value) -> serde_json::Value {
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_idx_86_16 = value["protocol"]["version"].clone();
assert_eq!(tops_idx_86_16, "1.4.0");
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_slot_90 = &mut value["protocol"]["version"];
*tops_slot_90 = serde_json::Value::from("1.0.0");
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let layers = value["layers"].as_array_mut().expect("layers array");
let laws: Vec<serde_json::Value> = layers
.iter()
.filter(|layer| layer["id"] == "laws")
.cloned()
.collect();
assert_eq!(
laws,
[serde_json::json!({"enabled": false, "id": "laws", "runner": "bend", "tier": 0})],
"template must carry one disabled tier-0 laws layer"
);
layers.retain(|layer| layer["id"] != "laws");
value
}
fn without_judged_floors(mut value: serde_json::Value) -> serde_json::Value {
let keys: [(&str, &[&str]); 2] = [
(
"/gates/coverage",
&["region_min_pct", "per_file_line_min_pct", "exclude_globs"],
),
(
"/gates/crap",
&["threshold_production", "fail_on", "baseline"],
),
];
for (pointer, names) in keys {
let map = value
.pointer_mut(pointer)
.and_then(serde_json::Value::as_object_mut)
.expect("the config has the gate");
for name in names {
map.remove(*name);
}
}
value
}
fn with_acceptance_restored(mut value: serde_json::Value) -> serde_json::Value {
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let layers = value["layers"].as_array_mut().expect("layers array");
let acceptance = layers
.iter_mut()
.find(|layer| layer["id"] == "acceptance")
.expect("template has an acceptance layer");
assert_eq!(
acceptance["enabled"], false,
"template must write acceptance off"
);
acceptance["enabled"] = serde_json::Value::from(true);
value
}
fn with_template_crap(class: &str, mut value: serde_json::Value) -> serde_json::Value {
if class == "binary-cli" {
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let agent = &mut value["gates"]["crap"]["threshold_agent"];
assert_eq!(*agent, serde_json::json!(8.0), "binary-cli agent CRAP");
*agent = serde_json::json!(6.0);
}
value
}
#[expect(clippy::too_many_lines, reason = "over the kit line threshold")]
fn without_kit_drop_in(mut value: serde_json::Value) -> serde_json::Value {
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_idx_158_16 = value["protocol"]["version"].clone();
assert_eq!(tops_idx_158_16, "1.4.0");
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_slot_161 = &mut value["protocol"]["version"];
*tops_slot_161 = serde_json::Value::from("1.0.0");
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let layers = value["layers"].as_array_mut().expect("layers array");
let laws: Vec<serde_json::Value> = layers
.iter()
.filter(|layer| layer["id"] == "laws")
.cloned()
.collect();
assert_eq!(
laws,
[serde_json::json!({"enabled": true, "id": "laws", "runner": "bend", "tier": 0})],
"the kit must judge its own laws"
);
layers.retain(|layer| layer["id"] != "laws");
let mut value = with_acceptance_restored(value);
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_idx_187_9 = value["performance"].clone();
assert_eq!(
tops_idx_187_9.get("release_profile"),
None,
"Cargo.toml has no [profile.release]"
);
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_slot_192 = &mut value["performance"]["release_profile"];
*tops_slot_192 = serde_json::json!({
"codegen-units": 1, "debug": 0, "lto": "thin", "opt-level": 3, "panic": "abort",
});
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_idx_203_16 = value["exemptions"].clone();
assert_eq!(tops_idx_203_16, serde_json::json!([]));
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_slot_204 = &mut value["exemptions"];
*tops_slot_204 = serde_json::json!([{
"expires": "2027-09-24", "layer": "crap", "owner": "platform",
"path": "src/generated/**",
"reason": "generated protobuf; public decode roundtrip is the oracle",
}]);
value
}
fn expect_value(name: &str, value: serde_json::Value) {
let path = golden_dir().join(format!("{name}.json"));
if std::env::var_os("RUST_TOPS_BLESS").is_some() {
fs::create_dir_all(golden_dir()).unwrap_or_else(|err| panic!("mkdir golden: {err}"));
#[expect(
clippy::string_add,
reason = "already in this crate when the strict table was turned on"
)]
let pretty = serde_json::to_string_pretty(&value).expect("pretty json") + "\n";
fs::write(&path, pretty).unwrap_or_else(|err| panic!("write {}: {err}", path.display()));
return;
}
let expected = fs::read_to_string(&path)
.unwrap_or_else(|err| panic!("missing golden {}: {err}", path.display()));
let expected_value: serde_json::Value =
serde_json::from_str(&expected).unwrap_or_else(|err| panic!("golden {name} json: {err}"));
assert_eq!(
value, expected_value,
"bundled profile {name} no longer parses to the pre-migration config"
);
}
#[test]
fn bundled_profile_templates_parse_to_pre_migration_config() {
for class in CLASSES {
let yaml = super::profiles::profile_yaml(class, "golden-crate").expect("profile merges");
let cfg = load_yaml(class, &yaml);
assert_eq!(cfg.crate_.name, "golden-crate");
assert_eq!(cfg.crate_.class, *class);
assert_eq!(cfg.protocol.id, "rust-tops");
expect_value(
class,
with_template_crap(
class,
with_acceptance_restored(without_protocol_1_1(without_judged_floors(config_json(
&cfg,
)))),
),
);
}
}
#[test]
fn workspace_instance_parses_to_pre_migration_config() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
let instance = root.join("rust-tops.yaml");
assert!(
instance.is_file(),
"workspace golden requires {}",
instance.display()
);
let cfg = load_config(&root).unwrap_or_else(|err| panic!("parse workspace instance: {err:#}"));
check(&cfg).unwrap_or_else(|err| panic!("check workspace instance: {err:#}"));
assert_eq!(cfg.crate_.name, "cargo-tops");
assert_eq!(cfg.crate_.class, "binary-cli");
let raw = fs::read_to_string(&instance).expect("read workspace instance");
let doc = super::facts::parse_yaml(&raw).expect("workspace instance parses");
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_idx_277_16 = doc["crate"]["unsafe_policy"].clone();
assert_eq!(tops_idx_277_16, "forbid");
expect_value(
"workspace",
without_kit_drop_in(without_judged_floors(config_json(&cfg))),
);
}
const YAML11_BOOL_WORDS: &[&str] = &["yes", "no", "on", "off", "y", "n"];
fn strict_bool_yaml() -> String {
include_str!("../tests/golden/strict-bool/instance.yaml").to_string()
}
#[test]
fn strict_booleans_keep_yaml11_words_as_strings() {
let path = PathBuf::from("strict-bool/rust-tops.yaml");
let cfg = super::parse_config(&path, &strict_bool_yaml())
.unwrap_or_else(|err| panic!("parse strict-bool: {err:#}"));
let goals = config_json(&cfg)
.get("goals")
.cloned()
.expect("goals present");
let path =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/strict-bool/goals.json");
let expected: serde_json::Value = serde_json::from_str(
&fs::read_to_string(&path).unwrap_or_else(|err| panic!("read {}: {err}", path.display())),
)
.expect("strict-bool goals golden");
assert_eq!(goals, expected);
#[expect(
clippy::indexing_slicing,
reason = "already in this crate when the strict table was turned on"
)]
let tops_idx_309_13 = &cfg.layers[0];
assert!(tops_idx_309_13.enabled);
}
#[test]
fn strict_booleans_reject_yaml11_words_on_typed_bool() {
let base = strict_bool_yaml();
for word in YAML11_BOOL_WORDS {
let yaml = base.replace("enabled: true", &format!("enabled: {word}"));
let dir =
std::env::temp_dir().join(format!("cargo-tops-bool-{word}-{}", std::process::id()));
#[expect(
clippy::let_underscore_must_use,
reason = "already in this crate when the strict table was turned on"
)]
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap_or_else(|err| panic!("mkdir {word}: {err}"));
fs::write(dir.join("rust-tops.yaml"), yaml)
.unwrap_or_else(|err| panic!("write {word}: {err}"));
let err = match load_config(&dir) {
Err(err) => err,
Ok(_) => panic!("typed bool accepted {word}"),
};
let message = format!("{err:#}");
assert!(
message.contains("invalid boolean"),
"enabled: {word} did not reject as a strict bool: {message}"
);
#[expect(
clippy::let_underscore_must_use,
reason = "already in this crate when the strict table was turned on"
)]
let _ = fs::remove_dir_all(&dir);
}
}