#[path = "library_support.rs"]
mod library;
use crate::serve::query::stages_tests_support as support;
use std::collections::BTreeSet;
use std::num::NonZeroU64;
use serde_json::{Value, json};
use crate::serve::protocol::{QueryRequest, Version};
use library::{Entry, load, render, run_entry};
use support::{Fixture, TestResult, patients, request, values};
const FOUR: NonZeroU64 = NonZeroU64::MIN.saturating_add(3);
#[test]
fn library_every_shipped_entry_runs_on_the_query_fixture_store() -> TestResult {
let groups = load()?;
let mut fixture = Fixture::new(None, &patients())?;
let before = fixture.run(&request("patients | limit(4)", FOUR), &[])?;
let earlier = before.get("selection").ok_or("missing fixture selection")?;
fixture.vectors(&[[1.0, 0.0], [4.0, 0.0], [3.0, 0.0], [2.0, 0.0]])?;
fixture.match_chain()?;
let current = fixture.run(&request("patients | limit(4)", FOUR), &[])?;
assert_ne!(
earlier,
current.get("selection").ok_or("missing head selection")?
);
let expected_groups = BTreeSet::from([
"Reading one collection",
"Choosing fields",
"Filtering",
"Ordering and bounding",
"Counting",
"Searching by meaning",
"Reading an earlier version",
"Grouping",
"Matching relationships",
"Executing labelled matches",
"Percentiles",
"Reranking",
"Searching by text",
"Shaping records",
"Append time windows",
]);
let mut seen_groups = BTreeSet::new();
let mut names = BTreeSet::new();
for group in &groups {
assert!(
seen_groups.insert(group.group.as_str()),
"duplicate group {}",
group.group
);
assert!(!group.entries.is_empty(), "empty group {}", group.group);
for entry in &group.entries {
assert!(
names.insert(entry.name.as_str()),
"duplicate entry {}",
entry.name
);
let answer = run_entry(&fixture, entry, earlier)?;
assert_eq!(
values(&answer)?,
expected(&entry.name)?,
"entry {}",
entry.name
);
assert!(
answer
.get("next")
.ok_or("missing page continuation")?
.is_null(),
"entry {} is incomplete",
entry.name
);
check_version(entry, &answer, &render(entry, earlier)?, &fixture)?;
}
}
assert_eq!(seen_groups, expected_groups);
assert_eq!(
names.len(),
27,
"every shipped entry must have a fixture expectation"
);
Ok(())
}
#[test]
fn library_two_collection_shape_has_exact_fixture_values() -> TestResult {
let mut fixture = Fixture::new(None, &patients())?;
let groups = load()?;
let entry = groups
.iter()
.flat_map(|group| &group.entries)
.find(|entry| entry.name == "Selected fields from two collections")
.ok_or("missing two-collection shape entry")?;
let expected = vec![
json!({"name":"Bea"}),
json!({"code":"4B"}),
json!({"code":"3A"}),
];
let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
assert_eq!(values(&answer)?, expected);
assert!(answer.get("next").ok_or("missing next")?.is_null());
fixture.match_chain()?;
let after = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
assert_eq!(values(&after)?, expected);
assert!(after.get("next").ok_or("missing next")?.is_null());
Ok(())
}
#[test]
fn library_pages_keep_response_roots_out_of_request_selection() -> TestResult {
let fixture = Fixture::new(None, &patients())?;
let before = fixture.run(&request("patients | limit(4)", FOUR), &[])?;
let captured = before.get("selection").ok_or("missing page selection")?;
let roots = captured
.get("roots")
.and_then(Value::as_array)
.ok_or("missing captured roots")?;
assert_eq!(roots.len(), 4);
let entry = sample()?;
let ask = render(&entry, captured)?;
let selection = serde_json::to_value(&ask.selection)?;
let fields: BTreeSet<_> = selection
.as_object()
.ok_or("request selection is not an object")?
.keys()
.map(String::as_str)
.collect();
assert_eq!(fields, BTreeSet::from(["branch", "version"]));
let answer = run_entry(&fixture, &entry, captured)?;
assert_eq!(
answer
.get("selection")
.ok_or("missing repeated selection")?,
captured
);
assert_eq!(values(&answer)?, patients());
Ok(())
}
#[test]
fn library_a_misspelt_word_fails_and_names_the_entry() -> TestResult {
let fixture = Fixture::new(None, &patients())?;
let entry: Entry = serde_json::from_value(json!({
"name": "Misspelt count",
"sentence": "Count the records in one collection.",
"query": "${collection} | coutn",
"change": "Choose ${collection}.",
"defaults": {"collection": "patients"}
}))?;
let failure = run_entry(&fixture, &entry, &json!({"branch":"main"}))
.err()
.ok_or("the library accepted a misspelt word")?;
assert!(failure.to_string().contains("Misspelt count"), "{failure}");
assert!(failure.to_string().contains("query_parse"), "{failure}");
Ok(())
}
#[test]
fn library_a_missing_default_fails_and_names_the_entry_and_part() -> TestResult {
let mut entry = sample()?;
entry.defaults.clear();
let failure = render(&entry, &json!({"branch":"main"}))
.err()
.ok_or("a placeholder without a default was inserted")?;
assert!(failure.to_string().contains("All records"), "{failure}");
assert!(failure.to_string().contains("collection"), "{failure}");
Ok(())
}
#[test]
fn library_an_unclosed_placeholder_fails_and_names_the_entry() -> TestResult {
let mut entry = sample()?;
entry.query = "${collection".to_owned();
let failure = render(&entry, &json!({"branch":"main"}))
.err()
.ok_or("an unclosed placeholder was inserted")?;
assert!(failure.to_string().contains("All records"), "{failure}");
assert!(failure.to_string().contains("unclosed"), "{failure}");
Ok(())
}
#[test]
fn library_a_missing_captured_version_is_refused_without_using_the_head() -> TestResult {
let groups = load()?;
let entry = groups
.iter()
.flat_map(|group| &group.entries)
.find(|entry| entry.name == "Records at an earlier version")
.ok_or("missing earlier-version example")?;
let failure = render(entry, &json!({"branch":"main"}))
.err()
.ok_or("a missing captured version became a head reading")?;
assert!(failure.to_string().contains(&entry.name), "{failure}");
assert!(
failure.to_string().contains("selection.version"),
"{failure}"
);
Ok(())
}
#[test]
fn library_a_store_refusal_fails_and_names_the_entry() -> TestResult {
let mut fixture = Fixture::new(None, &patients())?;
fixture.scan(NonZeroU64::MIN);
let mut entry = sample()?;
entry.query = "collection(${collection}) | count".to_owned();
let failure = run_entry(&fixture, &entry, &json!({"branch":"main"}))
.err()
.ok_or("an incomplete count was accepted")?;
assert!(failure.to_string().contains("All records"), "{failure}");
assert!(
failure.to_string().contains("query_scan_limit"),
"{failure}"
);
Ok(())
}
#[test]
fn library_a_worker_refusal_fails_and_names_the_entry() -> TestResult {
let mut fixture = Fixture::new(None, &patients())?;
fixture.no_worker();
let failure = run_entry(&fixture, &sample()?, &json!({"branch":"main"}))
.err()
.ok_or("an absent worker was accepted")?;
assert!(failure.to_string().contains("All records"), "{failure}");
assert!(
failure.to_string().contains("query_engine_unavailable"),
"{failure}"
);
Ok(())
}
#[test]
fn library_pages_keep_the_fixture_continuation() -> TestResult {
let fixture = Fixture::new(None, &patients())?;
let mut ask = render(&sample()?, &json!({"branch":"main"}))?;
ask.page.rows = NonZeroU64::MIN;
let answer = fixture.run(&ask, &[])?;
let next = answer
.get("next")
.and_then(Value::as_str)
.ok_or("missing continuation")?;
let token = crate::serve::query::Continuation::decode(next, &fixture.seal)?;
assert_eq!(token.branch, "main");
assert_eq!(token.resume.pending.collection, "patients");
assert_eq!(values(&answer)?, vec![patients()[0].clone()]);
ask.continuation = Some(next.to_owned());
let second = fixture.run(&ask, &[])?;
assert_eq!(values(&second)?, vec![patients()[1].clone()]);
assert_eq!(second.get("selection"), answer.get("selection"));
Ok(())
}
fn sample() -> Result<Entry, Box<dyn std::error::Error>> {
Ok(serde_json::from_value(json!({
"name": "All records",
"sentence": "Read every record in one collection.",
"query": "collection(${collection})",
"change": "Choose ${collection}.",
"defaults": {"collection": "\"patients\""}
}))?)
}
fn expected(name: &str) -> Result<Vec<Value>, Box<dyn std::error::Error>> {
let documents = patients();
match name {
"Labelled patients" => Ok(documents
.into_iter()
.map(|record| json!({"c": record}))
.collect()),
"Patients admitted to wards"
| "Wards admitting patients"
| "Bound relationship records" => Ok(vec![json!({
"c": documents[0], "w": {"ward":"4B", "code":"4B"}
})]),
"Patients with ward nurses" => Ok(vec![json!({
"c": documents[0], "w": {"ward":"4B", "code":"4B"}, "n": {"name":"Nia"}
})]),
"Bound labelled records" => Ok(documents
.into_iter()
.take(2)
.map(|record| json!({"c": record}))
.collect()),
"All records"
| "Records at an earlier version"
| "Records in a version window"
| "Records in an instant window" => Ok(documents),
"Names" => Ok(vec![json!("Ada"), json!("Bea"), json!("Cy"), json!("Dee")]),
"Records in one ward"
| "Records containing text"
| "Text in one field"
| "Whole field text" => Ok(vec![
documents[0].clone(),
documents[2].clone(),
documents[3].clone(),
]),
"Newest records" | "Similar records" => {
Ok(vec![documents[1].clone(), documents[2].clone()])
}
"Similar records after text" => Ok(vec![documents[2].clone(), documents[3].clone()]),
"Records without text" => Ok(vec![documents[1].clone()]),
"First records" => Ok(vec![documents[0].clone(), documents[1].clone()]),
"Count records" | "Nearest-rank percentile" => Ok(vec![json!(4)]),
"Reranked records" => Ok(vec![documents[1].clone(), documents[2].clone()]),
"Selected fields" | "Selected collection fields" => Ok(vec![
json!({"name":"Ada", "ward":"4B"}),
json!({"name":"Bea", "ward":"3A"}),
json!({"name":"Cy", "ward":"4B"}),
json!({"name":"Dee", "ward":"4B"}),
]),
"Selected fields from two collections" => Ok(vec![
json!({"name":"Bea"}),
json!({"code":"4B"}),
json!({"code":"3A"}),
]),
"Records by ward" => Ok(vec![
json!({"key":"3A","count":1,"values":[documents[1]]}),
json!({"key":"4B","count":3,"values":[
documents[0], documents[2], documents[3]
]}),
]),
other => Err(format!("entry {other} has no fixture expectation").into()),
}
}
fn check_version(
entry: &Entry,
answer: &Value,
asked: &QueryRequest,
fixture: &Fixture,
) -> TestResult {
let Some(version) = asked.selection.version else {
return Ok(());
};
let actual = answer
.get("selection")
.and_then(|selection| selection.get("version"))
.ok_or("missing page version")?;
assert_eq!(
serde_json::from_value::<Version>(actual.clone())?,
version,
"entry {} read a different version",
entry.name
);
for row in answer
.get("rows")
.and_then(Value::as_array)
.ok_or("missing rows")?
{
let origin = row.get("origin").ok_or("missing origin")?;
let collection = origin
.get("collection")
.and_then(Value::as_str)
.ok_or("missing origin collection")?;
let id = origin
.get("id")
.and_then(Value::as_str)
.ok_or("missing origin id")?;
let written = fixture
.written
.get(&format!("{collection}/{id}"))
.ok_or("origin record was never written")?;
assert_eq!(
origin.get("version").ok_or("missing origin version")?,
&serde_json::to_value(written)?,
"entry {} origin moved",
entry.name
);
}
Ok(())
}
#[test]
fn library_two_hop_chain_runs_to_exact_nonempty_fixture_values() -> TestResult {
let groups = load()?;
let entry = groups
.iter()
.flat_map(|group| &group.entries)
.find(|entry| entry.name == "Patients with ward nurses")
.ok_or("two-hop library entry missing")?;
let mut fixture = Fixture::new(None, &patients())?;
fixture.match_chain()?;
let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
assert_eq!(
values(&answer)?,
vec![json!({
"c": patients()[0], "w": {"ward":"4B", "code":"4B"}, "n": {"name":"Nia"}
})]
);
assert!(answer.get("next").ok_or("continuation missing")?.is_null());
Ok(())
}
#[test]
fn library_relationship_entries_return_no_rows_without_fixture_edges() -> TestResult {
let groups = load()?;
let fixture = Fixture::new(None, &patients())?;
for name in [
"Patients admitted to wards",
"Wards admitting patients",
"Bound relationship records",
] {
let entry = groups
.iter()
.flat_map(|group| &group.entries)
.find(|entry| entry.name == name)
.ok_or("relationship entry missing")?;
let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
assert_eq!(values(&answer)?, Vec::<Value>::new(), "{name}");
assert!(answer.get("next").ok_or("continuation missing")?.is_null());
}
Ok(())
}
#[test]
fn library_inverted_and_whole_field_searches_have_exact_fixture_results() -> TestResult {
let fixture = Fixture::new(None, &patients())?;
let groups = load()?;
for (name, expected) in [
("Records without text", vec![patients()[1].clone()]),
(
"Whole field text",
vec![
patients()[0].clone(),
patients()[2].clone(),
patients()[3].clone(),
],
),
] {
let entry = groups
.iter()
.flat_map(|group| &group.entries)
.find(|entry| entry.name == name)
.ok_or("missing new rg library entry")?;
let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
assert_eq!(values(&answer)?, expected, "{name}");
assert!(answer.get("next").ok_or("missing next")?.is_null());
}
Ok(())
}