//! The pipeline's formatting and JavaScript semantics (R5.2) against the TypeScript tools //! themselves: Prettier's JSON layout and table alignment, `slugify`, `deterministicUuid`, //! `Number()`, `Math.round`, `Object.keys` order, `trim`. The expectations were written by //! Node (`packages/anatomy/tests/r5.format-oracles.test.ts`, `r5.pipeline-oracles.test.ts`); //! nothing here computes its own expected text. #![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] mod common; use faunosteo_core::anatomy::svg::number::{is_js_space, js_number_of, js_split_list}; use faunosteo_core::curation::PipelineError; use faunosteo_core::curation::ids::deterministic_uuid; use faunosteo_core::curation::legacy::regions::{RegionMatch, infer_region_code}; use faunosteo_core::curation::markdown::format_markdown; use faunosteo_core::curation::prettier_json::format_json; use faunosteo_core::curation::text::{js_keys, js_round, slugify}; use faunosteo_core::domain::js::parse_json; use faunosteo_core::json::js_number; use serde_json::Value; fn oracle(name: &str) -> Value { serde_json::from_str(&common::repo_file(&format!( "crates/core/tests/oracles/r5/{name}" ))) .unwrap() } fn rows<'a>(value: &'a Value, key: &str) -> &'a Vec { value[key].as_array().unwrap() } /// Every case prints as Prettier printed it, except the declared refusal: a text holding an /// emoji, whose Prettier width table is not reproduced (`PipelineError::UnsupportedWidth`). #[test] fn json_layout_matches_prettier_on_every_probe() { let oracle = oracle("prettier-json.json"); let mut refused = Vec::new(); for (index, case) in rows(&oracle, "cases").iter().enumerate() { let input = parse_json(case["input"].as_str().unwrap()).unwrap(); match format_json(&input) { Ok(text) => assert_eq!(text, case["output"].as_str().unwrap(), "case {index}"), Err(PipelineError::UnsupportedWidth(_)) => refused.push(index), Err(other) => panic!("case {index}: {other}"), } } assert_eq!(refused, vec![19], "only the emoji case is refused"); } #[test] fn every_generated_json_file_of_the_seed_prints_byte_for_byte() { let seed = "supabase/seed/anatomical-sheets/equine"; for file in [ "legacy-import/document.json", "legacy-import/legacy-id-map.json", "legacy-import/assets.json", "draft/document.json", "draft/assets.json", "draft/sheet-ref.json", "draft/report-migration-map.json", ] { let text = common::repo_file(&format!("{seed}/{file}")); let value = parse_json(&text).unwrap(); assert_eq!(format_json(&value).unwrap(), text, "{file}"); } } #[test] fn tables_align_as_prettier_aligns_them() { let oracle = oracle("markdown-tables.json"); let mut refused = Vec::new(); for (index, case) in rows(&oracle, "cases").iter().enumerate() { match format_markdown(case["raw"].as_str().unwrap()) { Ok(text) => assert_eq!(text, case["output"].as_str().unwrap(), "case {index}"), Err(PipelineError::UnsupportedWidth(_)) => refused.push(index), Err(other) => panic!("case {index}: {other}"), } } assert_eq!(refused, vec![5], "only the emoji table is refused"); } /// One long cell pads every row of its column: the aligned table is bounded before any row is /// built (security gate R5.4 round 6: an 80 KB rationale over 14,000 records asked for 1 GB). #[test] fn an_aligned_table_past_the_bound_is_refused_before_it_is_built() { let mut raw = vec!["| a | b |".to_owned(), "| --- | --- |".to_owned()]; raw.push(format!("| {} | x |", "w".repeat(2_000))); raw.extend((0..20_000).map(|_| "| a | b |".to_owned())); let error = format_markdown(&raw.join("\n")).unwrap_err(); assert!( matches!(&error, PipelineError::Guard(message) if message.contains("exceeds the")), "{error}" ); } #[test] fn slugs_and_uuids_match_the_typescript() { let semantics = oracle("js-semantics.json"); let ids = oracle("ids.json"); for row in rows(&semantics, "slugify").iter().chain(rows(&ids, "slug")) { let label = row["label"].as_str().unwrap(); assert_eq!(slugify(label), row["slug"].as_str().unwrap(), "{label:?}"); } let uuid_rows = rows(&semantics, "deterministicUuid") .iter() .chain(rows(&ids, "uuid")); for row in uuid_rows { let name = row["name"].as_str().unwrap(); assert_eq!( deterministic_uuid(name), row["uuid"].as_str().unwrap(), "{name:?}" ); } } #[test] fn number_points_round_and_trim_follow_javascript() { let semantics = oracle("js-semantics.json"); for row in rows(&semantics, "number") { let value = js_number_of(row["text"].as_str().unwrap()); assert_eq!(js_string(value), row["string"].as_str().unwrap(), "{row}"); let negative_zero = value == 0.0 && value.is_sign_negative(); assert_eq!( negative_zero, row["negativeZero"].as_bool().unwrap(), "{row}" ); } for row in rows(&semantics, "points") { let numbers: Vec = js_split_list(row["text"].as_str().unwrap()) .into_iter() .map(|part| js_string(js_number_of(part))) .collect(); let expected: Vec<&str> = rows(row, "numbers") .iter() .map(|n| n.as_str().unwrap()) .collect(); assert_eq!(numbers, expected, "{row}"); } for row in rows(&semantics, "mathRound") { let bits = u64::from_str_radix(row["bits"].as_str().unwrap(), 16).unwrap(); let value = f64::from_bits(bits); let rounded = js_round(value); assert_eq!(js_string(rounded), row["round"].as_str().unwrap(), "{row}"); let negative_zero = rounded == 0.0 && rounded.is_sign_negative(); assert_eq!( negative_zero, row["negativeZero"].as_bool().unwrap(), "{row}" ); } for row in rows(&semantics, "trim") { let text = row["text"].as_str().unwrap(); assert_eq!( text.trim_matches(is_js_space), row["trimmed"].as_str().unwrap() ); let space = text.chars().next().unwrap(); assert_eq!( is_js_space(space), row["isSpace"].as_bool().unwrap(), "{space:?}" ); } } #[test] fn object_keys_follow_javascript_order() { let semantics = oracle("js-semantics.json"); for row in rows(&semantics, "objectEntriesOrder") { let value = parse_json(row["text"].as_str().unwrap()).unwrap(); let keys: Vec<&String> = js_keys(value.as_object().unwrap()); let expected: Vec<&str> = rows(row, "keys") .iter() .map(|k| k.as_str().unwrap()) .collect(); assert_eq!(keys, expected, "{row}"); } } /// `String(number)`, NaN and the infinities included. fn js_string(value: f64) -> String { if value.is_nan() { "NaN".to_owned() } else if value.is_infinite() { if value > 0.0 { "Infinity" } else { "-Infinity" }.to_owned() } else { js_number(value) } } fn region(fr: Option<&str>, en: Option<&str>) -> Option { infer_region_code(fr, en).map(|m| m.code) } /// `inferRegionCode` as Node ran it (`js-semantics.json`, 12 rows: root, label and code) and the /// cases of the deleted `legacy.regions.test.ts` (R5.7): FR roots with and without accents, EN /// roots when FR is absent, FR before EN, the EN fallback when FR names no root. #[test] fn region_inference_follows_the_typescript() { let semantics = oracle("js-semantics.json"); let cases = rows(&semantics, "inferRegionCode"); assert_eq!(cases.len(), 12); for case in cases { let (fr, en) = (case["fr"].as_str(), case["en"].as_str()); let actual = infer_region_code(fr, en).map(|RegionMatch { code, root, label }| { serde_json::json!({ "code": code, "root": root, "label": label }) }); assert_eq!( actual.unwrap_or(Value::Null), case["match"], "{fr:?} / {en:?}" ); } for (fr, code) in [ ("Vertèbres cervicales", "C"), ("Vertebres cervicales", "C"), ("Vertèbres thoraciques", "T"), ("Vertebres thoraciques", "T"), ("Vertèbres lombaires", "L"), ("Vertèbres sacrales", "S"), ("Vertèbres sacrées", "S"), ("Vertèbres caudales", "Cd"), ("Vertèbres coccygiennes", "Cd"), ("Région dorsale", "T"), ] { assert_eq!(region(Some(fr), None).as_deref(), Some(code), "{fr}"); } for (en, code) in [ ("Cervical Vertebrae", "C"), ("Thoracic Vertebrae", "T"), ("Lumbar Vertebrae", "L"), ("Sacral Vertebrae", "S"), ("Coccygeal Vertebrae", "Cd"), ] { assert_eq!(region(None, Some(en)).as_deref(), Some(code), "{en}"); } assert_eq!(region(Some("Épaule"), Some("Shoulder")), None); assert_eq!(region(Some(""), Some("")), None); assert_eq!(region(None, None), None); assert_eq!( infer_region_code(Some("Vertèbres lombaires"), Some("Cervical")), Some(RegionMatch { code: "L".into(), root: "lombair".into(), label: "Vertèbres lombaires".into() }) ); assert_eq!( region(Some("Épaule"), Some("Cervical Vertebrae")).as_deref(), Some("C") ); }