#![allow(clippy::indexing_slicing, clippy::expect_used)]
use docs_search::{Index, IndexBuilder, IndexError};
use proptest::prelude::*;
fn lib_ok<T>(r: Result<T, IndexError>) -> Result<T, TestCaseError> {
r.map_err(|e| TestCaseError::fail(e.to_string()))
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn corrupted_input_never_panics(
cut in 0usize..400,
bitflip in 0usize..400,
) {
let mut b = IndexBuilder::new();
b.add_doc("alpha beta gamma");
b.add_doc("beta delta epsilon zeta eta theta");
let mut bytes = lib_ok(b.build())?;
let cut = cut.min(bytes.len());
bytes.truncate(cut);
if let Some(slot) = bytes.get_mut(bitflip) {
*slot ^= 0xff;
}
let _ = Index::from_bytes(&bytes);
}
#[test]
fn round_trip_preserves_membership(
docs in proptest::collection::vec("[a-zA-Z0-9 ]{1,64}", 1..12),
) {
let mut b = IndexBuilder::new();
for d in &docs {
b.add_doc(d);
}
let bytes = lib_ok(b.build())?;
let idx = lib_ok(Index::from_bytes(&bytes))?;
prop_assert_eq!(idx.len() as usize, docs.len());
let first: String = docs[0]
.split(|c: char| !c.is_alphanumeric())
.find(|t| !t.is_empty())
.unwrap_or_default()
.to_lowercase();
if !first.is_empty() {
prop_assert!(idx.query(&first, docs.len()).iter().any(|h| h.doc == 0));
}
}
}
#[cfg(feature = "vectors")]
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn corrupted_vector_input_never_panics(
cut in 0usize..400,
bitflip in 0usize..400,
) {
let mut b = IndexBuilder::new();
let d0 = b.add_doc("alpha beta gamma");
let d1 = b.add_doc("beta delta epsilon zeta eta theta");
lib_ok(b.set_vector(d0 as u32, &[1.0, -2.5, 0.125]))?;
lib_ok(b.set_vector(d1 as u32, &[0.0, 3.0, -7.25]))?;
let mut bytes = lib_ok(b.build())?;
let cut = cut.min(bytes.len());
bytes.truncate(cut);
if let Some(slot) = bytes.get_mut(bitflip) {
*slot ^= 0xff;
}
let _ = Index::from_bytes(&bytes);
}
}