Files
faunosteo/crates/core/tests/sheet_rules.rs
T
bchanot bbab0e61cb feat(domain): sheet.empty free op for a new sheet's document (V1-2.5 C)
Wraps create_empty_sheet_document; refusals invalid_shape / invalid_json; ts-rs SheetEmptyInput, core-wasm proof, app wrapper emptySheetDocument.
2026-11-02 16:19:49 +01:00

613 lines
19 KiB
Rust

//! The sheet integrity rules, the publication gate and the empty document, ported from
//! `packages/domain/tests/anatomical-sheet.validate.test.ts` with their exact expectations.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::{
AnatomicalSheetDocument, Annotation, CountRange, FindingZone, LocalizedText,
SheetIssueSeverity, SheetView, check_sheet_document, create_empty_sheet_document,
is_publishable, validate_sheet_document,
};
use faunosteo_core::facade::call;
use serde_json::{Value, json};
const MAIN_ASSET: &str = "3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8";
fn slice_input() -> Value {
let fixture = parse_json(&common::repo_file(
"crates/core/tests/fixtures/horse-slice.json",
));
fixture.unwrap()["input"].clone()
}
fn slice() -> AnatomicalSheetDocument {
serde_json::from_value(slice_input()).unwrap()
}
fn issues_of(doc: &AnatomicalSheetDocument) -> Vec<(String, String)> {
validate_sheet_document(doc)
.into_iter()
.map(|issue| (issue.code, issue.path))
.collect()
}
fn pairs(expected: &[(&str, &str)]) -> Vec<(String, String)> {
expected
.iter()
.map(|(c, p)| ((*c).to_owned(), (*p).to_owned()))
.collect()
}
fn mutated(mutate: impl FnOnce(&mut AnatomicalSheetDocument)) -> AnatomicalSheetDocument {
let mut doc = slice();
mutate(&mut doc);
doc
}
fn point(id: &str, fields: Value) -> Annotation {
let mut base = json!({
"id": id, "kind": "point", "view_id": "view-main", "category_id": "articulations",
"laterality": "bilateral", "geometry": null, "review_status": "inherited", "color": null,
"name": { "fr": id, "en": id }, "finding_zone_id": "hip", "vertebral_region_code": null
});
for (key, value) in fields.as_object().unwrap() {
base[key] = value.clone();
}
serde_json::from_value(base).unwrap()
}
fn trigger(id: &str, view_id: &str, opens: &str) -> Annotation {
serde_json::from_value(json!({
"id": id, "kind": "detail_trigger", "view_id": view_id,
"category_id": "cadrans-du-crane", "laterality": "unpaired", "geometry": null,
"review_status": "inherited", "color": null, "name": null, "opens_view_id": opens
}))
.unwrap()
}
fn detail_view(id: &str, parent: &str) -> SheetView {
serde_json::from_value(json!({
"id": id, "kind": "detail", "name": { "fr": id, "en": id },
"parent_view_id": parent, "svg_asset_id": MAIN_ASSET, "view_box": null
}))
.unwrap()
}
fn set_view_asset(view: &mut SheetView, asset: Option<&str>) {
let value = asset.map(str::to_owned);
match view {
SheetView::Main(v) => v.svg_asset_id = value,
SheetView::Detail(v) => v.svg_asset_id = value,
}
}
#[test]
fn the_horse_slice_has_no_issue() {
assert!(validate_sheet_document(&slice()).is_empty());
}
#[test]
fn view_main_count() {
let doc = mutated(|d| {
let mut alt = d.views[0].clone();
if let SheetView::Main(v) = &mut alt {
v.id = "view-alt".to_owned();
}
d.views.push(alt);
});
assert_eq!(issues_of(&doc), pairs(&[("view.main.count", "views")]));
let none = mutated(|d| d.views.retain(|v| !v.is_main()));
assert!(
issues_of(&none)
.iter()
.any(|(code, _)| code == "view.main.count")
);
}
#[test]
fn view_id_duplicate() {
let doc = mutated(|d| d.views.push(d.views[1].clone()));
assert_eq!(
issues_of(&doc),
pairs(&[("view.id.duplicate", "views[2].id")])
);
}
#[test]
fn view_parent_missing() {
let doc = mutated(|d| d.views.push(detail_view("view-orphan", "view-ghost")));
assert_eq!(
issues_of(&doc),
pairs(&[("view.parent.missing", "views[2].parent_view_id")])
);
}
#[test]
fn view_parent_cycle_terminates_on_a_two_view_loop() {
let doc = mutated(|d| {
d.views.push(detail_view("view-a", "view-b"));
d.views.push(detail_view("view-b", "view-a"));
d.annotations.push(trigger("open-a", "view-b", "view-a"));
d.annotations.push(trigger("open-b", "view-a", "view-b"));
});
assert_eq!(
issues_of(&doc),
pairs(&[
("view.parent.cycle", "views[2].parent_view_id"),
("view.parent.cycle", "views[3].parent_view_id"),
])
);
}
#[test]
fn view_parent_cycle_on_a_self_parent() {
let doc = mutated(|d| {
d.views.push(detail_view("view-self", "view-self"));
d.annotations
.push(trigger("open-self", "view-self", "view-self"));
});
assert_eq!(
issues_of(&doc),
pairs(&[("view.parent.cycle", "views[2].parent_view_id")])
);
}
#[test]
fn view_unreachable() {
let doc = mutated(|d| d.annotations.retain(|a| a.id() != "head-trigger"));
assert_eq!(issues_of(&doc), pairs(&[("view.unreachable", "views[1]")]));
}
#[test]
fn view_asset_missing_on_the_main_view_and_on_a_bare_detail() {
let main = mutated(|d| set_view_asset(&mut d.views[0], None));
assert_eq!(
issues_of(&main),
pairs(&[("view.asset.missing", "views[0].svg_asset_id")])
);
let detail = mutated(|d| {
if let SheetView::Detail(v) = &mut d.views[1] {
v.view_box = None;
}
});
assert_eq!(
issues_of(&detail),
pairs(&[("view.asset.missing", "views[1].view_box")])
);
}
#[test]
fn annotation_id_duplicate_across_views() {
let doc = mutated(|d| {
let mut copy = d.annotations[4].clone();
if let Annotation::Observable(a) = &mut copy {
a.view_id = "view-main".to_owned();
}
d.annotations.push(copy);
});
assert_eq!(
issues_of(&doc),
pairs(&[("annotation.id.duplicate", "annotations[6].id")])
);
}
#[test]
fn annotation_view_and_category_missing() {
let view = mutated(|d| {
d.annotations
.push(point("ghost", json!({ "view_id": "view-ghost" })));
});
assert_eq!(
issues_of(&view),
pairs(&[("annotation.view.missing", "annotations[6].view_id")])
);
let category = mutated(|d| {
if let Annotation::Observable(a) = &mut d.annotations[0] {
a.category_id = "os".to_owned();
}
});
assert_eq!(
issues_of(&category),
pairs(&[("annotation.category.missing", "annotations[0].category_id")])
);
}
#[test]
fn annotation_opens_view_invalid() {
let not_child = mutated(|d| {
d.annotations
.push(trigger("loop", "view-head", "view-head"))
});
assert_eq!(
issues_of(&not_child),
pairs(&[(
"annotation.opens_view.invalid",
"annotations[6].opens_view_id"
)])
);
let main_or_absent = mutated(|d| {
d.annotations
.push(trigger("to-main", "view-main", "view-main"));
d.annotations
.push(trigger("to-ghost", "view-main", "view-ghost"));
});
assert_eq!(
issues_of(&main_or_absent),
pairs(&[
(
"annotation.opens_view.invalid",
"annotations[6].opens_view_id"
),
(
"annotation.opens_view.invalid",
"annotations[7].opens_view_id"
),
])
);
}
#[test]
fn annotation_finding_zone_and_region_missing() {
let zone = mutated(|d| {
d.annotations
.push(point("stifle", json!({ "finding_zone_id": "stifle" })));
});
assert_eq!(
issues_of(&zone),
pairs(&[(
"annotation.finding_zone.missing",
"annotations[6].finding_zone_id"
)])
);
let region = mutated(|d| {
if let Annotation::Observable(a) = &mut d.annotations[1] {
a.vertebral_region_code = Some("Q".to_owned());
}
});
assert_eq!(
issues_of(&region),
pairs(&[(
"annotation.region.missing",
"annotations[1].vertebral_region_code"
)])
);
}
#[test]
fn annotation_no_findings_is_a_warning() {
let doc = mutated(|d| {
d.annotations
.push(point("mandible", json!({ "finding_zone_id": null })));
});
assert_eq!(
issues_of(&doc),
pairs(&[("annotation.no_findings", "annotations[6].finding_zone_id")])
);
assert_eq!(
validate_sheet_document(&doc)[0].severity,
SheetIssueSeverity::Warning
);
}
#[test]
fn region_category_and_zone_duplicates() {
let region = mutated(|d| {
let first = d.vertebral_config.regions[0].clone();
d.vertebral_config.regions.push(first);
});
assert_eq!(
issues_of(&region),
pairs(&[("region.code.duplicate", "vertebral_config.regions[5].code")])
);
let category = mutated(|d| d.categories.push(d.categories[0].clone()));
assert_eq!(
issues_of(&category),
pairs(&[("category.id.duplicate", "categories[4].id")])
);
let zone = mutated(|d| d.finding_zones.push(d.finding_zones[0].clone()));
assert_eq!(
issues_of(&zone),
pairs(&[("finding_zone.id.duplicate", "finding_zones[5].id")])
);
}
#[test]
fn finding_id_duplicate_among_categories_and_nested_children() {
let categories = mutated(|d| {
let first = d.finding_zones[0].categories[0].clone();
d.finding_zones[0].categories.push(first);
});
assert_eq!(
issues_of(&categories),
pairs(&[("finding.id.duplicate", "finding_zones[0].categories[3].id")])
);
let nested = mutated(|d| {
let articular = &mut d.finding_zones[0].categories[0].children[0];
let first = articular.children[0].clone();
articular.children.push(first);
});
assert_eq!(
issues_of(&nested),
pairs(&[(
"finding.id.duplicate",
"finding_zones[0].categories[0].children[0].children[2].id"
)])
);
}
#[test]
fn finding_ids_may_repeat_across_different_sibling_arrays() {
let doc = mutated(|d| {
let copy = d.finding_zones[0].categories[0].children[0].clone();
d.finding_zones[0].categories[1].children.push(copy);
});
assert!(issues_of(&doc).is_empty());
}
#[test]
fn reference_duplicate_and_missing_citations() {
let duplicate = mutated(|d| d.references.push(d.references[0].clone()));
assert_eq!(
issues_of(&duplicate),
pairs(&[("reference.id.duplicate", "references[1].id")])
);
let missing = mutated(|d| {
let hip = &mut d.finding_zones[0].categories;
hip[0].reference_ids = vec!["nav-2017".to_owned()];
hip[0].children[0].children[0].reference_ids =
vec!["legacy-catalog".to_owned(), "x".to_owned()];
});
assert_eq!(
issues_of(&missing),
pairs(&[
(
"finding.reference.missing",
"finding_zones[0].categories[0].reference_ids[0]"
),
(
"finding.reference.missing",
"finding_zones[0].categories[0].children[0].children[0].reference_ids[1]"
),
])
);
}
fn count_range(min: u32, max: u32) -> CountRange {
serde_json::from_value(json!({ "min": min, "max": max })).unwrap()
}
#[test]
fn region_count_range_invalid_and_bounds() {
let outside =
mutated(|d| d.vertebral_config.regions[4].count_range = Some(count_range(19, 21)));
assert_eq!(
issues_of(&outside),
pairs(&[(
"region.count_range.invalid",
"vertebral_config.regions[4].count_range"
)])
);
assert_eq!(
validate_sheet_document(&outside)[0].message,
"Region \"Cd\": count 18 outside 19\u{2013}21"
);
let bounds = mutated(|d| d.vertebral_config.regions[4].count_range = Some(count_range(18, 18)));
assert!(issues_of(&bounds).is_empty());
}
#[test]
fn finding_zone_unreferenced_is_a_warning() {
let doc = mutated(|d| {
let zone: FindingZone = serde_json::from_value(json!({
"id": "stifle", "name": { "fr": "Grasset", "en": "Stifle" }, "categories": []
}))
.unwrap();
d.finding_zones.push(zone);
});
assert_eq!(
issues_of(&doc),
pairs(&[("finding_zone.unreferenced", "finding_zones[5]")])
);
assert_eq!(
validate_sheet_document(&doc)[0].severity,
SheetIssueSeverity::Warning
);
}
#[test]
fn messages_follow_the_typescript_wording() {
let doc = mutated(|d| {
d.views.push(detail_view("view-orphan", "view-ghost"));
d.annotations
.push(trigger("loop", "view-head", "view-head"));
d.categories.push(d.categories[0].clone());
});
let messages: Vec<String> = validate_sheet_document(&doc)
.into_iter()
.map(|issue| issue.message)
.collect();
assert_eq!(
messages,
[
"Parent view \"view-ghost\" does not exist",
"\"view-head\" is not a detail child of \"view-head\"",
"Duplicate id \"articulations\"",
]
);
}
#[test]
fn publication_gate() {
assert!(is_publishable(&validate_sheet_document(&slice())));
let warnings_only = mutated(|d| {
d.annotations
.push(point("mandible", json!({ "finding_zone_id": null })));
});
assert_eq!(validate_sheet_document(&warnings_only).len(), 1);
assert!(is_publishable(&validate_sheet_document(&warnings_only)));
let refused = mutated(|d| set_view_asset(&mut d.views[0], None));
assert!(!is_publishable(&validate_sheet_document(&refused)));
let check = check_sheet_document(serde_json::to_value(&refused).unwrap()).unwrap();
assert!(!check.publishable);
let codes: Vec<&str> = check.issues.iter().map(|i| i.code.as_str()).collect();
assert_eq!(codes, ["view.asset.missing"]);
assert!(check_sheet_document(json!({ "schema_version": 2 })).is_err());
}
#[test]
fn the_empty_document_is_shape_valid_but_not_publishable() {
let name = LocalizedText {
fr: "Nouvelle fiche".to_owned(),
en: "New sheet".to_owned(),
};
let empty = create_empty_sheet_document("equine", &name).unwrap();
let reparsed: AnatomicalSheetDocument =
serde_json::from_value(serde_json::to_value(&empty).unwrap()).unwrap();
assert_eq!(reparsed, empty);
assert_eq!(empty.views.len(), 1);
assert_eq!(empty.views[0].id(), "view-main");
assert!(empty.views[0].is_main() && empty.views[0].svg_asset_id().is_none());
let codes: Vec<String> = issues_of(&empty)
.into_iter()
.map(|(code, _)| code)
.collect();
assert_eq!(codes, ["view.asset.missing"]);
assert!(create_empty_sheet_document("Not An Id", &name).is_err());
}
fn sheet_empty(input: Value) -> Value {
serde_json::from_str(&call("sheet.empty", &input.to_string())).unwrap()
}
#[test]
fn sheet_empty_answers_the_document_sheet_check_reads() {
let name = json!({ "fr": "Nouvelle fiche", "en": "New sheet" });
let out = sheet_empty(json!({ "species_id": "equine", "name": name }));
assert_eq!(out["ok"], json!(true), "{out}");
let document = out["value"].clone();
assert_eq!(document["species_id"], json!("equine"));
assert_eq!(document["name"], name);
assert!(document.get("slug").is_none());
let check: Value = serde_json::from_str(&call("sheet.check", &document.to_string())).unwrap();
assert_eq!(check["ok"], json!(true), "{check}");
let codes: Vec<&Value> = check["value"]["issues"]
.as_array()
.unwrap()
.iter()
.map(|issue| &issue["code"])
.collect();
assert_eq!(codes, [&json!("view.asset.missing")]);
assert_eq!(check["value"]["publishable"], json!(false));
}
#[test]
fn sheet_empty_refuses_a_bad_species_an_empty_label_or_an_unknown_field() {
let name = json!({ "fr": "Nouvelle fiche", "en": "New sheet" });
for input in [
json!({ "species_id": "Not An Id", "name": name }),
json!({ "species_id": "equine", "name": { "fr": "", "en": "New sheet" } }),
json!({ "species_id": "equine", "name": { "fr": "Nouvelle fiche" } }),
json!({ "species_id": "equine", "name": name, "slug": "equine" }),
json!({ "name": name }),
] {
let out = sheet_empty(input.clone());
assert_eq!(out["ok"], json!(false), "{input}");
assert_eq!(out["kind"], json!("invalid_shape"), "{input}");
}
let out: Value = serde_json::from_str(&call("sheet.empty", "{ not json")).unwrap();
assert_eq!(out["kind"], json!("invalid_json"));
}
/// True for a `{ fr?, en? }` label object, the only thing a translator edits.
fn is_label(value: &Value) -> bool {
value
.as_object()
.is_some_and(|o| !o.is_empty() && o.keys().all(|k| k == "fr" || k == "en"))
}
fn map_labels(value: &Value, rewrite: &mut dyn FnMut(&Value) -> Value) -> Value {
if is_label(value) {
return rewrite(value);
}
match value {
Value::Array(items) => Value::Array(items.iter().map(|v| map_labels(v, rewrite)).collect()),
Value::Object(map) => Value::Object(
map.iter()
.map(|(k, v)| (k.clone(), map_labels(v, rewrite)))
.collect(),
),
other => other.clone(),
}
}
fn collect_ids(value: &Value, out: &mut Vec<String>) {
match value {
Value::Array(items) => items.iter().for_each(|v| collect_ids(v, out)),
Value::Object(map) => {
for (key, v) in map {
let is_ref = key == "id" || key.ends_with("_id") || key.ends_with("code");
match v.as_str() {
Some(text) if is_ref => out.push(format!("{key}={text}")),
_ => collect_ids(v, out),
}
}
}
_ => {}
}
}
#[test]
fn ids_and_validation_output_survive_a_translation() {
let original = slice();
let original_value = serde_json::to_value(&original).unwrap();
let mut counter = 0;
let relabeled_value = map_labels(&original_value, &mut |label| {
let keys: Vec<String> = label.as_object().unwrap().keys().cloned().collect();
let mut out = serde_json::Map::new();
for key in keys {
out.insert(key, Value::String(format!("x{counter}")));
counter += 1;
}
Value::Object(out)
});
let relabeled: AnatomicalSheetDocument = serde_json::from_value(relabeled_value).unwrap();
assert!(counter > 50);
let mut before = Vec::new();
let mut after = Vec::new();
collect_ids(&original_value, &mut before);
collect_ids(&serde_json::to_value(&relabeled).unwrap(), &mut after);
assert_eq!(before, after);
assert_eq!(
validate_sheet_document(&relabeled),
validate_sheet_document(&original)
);
}
#[test]
fn validation_output_survives_a_translation_of_a_broken_document() {
let broken = mutated(|d| {
if let Annotation::Observable(a) = &mut d.annotations[0] {
a.category_id = "os".to_owned();
}
if let SheetView::Detail(v) = &mut d.views[1] {
v.view_box = None;
}
});
let value = serde_json::to_value(&broken).unwrap();
let relabeled = map_labels(&value, &mut |_| json!({ "fr": "a", "en": "b" }));
let relabeled: AnatomicalSheetDocument = serde_json::from_value(relabeled).unwrap();
assert_eq!(
validate_sheet_document(&relabeled),
validate_sheet_document(&broken)
);
}
#[test]
fn the_curated_draft_validates_with_no_issue() {
let text = common::repo_file("supabase/seed/anatomical-sheets/equine/draft/document.json");
let doc: AnatomicalSheetDocument = serde_json::from_value(parse_json(&text).unwrap()).unwrap();
assert_eq!(validate_sheet_document(&doc), []);
}