use crate::imposter::Gate;
use crate::imposter::StubResponse;
use crate::imposter::{ImposterConfig, Stub};
use crate::imposter::{Predicate, PredicateOperation};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
pub const MAX_STUB_WARNINGS: usize = 100;
const SHADOW_HEURISTIC_MAX_STUBS: usize = 200;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StubWarning {
pub warning_type: WarningType,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub stub_index: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stub_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shadowed_by_index: Option<usize>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum WarningType {
DuplicateId,
ExactDuplicate,
PotentiallyShadowed,
CatchAll,
CatchAllNotLast,
Truncated,
StateOpsNeverRuns,
ConditionalNeverRuns,
ConfigKeyIgnored,
}
fn ignored_rift_shape(response: &StubResponse) -> Option<&'static str> {
match response {
StubResponse::Proxy {
ignored_rift: Some(_),
..
} => Some("proxy"),
StubResponse::Inject {
ignored_rift: Some(_),
..
} => Some("inject"),
StubResponse::Fault {
ignored_rift: Some(_),
..
} => Some("fault"),
_ => None,
}
}
fn ignored_script_shape(response: &StubResponse) -> Option<&'static str> {
match response {
StubResponse::Is {
rift: Some(rift), ..
} if rift.script.is_some() => Some("is"),
_ => None,
}
}
fn ignored_behaviors_shape(response: &StubResponse) -> Option<&'static str> {
let (shape, block) = match response {
StubResponse::Fault {
ignored_behaviors: Some(block),
..
} => ("fault", block),
StubResponse::RiftScript {
ignored_behaviors: Some(block),
..
} => ("_rift", block),
_ => return None,
};
let sets_more_than_repeat = block.as_array().is_some_and(|program| {
program
.iter()
.filter_map(serde_json::Value::as_object)
.any(|element| element.keys().any(|k| k != "repeat"))
});
sets_more_than_repeat.then_some(shape)
}
fn stubs_with_shape(
stubs: &[Stub],
shape: &str,
shape_of: fn(&StubResponse) -> Option<&'static str>,
) -> Option<(usize, String)> {
let indices: Vec<usize> = stubs
.iter()
.enumerate()
.filter(|(_, stub)| stub.responses.iter().any(|r| shape_of(r) == Some(shape)))
.map(|(index, _)| index)
.collect();
listed_stubs(&indices)
}
fn listed_stubs(indices: &[usize]) -> Option<(usize, String)> {
const LISTED: usize = 10;
let &first = indices.first()?;
let mut listed = indices
.iter()
.take(LISTED)
.map(usize::to_string)
.collect::<Vec<_>>()
.join(", ");
if indices.len() > LISTED {
listed.push_str(&format!(" and {} more", indices.len() - LISTED));
}
Some((first, listed))
}
pub fn ignored_config_keys(config: &ImposterConfig, stubs: &[Stub]) -> Vec<StubWarning> {
let imposter_level = |message: &str| StubWarning {
warning_type: WarningType::ConfigKeyIgnored,
message: message.to_owned(),
stub_index: None,
stub_id: None,
shadowed_by_index: None,
};
let mut warnings = Vec::new();
let rift = config.rift.as_ref();
if rift.is_some_and(|r| r.metrics.is_some()) {
warnings.push(imposter_level(
"`_rift.metrics` has no effect: metrics are process-wide, served on --metrics-port \
(default 9090), and not configurable per imposter",
));
}
if rift.is_some_and(|r| r.proxy.is_some()) {
warnings.push(imposter_level(
"`_rift.proxy` has no effect: a proxy response's upstream is its own `proxy.to`, and \
connection pooling is not configurable per imposter",
));
}
if config.record_matches {
warnings.push(imposter_level(
"`recordMatches` has no effect: this engine does not record per-stub `matches`; use \
`recordRequests` and GET /imposters/:port to see the requests",
));
}
if config.ciphers.is_some() && config.protocol.eq_ignore_ascii_case("https") {
warnings.push(imposter_level(
"`ciphers` is stored and printed but not applied: the TLS listener uses rustls' \
default suites (Mountebank passes it to OpenSSL as a cipher list)",
));
}
if config
.default_response
.as_ref()
.is_some_and(|d| d.proxy.is_some())
{
warnings.push(imposter_level(
"`defaultResponse.proxy` has no effect: an unmatched request is answered from \
`defaultResponse`'s statusCode/headers/body (Mountebank does not proxy from it either); \
use `defaultForward` to forward unmatched requests",
));
}
let per_shape = |first: usize, message: String| StubWarning {
warning_type: WarningType::ConfigKeyIgnored,
message,
stub_index: Some(first),
stub_id: stubs[first].id.clone(),
shadowed_by_index: None,
};
for shape in ["proxy", "inject", "fault"] {
if let Some((first, listed)) = stubs_with_shape(stubs, shape, ignored_rift_shape) {
warnings.push(per_shape(
first,
format!(
"`_rift` on a `{shape}` response has no effect: no `_rift` feature applies to \
a `{shape}` response (stubs {listed})"
),
));
}
}
if let Some((first, listed)) = stubs_with_shape(stubs, "is", ignored_script_shape) {
warnings.push(per_shape(
first,
format!(
"`_rift.script` beside an `is` response has no effect: a script is a response type \
of its own, and the `is` is served (stubs {listed})"
),
));
}
for (shape, noun, why) in [
(
"fault",
"a `fault` response",
"the rest do not apply to a fault, as in Mountebank",
),
(
"_rift",
"a `_rift`-only response",
"the rest do not apply to a script response",
),
] {
if let Some((first, listed)) = stubs_with_shape(stubs, shape, ignored_behaviors_shape) {
warnings.push(per_shape(
first,
format!(
"A behaviors block on {noun} has no effect except `repeat`: {why} \
(stubs {listed})"
),
));
}
}
if let Some(warning) = unread_generator_keys_warning(stubs) {
warnings.push(warning);
}
if let Some(warning) = unknown_fault_warning(stubs) {
warnings.push(warning);
}
warnings
}
fn unknown_fault_warning(stubs: &[Stub]) -> Option<StubWarning> {
let mut names: Vec<&str> = Vec::new();
let mut indices: Vec<usize> = Vec::new();
for (index, stub) in stubs.iter().enumerate() {
let mut unknown_here = false;
for response in &stub.responses {
if let StubResponse::Fault { fault, .. } = response
&& crate::imposter::fault_io::TcpFaultKind::parse(fault).is_none()
{
unknown_here = true;
if !names.contains(&fault.as_str()) {
names.push(fault);
}
}
}
if unknown_here {
indices.push(index);
}
}
let (first, listed) = listed_stubs(&indices)?;
let names = names
.iter()
.map(|name| format!("`{name}`"))
.collect::<Vec<_>>()
.join(", ");
Some(StubWarning {
warning_type: WarningType::ConfigKeyIgnored,
message: format!(
"`fault` {names} is not a fault Rift knows: it is ignored and the response is served as \
an empty response completed by `defaultResponse`, as in Mountebank (stubs {listed})"
),
stub_index: Some(first),
stub_id: stubs[first].id.clone(),
shadowed_by_index: None,
})
}
fn unread_generator_keys_warning(stubs: &[Stub]) -> Option<StubWarning> {
let mut keys: Vec<String> = Vec::new();
let mut indices: Vec<usize> = Vec::new();
for (index, stub) in stubs.iter().enumerate() {
let unread: Vec<String> = stub
.responses
.iter()
.filter_map(|response| match response {
StubResponse::Proxy { proxy, .. } => Some(&proxy.predicate_generators),
_ => None,
})
.flatten()
.flat_map(crate::imposter::unread_generator_keys)
.collect();
if !unread.is_empty() {
indices.push(index);
keys.extend(unread);
}
}
let (first, listed) = listed_stubs(&indices)?;
keys.sort_unstable();
keys.dedup();
Some(StubWarning {
warning_type: WarningType::ConfigKeyIgnored,
message: format!(
"proxy `predicateGenerators` key(s) {} have no effect: this engine reads inject, \
matches, caseSensitive, predicateOperator, except, jsonpath, xpath and ignore \
(stubs {listed})",
keys.iter()
.map(|key| format!("`{key}`"))
.collect::<Vec<_>>()
.join(", ")
),
stub_index: Some(first),
stub_id: stubs[first].id.clone(),
shadowed_by_index: None,
})
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct StubAnalysisResult {
pub warnings: Vec<StubWarning>,
}
impl StubAnalysisResult {
pub fn new() -> Self {
Self { warnings: vec![] }
}
pub fn has_warnings(&self) -> bool {
!self.warnings.is_empty()
}
pub fn add_warning(&mut self, warning: StubWarning) {
self.warnings.push(warning);
}
}
pub fn analyze_stubs(stubs: &[Stub]) -> StubAnalysisResult {
let mut result = StubAnalysisResult::new();
let mut total: usize = 0;
let mut push = |warnings: &mut Vec<StubWarning>, w: StubWarning| {
total += 1;
if warnings.len() < MAX_STUB_WARNINGS {
warnings.push(w);
}
};
let mut seen_ids: HashMap<String, usize> = HashMap::new();
let mut seen_predicates: HashMap<String, Vec<(Gate<'_>, usize)>> = HashMap::new();
let mut first_catch_all: Option<usize> = None;
let mut first_ungated_catch_all: Option<usize> = None;
let mut first_catch_all_by_gate: HashMap<Gate<'_>, usize> = HashMap::new();
let run_shadow_heuristic = stubs.len() <= SHADOW_HEURISTIC_MAX_STUBS;
for (index, stub) in stubs.iter().enumerate() {
if let Some(id) = &stub.id {
if let Some(&existing_index) = seen_ids.get(id) {
push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::DuplicateId,
message: format!(
"Stub at index {index} has duplicate ID '{id}' (same as stub at index {existing_index})"
),
stub_index: Some(index),
stub_id: Some(id.clone()),
shadowed_by_index: Some(existing_index),
},
);
} else {
seen_ids.insert(id.clone(), index);
}
}
if stub.predicates.is_empty() {
if first_catch_all.is_none() {
first_catch_all = Some(index);
}
let gate = stub.gate();
if gate.is_open() {
first_ungated_catch_all.get_or_insert(index);
} else {
first_catch_all_by_gate.entry(gate).or_insert(index);
}
push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::CatchAll,
message: format!(
"Stub at index {index} has empty predicates and will match ALL requests"
),
stub_index: Some(index),
stub_id: stub.id.clone(),
shadowed_by_index: None,
},
);
}
for response in &stub.responses {
if let StubResponse::RiftScript { rift, .. } = response
&& rift.script.is_some()
&& !rift.state_ops.is_empty()
{
push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::StateOpsNeverRuns,
message: format!(
"Stub at index {index} has _rift.stateOps on a script response \
(`_rift.script`); stateOps only runs after an `is` response is \
rendered, so these operations never execute"
),
stub_index: Some(index),
stub_id: stub.id.clone(),
shadowed_by_index: None,
},
);
}
}
let excluded_method = non_get_head_method(&stub.predicates);
for response in &stub.responses {
let message = match response {
StubResponse::RiftScript { rift, .. }
if rift.script.is_some() && declares_conditional(rift) =>
{
format!(
"Stub at index {index} has _rift.conditional on a script response \
(`_rift.script`); conditional GET applies only to an `is` response \
(move it to an `is`, or drop it)"
)
}
StubResponse::Is {
rift: Some(rift), ..
}
| StubResponse::RiftScript { rift, .. }
if declares_conditional(rift) =>
{
let Some(method) = excluded_method else {
continue;
};
format!(
"Stub at index {index} has _rift.conditional but its method predicate \
({method}) excludes GET and HEAD, so it never answers 304"
)
}
_ => continue,
};
push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::ConditionalNeverRuns,
message,
stub_index: Some(index),
stub_id: stub.id.clone(),
shadowed_by_index: None,
},
);
}
let key = predicate_key(&stub.predicates);
let gate = stub.gate();
let bucket = seen_predicates.entry(key).or_default();
match bucket.iter().find(|(earlier, _)| earlier.covers(&gate)) {
Some(&(_, first_index)) => push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::ExactDuplicate,
message: format!(
"Stub at index {index} has identical predicates to stub at index {first_index} and will never match"
),
stub_index: Some(index),
stub_id: stub.id.clone(),
shadowed_by_index: Some(first_index),
},
),
None => bucket.push((gate, index)),
}
if !stub.predicates.is_empty() {
let catch_all = first_ungated_catch_all
.or_else(|| first_catch_all_by_gate.get(&stub.gate()).copied());
if let Some(catch_all_index) = catch_all {
push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::PotentiallyShadowed,
message: format!(
"Stub at index {index} may be shadowed by catch-all stub at index {catch_all_index}"
),
stub_index: Some(index),
stub_id: stub.id.clone(),
shadowed_by_index: Some(catch_all_index),
},
);
}
if run_shadow_heuristic {
for (earlier_index, earlier_stub) in stubs[..index].iter().enumerate() {
if !earlier_stub.predicates.is_empty()
&& earlier_stub.gate().covers(&stub.gate())
&& is_subset_predicates(&stub.predicates, &earlier_stub.predicates)
{
push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::PotentiallyShadowed,
message: format!(
"Stub at index {index} may be partially shadowed by stub at index {earlier_index} which has overlapping predicates"
),
stub_index: Some(index),
stub_id: stub.id.clone(),
shadowed_by_index: Some(earlier_index),
},
);
}
}
}
}
}
if let Some(catch_all_idx) = first_catch_all
&& catch_all_idx < stubs.len() - 1
{
push(
&mut result.warnings,
StubWarning {
warning_type: WarningType::CatchAllNotLast,
message: format!(
"Catch-all stub at index {} will shadow {} stub(s) after it",
catch_all_idx,
stubs.len() - catch_all_idx - 1
),
stub_index: Some(catch_all_idx),
stub_id: stubs[catch_all_idx].id.clone(),
shadowed_by_index: None,
},
);
}
let retained = result.warnings.len();
if total > retained {
result.warnings.push(StubWarning {
warning_type: WarningType::Truncated,
message: format!(
"{} additional stub warning(s) suppressed (showing first {retained})",
total - retained
),
stub_index: None,
stub_id: None,
shadowed_by_index: None,
});
}
result
}
fn declares_conditional(rift: &crate::imposter::RiftResponseExtension) -> bool {
!matches!(
rift.conditional,
None | Some(crate::imposter::ConditionalGet::Enabled(false))
)
}
fn non_get_head_method(predicates: &[Predicate]) -> Option<&str> {
predicates.iter().find_map(|p| {
let (PredicateOperation::Equals(fields) | PredicateOperation::DeepEquals(fields)) =
&p.operation
else {
return None;
};
if !p.parameters.except.is_empty() || p.parameters.selector.is_some() {
return None;
}
let method = fields.get("method")?.as_str()?;
(!method.eq_ignore_ascii_case("GET") && !method.eq_ignore_ascii_case("HEAD"))
.then_some(method)
})
}
fn predicate_key(predicates: &[Predicate]) -> String {
let mut set: Vec<String> = predicates
.iter()
.map(|pred| {
let mut value =
serde_json::to_value(pred).expect("predicate can be serialized to json");
value.sort_all_objects();
value.to_string()
})
.collect();
set.sort();
set.dedup();
format!("{}\u{1e}{}", predicates.len(), set.join("\u{1e}"))
}
pub fn analyze_new_stub(
existing_stubs: &[Stub],
new_stub: &Stub,
insert_index: usize,
) -> StubAnalysisResult {
let mut result = StubAnalysisResult::new();
if let Some(new_id) = &new_stub.id {
for (index, stub) in existing_stubs.iter().enumerate() {
if stub.id.as_ref() == Some(new_id) {
result.add_warning(StubWarning {
warning_type: WarningType::DuplicateId,
message: format!(
"New stub has duplicate ID '{new_id}' (same as existing stub at index {index})"
),
stub_index: Some(insert_index),
stub_id: Some(new_id.clone()),
shadowed_by_index: Some(index),
});
}
}
}
if new_stub.predicates.is_empty() {
result.add_warning(StubWarning {
warning_type: WarningType::CatchAll,
message: "New stub has empty predicates and will match ALL requests".to_string(),
stub_index: Some(insert_index),
stub_id: new_stub.id.clone(),
shadowed_by_index: None,
});
let stubs_after = existing_stubs.len() - insert_index.min(existing_stubs.len());
if stubs_after > 0 {
result.add_warning(StubWarning {
warning_type: WarningType::CatchAllNotLast,
message: format!(
"New catch-all stub will shadow {stubs_after} existing stub(s) after it"
),
stub_index: Some(insert_index),
stub_id: new_stub.id.clone(),
shadowed_by_index: None,
});
}
}
for (index, stub) in existing_stubs.iter().enumerate() {
if predicates_equal(&new_stub.predicates, &stub.predicates) {
let (shadower, shadowed) = if index < insert_index {
(index, insert_index)
} else {
(insert_index, index)
};
let (earlier_gate, later_gate) = if index < insert_index {
(stub.gate(), new_stub.gate())
} else {
(new_stub.gate(), stub.gate())
};
if !earlier_gate.covers(&later_gate) {
continue;
}
result.add_warning(StubWarning {
warning_type: WarningType::ExactDuplicate,
message: format!(
"New stub has identical predicates to stub at index {index}. Stub at index {shadower} will shadow the other."
),
stub_index: Some(shadowed),
stub_id: new_stub.id.clone(),
shadowed_by_index: Some(shadower),
});
}
}
if !new_stub.predicates.is_empty() {
for (index, stub) in existing_stubs.iter().enumerate() {
if index >= insert_index {
break;
}
if stub.predicates.is_empty() && stub.gate().covers(&new_stub.gate()) {
result.add_warning(StubWarning {
warning_type: WarningType::PotentiallyShadowed,
message: format!(
"New stub will be shadowed by catch-all stub at index {index}"
),
stub_index: Some(insert_index),
stub_id: new_stub.id.clone(),
shadowed_by_index: Some(index),
});
}
}
}
result
}
fn predicates_equal(a: &[Predicate], b: &[Predicate]) -> bool {
if a.len() != b.len() {
return false;
}
let canonicalize = |pred: &Predicate| {
let mut value = serde_json::to_value(pred).expect("predicate can be serialized to json");
value.sort_all_objects();
value.to_string()
};
let a_set: HashSet<String> = a.iter().map(canonicalize).collect();
let b_set: HashSet<String> = b.iter().map(canonicalize).collect();
a_set == b_set
}
fn is_subset_predicates(a: &[Predicate], b: &[Predicate]) -> bool {
if b.is_empty() || a.is_empty() {
return false;
}
let a_fields = extract_predicate_fields(a);
let b_fields = extract_predicate_fields(b);
for (field, b_value) in &b_fields {
if let Some(a_value) = a_fields.get(field) {
if is_more_general_constraint(b_value, a_value) {
return true;
}
}
}
false
}
fn extract_predicate_fields(predicates: &[Predicate]) -> HashMap<String, PredicateConstraint> {
let mut fields = HashMap::new();
for pred in predicates {
match &pred.operation {
PredicateOperation::Equals(equals) => {
fields.extend(
equals
.iter()
.map(|(k, v)| (k.clone(), PredicateConstraint::Equals(v.clone()))),
);
}
PredicateOperation::Contains(contains) => {
fields.extend(
contains
.iter()
.map(|(k, v)| (k.clone(), PredicateConstraint::Contains(v.clone()))),
);
}
PredicateOperation::StartsWith(starts_with) => {
fields.extend(
starts_with
.iter()
.map(|(k, v)| (k.clone(), PredicateConstraint::StartsWith(v.clone()))),
);
}
_ => {}
}
}
fields
}
#[derive(Debug, Clone)]
enum PredicateConstraint {
Equals(serde_json::Value),
StartsWith(serde_json::Value),
Contains(serde_json::Value),
}
fn is_more_general_constraint(a: &PredicateConstraint, b: &PredicateConstraint) -> bool {
match (a, b) {
(PredicateConstraint::StartsWith(prefix), PredicateConstraint::Equals(exact)) => {
if let (Some(prefix_str), Some(exact_str)) = (prefix.as_str(), exact.as_str()) {
exact_str.starts_with(prefix_str)
} else {
false
}
}
(PredicateConstraint::Contains(needle), PredicateConstraint::Equals(exact)) => {
if let (Some(needle_str), Some(exact_str)) = (needle.as_str(), exact.as_str()) {
exact_str.contains(needle_str)
} else {
false
}
}
(PredicateConstraint::StartsWith(a_prefix), PredicateConstraint::StartsWith(b_prefix)) => {
if let (Some(a_str), Some(b_str)) = (a_prefix.as_str(), b_prefix.as_str()) {
b_str.starts_with(a_str) && a_str != b_str
} else {
false
}
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imposter::RiftResponseExtension;
use serde_json::json;
fn predicates_from_jsons(predicates: Vec<serde_json::Value>) -> Vec<Predicate> {
predicates
.into_iter()
.map(|v| serde_json::from_value(v).unwrap())
.collect()
}
fn stub_with_predicates(predicates: Vec<serde_json::Value>) -> Stub {
let predicates = predicates_from_jsons(predicates);
Stub {
name: None,
id: None,
route_pattern: None,
predicates,
responses: vec![],
scenario_name: None,
required_scenario_state: None,
new_scenario_state: None,
space: None,
recorded_from: None,
recorded_at: None,
verify: None,
}
}
fn stub_with_id_and_predicates(id: &str, predicates: Vec<serde_json::Value>) -> Stub {
let predicates = predicates_from_jsons(predicates);
Stub {
name: None,
id: Some(id.to_string()),
route_pattern: None,
predicates,
responses: vec![],
scenario_name: None,
required_scenario_state: None,
new_scenario_state: None,
space: None,
recorded_from: None,
recorded_at: None,
verify: None,
}
}
#[test]
fn test_duplicate_id_detection() {
let stubs = vec![
stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/a"}})]),
stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/b"}})]),
];
let result = analyze_stubs(&stubs);
assert!(result.has_warnings());
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::DuplicateId)
);
}
#[test]
fn test_catch_all_detection() {
let stubs = vec![
stub_with_predicates(vec![json!({"equals": {"path": "/specific"}})]),
stub_with_predicates(vec![]), ];
let result = analyze_stubs(&stubs);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::CatchAll)
);
}
#[test]
fn test_catch_all_not_last_warning() {
let stubs = vec![
stub_with_predicates(vec![]), stub_with_predicates(vec![json!({"equals": {"path": "/specific"}})]),
];
let result = analyze_stubs(&stubs);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::CatchAllNotLast)
);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::PotentiallyShadowed)
);
}
#[test]
fn test_exact_duplicate_detection() {
let stubs = vec![
stub_with_predicates(vec![json!({"equals": {"path": "/test", "method": "GET"}})]),
stub_with_predicates(vec![json!({"equals": {"path": "/test", "method": "GET"}})]),
];
let result = analyze_stubs(&stubs);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::ExactDuplicate)
);
}
#[test]
fn analyze_stubs_linear_capped_on_overlap() {
let stubs: Vec<Stub> = (0..500)
.map(|_| stub_with_predicates(vec![json!({"equals": {"path": "/data"}})]))
.collect();
let result = analyze_stubs(&stubs);
assert!(
result.warnings.len() <= MAX_STUB_WARNINGS + 1,
"warnings must be bounded, got {}",
result.warnings.len()
);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::ExactDuplicate)
);
let summary = result
.warnings
.iter()
.find(|w| w.warning_type == WarningType::Truncated)
.expect("a Truncated summary must record the suppressed warnings");
assert!(
summary.message.contains("399 additional"),
"wrong suppressed count: {}",
summary.message
);
}
#[test]
fn exact_duplicate_points_at_first_occurrence() {
let stubs: Vec<Stub> = (0..3)
.map(|_| stub_with_predicates(vec![json!({"equals": {"path": "/same"}})]))
.collect();
let result = analyze_stubs(&stubs);
let dups: Vec<&StubWarning> = result
.warnings
.iter()
.filter(|w| w.warning_type == WarningType::ExactDuplicate)
.collect();
assert_eq!(
dups.len(),
2,
"one warning per later duplicate, not per pair"
);
assert!(
dups.iter().all(|w| w.shadowed_by_index == Some(0)),
"each duplicate must point at the first occurrence"
);
}
#[test]
fn subset_shadow_heuristic_gated_above_threshold() {
let mut stubs = vec![stub_with_predicates(vec![
json!({"startsWith": {"path": "/api"}}),
])];
for i in 0..SHADOW_HEURISTIC_MAX_STUBS {
stubs.push(stub_with_predicates(vec![
json!({"equals": {"path": format!("/api/{i}")}}),
]));
}
assert!(stubs.len() > SHADOW_HEURISTIC_MAX_STUBS);
assert!(
!analyze_stubs(&stubs)
.warnings
.iter()
.any(|w| w.warning_type == WarningType::PotentiallyShadowed),
"subset-shadowing heuristic must be skipped above the threshold"
);
let small = vec![
stub_with_predicates(vec![json!({"startsWith": {"path": "/api"}})]),
stub_with_predicates(vec![json!({"equals": {"path": "/api/users"}})]),
];
assert!(
analyze_stubs(&small)
.warnings
.iter()
.any(|w| w.warning_type == WarningType::PotentiallyShadowed),
"below the threshold the heuristic still runs"
);
}
#[test]
fn test_no_warnings_for_different_stubs() {
let stubs = vec![
stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/a"}})]),
stub_with_id_and_predicates("stub2", vec![json!({"equals": {"path": "/b"}})]),
];
let result = analyze_stubs(&stubs);
assert!(
!result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::DuplicateId)
);
assert!(
!result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::ExactDuplicate)
);
}
#[test]
fn test_shadowing_by_startswith() {
let stubs = vec![
stub_with_predicates(vec![json!({"startsWith": {"path": "/api"}})]),
stub_with_predicates(vec![json!({"equals": {"path": "/api/users"}})]),
];
let result = analyze_stubs(&stubs);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::PotentiallyShadowed)
);
}
#[test]
fn test_analyze_new_stub_duplicate_id() {
let existing = vec![stub_with_id_and_predicates(
"stub1",
vec![json!({"equals": {"path": "/a"}})],
)];
let new_stub =
stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/b"}})]);
let result = analyze_new_stub(&existing, &new_stub, 1);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::DuplicateId)
);
}
#[test]
fn test_analyze_new_stub_shadowed_by_catchall() {
let existing = vec![
stub_with_predicates(vec![]), ];
let new_stub = stub_with_predicates(vec![json!({"equals": {"path": "/specific"}})]);
let result = analyze_new_stub(&existing, &new_stub, 1);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::PotentiallyShadowed)
);
}
#[test]
fn state_ops_on_a_rift_script_response_warns() {
let rift: RiftResponseExtension = serde_json::from_value(json!({
"script": { "code": "response.body = 'x';" },
"stateOps": [{ "op": "increment", "key": "hits" }]
}))
.expect("parses");
let stub = Stub {
name: None,
id: None,
route_pattern: None,
predicates: vec![],
responses: vec![StubResponse::RiftScript {
rift: Box::new(rift),
ignored_behaviors: None,
}],
scenario_name: None,
required_scenario_state: None,
new_scenario_state: None,
space: None,
recorded_from: None,
recorded_at: None,
verify: None,
};
let result = analyze_stubs(&[stub]);
assert!(
result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
"a RiftScript response's stateOps must be flagged as never running: {:?}",
result.warnings
);
}
#[test]
fn a_script_only_response_without_state_ops_does_not_warn() {
let rift: RiftResponseExtension = serde_json::from_value(json!({
"script": { "code": "response.body = 'x';" }
}))
.expect("parses");
let stub = Stub {
name: None,
id: None,
route_pattern: None,
predicates: vec![],
responses: vec![StubResponse::RiftScript {
rift: Box::new(rift),
ignored_behaviors: None,
}],
scenario_name: None,
required_scenario_state: None,
new_scenario_state: None,
space: None,
recorded_from: None,
recorded_at: None,
verify: None,
};
let result = analyze_stubs(&[stub]);
assert!(
!result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
"a script-only response with no stateOps must not warn: {:?}",
result.warnings
);
}
#[test]
fn state_ops_on_an_is_response_does_not_warn() {
let rift: RiftResponseExtension = serde_json::from_value(json!({
"stateOps": [{ "op": "increment", "key": "hits" }]
}))
.expect("parses");
let is_response = crate::imposter::StubResponse::new_is(
crate::imposter::IsResponse::new(200, Default::default(), None, Default::default()),
None,
Some(Box::new(rift)),
);
let stub = Stub {
name: None,
id: None,
route_pattern: None,
predicates: vec![],
responses: vec![is_response],
scenario_name: None,
required_scenario_state: None,
new_scenario_state: None,
space: None,
recorded_from: None,
recorded_at: None,
verify: None,
};
let result = analyze_stubs(&[stub]);
assert!(
!result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
"stateOps on an `is` response must not warn: {:?}",
result.warnings
);
}
#[test]
fn state_ops_on_a_script_less_rift_response_does_not_warn() {
let rift: RiftResponseExtension = serde_json::from_value(json!({
"stateOps": [{ "op": "increment", "key": "hits" }]
}))
.expect("parses");
let mut stub = conditional_stub(json!([]), true);
stub.responses = vec![StubResponse::RiftScript {
rift: Box::new(rift),
ignored_behaviors: None,
}];
let result = analyze_stubs(&[stub]);
assert!(
!result
.warnings
.iter()
.any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
"a script-less `_rift` response runs its stateOps: {:?}",
result.warnings
);
}
#[test]
fn conditional_on_a_script_less_rift_response_warns_only_like_is() {
let script_less = |predicates: serde_json::Value| {
let mut stub = conditional_stub(predicates, true);
stub.responses = vec![StubResponse::RiftScript {
rift: Box::new(
serde_json::from_value(json!({ "conditional": true })).expect("parses"),
),
ignored_behaviors: None,
}];
conditional_warnings(stub)
};
let w = script_less(json!([]));
assert!(w.is_empty(), "{w:?}");
let w = script_less(json!([{ "equals": { "method": "post" } }]));
assert_eq!(w.len(), 1, "{w:?}");
assert!(w[0].message.contains("post"), "{}", w[0].message);
}
fn conditional_stub(predicates: serde_json::Value, script_only: bool) -> Stub {
let rift: RiftResponseExtension = serde_json::from_value(json!({
"conditional": true,
"script": { "code": "response.body = 'x';" }
}))
.expect("parses");
let response = if script_only {
StubResponse::RiftScript {
rift: Box::new(rift),
ignored_behaviors: None,
}
} else {
crate::imposter::StubResponse::new_is(
crate::imposter::IsResponse::new(200, Default::default(), None, Default::default()),
None,
Some(Box::new(rift)),
)
};
Stub {
name: None,
id: None,
route_pattern: None,
predicates: serde_json::from_value(predicates).expect("predicates parse"),
responses: vec![response],
scenario_name: None,
required_scenario_state: None,
new_scenario_state: None,
space: None,
recorded_from: None,
recorded_at: None,
verify: None,
}
}
fn conditional_warnings(stub: Stub) -> Vec<StubWarning> {
analyze_stubs(&[stub])
.warnings
.into_iter()
.filter(|w| w.warning_type == WarningType::ConditionalNeverRuns)
.collect()
}
#[test]
fn conditional_on_script_only_warns() {
let w = conditional_warnings(conditional_stub(json!([]), true));
assert_eq!(w.len(), 1, "{w:?}");
assert!(w[0].message.contains("script response"), "{}", w[0].message);
}
#[test]
fn conditional_behind_a_post_method_predicate_warns() {
let w = conditional_warnings(conditional_stub(
json!([{ "equals": { "method": "post" } }]),
false,
));
assert_eq!(w.len(), 1, "{w:?}");
assert!(w[0].message.contains("post"), "{}", w[0].message);
let w = conditional_warnings(conditional_stub(
json!([{ "deepEquals": { "method": "POST" } }]),
false,
));
assert_eq!(w.len(), 1, "{w:?}");
}
#[test]
fn conditional_on_a_get_stub_is_quiet() {
for preds in [
json!([]),
json!([{ "equals": { "method": "GET" } }]),
json!([{ "equals": { "method": "head" } }]),
json!([{ "equals": { "path": "/x" } }]),
] {
let w = conditional_warnings(conditional_stub(preds.clone(), false));
assert!(w.is_empty(), "{preds}: {w:?}");
}
}
#[test]
fn conditional_under_or_is_not_judged() {
for preds in [
json!([{ "or": [{ "equals": { "method": "POST" } }, { "equals": { "method": "GET" } }] }]),
json!([{ "not": { "equals": { "method": "GET" } } }]),
json!([{ "matches": { "method": "^P" } }]),
json!([{ "exists": { "method": true } }]),
json!([{ "equals": { "method": 5 } }]),
] {
let w = conditional_warnings(conditional_stub(preds.clone(), false));
assert!(w.is_empty(), "{preds}: {w:?}");
}
}
#[test]
fn test_predicates_equal_order_independent() {
let a = vec![
json!({"equals": {"path": "/test"}}),
json!({"equals": {"method": "GET"}}),
];
let b = vec![
json!({"equals": {"method": "GET"}}),
json!({"equals": {"path": "/test"}}),
];
let a = predicates_from_jsons(a);
let b = predicates_from_jsons(b);
assert!(predicates_equal(&a, &b));
}
#[test]
fn test_predicates_not_equal() {
let a = vec![json!({"equals": {"path": "/test"}})];
let b = vec![json!({"equals": {"path": "/other"}})];
let a = predicates_from_jsons(a);
let b = predicates_from_jsons(b);
assert!(!predicates_equal(&a, &b));
}
fn gated_stub(
space: Option<&str>,
scenario: Option<(&str, &str)>,
predicates: Vec<serde_json::Value>,
) -> Stub {
let mut stub = stub_with_predicates(predicates);
stub.space = space.map(str::to_string);
if let Some((name, state)) = scenario {
stub.scenario_name = Some(name.to_string());
stub.required_scenario_state = Some(state.to_string());
}
stub
}
fn count(result: &StubAnalysisResult, ty: WarningType) -> usize {
result
.warnings
.iter()
.filter(|w| w.warning_type == ty)
.count()
}
fn pay() -> Vec<serde_json::Value> {
vec![json!({"equals": {"method": "POST", "path": "/pay"}})]
}
#[test]
fn a_scenario_gated_pair_with_identical_predicates_is_not_a_duplicate() {
let stubs = vec![
gated_stub(None, Some(("checkout", "Started")), pay()),
gated_stub(None, Some(("checkout", "paid")), pay()),
];
let result = analyze_stubs(&stubs);
assert_eq!(count(&result, WarningType::ExactDuplicate), 0);
assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);
}
#[test]
fn stubs_in_different_spaces_are_neither_duplicates_nor_shadowing() {
let stubs = vec![
gated_stub(Some("a"), None, vec![]),
gated_stub(Some("b"), None, vec![]),
gated_stub(Some("a"), None, pay()),
gated_stub(Some("b"), None, pay()),
gated_stub(
Some("c"),
None,
vec![json!({"startsWith": {"path": "/api"}})],
),
gated_stub(
Some("d"),
None,
vec![json!({"equals": {"path": "/api/users"}})],
),
];
let result = analyze_stubs(&stubs);
assert_eq!(count(&result, WarningType::ExactDuplicate), 0);
let shadowed: Vec<_> = result
.warnings
.iter()
.filter(|w| w.warning_type == WarningType::PotentiallyShadowed)
.map(|w| (w.stub_index, w.shadowed_by_index))
.collect();
assert_eq!(shadowed, vec![(Some(2), Some(0)), (Some(3), Some(1))]);
}
#[test]
fn a_gated_catch_all_does_not_shadow_an_ungated_stub() {
let stubs = vec![
gated_stub(None, Some(("s", "Started")), vec![]),
gated_stub(None, None, vec![json!({"equals": {"path": "/x"}})]),
];
let result = analyze_stubs(&stubs);
assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);
}
#[test]
fn the_subset_heuristic_honours_gates() {
let stubs = vec![
gated_stub(
None,
Some(("s", "Started")),
vec![json!({"startsWith": {"path": "/api"}})],
),
gated_stub(
None,
Some(("s", "paid")),
vec![json!({"equals": {"path": "/api/users"}})],
),
];
let result = analyze_stubs(&stubs);
assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);
}
#[test]
fn analyze_new_stub_honours_gates_for_duplicates_and_catch_alls() {
let started = gated_stub(None, Some(("s", "Started")), pay());
let paid = gated_stub(None, Some(("s", "paid")), pay());
let result = analyze_new_stub(std::slice::from_ref(&started), &paid, 1);
assert_eq!(count(&result, WarningType::ExactDuplicate), 0);
let gated_catch_all = gated_stub(None, Some(("s", "Started")), vec![]);
let ungated = stub_with_predicates(pay());
let result = analyze_new_stub(std::slice::from_ref(&gated_catch_all), &ungated, 1);
assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);
let same_gate = gated_stub(None, Some(("s", "Started")), pay());
let result = analyze_new_stub(std::slice::from_ref(&gated_catch_all), &same_gate, 1);
assert_eq!(count(&result, WarningType::PotentiallyShadowed), 1);
}
#[test]
fn an_ungated_twin_ahead_still_makes_a_gated_stub_a_duplicate() {
let stubs = vec![
stub_with_predicates(pay()),
gated_stub(None, Some(("s", "paid")), pay()),
];
let result = analyze_stubs(&stubs);
assert_eq!(count(&result, WarningType::ExactDuplicate), 1);
let result = analyze_new_stub(&stubs[..1], &stubs[1], 1);
assert_eq!(count(&result, WarningType::ExactDuplicate), 1);
}
#[test]
fn an_ungated_catch_all_still_shadows_a_gated_stub() {
let stubs = vec![
stub_with_predicates(vec![]),
gated_stub(None, Some(("s", "paid")), pay()),
];
let result = analyze_stubs(&stubs);
assert_eq!(count(&result, WarningType::PotentiallyShadowed), 1);
let result = analyze_new_stub(&stubs[..1], &stubs[1], 1);
assert_eq!(count(&result, WarningType::PotentiallyShadowed), 1);
}
#[test]
fn a_rift_script_beside_is_is_reported_ignored() {
let replayed = |response: serde_json::Value| -> Stub {
crate::imposter::deserialize_replayed(json!({ "responses": [response] }))
.expect("a replayed stub decodes")
};
let script =
json!({ "script": { "engine": "rhai", "code": "fn respond(ctx) { pass() }" } });
let stubs = [
replayed(json!({ "is": { "body": "plain" } })),
replayed(json!({ "is": { "statusCode": 200 }, "_rift": script })),
replayed(
json!({ "is": {}, "_rift": { "fault": { "latency": { "probability": 1.0, "ms": 5 } } } }),
),
replayed(json!({ "is": { "statusCode": 201 }, "_rift": script })),
];
let config: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "http" })).expect("config");
let warnings = ignored_config_keys(&config, &stubs);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
assert_eq!(warnings[0].stub_index, Some(1));
assert_eq!(
warnings[0].message,
"`_rift.script` beside an `is` response has no effect: a script is a response type of \
its own, and the `is` is served (stubs 1, 3)"
);
assert!(ignored_config_keys(&config, &stubs[..1]).is_empty());
assert!(ignored_config_keys(&config, &stubs[2..3]).is_empty());
}
#[test]
fn unread_predicate_generator_keys_are_reported() {
let proxy = |generators: serde_json::Value| -> Stub {
serde_json::from_value(json!({
"responses": [{ "proxy": { "to": "http://127.0.0.1:9", "predicateGenerators": generators } }]
}))
.expect("valid stub")
};
let stubs = [
proxy(
json!([{ "matches": { "body": true }, "jsonpath": { "selector": "$.id" }, "ignore": { "query": "ts" } }]),
),
proxy(json!([{ "matches": { "method": true }, "matchs": { "path": true } }])),
proxy(
json!([{ "matches": { "path": true }, "keyCaseSensitive": true }, { "matches": {}, "matchs": {} }]),
),
];
let config: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "http" })).expect("config");
let warnings = ignored_config_keys(&config, &stubs);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
assert_eq!(warnings[0].stub_index, Some(1));
assert_eq!(
warnings[0].message,
"proxy `predicateGenerators` key(s) `keyCaseSensitive`, `matchs` have no effect: this \
engine reads inject, matches, caseSensitive, predicateOperator, except, jsonpath, \
xpath and ignore (stubs 1, 2)"
);
assert!(ignored_config_keys(&config, &stubs[..1]).is_empty());
}
#[test]
fn an_unknown_fault_name_is_reported_once() {
let fault = |name: &str| -> Stub {
serde_json::from_value(json!({ "responses": [{ "fault": name }] })).expect("valid stub")
};
let stubs = [
fault("CONNECTION_RESET_BY_PEER"),
fault("NON_EXISTENT_FAULT"),
fault("RANDOM_DATA_THEN_CLOSE"),
fault("reset"),
fault("EMPTY_RESPONSE"),
fault("connection_reset_by_peer"),
fault("NON_EXISTENT_FAULT"),
];
let config: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "http" })).expect("config");
let warnings = ignored_config_keys(&config, &stubs);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
assert_eq!(warnings[0].stub_index, Some(1));
assert_eq!(
warnings[0].message,
"`fault` `NON_EXISTENT_FAULT`, `connection_reset_by_peer` is not a fault Rift knows: \
it is ignored and the response is served as an empty response completed by \
`defaultResponse`, as in Mountebank (stubs 1, 5, 6)"
);
assert!(ignored_config_keys(&config, &stubs[..1]).is_empty());
assert!(ignored_config_keys(&config, &stubs[2..5]).is_empty());
}
#[test]
fn ciphers_is_reported_as_ignored() {
let config: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "https", "ciphers": "x" }))
.expect("config");
let warnings = ignored_config_keys(&config, &[]);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
assert!(
warnings[0]
.message
.starts_with("`ciphers` is stored and printed but not applied"),
"{}",
warnings[0].message
);
let plain: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "https" })).expect("config");
assert!(ignored_config_keys(&plain, &[]).is_empty());
let http: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "http", "ciphers": "x" }))
.expect("config");
assert!(ignored_config_keys(&http, &[]).is_empty());
}
}