use std::io::Write;
use std::path::{Path, PathBuf};
const STORE: &str = r#"{"plays": [
{"title": "Antigone", "meta": "{\"author\": {\"name\": \"Sophocles\"}}"},
{"title": "Medea", "meta": "by Euripides"},
{"title": "Electra", "meta": null},
{"title": "Ajax", "meta": "{\"author\": {\"name\": \"Sophocles\"}}"},
{"title": "Ion", "meta": "<author>Euripides</author>"}
]}"#;
fn fixture(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("quarb-notation-{}-{tag}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("shelf")).unwrap();
std::fs::write(dir.join("store.json"), STORE).unwrap();
std::fs::write(dir.join("shelf/lines.dat"), "[1353, 1419, 1510]\n").unwrap();
std::fs::write(dir.join("shelf/note.dat"), "three plays\n").unwrap();
std::fs::write(dir.join("shelf/play.json"), "{\"lines\": 1353}\n").unwrap();
std::fs::write(
dir.join("plays.csv"),
"id,payload\n1,\"{\"\"lines\"\": 1353}\"\n2,unknown\n3,\"{\"\"lines\"\": 1510}\"\n",
)
.unwrap();
let db = rusqlite::Connection::open(dir.join("plays.db")).unwrap();
db.execute_batch(
"CREATE TABLE plays (id INTEGER PRIMARY KEY, meta TEXT);
INSERT INTO plays VALUES
(1,'{\"author\": {\"name\": \"Sophocles\"}}'),
(2,'by Euripides'),
(3,NULL),
(4,'{\"author\": {\"name\": \"Sophocles\"}}');",
)
.unwrap();
let mut z = zip::ZipWriter::new(std::fs::File::create(dir.join("shelf.zip")).unwrap());
let o = zip::write::SimpleFileOptions::default();
z.start_file("lines.dat", o).unwrap();
z.write_all(b"[1353, 1419, 1510]\n").unwrap();
z.start_file("note.dat", o).unwrap();
z.write_all(b"three plays\n").unwrap();
z.finish().unwrap();
std::fs::write(dir.join("roles.model"), "trait <late>: row[::id > 1];\n").unwrap();
std::fs::write(dir.join("taken.model"), "trait <json>: meta;\n").unwrap();
dir
}
fn run(dir: &Path, args: &[&str]) -> (String, String, bool) {
let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
.env("QUARB_LOCALE", "C")
.env("QUARB_OFFLINE", "localhost")
.current_dir(dir)
.args(args)
.stdin(std::process::Stdio::null())
.output()
.unwrap();
(
String::from_utf8_lossy(&out.stdout)
.trim()
.replace('\n', " "),
String::from_utf8_lossy(&out.stderr).trim().to_string(),
out.status.success(),
)
}
fn quiet(dir: &Path, args: &[&str]) -> String {
let (out, err, ok) = run(dir, args);
assert!(ok, "{args:?}: {err}");
assert_eq!(err, "", "{args:?}");
out
}
fn told(dir: &Path, args: &[&str]) -> (String, String) {
let (out, err, ok) = run(dir, args);
assert!(ok, "{args:?}: {err}");
assert_eq!(err.lines().count(), 1, "{args:?}: {err}");
(out, err)
}
#[test]
fn a_named_step_under_a_notation_tells_the_texts_it_does_not_read() {
let d = fixture("told");
let (out, line) = told(&d, &["/plays/*/meta<json>/author/name::", "store.json"]);
assert_eq!(out, "Sophocles Sophocles");
assert_eq!(
line,
"warning NOT_IN_NOTATION (/meta<json>): '<json>' reads a text as json: 2 texts are not \
written in it (the first: \"by Euripides\"), and the step matches nothing there. Spell \
it another way: qua man NOT_IN_NOTATION"
);
let (out, line) = told(&d, &["/plays/*/meta<json> @| count", "plays.db"]);
assert_eq!(out, "2");
assert_eq!(
line,
"warning NOT_IN_NOTATION (/meta<json>): '<json>' reads a text as json: 1 text is not \
written in it (\"by Euripides\"), and the step matches nothing there. Spell it another \
way: qua man NOT_IN_NOTATION"
);
assert_eq!(quiet(&d, &["//*<json> @| count", "store.json"]), "2");
assert_eq!(
quiet(&d, &["/plays/*/meta<!json> @| count", "store.json"]),
"3"
);
assert_eq!(
quiet(&d, &["/plays/*/meta<json || xml> @| count", "store.json"]),
"3"
);
let (out, line) = told(&d, &["/plays/*/meta<json>[1]/author/name::", "store.json"]);
assert_eq!(out, "Sophocles Sophocles");
assert!(
line.starts_with("warning NOT_IN_NOTATION (/meta<json>): "),
"{line}"
);
}
#[test]
fn the_step_walks_into_what_it_read_wherever_the_text_lies() {
let d = fixture("walks");
let (out, _) = told(&d, &["/plays/*/meta<json>/author/name::", "plays.db"]);
assert_eq!(out, "Sophocles Sophocles");
assert_eq!(
quiet(&d, &["/plays/1/meta<json>/author/name::", "store.json"]),
"Sophocles"
);
assert_eq!(
quiet(&d, &["/lines.dat<json>/*::", "shelf"]),
"1353 1419 1510"
);
let (out, line) = told(&d, &["/note.dat<json>/*::", "shelf"]);
assert_eq!(out, "");
assert_eq!(
line,
"warning NOT_IN_NOTATION (/note.dat<json>): '<json>' reads a text as json: 1 text is \
not written in it (\"three plays\"), and the step matches nothing there. Spell it \
another way: qua man NOT_IN_NOTATION"
);
assert_eq!(
quiet(&d, &["/lines.dat<json>/*::", "shelf.zip"]),
"1353 1419 1510"
);
let (out, line) = told(&d, &["/row/payload<json>/lines::", "plays.csv"]);
assert_eq!(out, "1353 1510");
assert_eq!(
line,
"warning NOT_IN_NOTATION (/payload<json>): '<json>' reads a text as json: 1 text is not \
written in it (\"unknown\"), and the step matches nothing there. Spell it another way: \
qua man NOT_IN_NOTATION"
);
assert_eq!(quiet(&d, &["/row/nosuch<json>/lines::", "plays.csv"]), "");
}
#[test]
fn a_cell_named_by_its_column_stands_under_its_row() {
let d = fixture("cell");
assert_eq!(
quiet(&d, &["/row[1]/payload<json>/lines", "plays.csv"]),
"/row[1]/payload!/lines"
);
assert_eq!(
quiet(&d, &["/row[3]/payload<json> | :name", "plays.csv"]),
"payload"
);
assert_eq!(
quiet(
&d,
&["/row[3]/payload<json>/lines | \\\\row::id", "plays.csv"]
),
"3"
);
assert_eq!(quiet(&d, &["/row/payload", "plays.csv"]), "");
assert_eq!(quiet(&d, &["/row/* @| count", "plays.csv"]), "0");
}
#[test]
fn graft_answers_null_for_a_text_that_is_not_in_the_notation() {
let d = fixture("graft");
let (out, line) = told(
&d,
&[
"/plays/*/meta:: | graft(json) | /author/name::",
"store.json",
],
);
assert_eq!(out, "Sophocles Sophocles");
assert_eq!(
line,
"warning NOT_IN_NOTATION (graft(json)): 'graft(json)' reads a text as json: 2 texts are \
not written in it (the first: \"by Euripides\"), and the command answers null for \
each. Spell it another way: qua man NOT_IN_NOTATION"
);
let (out, line) = told(&d, &["/row[2]::payload | graft(json)", "plays.csv"]);
assert_eq!(out, "null");
assert_eq!(
line,
"warning NOT_IN_NOTATION (graft(json)): 'graft(json)' reads a text as json: 1 text is \
not written in it (\"unknown\"), and the command answers null. Spell it another way: \
qua man NOT_IN_NOTATION"
);
let (_, err, ok) = run(&d, &["/plays/*/meta:: | graft(nosuch)", "store.json"]);
assert!(!ok);
assert!(
err.starts_with(
"error REFUSED (query): refused: graft(nosuch): 'nosuch' names no notation"
),
"{err}"
);
}
#[test]
fn graft_reads_the_text_of_the_node_it_stands_on() {
let d = fixture("node");
assert_eq!(
quiet(&d, &["//lines.dat | graft(json) | /*::", "shelf"]),
"1353 1419 1510"
);
assert_eq!(
quiet(&d, &["//play.json | graft(json) | /lines::", "shelf"]),
"1353"
);
assert_eq!(
quiet(&d, &["//play.json | graft | /lines::", "shelf"]),
"1353"
);
assert_eq!(
quiet(&d, &["//play.json | graft(json2) | ::lines", "shelf"]),
"1353"
);
let (out, _, ok) = run(
&d,
&["/plays/1/meta | graft(json) | /author/name::", "plays.db"],
);
assert!(ok);
assert_eq!(out, "Sophocles");
let (out, line) = told(&d, &["//note.dat | graft(json)", "shelf"]);
assert_eq!(out, "null");
assert_eq!(
line,
"warning NOT_IN_NOTATION (graft(json)): 'graft(json)' reads a text as json: 1 text is \
not written in it (\"three plays\"), and the command answers null. Spell it another \
way: qua man NOT_IN_NOTATION"
);
let (_, err, ok) = run(&d, &["//note.dat | graft", "shelf"]);
assert!(!ok);
assert!(
err.starts_with("error REFUSED (query): refused: graft: the text declares no notation"),
"{err}"
);
}
#[test]
fn a_model_keeps_the_notation_and_declares_no_trait_under_its_name() {
let d = fixture("model");
assert_eq!(
quiet(
&d,
&[
"--model",
"roles.model",
"/plays/1/meta<json>/author/name::",
"store.json"
]
),
"Sophocles"
);
assert_eq!(
quiet(
&d,
&["--model", "roles.model", "/lines.dat<json>/*::", "shelf"]
),
"1353 1419 1510"
);
let (out, line) = told(
&d,
&[
"--model",
"roles.model",
"/row<late>/payload<json>/lines::",
"plays.csv",
],
);
assert_eq!(out, "1510");
assert!(
line.starts_with("warning NOT_IN_NOTATION (/payload<json>): "),
"{line}"
);
let (_, err, ok) = run(&d, &["--model", "taken.model", "/plays/*", "store.json"]);
assert!(!ok);
assert!(
err.contains(
"trait <json>: 'json' is a notation's name, and '<json>' at a step reads what the \
step names in that notation; a model's trait takes another name"
),
"{err}"
);
}
#[test]
fn a_source_languages_word_is_a_notations_name() {
let d = fixture("source");
std::fs::write(d.join("shelf/code.dat"), "x = 1\n").unwrap();
std::fs::write(d.join("shelf/lib.rs"), "fn main() {}\n").unwrap();
for word in quarb_tree_sitter::EXTENSIONS {
assert_eq!(
quiet(&d, &[&format!("/code.dat<{word}> @| count"), "shelf"]),
"1",
"{word}"
);
let err = quarb_model::parse_model(&format!("trait <{word}>: row;")).unwrap_err();
assert!(
err.starts_with(&format!("trait <{word}>: '{word}' is a notation's name")),
"{word}: {err}"
);
}
for (long, word) in quarb_tree_sitter::LONG_NAMES {
assert!(
quarb_compose::LONG_NAMES.contains(&(*long, *word)),
"{long}"
);
assert_eq!(quarb_compose::canonical_notation(long), *word);
for (a, b) in [
(
format!(r#"= "x = 1" | graft({long}) | //* @| count"#),
format!(r#"= "x = 1" | graft({word}) | //* @| count"#),
),
(
"/code.dat//* @| count".to_string(),
"/code.dat//* @| count".to_string(),
),
] {
let with_long = if a.starts_with('=') {
quiet(&d, &[&a])
} else {
quiet(&d, &[&a, &format!("shelf?format={long}")])
};
let with_word = if b.starts_with('=') {
quiet(&d, &[&b])
} else {
quiet(&d, &[&b, &format!("shelf?format={word}")])
};
assert_eq!(with_long, with_word, "{long}: {a}");
assert_ne!(with_long, "0", "{long}: {a}");
}
let err = quarb_model::parse_model(&format!("trait <{long}>: row;")).unwrap_err();
assert!(
err.starts_with(&format!("trait <{long}>: '{long}' is a notation's name")),
"{long}: {err}"
);
}
let piped = |format: &str, text: &[u8]| {
let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
.current_dir(&d)
.args(["--format", format, "//* @| count"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(text).unwrap();
let out = child.wait_with_output().unwrap();
(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
String::from_utf8_lossy(&out.stderr).to_string(),
out.status.success(),
)
};
let (by_long, err, ok) = piped("rust", b"fn main() {}\n");
assert!(ok, "{err}");
assert_eq!(by_long, piped("rs", b"fn main() {}\n").0);
assert_eq!(by_long, "4");
assert_eq!(quiet(&d, &["/*<rust> | :name", "shelf"]), "lib.rs");
assert_eq!(quiet(&d, &["/code.dat<rust> @| count", "shelf"]), "0");
assert!(quarb_model::parse_model("trait <pascal>: row;").is_ok());
let listed = format!(
"or a source language's word ({})",
quarb_compose::source_words_listed()
);
assert!(listed.contains("rs or rust, py or python, js or javascript, mjs"));
for args in [
&[r#"= "fn main() {}" | graft(pascal)"#][..],
&["--graft", "/* @| count", "shelf?format=pascal"][..],
] {
let (_, err, ok) = run(&d, args);
assert!(!ok, "{args:?}");
assert!(err.contains(&listed), "{args:?}: {err}");
}
let (_, err, ok) = piped("pascal", b"begin end.\n");
assert!(!ok);
assert!(err.contains(&listed), "--format pascal: {err}");
let (_, err, ok) = run(&d, &["/* @| count", "shelf/code.dat?format=rust"]);
assert!(!ok);
assert!(
err.contains(
"format=rust names a source language, which a file is read as by its extension"
),
"{err}"
);
assert_eq!(
quiet(&d, &[r#"= "fn main() {}" | graft(rs) | //* @| count"#]),
"4"
);
}
#[test]
fn a_mounts_format_opens_its_leaves_with_or_without_the_flag() {
let d = fixture("mount-format");
assert_eq!(quiet(&d, &["/lines.dat/* @| count", "shelf"]), "0");
for args in [
&["/lines.dat/* @| count", "shelf?format=json"][..],
&["--graft", "/lines.dat/* @| count", "shelf?format=json"],
] {
assert_eq!(quiet(&d, args), "3", "{args:?}");
}
assert_eq!(
quiet(&d, &["/s/lines.dat/*:: @| sum", "s=shelf?format=json"]),
"4282"
);
assert_eq!(
quiet(&d, &["/play.json/lines::", "shelf?format=json"]),
"1353"
);
assert_eq!(
quiet(&d, &["/* | [:is-leaf] | :name", "shelf?format=json"]),
"note.dat"
);
assert_eq!(quiet(&d, &["/lines.dat/* @| count", "shelf.zip"]), "0");
assert_eq!(
quiet(&d, &["/lines.dat/* @| count", "shelf.zip?format=json"]),
"3"
);
assert_eq!(
quiet(&d, &["/z/lines.dat/*:: @| sum", "z=shelf.zip?format=json"]),
"4282"
);
assert_eq!(
quiet(
&d,
&[
"--no-graft",
"/lines.dat/* @| count",
"shelf.zip?format=json"
]
),
"0"
);
}