use crate::core::config::e2e::ArgMapping;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MockResponse {
pub status: u16,
#[serde(default)]
pub body: Option<serde_json::Value>,
#[serde(default)]
pub stream_chunks: Option<Vec<serde_json::Value>>,
#[serde(default)]
pub headers: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisitorSpec {
pub callbacks: BTreeMap<String, CallbackAction>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action")]
pub enum CallbackAction {
#[serde(rename = "skip")]
Skip,
#[serde(rename = "continue")]
Continue,
#[serde(rename = "preserve_html")]
PreserveHtml,
#[serde(rename = "custom")]
Custom {
output: String,
},
#[serde(rename = "custom_template")]
CustomTemplate {
template: String,
#[serde(default)]
return_form: TemplateReturnForm,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TemplateReturnForm {
#[default]
Dict,
BareString,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureEnv {
#[serde(default)]
pub api_key_var: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetupCall {
pub call: String,
#[serde(default)]
pub input: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Fixture {
pub id: String,
#[serde(default)]
pub category: Option<String>,
pub description: String,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub skip: Option<SkipDirective>,
#[serde(default)]
pub env: Option<FixtureEnv>,
#[serde(default)]
pub setup: Vec<SetupCall>,
#[serde(default)]
pub call: Option<String>,
#[serde(default)]
pub input: serde_json::Value,
#[serde(default)]
pub mock_response: Option<MockResponse>,
#[serde(default)]
pub visitor: Option<VisitorSpec>,
#[serde(default)]
pub args: Vec<ArgMapping>,
#[serde(default)]
pub assertion_recipes: Vec<String>,
#[serde(default)]
pub assertions: Vec<Assertion>,
#[serde(skip)]
pub source: String,
#[serde(default)]
pub http: Option<HttpFixture>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpFixture {
pub handler: HttpHandler,
pub request: HttpRequest,
pub expected_response: HttpExpectedResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpHandler {
pub route: String,
pub method: String,
#[serde(default)]
pub body_schema: Option<serde_json::Value>,
#[serde(default)]
pub parameters: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
#[serde(default)]
pub middleware: Option<HttpMiddleware>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpRequest {
pub method: String,
pub path: String,
#[serde(default)]
pub headers: BTreeMap<String, String>,
#[serde(default)]
pub query_params: BTreeMap<String, serde_json::Value>,
#[serde(default)]
pub cookies: BTreeMap<String, String>,
#[serde(default)]
pub body: Option<serde_json::Value>,
#[serde(default)]
pub form_data: Option<BTreeMap<String, String>>,
#[serde(default)]
pub content_type: Option<String>,
}
impl HttpRequest {
pub fn url_encoded_body(&self) -> Option<String> {
self.form_data.as_ref().map(|form| {
form.iter()
.map(|(k, v)| {
let encoded_k = Self::url_encode(k);
let encoded_v = Self::url_encode(v);
format!("{}={}", encoded_k, encoded_v)
})
.collect::<Vec<_>>()
.join("&")
})
}
fn url_encode(s: &str) -> String {
s.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
_ => format!("%{:02X}", b),
})
.collect()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpExpectedResponse {
pub status_code: u16,
#[serde(default)]
pub body: Option<serde_json::Value>,
#[serde(default)]
pub body_partial: Option<serde_json::Value>,
#[serde(default)]
pub headers: BTreeMap<String, String>,
#[serde(default)]
pub validation_errors: Option<Vec<ValidationErrorExpectation>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationErrorExpectation {
pub loc: Vec<String>,
pub msg: String,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CorsConfig {
#[serde(default)]
pub allow_origins: Vec<String>,
#[serde(default)]
pub allow_methods: Vec<String>,
#[serde(default)]
pub allow_headers: Vec<String>,
#[serde(default)]
pub expose_headers: Vec<String>,
#[serde(default)]
pub max_age: Option<u64>,
#[serde(default)]
pub allow_credentials: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StaticFile {
pub path: String,
pub content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StaticFilesConfig {
pub route_prefix: String,
#[serde(default)]
pub files: Vec<StaticFile>,
#[serde(default)]
pub index_file: bool,
#[serde(default)]
pub cache_control: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HttpMiddleware {
#[serde(default)]
pub jwt_auth: Option<serde_json::Value>,
#[serde(default)]
pub api_key_auth: Option<serde_json::Value>,
#[serde(default)]
pub compression: Option<serde_json::Value>,
#[serde(default)]
pub rate_limit: Option<serde_json::Value>,
#[serde(default)]
pub request_timeout: Option<serde_json::Value>,
#[serde(default)]
pub body_limit: Option<serde_json::Value>,
#[serde(default)]
pub request_id: Option<serde_json::Value>,
#[serde(default)]
pub cors: Option<CorsConfig>,
#[serde(default)]
pub static_files: Option<Vec<StaticFilesConfig>>,
#[serde(default)]
pub graphql: Option<serde_json::Value>,
#[serde(default)]
pub lifecycle_hooks: Option<serde_json::Value>,
#[serde(default)]
pub openrpc: Option<serde_json::Value>,
#[serde(default)]
pub background_tasks: Option<serde_json::Value>,
#[serde(default)]
pub websocket: Option<serde_json::Value>,
#[serde(default)]
pub authorization: Option<serde_json::Value>,
}
const ORIGIN_ROOT_ROUTE_PREFIXES: [&str; 2] = ["/robots", "/sitemap"];
fn is_host_root_path(path: &str) -> bool {
ORIGIN_ROOT_ROUTE_PREFIXES.iter().any(|prefix| path.starts_with(prefix))
}
impl Default for Fixture {
fn default() -> Self {
Fixture {
id: String::new(),
category: None,
description: String::new(),
tags: Vec::new(),
skip: None,
env: None,
setup: Vec::new(),
call: None,
input: serde_json::Value::Null,
mock_response: None,
visitor: None,
args: Vec::new(),
assertion_recipes: Vec::new(),
assertions: Vec::new(),
source: String::new(),
http: None,
}
}
}
impl Fixture {
pub fn resolved_args<'a>(&'a self, call_config: &'a crate::core::config::e2e::CallConfig) -> &'a [ArgMapping] {
if !self.args.is_empty() {
&self.args
} else {
&call_config.args
}
}
pub fn is_http_test(&self) -> bool {
self.http.is_some()
}
pub fn needs_mock_server(&self) -> bool {
if self.mock_response.is_some() || self.http.is_some() {
return true;
}
self.input
.get("mock_responses")
.and_then(|v| v.as_array())
.map(|arr| !arr.is_empty())
.unwrap_or(false)
}
pub fn as_mock_response(&self) -> Option<MockResponse> {
if let Some(mock) = &self.mock_response {
return Some(mock.clone());
}
if let Some(http) = &self.http {
return Some(MockResponse {
status: http.expected_response.status_code,
body: http.expected_response.body.clone(),
stream_chunks: None,
headers: http.expected_response.headers.clone(),
});
}
None
}
pub fn is_streaming_mock(&self) -> bool {
self.mock_response
.as_ref()
.and_then(|m| m.stream_chunks.as_ref())
.map(|c| !c.is_empty())
.unwrap_or(false)
}
pub fn has_host_root_route(&self) -> bool {
if let Some(arr) = self.input.get("mock_responses").and_then(|v| v.as_array()) {
if arr.iter().any(|entry| {
entry
.get("path")
.and_then(|v| v.as_str())
.map(is_host_root_path)
.unwrap_or(false)
}) {
return true;
}
return arr.iter().any(|entry| {
let status = entry.get("status_code").and_then(|v| v.as_u64()).unwrap_or(0);
let headers = entry.get("headers").and_then(|v| v.as_object());
let location_redirect = (300..400).contains(&status)
&& headers
.map(|hdrs| {
hdrs.iter().any(|(name, value)| {
name.eq_ignore_ascii_case("location")
&& value.as_str().is_some_and(|s| s.starts_with('/'))
})
})
.unwrap_or(false);
let refresh_redirect = headers
.map(|hdrs| {
hdrs.iter().any(|(name, value)| {
if !name.eq_ignore_ascii_case("refresh") {
return false;
}
value
.as_str()
.and_then(|s| s.to_ascii_lowercase().find("url=").map(|i| (s.to_owned(), i)))
.map(|(s, idx)| s[idx + 4..].trim_start().starts_with('/'))
.unwrap_or(false)
})
})
.unwrap_or(false);
let meta_refresh = entry
.get("body_inline")
.and_then(|v| v.as_str())
.map(|body| {
let lower = body.to_ascii_lowercase();
lower
.split("http-equiv=\"refresh\"")
.nth(1)
.and_then(|s| s.split("content=").nth(1))
.map(|s| s.trim_start_matches(['"', '\'']).contains("url=/"))
.unwrap_or(false)
})
.unwrap_or(false);
let inline_host_link = entry
.get("body_inline")
.and_then(|v| v.as_str())
.map(|body| body.contains("href=\"/") || body.contains("href='/"))
.unwrap_or(false);
location_redirect || refresh_redirect || meta_refresh || inline_host_link
});
}
false
}
pub fn resolved_category(&self) -> String {
self.category.clone().unwrap_or_else(|| {
Path::new(&self.source)
.parent()
.and_then(|p| p.file_name())
.and_then(|n| n.to_str())
.unwrap_or("default")
.to_string()
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkipDirective {
#[serde(default)]
pub languages: Vec<String>,
#[serde(default)]
pub reason: Option<String>,
}
impl SkipDirective {
pub fn should_skip(&self, language: &str) -> bool {
self.languages.is_empty() || self.languages.iter().any(|l| l == language)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Assertion {
#[serde(rename = "type")]
pub assertion_type: String,
#[serde(default)]
pub field: Option<String>,
#[serde(default)]
pub value: Option<serde_json::Value>,
#[serde(default)]
pub values: Option<Vec<serde_json::Value>>,
#[serde(default)]
pub method: Option<String>,
#[serde(default)]
pub check: Option<String>,
#[serde(default)]
pub args: Option<serde_json::Value>,
#[serde(default)]
pub return_type: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FixtureGroup {
pub category: String,
pub fixtures: Vec<Fixture>,
}
pub fn load_fixtures(dir: &Path) -> Result<Vec<Fixture>> {
let mut fixtures = Vec::new();
load_fixtures_recursive(dir, dir, &mut fixtures)?;
let mut seen: HashMap<String, String> = HashMap::new();
for f in &fixtures {
if let Some(prev_source) = seen.get(&f.id) {
bail!(
"duplicate fixture ID '{}': found in '{}' and '{}'",
f.id,
prev_source,
f.source
);
}
seen.insert(f.id.clone(), f.source.clone());
}
fixtures.sort_by(|a, b| {
let cat_cmp = a.resolved_category().cmp(&b.resolved_category());
cat_cmp.then_with(|| a.id.cmp(&b.id))
});
Ok(fixtures)
}
fn load_fixtures_recursive(base: &Path, dir: &Path, fixtures: &mut Vec<Fixture>) -> Result<()> {
let entries =
std::fs::read_dir(dir).with_context(|| format!("failed to read fixture directory: {}", dir.display()))?;
let mut paths: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
paths.sort();
for path in paths {
if path.is_dir() {
load_fixtures_recursive(base, &path, fixtures)?;
} else if path.extension().is_some_and(|ext| ext == "json") {
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if filename == "schema.json" || filename.starts_with('_') {
continue;
}
let content = std::fs::read_to_string(&path)
.with_context(|| format!("failed to read fixture: {}", path.display()))?;
let relative = path.strip_prefix(base).unwrap_or(&path).to_string_lossy().to_string();
let parsed: Vec<Fixture> = if content.trim_start().starts_with('[') {
let values: Vec<serde_json::Value> = serde_json::from_str(&content)
.with_context(|| format!("failed to parse fixture array: {}", path.display()))?;
values
.into_iter()
.map(normalize_fixture_value)
.map(serde_json::from_value)
.collect::<std::result::Result<Vec<_>, _>>()
.with_context(|| format!("failed to parse fixture array: {}", path.display()))?
} else {
let value: serde_json::Value = serde_json::from_str(&content)
.with_context(|| format!("failed to parse fixture: {}", path.display()))?;
let single: Fixture = serde_json::from_value(normalize_fixture_value(value))
.with_context(|| format!("failed to parse fixture: {}", path.display()))?;
vec![single]
};
for mut fixture in parsed {
fixture.source = relative.clone();
expand_json_templates(&mut fixture.input);
if let Some(ref mut http) = fixture.http {
for v in http.request.headers.values_mut() {
*v = crate::e2e::escape::expand_fixture_templates(v);
}
if let Some(ref mut body) = http.request.body {
expand_json_templates(body);
}
}
fixtures.push(fixture);
}
}
}
Ok(())
}
fn normalize_fixture_value(mut value: serde_json::Value) -> serde_json::Value {
let Some(object) = value.as_object_mut() else {
return value;
};
if let Some(config) = object.get("config").cloned() {
let input = object
.entry("input")
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
if let Some(input_object) = input.as_object_mut() {
input_object.entry("config".to_string()).or_insert(config);
}
}
value
}
pub fn validate_skip_languages(fixtures: &[Fixture], valid_languages: &[String]) -> Result<()> {
for fixture in fixtures {
let Some(skip) = &fixture.skip else {
continue;
};
for language in &skip.languages {
if !valid_languages.iter().any(|valid| valid == language) {
bail!(
"fixture '{}' ({}) has unknown skip.languages id '{}'; valid ids are: {}",
fixture.id,
fixture.source,
language,
valid_languages.join(", ")
);
}
}
}
Ok(())
}
pub fn group_fixtures(fixtures: &[Fixture]) -> Vec<FixtureGroup> {
let mut groups: HashMap<String, Vec<Fixture>> = HashMap::new();
for f in fixtures {
groups.entry(f.resolved_category()).or_default().push(f.clone());
}
let mut result: Vec<FixtureGroup> = groups
.into_iter()
.map(|(category, fixtures)| FixtureGroup { category, fixtures })
.collect();
result.sort_by(|a, b| a.category.cmp(&b.category));
result
}
fn expand_json_templates(value: &mut serde_json::Value) {
match value {
serde_json::Value::String(s) => {
let expanded = crate::e2e::escape::expand_fixture_templates(s);
if expanded != *s {
*s = expanded;
}
}
serde_json::Value::Array(arr) => {
for item in arr {
expand_json_templates(item);
}
}
serde_json::Value::Object(map) => {
for (_, v) in map.iter_mut() {
expand_json_templates(v);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fixture_with_mock_response() {
let json = r#"{
"id": "test_chat",
"description": "Test chat",
"call": "chat",
"input": {"model": "gpt-4", "messages": [{"role": "user", "content": "hi"}]},
"mock_response": {
"status": 200,
"body": {"choices": [{"message": {"content": "hello"}}]}
},
"assertions": [{"type": "not_error"}]
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(fixture.needs_mock_server());
assert!(!fixture.is_streaming_mock());
assert_eq!(fixture.mock_response.unwrap().status, 200);
}
#[test]
fn test_fixture_with_streaming_mock_response() {
let json = r#"{
"id": "test_stream",
"description": "Test streaming",
"input": {},
"mock_response": {
"status": 200,
"stream_chunks": [{"delta": "hello"}, {"delta": " world"}]
},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(fixture.needs_mock_server());
assert!(fixture.is_streaming_mock());
}
#[test]
fn test_fixture_without_mock_response() {
let json = r#"{
"id": "test_no_mock",
"description": "No mock",
"input": {},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(!fixture.needs_mock_server());
assert!(!fixture.is_streaming_mock());
}
#[test]
fn http_middleware_deserializes_lifecycle_hooks_keyed_by_phase() {
let json = r#"{
"lifecycle_hooks": {
"on_request": [{"name": "request_logger", "handler": "log_request"}],
"pre_validation": [
{"name": "rate_limiter", "handler": "check_rate_limit",
"config": {"max_requests": 10, "window_seconds": 60}}
]
}
}"#;
let middleware: HttpMiddleware = serde_json::from_str(json).unwrap();
let hooks = middleware
.lifecycle_hooks
.expect("lifecycle_hooks must survive deserialization");
assert_eq!(hooks["on_request"][0]["handler"], serde_json::json!("log_request"));
assert_eq!(
hooks["pre_validation"][0]["config"]["max_requests"],
serde_json::json!(10)
);
}
#[test]
fn http_middleware_deserializes_openrpc_spec_document() {
let json = r#"{
"openrpc": {
"enabled": true,
"spec": {
"openrpc": "1.3.2",
"info": {"title": "Math API", "version": "1.0.0"},
"methods": [{"name": "add"}]
}
}
}"#;
let middleware: HttpMiddleware = serde_json::from_str(json).unwrap();
let openrpc = middleware.openrpc.expect("openrpc must survive deserialization");
assert_eq!(openrpc["enabled"], serde_json::json!(true));
assert_eq!(openrpc["spec"]["methods"][0]["name"], serde_json::json!("add"));
}
#[test]
fn http_middleware_deserializes_background_tasks_config() {
let json = r#"{"background_tasks": {"enabled": true, "max_concurrent": 5}}"#;
let middleware: HttpMiddleware = serde_json::from_str(json).unwrap();
let tasks = middleware
.background_tasks
.expect("background_tasks must survive deserialization");
assert_eq!(tasks["max_concurrent"], serde_json::json!(5));
}
#[test]
fn http_middleware_deserializes_websocket_config() {
let json = r#"{"websocket": {"enabled": true}}"#;
let middleware: HttpMiddleware = serde_json::from_str(json).unwrap();
let websocket = middleware.websocket.expect("websocket must survive deserialization");
assert_eq!(websocket["enabled"], serde_json::json!(true));
}
#[test]
fn http_middleware_deserializes_authorization_policy() {
let json = r#"{"authorization": {"required_role": "admin"}}"#;
let middleware: HttpMiddleware = serde_json::from_str(json).unwrap();
let authorization = middleware
.authorization
.expect("authorization must survive deserialization");
assert_eq!(authorization["required_role"], serde_json::json!("admin"));
}
#[test]
fn http_middleware_defaults_every_field_to_none() {
let middleware: HttpMiddleware = serde_json::from_str("{}").unwrap();
assert!(middleware.lifecycle_hooks.is_none());
assert!(middleware.openrpc.is_none());
assert!(middleware.background_tasks.is_none());
assert!(middleware.websocket.is_none());
assert!(middleware.authorization.is_none());
}
#[test]
fn http_middleware_rejects_unknown_key() {
let error = serde_json::from_str::<HttpMiddleware>(r#"{"telemetry": {"enabled": true}}"#)
.expect_err("unknown middleware keys must be rejected");
assert!(
error.to_string().contains("telemetry"),
"error should name the offending key, got: {error}"
);
}
#[test]
fn normalize_fixture_value_copies_top_level_config_into_input() {
let value = serde_json::json!({
"id": "configured_call",
"description": "Configured call",
"input": {"kind": "uri", "uri": "doc.txt"},
"config": {"output_format": "markdown"}
});
let normalized = normalize_fixture_value(value);
assert_eq!(
normalized.pointer("/input/config/output_format"),
Some(&serde_json::json!("markdown"))
);
}
#[test]
fn normalize_fixture_value_preserves_explicit_input_config() {
let value = serde_json::json!({
"id": "configured_call",
"description": "Configured call",
"input": {
"kind": "uri",
"uri": "doc.txt",
"config": {"output_format": "html"}
},
"config": {"output_format": "markdown"}
});
let normalized = normalize_fixture_value(value);
assert_eq!(
normalized.pointer("/input/config/output_format"),
Some(&serde_json::json!("html"))
);
}
#[test]
fn has_host_root_route_true_for_origin_root_robot_route_path() {
let json = r#"{
"id": "robots_disallow_path",
"description": "Robots fixture",
"input": {
"mock_responses": [
{"path": "/robots.txt", "status_code": 200, "body_inline": "User-agent: *\nDisallow: /"},
{"path": "/", "status_code": 200, "body_inline": "<html/>"}
]
},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(fixture.has_host_root_route(), "expected true for /robots.txt path");
}
#[test]
fn has_host_root_route_true_for_origin_root_sitemap_route_path() {
let json = r#"{
"id": "sitemap_index",
"description": "Sitemap fixture",
"input": {
"mock_responses": [
{"path": "/sitemap.xml", "status_code": 200, "body_inline": "<?xml version='1.0'?>"},
{"path": "/", "status_code": 200, "body_inline": "<html/>"}
]
},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(fixture.has_host_root_route(), "expected true for /sitemap.xml path");
}
#[test]
fn has_host_root_route_true_for_origin_root_redirect_target() {
let json = r#"{
"id": "redirect_fixture",
"description": "Redirect fixture",
"input": {
"mock_responses": [
{
"path": "/",
"status_code": 302,
"headers": {"Location": "/final"},
"body_inline": ""
},
{"path": "/final", "status_code": 200, "body_inline": "{}"}
]
},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(
fixture.has_host_root_route(),
"expected origin-root listener for origin-root redirect target"
);
}
#[test]
fn has_host_root_route_true_for_origin_root_link_target() {
let json = r#"{
"id": "linked_pages",
"description": "Linked pages",
"input": {
"mock_responses": [
{
"path": "/",
"status_code": 200,
"body_inline": "<html><a href='/page'>Page</a></html>"
},
{"path": "/page", "status_code": 200, "body_inline": "{}"}
]
},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(
fixture.has_host_root_route(),
"expected origin-root listener for origin-root link target"
);
}
#[test]
fn has_host_root_route_false_for_data_json_path() {
let json = r#"{
"id": "data_endpoint",
"description": "Namespaced route fixture",
"input": {
"mock_responses": [
{"path": "/data.json", "status_code": 200, "body_inline": "{}"}
]
},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(!fixture.has_host_root_route(), "expected false for /data.json path");
}
#[test]
fn has_host_root_route_false_for_single_mock_response_schema() {
let json = r#"{
"id": "basic_chat",
"description": "Basic chat",
"mock_response": {"status": 200, "body": {}},
"input": {},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(
!fixture.has_host_root_route(),
"expected false for single mock_response schema"
);
}
#[test]
fn has_host_root_route_false_for_empty_mock_responses() {
let json = r#"{
"id": "empty_responses",
"description": "No mock_responses",
"input": {},
"assertions": []
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
assert!(!fixture.has_host_root_route(), "expected false when no mock_responses");
}
#[test]
fn validate_skip_languages_accepts_known_id() {
let json = r#"{
"id": "known_skip",
"description": "Skips a real target",
"input": {},
"assertions": [],
"skip": {"languages": ["python", "node"], "reason": "not applicable"}
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
let valid = vec!["python".to_string(), "node".to_string(), "rust".to_string()];
assert!(validate_skip_languages(&[fixture], &valid).is_ok());
}
#[test]
fn validate_skip_languages_rejects_unknown_id() {
let json = r#"{
"id": "bogus_skip",
"description": "Skips a nonexistent target",
"input": {},
"assertions": [],
"skip": {"languages": ["typescript"], "reason": "wrong id"}
}"#;
let fixture: Fixture = serde_json::from_str(json).unwrap();
let valid = vec!["python".to_string(), "node".to_string(), "rust".to_string()];
let err = validate_skip_languages(&[fixture], &valid).expect_err("unknown id must fail validation");
let message = err.to_string();
assert!(
message.contains("bogus_skip"),
"error should name the fixture: {message}"
);
assert!(
message.contains("typescript"),
"error should name the bad id: {message}"
);
assert!(message.contains("python"), "error should list valid ids: {message}");
}
}