Files
faunosteo/crates/core/tests/sheet_review.rs
T
bchanot bb5efa0f00 fix(domain): V1-2.2 refuse a removal while another element names it
sheet.edit remove answers has_dependents, the document unchanged, while
dependents lists anything but descendants (owner decision 2026-10-29);
the property test checks no removal adds a referential issue.
2026-10-29 16:24:17 +01:00

385 lines
14 KiB
Rust

//! V1-2.2: completeness, review groups, digests, removal groups and the change list
//! (contract §6.3, §6.6), on the equine draft (the counts of contract §1 and §14.1) and on
//! derived versions built by the edit commands (a zone removed after its annotations are
//! unlinked, since a removal is refused while anything names it).
#![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;
use faunosteo_core::domain::sheet::edit::{EditCommand, apply_edit};
use faunosteo_core::domain::sheet::keys::ElementKey;
use faunosteo_core::domain::sheet::review::{
ChangeKind, ElementChange, ReviewGroup, change_list, completeness, review_groups,
};
use faunosteo_core::domain::sheet::schema::ReviewStatus;
use serde_json::{Value, json};
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft/document.json";
fn equine() -> AnatomicalSheetDocument {
serde_json::from_value(parse_json(&common::repo_file(SEED)).unwrap()).unwrap()
}
fn edit(document: &AnatomicalSheetDocument, command: Value) -> AnatomicalSheetDocument {
let command: EditCommand = serde_json::from_value(command).unwrap();
apply_edit(document, command).unwrap()
}
/// The document without the zone, as an editor gets there: the annotations linked to it are
/// unlinked first (a removal is refused while they name it), then the zone goes. Answers the
/// ids of the annotations unlinked.
fn without_zone(
document: &AnatomicalSheetDocument,
zone_id: &str,
) -> (AnatomicalSheetDocument, Vec<String>) {
let mut next = document.clone();
let mut unlinked = Vec::new();
for annotation in &document.annotations {
let mut value = serde_json::to_value(annotation).unwrap();
if value["finding_zone_id"] == json!(zone_id) {
value["finding_zone_id"] = Value::Null;
let key = json!({ "kind": "annotation", "id": annotation.id() });
next = edit(
&next,
json!({ "op": "update", "key": key, "element": { "kind": "annotation", "value": value } }),
);
unlinked.push(annotation.id().to_owned());
}
}
let next = edit(
&next,
json!({ "op": "remove", "key": { "kind": "zone", "id": zone_id } }),
);
(next, unlinked)
}
fn groups(
document: &AnatomicalSheetDocument,
base: Option<&AnatomicalSheetDocument>,
) -> Vec<ReviewGroup> {
review_groups(document, base).unwrap()
}
fn group<'a>(groups: &'a [ReviewGroup], key: &str) -> &'a ReviewGroup {
groups
.iter()
.find(|g| g.key == key)
.unwrap_or_else(|| panic!("{key}"))
}
#[test]
fn the_equine_draft_has_the_counts_of_the_contract() {
let document = equine();
let counts = completeness(&document);
assert_eq!(counts.statuses.to_confirm, 188);
assert_eq!(counts.statuses.reviewed, 31);
assert_eq!(counts.statuses.inherited, 620);
let total = counts.statuses.to_confirm + counts.statuses.reviewed + counts.statuses.inherited;
assert_eq!(total, 839, "28 annotations, 81 categories, 730 nodes");
assert!(counts.vet_referrals > 0 && counts.uncited > 0);
let all = groups(&document, None);
assert_eq!(all.len(), 30, "general, 2 views, 27 zones");
assert_eq!(all[0].key, "general");
assert_eq!(all.iter().filter(|g| g.key.starts_with("view:")).count(), 2);
assert_eq!(
all.iter().filter(|g| g.key.starts_with("zone:")).count(),
27
);
assert!(all.iter().all(|g| g.digest.len() == 64 && !g.removed));
let marked: u64 = all
.iter()
.map(|g| g.statuses.to_confirm + g.statuses.reviewed + g.statuses.inherited)
.sum();
assert_eq!(
marked, 839,
"every marked element sits in exactly one group"
);
assert!(group(&all, "general").coverable);
assert_eq!(
all.iter().filter(|g| g.coverable).count(),
1,
"only general: nothing reviewed whole"
);
}
#[test]
fn digests_are_stable_and_local_to_their_group() {
let document = equine();
let before = groups(&document, None);
assert_eq!(before, groups(&document.clone(), None));
let zone = document.finding_zones[3].id.clone();
let renamed = edit(
&document,
json!({ "op": "update", "key": { "kind": "zone", "id": zone },
"element": { "kind": "zone", "value": { "id": zone, "name": { "fr": "Autre", "en": "Other" }, "categories": [] } } }),
);
let after = groups(&renamed, None);
for (old, new) in before.iter().zip(&after) {
assert_eq!(old.key, new.key);
assert_eq!(
old.digest == new.digest,
old.key != format!("zone:{zone}"),
"{}",
old.key
);
}
}
#[test]
fn an_omitted_status_digests_as_written_out_inherited() {
let text = common::repo_file(SEED);
let mut value = parse_json(&text).unwrap();
let pointer = first_omitted_status(&value).expect("the seed omits inherited somewhere");
let omitted: AnatomicalSheetDocument = serde_json::from_value(value.clone()).unwrap();
value.pointer_mut(&pointer).unwrap()["review_status"] = json!("inherited");
let explicit: AnatomicalSheetDocument = serde_json::from_value(value).unwrap();
assert_eq!(groups(&omitted, None), groups(&explicit, None));
}
/// The JSON pointer of the first finding node written without a `review_status`.
fn first_omitted_status(document: &Value) -> Option<String> {
let zones = document["finding_zones"].as_array()?;
for (z, zone) in zones.iter().enumerate() {
for (c, category) in zone["categories"].as_array()?.iter().enumerate() {
for (n, node) in category["children"].as_array()?.iter().enumerate() {
if node.get("review_status").is_none() {
return Some(format!("/finding_zones/{z}/categories/{c}/children/{n}"));
}
}
}
}
None
}
#[test]
fn a_group_is_coverable_once_every_element_is_reviewed() {
let document = equine();
let zone = document.finding_zones[0].id.clone();
let marked = edit(
&document,
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": zone } }),
);
let all = groups(&marked, None);
let target = group(&all, &format!("zone:{zone}"));
assert!(target.coverable);
assert_eq!(target.statuses.to_confirm + target.statuses.inherited, 0);
assert_ne!(
target.digest,
group(&groups(&document, None), &format!("zone:{zone}")).digest
);
}
#[test]
fn a_derived_version_that_deletes_a_zone_has_its_removal_group() {
let base = equine();
let zone = base.finding_zones[5].id.clone();
let (derived, unlinked) = without_zone(&base, &zone);
assert!(!unlinked.is_empty(), "every equine zone is linked");
let all = groups(&derived, Some(&base));
assert_eq!(
all.len(),
30,
"29 groups of the version and one removal group"
);
let removal = all.last().unwrap();
assert_eq!(removal.key, format!("zone:{zone}"));
assert!(removal.removed && removal.coverable);
assert_ne!(
removal.digest,
group(&groups(&base, None), &removal.key).digest
);
// A second derivation removing the same zone gives the same removal digest (carry).
let again = groups(&derived.clone(), Some(&base));
assert_eq!(again.last().unwrap().digest, removal.digest);
// Unchanged groups keep the base's digest (the views of the unlinked annotations changed);
// without a base nothing is a removal.
let base_groups = groups(&base, None);
let redrawn: Vec<String> = base
.annotations
.iter()
.filter(|a| unlinked.iter().any(|id| id == a.id()))
.map(|a| format!("view:{}", a.view_id()))
.collect();
for g in all.iter().filter(|g| !g.removed) {
let same = g.digest == group(&base_groups, &g.key).digest;
assert_eq!(same, !redrawn.contains(&g.key), "{}", g.key);
}
assert!(groups(&derived, None).iter().all(|g| !g.removed));
// The change list names the zone and everything that went with it.
let changes = change_list(&derived, &base);
let removed: Vec<&ElementChange> = changes
.iter()
.filter(|c| c.change == ChangeKind::Removed)
.collect();
assert!(removed.iter().all(|c| c.group == removal.key));
assert!(
removed
.iter()
.any(|c| c.element == ElementKey::Zone { id: zone.clone() })
);
let zone_size = 1 + count_findings(&base, &zone);
assert_eq!(removed.len(), zone_size);
assert_eq!(
changes.len(),
zone_size + unlinked.len(),
"nothing else changed"
);
}
fn count_findings(document: &AnatomicalSheetDocument, zone_id: &str) -> usize {
fn nodes(list: &[faunosteo_core::domain::sheet::FindingNode]) -> usize {
list.iter().map(|n| 1 + nodes(&n.children)).sum()
}
let zone = document
.finding_zones
.iter()
.find(|z| z.id == zone_id)
.unwrap();
zone.categories.iter().map(|c| 1 + nodes(&c.children)).sum()
}
#[test]
fn the_change_list_tells_added_changed_status_changed_and_moved() {
let base = equine();
let zone = base.finding_zones[0].clone();
let category = zone.categories[0].clone();
let node = category.children[0].clone();
let path = vec![category.id.clone(), node.id.clone()];
let finding = |path: &[String]| json!({ "kind": "finding", "zone_id": zone.id, "path": path });
// Status only.
let marked = edit(
&base,
json!({ "op": "set_status", "key": finding(&path), "status": "reviewed" }),
);
// A renamed node: content changed.
let mut renamed = node.clone();
renamed.name.fr = format!("{} (corrigé)", renamed.name.fr);
let changed = edit(
&marked,
json!({ "op": "update", "key": finding(&[category.id.clone(), category.children[1].id.clone()]),
"element": { "kind": "finding_node", "value": { "id": category.children[1].id, "name": renamed.name, "children": [] } } }),
);
// A new node under the category.
let added = edit(
&changed,
json!({ "op": "insert", "parent": finding(std::slice::from_ref(&category.id)),
"element": { "kind": "finding_node", "value": { "id": "n-new", "name": { "fr": "Nouveau", "en": "New" } } } }),
);
let changes = change_list(&added, &base);
let kind_of = |path: &[String]| {
changes
.iter()
.find(|c| {
c.element
== ElementKey::Finding {
zone_id: zone.id.clone(),
path: path.to_vec(),
}
})
.map(|c| (c.change, c.status_before, c.status_after))
};
assert_eq!(
kind_of(&path),
Some((
ChangeKind::StatusChanged,
Some(node.review_status),
Some(ReviewStatus::Reviewed)
))
);
let second = vec![category.id.clone(), category.children[1].id.clone()];
assert_eq!(kind_of(&second).map(|k| k.0), Some(ChangeKind::Changed));
assert_eq!(
kind_of(&second).map(|k| k.2),
Some(Some(ReviewStatus::ToConfirm))
);
let new = vec![category.id.clone(), "n-new".to_owned()];
assert_eq!(
kind_of(&new),
Some((ChangeKind::Added, None, Some(ReviewStatus::ToConfirm)))
);
assert_eq!(changes.len(), 3);
assert!(
changes
.iter()
.all(|c| c.group == format!("zone:{}", zone.id))
);
// A node re-created under another parent (no move in level 1): removed plus added.
let leaf = &category.children[2];
let other = &zone.categories[1];
let removed = edit(
&base,
json!({ "op": "remove", "key": finding(&[category.id.clone(), leaf.id.clone()]) }),
);
let mut copy = serde_json::to_value(leaf).unwrap();
copy["children"] = json!([]);
let recreated = edit(
&removed,
json!({ "op": "insert", "parent": finding(std::slice::from_ref(&other.id)), "element": { "kind": "finding_node", "value": copy } }),
);
let moved = change_list(&recreated, &base);
assert!(moved.iter().any(|c| c.change == ChangeKind::Removed));
assert!(moved.iter().any(|c| c.change == ChangeKind::Added));
}
#[test]
fn a_reorder_changes_the_group_digest_only() {
let base = equine();
let zone = &base.finding_zones[0];
let path = [zone.categories[0].id.clone()];
let moved = edit(
&base,
json!({ "op": "move", "key": { "kind": "finding", "zone_id": zone.id, "path": path }, "position": 1 }),
);
assert!(change_list(&moved, &base).is_empty(), "no element changed");
let key = format!("zone:{}", zone.id);
assert_ne!(
group(&groups(&moved, None), &key).digest,
group(&groups(&base, None), &key).digest
);
}
#[test]
fn a_removal_digest_is_bound_to_its_group_key() {
let base = equine();
let first = base.finding_zones[0].id.clone();
let second = base.finding_zones[1].id.clone();
let (without_first, _) = without_zone(&base, &first);
let (derived, _) = without_zone(&without_first, &second);
let removals: Vec<ReviewGroup> = groups(&derived, Some(&base))
.into_iter()
.filter(|g| g.removed)
.collect();
assert_eq!(removals.len(), 2);
assert_ne!(removals[0].digest, removals[1].digest);
}
#[test]
fn an_inherited_element_alone_keeps_its_group_uncoverable() {
let document = equine();
let zone = document.finding_zones[0].clone();
let marked = edit(
&document,
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": zone.id } }),
);
let mut value = serde_json::to_value(&marked).unwrap();
value["finding_zones"][0]["categories"][0]["children"][0]
.as_object_mut()
.unwrap()
.remove("review_status");
let one_inherited: AnatomicalSheetDocument = serde_json::from_value(value).unwrap();
let key = format!("zone:{}", zone.id);
let all = groups(&one_inherited, None);
let target = group(&all, &key);
assert_eq!(
(target.statuses.to_confirm, target.statuses.inherited),
(0, 1)
);
assert!(
!target.coverable,
"an omitted status is inherited, never acknowledgeable"
);
assert!(group(&groups(&marked, None), &key).coverable);
}