use super::StubState;
use super::bitset::CandidateBits;
use crate::imposter::predicates::json::{leaf_text, structural_hash};
use crate::imposter::types::Stub;
use crate::util::FastMap;
use aho_corasick::{AhoCorasick, MatchKind as AcMatchKind};
use regex_automata::util::syntax;
use regex_automata::{Input, MatchKind, PatternSet, meta};
use rift_types::predicate::{Predicate, PredicateOperation};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
pub(crate) struct DimensionRequest<'a> {
pub(crate) method: &'a str,
pub(crate) path: &'a str,
pub(crate) body: &'a crate::behaviors::LazyJson<'a>,
}
trait Dimension {
fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits);
fn prunes(&self) -> bool;
}
enum PathAnchor {
Exact(String),
}
fn field_path(fields: &HashMap<String, serde_json::Value>) -> Option<String> {
match fields.get("path") {
Some(serde_json::Value::String(s)) => Some(fold(s)),
_ => None,
}
}
fn fold(s: &str) -> String {
s.to_ascii_lowercase()
}
fn is_value_preserving(p: &rift_types::predicate::PredicateParameters) -> bool {
p.except.is_empty() && p.selector.is_none()
}
fn is_safely_indexable(p: &rift_types::predicate::PredicateParameters) -> bool {
is_value_preserving(p) && p.case_sensitive != Some(true)
}
fn path_anchor(pred: &Predicate) -> Option<PathAnchor> {
if !is_safely_indexable(&pred.parameters) {
return None;
}
match &pred.operation {
PredicateOperation::Equals(fields) => field_path(fields).map(PathAnchor::Exact),
_ => None,
}
}
fn classify(stub: &Stub) -> Option<PathAnchor> {
stub.predicates.iter().find_map(path_anchor)
}
struct PathDimension {
exact: FastMap<String, Vec<usize>>,
always: CandidateBits,
}
impl Dimension for PathDimension {
fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
out.copy_from(&self.always);
let matched = if request.path.bytes().any(|b| b.is_ascii_uppercase()) {
self.exact.get(&fold(request.path))
} else {
self.exact.get(request.path)
};
if let Some(v) = matched {
v.iter().for_each(|i| out.set(*i));
}
}
fn prunes(&self) -> bool {
!self.exact.is_empty()
}
}
const METHOD_SLOTS: usize = 8;
const SLOT_OTHER: usize = METHOD_SLOTS - 1;
fn method_slot(method: &str) -> usize {
const NAMED: [&str; SLOT_OTHER] = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
NAMED
.iter()
.position(|m| method.eq_ignore_ascii_case(m))
.unwrap_or(SLOT_OTHER)
}
fn method_anchor(pred: &Predicate) -> Option<&str> {
if !is_safely_indexable(&pred.parameters) {
return None;
}
match &pred.operation {
PredicateOperation::Equals(fields) => match fields.get("method") {
Some(serde_json::Value::String(s)) => Some(s.as_str()),
_ => None,
},
_ => None,
}
}
struct MethodDimension {
slots: [Vec<usize>; METHOD_SLOTS],
always: CandidateBits,
}
impl Dimension for MethodDimension {
fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
out.copy_from(&self.always);
self.slots[method_slot(request.method)]
.iter()
.for_each(|i| out.set(*i));
}
fn prunes(&self) -> bool {
self.slots.iter().any(|s| !s.is_empty())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LiteralKind {
Contains,
StartsWith,
EndsWith,
}
struct LiteralSet {
ac: AhoCorasick,
entries: Vec<(usize, LiteralKind)>,
}
impl LiteralSet {
fn mark(&self, path: &str, out: &mut CandidateBits) {
for m in self.ac.find_overlapping_iter(path) {
let (stub, kind) = self.entries[m.pattern().as_usize()];
let hit = match kind {
LiteralKind::Contains => true,
LiteralKind::StartsWith => m.start() == 0,
LiteralKind::EndsWith => m.end() == path.len(),
};
if hit {
out.set(stub);
}
}
}
}
fn build_literal_class(
entries: Vec<(usize, String, LiteralKind)>,
case_insensitive: bool,
) -> (Option<LiteralSet>, Vec<usize>) {
if entries.is_empty() {
return (None, Vec::new());
}
let patterns: Vec<&str> = entries.iter().map(|(_, p, _)| p.as_str()).collect();
match AhoCorasick::builder()
.match_kind(AcMatchKind::Standard)
.ascii_case_insensitive(case_insensitive)
.build(&patterns)
{
Ok(ac) => {
let entries = entries
.into_iter()
.map(|(stub, _, kind)| (stub, kind))
.collect();
(Some(LiteralSet { ac, entries }), Vec::new())
}
Err(e) => {
tracing::warn!(
stubs = entries.len(),
case_insensitive,
error = %e,
"literal dimension: multi-pattern build failed for the whole set; all its stubs \
fall back to full predicate evaluation"
);
(None, entries.into_iter().map(|(stub, _, _)| stub).collect())
}
}
}
struct LiteralAnchor<'a> {
text: &'a str,
kind: LiteralKind,
case_sensitive: bool,
}
fn literal_anchor(pred: &Predicate) -> Option<LiteralAnchor<'_>> {
if !is_value_preserving(&pred.parameters) {
return None;
}
let (fields, kind) = match &pred.operation {
PredicateOperation::Contains(fields) => (fields, LiteralKind::Contains),
PredicateOperation::StartsWith(fields) => (fields, LiteralKind::StartsWith),
PredicateOperation::EndsWith(fields) => (fields, LiteralKind::EndsWith),
_ => return None,
};
match fields.get("path") {
Some(serde_json::Value::String(text)) => Some(LiteralAnchor {
text,
kind,
case_sensitive: pred.parameters.case_sensitive == Some(true),
}),
_ => None,
}
}
struct LiteralDimension {
insensitive: Option<LiteralSet>,
sensitive: Option<LiteralSet>,
always: CandidateBits,
}
impl Dimension for LiteralDimension {
fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
out.copy_from(&self.always);
for s in [&self.insensitive, &self.sensitive].into_iter().flatten() {
s.mark(request.path, out);
}
}
fn prunes(&self) -> bool {
self.insensitive.is_some() || self.sensitive.is_some()
}
}
const NFA_SIZE_LIMIT: usize = 10 * (1 << 20);
const DFA_SIZE_LIMIT: usize = 32 * (1 << 20);
const HYBRID_CACHE_CAPACITY: usize = 16 * (1 << 20);
struct MultiRegex {
re: meta::Regex,
pattern_stubs: Vec<usize>,
}
thread_local! {
static PATTERN_SCRATCH: RefCell<PatternSet> = RefCell::new(PatternSet::new(0));
}
impl MultiRegex {
fn mark(&self, path: &str, out: &mut CandidateBits) {
PATTERN_SCRATCH.with_borrow_mut(|set| {
let needed = self.re.pattern_len();
if set.capacity() < needed {
*set = PatternSet::new(needed);
} else {
set.clear();
}
self.re.which_overlapping_matches(&Input::new(path), set);
for pid in set.iter() {
out.set(self.pattern_stubs[pid.as_usize()]);
}
});
}
}
fn build_multi_regex(
patterns: &[&str],
case_insensitive: bool,
) -> Result<meta::Regex, Box<meta::BuildError>> {
meta::Regex::builder()
.syntax(syntax::Config::new().case_insensitive(case_insensitive))
.configure(
meta::Config::new()
.match_kind(MatchKind::All)
.nfa_size_limit(Some(NFA_SIZE_LIMIT))
.dfa_size_limit(Some(DFA_SIZE_LIMIT))
.hybrid_cache_capacity(HYBRID_CACHE_CAPACITY),
)
.build_many(patterns)
.map_err(Box::new)
}
fn pattern_preview(p: &str) -> String {
const MAX: usize = 80;
if p.len() <= MAX {
return p.to_owned();
}
let cut = (0..=MAX)
.rev()
.find(|i| p.is_char_boundary(*i))
.unwrap_or(0);
format!("{}… ({} bytes total)", &p[..cut], p.len())
}
fn build_case_class(
entries: Vec<(usize, String)>,
case_insensitive: bool,
) -> (Option<MultiRegex>, Vec<usize>) {
let assemble = |entries: &[(usize, String)]| -> Option<MultiRegex> {
if entries.is_empty() {
return None;
}
let patterns: Vec<&str> = entries.iter().map(|(_, p)| p.as_str()).collect();
let re = build_multi_regex(&patterns, case_insensitive).ok()?;
Some(MultiRegex {
re,
pattern_stubs: entries.iter().map(|(stub, _)| *stub).collect(),
})
};
if entries.is_empty() {
return (None, Vec::new());
}
if let Some(m) = assemble(&entries) {
return (Some(m), Vec::new());
}
let mut ok: Vec<(usize, String)> = Vec::new();
let mut fallback: Vec<usize> = Vec::new();
for (stub, pattern) in entries {
match build_multi_regex(&[pattern.as_str()], case_insensitive) {
Ok(_) => ok.push((stub, pattern)),
Err(e) => {
tracing::warn!(
stub,
pattern = %pattern_preview(&pattern),
case_insensitive,
error = %e,
"regex dimension: pattern rejected by the multi-pattern build; this stub falls \
back to full predicate evaluation"
);
fallback.push(stub);
}
}
}
if !fallback.is_empty()
&& let Some(m) = assemble(&ok)
{
return (Some(m), fallback);
}
tracing::warn!(
stubs = ok.len(),
case_insensitive,
"regex dimension: multi-pattern build failed for the whole set (aggregate size); all its \
stubs fall back to full predicate evaluation"
);
fallback.extend(ok.into_iter().map(|(stub, _)| stub));
(None, fallback)
}
struct RegexAnchor<'a> {
pattern: &'a str,
case_sensitive: bool,
}
fn regex_anchor(pred: &Predicate) -> Option<RegexAnchor<'_>> {
if !is_value_preserving(&pred.parameters) {
return None;
}
let PredicateOperation::Matches(fields) = &pred.operation else {
return None;
};
match fields.get("path") {
Some(serde_json::Value::String(pattern)) => Some(RegexAnchor {
pattern,
case_sensitive: pred.parameters.case_sensitive == Some(true),
}),
_ => None,
}
}
struct RegexDimension {
insensitive: Option<MultiRegex>,
sensitive: Option<MultiRegex>,
always: CandidateBits,
}
impl Dimension for RegexDimension {
fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
out.copy_from(&self.always);
for m in [&self.insensitive, &self.sensitive].into_iter().flatten() {
m.mark(request.path, out);
}
}
fn prunes(&self) -> bool {
self.insensitive.is_some() || self.sensitive.is_some()
}
}
fn body_anchor(pred: &Predicate) -> Option<u64> {
if !is_safely_indexable(&pred.parameters) || pred.parameters.key_case_sensitive == Some(true) {
return None;
}
let PredicateOperation::DeepEquals(fields) = &pred.operation else {
return None;
};
match fields.get("body") {
Some(v @ (serde_json::Value::Object(_) | serde_json::Value::Array(_))) => {
structural_hash(v)
}
_ => None,
}
}
struct BodyHashDimension {
by_hash: FastMap<u64, Vec<usize>>,
always: CandidateBits,
len: usize,
}
impl Dimension for BodyHashDimension {
fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
match request.body.get() {
None => out.copy_from(&self.always),
Some(body) => match structural_hash(body) {
None => out.copy_from(&CandidateBits::all(self.len)),
Some(h) => {
out.copy_from(&self.always);
if let Some(ids) = self.by_hash.get(&h) {
ids.iter().for_each(|i| out.set(*i));
}
}
},
}
}
fn prunes(&self) -> bool {
!self.by_hash.is_empty()
}
}
fn folded_leaf_string(v: &serde_json::Value) -> String {
leaf_text(v).to_ascii_lowercase()
}
#[cfg(feature = "quamina-matching")]
fn normalize_json_value(v: &serde_json::Value) -> serde_json::Value {
use serde_json::Value;
match v {
Value::Object(map) => Value::Object(
map.iter()
.map(|(k, val)| (k.to_ascii_lowercase(), normalize_json_value(val)))
.collect(),
),
Value::Array(items) => Value::Array(items.iter().map(normalize_json_value).collect()),
scalar => Value::String(folded_leaf_string(scalar)),
}
}
fn to_quamina_pattern_value(v: &serde_json::Value) -> Option<serde_json::Value> {
use serde_json::Value;
match v {
Value::String(s) if s.is_empty() => None,
Value::String(_) | Value::Bool(_) | Value::Number(_) => {
Some(Value::Array(vec![Value::String(folded_leaf_string(v))]))
}
Value::Object(map) => {
let mut out = serde_json::Map::with_capacity(map.len());
for (k, val) in map {
out.insert(k.to_ascii_lowercase(), to_quamina_pattern_value(val)?);
}
Some(Value::Object(out))
}
_ => None,
}
}
fn body_field_pattern(pred: &Predicate) -> Option<String> {
if !is_safely_indexable(&pred.parameters) || pred.parameters.key_case_sensitive == Some(true) {
return None;
}
let PredicateOperation::Equals(fields) = &pred.operation else {
return None;
};
let body = match fields.get("body") {
Some(v @ serde_json::Value::Object(map)) if !map.is_empty() => v,
_ => return None, };
structural_hash(body)?;
let pattern = to_quamina_pattern_value(body)?;
serde_json::to_string(&pattern).ok()
}
struct BodyFieldDimension {
#[cfg(feature = "quamina-matching")]
quamina: Option<quamina::Quamina<usize>>,
always: CandidateBits,
#[cfg(feature = "quamina-matching")]
len: usize,
}
impl Dimension for BodyFieldDimension {
fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
#[cfg(feature = "quamina-matching")]
debug_assert!(
self.quamina.is_some(),
"select() on a deactivated body-field dimension would under-approximate: its indexed \
stubs are in neither `quamina` nor `always`"
);
out.copy_from(&self.always);
#[cfg(not(feature = "quamina-matching"))]
let _ = request; #[cfg(feature = "quamina-matching")]
{
let Some(q) = &self.quamina else { return };
let Some(body) = request.body.get() else {
return;
};
if structural_hash(body).is_none() {
out.copy_from(&CandidateBits::all(self.len));
return;
}
let Ok(event) = serde_json::to_vec(&normalize_json_value(body)) else {
out.copy_from(&CandidateBits::all(self.len));
return;
};
match q.matches_for_event(&event) {
Ok(ids) => ids.into_iter().for_each(|i| out.set(i)),
Err(_) => out.copy_from(&CandidateBits::all(self.len)),
}
}
}
fn prunes(&self) -> bool {
#[cfg(feature = "quamina-matching")]
{
self.quamina.is_some()
}
#[cfg(not(feature = "quamina-matching"))]
{
false
}
}
}
#[cfg(feature = "quamina-matching")]
fn body_field_discriminates(
indexed: &CandidateBits,
exact: &FastMap<String, Vec<usize>>,
path_always: &CandidateBits,
method_of: &[Option<usize>],
) -> bool {
if indexed.count() < 2 {
return false;
}
if indexed.iter().any(|i| path_always.contains(i)) {
return true;
}
exact.values().any(|bucket| {
let members: Vec<usize> = bucket
.iter()
.copied()
.filter(|&i| indexed.contains(i))
.collect();
if members.len() < 2 {
return false;
}
const _: () = assert!(METHOD_SLOTS <= u8::BITS as usize);
let mut seen: u8 = 0;
for i in members {
match method_of[i] {
None => return true,
Some(slot) => {
let bit = 1u8 << slot;
if seen & bit != 0 {
return true;
}
seen |= bit;
}
}
}
false
})
}
pub(crate) struct StubIndex {
len: usize,
path: PathDimension,
method: MethodDimension,
literal: LiteralDimension,
regex: RegexDimension,
body: BodyHashDimension,
body_field: BodyFieldDimension,
}
impl StubIndex {
fn build(stubs: &[Arc<StubState>]) -> Self {
let len = stubs.len();
let mut exact: FastMap<String, Vec<usize>> = FastMap::default();
let mut path_always = CandidateBits::zeros(len);
let mut slots: [Vec<usize>; METHOD_SLOTS] = Default::default();
let mut method_always = CandidateBits::zeros(len);
let mut literal_ci: Vec<(usize, String, LiteralKind)> = Vec::new();
let mut literal_cs: Vec<(usize, String, LiteralKind)> = Vec::new();
let mut literal_always = CandidateBits::zeros(len);
let mut regex_ci: Vec<(usize, String)> = Vec::new();
let mut regex_cs: Vec<(usize, String)> = Vec::new();
let mut regex_always = CandidateBits::zeros(len);
let mut body_by_hash: FastMap<u64, Vec<usize>> = FastMap::default();
let mut body_always = CandidateBits::zeros(len);
#[cfg(feature = "quamina-matching")]
let mut body_field_patterns: Vec<(usize, String)> = Vec::new();
#[cfg(feature = "quamina-matching")]
let mut body_field_indexed = CandidateBits::zeros(len);
#[cfg(feature = "quamina-matching")]
let mut method_of: Vec<Option<usize>> = vec![None; len];
let mut body_field_always = CandidateBits::zeros(len);
for (i, state) in stubs.iter().enumerate() {
match classify(&state.stub) {
Some(PathAnchor::Exact(k)) => exact.entry(k).or_default().push(i),
None => path_always.set(i),
}
match state.stub.predicates.iter().find_map(method_anchor) {
Some(m) => {
let slot = method_slot(m);
slots[slot].push(i);
#[cfg(feature = "quamina-matching")]
{
method_of[i] = Some(slot);
}
}
None => method_always.set(i),
}
match state.stub.predicates.iter().find_map(literal_anchor) {
Some(a) if a.text.is_empty() => literal_always.set(i),
Some(a) if a.case_sensitive => literal_cs.push((i, a.text.to_owned(), a.kind)),
Some(a) => literal_ci.push((i, a.text.to_owned(), a.kind)),
None => literal_always.set(i),
}
match state.stub.predicates.iter().find_map(regex_anchor) {
Some(a) if a.case_sensitive => regex_cs.push((i, a.pattern.to_owned())),
Some(a) => regex_ci.push((i, a.pattern.to_owned())),
None => regex_always.set(i),
}
match state.stub.predicates.iter().find_map(body_anchor) {
Some(h) => body_by_hash.entry(h).or_default().push(i),
None => body_always.set(i),
}
match state.stub.predicates.iter().find_map(body_field_pattern) {
Some(_pattern) => {
#[cfg(feature = "quamina-matching")]
{
body_field_indexed.set(i);
body_field_patterns.push((i, _pattern));
}
#[cfg(not(feature = "quamina-matching"))]
body_field_always.set(i);
}
None => body_field_always.set(i),
}
}
let (literal_insensitive, literal_ci_fallback) = build_literal_class(literal_ci, true);
let (literal_sensitive, literal_cs_fallback) = build_literal_class(literal_cs, false);
for i in literal_ci_fallback.into_iter().chain(literal_cs_fallback) {
literal_always.set(i);
}
let (insensitive, ci_fallback) = build_case_class(regex_ci, true);
let (sensitive, cs_fallback) = build_case_class(regex_cs, false);
for i in ci_fallback.into_iter().chain(cs_fallback) {
regex_always.set(i);
}
#[cfg(feature = "quamina-matching")]
let body_field_quamina = if body_field_discriminates(
&body_field_indexed,
&exact,
&path_always,
&method_of,
) {
let mut q = quamina::Quamina::new();
for (i, pattern) in &body_field_patterns {
if let Err(e) = q.add_pattern(*i, pattern) {
tracing::warn!(stub = *i, error = %e,
"body-field dimension: pattern rejected; stub falls back to full evaluation");
body_field_always.set(*i);
}
}
Some(q)
} else {
None
};
let path = PathDimension {
exact,
always: path_always,
};
let method = MethodDimension {
slots,
always: method_always,
};
let literal = LiteralDimension {
insensitive: literal_insensitive,
sensitive: literal_sensitive,
always: literal_always,
};
let regex = RegexDimension {
insensitive,
sensitive,
always: regex_always,
};
let body = BodyHashDimension {
by_hash: body_by_hash,
always: body_always,
len,
};
let body_field = BodyFieldDimension {
#[cfg(feature = "quamina-matching")]
quamina: body_field_quamina,
always: body_field_always,
#[cfg(feature = "quamina-matching")]
len,
};
StubIndex {
len,
path,
method,
literal,
regex,
body,
body_field,
}
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.len
}
fn fold_in<D: Dimension>(
dimension: &D,
request: &DimensionRequest<'_>,
acc: &mut CandidateBits,
seeded: &mut bool,
len: usize,
) -> bool {
if !dimension.prunes() {
return true;
}
if *seeded {
let mut scratch = CandidateBits::zeros(len);
dimension.select(request, &mut scratch);
acc.intersect_with(&scratch);
} else {
dimension.select(request, acc);
*seeded = true;
}
!acc.is_empty()
}
pub(crate) fn candidates(&self, request: &DimensionRequest<'_>) -> CandidateBits {
let mut acc = CandidateBits::zeros(self.len);
let mut seeded = false;
if Self::fold_in(&self.method, request, &mut acc, &mut seeded, self.len)
&& Self::fold_in(&self.path, request, &mut acc, &mut seeded, self.len)
&& Self::fold_in(&self.literal, request, &mut acc, &mut seeded, self.len)
&& Self::fold_in(&self.regex, request, &mut acc, &mut seeded, self.len)
{
if Self::fold_in(&self.body, request, &mut acc, &mut seeded, self.len) {
Self::fold_in(&self.body_field, request, &mut acc, &mut seeded, self.len);
}
}
if seeded {
acc
} else {
CandidateBits::all(self.len)
}
}
}
fn predicate_contains_inject(pred: &Predicate) -> bool {
match &pred.operation {
PredicateOperation::Inject(_) => true,
PredicateOperation::Not(inner) => predicate_contains_inject(inner),
PredicateOperation::And(children) | PredicateOperation::Or(children) => {
children.iter().any(predicate_contains_inject)
}
_ => false,
}
}
pub(crate) struct StubSnapshot {
stubs: Vec<Arc<StubState>>,
index: StubIndex,
has_inject: bool,
has_scenario_gate: bool,
conditional_gates: Vec<(usize, Box<str>)>,
}
fn serves_conditional(stub: &crate::imposter::types::Stub) -> bool {
stub.responses.iter().any(|r| match r {
crate::imposter::types::StubResponse::Is {
rift: Some(rift), ..
} => !matches!(
rift.conditional,
None | Some(crate::imposter::types::ConditionalGet::Enabled(false))
),
_ => false,
})
}
impl StubSnapshot {
pub(crate) fn build(stubs: Vec<Arc<StubState>>) -> Self {
let index = StubIndex::build(&stubs);
let has_inject = stubs
.iter()
.any(|s| s.stub.predicates.iter().any(predicate_contains_inject));
let has_scenario_gate = stubs
.iter()
.any(|s| s.stub.required_scenario_state.is_some());
let conditional_gates = match stubs.iter().rposition(|s| serves_conditional(&s.stub)) {
None => Vec::new(),
Some(last) => stubs[..=last]
.iter()
.enumerate()
.filter_map(|(i, s)| {
s.stub
.required_scenario_state
.as_ref()
.map(|_| (i, s.stub.scenario_name.as_deref().unwrap_or("").into()))
})
.collect(),
};
StubSnapshot {
stubs,
index,
has_inject,
has_scenario_gate,
conditional_gates,
}
}
pub(crate) fn is_conditional_gate(&self, scenario: &str) -> bool {
self.conditional_gates.iter().any(|(_, s)| &**s == scenario)
}
pub(crate) fn conditional_gates_through(&self, index: usize) -> impl Iterator<Item = &str> {
self.conditional_gates
.iter()
.take_while(move |(i, _)| *i <= index)
.map(|(_, s)| &**s)
}
pub(crate) fn stubs(&self) -> &[Arc<StubState>] {
&self.stubs
}
pub(crate) fn has_inject(&self) -> bool {
self.has_inject
}
pub(crate) fn has_scenario_gate(&self) -> bool {
self.has_scenario_gate
}
#[cfg(test)]
pub(crate) fn candidates(&self, method: &str, path: &str) -> CandidateBits {
self.candidates_with_body(method, path, &crate::behaviors::LazyJson::absent())
}
pub(crate) fn candidates_with_body(
&self,
method: &str,
path: &str,
body_json: &crate::behaviors::LazyJson<'_>,
) -> CandidateBits {
self.index.candidates(&DimensionRequest {
method,
path,
body: body_json,
})
}
#[cfg(test)]
pub(crate) fn index(&self) -> &StubIndex {
&self.index
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imposter::core::Imposter;
use crate::imposter::types::ImposterConfig;
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use serde_json::{Value, json};
use std::collections::HashMap;
use tracing_test::traced_test;
fn unchecked_stub(preds: &Value) -> Stub {
let mut stub: Stub =
serde_json::from_value(json!({ "responses": [{ "is": { "statusCode": 200 } }] }))
.expect("valid stub");
stub.predicates = serde_json::from_value(preds.clone()).expect("valid predicates");
stub
}
fn stub_states(preds: &[Value]) -> Vec<Arc<StubState>> {
preds
.iter()
.map(|p| Arc::new(StubState::new(unchecked_stub(p))))
.collect()
}
fn snapshot(preds: &[Value]) -> StubSnapshot {
StubSnapshot::build(stub_states(preds))
}
fn candidate_ids(snap: &StubSnapshot, method: &str, path: &str) -> Vec<usize> {
snap.candidates(method, path).iter().collect()
}
fn candidate_ids_body(
snap: &StubSnapshot,
method: &str,
path: &str,
body: &Value,
) -> Vec<usize> {
let text = body.to_string();
snap.candidates_with_body(method, path, &crate::behaviors::LazyJson::new(Some(&text)))
.iter()
.collect()
}
fn imposter(preds: &[Value]) -> Imposter {
let mut config: ImposterConfig =
serde_json::from_value(json!({ "port": 9999, "protocol": "http" }))
.expect("valid imposter config");
config.stubs = preds.iter().map(unchecked_stub).collect();
Imposter::new(config).expect("test imposter")
}
fn corpus() -> Vec<Value> {
vec![
json!([{"equals": {"path": "/exact"}}]), json!([{"equals": {"path": "/EXACT"}}]), json!([{"startsWith": {"path": "/pre"}}]), json!([{"contains": {"path": "mid"}}]), json!([{"matches": {"path": "^/re[0-9]+$"}}]), json!([{"exists": {"query": true}}]), json!([{"equals": {"method": "POST"}}]), json!([{"equals": {"body": "ping"}}]), json!([{"or": [{"equals": {"path": "/o1"}}, {"equals": {"path": "/o2"}}]}]), json!([{"not": {"equals": {"path": "/nope"}}}]), json!([{"equals": {"path": "/cs"}, "caseSensitive": true}]), json!([{"equals": {"method": "GET", "path": "/mp"}}]), json!([]), ]
}
fn idx(r: anyhow::Result<Option<(Arc<StubState>, usize)>>) -> Option<usize> {
r.expect("no backend error").map(|(_, i)| i)
}
#[test]
fn indexed_matching_equals_linear() {
let imp = imposter(&corpus());
let no_headers: HashMap<String, String> = HashMap::new();
let requests: &[(&str, &str, Option<&str>, Option<&str>)] = &[
("GET", "/exact", None, None),
("GET", "/EXACT", None, None),
("GET", "/eXaCt", None, None), ("GET", "/prefixed/deep", None, None),
("GET", "/pre", None, None),
("GET", "/x-mid-y", None, None),
("GET", "/re12", None, None),
("GET", "/re", None, None), ("GET", "/mp", None, None),
("POST", "/mp", None, None), ("GET", "/nope", None, None), ("GET", "/cs", None, None), ("GET", "/CS", None, None),
("GET", "/o1", None, None),
("GET", "/o2", None, None),
("GET", "/anything", Some("a=1"), None), ("GET", "/anything", None, Some("ping")), ("GET", "/zzz", None, None), ("POST", "/zzz", None, None),
("GET", "/pre-mid-exact", None, None), ];
for (m, p, q, b) in requests {
let linear = idx(imp.find_matching_stub_linear(m, p, &no_headers, *q, *b, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, *q, *b, None, None));
assert_eq!(
indexed, linear,
"index diverged from linear for {m} {p} q={q:?} b={b:?}"
);
}
}
#[test]
fn indexed_matching_equals_linear_edge_cases() {
let imp = imposter(&[
json!([{"equals": {"path": "/café"}}]), json!([{"startsWith": {"path": "/A"}}]), json!([{"and": [{"equals": {"method": "GET"}}, {"equals": {"path": "/andp"}}]}]), json!([{"equals": {"path": "/exact"}}, {"startsWith": {"path": "/exa"}}]), json!([{"contains": {"path": "/seg"}}]), json!([{"equals": {"path": "/pm2"}}, {"equals": {"method": "GET"}}]), ]);
let no_headers: HashMap<String, String> = HashMap::new();
let requests: &[(&str, &str)] = &[
("GET", "/café"),
("GET", "/CAFÉ"), ("GET", "/caFé"),
("GET", "/a1"), ("GET", "/andp"), ("POST", "/andp"),
("GET", "/exact"), ("GET", "/exa"), ("GET", "/x/seg/y"),
("GET", "/exact/"), ("GET", "/andp/extra"),
("GET", "/pm2"), ("POST", "/pm2"), ];
for (m, p) in requests {
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
}
}
#[test]
fn body_field_dimension_matches_linear() {
let imp = imposter(&[
json!([{"equals": {"body": {"user": {"id": 5}}}}]), json!([{"equals": {"body": {"user": {"id": 7}}}}]), json!([{"equals": {"body": {"name": "Alice"}}}]), json!([{"equals": {"body": {"active": true}}}]), json!([{"equals": {"body": {"a": 1, "b": 2}}}]), json!([{"equals": {"body": {"tags": [1, 2]}}}]), json!([{"equals": {"body": {"x": null}}}]), json!([{"equals": {"body": {"n": 1.5}}}]), json!([{"equals": {"body": {"K": "V"}}, "caseSensitive": true}]), json!([{"equals": {"body": {"K": "v"}}, "keyCaseSensitive": true}]), json!([{"deepEquals": {"body": {"whole": 1}}}]), json!([{"equals": {"body": {"u": {"id": 5}}}, "except": "x"}]), json!([{"equals": {"body": {"deep": {"a": {"b": 3}}}}}]), json!([{"equals": {"body": {"code": "5"}}}]), json!([{"equals": {"body": {"j": "{\"x\":1}"}}}]), json!([{"equals": {"body": {"empt": ""}}}]), json!([]), ]);
let no_headers: HashMap<String, String> = HashMap::new();
let bodies: &[&str] = &[
r#"{"user":{"id":5}}"#,
r#"{"user":{"id":7}}"#,
r#"{"user":{"id":9}}"#, r#"{"USER":{"ID":5}}"#, r#"{"user":{"id":"5"}}"#, r#"{"name":"Alice"}"#,
r#"{"NAME":"ALICE"}"#, r#"{"name":"bob"}"#,
r#"{"active":true}"#,
r#"{"active":"true"}"#, r#"{"a":1,"b":2}"#,
r#"{"a":1,"b":3}"#, r#"{"tags":[1,2]}"#, r#"{"x":null}"#,
r#"{"n":1.5}"#,
r#"{"n":"1.5"}"#, r#"{"whole":1}"#, r#"{"K":"V"}"#, r#"{"deep":{"a":{"b":3}}}"#, r#"{"code":5}"#, r#"{"code":"5"}"#,
r#"{"j":{"x":1}}"#, r#"{"j":"{\"x\":1}"}"#, r#"{"empt":""}"#, r#"{"empt":null}"#, r#"not json at all"#, r#"{}"#, r#"{"user":{"id":5.0}}"#, r#"{"n":1.50}"#, r#"{"user":[{"id":9},{"id":7}]}"#, r#"{"name":["bob","ALICE"]}"#, r#"[{"name":"x"},{"name":"Alice"}]"#, r#"[1,2]"#,
];
for b in bodies {
let linear = idx(imp.find_matching_stub_linear(
"POST",
"/x",
&no_headers,
None,
Some(b),
None,
None,
));
let indexed = idx(imp.find_matching_stub_with_client(
"POST",
"/x",
&no_headers,
None,
Some(b),
None,
None,
));
assert_eq!(
indexed, linear,
"body-field index diverged from linear for body {b}"
);
}
}
#[test]
fn body_field_pattern_eligibility() {
let pat = |p: Value| -> Option<String> {
let stub: crate::imposter::types::Stub = serde_json::from_value(
json!({"predicates": p, "responses": [{"is": {"statusCode": 200}}]}),
)
.expect("stub");
stub.predicates.iter().find_map(body_field_pattern)
};
assert_eq!(
pat(json!([{"equals": {"body": {"User": {"Id": 5}}}}])).as_deref(),
Some(r#"{"user":{"id":["5"]}}"#)
);
assert_eq!(
pat(json!([{"equals": {"body": {"Name": "Alice"}}}])).as_deref(),
Some(r#"{"name":["alice"]}"#)
);
assert_eq!(
pat(json!([{"equals": {"body": {"ok": true}}}])).as_deref(),
Some(r#"{"ok":["true"]}"#)
);
assert_eq!(
pat(json!([{"equals": {"body": {"n": 1.5}}}])).as_deref(),
Some(r#"{"n":["1.5"]}"#) );
assert_eq!(
pat(json!([{"equals": {"body": {"n": 2.0}}}])).as_deref(),
Some(r#"{"n":["2"]}"#) );
for ineligible in [
json!([{"equals": {"body": {"tags": [1, 2]}}}]), json!([{"equals": {"body": {"x": null}}}]), json!([{"equals": {"body": {"x": ""}}}]), json!([{"equals": {"body": {"j": "{\"x\":1}"}}}]), json!([{"equals": {"body": {}}}]), json!([{"equals": {"body": "scalar"}}]), json!([{"equals": {"path": "/p"}}]), json!([{"deepEquals": {"body": {"a": 1}}}]), json!([{"equals": {"body": {"a": 1}}, "caseSensitive": true}]),
json!([{"equals": {"body": {"a": 1}}, "keyCaseSensitive": true}]),
json!([{"equals": {"body": {"a": 1}}, "except": "x"}]), json!([{"equals": {"body": {"a": 1}}, "jsonpath": {"selector": "$.a"}}]), ] {
assert!(
pat(ineligible.clone()).is_none(),
"should be ineligible: {ineligible}"
);
}
}
#[cfg(feature = "quamina-matching")]
#[test]
fn normalize_json_value_folds_to_comparator_string_form() {
let out = normalize_json_value(
&json!({"User": {"Name": "ALICE", "Id": 5, "OK": true, "F": 5.0, "Z": null}}),
);
assert_eq!(
out,
json!({"user": {"name": "alice", "id": "5", "ok": "true", "f": "5", "z": "null"}})
);
assert_eq!(normalize_json_value(&json!("CAFÉ")), json!("cafÉ"));
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_collapses_candidates() {
let preds: Vec<Value> = (0..500)
.map(|i| json!([{"equals": {"body": {"user": {"id": i}}}}]))
.collect();
let snap = snapshot(&preds);
let target = 437usize;
let ids = candidate_ids_body(&snap, "POST", "/x", &json!({"user": {"id": target}}));
assert_eq!(
ids,
vec![target],
"collapses to the single matching stub, got {ids:?}"
);
assert!(candidate_ids_body(&snap, "POST", "/x", &json!({"user": {"id": 9999}})).is_empty());
}
#[cfg(feature = "quamina-matching")]
fn body_field_active(preds: &[Value]) -> bool {
snapshot(preds).index.body_field.prunes()
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_inactive_when_no_path_method_is_shared() {
let preds: Vec<Value> = (0..50)
.map(|i| json!([{"equals": {"path": format!("/p{i}"), "body": {"user": {"id": i}}}}]))
.collect();
assert!(
!body_field_active(&preds),
"distinct paths ⇒ the automaton cannot discriminate; it must be skipped"
);
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_active_when_a_path_method_is_shared() {
let preds: Vec<Value> = (0..50)
.map(|i| json!([{"equals": {"path": "/shared", "body": {"user": {"id": i}}}}]))
.collect();
assert!(
body_field_active(&preds),
"stubs sharing a path are what the dimension prunes; it must stay active"
);
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_active_when_a_stub_has_no_path_anchor() {
let mut preds: Vec<Value> = (0..10)
.map(|i| json!([{"equals": {"path": format!("/p{i}"), "body": {"user": {"id": i}}}}]))
.collect();
preds.push(json!([{"equals": {"body": {"user": {"id": 999}}}}]));
assert!(
body_field_active(&preds),
"a path-unanchored body-field stub can share a path with any other; stay active"
);
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_inactive_when_a_shared_path_is_split_by_distinct_methods() {
let preds = vec![
json!([{"equals": {"path": "/shared", "method": "GET", "body": {"user": {"id": 1}}}}]),
json!([{"equals": {"path": "/shared", "method": "POST", "body": {"user": {"id": 2}}}}]),
];
assert!(
!body_field_active(&preds),
"distinct methods on one path cannot co-occur; the automaton cannot discriminate"
);
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_active_when_a_shared_path_stub_has_no_method_anchor() {
let preds = vec![
json!([{"equals": {"path": "/shared", "method": "GET", "body": {"user": {"id": 1}}}}]),
json!([{"equals": {"path": "/shared", "method": "POST", "body": {"user": {"id": 2}}}}]),
json!([{"equals": {"path": "/shared", "body": {"user": {"id": 3}}}}]),
];
assert!(
body_field_active(&preds),
"a method-unanchored stub co-occurs with every method on its path; stay active"
);
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_inactive_for_a_lone_stub_even_when_path_unanchored() {
let preds = vec![
json!([{"equals": {"body": {"user": {"id": 1}}}}]),
json!([{"equals": {"path": "/other"}}]),
];
assert!(
!body_field_active(&preds),
"one body-field stub has nothing to discriminate against; skip the automaton"
);
}
#[cfg(feature = "quamina-matching")]
#[test]
fn body_field_dimension_inactive_when_the_shared_path_sibling_has_no_body_predicate() {
let preds = vec![
json!([{"equals": {"path": "/shared", "body": {"user": {"id": 1}}}}]),
json!([{"equals": {"path": "/shared"}}]),
json!([{"equals": {"path": "/shared", "method": "PUT"}}]),
];
assert!(
!body_field_active(&preds),
"a lone body-field stub on a shared path still has no body-field sibling"
);
}
#[test]
fn distinct_path_body_field_corpus_matches_linear_oracle() {
const BODIES: &[Option<&str>] = &[
Some(r#"{"k":1}"#),
Some(r#"{"k":"1"}"#),
Some(r#"{"n":{"a":1}}"#),
Some(r#"{"k":1,"z":9}"#),
Some("ping"),
None,
];
let preds: Vec<Value> = (0..24)
.map(|i| match i % 4 {
0 => json!([{"equals": {"path": format!("/p{i}"), "body": {"k": 1}}}]),
1 => json!([{"equals": {"path": format!("/p{i}"), "body": {"n": {"a": 1}}}}]),
2 => {
json!([{"equals": {"path": format!("/p{i}"), "method": "POST", "body": {"k": 1}}}])
}
_ => json!([{"equals": {"path": format!("/p{i}")}}]),
})
.collect();
#[cfg(feature = "quamina-matching")]
assert!(
!body_field_active(&preds),
"this corpus must deactivate the dimension — that is the shape under test"
);
let imp = imposter(&preds);
let no_headers: HashMap<String, String> = HashMap::new();
for i in 0..24 {
for m in ["GET", "POST", "PUT"] {
for body in BODIES {
let p = format!("/p{i}");
let linear = idx(imp.find_matching_stub_linear(
m,
&p,
&no_headers,
None,
*body,
None,
None,
));
let indexed = idx(imp.find_matching_stub_with_client(
m,
&p,
&no_headers,
None,
*body,
None,
None,
));
assert_eq!(
indexed, linear,
"index diverged from linear oracle with the body-field dimension inactive: {m} {p} b={body:?}"
);
}
}
}
}
#[test]
fn stub_index_narrows_and_covers() {
let snap = snapshot(&corpus());
let cands = candidate_ids(&snap, "GET", "/exact");
assert!(!cands.contains(&2), "prefix /pre stub excluded for /exact");
assert!(
!cands.contains(&11),
"method+path /mp stub excluded for /exact"
);
assert!(
!cands.contains(&6),
"POST-only stub excluded for a GET request (method dimension, #707)"
);
assert!(
!cands.contains(&4),
"regex stub ^/re[0-9]+$ excluded for /exact (regex dimension, #709)"
);
assert!(
cands.contains(&0) && cands.contains(&1),
"exact stubs present"
);
for fb in [5, 7, 8, 9, 10, 12] {
assert!(
cands.contains(&fb),
"un-indexable stub {fb} must always be a candidate"
);
}
let mut sorted = cands.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(cands, sorted, "candidates must be ascending and deduped");
}
#[test]
fn method_dimension_collapses_candidates() {
let snap = snapshot(&[
json!([{"equals": {"method": "GET"}}]),
json!([{"equals": {"method": "POST"}}]),
json!([{"equals": {"method": "PUT"}}]),
json!([{"equals": {"method": "DELETE"}}]),
]);
for (i, m) in ["GET", "POST", "PUT", "DELETE"].iter().enumerate() {
let c = snap.candidates(m, "/anything");
assert_eq!(c.count(), 1, "{m}: exactly one candidate survives");
assert!(c.contains(i), "{m}: the {m}-anchored stub is the survivor");
}
assert_eq!(snap.candidates("PATCH", "/anything").count(), 0);
assert!(snap.candidates("get", "/anything").contains(0));
}
#[test]
fn ineligible_method_shapes_are_always_candidates() {
let snap = snapshot(&[
json!([{"equals": {"method": "GET"}}]), json!([{"or": [{"equals": {"method": "GET"}}, {"equals": {"method": "POST"}}]}]), json!([{"not": {"equals": {"method": "GET"}}}]), json!([{"and": [{"equals": {"method": "GET"}}, {"equals": {"path": "/x"}}]}]), json!([{"equals": {"method": "GET"}, "except": "X"}]), json!([{"equals": {"method": "GET"}, "caseSensitive": true}]), json!([{"matches": {"method": "^G"}}]), json!([{"equals": {"method": 7}}]),
json!([{"equals": {"method": "GET"}, "jsonpath": {"selector": "$.id"}}]), json!([]), ]);
let c = snap.candidates("PATCH", "/x");
assert!(!c.contains(0), "the indexable GET stub must be pruned");
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9] {
assert!(
c.contains(i),
"stub {i} is un-indexable → always a candidate"
);
}
}
#[test]
fn selector_scoped_path_predicates_are_always_candidates() {
let snap = snapshot(&[
json!([{"equals": {"path": "/a"}, "jsonpath": {"selector": "$.id"}}]), json!([{"equals": {"path": "/a"}, "except": "X"}]), json!([{"equals": {"path": "/a"}, "caseSensitive": true}]), json!([{"equals": {"path": "/a"}}]), ]);
let c = snap.candidates("GET", "/other");
for i in [0, 1, 2] {
assert!(
c.contains(i),
"stub {i} is un-indexable → always a candidate"
);
}
assert!(!c.contains(3), "the indexable /a stub must be pruned");
}
#[test]
fn non_ascii_case_folding_matches_the_evaluator() {
let imp = imposter(&[
json!([{"startsWith": {"path": "/ΟΣ"}}]), json!([{"contains": {"path": "ΑΣ"}}]), json!([{"equals": {"path": "/İ"}}]), ]);
let no_headers: HashMap<String, String> = HashMap::new();
for (m, p) in [
("GET", "/ΟΣΑ"),
("GET", "/ΟΣ"),
("GET", "/οσα"),
("GET", "/xΑΣy"),
("GET", "/İ"),
("GET", "/i̇"),
] {
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
}
}
#[test]
fn unnamed_methods_share_the_other_slot_soundly() {
let snap = snapshot(&[
json!([{"equals": {"method": "TRACE"}}]),
json!([{"equals": {"method": "CONNECT"}}]),
json!([{"equals": {"method": "GET"}}]),
]);
for m in ["TRACE", "CONNECT"] {
let c = snap.candidates(m, "/x");
assert!(c.contains(0) && c.contains(1), "{m}: Other-slot stubs kept");
assert!(!c.contains(2), "{m}: the GET stub is still pruned");
}
let imp = imposter(&[
json!([{"equals": {"method": "TRACE"}}]),
json!([{"equals": {"method": "CONNECT"}}]),
]);
let no_headers: HashMap<String, String> = HashMap::new();
assert_eq!(
idx(imp.find_matching_stub_with_client(
"CONNECT",
"/x",
&no_headers,
None,
None,
None,
None
)),
Some(1)
);
}
#[test]
fn snapshot_stubs_and_index_are_one_unit() {
let imp = imposter(&[json!([{"equals": {"path": "/a"}}])]);
for n in 1..6usize {
let snap = imp.snapshot();
assert_eq!(
snap.stubs().len(),
snap.index().len(),
"index spans exactly the stubs it was loaded with"
);
let c = snap.candidates("GET", "/a");
assert!(c.iter().all(|i| i < snap.stubs().len()));
drop(snap);
let stub = serde_json::from_value(json!({
"predicates": [{"equals": {"path": format!("/p{n}")}}],
"responses": [{ "is": { "statusCode": 200 } }]
}))
.expect("valid stub");
imp.add_stub(stub, None);
}
let snap = imp.snapshot();
assert_eq!(snap.stubs().len(), 6);
assert_eq!(snap.index().len(), 6);
}
#[test]
fn index_rebuilt_on_replace_stubs() {
let imp = imposter(&[json!([{"equals": {"path": "/old"}}])]);
let no_headers: HashMap<String, String> = HashMap::new();
assert_eq!(
idx(imp.find_matching_stub_with_client(
"GET",
"/old",
&no_headers,
None,
None,
None,
None
)),
Some(0)
);
let new_stub =
serde_json::from_value(json!({ "predicates": [{"equals": {"path": "/new"}}], "responses": [{ "is": { "statusCode": 200 } }] }))
.expect("valid stub");
imp.replace_stubs(vec![new_stub]);
assert_eq!(
idx(imp.find_matching_stub_with_client(
"GET",
"/old",
&no_headers,
None,
None,
None,
None
)),
None
);
assert_eq!(
idx(imp.find_matching_stub_with_client(
"GET",
"/new",
&no_headers,
None,
None,
None,
None
)),
Some(0)
);
}
#[test]
fn match_all_before_anchor_wins() {
let imp = imposter(&[
json!([]), json!([{"equals": {"path": "/a"}}]), ]);
let no_headers: HashMap<String, String> = HashMap::new();
assert_eq!(
idx(imp.find_matching_stub_linear("GET", "/a", &no_headers, None, None, None, None)),
Some(0)
);
assert_eq!(
idx(imp.find_matching_stub_with_client(
"GET",
"/a",
&no_headers,
None,
None,
None,
None
)),
Some(0),
"the earlier match-all stub must win over the anchored stub"
);
}
fn random_corpus(rng: &mut StdRng, n: usize) -> Vec<Value> {
const METHODS: &[&str] = &["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "TRACE"];
const SEGS: &[&str] = &["/a", "/b", "/api/v1", "/api/v2", "/x/y", "/mid"];
(0..n)
.map(|_| {
let seg = SEGS[rng.random_range(0..SEGS.len())];
let m = METHODS[rng.random_range(0..METHODS.len())];
match rng.random_range(0..36) {
0 => json!([{"equals": {"method": m, "path": seg}}]),
1 => json!([{"equals": {"method": m}}, {"equals": {"path": seg}}]),
2 => json!([{"equals": {"method": m}}]),
3 => json!([{"equals": {"path": seg}}]),
4 => json!([{"startsWith": {"path": seg}}]),
5 => json!([{"contains": {"path": seg}}]),
6 => json!([{"matches": {"path": format!("^{seg}[0-9]*$")}}]),
7 => json!([{"matches": {"path": format!("^{seg}$")}, "caseSensitive": true}]),
8 => json!([{"matches": {"path": format!("(?i)^{seg}[0-9]*$")}}]),
9 => json!([{"matches": {"path": format!("(?-i)^{seg}[0-9]*$")}}]),
10 => json!([{"matches": {"path": "[0-9]+"}}]),
11 => json!([{"matches": {"path": format!("^{seg}$"), "except": "X"}}]),
12 => json!([{"matches": {"path": format!("^{seg}$")}, "jsonpath": {"selector": "$.id"}}]),
13 => json!([{"matches": {"path": 7}}]),
14 => json!([{"matches": {"path": "^/unclosed["}}]),
15 => json!([{"or": [{"equals": {"method": m}}, {"matches": {"path": format!("^{seg}$")}}]}]),
16 => json!([{"not": {"equals": {"path": seg}}}]),
17 => json!([{"equals": {"method": m}, "caseSensitive": true}]),
18 => json!([{"equals": {"method": m}, "except": "X"}]),
20 => json!([{"endsWith": {"path": seg}}]),
21 => json!([{"startsWith": {"path": seg}, "caseSensitive": true}]),
22 => json!([{"contains": {"path": seg}, "caseSensitive": true}]),
23 => json!([{"endsWith": {"path": seg}, "caseSensitive": true}]),
24 => json!([{"contains": {"path": ""}}]),
25 => json!([{"startsWith": {"path": ""}}]),
26 => json!([{"contains": {"path": "/"}}]),
27 => json!([{"startsWith": {"path": &seg[..2.min(seg.len())]}}]),
19 => json!([{"matches": {"path": format!("^{seg}")}}]),
28 => json!([{"deepEquals": {"body": {"k": 1}}}]),
29 => json!([{"deepEquals": {"body": [1, 2]}}]),
30 => json!([{"deepEquals": {"body": {"n": {"a": 1}}}}]),
31 => json!([{"deepEquals": {"body": {"k": 1}}, "caseSensitive": true}]),
32 => json!([{"equals": {"body": {"k": 1}}}]),
33 => json!([{"equals": {"body": {"n": {"a": 1}}}}]),
34 => json!([{"equals": {"body": {"k": 1}}, "caseSensitive": true}]),
35 => json!([{"equals": {"body": {"j": "{\"x\":1}"}}}]),
_ => json!([]),
}
})
.collect()
}
#[test]
fn differential_index_matches_linear_oracle() {
const METHODS: &[&str] = &[
"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "TRACE", "get",
];
const PATHS: &[&str] = &[
"/a",
"/b",
"/A",
"/api/v1",
"/api/v2",
"/api/v1/deep",
"/x/y",
"/x-mid-y",
"/mid",
"/zzz",
"/a0",
"/GETX",
];
let mut rng = StdRng::seed_from_u64(0x0707_5EED);
let no_headers: HashMap<String, String> = HashMap::new();
for corpus_n in 0..8 {
let imp = imposter(&random_corpus(&mut rng, 40));
for _ in 0..1250 {
let m = METHODS[rng.random_range(0..METHODS.len())];
let p = PATHS[rng.random_range(0..PATHS.len())];
let body = match rng.random_range(0..9) {
0 => Some("ping"),
1 => Some(r#"{"k":1}"#),
2 => Some(r#"{"k":"1"}"#),
3 => Some(r#"[1,2]"#),
4 => Some(r#"{"n":{"a":1}}"#),
5 => Some(r#"{"j":"{\"x\":1}"}"#),
6 => Some(r#"{"k":1,"z":9}"#),
7 => None,
_ => Some(r#"[2,1]"#),
};
let query = if rng.random_bool(0.25) {
Some("a=1")
} else {
None
};
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, query, body, None, None));
let indexed = idx(imp.find_matching_stub_with_client(
m,
p,
&no_headers,
query,
body,
None,
None,
));
assert_eq!(
indexed, linear,
"index diverged from linear oracle: corpus {corpus_n}, {m} {p} q={query:?} b={body:?}"
);
}
}
}
#[test]
fn literal_dimension_collapses_candidates() {
let mut preds: Vec<Value> = Vec::new();
for i in 0..200 {
preds.push(json!([{"startsWith": {"path": format!("/pre{i}/")}}]));
preds.push(json!([{"contains": {"path": format!("~mid{i}~")}}]));
preds.push(json!([{"endsWith": {"path": format!("/end{i}")}}]));
}
let snap = snapshot(&preds);
let c = snap.candidates("GET", "/pre199/detail");
assert_eq!(c.count(), 1, "one startsWith stub survives");
assert!(c.contains(199 * 3));
let c = snap.candidates("GET", "/x~mid150~y");
assert_eq!(c.count(), 1, "one contains stub survives");
assert!(c.contains(150 * 3 + 1));
let c = snap.candidates("GET", "/whatever/end42");
assert_eq!(c.count(), 1, "one endsWith stub survives");
assert!(c.contains(42 * 3 + 2));
assert_eq!(snap.candidates("GET", "/nothing").count(), 0);
}
#[test]
fn overlapping_literals_are_all_candidates() {
let snap = snapshot(&[
json!([{"startsWith": {"path": "/api"}}]), json!([{"startsWith": {"path": "/api/v1"}}]), json!([{"contains": {"path": "api"}}]), json!([{"contains": {"path": "api/v1/x"}}]), json!([{"endsWith": {"path": "/x"}}]), json!([{"endsWith": {"path": "v1/x"}}]), json!([{"contains": {"path": "/"}}]), ]);
let c = snap.candidates("GET", "/api/v1/x");
for i in 0..7 {
assert!(
c.contains(i),
"stub {i}'s literal matches /api/v1/x and must survive — every overlapping \
pattern must be reported"
);
}
}
#[test]
fn empty_literal_always_matches() {
let imp = imposter(&[
json!([{"contains": {"path": ""}}]), json!([{"startsWith": {"path": ""}}]), json!([{"endsWith": {"path": ""}}]), ]);
let no_headers: HashMap<String, String> = HashMap::new();
for (m, p) in [("GET", "/anything"), ("GET", "/"), ("POST", "/x/y/z")] {
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
assert_eq!(
linear,
Some(0),
"the empty contains stub matches everything"
);
}
let snap = snapshot(&[
json!([{"contains": {"path": ""}}]),
json!([{"startsWith": {"path": ""}}]),
json!([{"endsWith": {"path": ""}}]),
]);
let c = snap.candidates("GET", "/zzz");
for i in 0..3 {
assert!(
c.contains(i),
"empty-literal stub {i} must always be a candidate"
);
}
}
#[test]
fn literal_case_semantics_match_the_evaluator() {
let imp = imposter(&[
json!([{"startsWith": {"path": "/Pre"}}]), json!([{"startsWith": {"path": "/Pre2"}, "caseSensitive": true}]), json!([{"contains": {"path": "MiD"}}]), json!([{"contains": {"path": "MiD2"}, "caseSensitive": true}]), json!([{"endsWith": {"path": "/End"}}]), json!([{"endsWith": {"path": "/End2"}, "caseSensitive": true}]), json!([{"startsWith": {"path": "/ΟΣ"}}]), json!([{"contains": {"path": "ΑΣ"}}]), ]);
let no_headers: HashMap<String, String> = HashMap::new();
for (m, p) in [
("GET", "/pre/x"),
("GET", "/PRE/x"),
("GET", "/Pre2/x"),
("GET", "/pre2/x"),
("GET", "/a-mid-b"),
("GET", "/a-MiD-b"),
("GET", "/a-MiD2-b"),
("GET", "/a-mid2-b"),
("GET", "/x/end"),
("GET", "/x/END"),
("GET", "/x/End2"),
("GET", "/x/end2"),
("GET", "/ΟΣΑ"),
("GET", "/οσα"),
("GET", "/xΑΣy"),
] {
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
}
}
#[test]
fn ineligible_literal_shapes_are_always_candidates() {
let snap = snapshot(&[
json!([{"startsWith": {"path": "/idx"}}]), json!([{"startsWith": {"path": "/x"}, "except": "Y"}]), json!([{"contains": {"path": "/x"}, "jsonpath": {"selector": "$.id"}}]), json!([{"or": [{"startsWith": {"path": "/x"}}, {"equals": {"path": "/y"}}]}]), json!([{"not": {"contains": {"path": "/x"}}}]), json!([{"and": [{"endsWith": {"path": "/x"}}, {"equals": {"method": "GET"}}]}]), json!([{"contains": {"body": "ping"}}]), json!([{"startsWith": {"path": 7}}]), ]);
let c = snap.candidates("GET", "/other");
assert!(!c.contains(0), "the indexable /idx stub must be pruned");
for i in 1..8 {
assert!(
c.contains(i),
"stub {i} is un-indexable → must always be a candidate"
);
}
}
#[test]
fn regex_dimension_collapses_candidates() {
let preds: Vec<Value> = (0..100)
.map(|i| json!([{"matches": {"path": format!("^/api/endpoint{i}$")}}]))
.collect();
let snap = snapshot(&preds);
for target in [0usize, 42, 99] {
let c = snap.candidates("GET", &format!("/api/endpoint{target}"));
assert_eq!(
c.count(),
1,
"exactly one regex stub survives for /api/endpoint{target}"
);
assert!(
c.contains(target),
"the {target}-anchored stub is the survivor"
);
}
assert_eq!(snap.candidates("GET", "/nothing").count(), 0);
}
#[test]
fn regex_scratch_reuse_is_correct() {
let big: Vec<Value> = (0..100)
.map(|i| json!([{"matches": {"path": format!("^/e{i}$")}}]))
.collect();
let big_snap = snapshot(&big);
assert_eq!(candidate_ids(&big_snap, "GET", "/e42"), vec![42]);
let small = snapshot(&[
json!([{"matches": {"path": "^/only$"}}]),
json!([{"matches": {"path": "^/other$"}}]),
]);
assert_eq!(candidate_ids(&small, "GET", "/only"), vec![0]);
assert!(candidate_ids(&small, "GET", "/nomatch").is_empty());
let mixed = snapshot(&[
json!([{"matches": {"path": "^/mix$"}}]), json!([{"matches": {"path": "^/MIX$"}, "caseSensitive": true}]), ]);
assert_eq!(candidate_ids(&mixed, "GET", "/mix"), vec![0]);
assert_eq!(candidate_ids(&mixed, "GET", "/MIX"), vec![0, 1]);
assert_eq!(candidate_ids(&big_snap, "GET", "/e7"), vec![7]);
}
#[test]
fn path_dimension_fast_path_matches_regardless_of_case() {
let snap = snapshot(&[
json!([{"equals": {"path": "/users"}}]), json!([{"equals": {"path": "/Admin"}}]), ]);
assert_eq!(candidate_ids(&snap, "GET", "/users"), vec![0]);
assert_eq!(candidate_ids(&snap, "GET", "/ADMIN"), vec![1]);
assert_eq!(candidate_ids(&snap, "GET", "/admin"), vec![1]);
assert!(candidate_ids(&snap, "GET", "/nope").is_empty());
}
#[test]
fn overlapping_patterns_are_all_candidates() {
let snap = snapshot(&[
json!([{"matches": {"path": "^/api"}}]), json!([{"matches": {"path": "^/api/v1$"}}]), json!([{"matches": {"path": "[0-9]+"}}]), json!([{"matches": {"path": "^/a[0-9]*$"}}]), ]);
let c = snap.candidates("GET", "/api/v1");
assert!(
c.contains(0) && c.contains(1),
"both overlapping /api patterns must survive (earlier masking later)"
);
let c = snap.candidates("GET", "/a0");
assert!(
c.contains(2) && c.contains(3),
"both overlapping /a0 patterns must survive (later masking earlier)"
);
let imp = imposter(&[
json!([{"matches": {"path": "^/api"}}, {"equals": {"method": "POST"}}]),
json!([{"matches": {"path": "^/api/v1$"}}]),
]);
let no_headers: HashMap<String, String> = HashMap::new();
assert_eq!(
idx(imp.find_matching_stub_with_client(
"GET",
"/api/v1",
&no_headers,
None,
None,
None,
None
)),
Some(1),
"the GET must fall through the POST-gated stub to the stub that matches"
);
}
#[test]
fn regex_dimension_case_semantics_match_the_evaluator() {
let imp = imposter(&[
json!([{"matches": {"path": "^/Case$"}}]), json!([{"matches": {"path": "^/Case2$"}, "caseSensitive": true}]), json!([{"matches": {"path": "(?i)^/inline$"}, "caseSensitive": true}]), json!([{"matches": {"path": "(?-i)^/noinline$"}}]), json!([{"matches": {"path": "^/ünï$"}}]), json!([{"matches": {"path": "^/STRASSE$"}}]), ]);
let no_headers: HashMap<String, String> = HashMap::new();
for (m, p) in [
("GET", "/case"),
("GET", "/Case"),
("GET", "/CASE"),
("GET", "/case2"),
("GET", "/Case2"),
("GET", "/inline"),
("GET", "/INLINE"),
("GET", "/noinline"),
("GET", "/NOINLINE"),
("GET", "/ünï"),
("GET", "/ÜNÏ"),
("GET", "/strasse"),
("GET", "/STRASSE"),
("GET", "/straße"),
] {
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
}
}
#[test]
fn ineligible_regex_shapes_are_always_candidates() {
let snap = snapshot(&[
json!([{"matches": {"path": "^/idx$"}}]), json!([{"matches": {"path": "^/x$"}, "except": "Y"}]), json!([{"matches": {"path": "^/x$"}, "jsonpath": {"selector": "$.id"}}]), json!([{"or": [{"matches": {"path": "^/x$"}}, {"equals": {"path": "/y"}}]}]), json!([{"not": {"matches": {"path": "^/x$"}}}]), json!([{"and": [{"matches": {"path": "^/x$"}}, {"equals": {"method": "GET"}}]}]), json!([{"matches": {"body": "^ping$"}}]), json!([{"matches": {"path": 7}}]), json!([{"matches": {"path": "^/unclosed["}}]), ]);
let c = snap.candidates("GET", "/other");
assert!(!c.contains(0), "the indexable /idx stub must be pruned");
for i in [1, 2, 3, 4, 5, 6, 7, 8] {
assert!(
c.contains(i),
"stub {i} is un-indexable → must always be a candidate"
);
}
}
#[test]
fn invalid_pattern_does_not_disable_the_dimension() {
let imp = imposter(&[
json!([{"matches": {"path": "^/good1$"}}]),
json!([{"matches": {"path": "^/unclosed["}}]), json!([{"matches": {"path": "^/good2$"}}]),
]);
let no_headers: HashMap<String, String> = HashMap::new();
for (m, p) in [
("GET", "/good1"),
("GET", "/good2"),
("GET", "/unclosed["),
("GET", "/other"),
] {
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
}
let snap = snapshot(&[
json!([{"matches": {"path": "^/good1$"}}]),
json!([{"matches": {"path": "^/unclosed["}}]),
json!([{"matches": {"path": "^/good2$"}}]),
]);
let c = snap.candidates("GET", "/good1");
assert!(c.contains(0), "the matching stub survives");
assert!(
!c.contains(2),
"the non-matching valid stub is still pruned"
);
assert!(c.contains(1), "the invalid-pattern stub stays a candidate");
}
#[test]
fn oversized_regex_set_falls_back_to_always_bits() {
let huge = format!("^/{}$", r"\p{L}{5000}".repeat(4));
let imp = imposter(&[
json!([{"matches": {"path": huge}}]),
json!([{"matches": {"path": "^/small$"}}]),
]);
let no_headers: HashMap<String, String> = HashMap::new();
for (m, p) in [("GET", "/small"), ("GET", "/abc"), ("GET", "/other")] {
let linear =
idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
let indexed =
idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
}
let snap = snapshot(&[
json!([{"matches": {"path": huge}}]),
json!([{"matches": {"path": "^/small$"}}]),
]);
let c = snap.candidates("GET", "/nothing-matches");
assert!(
c.contains(0),
"the oversized-pattern stub must stay a candidate"
);
assert!(!c.contains(1), "the small-pattern stub is still pruned");
}
#[traced_test]
#[test]
fn rejected_pattern_warns_at_build_naming_the_stub() {
let huge = format!("^/{}$", r"\p{L}{5000}".repeat(4));
let _snap = snapshot(&[
json!([{"matches": {"path": "^/small$"}}]),
json!([{"matches": {"path": huge}}]),
]);
assert!(
logs_contain("regex dimension: pattern rejected by the multi-pattern build"),
"the rejected pattern must be warned about at build time"
);
assert!(
logs_contain("stub=1"),
"the warn must name which stub lost its index"
);
}
#[test]
fn has_scenario_gate_detects_required_scenario_state() {
let build = |v: Value| {
let states: Vec<Arc<StubState>> = v
.as_array()
.expect("array")
.iter()
.map(|s| {
Arc::new(StubState::new(
serde_json::from_value(s.clone()).expect("stub"),
))
})
.collect();
StubSnapshot::build(states)
};
let ungated = build(json!([
{ "predicates": [{"equals": {"path": "/a"}}], "responses": [{"is": {"statusCode": 200}}] }
]));
assert!(!ungated.has_scenario_gate());
let gated = build(json!([
{
"predicates": [{"equals": {"path": "/a"}}],
"scenarioName": "sc",
"requiredScenarioState": "started",
"responses": [{"is": {"statusCode": 200}}]
}
]));
assert!(gated.has_scenario_gate());
}
#[test]
fn has_inject_detects_top_level_and_nested() {
let scriptless = StubSnapshot::build(stub_states(&[
json!([{"equals": {"path": "/a"}}]),
json!([{"and": [{"equals": {"path": "/b"}}, {"exists": {"query": {"q": true}}}]}]),
]));
assert!(!scriptless.has_inject());
let top_level = StubSnapshot::build(stub_states(&[
json!([{"equals": {"path": "/a"}}]),
json!([{"inject": "function (config) { return true; }"}]),
]));
assert!(top_level.has_inject());
let under_and = StubSnapshot::build(stub_states(&[json!([
{"and": [{"equals": {"path": "/a"}}, {"inject": "function (config) { return true; }"}]}
])]));
assert!(under_and.has_inject());
let under_not_in_or = StubSnapshot::build(stub_states(&[json!([
{"or": [{"equals": {"path": "/a"}}, {"not": {"inject": "function (config) { return true; }"}}]}
])]));
assert!(under_not_in_or.has_inject());
}
fn deep_body(expected: Value) -> Value {
json!([{"deepEquals": {"body": expected}}])
}
#[test]
fn body_dimension_collapses_candidates() {
let preds: Vec<Value> = (0..500)
.map(|i| deep_body(json!({"id": i, "kind": "order"})))
.collect();
let snap = snapshot(&preds);
let target = 437usize;
let ids = candidate_ids_body(&snap, "POST", "/x", &json!({"id": target, "kind": "order"}));
assert_eq!(ids.len(), 1, "collapses to a single candidate, got {ids:?}");
assert_eq!(ids, vec![target]);
assert!(
candidate_ids_body(&snap, "POST", "/x", &json!({"id": 9999, "kind": "order"}))
.is_empty()
);
}
#[test]
fn body_dimension_matches_across_coercion_key_order_and_case() {
let snap = snapshot(&[
deep_body(json!({"a": 1, "b": "x"})), deep_body(json!({"a": 2})), ]);
let ids = candidate_ids_body(&snap, "POST", "/p", &json!({"B": "X", "a": "1"}));
assert_eq!(ids, vec![0]);
}
#[test]
fn body_dimension_ineligible_stubs_are_never_pruned() {
let snap = snapshot(&[
json!([{"deepEquals": {"body": {"a": 1}}, "caseSensitive": true}]), json!([{"deepEquals": {"body": {"a": 1}}, "keyCaseSensitive": true}]), json!([{"deepEquals": {"body": {"a": 1}}, "jsonpath": {"selector": "$.x"}}]), json!([{"deepEquals": {"body": "hello"}}]), json!([{"deepEquals": {"body": {"a": "{\"k\":1}"}}}]), json!([{"deepEquals": {"body": {"a": 1}}, "except": "x"}]), deep_body(json!({"eligible": true})), ]);
let hit = candidate_ids_body(&snap, "POST", "/p", &json!({"eligible": true}));
assert_eq!(hit, vec![0, 1, 2, 3, 4, 5, 6]);
let miss = candidate_ids_body(&snap, "POST", "/p", &json!({"zzz": 0}));
assert_eq!(miss, vec![0, 1, 2, 3, 4, 5]);
}
#[test]
fn body_dimension_keeps_every_stub_a_reordered_body_matches() {
let orders = [
json!({"t": ["a", "b", "c"]}),
json!({"t": ["c", "b", "a"]}),
json!({"t": ["b", "c", "a"]}),
json!({"items": [{"id": 1}, {"id": 2}]}),
json!({"items": [{"id": 2}, {"id": 1}]}),
json!({"t": ["a", "b"]}), ];
let preds: Vec<Value> = orders.iter().cloned().map(deep_body).collect();
let snap = snapshot(&preds);
assert_eq!(
candidate_ids_body(&snap, "POST", "/p", &json!({"t": ["c", "a", "b"]})),
vec![0, 1, 2]
);
assert_eq!(
candidate_ids_body(
&snap,
"POST",
"/p",
&json!({"items": [{"id": 2}, {"id": 1}]})
),
vec![3, 4]
);
let imp = imposter(&preds);
let no_headers: HashMap<String, String> = HashMap::new();
let body = Some(r#"{"t":["b","a","c"]}"#);
let linear =
idx(imp.find_matching_stub_linear("POST", "/p", &no_headers, None, body, None, None));
let indexed = idx(imp.find_matching_stub_with_client(
"POST",
"/p",
&no_headers,
None,
body,
None,
None,
));
assert_eq!((linear, indexed), (Some(0), Some(0)));
}
#[test]
fn body_dimension_non_json_body_excludes_indexed_stubs() {
let snap = snapshot(&[
deep_body(json!({"a": 1})), json!([{"equals": {"path": "/p"}}]), ]);
assert_eq!(candidate_ids(&snap, "GET", "/p"), vec![1]);
}
#[test]
fn body_dimension_json_in_string_request_widens() {
let snap = snapshot(&[
deep_body(json!({"a": {"b": 1}})), deep_body(json!({"z": 9})), ]);
let ids = candidate_ids_body(&snap, "POST", "/p", &json!({"a": "{\"b\":1}"}));
assert_eq!(
ids,
vec![0, 1],
"a JSON-ish string leaf disables pruning for the dimension"
);
}
}