Cotton code
144 lines · 6.6 KB · RustRaw
//! The open bundle laid from the shared fixture library//! (`vectors/open_bundle.json`, written by cotton-store from its fixtures)://! the rule asks for what it must know, and once answered lays the tree the//! store lays.use std::collections::BTreeMap;use serde_json::{json, Value};use super::*;const VECTOR: &str = include_str!("../../vectors/open_bundle.json");fn vector() -> Value {    serde_json::from_str(VECTOR).expect("the vector is JSON")}fn library(vector: &Value, kit: &str, media: bool) -> Library {    serde_json::from_value(json!({        "kit": kit,        "tables": vector["kits"][kit]["tables"],        "database": vector["database"],        "exported_at": vector["exported_at"],        "media": media,    }))    .expect("the library reads")}/// What a host answers for `ask` from the vector's media.fn answer(vector: &Value, kit: &str, ask: &Ask) -> Held {    match &vector["kits"][kit]["media"][&ask.key] {        Value::Null => Held::Missing,        held if ask.read => Held::Text(held["text"].as_str().expect("a playlist is text").to_string()),        _ => Held::Held,    }}/// Lay `kit`, answering every ask; the tree, the missing keys and how many/// rounds of asks it took.fn laid(vector: &Value, kit: &str) -> (Vec<Entry>, Vec<String>, usize) {    let mut library = library(vector, kit, true);    let mut rounds = 0;    loop {        match lay(&library).expect("lays") {            Laid::Asks(asks) => {                rounds += 1;                assert!(rounds < 10, "{kit}: the asks never end");                for ask in &asks {                    library.known.insert(ask.key.clone(), answer(vector, kit, ask));                }            }            Laid::Tree { entries, missing_media } => return (entries, missing_media, rounds),        }    }}fn strings(value: &Value) -> Vec<String> {    value.as_array().expect("a list").iter().map(|v| v.as_str().expect("text").to_string()).collect()}#[test]fn each_kit_lays_the_fixture_tree_once_its_media_is_known() {    let vector = vector();    for kit in ["books", "music", "films"] {        let (entries, missing, _) = laid(&vector, kit);        let paths: Vec<String> = entries.iter().map(|e| e.path().to_string()).collect();        assert_eq!(paths, strings(&vector["kits"][kit]["tree"]), "{kit}: the tree");        assert_eq!(missing, strings(&vector["kits"][kit]["missing_media"]), "{kit}: the missing keys");        for entry in &entries {            if let Entry::Media { media, path } = entry {                assert!(!vector["kits"][kit]["media"][media].is_null(), "{kit}: {path} names {media}, which is not held");            }        }    }}#[test]fn a_first_call_asks_for_every_key_the_rows_name_and_lays_nothing() {    let vector = vector();    let Laid::Asks(asks) = lay(&library(&vector, "books", true)).expect("lays") else { panic!("books must ask first") };    let db = vector["database"].as_str().unwrap();    let keys: Vec<&str> = asks.iter().map(|a| a.key.as_str()).collect();    assert_eq!(        keys,        [            format!("{db}/books/{}.epub", "a".repeat(64)),            format!("{db}/books/{}.pdf", "b".repeat(64)),            format!("{db}/books/{}.epub", "d".repeat(64)),            format!("{db}/photos/{}.jpg", "c".repeat(64)),        ]    );    assert!(asks.iter().all(|a| !a.read), "a book's media is only asked whether it is held");}#[test]fn an_hls_film_is_read_playlist_by_playlist() {    let vector = vector();    let (entries, _, rounds) = laid(&vector, "films");    // The master, then its renditions' playlists, then their segments.    assert_eq!(rounds, 3);    let master = entries.iter().find(|e| e.path() == "Films/Dust Signals (2011)/Dust Signals (2011).m3u8").expect("the master");    let Entry::Text { text, .. } = master else { panic!("the master is rewritten, so it is text") };    assert!(text.contains("URI=\"Dust Signals (2011).hls/audio-1/index.m3u8\""));    assert!(text.contains("\nDust Signals (2011).hls/video/index.m3u8\n"));    let rendition = entries.iter().find(|e| e.path() == "Films/Dust Signals (2011)/Dust Signals (2011).hls/video/index.m3u8").expect("a rendition");    assert!(matches!(rendition, Entry::Media { media, .. } if media.ends_with("/films/f2/video/index.m3u8")), "a rendition's playlist is copied as stored");}#[test]fn without_media_the_metadata_is_laid_and_nothing_is_asked_or_missing() {    let vector = vector();    for kit in ["books", "music", "films"] {        let Laid::Tree { entries, missing_media } = lay(&library(&vector, kit, false)).expect("lays") else { panic!("{kit}: asked with media off") };        assert!(missing_media.is_empty(), "{kit}");        assert!(entries.iter().all(|e| matches!(e, Entry::Text { .. })), "{kit}: a media entry with media off");    }    let Laid::Tree { entries, .. } = lay(&library(&vector, "books", false)).unwrap() else { unreachable!() };    let paths: Vec<&str> = entries.iter().map(Entry::path).collect();    assert!(paths.contains(&"Books/Ana Vell/Harbour Lights/metadata.opf"));    assert!(paths.contains(&"Books/goodreads.csv"));    assert!(!paths.iter().any(|p| p.ends_with(".epub") || p.ends_with(".jpg")));}#[test]fn the_boundary_answers_asks_then_a_tree_and_refuses_in_words() {    let vector = vector();    let input = json!({ "kit": "books", "tables": vector["kits"]["books"]["tables"], "exported_at": vector["exported_at"] });    let out: Value = serde_json::from_str(&crate::boundary::call_json("open_bundle.lay", &input.to_string())).unwrap();    assert!(out["ok"]["asks"].as_array().is_some_and(|a| !a.is_empty()), "{out}");    let asked: Value = serde_json::from_str(&crate::boundary::call_json("open_bundle.lay", &json!({ "kit": "music", "tables": vector["kits"]["music"]["tables"], "exported_at": "x" }).to_string())).unwrap();    assert!(asked["ok"]["asks"].as_array().is_some_and(|a| !a.is_empty()));    let known: BTreeMap<&str, Value> = [("k", json!("held")), ("p", json!({ "text": "#EXTM3U" })), ("m", json!("missing"))].into();    let library: Library = serde_json::from_value(json!({ "kit": "films", "exported_at": "x", "known": known })).unwrap();    assert_eq!(library.known["p"], Held::Text("#EXTM3U".into()));    let bad = json!({ "kit": "books", "exported_at": "yesterday" });    assert_eq!(        crate::boundary::call_json("open_bundle.lay", &bad.to_string()),        json!({ "error": "yesterday is not an RFC 3339 instant: premature end of input" }).to_string()    );    assert!(crate::boundary::call_json("open_bundle.lay", r#"{"kit":"games","exported_at":"x"}"#).starts_with(r#"{"error":"open_bundle.lay: the input does not read"#));}