alef 0.38.2

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Shared HTTP-test driver.
//!
//! Calls trait primitives on a [`TestClientRenderer`] in the canonical order
//! a TestClient-driven test takes:
//!
//! 1. `render_test_open` — doc, signature, opening brace, language-native skip annotation.
//! 2. `render_call` — `let response = client.METHOD(...)`.
//! 3. `render_assert_status` — status code assertion.
//! 4. `render_assert_header` (per header) — header assertions.
//! 5. `render_assert_json_body` / `render_assert_partial_body` — body assertion.
//! 6. `render_assert_validation_errors` — 422 validation errors, if present.
//! 7. `render_test_close` — closing brace / `end`.
//!
//! Steps 3-6 are skipped automatically when the corresponding expectation is empty.

use super::{CallCtx, TestClientRenderer, has_meaningful_body, is_skipped};
use crate::e2e::fixture::Fixture;

/// Default name for the response binding inside a generated test.
pub const DEFAULT_RESPONSE_VAR: &str = "response";

/// Render a single HTTP test for `fixture` to `out` using `renderer`.
///
/// Returns `true` if a test was emitted (the fixture has an `http` block),
/// `false` otherwise — caller is responsible for handling non-HTTP fixtures
/// (WebSocket, AsyncAPI spec validation, etc.) via different drivers.
pub fn render_http_test<R: TestClientRenderer + ?Sized>(out: &mut String, renderer: &R, fixture: &Fixture) -> bool {
    let Some(http) = fixture.http.as_ref() else {
        return false;
    };

    let fn_name = renderer.sanitize_test_name(&fixture.id);

    let skip_reason = if is_skipped(fixture, renderer.language_name()) {
        Some(
            fixture
                .skip
                .as_ref()
                .and_then(|s| s.reason.as_deref())
                .unwrap_or("skipped"),
        )
    } else {
        None
    };

    renderer.render_test_open(out, &fn_name, &fixture.description, skip_reason);

    if skip_reason.is_some() {
        // For some languages, render_test_open already emitted a stub body; in
        // those cases render_test_close is still required for symmetry. Calls
        // below are gated on the renderer's expectations.
        renderer.render_test_close(out);
        return true;
    }

    let response_var = DEFAULT_RESPONSE_VAR;
    // For server-pattern e2e tests: build the full path to the fixture handler.
    // Path combines the fixture ID namespace with the actual fixture request path:
    // `/fixtures/{fixture.id}{request.path}` (e.g., `/fixtures/put_create_if_not_exists/items/999`)
    // Using request.path ensures parameterized routes are replaced with actual values.
    let request_path = &http.request.path;
    let namespaced_path = format!("/fixtures/{}{}", fixture.id, request_path);
    let req = &http.request;

    // Synthesize a multipart/form-data body when the fixture declares that
    // content type but carries no explicit request body, mirroring the
    // python/ruby/typescript generators. Without this the TestClient-driven
    // request goes out empty and the core rejects it with 422 (required binary
    // field missing) before the handler is reached. The synthesized body is a
    // raw string; each renderer's `render_call` escapes it for its language.
    let synthesized_multipart = synthesize_multipart_request(http);
    let (synth_body, synth_ct) = match &synthesized_multipart {
        Some(body) => (Some(body), Some("multipart/form-data; boundary=alef-boundary")),
        None => (None, None),
    };

    let ctx = CallCtx {
        method: req.method.as_str(),
        path: &namespaced_path,
        headers: &req.headers,
        query_params: &req.query_params,
        cookies: &req.cookies,
        body: req.body.as_ref().or(synth_body),
        content_type: synth_ct.or(req.content_type.as_deref()),
        response_var,
    };
    renderer.render_call(out, &ctx);

    renderer.render_assert_status(out, response_var, http.expected_response.status_code);

    // Emit header assertions in deterministic (sorted) order so generated
    // output is stable across cargo invocations.
    let mut header_names: Vec<&String> = http.expected_response.headers.keys().collect();
    header_names.sort();
    for name in header_names {
        let value = &http.expected_response.headers[name];
        if name.eq_ignore_ascii_case("content-encoding") {
            // Mock layer strips Content-Encoding before delivering the body;
            // asserting on it is a known false-positive source.
            continue;
        }
        renderer.render_assert_header(out, response_var, name, value);
    }

    if has_meaningful_body(&http.expected_response) {
        if let Some(body) = http.expected_response.body.as_ref() {
            renderer.render_assert_json_body(out, response_var, body);
        }
    }

    if let Some(partial) = http.expected_response.body_partial.as_ref() {
        renderer.render_assert_partial_body(out, response_var, partial);
    }

    if let Some(errors) = http.expected_response.validation_errors.as_ref() {
        if !errors.is_empty() {
            renderer.render_assert_validation_errors(out, response_var, errors);
        }
    }

    renderer.render_test_close(out);
    true
}

/// Boundary marker shared by every synthesized multipart body.
const MULTIPART_BOUNDARY: &str = "alef-boundary";

/// Synthesize a `multipart/form-data` request body from the handler's body
/// schema when the fixture declares that content type but carries no explicit
/// body. Returns the raw body as a JSON string value (each renderer escapes it
/// for its own language), or `None` when synthesis does not apply.
fn synthesize_multipart_request(http: &crate::e2e::fixture::HttpFixture) -> Option<serde_json::Value> {
    if http.request.body.is_some() {
        return None;
    }

    let content_type = http
        .request
        .headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
        .map(|(_, v)| v.to_ascii_lowercase())
        .or_else(|| http.request.content_type.as_ref().map(|c| c.to_ascii_lowercase()))
        .unwrap_or_default();
    let is_multipart = content_type
        .split(';')
        .next()
        .map(str::trim)
        .is_some_and(|t| t.eq_ignore_ascii_case("multipart/form-data"));
    if !is_multipart {
        return None;
    }

    let schema = http.handler.body_schema.as_ref()?;
    if schema.get("type").and_then(|t| t.as_str()) != Some("object") {
        return None;
    }
    let props = schema.get("properties").and_then(|p| p.as_object())?;
    Some(serde_json::Value::String(synthesize_multipart_body_raw(props)))
}

/// Build the raw multipart body: one part per schema property, with a filename
/// and `text/plain` part for `format: binary` fields and a plain value
/// otherwise.
fn synthesize_multipart_body_raw(props: &serde_json::Map<String, serde_json::Value>) -> String {
    let mut body = String::new();
    for (prop_name, prop_schema) in props {
        let is_binary = prop_schema
            .get("format")
            .and_then(|f| f.as_str())
            .is_some_and(|f| f == "binary");
        body.push_str(&format!(
            "--{MULTIPART_BOUNDARY}\r\nContent-Disposition: form-data; name=\"{prop_name}\""
        ));
        if is_binary {
            body.push_str(&format!(
                "; filename=\"{prop_name}.txt\"\r\nContent-Type: text/plain\r\n\r\nplaceholder content"
            ));
        } else {
            body.push_str("\r\n\r\nsample");
        }
        body.push_str("\r\n");
    }
    body.push_str(&format!("--{MULTIPART_BOUNDARY}--\r\n"));
    body
}

#[cfg(test)]
mod tests {
    use super::super::{CallCtx, TestClientRenderer};
    use super::render_http_test;
    use crate::e2e::fixture::{Fixture, HttpExpectedResponse, HttpFixture, HttpRequest, ValidationErrorExpectation};
    use std::collections::BTreeMap;

    /// Mock renderer that records every call as a tag in `out`. Lets us assert
    /// the exact sequence of trait calls the shared driver makes for each
    /// expected-response shape.
    struct TagRenderer;

    impl TestClientRenderer for TagRenderer {
        fn language_name(&self) -> &'static str {
            "mock"
        }
        fn render_test_open(&self, out: &mut String, fn_name: &str, _: &str, skip: Option<&str>) {
            let skip_marker = skip.map(|r| format!("|skip={r}")).unwrap_or_default();
            out.push_str(&format!("OPEN({fn_name}{skip_marker})\n"));
        }
        fn render_test_close(&self, out: &mut String) {
            out.push_str("CLOSE\n");
        }
        fn render_call(&self, out: &mut String, ctx: &CallCtx<'_>) {
            out.push_str(&format!("CALL({} {} -> {})\n", ctx.method, ctx.path, ctx.response_var));
        }
        fn render_assert_status(&self, out: &mut String, _: &str, status: u16) {
            out.push_str(&format!("STATUS={status}\n"));
        }
        fn render_assert_header(&self, out: &mut String, _: &str, name: &str, value: &str) {
            out.push_str(&format!("HEADER({name}={value})\n"));
        }
        fn render_assert_json_body(&self, out: &mut String, _: &str, expected: &serde_json::Value) {
            out.push_str(&format!("JSON_BODY({expected})\n"));
        }
        fn render_assert_partial_body(&self, out: &mut String, _: &str, expected: &serde_json::Value) {
            out.push_str(&format!("PARTIAL_BODY({expected})\n"));
        }
        fn render_assert_validation_errors(&self, out: &mut String, _: &str, errors: &[ValidationErrorExpectation]) {
            out.push_str(&format!("VALIDATION({})\n", errors.len()));
        }
    }

    fn http_fixture(id: &str, expected: HttpExpectedResponse) -> Fixture {
        Fixture {
            id: id.into(),
            description: "test".into(),
            category: Some("smoke".into()),
            tags: vec![],
            skip: None,
            env: None,
            setup: Vec::new(),
            call: None,
            input: serde_json::Value::Null,
            mock_response: None,
            visitor: None,
            args: vec![],
            assertion_recipes: vec![],
            assertions: vec![],
            source: String::new(),
            http: Some(HttpFixture {
                handler: crate::e2e::fixture::HttpHandler {
                    route: String::new(),
                    method: "GET".into(),
                    body_schema: None,
                    parameters: BTreeMap::new(),
                    middleware: None,
                },
                request: HttpRequest {
                    method: "GET".into(),
                    path: String::new(),
                    headers: BTreeMap::new(),
                    query_params: BTreeMap::new(),
                    cookies: BTreeMap::new(),
                    body: None,
                    form_data: None,
                    content_type: None,
                },
                expected_response: expected,
            }),
        }
    }

    fn empty_expected(status: u16) -> HttpExpectedResponse {
        HttpExpectedResponse {
            status_code: status,
            body: None,
            body_partial: None,
            headers: BTreeMap::new(),
            validation_errors: None,
        }
    }

    #[test]
    fn driver_emits_open_call_status_close_in_order() {
        let fixture = http_fixture("simple", empty_expected(200));
        let mut out = String::new();
        let emitted = render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(emitted);
        assert_eq!(
            out,
            "OPEN(simple)\nCALL(GET /fixtures/simple -> response)\nSTATUS=200\nCLOSE\n"
        );
    }

    #[test]
    fn driver_skips_when_no_http_block() {
        let mut fixture = http_fixture("noop", empty_expected(200));
        fixture.http = None;
        let mut out = String::new();
        let emitted = render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(!emitted);
        assert!(out.is_empty());
    }

    #[test]
    fn driver_emits_skip_marker_and_short_circuits_assertions() {
        let mut fixture = http_fixture("skipme", empty_expected(200));
        fixture.skip = Some(crate::e2e::fixture::SkipDirective {
            languages: vec!["mock".into()],
            reason: Some("not yet".into()),
        });
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(out.contains("OPEN(skipme|skip=not yet)"));
        assert!(out.contains("CLOSE"));
        assert!(!out.contains("CALL"));
        assert!(!out.contains("STATUS"));
    }

    #[test]
    fn driver_strips_content_encoding_header_assertion() {
        let mut expected = empty_expected(200);
        expected.headers.insert("Content-Encoding".into(), "gzip".into());
        expected.headers.insert("X-Foo".into(), "bar".into());
        let fixture = http_fixture("hdr", expected);
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(!out.contains("HEADER(Content-Encoding"));
        assert!(out.contains("HEADER(X-Foo=bar)"));
    }

    #[test]
    fn driver_emits_headers_in_sorted_order() {
        let mut expected = empty_expected(200);
        expected.headers.insert("Z-Header".into(), "z".into());
        expected.headers.insert("A-Header".into(), "a".into());
        expected.headers.insert("M-Header".into(), "m".into());
        let fixture = http_fixture("hdr", expected);
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        let a_pos = out.find("HEADER(A-Header").unwrap();
        let m_pos = out.find("HEADER(M-Header").unwrap();
        let z_pos = out.find("HEADER(Z-Header").unwrap();
        assert!(a_pos < m_pos);
        assert!(m_pos < z_pos);
    }

    #[test]
    fn driver_skips_body_assert_for_null_and_empty_string_sentinels() {
        let mut expected = empty_expected(200);
        expected.body = Some(serde_json::Value::Null);
        let fixture = http_fixture("nullbody", expected);
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(!out.contains("JSON_BODY"));

        let mut expected = empty_expected(200);
        expected.body = Some(serde_json::Value::String(String::new()));
        let fixture = http_fixture("emptybody", expected);
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(!out.contains("JSON_BODY"));
    }

    #[test]
    fn driver_emits_body_partial_assertion_independently_of_body() {
        let mut expected = empty_expected(200);
        expected.body_partial = Some(serde_json::json!({"k": "v"}));
        let fixture = http_fixture("partial", expected);
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(out.contains("PARTIAL_BODY"));
    }

    #[test]
    fn driver_emits_validation_errors_assertion_when_present_and_nonempty() {
        let mut expected = empty_expected(422);
        expected.validation_errors = Some(vec![ValidationErrorExpectation {
            loc: vec!["name".into()],
            msg: "field required".into(),
            error_type: "missing".into(),
        }]);
        let fixture = http_fixture("ve", expected);
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(out.contains("VALIDATION(1)"));

        // Empty vec → no assertion
        let mut expected = empty_expected(422);
        expected.validation_errors = Some(vec![]);
        let fixture = http_fixture("ve_empty", expected);
        let mut out = String::new();
        render_http_test(&mut out, &TagRenderer, &fixture);
        assert!(!out.contains("VALIDATION"));
    }

    #[test]
    fn synthesizes_multipart_body_for_schema_only_fixture() {
        let mut fixture = http_fixture("upload", empty_expected(200));
        {
            let http = fixture.http.as_mut().unwrap();
            http.request.content_type = Some("multipart/form-data".into());
            http.handler.body_schema = Some(serde_json::json!({
                "type": "object",
                "properties": { "file": { "type": "string", "format": "binary" } },
                "required": ["file"],
            }));
        }
        let body = super::synthesize_multipart_request(fixture.http.as_ref().unwrap())
            .expect("multipart body should be synthesized");
        let raw = body.as_str().unwrap();
        assert!(raw.contains("--alef-boundary"));
        assert!(raw.contains("name=\"file\""));
        assert!(raw.contains("filename=\"file.txt\""));
        assert!(raw.contains("placeholder content"));
        assert!(raw.ends_with("--alef-boundary--\r\n"));
    }

    #[test]
    fn no_multipart_synthesis_when_body_present_or_not_multipart() {
        // An explicit request body is used verbatim — never overridden.
        let mut with_body = http_fixture("explicit", empty_expected(200));
        {
            let http = with_body.http.as_mut().unwrap();
            http.request.content_type = Some("multipart/form-data".into());
            http.request.body = Some(serde_json::json!("verbatim"));
            http.handler.body_schema = Some(serde_json::json!({
                "type": "object",
                "properties": { "f": { "type": "string", "format": "binary" } },
            }));
        }
        assert!(super::synthesize_multipart_request(with_body.http.as_ref().unwrap()).is_none());

        // A non-multipart content type is left alone.
        let mut json_req = http_fixture("json", empty_expected(200));
        {
            let http = json_req.http.as_mut().unwrap();
            http.request.content_type = Some("application/json".into());
            http.handler.body_schema = Some(serde_json::json!({
                "type": "object",
                "properties": { "f": { "type": "string" } },
            }));
        }
        assert!(super::synthesize_multipart_request(json_req.http.as_ref().unwrap()).is_none());
    }
}