alef 0.62.4

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
//! Go e2e test file rendering.

use crate::core::hash::{self, CommentStyle};
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::Fixture;
use std::fmt::Write as FmtWrite;

use super::test_function::{GoTestFunctionContext, fixture_has_go_callable, render_test_function};
use super::visitors::{emit_go_visitor_struct, resolve_go_visitor_binding, visitor_struct_name};
use crate::e2e::codegen::resolve_field;

pub(super) struct GoTestFileContext<'a> {
    pub(super) go_module_path: &'a str,
    pub(super) import_alias: &'a str,
    pub(super) e2e_config: &'a crate::e2e::config::E2eConfig,
    pub(super) adapters: &'a [crate::core::config::AdapterConfig],
    pub(super) data_enum_names: &'a std::collections::HashSet<&'a str>,
    pub(super) config: &'a crate::core::config::ResolvedCrateConfig,
    pub(super) type_defs: &'a [crate::core::ir::TypeDef],
    pub(super) enums: &'a [crate::core::ir::EnumDef],
    pub(super) errors: &'a [crate::core::ir::ErrorDef],
}

/// Whether a fixture's `error` assertion declares a value THAT WILL RENDER AS AN ASSERTION,
/// meaning the generated `expects_error` branch will emit `fmt.Sprintf` and therefore requires
/// the `fmt` import — independent of the pre-existing visitor `CustomTemplate` heuristic.
///
/// ~keep Must consult `classify`, not just "a value is declared": a value naming an
/// unsubstantiable variant now renders `declared_error_variant::skip_line`'s bare `//` comment
/// instead of `fmt.Sprintf`, so importing `fmt` for that fixture alone would be unused and Go
/// rejects unused imports at compile time.
fn fixture_needs_fmt_for_declared_error_value(fixture: &Fixture, errors: &[crate::core::ir::ErrorDef]) -> bool {
    matches!(
        crate::e2e::codegen::declared_error_variant::classify("go", fixture, errors),
        crate::e2e::codegen::declared_error_variant::DeclaredErrorAssertion::Assert(_)
    )
}

pub(super) fn render_test_file(category: &str, fixtures: &[&Fixture], context: GoTestFileContext<'_>) -> String {
    let GoTestFileContext {
        go_module_path,
        import_alias,
        e2e_config,
        adapters,
        data_enum_names,
        config,
        type_defs,
        enums,
        errors,
    } = context;
    let mut out = String::new();
    let emits_executable_test =
        |fixture: &Fixture| fixture.is_http_test() || fixture_has_go_callable(fixture, e2e_config);

    out.push_str(&hash::header(CommentStyle::DoubleSlash));
    let _ = writeln!(out);

    let needs_pkg = fixtures
        .iter()
        .any(|f| fixture_has_go_callable(f, e2e_config) || f.is_http_test() || f.visitor.is_some());

    let needs_os = fixtures.iter().any(|f| {
        if f.is_http_test() {
            return true;
        }
        if !emits_executable_test(f) {
            return false;
        }
        let call_config =
            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
        let go_override = call_config
            .overrides
            .get("go")
            .or_else(|| e2e_config.call.overrides.get("go"));
        if go_override.and_then(|o| o.client_factory.as_deref()).is_some() {
            return true;
        }
        let call_args = f.resolved_args(call_config);
        if call_args
            .iter()
            .any(|a| a.arg_type == "mock_url" || a.arg_type == "mock_url_list")
        {
            return true;
        }
        call_args.iter().any(|a| {
            if a.arg_type != "bytes" {
                return false;
            }
            let mut current = &f.input;
            let path = a.field.strip_prefix("input.").unwrap_or(&a.field);
            for segment in path.split('.') {
                match current.get(segment) {
                    Some(next) => current = next,
                    None => return false,
                }
            }
            current.is_string()
        })
    });

    let needs_filepath = false;

    let needs_json = fixtures.iter().any(|f| {
        if let Some(http) = &f.http {
            let body_needs_json = http
                .expected_response
                .body
                .as_ref()
                .is_some_and(|b| matches!(b, serde_json::Value::Object(_) | serde_json::Value::Array(_)));
            let partial_needs_json = http.expected_response.body_partial.is_some();
            let ve_needs_json = http
                .expected_response
                .validation_errors
                .as_ref()
                .is_some_and(|v| !v.is_empty());
            if body_needs_json || partial_needs_json || ve_needs_json {
                return true;
            }
        }
        if !emits_executable_test(f) {
            return false;
        }

        let call =
            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
        let recipe = crate::e2e::codegen::recipe::ResolvedE2eCallRecipe::resolve("go", f, call, type_defs);
        let call_args = recipe.args;
        let has_handle = call_args.iter().any(|a| a.arg_type == "handle") && {
            call_args.iter().filter(|a| a.arg_type == "handle").any(|a| {
                let v = resolve_field(&f.input, &a.field);
                !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
                    && super::resolve_handle_config_type(a, recipe.options_type, type_defs).is_some()
            })
        };
        let go_override = call.overrides.get("go");
        let opts_type = go_override.and_then(|o| o.options_type.as_deref()).or_else(|| {
            e2e_config
                .call
                .overrides
                .get("go")
                .and_then(|o| o.options_type.as_deref())
        });
        let has_json_obj = call_args.iter().any(|a| {
            if a.arg_type != "json_object" {
                return false;
            }
            let v = if a.field == "input" {
                f.input.get("extract_input").unwrap_or(&f.input)
            } else {
                let field = a.field.strip_prefix("input.").unwrap_or(&a.field);
                f.input.get(field).unwrap_or(&serde_json::Value::Null)
            };
            if v.is_array() {
                return true;
            }
            opts_type.is_some() && v.is_object() && !v.as_object().is_some_and(|o| o.is_empty())
        });
        has_handle || has_json_obj
    });

    let needs_base64 = false;

    let call_result_is_simple = |cc: &crate::core::config::e2e::CallConfig| -> bool {
        cc.overrides.get("go").is_some_and(|o| o.result_is_simple)
            || cc.result_is_simple
            || cc.overrides.get("rust").map(|o| o.result_is_simple).unwrap_or(false)
    };

    let needs_fmt = fixtures.iter().any(|f| {
        f.visitor.as_ref().is_some_and(|v| {
            v.callbacks.values().any(|action| {
                if let crate::e2e::fixture::CallbackAction::CustomTemplate { template, .. } = action {
                    template.contains('{')
                } else {
                    false
                }
            })
        })
    }) || fixtures.iter().any(|f| fixture_needs_fmt_for_declared_error_value(f, errors))
        // Bracket-wildcard traversal assertions stringify each element with
        // `fmt.Sprintf("%v", …)`; without this the `needs_fmt` conjunction below would
        // veto the import even though the body references the package. ~keep
        || fixtures.iter().any(|f| {
            f.assertions
                .iter()
                .any(|a| a.field.as_deref().is_some_and(|field| field.contains("[].")))
        });

    let needs_strings = fixtures.iter().any(|f| {
        if !emits_executable_test(f) {
            return false;
        }
        let cc =
            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
        if cc.args.iter().any(|arg| arg.arg_type == "mock_url_list") {
            return true;
        }
        let (ir_reachable_fields, ir_known_excluded_fields, ir_optional_fields) =
            FieldResolver::ir_field_sets(type_defs);
        let per_call_resolver = FieldResolver::new(
            e2e_config.effective_fields(cc),
            e2e_config.effective_fields_optional(cc),
            e2e_config.effective_result_fields(cc),
            e2e_config.effective_fields_array(cc),
            &std::collections::HashSet::new(),
        )
        .with_ir_fields(ir_reachable_fields, ir_known_excluded_fields, ir_optional_fields);
        f.assertions.iter().any(|a| {
            let type_needs_strings = if a.assertion_type == "equals" {
                a.value.as_ref().is_some_and(|v| v.is_string())
            } else {
                matches!(
                    a.assertion_type.as_str(),
                    "contains" | "contains_all" | "contains_any" | "not_contains" | "starts_with" | "ends_with"
                )
            };
            let simple_result = call_result_is_simple(cc);
            let field_valid = a
                .field
                .as_ref()
                .map(|f| f.is_empty() || simple_result || per_call_resolver.is_valid_for_result(f))
                .unwrap_or(true);
            type_needs_strings && field_valid
        })
    });

    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
    let needs_http = has_http_fixtures;
    let needs_io = has_http_fixtures;

    let needs_reflect = fixtures.iter().any(|f| {
        if let Some(http) = &f.http {
            let body_needs_reflect = http
                .expected_response
                .body
                .as_ref()
                .is_some_and(|b| matches!(b, serde_json::Value::Object(_) | serde_json::Value::Array(_)));
            let partial_needs_reflect = http.expected_response.body_partial.is_some();
            body_needs_reflect || partial_needs_reflect
        } else {
            false
        }
    });

    let mut body = String::new();
    for fixture in fixtures.iter() {
        if let Some(visitor_spec) = &fixture.visitor {
            let struct_name = visitor_struct_name(&fixture.id);
            let binding = resolve_go_visitor_binding(config, type_defs, visitor_spec, import_alias);
            emit_go_visitor_struct(&mut body, &struct_name, visitor_spec, import_alias, binding.as_ref());
            let _ = writeln!(body);
        }
    }
    for (i, fixture) in fixtures.iter().enumerate() {
        render_test_function(
            &mut body,
            fixture,
            GoTestFunctionContext {
                import_alias,
                e2e_config,
                adapters,
                data_enum_names,
                config,
                type_defs,
                enums,
                errors,
            },
        );
        if i + 1 < fixtures.len() {
            let _ = writeln!(body);
        }
    }

    let needs_assert = body.contains("assert.");
    // ~keep Both flags above are fixture-level heuristics ("some assertion is of a kind that
    // might want this package"), deliberately a superset: an assertion can be skipped, degraded
    // to a stub, or rendered without ever naming the package. Go rejects an unused import, so
    // the rendered body is the only sound authority — `||` let the heuristic alone force the
    // import and emitted `"strings" imported and not used`. Matches how needs_fmt/needs_pkg
    // below already narrow their own heuristics.
    let needs_os = needs_os && body.contains("os.");
    let needs_strings = needs_strings && body.contains("strings.");
    let needs_pkg = needs_pkg && body.contains(&format!("{import_alias}."));
    // Even when a fixture *could* need fmt (a CustomTemplate), it might be
    // emitted as a panic stub instead. Require the body to actually reference
    // the package before importing it.
    let needs_fmt = needs_fmt && body.contains("fmt.");

    let _ = writeln!(out, "// E2e tests for category: {category}");
    let _ = writeln!(out, "package e2e_test");
    let _ = writeln!(out);
    let _ = writeln!(out, "import (");
    if needs_base64 {
        let _ = writeln!(out, "\t\"encoding/base64\"");
    }
    let needs_json = needs_json || body.contains("json.");
    if needs_json || needs_reflect {
        let _ = writeln!(out, "\t\"encoding/json\"");
    }
    if needs_fmt {
        let _ = writeln!(out, "\t\"fmt\"");
    }
    if needs_io {
        let _ = writeln!(out, "\t\"io\"");
    }
    if needs_http {
        let _ = writeln!(out, "\t\"net/http\"");
    }
    if needs_os {
        let _ = writeln!(out, "\t\"os\"");
    }
    let _ = needs_filepath;
    if needs_reflect {
        let _ = writeln!(out, "\t\"reflect\"");
    }
    if needs_strings {
        let _ = writeln!(out, "\t\"strings\"");
    }
    let _ = writeln!(out, "\t\"testing\"");
    if needs_assert {
        let _ = writeln!(out);
        let _ = writeln!(out, "\t\"github.com/stretchr/testify/assert\"");
    }
    if needs_pkg {
        let _ = writeln!(out);
        let _ = writeln!(out, "\t{import_alias} \"{go_module_path}\"");
    }
    let _ = writeln!(out, ")");
    let _ = writeln!(out);

    out.push_str(&body);
    while out.ends_with("\n\n") {
        out.pop();
    }
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod fmt_import_tests {
    use super::fixture_needs_fmt_for_declared_error_value;
    use crate::e2e::fixture::{Assertion, Fixture};

    fn error_fixture(value: Option<serde_json::Value>) -> Fixture {
        Fixture {
            assertions: vec![Assertion {
                skip: None,
                assertion_type: "error".to_string(),
                field: None,
                value,
                values: None,
                method: None,
                check: None,
                args: None,
                return_type: None,
            }],
            ..Fixture::default()
        }
    }

    #[test]
    fn declared_error_value_requires_fmt_import() {
        let fixture = error_fixture(Some(serde_json::Value::String("SomeExpectedError".to_string())));

        assert!(fixture_needs_fmt_for_declared_error_value(&fixture, &[]));
    }

    #[test]
    fn undeclared_error_value_does_not_require_fmt_import() {
        let fixture = error_fixture(None);

        assert!(!fixture_needs_fmt_for_declared_error_value(&fixture, &[]));
    }

    #[test]
    fn non_error_assertion_does_not_require_fmt_import() {
        let mut fixture = error_fixture(Some(serde_json::Value::String("SomeExpectedError".to_string())));
        fixture.assertions[0].assertion_type = "contains".to_string();

        assert!(!fixture_needs_fmt_for_declared_error_value(&fixture, &[]));
    }

    /// The defect this fix closes: a fixture whose declared value names a real `ErrorVariant`
    /// with no `#[alef(error_code = N)]` now renders `declared_error_variant::skip_line`'s bare
    /// `//` comment, not `fmt.Sprintf` — so it must NOT pull in the `fmt` import either.
    #[test]
    fn uncoded_known_variant_does_not_require_fmt_import() {
        use crate::core::ir::{ErrorDef, ErrorVariant};

        let fixture = error_fixture(Some(serde_json::Value::String("Authentication".to_string())));
        let errors = vec![ErrorDef {
            name: "ApiError".to_string(),
            rust_path: "lib::ApiError".to_string(),
            original_rust_path: String::new(),
            variants: vec![ErrorVariant {
                name: "Authentication".to_string(),
                error_code: None,
                is_unit: true,
                ..ErrorVariant::default()
            }],
            doc: String::new(),
            methods: vec![],
            binding_excluded: false,
            binding_exclusion_reason: None,
            version: Default::default(),
        }];

        assert!(!fixture_needs_fmt_for_declared_error_value(&fixture, &errors));
    }

    /// A CODED known variant still renders the `fmt`-using assertion.
    #[test]
    fn coded_known_variant_still_requires_fmt_import() {
        use crate::core::ir::{ErrorDef, ErrorVariant};

        let fixture = error_fixture(Some(serde_json::Value::String("Authentication".to_string())));
        let errors = vec![ErrorDef {
            name: "ApiError".to_string(),
            rust_path: "lib::ApiError".to_string(),
            original_rust_path: String::new(),
            variants: vec![ErrorVariant {
                name: "Authentication".to_string(),
                error_code: Some(100),
                is_unit: true,
                ..ErrorVariant::default()
            }],
            doc: String::new(),
            methods: vec![],
            binding_excluded: false,
            binding_exclusion_reason: None,
            version: Default::default(),
        }];

        assert!(fixture_needs_fmt_for_declared_error_value(&fixture, &errors));
    }
}