Files
faunosteo/crates/core/tests/sheet_index.rs
T
bchanot 0c47d0f837 feat(domain): R2.2 sheet integrity rules, publish check, SheetIndexData and SQL conformance in Rust
The 21 rules of validateSheetDocument ported with identical codes,
severities, paths and messages (frozen from the TypeScript on 26
conformance fixtures), createEmptySheetDocument, the publish check
(strict shape then rules), and the index data React reads once (positions
with Map semantics, names, spine ids, finding-path keys). The fixtures
also carry the codes private.sheet_document_issues returns: a cargo test
generates supabase/tests/011_sheet_conformance.sql and refuses drift
(PGlite 12/12 files, real stack 446/446). .prettierignore keeps the
byte-exact oracles and generated fixtures out of pnpm format.
2026-10-14 00:17:21 +02:00

233 lines
8.3 KiB
Rust

//! The sheet index, ported from `packages/domain/tests/sheet-index.test.ts`, and the index
//! data React reads (R2 plan rev 2 §5), with the TypeScript duplicate-id policies.
#![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, BundledSheetData, FindingTreeItem, LoadedSheet,
NoMainView, SheetIndex, SheetIndexData, SheetView,
};
use serde_json::{Value, json};
fn slice() -> AnatomicalSheetDocument {
let fixture = parse_json(&common::repo_file(
"crates/core/tests/fixtures/horse-slice.json",
));
serde_json::from_value(fixture.unwrap()["input"].clone()).unwrap()
}
fn path(segments: &[&str]) -> Vec<String> {
segments.iter().map(|s| (*s).to_owned()).collect()
}
fn fr_name(item: Option<FindingTreeItem<'_>>) -> Option<String> {
item.map(|node| node.name().fr.clone())
}
#[test]
fn views_by_id_and_the_main_view() {
let doc = slice();
let index = SheetIndex::build(&doc).unwrap();
let indexed = index.over(&doc);
assert_eq!(indexed.main_view().id(), "view-main");
assert!(matches!(
indexed.view("view-head"),
Some(SheetView::Detail(_))
));
assert!(indexed.view("nowhere").is_none());
}
#[test]
fn annotations_zones_regions_and_spine_markers_by_id() {
let doc = slice();
let index = SheetIndex::build(&doc).unwrap();
let indexed = index.over(&doc);
assert!(indexed.annotation("hip").unwrap().observable().is_some());
let head: Vec<&str> = indexed
.annotations_of_view("view-head")
.map(Annotation::id)
.collect();
assert!(head.contains(&"atm"));
assert_eq!(
indexed.finding_zone("cervical").unwrap().name.en,
"Cervical Vertebrae"
);
let codes: Vec<&str> = indexed.regions().iter().map(|r| r.code.as_str()).collect();
assert_eq!(codes, ["C", "T", "L", "S", "Cd"]);
let range = indexed.region("Cd").unwrap().count_range.as_ref().unwrap();
assert_eq!((range.min.get(), range.max.get()), (15.0, 21.0));
assert_eq!(
indexed.spine_annotation("C", "view-main").unwrap().id,
"cervical-vertebrae"
);
assert!(indexed.spine_annotation("C", "view-head").is_none());
assert!(indexed.is_spine("cervical-vertebrae"));
assert!(!indexed.is_spine("hip"));
assert!(!indexed.is_spine("head-trigger"));
}
#[test]
fn finding_paths_resolve_or_report_absence() {
let doc = slice();
let index = SheetIndex::build(&doc).unwrap();
let indexed = index.over(&doc);
let leaf = path(&["hip-dysfunctions", "articular", "restriction-flexion"]);
assert_eq!(
fr_name(indexed.node_at("hip", &leaf)).as_deref(),
Some("Restriction en flexion")
);
assert_eq!(
fr_name(indexed.node_at("hip", &path(&["hip-dysfunctions"]))).as_deref(),
Some("Dysfonctions ostéopathiques")
);
assert!(
indexed
.node_at("hip", &path(&["hip-dysfunctions", "ghost"]))
.is_none()
);
assert!(indexed.node_at("nowhere", &path(&["x"])).is_none());
assert!(indexed.node_at("hip", &[]).is_none());
}
#[test]
fn a_nameless_trigger_is_named_after_the_view_it_opens() {
let doc = slice();
let index = SheetIndex::build(&doc).unwrap();
let indexed = index.over(&doc);
let trigger = indexed.annotation("head-trigger").unwrap();
let name = indexed.name(trigger);
assert_eq!((name.fr.as_str(), name.en.as_str()), ("Tête", "Head"));
assert_eq!(
indexed.name(indexed.annotation("hip").unwrap()).en,
"Hip joint"
);
assert!(trigger.observable().is_none());
}
#[test]
fn a_document_without_a_main_view_cannot_be_indexed() {
let mut doc = slice();
doc.views.retain(|v| !v.is_main());
assert_eq!(SheetIndex::build(&doc), Err(NoMainView));
}
fn loaded(document: Value, migration_map: Value) -> LoadedSheet {
let data: BundledSheetData = serde_json::from_value(json!({
"status": "draft",
"ref": {
"sheet_id": "s", "version_id": null, "document_sha256": "0".repeat(64),
"schema_version": 2, "species_id": "equine"
},
"document": document,
"migrationMap": migration_map,
"assets": {}, "assetHashes": {}
}))
.unwrap();
LoadedSheet::from_bundle(data).unwrap()
}
fn empty_map() -> Value {
json!({
"schema_version": 1,
"sheet": { "sheetId": "s", "versionId": null, "documentSha256": "0".repeat(64) },
"main_view_id": "view-main", "views": {}, "annotations": {}, "finding_paths": {}
})
}
#[test]
fn index_data_of_the_curated_draft() {
let seed = "supabase/seed/anatomical-sheets/equine/draft";
let document = parse_json(&common::repo_file(&format!("{seed}/document.json"))).unwrap();
let map = parse_json(&common::repo_file(&format!(
"{seed}/report-migration-map.json"
)))
.unwrap();
let sheet = loaded(document, map);
let data = serde_json::to_value(SheetIndexData::of(&sheet)).unwrap();
let doc = &sheet.document;
assert_eq!(data["mainViewId"], "main");
assert_eq!(
data["annotationById"].as_object().unwrap().len(),
doc.annotations.len()
);
assert_eq!(
data["names"].as_object().unwrap().len(),
doc.annotations.len()
);
assert_eq!(data["viewById"].as_object().unwrap().len(), doc.views.len());
let nodes: usize = doc
.finding_zones
.iter()
.map(|z| count_nodes(&z.categories))
.sum();
assert_eq!(data["nodeKeys"].as_array().unwrap().len(), nodes);
let spine = data["spineIds"].as_array().unwrap();
assert!(!spine.is_empty());
assert_eq!(data["ref"]["versionId"], Value::Null);
assert_eq!(data["schemaVersion"], 2);
let reparsed: AnatomicalSheetDocument =
serde_json::from_value(data["document"].clone()).unwrap();
assert_eq!(&reparsed, doc);
}
fn count_nodes(categories: &[faunosteo_core::domain::sheet::FindingCategory]) -> usize {
fn below(nodes: &[faunosteo_core::domain::sheet::FindingNode]) -> usize {
nodes.iter().map(|n| 1 + below(&n.children)).sum()
}
categories.iter().map(|c| 1 + below(&c.children)).sum()
}
#[test]
fn index_data_of_the_slice_lists_paths_names_and_spines() {
let sheet = loaded(serde_json::to_value(slice()).unwrap(), empty_map());
let data = serde_json::to_value(SheetIndexData::of(&sheet)).unwrap();
assert_eq!(data["mainViewId"], "view-main");
assert_eq!(data["spineIds"], json!(["cervical-vertebrae"]));
assert_eq!(
data["names"]["head-trigger"],
json!({ "fr": "Tête", "en": "Head" })
);
let keys: Vec<&str> = data["nodeKeys"]
.as_array()
.unwrap()
.iter()
.map(|k| k.as_str().unwrap())
.collect();
assert!(keys.contains(&r#"["hip","hip-dysfunctions","articular","restriction-flexion"]"#));
assert!(keys.contains(&r#"["hip","hip-dysfunctions"]"#));
assert_eq!(data["viewById"], json!({ "view-head": 1, "view-main": 0 }));
}
#[test]
fn index_data_keeps_the_typescript_duplicate_policies() {
let mut doc = slice();
// A second "hip" annotation: by-id lookups keep the last one, as new Map does.
let mut copy = doc.annotations[0].clone();
if let Annotation::Observable(a) = &mut copy {
a.name.en = "Second hip".to_owned();
a.vertebral_region_code = Some("C".to_owned());
}
doc.annotations.push(copy);
// A duplicate sibling holding an extra child: the first-wins walk never reaches it.
let categories = &mut doc.finding_zones[0].categories;
let mut twin = categories[0].clone();
twin.children[0].id = "only-in-twin".to_owned();
categories.push(twin);
let sheet = loaded(serde_json::to_value(&doc).unwrap(), empty_map());
let data = serde_json::to_value(SheetIndexData::of(&sheet)).unwrap();
assert_eq!(data["annotationById"]["hip"], 6);
assert_eq!(data["names"]["hip"]["en"], "Second hip");
let spine: Vec<&str> = data["spineIds"]
.as_array()
.unwrap()
.iter()
.map(|k| k.as_str().unwrap())
.collect();
// Document order of the first occurrence; "hip" is a spine through its last duplicate.
assert_eq!(spine, ["hip", "cervical-vertebrae"]);
let keys = data["nodeKeys"].to_string();
assert!(!keys.contains("only-in-twin"));
}