use std::collections::BTreeMap;
use crate::engine::Engine;
use crate::{Result, ScoutError, SearchDocument, SearchResult};
#[cfg(any(feature = "elasticsearch", feature = "meilisearch", feature = "typesense"))]
pub(crate) const DEAD_HTTP: &str = "http://127.0.0.1:1";
#[cfg(feature = "xunsearch")]
pub(crate) const DEAD_TCP: &str = "127.0.0.1:1";
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Observed {
Ok,
InvalidIndexName,
InvalidFieldName,
Unsupported,
Io,
Other(String),
}
pub(crate) fn inspect<T>(r: &Result<T>) -> Observed {
match r {
Ok(_) => Observed::Ok,
Err(ScoutError::InvalidIndexName(_)) => Observed::InvalidIndexName,
Err(ScoutError::InvalidFieldName(_)) => Observed::InvalidFieldName,
Err(ScoutError::Unsupported(_)) => Observed::Unsupported,
#[cfg(any(feature = "elasticsearch", feature = "meilisearch", feature = "typesense", feature = "algolia"))]
Err(ScoutError::Http(_)) => Observed::Io,
#[cfg(feature = "xunsearch")]
Err(ScoutError::XunSearch(_) | ScoutError::XunSearchIo(_)) => Observed::Io,
#[cfg(any(feature = "elasticsearch", feature = "meilisearch", feature = "typesense", feature = "algolia", feature = "xunsearch"))]
Err(ScoutError::Backend(_)) => Observed::Io,
#[cfg(feature = "database")]
Err(ScoutError::Sqlx(_)) => Observed::Io,
Err(other) => Observed::Other(format!("{other:?}")),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Want {
Index,
Field,
NotField,
Unsupported,
Ok,
OkOrIo,
}
impl Want {
fn accepts(self, o: &Observed) -> bool {
match self {
Want::Index => *o == Observed::InvalidIndexName,
Want::Field => *o == Observed::InvalidFieldName,
Want::NotField => *o != Observed::InvalidFieldName,
Want::Unsupported => *o == Observed::Unsupported,
Want::Ok => *o == Observed::Ok,
Want::OkOrIo => matches!(o, Observed::Ok | Observed::Io),
}
}
fn text(self) -> &'static str {
match self {
Want::Index => "InvalidIndexName", Want::Field => "InvalidFieldName",
Want::NotField => "非 InvalidFieldName", Want::Unsupported => "Unsupported(已声明例外)",
Want::Ok => "Ok", Want::OkOrIo => "Ok 或 I/O",
}
}
}
#[derive(Default)]
pub(crate) struct Sink {
gate: &'static str,
total: usize,
satisfied: BTreeMap<&'static str, usize>,
exceptions: Vec<String>,
unobservable: Vec<String>,
divergences: Vec<String>,
}
impl Sink {
pub(crate) fn new(gate: &'static str) -> Self {
Self { gate, ..Default::default() }
}
pub(crate) fn push(&mut self, driver: &'static str, what: &str, want: Want, obs: Observed, why: &str) {
self.total += 1;
let line = format!("{driver} / {what}: {obs:?}");
if !want.accepts(&obs) {
self.divergences.push(format!("{line} —— 期望 {}", want.text()));
} else if !why.is_empty() {
self.exceptions.push(format!("{line} —— {why}"));
} else if obs == Observed::Io {
self.unobservable.push(line);
} else {
*self.satisfied.entry(driver).or_insert(0) += 1;
}
}
pub(crate) fn content(&mut self, driver: &'static str, what: &str, res: &Result<SearchResult>, why: &str,
bad: impl FnOnce(&SearchResult) -> Option<String>) {
self.total += 1;
match res {
Ok(r) => match bad(r) {
None if why.is_empty() => *self.satisfied.entry(driver).or_insert(0) += 1,
None => self.exceptions.push(format!("{driver} / {what}: Ok —— {why}")),
Some(msg) => self.divergences.push(format!("{driver} / {what}: {msg}")),
},
Err(e) if inspect(res) == Observed::Io => self.unobservable.push(format!("{driver} / {what}: {e}")),
Err(e) => self.divergences.push(format!("{driver} / {what}: {e} —— 期望 Ok,实测非 Ok")),
}
}
pub(crate) fn empty(&mut self, driver: &'static str, what: &str, res: &Result<SearchResult>, why: &str) {
self.content(driver, what, res, why, |r| {
(r.total != 0 || !r.hits.is_empty())
.then(|| format!("期望空结果,实测 total={} hits={}", r.total, r.hits.len()))
});
}
pub(crate) fn total_is(&mut self, driver: &'static str, what: &str, res: &Result<SearchResult>, want_total: usize, why: &str) {
self.content(driver, what, res, why, |r| {
(r.total != want_total).then(|| format!("实测 total={},期望 {want_total}", r.total))
});
}
pub(crate) fn finish(self) {
let per_driver: Vec<String> = self.satisfied.iter().map(|(k, v)| format!("{k}={v}")).collect();
println!("[{}] 判据 {} 条 | 满足 [{}] | 已声明例外 {} | 不可观测 {} | 分歧 {}", self.gate, self.total,
per_driver.join(" "), self.exceptions.len(), self.unobservable.len(), self.divergences.len());
for (label, lines) in [("例外", &self.exceptions), ("不可观测", &self.unobservable), ("分歧", &self.divergences)] {
for line in lines {
println!(" [{label}] {line}");
}
}
assert!(self.divergences.is_empty(), "[{}] {} 处未声明分歧:\n{}", self.gate,
self.divergences.len(), self.divergences.join("\n"));
}
}
#[derive(Default, Clone, Copy)]
pub(crate) struct Caps {
pub(crate) no_reindex: bool,
pub(crate) no_soft_delete_in: bool,
pub(crate) no_soft_delete: bool,
pub(crate) indexless_soft_delete: bool,
pub(crate) no_where_not_in: bool,
pub(crate) concatenates_fields: bool,
pub(crate) ignores_order: bool,
pub(crate) never_validates: bool,
}
pub(crate) struct Subject {
pub(crate) name: &'static str,
pub(crate) engine: Box<dyn Engine>,
pub(crate) in_process: bool,
pub(crate) caps: Caps,
}
impl Subject {
pub(crate) fn new(name: &'static str, engine: impl Engine + 'static, in_process: bool, caps: Caps) -> Self {
Self { name, engine: Box::new(engine), in_process, caps }
}
pub(crate) fn ok(&self) -> Want {
if self.in_process { Want::Ok } else { Want::OkOrIo }
}
}
pub(crate) struct Harness {
pub(crate) subjects: Vec<Subject>,
#[cfg(feature = "database")]
db_files: Vec<std::path::PathBuf>,
}
impl Harness {
pub(crate) fn new(_tag: &str) -> Self {
#[allow(unused_mut)]
let mut subjects: Vec<Subject> = vec![Subject::new("collection", crate::CollectionEngine::new(), true, Caps::default())];
#[cfg(feature = "null")]
subjects.push(Subject::new("null", crate::NullEngine::new(), true, Caps { never_validates: true, ..Caps::default() }));
#[cfg(feature = "database")]
let mut db_files = Vec::new();
#[cfg(feature = "database")]
{
let path = temp_db_path(_tag);
let url = format!("sqlite://{}?mode=rwc", path.display());
let engine = crate::DatabaseEngine::new(&url, Vec::new()).expect("临时 sqlite 路径");
subjects.push(Subject::new("database", engine, true, Caps::default()));
db_files.push(path);
}
#[cfg(feature = "elasticsearch")]
subjects.push(Subject::new("elasticsearch", crate::ElasticsearchEngine::new(DEAD_HTTP.to_string(), None), false,
Caps { indexless_soft_delete: true, ..Caps::default() }));
#[cfg(feature = "meilisearch")]
subjects.push(Subject::new("meilisearch", crate::MeilisearchEngine::new(DEAD_HTTP.to_string(), Some("k".to_string())), false,
Caps { no_reindex: true, indexless_soft_delete: true, concatenates_fields: true, ..Caps::default() }));
#[cfg(feature = "typesense")]
subjects.push(Subject::new("typesense", crate::TypesenseEngine::new(DEAD_HTTP.to_string(), Some("k".to_string())), false,
Caps { no_reindex: true, indexless_soft_delete: true, concatenates_fields: true, ..Caps::default() }));
#[cfg(feature = "algolia")]
subjects.push(Subject::new("algolia", crate::AlgoliaEngine::new("scoutconformance".to_string(), "k".to_string()), false,
Caps { indexless_soft_delete: true, concatenates_fields: true, ignores_order: true, ..Caps::default() }));
#[cfg(feature = "xunsearch")]
subjects.push(Subject::new("xunsearch", crate::XunSearchEngine::new(DEAD_TCP, "scout", None), false,
Caps { no_reindex: true, no_soft_delete_in: true, no_soft_delete: true, no_where_not_in: true, ..Caps::default() }));
Self { subjects, #[cfg(feature = "database")] db_files }
}
}
impl Drop for Harness {
fn drop(&mut self) {
#[cfg(feature = "database")]
for path in &self.db_files {
let base = path.to_string_lossy().into_owned();
for suffix in ["", "-journal", "-wal", "-shm"] {
let _ = std::fs::remove_file(format!("{base}{suffix}"));
}
}
}
}
#[cfg(feature = "database")]
fn temp_db_path(tag: &str) -> std::path::PathBuf {
use std::sync::atomic::{AtomicUsize, Ordering};
static N: AtomicUsize = AtomicUsize::new(0);
std::env::temp_dir().join(format!("rust_scout_conformance_{}_{}_{}.db",
std::process::id(), tag, N.fetch_add(1, Ordering::Relaxed)))
}
pub(crate) fn doc(id: &str, index: &str) -> SearchDocument {
let mut d = SearchDocument::new(id, serde_json::json!({"tag": "x"})).expect("字段必须是 JSON 对象");
d.index = Some(index.to_string());
d
}