Skip to main content

alef_e2e/
fixture.rs

1//! Fixture loading, validation, and grouping for e2e test generation.
2
3use anyhow::{Context, Result, bail};
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::path::Path;
7
8/// Mock HTTP response for testing HTTP clients.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct MockResponse {
11    /// HTTP status code.
12    pub status: u16,
13    /// JSON response body (for non-streaming responses).
14    #[serde(default)]
15    pub body: Option<serde_json::Value>,
16    /// SSE stream chunks (for streaming responses).
17    /// Each chunk is a JSON object sent as `data: <chunk>\n\n`.
18    #[serde(default)]
19    pub stream_chunks: Option<Vec<serde_json::Value>>,
20    /// Response headers to apply to the mock response.
21    /// Bridged from `http.expected_response.headers` for spikard-style fixtures.
22    #[serde(default)]
23    pub headers: HashMap<String, String>,
24}
25
26/// Visitor specification for visitor pattern tests.
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct VisitorSpec {
29    /// Map of callback method name to action.
30    pub callbacks: HashMap<String, CallbackAction>,
31}
32
33/// Action a visitor callback should take.
34#[derive(Debug, Clone, Serialize, Deserialize)]
35#[serde(tag = "action")]
36pub enum CallbackAction {
37    /// Return VisitResult::Skip.
38    #[serde(rename = "skip")]
39    Skip,
40    /// Return VisitResult::Continue.
41    #[serde(rename = "continue")]
42    Continue,
43    /// Return VisitResult::PreserveHtml.
44    #[serde(rename = "preserve_html")]
45    PreserveHtml,
46    /// Return VisitResult::Custom with static output.
47    #[serde(rename = "custom")]
48    Custom {
49        /// The static replacement string.
50        output: String,
51    },
52    /// Return VisitResult::Custom with template interpolation.
53    #[serde(rename = "custom_template")]
54    CustomTemplate {
55        /// Template with placeholders like {text}, {href}.
56        template: String,
57    },
58}
59
60/// A single e2e test fixture.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct Fixture {
63    /// Unique identifier (used as test function name).
64    pub id: String,
65    /// Optional category (defaults to parent directory name).
66    #[serde(default)]
67    pub category: Option<String>,
68    /// Human-readable description.
69    pub description: String,
70    /// Optional tags for filtering.
71    #[serde(default)]
72    pub tags: Vec<String>,
73    /// Skip directive.
74    #[serde(default)]
75    pub skip: Option<SkipDirective>,
76    /// Named call config to use (references `[e2e.calls.<name>]`).
77    /// When omitted, uses the default `[e2e.call]`.
78    #[serde(default)]
79    pub call: Option<String>,
80    /// Input data passed to the function under test.
81    #[serde(default)]
82    pub input: serde_json::Value,
83    /// Optional mock HTTP response for testing HTTP clients.
84    #[serde(default)]
85    pub mock_response: Option<MockResponse>,
86    /// Optional visitor specification for visitor pattern tests.
87    #[serde(default)]
88    pub visitor: Option<VisitorSpec>,
89    /// List of assertions to check.
90    #[serde(default)]
91    pub assertions: Vec<Assertion>,
92    /// Source file path (populated during loading).
93    #[serde(skip)]
94    pub source: String,
95    /// HTTP server test specification. When present, this fixture tests
96    /// an HTTP handler rather than a function call.
97    #[serde(default)]
98    pub http: Option<HttpFixture>,
99}
100
101/// HTTP server test specification.
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct HttpFixture {
104    /// Handler/route definition.
105    pub handler: HttpHandler,
106    /// The HTTP request to send.
107    pub request: HttpRequest,
108    /// Expected response.
109    pub expected_response: HttpExpectedResponse,
110}
111
112/// Handler/route definition for HTTP server tests.
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct HttpHandler {
115    /// Route pattern (e.g., "/users/{user_id}").
116    pub route: String,
117    /// HTTP method (GET, POST, PUT, etc.).
118    pub method: String,
119    /// JSON Schema for request body validation.
120    #[serde(default)]
121    pub body_schema: Option<serde_json::Value>,
122    /// Parameter schemas by source (path, query, header, cookie).
123    #[serde(default)]
124    pub parameters: HashMap<String, HashMap<String, serde_json::Value>>,
125    /// Middleware configuration.
126    #[serde(default)]
127    pub middleware: Option<HttpMiddleware>,
128}
129
130/// HTTP request to send in a server test.
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct HttpRequest {
133    pub method: String,
134    pub path: String,
135    #[serde(default)]
136    pub headers: HashMap<String, String>,
137    #[serde(default)]
138    pub query_params: HashMap<String, serde_json::Value>,
139    #[serde(default)]
140    pub cookies: HashMap<String, String>,
141    #[serde(default)]
142    pub body: Option<serde_json::Value>,
143    #[serde(default)]
144    pub content_type: Option<String>,
145}
146
147/// Expected HTTP response specification.
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct HttpExpectedResponse {
150    pub status_code: u16,
151    /// Exact body match.
152    #[serde(default)]
153    pub body: Option<serde_json::Value>,
154    /// Partial body match (only check specified fields).
155    #[serde(default)]
156    pub body_partial: Option<serde_json::Value>,
157    /// Header expectations. Special tokens: `<<uuid>>`, `<<present>>`, `<<absent>>`.
158    #[serde(default)]
159    pub headers: HashMap<String, String>,
160    /// Expected validation errors (for 422 responses).
161    #[serde(default)]
162    pub validation_errors: Option<Vec<ValidationErrorExpectation>>,
163}
164
165/// Expected validation error entry.
166#[derive(Debug, Clone, Serialize, Deserialize)]
167pub struct ValidationErrorExpectation {
168    pub loc: Vec<String>,
169    pub msg: String,
170    #[serde(rename = "type")]
171    pub error_type: String,
172}
173
174/// Middleware configuration for HTTP handler tests.
175#[derive(Debug, Clone, Default, Serialize, Deserialize)]
176pub struct HttpMiddleware {
177    #[serde(default)]
178    pub jwt_auth: Option<serde_json::Value>,
179    #[serde(default)]
180    pub api_key_auth: Option<serde_json::Value>,
181    #[serde(default)]
182    pub compression: Option<serde_json::Value>,
183    #[serde(default)]
184    pub rate_limit: Option<serde_json::Value>,
185    #[serde(default)]
186    pub request_timeout: Option<serde_json::Value>,
187    #[serde(default)]
188    pub request_id: Option<serde_json::Value>,
189}
190
191impl Fixture {
192    /// Returns true if this is an HTTP server test fixture.
193    pub fn is_http_test(&self) -> bool {
194        self.http.is_some()
195    }
196
197    /// Returns true if this fixture requires a mock HTTP server.
198    /// This is true when either `mock_response` (liter-llm shape) or
199    /// `http.expected_response` (spikard shape) is present.
200    pub fn needs_mock_server(&self) -> bool {
201        self.mock_response.is_some() || self.http.is_some()
202    }
203
204    /// Returns the effective mock response for this fixture, bridging both schemas:
205    /// - liter-llm shape: `mock_response: { status, body, stream_chunks }`
206    /// - spikard shape: `http.expected_response: { status_code, body, headers }`
207    ///
208    /// Returns `None` if neither schema is present.
209    pub fn as_mock_response(&self) -> Option<MockResponse> {
210        if let Some(mock) = &self.mock_response {
211            return Some(mock.clone());
212        }
213        if let Some(http) = &self.http {
214            return Some(MockResponse {
215                status: http.expected_response.status_code,
216                body: http.expected_response.body.clone(),
217                stream_chunks: None,
218                headers: http.expected_response.headers.clone(),
219            });
220        }
221        None
222    }
223
224    /// Returns true if the mock response uses streaming (SSE).
225    pub fn is_streaming_mock(&self) -> bool {
226        self.mock_response
227            .as_ref()
228            .and_then(|m| m.stream_chunks.as_ref())
229            .map(|c| !c.is_empty())
230            .unwrap_or(false)
231    }
232
233    /// Get the resolved category (explicit or from source directory).
234    pub fn resolved_category(&self) -> String {
235        self.category.clone().unwrap_or_else(|| {
236            Path::new(&self.source)
237                .parent()
238                .and_then(|p| p.file_name())
239                .and_then(|n| n.to_str())
240                .unwrap_or("default")
241                .to_string()
242        })
243    }
244}
245
246/// Skip directive for conditionally excluding fixtures.
247#[derive(Debug, Clone, Serialize, Deserialize)]
248pub struct SkipDirective {
249    /// Languages to skip (empty means skip all).
250    #[serde(default)]
251    pub languages: Vec<String>,
252    /// Human-readable reason for skipping.
253    #[serde(default)]
254    pub reason: Option<String>,
255}
256
257impl SkipDirective {
258    /// Check if this fixture should be skipped for a given language.
259    pub fn should_skip(&self, language: &str) -> bool {
260        self.languages.is_empty() || self.languages.iter().any(|l| l == language)
261    }
262}
263
264/// A single assertion in a fixture.
265#[derive(Debug, Clone, Serialize, Deserialize)]
266pub struct Assertion {
267    /// Assertion type (equals, contains, not_empty, error, etc.).
268    #[serde(rename = "type")]
269    pub assertion_type: String,
270    /// Field path to access on the result (dot-separated).
271    #[serde(default)]
272    pub field: Option<String>,
273    /// Expected value (string, number, bool, or array depending on type).
274    #[serde(default)]
275    pub value: Option<serde_json::Value>,
276    /// Expected values (for contains_all, contains_any).
277    #[serde(default)]
278    pub values: Option<Vec<serde_json::Value>>,
279    /// Method name to call on the result (for method_result assertions).
280    #[serde(default)]
281    pub method: Option<String>,
282    /// Assertion check type for the method result (equals, is_true, is_false, greater_than_or_equal, count_min).
283    #[serde(default)]
284    pub check: Option<String>,
285    /// Arguments to pass to the method call (for method_result assertions).
286    #[serde(default)]
287    pub args: Option<serde_json::Value>,
288}
289
290/// A group of fixtures sharing the same category.
291#[derive(Debug, Clone)]
292pub struct FixtureGroup {
293    pub category: String,
294    pub fixtures: Vec<Fixture>,
295}
296
297/// Load all fixtures from a directory recursively.
298pub fn load_fixtures(dir: &Path) -> Result<Vec<Fixture>> {
299    let mut fixtures = Vec::new();
300    load_fixtures_recursive(dir, dir, &mut fixtures)?;
301
302    // Validate: check for duplicate IDs
303    let mut seen: HashMap<String, String> = HashMap::new();
304    for f in &fixtures {
305        if let Some(prev_source) = seen.get(&f.id) {
306            bail!(
307                "duplicate fixture ID '{}': found in '{}' and '{}'",
308                f.id,
309                prev_source,
310                f.source
311            );
312        }
313        seen.insert(f.id.clone(), f.source.clone());
314    }
315
316    // Sort by (category, id) for deterministic output
317    fixtures.sort_by(|a, b| {
318        let cat_cmp = a.resolved_category().cmp(&b.resolved_category());
319        cat_cmp.then_with(|| a.id.cmp(&b.id))
320    });
321
322    Ok(fixtures)
323}
324
325fn load_fixtures_recursive(base: &Path, dir: &Path, fixtures: &mut Vec<Fixture>) -> Result<()> {
326    let entries =
327        std::fs::read_dir(dir).with_context(|| format!("failed to read fixture directory: {}", dir.display()))?;
328
329    let mut paths: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
330    paths.sort();
331
332    for path in paths {
333        if path.is_dir() {
334            load_fixtures_recursive(base, &path, fixtures)?;
335        } else if path.extension().is_some_and(|ext| ext == "json") {
336            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
337            // Skip schema files and files starting with _
338            if filename == "schema.json" || filename.starts_with('_') {
339                continue;
340            }
341            let content = std::fs::read_to_string(&path)
342                .with_context(|| format!("failed to read fixture: {}", path.display()))?;
343            let relative = path.strip_prefix(base).unwrap_or(&path).to_string_lossy().to_string();
344
345            // Try parsing as array first, then as single fixture
346            let parsed: Vec<Fixture> = if content.trim_start().starts_with('[') {
347                serde_json::from_str(&content)
348                    .with_context(|| format!("failed to parse fixture array: {}", path.display()))?
349            } else {
350                let single: Fixture = serde_json::from_str(&content)
351                    .with_context(|| format!("failed to parse fixture: {}", path.display()))?;
352                vec![single]
353            };
354
355            for mut fixture in parsed {
356                fixture.source = relative.clone();
357                // Expand template expressions (e.g. `{{ repeat 'x' 10000 times }}`)
358                // in all JSON string values so generators emit the expanded values.
359                expand_json_templates(&mut fixture.input);
360                if let Some(ref mut http) = fixture.http {
361                    for (_, v) in http.request.headers.iter_mut() {
362                        *v = crate::escape::expand_fixture_templates(v);
363                    }
364                    if let Some(ref mut body) = http.request.body {
365                        expand_json_templates(body);
366                    }
367                }
368                fixtures.push(fixture);
369            }
370        }
371    }
372    Ok(())
373}
374
375/// Group fixtures by their resolved category.
376pub fn group_fixtures(fixtures: &[Fixture]) -> Vec<FixtureGroup> {
377    let mut groups: HashMap<String, Vec<Fixture>> = HashMap::new();
378    for f in fixtures {
379        groups.entry(f.resolved_category()).or_default().push(f.clone());
380    }
381    let mut result: Vec<FixtureGroup> = groups
382        .into_iter()
383        .map(|(category, fixtures)| FixtureGroup { category, fixtures })
384        .collect();
385    result.sort_by(|a, b| a.category.cmp(&b.category));
386    result
387}
388
389/// Recursively expand fixture template expressions in all string values of a JSON tree.
390fn expand_json_templates(value: &mut serde_json::Value) {
391    match value {
392        serde_json::Value::String(s) => {
393            let expanded = crate::escape::expand_fixture_templates(s);
394            if expanded != *s {
395                *s = expanded;
396            }
397        }
398        serde_json::Value::Array(arr) => {
399            for item in arr {
400                expand_json_templates(item);
401            }
402        }
403        serde_json::Value::Object(map) => {
404            for (_, v) in map.iter_mut() {
405                expand_json_templates(v);
406            }
407        }
408        _ => {}
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn test_fixture_with_mock_response() {
418        let json = r#"{
419            "id": "test_chat",
420            "description": "Test chat",
421            "call": "chat",
422            "input": {"model": "gpt-4", "messages": [{"role": "user", "content": "hi"}]},
423            "mock_response": {
424                "status": 200,
425                "body": {"choices": [{"message": {"content": "hello"}}]}
426            },
427            "assertions": [{"type": "not_error"}]
428        }"#;
429        let fixture: Fixture = serde_json::from_str(json).unwrap();
430        assert!(fixture.needs_mock_server());
431        assert!(!fixture.is_streaming_mock());
432        assert_eq!(fixture.mock_response.unwrap().status, 200);
433    }
434
435    #[test]
436    fn test_fixture_with_streaming_mock_response() {
437        let json = r#"{
438            "id": "test_stream",
439            "description": "Test streaming",
440            "input": {},
441            "mock_response": {
442                "status": 200,
443                "stream_chunks": [{"delta": "hello"}, {"delta": " world"}]
444            },
445            "assertions": []
446        }"#;
447        let fixture: Fixture = serde_json::from_str(json).unwrap();
448        assert!(fixture.needs_mock_server());
449        assert!(fixture.is_streaming_mock());
450    }
451
452    #[test]
453    fn test_fixture_without_mock_response() {
454        let json = r#"{
455            "id": "test_no_mock",
456            "description": "No mock",
457            "input": {},
458            "assertions": []
459        }"#;
460        let fixture: Fixture = serde_json::from_str(json).unwrap();
461        assert!(!fixture.needs_mock_server());
462        assert!(!fixture.is_streaming_mock());
463    }
464}