feat(domain): V1-2.2 document measure, review groups, verdict, preview, edits
The core's authoring surface of contract §16.3: the server's document measure, review groups with digests and removal groups, the change list, the pure server verdict in the shape M5 reads, PreviewSheet with draft and published modes, and the editor's commands with the §6.6 markings.
This commit is contained in:
1 parent
ac71c5b662
commit
64a43840ce
21 files changed
+5204
-17
No files matched your search
@@ -0,0 +1,797 @@
|
||||
//! V1-2.2: the editor's commands (contract §6.6, §8.1). The status rules, case by case; the
|
||||
//! refusals; `dependents`; the facade; and a property test over random command sequences:
|
||||
//! every output reads back strictly, existing keys survive unless removed, an edited or new
|
||||
//! element is `to_confirm`, nothing ever becomes `inherited`.
|
||||
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use faunosteo_core::domain::js::parse_json;
|
||||
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
|
||||
use faunosteo_core::domain::sheet::edit::{
|
||||
EditCommand, EditError, Relation, apply_edit, dependents,
|
||||
};
|
||||
use faunosteo_core::domain::sheet::keys::{ElementKey, marked_elements};
|
||||
use faunosteo_core::domain::sheet::schema::ReviewStatus;
|
||||
use faunosteo_core::facade::call;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft/document.json";
|
||||
|
||||
fn name(text: &str) -> Value {
|
||||
json!({ "fr": text, "en": text })
|
||||
}
|
||||
|
||||
/// Two views (a detail crop of the main one), a point in each, a trigger, a zone with a
|
||||
/// category and a two-level node, one reference, one region; everything `reviewed`.
|
||||
fn small() -> AnatomicalSheetDocument {
|
||||
serde_json::from_value(json!({
|
||||
"schema_version": 2, "species_id": "canine", "name": name("Chien"),
|
||||
"description": {}, "scope_disclaimer": {},
|
||||
"attribution": { "authors": [], "license": null, "notes": null },
|
||||
"vertebral_config": { "regions": [{ "code": "C", "name": name("Cervicales"), "count": 7 }] },
|
||||
"references": [{ "id": "r1", "type": "book", "citation": "Atlas" }],
|
||||
"categories": [{ "id": "c", "name": name("C"), "color": null }],
|
||||
"views": [
|
||||
{ "id": "main", "kind": "main", "name": name("Vue"), "svg_asset_id": "11111111-2222-4333-8444-555555555555", "view_box": null },
|
||||
{ "id": "head", "kind": "detail", "name": name("Tête"), "svg_asset_id": null,
|
||||
"view_box": { "min_x": 0, "min_y": 0, "width": 4, "height": 4 }, "parent_view_id": "main" }
|
||||
],
|
||||
"annotations": [
|
||||
{ "id": "a1", "kind": "point", "view_id": "main", "category_id": "c", "laterality": "left",
|
||||
"geometry": { "type": "circle", "cx": 1, "cy": 1, "r": 1 }, "review_status": "reviewed",
|
||||
"name": name("P1"), "finding_zone_id": "z1", "vertebral_region_code": "C" },
|
||||
{ "id": "a2", "kind": "point", "view_id": "head", "category_id": "c", "laterality": "unpaired",
|
||||
"geometry": { "type": "circle", "cx": 2, "cy": 2, "r": 1 }, "review_status": "reviewed",
|
||||
"name": name("P2"), "finding_zone_id": "z1", "vertebral_region_code": null },
|
||||
{ "id": "t1", "kind": "detail_trigger", "view_id": "main", "category_id": "c", "laterality": "unpaired",
|
||||
"geometry": { "type": "polygon", "points": [[0, 0], [1, 0], [1, 1]] }, "review_status": "reviewed",
|
||||
"name": null, "opens_view_id": "head" }
|
||||
],
|
||||
"finding_zones": [{ "id": "z1", "name": name("Z"), "categories": [{ "id": "cat", "kind": "dysfunction",
|
||||
"name": name("D"), "reference_ids": ["r1"], "review_status": "reviewed",
|
||||
"children": [{ "id": "n1", "name": name("N1"), "review_status": "reviewed",
|
||||
"children": [{ "id": "n2", "name": name("N2"), "review_status": "reviewed" }] }] }] }]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn command(value: Value) -> EditCommand {
|
||||
serde_json::from_value(value).unwrap()
|
||||
}
|
||||
|
||||
fn edit(doc: &AnatomicalSheetDocument, value: Value) -> AnatomicalSheetDocument {
|
||||
apply_edit(doc, command(value)).unwrap()
|
||||
}
|
||||
|
||||
fn refused(doc: &AnatomicalSheetDocument, value: Value) -> EditError {
|
||||
apply_edit(doc, command(value)).unwrap_err()
|
||||
}
|
||||
|
||||
fn statuses(doc: &AnatomicalSheetDocument) -> HashMap<ElementKey, ReviewStatus> {
|
||||
marked_elements(doc)
|
||||
.into_iter()
|
||||
.map(|m| (m.key, m.status))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn status(doc: &AnatomicalSheetDocument, key: Value) -> ReviewStatus {
|
||||
let key: ElementKey = serde_json::from_value(key).unwrap();
|
||||
statuses(doc)[&key]
|
||||
}
|
||||
|
||||
fn finding(path: &[&str]) -> Value {
|
||||
json!({ "kind": "finding", "zone_id": "z1", "path": path })
|
||||
}
|
||||
|
||||
fn annotation(id: &str) -> Value {
|
||||
json!({ "kind": "annotation", "id": id })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserted_elements_start_to_confirm_with_their_subtree() {
|
||||
let doc = small();
|
||||
let point = json!({ "id": "a3", "kind": "point", "view_id": "main", "category_id": "c", "laterality": "right",
|
||||
"geometry": null, "review_status": "reviewed", "name": name("P3"), "finding_zone_id": null, "vertebral_region_code": null });
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "insert", "element": { "kind": "annotation", "value": point }, "position": 0 }),
|
||||
);
|
||||
assert_eq!(next.annotations[0].id(), "a3");
|
||||
assert_eq!(
|
||||
status(&next, annotation("a3")),
|
||||
ReviewStatus::ToConfirm,
|
||||
"a page's marking is ignored"
|
||||
);
|
||||
let subtree = json!({ "id": "n3", "name": name("N3"), "review_status": "reviewed",
|
||||
"children": [{ "id": "n4", "name": name("N4"), "review_status": "inherited" }] });
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "insert", "parent": finding(&["cat"]), "element": { "kind": "finding_node", "value": subtree } }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n3"])),
|
||||
ReviewStatus::ToConfirm
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n3", "n4"])),
|
||||
ReviewStatus::ToConfirm
|
||||
);
|
||||
let zone = json!({ "id": "z2", "name": name("Z2"), "categories": [{ "id": "k", "kind": "custom", "name": name("K"),
|
||||
"review_status": "reviewed", "children": [] }] });
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "insert", "element": { "kind": "zone", "value": zone } }),
|
||||
);
|
||||
let key = json!({ "kind": "finding", "zone_id": "z2", "path": ["k"] });
|
||||
assert_eq!(status(&next, key), ReviewStatus::ToConfirm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_content_change_reconfirms_an_identical_update_does_not() {
|
||||
let doc = small();
|
||||
let mut same = serde_json::to_value(&doc.annotations[0]).unwrap();
|
||||
let unchanged = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "annotation", "value": same.clone() } }),
|
||||
);
|
||||
assert_eq!(unchanged, doc);
|
||||
same["review_status"] = json!("to_confirm");
|
||||
let ignored = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "annotation", "value": same.clone() } }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&ignored, annotation("a1")),
|
||||
ReviewStatus::Reviewed,
|
||||
"update never sets a marking"
|
||||
);
|
||||
for (field, value) in [
|
||||
("name", name("Autre")),
|
||||
("laterality", json!("right")),
|
||||
("color", json!("#112233")),
|
||||
("finding_zone_id", Value::Null),
|
||||
("view_id", json!("head")),
|
||||
(
|
||||
"geometry",
|
||||
json!({ "type": "circle", "cx": 1.5, "cy": 1, "r": 1 }),
|
||||
),
|
||||
] {
|
||||
let mut changed = serde_json::to_value(&doc.annotations[0]).unwrap();
|
||||
changed[field] = value;
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "annotation", "value": changed } }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, annotation("a1")),
|
||||
ReviewStatus::ToConfirm,
|
||||
"{field}"
|
||||
);
|
||||
assert_eq!(status(&next, annotation("a2")), ReviewStatus::Reviewed);
|
||||
}
|
||||
let node = json!({ "id": "n1", "name": name("N1 bis"), "requires_vet_referral": false, "review_status": "reviewed" });
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": finding(&["cat", "n1"]), "element": { "kind": "finding_node", "value": node } }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n1"])),
|
||||
ReviewStatus::ToConfirm
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n1", "n2"])),
|
||||
ReviewStatus::Reviewed,
|
||||
"children untouched"
|
||||
);
|
||||
assert_eq!(
|
||||
next.finding_zones[0].categories[0].children[0]
|
||||
.children
|
||||
.len(),
|
||||
1,
|
||||
"children kept"
|
||||
);
|
||||
let cited =
|
||||
json!({ "id": "n1", "name": name("N1"), "reference_ids": [], "review_status": "reviewed" });
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": finding(&["cat", "n1"]), "element": { "kind": "finding_node", "value": cited } }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n1"])),
|
||||
ReviewStatus::Reviewed,
|
||||
"same content"
|
||||
);
|
||||
let flagged = json!({ "id": "n1", "name": name("N1"), "requires_vet_referral": true });
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": finding(&["cat", "n1"]), "element": { "kind": "finding_node", "value": flagged } }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n1"])),
|
||||
ReviewStatus::ToConfirm
|
||||
);
|
||||
let category = json!({ "id": "cat", "kind": "anamnesis", "name": name("D"), "reference_ids": ["r1"], "children": [] });
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": finding(&["cat"]), "element": { "kind": "finding_category", "value": category } }),
|
||||
);
|
||||
assert_eq!(status(&next, finding(&["cat"])), ReviewStatus::ToConfirm);
|
||||
assert_eq!(next.finding_zones[0].categories[0].children.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_elements_and_reorders_keep_the_markings() {
|
||||
let doc = small();
|
||||
let before = statuses(&doc);
|
||||
let texts = json!({ "name": name("Chien domestique"), "description": { "fr": "d" }, "scope_disclaimer": { "fr": "x", "en": "x" },
|
||||
"attribution": { "authors": ["B"], "license": null, "notes": null } });
|
||||
let reference = json!({ "id": "r1", "type": "journal", "citation": "Revue" });
|
||||
let region = json!({ "code": "C", "name": name("Cou"), "count": 7, "count_range": { "min": 6, "max": 8 } });
|
||||
let category = json!({ "id": "c", "name": name("Catégorie"), "color": "#aa0000" });
|
||||
for command in [
|
||||
json!({ "op": "update", "key": { "kind": "sheet" }, "element": { "kind": "sheet", "value": texts } }),
|
||||
json!({ "op": "update", "key": { "kind": "reference", "id": "r1" }, "element": { "kind": "reference", "value": reference } }),
|
||||
json!({ "op": "update", "key": { "kind": "region", "code": "C" }, "element": { "kind": "region", "value": region } }),
|
||||
json!({ "op": "update", "key": { "kind": "category", "id": "c" }, "element": { "kind": "category", "value": category } }),
|
||||
json!({ "op": "move", "key": annotation("t1"), "position": 0 }),
|
||||
json!({ "op": "move", "key": { "kind": "view", "id": "head" }, "position": 0 }),
|
||||
] {
|
||||
assert_eq!(statuses(&edit(&doc, command.clone())), before, "{command}");
|
||||
}
|
||||
let moved = edit(
|
||||
&doc,
|
||||
json!({ "op": "move", "key": annotation("t1"), "position": 0 }),
|
||||
);
|
||||
assert_eq!(moved.annotations[0].id(), "t1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_redrawn_view_reconfirms_its_annotations_and_its_crops() {
|
||||
let doc = small();
|
||||
let mut main = serde_json::to_value(&doc.views[0]).unwrap();
|
||||
main["svg_asset_id"] = json!("11111111-2222-4333-8444-000000000009");
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": { "kind": "view", "id": "main" }, "element": { "kind": "view", "value": main } }),
|
||||
);
|
||||
assert_eq!(status(&next, annotation("a1")), ReviewStatus::ToConfirm);
|
||||
assert_eq!(status(&next, annotation("t1")), ReviewStatus::ToConfirm);
|
||||
assert_eq!(
|
||||
status(&next, annotation("a2")),
|
||||
ReviewStatus::ToConfirm,
|
||||
"head crops main: its drawing changed too"
|
||||
);
|
||||
let mut head = serde_json::to_value(&doc.views[1]).unwrap();
|
||||
head["view_box"]["width"] = json!(5);
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": { "kind": "view", "id": "head" }, "element": { "kind": "view", "value": head } }),
|
||||
);
|
||||
assert_eq!(status(&next, annotation("a2")), ReviewStatus::ToConfirm);
|
||||
assert_eq!(status(&next, annotation("a1")), ReviewStatus::Reviewed);
|
||||
let mut renamed = serde_json::to_value(&doc.views[1]).unwrap();
|
||||
renamed["name"] = name("Crâne");
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "update", "key": { "kind": "view", "id": "head" }, "element": { "kind": "view", "value": renamed } }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, annotation("a2")),
|
||||
ReviewStatus::Reviewed,
|
||||
"a rename draws nothing new"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markings_are_set_one_element_category_or_zone_at_a_time() {
|
||||
let doc = small();
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "set_status", "key": finding(&["cat", "n1"]), "status": "to_confirm" }),
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n1"])),
|
||||
ReviewStatus::ToConfirm
|
||||
);
|
||||
assert_eq!(
|
||||
status(&next, finding(&["cat", "n1", "n2"])),
|
||||
ReviewStatus::Reviewed
|
||||
);
|
||||
let next = edit(
|
||||
&next,
|
||||
json!({ "op": "set_status", "key": finding(&["cat", "n1"]), "status": "reviewed" }),
|
||||
);
|
||||
assert_eq!(statuses(&next), statuses(&doc));
|
||||
let inherited: Result<EditCommand, _> = serde_json::from_value(
|
||||
json!({ "op": "set_status", "key": annotation("a1"), "status": "inherited" }),
|
||||
);
|
||||
assert!(inherited.is_err(), "no command assigns inherited");
|
||||
let all_to_confirm = edit(
|
||||
&doc,
|
||||
json!({ "op": "set_status", "key": finding(&["cat"]), "status": "to_confirm" }),
|
||||
);
|
||||
let all_to_confirm = edit(
|
||||
&all_to_confirm,
|
||||
json!({ "op": "set_status", "key": finding(&["cat", "n1", "n2"]), "status": "to_confirm" }),
|
||||
);
|
||||
let marked = edit(
|
||||
&all_to_confirm,
|
||||
json!({ "op": "mark_reviewed", "key": finding(&["cat"]) }),
|
||||
);
|
||||
assert_eq!(status(&marked, finding(&["cat"])), ReviewStatus::Reviewed);
|
||||
assert_eq!(
|
||||
status(&marked, finding(&["cat", "n1", "n2"])),
|
||||
ReviewStatus::Reviewed
|
||||
);
|
||||
let zone = edit(
|
||||
&all_to_confirm,
|
||||
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": "z1" } }),
|
||||
);
|
||||
assert_eq!(statuses(&zone), statuses(&doc));
|
||||
for key in [
|
||||
finding(&["cat", "n1"]),
|
||||
annotation("a1"),
|
||||
json!({ "kind": "view", "id": "main" }),
|
||||
json!({ "kind": "sheet" }),
|
||||
] {
|
||||
assert_eq!(
|
||||
refused(&doc, json!({ "op": "mark_reviewed", "key": key })),
|
||||
EditError::InvalidTarget
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
refused(
|
||||
&doc,
|
||||
json!({ "op": "set_status", "key": { "kind": "view", "id": "main" }, "status": "reviewed" })
|
||||
),
|
||||
EditError::InvalidTarget
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removal_takes_the_descendants_and_leaves_references_to_the_panel() {
|
||||
let doc = small();
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "remove", "key": finding(&["cat", "n1"]) }),
|
||||
);
|
||||
assert!(next.finding_zones[0].categories[0].children.is_empty());
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "remove", "key": { "kind": "view", "id": "head" } }),
|
||||
);
|
||||
assert_eq!(next.views.len(), 1);
|
||||
assert_eq!(next.annotations.len(), 3, "a2 and t1 stay, dangling");
|
||||
let issues = faunosteo_core::domain::sheet::validate_sheet_document(&next);
|
||||
assert!(issues.iter().any(|i| i.code == "annotation.view.missing"));
|
||||
let next = edit(
|
||||
&doc,
|
||||
json!({ "op": "remove", "key": { "kind": "zone", "id": "z1" } }),
|
||||
);
|
||||
assert!(next.finding_zones.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_unknown_or_out_of_range_targets_are_refused() {
|
||||
let doc = small();
|
||||
let copy = serde_json::to_value(&doc.annotations[0]).unwrap();
|
||||
let cases = [
|
||||
(
|
||||
json!({ "op": "insert", "element": { "kind": "annotation", "value": copy.clone() } }),
|
||||
EditError::DuplicateKey,
|
||||
),
|
||||
(
|
||||
json!({ "op": "insert", "element": { "kind": "annotation", "value": copy.clone() }, "position": 9 }),
|
||||
EditError::DuplicateKey,
|
||||
),
|
||||
(
|
||||
json!({ "op": "remove", "key": annotation("zz") }),
|
||||
EditError::UnknownKey,
|
||||
),
|
||||
(
|
||||
json!({ "op": "remove", "key": finding(&["cat", "zz"]) }),
|
||||
EditError::UnknownKey,
|
||||
),
|
||||
(
|
||||
json!({ "op": "remove", "key": finding(&[]) }),
|
||||
EditError::UnknownKey,
|
||||
),
|
||||
(
|
||||
json!({ "op": "remove", "key": { "kind": "sheet" } }),
|
||||
EditError::InvalidTarget,
|
||||
),
|
||||
(
|
||||
json!({ "op": "move", "key": annotation("a1"), "position": 3 }),
|
||||
EditError::InvalidPosition,
|
||||
),
|
||||
(
|
||||
json!({ "op": "update", "key": annotation("a2"), "element": { "kind": "annotation", "value": copy.clone() } }),
|
||||
EditError::IdChanged,
|
||||
),
|
||||
(
|
||||
json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "zone", "value": { "id": "a1", "name": name("x"), "categories": [] } } }),
|
||||
EditError::InvalidTarget,
|
||||
),
|
||||
(
|
||||
json!({ "op": "insert", "parent": { "kind": "zone", "id": "z1" }, "element": { "kind": "finding_node", "value": { "id": "x", "name": name("x") } } }),
|
||||
EditError::InvalidTarget,
|
||||
),
|
||||
(
|
||||
json!({ "op": "insert", "parent": finding(&["cat"]), "element": { "kind": "finding_node", "value": { "id": "n1", "name": name("x") } } }),
|
||||
EditError::DuplicateKey,
|
||||
),
|
||||
(
|
||||
json!({ "op": "insert", "parent": { "kind": "zone", "id": "z9" }, "element": { "kind": "finding_category", "value": { "id": "k", "kind": "custom", "name": name("x"), "children": [] } } }),
|
||||
EditError::UnknownKey,
|
||||
),
|
||||
(
|
||||
json!({ "op": "insert", "element": { "kind": "sheet", "value": { "name": name("x"), "description": {}, "scope_disclaimer": {}, "attribution": { "authors": [], "license": null, "notes": null } } } }),
|
||||
EditError::InvalidTarget,
|
||||
),
|
||||
];
|
||||
for (command, error) in cases {
|
||||
assert_eq!(refused(&doc, command.clone()), error, "{command}");
|
||||
}
|
||||
let twins = json!({ "id": "n9", "name": name("x"), "children": [{ "id": "k", "name": name("k") }, { "id": "k", "name": name("k") }] });
|
||||
assert_eq!(
|
||||
refused(
|
||||
&doc,
|
||||
json!({ "op": "insert", "parent": finding(&["cat"]), "element": { "kind": "finding_node", "value": twins } })
|
||||
),
|
||||
EditError::DuplicateKey
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findings_stop_at_eight_levels() {
|
||||
let doc = small();
|
||||
// n2 sits at level 3 (category 1, n1 2, n2 3): five more levels fit, six do not.
|
||||
let nested = |levels: usize| {
|
||||
let mut node = json!({ "id": format!("d{levels}"), "name": name("d") });
|
||||
for level in (1..levels).rev() {
|
||||
node = json!({ "id": format!("d{level}"), "name": name("d"), "children": [node] });
|
||||
}
|
||||
node
|
||||
};
|
||||
let under_n2 = finding(&["cat", "n1", "n2"]);
|
||||
edit(
|
||||
&doc,
|
||||
json!({ "op": "insert", "parent": under_n2.clone(), "element": { "kind": "finding_node", "value": nested(5) } }),
|
||||
);
|
||||
assert_eq!(
|
||||
refused(
|
||||
&doc,
|
||||
json!({ "op": "insert", "parent": under_n2, "element": { "kind": "finding_node", "value": nested(6) } })
|
||||
),
|
||||
EditError::TooDeep
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dependents_list_what_a_removal_leaves_dangling_or_takes() {
|
||||
let doc = small();
|
||||
let of = |key: Value| -> Vec<(ElementKey, Relation)> {
|
||||
let key: ElementKey = serde_json::from_value(key).unwrap();
|
||||
dependents(&doc, &key)
|
||||
.into_iter()
|
||||
.map(|d| (d.element, d.relation))
|
||||
.collect()
|
||||
};
|
||||
let a = |id: &str| ElementKey::Annotation { id: id.to_owned() };
|
||||
let f = |path: &[&str]| ElementKey::Finding {
|
||||
zone_id: "z1".to_owned(),
|
||||
path: path.iter().map(|s| (*s).to_owned()).collect(),
|
||||
};
|
||||
assert_eq!(
|
||||
of(json!({ "kind": "view", "id": "head" })),
|
||||
[(a("a2"), Relation::DrawnIn), (a("t1"), Relation::Opens)]
|
||||
);
|
||||
assert_eq!(
|
||||
of(json!({ "kind": "view", "id": "main" }))[0],
|
||||
(
|
||||
ElementKey::View {
|
||||
id: "head".to_owned()
|
||||
},
|
||||
Relation::ChildView
|
||||
)
|
||||
);
|
||||
assert_eq!(of(json!({ "kind": "category", "id": "c" })).len(), 3);
|
||||
assert_eq!(
|
||||
of(json!({ "kind": "region", "code": "C" })),
|
||||
[(a("a1"), Relation::UsesRegion)]
|
||||
);
|
||||
assert_eq!(
|
||||
of(json!({ "kind": "reference", "id": "r1" })),
|
||||
[(f(&["cat"]), Relation::Cites)]
|
||||
);
|
||||
assert_eq!(
|
||||
of(json!({ "kind": "zone", "id": "z1" })),
|
||||
[
|
||||
(a("a1"), Relation::LinksZone),
|
||||
(a("a2"), Relation::LinksZone),
|
||||
(f(&["cat"]), Relation::Descendant),
|
||||
(f(&["cat", "n1"]), Relation::Descendant),
|
||||
(f(&["cat", "n1", "n2"]), Relation::Descendant)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
of(finding(&["cat", "n1"])),
|
||||
[(f(&["cat", "n1", "n2"]), Relation::Descendant)]
|
||||
);
|
||||
assert!(of(annotation("a1")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_facade_runs_the_commands_with_closed_kinds() {
|
||||
let doc = serde_json::to_value(small()).unwrap();
|
||||
let input = json!({ "document": doc, "command": { "op": "remove", "key": annotation("a1") } });
|
||||
let outcome: Value = serde_json::from_str(&call("sheet.edit", &input.to_string())).unwrap();
|
||||
assert_eq!(outcome["ok"], json!(true));
|
||||
assert_eq!(
|
||||
outcome["value"]["document"]["annotations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
let bad = json!({ "document": doc, "command": { "op": "remove", "key": annotation("zz") } });
|
||||
let outcome: Value = serde_json::from_str(&call("sheet.edit", &bad.to_string())).unwrap();
|
||||
assert_eq!(outcome["kind"], json!("unknown_key"));
|
||||
let shape = json!({ "document": doc, "command": { "op": "remove" } });
|
||||
assert!(call("sheet.edit", &shape.to_string()).contains(r#""kind":"invalid_shape""#));
|
||||
let deps = json!({ "document": doc, "key": { "kind": "view", "id": "head" } });
|
||||
let outcome: Value =
|
||||
serde_json::from_str(&call("sheet.dependents", &deps.to_string())).unwrap();
|
||||
assert_eq!(
|
||||
outcome["value"]["dependents"][0],
|
||||
json!({ "element": annotation("a2"), "relation": "drawn_in" })
|
||||
);
|
||||
let huge = format!("{{\"document\":\"{}\"}}", "x".repeat(11 * 1024 * 1024));
|
||||
assert!(call("sheet.edit", &huge).contains(r#""kind":"too_large""#));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Property test
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
if n == 0 {
|
||||
0
|
||||
} else {
|
||||
(self.next() % n as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
fn pick<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
|
||||
(!items.is_empty()).then(|| &items[self.below(items.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// A random command against the document as it stands; ids from `counter`.
|
||||
fn random_command(doc: &AnatomicalSheetDocument, rng: &mut Rng, counter: &mut usize) -> Value {
|
||||
*counter += 1;
|
||||
let id = format!("g{counter}");
|
||||
let marked: Vec<ElementKey> = marked_elements(doc).into_iter().map(|m| m.key).collect();
|
||||
let views: Vec<&str> = doc.views.iter().map(|v| v.id()).collect();
|
||||
let view = rng.pick(&views).copied().unwrap_or("main");
|
||||
let findings: Vec<&ElementKey> = marked
|
||||
.iter()
|
||||
.filter(|k| matches!(k, ElementKey::Finding { path, .. } if path.len() < 8))
|
||||
.collect();
|
||||
match rng.below(9) {
|
||||
0 => {
|
||||
json!({ "op": "insert", "position": rng.below(2), "element": { "kind": "annotation", "value": {
|
||||
"id": id, "kind": "point", "view_id": view, "category_id": "c", "laterality": "left",
|
||||
"geometry": { "type": "circle", "cx": rng.below(9), "cy": 1, "r": 1 }, "review_status": "reviewed",
|
||||
"name": name(&id), "finding_zone_id": "z1", "vertebral_region_code": null } } })
|
||||
}
|
||||
1 => match rng.pick(&findings) {
|
||||
Some(ElementKey::Finding { zone_id, path }) => json!({ "op": "insert",
|
||||
"parent": { "kind": "finding", "zone_id": zone_id, "path": path },
|
||||
"element": { "kind": "finding_node", "value": { "id": id, "name": name(&id), "review_status": "reviewed" } } }),
|
||||
_ => {
|
||||
json!({ "op": "insert", "element": { "kind": "zone", "value": { "id": id, "name": name(&id), "categories": [] } } })
|
||||
}
|
||||
},
|
||||
2 => {
|
||||
json!({ "op": "insert", "element": { "kind": "view", "value": { "id": id, "kind": "detail", "name": name(&id),
|
||||
"svg_asset_id": null, "view_box": { "min_x": 0, "min_y": 0, "width": 1 + rng.below(4), "height": 2 }, "parent_view_id": view } } })
|
||||
}
|
||||
3 | 4 => {
|
||||
let key = rng.pick(&marked).cloned();
|
||||
match key {
|
||||
Some(key) => update_command(doc, &key, rng),
|
||||
None => json!({ "op": "remove", "key": { "kind": "sheet" } }),
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
json!({ "op": "remove", "key": rng.pick(&marked).cloned().unwrap_or(ElementKey::Sheet) })
|
||||
}
|
||||
6 => {
|
||||
json!({ "op": "move", "key": rng.pick(&marked).cloned().unwrap_or(ElementKey::Sheet), "position": rng.below(3) })
|
||||
}
|
||||
7 => {
|
||||
json!({ "op": "set_status", "key": rng.pick(&marked).cloned().unwrap_or(ElementKey::Sheet),
|
||||
"status": if rng.below(2) == 0 { "reviewed" } else { "to_confirm" } })
|
||||
}
|
||||
_ => {
|
||||
let zone = rng
|
||||
.pick(&doc.finding_zones)
|
||||
.map(|z| z.id.clone())
|
||||
.unwrap_or_default();
|
||||
json!({ "op": "mark_reviewed", "key": { "kind": "zone", "id": zone } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An update of `key`: its current value, renamed half the time.
|
||||
fn update_command(doc: &AnatomicalSheetDocument, key: &ElementKey, rng: &mut Rng) -> Value {
|
||||
let rename = rng.below(2) == 0;
|
||||
let (kind, mut value) = match key {
|
||||
ElementKey::Annotation { id } => (
|
||||
"annotation",
|
||||
serde_json::to_value(doc.annotations.iter().find(|a| a.id() == id).unwrap()).unwrap(),
|
||||
),
|
||||
ElementKey::Finding { zone_id, path } => {
|
||||
let zone = doc.finding_zones.iter().find(|z| &z.id == zone_id).unwrap();
|
||||
let category = zone.categories.iter().find(|c| c.id == path[0]).unwrap();
|
||||
if path.len() == 1 {
|
||||
("finding_category", serde_json::to_value(category).unwrap())
|
||||
} else {
|
||||
let mut nodes = &category.children;
|
||||
let mut node = None;
|
||||
for segment in &path[1..] {
|
||||
let found = nodes.iter().find(|n| &n.id == segment).unwrap();
|
||||
nodes = &found.children;
|
||||
node = Some(found);
|
||||
}
|
||||
("finding_node", serde_json::to_value(node.unwrap()).unwrap())
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let changes = rename && value["name"] != name("renamed");
|
||||
if rename {
|
||||
value["name"] = name("renamed");
|
||||
}
|
||||
json!({ "op": "update", "key": key, "element": { "kind": kind, "value": value }, "changes": changes })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_command_sequences_keep_every_invariant() {
|
||||
let equine: AnatomicalSheetDocument =
|
||||
serde_json::from_value(parse_json(&common::repo_file(SEED)).unwrap()).unwrap();
|
||||
for (seed, start) in [
|
||||
(0x9e37_79b9_7f4a_7c15_u64, small()),
|
||||
(0x2545_f491_4f6c_dd1d, equine),
|
||||
] {
|
||||
let mut rng = Rng(seed);
|
||||
let mut counter = 0;
|
||||
let mut doc = start;
|
||||
let (mut applied, mut refusals) = (0, 0);
|
||||
for _ in 0..400 {
|
||||
let mut raw = random_command(&doc, &mut rng, &mut counter);
|
||||
let changes = raw.as_object_mut().unwrap().remove("changes");
|
||||
let Ok(command) = serde_json::from_value::<EditCommand>(raw.clone()) else {
|
||||
continue;
|
||||
};
|
||||
let before = statuses(&doc);
|
||||
let inherited_before = before
|
||||
.values()
|
||||
.filter(|s| **s == ReviewStatus::Inherited)
|
||||
.count();
|
||||
match apply_edit(&doc, command) {
|
||||
Err(_) => refusals += 1,
|
||||
Ok(next) => {
|
||||
applied += 1;
|
||||
let text = serde_json::to_string(&next).unwrap();
|
||||
let reread: AnatomicalSheetDocument =
|
||||
serde_json::from_value(parse_json(&text).unwrap()).unwrap();
|
||||
assert_eq!(reread, next, "strictly parseable: {raw}");
|
||||
let after = statuses(&next);
|
||||
let inherited_after = after
|
||||
.values()
|
||||
.filter(|s| **s == ReviewStatus::Inherited)
|
||||
.count();
|
||||
assert!(
|
||||
inherited_after <= inherited_before,
|
||||
"nothing becomes inherited: {raw}"
|
||||
);
|
||||
check_command(&raw, changes.as_ref(), &before, &after);
|
||||
doc = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
applied > 200 && refusals > 0,
|
||||
"{applied} applied, {refusals} refused"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The marking rule of the command just applied, on the keys it names.
|
||||
fn check_command(
|
||||
raw: &Value,
|
||||
changes: Option<&Value>,
|
||||
before: &HashMap<ElementKey, ReviewStatus>,
|
||||
after: &HashMap<ElementKey, ReviewStatus>,
|
||||
) {
|
||||
let op = raw["op"].as_str().unwrap();
|
||||
let key = || serde_json::from_value::<ElementKey>(raw["key"].clone()).unwrap();
|
||||
match op {
|
||||
"insert" => {
|
||||
let new: Vec<_> = after.keys().filter(|k| !before.contains_key(*k)).collect();
|
||||
assert!(
|
||||
new.iter().all(|k| after[*k] == ReviewStatus::ToConfirm),
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
"update" => {
|
||||
let key = key();
|
||||
let expected = if changes == Some(&json!(true)) {
|
||||
ReviewStatus::ToConfirm
|
||||
} else {
|
||||
before[&key]
|
||||
};
|
||||
assert_eq!(after[&key], expected, "{raw}");
|
||||
assert!(
|
||||
before
|
||||
.iter()
|
||||
.all(|(k, s)| *k == key || after.get(k) == Some(s)),
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
"move" => assert_eq!(before, after, "{raw}"),
|
||||
"set_status" => {
|
||||
let expected = if raw["status"] == json!("reviewed") {
|
||||
ReviewStatus::Reviewed
|
||||
} else {
|
||||
ReviewStatus::ToConfirm
|
||||
};
|
||||
assert_eq!(after[&key()], expected);
|
||||
assert!(
|
||||
before
|
||||
.iter()
|
||||
.all(|(k, s)| *k == key() || after.get(k) == Some(s)),
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
"remove" => {
|
||||
let gone: Vec<_> = before.keys().filter(|k| !after.contains_key(*k)).collect();
|
||||
assert!(
|
||||
gone.iter().all(|k| k == &&key() || is_below(k, &key())),
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_below(key: &ElementKey, ancestor: &ElementKey) -> bool {
|
||||
match (key, ancestor) {
|
||||
(ElementKey::Finding { zone_id, .. }, ElementKey::Zone { id }) => zone_id == id,
|
||||
(
|
||||
ElementKey::Finding {
|
||||
zone_id: a,
|
||||
path: p,
|
||||
},
|
||||
ElementKey::Finding {
|
||||
zone_id: b,
|
||||
path: q,
|
||||
},
|
||||
) => a == b && p.len() > q.len() && p.starts_with(q),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user