1use anyhow::{Context, Result, bail};
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::path::Path;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct MockResponse {
11 pub status: u16,
13 #[serde(default)]
15 pub body: Option<serde_json::Value>,
16 #[serde(default)]
19 pub stream_chunks: Option<Vec<serde_json::Value>>,
20 #[serde(default)]
23 pub headers: HashMap<String, String>,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct VisitorSpec {
29 pub callbacks: HashMap<String, CallbackAction>,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
35#[serde(tag = "action")]
36pub enum CallbackAction {
37 #[serde(rename = "skip")]
39 Skip,
40 #[serde(rename = "continue")]
42 Continue,
43 #[serde(rename = "preserve_html")]
45 PreserveHtml,
46 #[serde(rename = "custom")]
48 Custom {
49 output: String,
51 },
52 #[serde(rename = "custom_template")]
54 CustomTemplate {
55 template: String,
57 },
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct FixtureEnv {
63 #[serde(default)]
65 pub api_key_var: Option<String>,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct Fixture {
71 pub id: String,
73 #[serde(default)]
75 pub category: Option<String>,
76 pub description: String,
78 #[serde(default)]
80 pub tags: Vec<String>,
81 #[serde(default)]
83 pub skip: Option<SkipDirective>,
84 #[serde(default)]
86 pub env: Option<FixtureEnv>,
87 #[serde(default)]
90 pub call: Option<String>,
91 #[serde(default)]
93 pub input: serde_json::Value,
94 #[serde(default)]
96 pub mock_response: Option<MockResponse>,
97 #[serde(default)]
99 pub visitor: Option<VisitorSpec>,
100 #[serde(default)]
102 pub assertions: Vec<Assertion>,
103 #[serde(skip)]
105 pub source: String,
106 #[serde(default)]
109 pub http: Option<HttpFixture>,
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct HttpFixture {
115 pub handler: HttpHandler,
117 pub request: HttpRequest,
119 pub expected_response: HttpExpectedResponse,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct HttpHandler {
126 pub route: String,
128 pub method: String,
130 #[serde(default)]
132 pub body_schema: Option<serde_json::Value>,
133 #[serde(default)]
135 pub parameters: HashMap<String, HashMap<String, serde_json::Value>>,
136 #[serde(default)]
138 pub middleware: Option<HttpMiddleware>,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct HttpRequest {
144 pub method: String,
145 pub path: String,
146 #[serde(default)]
147 pub headers: HashMap<String, String>,
148 #[serde(default)]
149 pub query_params: HashMap<String, serde_json::Value>,
150 #[serde(default)]
151 pub cookies: HashMap<String, String>,
152 #[serde(default)]
153 pub body: Option<serde_json::Value>,
154 #[serde(default)]
155 pub content_type: Option<String>,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct HttpExpectedResponse {
161 pub status_code: u16,
162 #[serde(default)]
164 pub body: Option<serde_json::Value>,
165 #[serde(default)]
167 pub body_partial: Option<serde_json::Value>,
168 #[serde(default)]
170 pub headers: HashMap<String, String>,
171 #[serde(default)]
173 pub validation_errors: Option<Vec<ValidationErrorExpectation>>,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct ValidationErrorExpectation {
179 pub loc: Vec<String>,
180 pub msg: String,
181 #[serde(rename = "type")]
182 pub error_type: String,
183}
184
185#[derive(Debug, Clone, Default, Serialize, Deserialize)]
187pub struct CorsConfig {
188 #[serde(default)]
190 pub allow_origins: Vec<String>,
191 #[serde(default)]
193 pub allow_methods: Vec<String>,
194 #[serde(default)]
196 pub allow_headers: Vec<String>,
197 #[serde(default)]
199 pub expose_headers: Vec<String>,
200 #[serde(default)]
202 pub max_age: Option<u64>,
203 #[serde(default)]
205 pub allow_credentials: bool,
206}
207
208#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct StaticFile {
211 pub path: String,
213 pub content: String,
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
219pub struct StaticFilesConfig {
220 pub route_prefix: String,
222 #[serde(default)]
224 pub files: Vec<StaticFile>,
225 #[serde(default)]
227 pub index_file: bool,
228 #[serde(default)]
230 pub cache_control: Option<String>,
231}
232
233#[derive(Debug, Clone, Default, Serialize, Deserialize)]
235pub struct HttpMiddleware {
236 #[serde(default)]
237 pub jwt_auth: Option<serde_json::Value>,
238 #[serde(default)]
239 pub api_key_auth: Option<serde_json::Value>,
240 #[serde(default)]
241 pub compression: Option<serde_json::Value>,
242 #[serde(default)]
243 pub rate_limit: Option<serde_json::Value>,
244 #[serde(default)]
245 pub request_timeout: Option<serde_json::Value>,
246 #[serde(default)]
247 pub request_id: Option<serde_json::Value>,
248 #[serde(default)]
250 pub cors: Option<CorsConfig>,
251 #[serde(default)]
253 pub static_files: Option<Vec<StaticFilesConfig>>,
254}
255
256impl Fixture {
257 pub fn is_http_test(&self) -> bool {
259 self.http.is_some()
260 }
261
262 pub fn needs_mock_server(&self) -> bool {
266 self.mock_response.is_some() || self.http.is_some()
267 }
268
269 pub fn as_mock_response(&self) -> Option<MockResponse> {
275 if let Some(mock) = &self.mock_response {
276 return Some(mock.clone());
277 }
278 if let Some(http) = &self.http {
279 return Some(MockResponse {
280 status: http.expected_response.status_code,
281 body: http.expected_response.body.clone(),
282 stream_chunks: None,
283 headers: http.expected_response.headers.clone(),
284 });
285 }
286 None
287 }
288
289 pub fn is_streaming_mock(&self) -> bool {
291 self.mock_response
292 .as_ref()
293 .and_then(|m| m.stream_chunks.as_ref())
294 .map(|c| !c.is_empty())
295 .unwrap_or(false)
296 }
297
298 pub fn resolved_category(&self) -> String {
300 self.category.clone().unwrap_or_else(|| {
301 Path::new(&self.source)
302 .parent()
303 .and_then(|p| p.file_name())
304 .and_then(|n| n.to_str())
305 .unwrap_or("default")
306 .to_string()
307 })
308 }
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize)]
313pub struct SkipDirective {
314 #[serde(default)]
316 pub languages: Vec<String>,
317 #[serde(default)]
319 pub reason: Option<String>,
320}
321
322impl SkipDirective {
323 pub fn should_skip(&self, language: &str) -> bool {
325 self.languages.is_empty() || self.languages.iter().any(|l| l == language)
326 }
327}
328
329#[derive(Debug, Clone, Default, Serialize, Deserialize)]
331pub struct Assertion {
332 #[serde(rename = "type")]
334 pub assertion_type: String,
335 #[serde(default)]
337 pub field: Option<String>,
338 #[serde(default)]
340 pub value: Option<serde_json::Value>,
341 #[serde(default)]
343 pub values: Option<Vec<serde_json::Value>>,
344 #[serde(default)]
346 pub method: Option<String>,
347 #[serde(default)]
349 pub check: Option<String>,
350 #[serde(default)]
352 pub args: Option<serde_json::Value>,
353 #[serde(default)]
362 pub return_type: Option<String>,
363}
364
365#[derive(Debug, Clone)]
367pub struct FixtureGroup {
368 pub category: String,
369 pub fixtures: Vec<Fixture>,
370}
371
372pub fn load_fixtures(dir: &Path) -> Result<Vec<Fixture>> {
374 let mut fixtures = Vec::new();
375 load_fixtures_recursive(dir, dir, &mut fixtures)?;
376
377 let mut seen: HashMap<String, String> = HashMap::new();
379 for f in &fixtures {
380 if let Some(prev_source) = seen.get(&f.id) {
381 bail!(
382 "duplicate fixture ID '{}': found in '{}' and '{}'",
383 f.id,
384 prev_source,
385 f.source
386 );
387 }
388 seen.insert(f.id.clone(), f.source.clone());
389 }
390
391 fixtures.sort_by(|a, b| {
393 let cat_cmp = a.resolved_category().cmp(&b.resolved_category());
394 cat_cmp.then_with(|| a.id.cmp(&b.id))
395 });
396
397 Ok(fixtures)
398}
399
400fn load_fixtures_recursive(base: &Path, dir: &Path, fixtures: &mut Vec<Fixture>) -> Result<()> {
401 let entries =
402 std::fs::read_dir(dir).with_context(|| format!("failed to read fixture directory: {}", dir.display()))?;
403
404 let mut paths: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
405 paths.sort();
406
407 for path in paths {
408 if path.is_dir() {
409 load_fixtures_recursive(base, &path, fixtures)?;
410 } else if path.extension().is_some_and(|ext| ext == "json") {
411 let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
412 if filename == "schema.json" || filename.starts_with('_') {
414 continue;
415 }
416 let content = std::fs::read_to_string(&path)
417 .with_context(|| format!("failed to read fixture: {}", path.display()))?;
418 let relative = path.strip_prefix(base).unwrap_or(&path).to_string_lossy().to_string();
419
420 let parsed: Vec<Fixture> = if content.trim_start().starts_with('[') {
422 serde_json::from_str(&content)
423 .with_context(|| format!("failed to parse fixture array: {}", path.display()))?
424 } else {
425 let single: Fixture = serde_json::from_str(&content)
426 .with_context(|| format!("failed to parse fixture: {}", path.display()))?;
427 vec![single]
428 };
429
430 for mut fixture in parsed {
431 fixture.source = relative.clone();
432 expand_json_templates(&mut fixture.input);
435 if let Some(ref mut http) = fixture.http {
436 for (_, v) in http.request.headers.iter_mut() {
437 *v = crate::escape::expand_fixture_templates(v);
438 }
439 if let Some(ref mut body) = http.request.body {
440 expand_json_templates(body);
441 }
442 }
443 fixtures.push(fixture);
444 }
445 }
446 }
447 Ok(())
448}
449
450pub fn group_fixtures(fixtures: &[Fixture]) -> Vec<FixtureGroup> {
452 let mut groups: HashMap<String, Vec<Fixture>> = HashMap::new();
453 for f in fixtures {
454 groups.entry(f.resolved_category()).or_default().push(f.clone());
455 }
456 let mut result: Vec<FixtureGroup> = groups
457 .into_iter()
458 .map(|(category, fixtures)| FixtureGroup { category, fixtures })
459 .collect();
460 result.sort_by(|a, b| a.category.cmp(&b.category));
461 result
462}
463
464fn expand_json_templates(value: &mut serde_json::Value) {
466 match value {
467 serde_json::Value::String(s) => {
468 let expanded = crate::escape::expand_fixture_templates(s);
469 if expanded != *s {
470 *s = expanded;
471 }
472 }
473 serde_json::Value::Array(arr) => {
474 for item in arr {
475 expand_json_templates(item);
476 }
477 }
478 serde_json::Value::Object(map) => {
479 for (_, v) in map.iter_mut() {
480 expand_json_templates(v);
481 }
482 }
483 _ => {}
484 }
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490
491 #[test]
492 fn test_fixture_with_mock_response() {
493 let json = r#"{
494 "id": "test_chat",
495 "description": "Test chat",
496 "call": "chat",
497 "input": {"model": "gpt-4", "messages": [{"role": "user", "content": "hi"}]},
498 "mock_response": {
499 "status": 200,
500 "body": {"choices": [{"message": {"content": "hello"}}]}
501 },
502 "assertions": [{"type": "not_error"}]
503 }"#;
504 let fixture: Fixture = serde_json::from_str(json).unwrap();
505 assert!(fixture.needs_mock_server());
506 assert!(!fixture.is_streaming_mock());
507 assert_eq!(fixture.mock_response.unwrap().status, 200);
508 }
509
510 #[test]
511 fn test_fixture_with_streaming_mock_response() {
512 let json = r#"{
513 "id": "test_stream",
514 "description": "Test streaming",
515 "input": {},
516 "mock_response": {
517 "status": 200,
518 "stream_chunks": [{"delta": "hello"}, {"delta": " world"}]
519 },
520 "assertions": []
521 }"#;
522 let fixture: Fixture = serde_json::from_str(json).unwrap();
523 assert!(fixture.needs_mock_server());
524 assert!(fixture.is_streaming_mock());
525 }
526
527 #[test]
528 fn test_fixture_without_mock_response() {
529 let json = r#"{
530 "id": "test_no_mock",
531 "description": "No mock",
532 "input": {},
533 "assertions": []
534 }"#;
535 let fixture: Fixture = serde_json::from_str(json).unwrap();
536 assert!(!fixture.needs_mock_server());
537 assert!(!fixture.is_streaming_mock());
538 }
539}