alef-e2e 0.15.7

Fixture-driven e2e test generator for alef
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
445
446
447
448
449
450
451
452
453
454
455
456
//! Rust argument rendering helpers.

use crate::escape::rust_raw_string;

/// Render a single argument binding and expression for a Rust e2e test call.
///
/// Returns `(binding_lines, call_expression)`.
#[allow(clippy::too_many_arguments)]
pub fn render_rust_arg(
    name: &str,
    value: &serde_json::Value,
    arg_type: &str,
    optional: bool,
    module: &str,
    fixture_id: &str,
    mock_base_url: Option<&str>,
    owned: bool,
    element_type: Option<&str>,
) -> (Vec<String>, String) {
    if arg_type == "mock_url" {
        let lines = vec![format!(
            "let {name} = format!(\"{{}}/fixtures/{{}}\", std::env::var(\"MOCK_SERVER_URL\").expect(\"MOCK_SERVER_URL not set\"), \"{fixture_id}\");"
        )];
        return (lines, format!("&{name}"));
    }
    // When the arg is a base_url and a mock server is running, use the mock server URL.
    if arg_type == "base_url" {
        if let Some(url_expr) = mock_base_url {
            return (vec![], url_expr.to_string());
        }
        // No mock server: fall through to string handling below.
    }
    if arg_type == "handle" {
        // Generate a create_engine (or equivalent) call and pass the config.
        // If the fixture has input.config, serialize it as a json_object and pass it;
        // otherwise pass None.
        use heck::ToSnakeCase;
        let constructor_name = format!("create_{}", name.to_snake_case());
        let mut lines = Vec::new();
        if value.is_null() || value.is_object() && value.as_object().unwrap().is_empty() {
            lines.push(format!(
                "let {name} = {constructor_name}(None).expect(\"handle creation should succeed\");"
            ));
        } else {
            // Serialize the config JSON and deserialize at runtime.
            let json_literal = serde_json::to_string(value).unwrap_or_default();
            let escaped = json_literal.replace('\\', "\\\\").replace('"', "\\\"");
            lines.push(format!(
                "let {name}_config: CrawlConfig = serde_json::from_str(\"{escaped}\").expect(\"config should parse\");"
            ));
            lines.push(format!(
                "let {name} = {constructor_name}(Some({name}_config)).expect(\"handle creation should succeed\");"
            ));
        }
        return (lines, format!("&{name}"));
    }
    if arg_type == "json_object" {
        return render_json_object_arg(name, value, optional, owned, element_type, module);
    }
    if value.is_null() && !optional {
        // Required arg with no fixture value: use a language-appropriate default.
        let default_val = match arg_type {
            "string" => "String::new()".to_string(),
            "int" | "integer" => "0".to_string(),
            "float" | "number" => "0.0_f64".to_string(),
            "bool" | "boolean" => "false".to_string(),
            _ => "Default::default()".to_string(),
        };
        // String args are passed by reference in Rust.
        let expr = if arg_type == "string" {
            format!("&{name}")
        } else {
            name.to_string()
        };
        return (vec![format!("let {name} = {default_val};")], expr);
    }
    // Bytes args whose fixture value is a string are treated as relative file paths into
    // test_documents/. Emit `std::fs::read(...)` to load the binary content at test-run
    // time instead of passing the path string as inline bytes via `.as_bytes()`.
    // This matches the upstream behaviour introduced in alef-e2e commit 9133eb3b.
    if arg_type == "bytes" {
        if let serde_json::Value::String(path_str) = value {
            // File-path value: load via std::fs::read at test-run time.
            let binding = format!(
                "let {name} = std::fs::read(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../test_documents/{path_str}\")).expect(\"test_documents/{path_str} must exist\");"
            );
            let call_expr = if owned { name.to_string() } else { format!("&{name}") };
            return (vec![binding], call_expr);
        }
        // Null optional bytes → None binding.
        if value.is_null() && optional {
            return (
                vec![format!("let {name}: Option<Vec<u8>> = None;")],
                format!("{name}.as_deref().map(|v| v.as_slice())"),
            );
        }
    }
    // file_path args are fixture-relative paths into the repo-root `test_documents/`
    // directory; resolve to a `&'static str` absolute path at compile time so the test
    // can run from any cwd without depending on the current working directory.
    if arg_type == "file_path" {
        if let serde_json::Value::String(path_str) = value {
            let binding = format!(
                "let {name}: &str = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../test_documents/\", \"{path_str}\");"
            );
            return (vec![binding], name.to_string());
        }
    }

    let literal = json_to_rust_literal(value, arg_type);
    // String args are raw string literals (`r#"..."#`) — already `&str`, no extra `&` needed.
    // Bytes args without a file-path value are passed by reference using `.as_bytes()` below.
    let optional_expr = |n: &str| {
        if arg_type == "string" {
            format!("{n}.as_deref()")
        } else if arg_type == "bytes" {
            format!("{n}.as_deref().map(|v| v.as_slice())")
        } else {
            // Owned numeric / bool / generic: pass the Option<T> by value.
            // Function signature shape `Option<T>` matches without `.as_ref()`,
            // which would produce `Option<&T>` and fail to coerce.
            n.to_string()
        }
    };
    let expr = |n: &str| {
        if arg_type == "bytes" {
            format!("{n}.as_bytes()")
        } else if arg_type == "string" && owned {
            // Owned string: caller expects `String` by value, not `&str`.
            format!("{n}.to_string()")
        } else {
            n.to_string()
        }
    };
    if optional && value.is_null() {
        let none_decl = match arg_type {
            "string" => format!("let {name}: Option<String> = None;"),
            "bytes" => format!("let {name}: Option<Vec<u8>> = None;"),
            _ => format!("let {name} = None;"),
        };
        (vec![none_decl], optional_expr(name))
    } else if optional {
        (vec![format!("let {name} = Some({literal});")], optional_expr(name))
    } else {
        (vec![format!("let {name} = {literal};")], expr(name))
    }
}

/// Render a `json_object` argument: serialize the fixture JSON as a `serde_json::json!` literal
/// and deserialize it through serde at runtime. Type inference from the function signature
/// determines the concrete type, keeping the generator generic.
///
/// `owned` — when true the binding is passed by value (no leading `&`); use for `Vec<T>` params.
/// `element_type` — when set, emits `Vec<element_type>` annotation to satisfy type inference for
///   `&[T]` parameters where `serde_json::from_value` cannot resolve the unsized slice type.
fn render_json_object_arg(
    name: &str,
    value: &serde_json::Value,
    optional: bool,
    owned: bool,
    element_type: Option<&str>,
    _module: &str,
) -> (Vec<String>, String) {
    // Owned params (Vec<T>) are passed by value; ref params (most configs) use &.
    let pass_by_ref = !owned;

    if value.is_null() && optional {
        // Use Default::default() — Rust functions take &T (or T for owned), not Option<T>.
        let expr = if pass_by_ref {
            format!("&{name}")
        } else {
            name.to_string()
        };
        return (vec![format!("let {name} = Default::default();")], expr);
    }

    // Fixture keys are camelCase; the Rust ConversionOptions type uses snake_case serde.
    // Normalize keys before building the json! literal so deserialization succeeds.
    let normalized = super::super::normalize_json_keys_to_snake_case(value);
    // Build the json! macro invocation from the fixture object.
    let json_literal = json_value_to_macro_literal(&normalized);
    let mut lines = Vec::new();
    lines.push(format!("let {name}_json = serde_json::json!({json_literal});"));

    // When an explicit element type is given, annotate with Vec<T> so that
    // serde_json::from_value can infer the element type for &[T] parameters (A4 fix).
    let deser_expr = if let Some(elem) = element_type {
        format!("serde_json::from_value::<Vec<{elem}>>({name}_json).unwrap()")
    } else {
        format!("serde_json::from_value({name}_json).unwrap()")
    };

    // A1 fix: always deser as T (never wrap in Some()); optional non-null args target
    // &T not &Option<T>. Pass as &T (ref) or T (owned) depending on the `owned` flag.
    lines.push(format!("let {name} = {deser_expr};"));
    let expr = if pass_by_ref {
        format!("&{name}")
    } else {
        name.to_string()
    };
    (lines, expr)
}

/// Convert a `serde_json::Value` into a string suitable for the `serde_json::json!()` macro.
pub fn json_value_to_macro_literal(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Bool(b) => format!("{b}"),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => {
            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
            format!("\"{escaped}\"")
        }
        serde_json::Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(json_value_to_macro_literal).collect();
            format!("[{}]", items.join(", "))
        }
        serde_json::Value::Object(obj) => {
            let entries: Vec<String> = obj
                .iter()
                .map(|(k, v)| {
                    let escaped_key = k.replace('\\', "\\\\").replace('"', "\\\"");
                    format!("\"{escaped_key}\": {}", json_value_to_macro_literal(v))
                })
                .collect();
            format!("{{{}}}", entries.join(", "))
        }
    }
}

pub fn json_to_rust_literal(value: &serde_json::Value, arg_type: &str) -> String {
    match value {
        serde_json::Value::Null => "None".to_string(),
        serde_json::Value::Bool(b) => format!("{b}"),
        serde_json::Value::Number(n) => {
            if arg_type.contains("float") || arg_type.contains("f64") || arg_type.contains("f32") {
                if let Some(f) = n.as_f64() {
                    return format!("{f}_f64");
                }
            }
            n.to_string()
        }
        serde_json::Value::String(s) => rust_raw_string(s),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
            let json_str = serde_json::to_string(value).unwrap_or_default();
            let literal = rust_raw_string(&json_str);
            format!("serde_json::from_str({literal}).unwrap()")
        }
    }
}

/// Resolve the visitor trait name from the Rust e2e call override config.
///
/// Returns `Some(trait_name)` when `visitor_trait` is configured in the Rust
/// override, or `None` when unconfigured. Callers must treat `None` as a
/// codegen error when a fixture declares a `visitor` block.
pub fn resolve_visitor_trait(rust_override: Option<&crate::config::CallOverride>) -> Option<String> {
    rust_override.and_then(|o| o.visitor_trait.clone())
}

/// Emit a Rust visitor method for a callback action.
///
/// The parameter type list mirrors the `HtmlVisitor` trait in
/// `kreuzberg-dev/html-to-markdown`. For non-template actions params are bound
/// to `_name` patterns so the generated body needn't introduce unused bindings
/// (clippy `-D warnings` would otherwise fire). For `CustomTemplate` actions
/// the template string may reference named variables via `{name}` interpolation,
/// so those params are exposed with their real names and any `Option<T>` ones
/// that appear in the template are unwrapped with `.unwrap_or_default()`.
pub fn emit_rust_visitor_method(out: &mut String, method_name: &str, action: &crate::fixture::CallbackAction) {
    use std::fmt::Write as FmtWrite;

    // Each method entry: list of (name, type_str) pairs, excluding `&mut self`.
    // Types match the `HtmlVisitor` trait exactly.
    // `_ctx` is always first; subsequent params vary by method.
    let raw_params: &[(&str, &str)] = match method_name {
        "visit_link" => &[
            ("ctx", "&NodeContext"),
            ("href", "&str"),
            ("text", "&str"),
            ("title", "Option<&str>"),
        ],
        "visit_image" => &[
            ("ctx", "&NodeContext"),
            ("src", "&str"),
            ("alt", "&str"),
            ("title", "Option<&str>"),
        ],
        "visit_heading" => &[
            ("ctx", "&NodeContext"),
            ("level", "u32"),
            ("text", "&str"),
            ("id", "Option<&str>"),
        ],
        "visit_code_block" => &[("ctx", "&NodeContext"), ("lang", "Option<&str>"), ("code", "&str")],
        "visit_code_inline"
        | "visit_strong"
        | "visit_emphasis"
        | "visit_strikethrough"
        | "visit_underline"
        | "visit_subscript"
        | "visit_superscript"
        | "visit_mark"
        | "visit_button"
        | "visit_summary"
        | "visit_figcaption"
        | "visit_definition_term"
        | "visit_definition_description" => &[("ctx", "&NodeContext"), ("text", "&str")],
        "visit_text" => &[("ctx", "&NodeContext"), ("text", "&str")],
        "visit_list_item" => &[
            ("ctx", "&NodeContext"),
            ("ordered", "bool"),
            ("marker", "&str"),
            ("text", "&str"),
        ],
        "visit_blockquote" => &[("ctx", "&NodeContext"), ("content", "&str"), ("depth", "usize")],
        "visit_table_row" => &[("ctx", "&NodeContext"), ("cells", "&[String]"), ("is_header", "bool")],
        "visit_custom_element" => &[("ctx", "&NodeContext"), ("tag_name", "&str"), ("html", "&str")],
        "visit_form" => &[
            ("ctx", "&NodeContext"),
            ("action", "Option<&str>"),
            ("method", "Option<&str>"),
        ],
        "visit_input" => &[
            ("ctx", "&NodeContext"),
            ("input_type", "&str"),
            ("name", "Option<&str>"),
            ("value", "Option<&str>"),
        ],
        "visit_audio" | "visit_video" | "visit_iframe" => &[("ctx", "&NodeContext"), ("src", "Option<&str>")],
        "visit_details" => &[("ctx", "&NodeContext"), ("open", "bool")],
        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
            &[("ctx", "&NodeContext"), ("output", "&str")]
        }
        "visit_list_start" => &[("ctx", "&NodeContext"), ("ordered", "bool")],
        "visit_list_end" => &[("ctx", "&NodeContext"), ("ordered", "bool"), ("output", "&str")],
        _ => &[("ctx", "&NodeContext")],
    };

    let is_template = matches!(action, crate::fixture::CallbackAction::CustomTemplate { .. });

    // Determine which names the template references (only relevant for CustomTemplate).
    let template_vars: std::collections::HashSet<String> =
        if let crate::fixture::CallbackAction::CustomTemplate { template } = action {
            // Extract `{name}` patterns from the template string.
            let mut vars = std::collections::HashSet::new();
            let mut chars = template.chars().peekable();
            while let Some(c) = chars.next() {
                if c == '{' {
                    let mut var = String::new();
                    for inner in chars.by_ref() {
                        if inner == '}' {
                            break;
                        }
                        var.push(inner);
                    }
                    if !var.is_empty() {
                        vars.insert(var);
                    }
                }
            }
            vars
        } else {
            std::collections::HashSet::new()
        };

    // Build the param list: use `_name` unless this is a template action AND the
    // name appears in the template (in which case it must be addressable by name).
    let params_str: String = raw_params
        .iter()
        .map(|(name, ty)| {
            if is_template && template_vars.contains(*name) {
                format!("{name}: {ty}")
            } else {
                format!("_{name}: {ty}")
            }
        })
        .collect::<Vec<_>>()
        .join(", ");

    let _ = writeln!(
        out,
        "        fn {method_name}(&mut self, {params_str}) -> VisitResult {{"
    );

    match action {
        crate::fixture::CallbackAction::Skip => {
            let _ = writeln!(out, "            VisitResult::Skip");
        }
        crate::fixture::CallbackAction::Continue => {
            let _ = writeln!(out, "            VisitResult::Continue");
        }
        crate::fixture::CallbackAction::PreserveHtml => {
            let _ = writeln!(out, "            VisitResult::PreserveHtml");
        }
        crate::fixture::CallbackAction::Custom { output } => {
            let escaped = crate::escape::escape_rust(output);
            let _ = writeln!(out, "            VisitResult::Custom(\"{escaped}\".to_string())");
        }
        crate::fixture::CallbackAction::CustomTemplate { template } => {
            // For any template-referenced param that is `Option<T>`, emit a shadow
            // `let name = name.unwrap_or_default();` so the format! string can use it.
            for (name, ty) in raw_params {
                if template_vars.contains(*name) && ty.starts_with("Option<") {
                    let _ = writeln!(out, "            let {name} = {name}.unwrap_or_default();");
                }
            }
            let escaped = crate::escape::escape_rust(template);
            let _ = writeln!(out, "            VisitResult::Custom(format!(\"{escaped}\"))");
        }
    }
    let _ = writeln!(out, "        }}");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn json_value_to_macro_literal_null() {
        let v = serde_json::Value::Null;
        assert_eq!(json_value_to_macro_literal(&v), "null");
    }

    #[test]
    fn json_value_to_macro_literal_string_escapes_quotes() {
        let v = serde_json::Value::String("hello \"world\"".to_string());
        let out = json_value_to_macro_literal(&v);
        assert!(out.contains("\\\""));
    }

    #[test]
    fn json_to_rust_literal_null_returns_none() {
        let out = json_to_rust_literal(&serde_json::Value::Null, "string");
        assert_eq!(out, "None");
    }

    #[test]
    fn resolve_visitor_trait_uses_config() {
        use crate::config::CallOverride;

        let override_with_trait = CallOverride {
            visitor_trait: Some("HtmlVisitor".to_string()),
            ..Default::default()
        };
        assert_eq!(
            resolve_visitor_trait(Some(&override_with_trait)),
            Some("HtmlVisitor".to_string())
        );

        let override_without_trait = CallOverride::default();
        assert_eq!(resolve_visitor_trait(Some(&override_without_trait)), None);

        assert_eq!(resolve_visitor_trait(None), None);
    }
}