alef 0.62.8

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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! Dart-specific e2e generator tests.

use super::stubs::emit_test_backend;
use crate::core::config::TraitBridgeConfig;
use crate::core::ir::{MethodDef, PrimitiveType, TypeRef};
use crate::e2e::fixture::Fixture;

fn make_trait_bridge(trait_name: &str) -> TraitBridgeConfig {
    TraitBridgeConfig {
        trait_name: trait_name.to_string(),
        super_trait: Some("Plugin".to_string()),
        register_fn: Some(format!("register_{}", trait_name.to_lowercase())),
        ..Default::default()
    }
}

fn make_method(name: &str, required: bool) -> MethodDef {
    MethodDef {
        name: name.to_string(),
        params: vec![],
        return_type: TypeRef::Primitive(PrimitiveType::Bool),
        is_async: true,
        is_static: false,
        error_type: None,
        doc: String::new(),
        receiver: Some(crate::core::ir::ReceiverKind::Ref),
        cfg: None,
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: !required,
        binding_excluded: false,
        binding_exclusion_reason: None,
        version: Default::default(),
    }
}

fn make_fixture(id: &str) -> Fixture {
    Fixture {
        docs: None,
        requirements: Vec::new(),
        id: id.to_string(),
        category: None,
        description: "test".to_string(),
        tags: vec![],
        skip: None,
        env: None,
        setup: Vec::new(),
        call: None,
        input: serde_json::Value::Null,
        mock_response: None,
        source: String::new(),
        http: None,
        asyncapi: None,
        websocket: None,
        preserve_input_urls: false,
        assertions: vec![],
        visitor: None,
        args: vec![],
        assertion_recipes: vec![],
    }
}

/// Verify that no sample_core-domain names leak into the generated output when
/// the trait bridge is configured for a synthetic `TestTrait` in `testlib`.
#[test]
fn dart_stub_contains_no_sample_crate_domain_names() {
    let bridge = make_trait_bridge("TestTrait");
    let required_method = make_method("doWork", true);
    let methods = [&required_method];
    let fixture = make_fixture("my_test_fixture");

    let emission = emit_test_backend(&bridge, &methods, &fixture, &[]);

    let output = format!("{}\n{}", emission.setup_block, emission.arg_expr);

    assert!(
        !output.contains("SampleCrate"),
        "must not contain literal 'SampleCrate', got:\n{output}"
    );
    assert!(
        !output.contains("sample_crate::"),
        "must not contain 'sample_crate::', got:\n{output}"
    );
    assert!(
        !output.contains("SampleCrateBridge"),
        "must not contain 'SampleCrateBridge', got:\n{output}"
    );
    assert!(
        output.contains("TestStubMyTestFixture"),
        "class name must be derived from fixture id, got:\n{output}"
    );
    assert!(
        output.contains("extends TestTrait"),
        "class must extend the configured trait class, got:\n{output}"
    );
    assert!(
        output.contains("doWork"),
        "required method must be emitted, got:\n{output}"
    );
}

fn make_param(name: &str, ty: TypeRef) -> crate::core::ir::ParamDef {
    crate::core::ir::ParamDef {
        name: name.to_string(),
        ty,
        optional: false,
        default: None,
        sanitized: false,
        typed_default: None,
        is_ref: false,
        is_mut: false,
        newtype_wrapper: None,
        original_type: None,
        map_is_ahash: false,
        map_key_is_cow: false,
        vec_inner_is_ref: false,
        map_is_btree: false,
        core_wrapper: crate::core::ir::CoreWrapper::None,
    }
}

fn make_method_with_params(name: &str, required: bool) -> MethodDef {
    MethodDef {
        name: name.to_string(),
        params: vec![
            make_param("content", TypeRef::Bytes),
            make_param("mime_type", TypeRef::String),
        ],
        return_type: TypeRef::Named("SampleResult".to_string()),
        is_async: true,
        is_static: false,
        error_type: Some("anyhow::Error".to_string()),
        doc: String::new(),
        receiver: Some(crate::core::ir::ReceiverKind::Ref),
        cfg: None,
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: !required,
        binding_excluded: false,
        binding_exclusion_reason: None,
        version: Default::default(),
    }
}

/// Verify params use concrete Dart types (not `dynamic`) and no @override annotation.
#[test]
fn dart_stub_uses_typed_params_not_dynamic() {
    let bridge = make_trait_bridge("TestTrait");
    let required_method = make_method_with_params("extract", true);
    let methods = [&required_method];
    let fixture = make_fixture("my_test_fixture");

    let emission = emit_test_backend(&bridge, &methods, &fixture, &[]);
    let output = format!("{}\n{}", emission.setup_block, emission.arg_expr);

    assert!(
        !output.contains("dynamic content"),
        "param must not use `dynamic`, got:\n{output}"
    );
    assert!(
        output.contains("Uint8List content"),
        "bytes param must map to Uint8List, got:\n{output}"
    );
    assert!(
        output.contains("String mimeType"),
        "string param must map to String, got:\n{output}"
    );
    assert!(
        output.contains("Future<SampleResult>"),
        "return type must be concrete not dynamic, got:\n{output}"
    );
    assert!(
        !output.contains("@override"),
        "local class members must not use @override annotation, got:\n{output}"
    );
}

/// Verify that `fixture.input["name"]` is used as the plugin name when present.
#[test]
fn dart_stub_uses_fixture_input_name_for_plugin_name() {
    let bridge = make_trait_bridge("TestTrait");
    let required_method = make_method("doWork", true);
    let methods = [&required_method];
    let mut fixture = make_fixture("my_fixture_id");
    fixture.input = serde_json::json!({ "name": "my-backend-name" });

    let emission = emit_test_backend(&bridge, &methods, &fixture, &[]);
    let output = format!("{}\n{}", emission.setup_block, emission.arg_expr);

    assert!(
        output.contains("'my-backend-name'"),
        "plugin name must come from fixture.input.name, got:\n{output}"
    );
    assert!(
        !output.contains("my_fixture_id"),
        "fixture id must not appear as plugin name when input.name is set, got:\n{output}"
    );
}

/// Verify that _setEnv helper forces overwrite=1 and checks return code.
/// Regression test for the bug where setenv(..., 0) silently no-ops when the
/// env var is already set, causing SAMPLE_ALLOW_PRIVATE_NETWORK to be
/// invisible to Rust FFI dylib in dart e2e tests.
#[test]
fn dart_emit_setenv_forces_overwrite_and_checks_return_code() {
    use crate::e2e::config::E2eConfig;
    use std::collections::HashMap;

    // Create a minimal E2eConfig with an env var to trigger _setEnv emission.
    let mut env = HashMap::new();
    env.insert("SAMPLE_ALLOW_PRIVATE_NETWORK".to_string(), "true".to_string());

    let e2e_config = E2eConfig {
        env,
        ..Default::default()
    };

    // Build a minimal test file just to check the _setEnv helper.
    // We'll use a dummy fixture and configuration.
    let fixture = make_fixture("test_fixture");
    let _bridge = make_trait_bridge("TestTrait");
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs = [];
    let enums = [];
    let adapters = [];
    let dart_first_class_map = crate::e2e::field_access::DartFirstClassMap::default();

    let output = super::test_file::render_test_file(
        "smoke",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &dart_first_class_map,
        &adapters,
        &config,
        &type_defs,
        &enums,
        &[],
        &[],
    );

    // Verify that the generated setenv call uses overwrite=1 (third argument).
    assert!(
        output.contains("setenv(keyPtr, valuePtr, 1)"),
        "setenv must use overwrite=1, got:\n{output}"
    );

    // Verify that the old buggy pattern is NOT in the output.
    assert!(
        !output.contains("setenv(keyPtr, valuePtr, 0)"),
        "setenv must NOT use overwrite=0, got:\n{output}"
    );

    // Verify that return code is captured and checked.
    assert!(
        output.contains("final result = setenv(keyPtr, valuePtr, 1)"),
        "setenv result must be captured, got:\n{output}"
    );

    assert!(
        output.contains("if (result != 0)"),
        "return code must be checked with 'if (result != 0)', got:\n{output}"
    );

    assert!(
        output.contains("throw StateError"),
        "must throw StateError on non-zero return code, got:\n{output}"
    );
}

/// An `error` assertion with a declared `value` must produce a `throwsA`
/// predicate matcher that checks both the caught error's `toString()` and its
/// `runtimeType.toString()`, since fixture authors use either a message-only
/// field name or a type-name prefix.
#[test]
fn dart_error_assertion_with_declared_value_checks_message_and_type() {
    use crate::e2e::fixture::Assertion;

    let mut fixture = make_fixture("invalid_thing");
    fixture.assertions.push(Assertion {
        assertion_type: "error".into(),
        value: Some(serde_json::json!("ThingNotFound")),
        ..Default::default()
    });

    let mut e2e_config = crate::e2e::config::E2eConfig::default();
    e2e_config.call.function = "parseThing".into();

    let config = crate::core::config::ResolvedCrateConfig::default();
    let dart_first_class_map = crate::e2e::field_access::DartFirstClassMap::default();

    let output = super::test_file::render_test_file(
        "smoke",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &dart_first_class_map,
        &[],
        &config,
        &[],
        &[],
        &[],
        &[],
    );

    assert!(
        output.contains(
            "throwsA(predicate((e) => e.toString().contains('ThingNotFound') || e.runtimeType.toString().contains('ThingNotFound')))"
        ),
        "expected a disjunctive message-or-type predicate matcher against the declared value, got:\n{output}"
    );
    assert!(
        !output.contains("throwsA(anything)"),
        "declared value must replace the anything-matcher, got:\n{output}"
    );
}

/// With no declared `value` on the `error` assertion, output must be
/// byte-identical to the pre-existing `throwsA(anything)` behavior.
#[test]
fn dart_error_assertion_without_declared_value_is_byte_identical() {
    use crate::e2e::fixture::Assertion;

    let mut fixture = make_fixture("invalid_thing");
    fixture.assertions.push(Assertion {
        assertion_type: "error".into(),
        ..Default::default()
    });

    let mut e2e_config = crate::e2e::config::E2eConfig::default();
    e2e_config.call.function = "parseThing".into();

    let config = crate::core::config::ResolvedCrateConfig::default();
    let dart_first_class_map = crate::e2e::field_access::DartFirstClassMap::default();

    let output = super::test_file::render_test_file(
        "smoke",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &dart_first_class_map,
        &[],
        &config,
        &[],
        &[],
        &[],
        &[],
    );

    assert!(output.contains("throwsA(anything)"));
    assert!(!output.contains("predicate((e)"));
}

/// Declared error values containing Dart string-interpolation and escape
/// characters (`'`, `\`, `$`) must be escaped via the shared `escape_dart`
/// helper, not hand-rolled, so the emitted literal stays a valid single-quoted
/// Dart string.
#[test]
fn dart_error_assertion_escapes_declared_value_for_dart_string_literal() {
    use crate::e2e::fixture::Assertion;

    let mut fixture = make_fixture("invalid_thing");
    fixture.assertions.push(Assertion {
        assertion_type: "error".into(),
        value: Some(serde_json::json!("bad 'field' \\ $value")),
        ..Default::default()
    });

    let mut e2e_config = crate::e2e::config::E2eConfig::default();
    e2e_config.call.function = "parseThing".into();

    let config = crate::core::config::ResolvedCrateConfig::default();
    let dart_first_class_map = crate::e2e::field_access::DartFirstClassMap::default();

    let output = super::test_file::render_test_file(
        "smoke",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &dart_first_class_map,
        &[],
        &config,
        &[],
        &[],
        &[],
        &[],
    );

    let expected_escaped = super::values::escape_dart("bad 'field' \\ $value");
    let expected_snippet = format!("e.toString().contains('{expected_escaped}')");
    assert!(
        output.contains(&expected_snippet),
        "expected escaped literal snippet `{expected_snippet}` in:\n{output}"
    );
}

#[test]
fn dart_test_file_emits_wrapper_for_call_config_trait_argument() {
    let fixture = make_fixture("register_backend");
    let mut e2e_config = crate::e2e::config::E2eConfig::default();
    e2e_config.call.function = "registerBackend".into();
    e2e_config.call.args.push(crate::e2e::config::ArgMapping {
        name: "backend".into(),
        field: "input.backend".into(),
        arg_type: "test_backend".into(),
        optional: false,
        owned: false,
        element_type: None,
        go_type: None,
        vec_inner_is_ref: false,
        trait_name: Some("TestTrait".into()),
    });
    let mut config = crate::core::config::ResolvedCrateConfig::default();
    config.trait_bridges.push(make_trait_bridge("TestTrait"));
    let type_defs = [crate::core::ir::TypeDef {
        name: "TestTrait".into(),
        methods: vec![make_method("doWork", true)],
        ..Default::default()
    }];
    let output = super::test_file::render_test_file(
        "plugins",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &crate::e2e::field_access::DartFirstClassMap::default(),
        &[],
        &config,
        &type_defs,
        &[],
        &[],
        &[],
    );
    assert!(output.contains("Future<TestTraitDartImpl> _createTestStubRegisterBackendWrapper()"));
    assert!(output.contains("await _createTestStubRegisterBackendWrapper()"));
}

#[test]
fn dart_trait_stub_wrapper_compiles() {
    if std::process::Command::new("dart").arg("--version").output().is_err() {
        return;
    }
    let method = make_method("doWork", true);
    let emission = emit_test_backend(
        &make_trait_bridge("TestTrait"),
        &[&method],
        &make_fixture("register_backend"),
        &[],
    );
    let source = format!(
        "abstract class TestTrait {{ Future<bool> doWork(); }}\nclass TestTraitDartImpl {{}}\nFuture<TestTraitDartImpl> createTestTraitDartImpl({{required String pluginName, required String pluginVersion, required Future<bool> Function() doWork}}) async => TestTraitDartImpl();\n{}\nFuture<void> main() async {{ await _createTestStubRegisterBackendWrapper(); }}\n",
        emission.setup_block
    );
    let directory = tempfile::tempdir().expect("temporary directory");
    let source_path = directory.path().join("stub.dart");
    std::fs::write(&source_path, &source).expect("write Dart source");
    // Pin the child's working directory. Other tests in this binary mutate the
    // process-global cwd via `set_current_dir` into tempdirs that are then dropped, so
    // an inherited cwd can already be deleted by the time this runs -- the Dart VM then
    // fails startup with "Error determining current directory" rather than any analysis
    // result. ~keep
    let output = std::process::Command::new("dart")
        .args(["analyze", "--fatal-infos"])
        .arg(&source_path)
        .current_dir(directory.path())
        .output()
        .expect("run Dart analyzer");
    assert!(
        output.status.success(),
        "dart analyze failed ({})\n--- stdout ---\n{}\n--- stderr ---\n{}\n--- source ---\n{source}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

/// Dart's error path renders `expectLater(..., throwsA(..))` and returns, so every other
/// assertion on the fixture used to leave no trace in the generated test at all.
#[test]
fn dart_equals_on_an_error_field_is_named_instead_of_dropped() {
    use crate::e2e::fixture::Assertion;

    let mut fixture = make_fixture("rate_limited");
    fixture.assertions.push(Assertion {
        assertion_type: "error".into(),
        value: Some(serde_json::json!("ThingNotFound")),
        ..Default::default()
    });
    fixture.assertions.push(Assertion {
        assertion_type: "equals".into(),
        field: Some("error.status_code".into()),
        ..Default::default()
    });

    let mut e2e_config = crate::e2e::config::E2eConfig::default();
    e2e_config.call.function = "parseThing".into();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let dart_first_class_map = crate::e2e::field_access::DartFirstClassMap::default();

    let _ = crate::e2e::codegen::take_skip_records();
    let output = super::test_file::render_test_file(
        "smoke",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &dart_first_class_map,
        &[],
        &config,
        &[],
        &[],
        &[],
        &[],
    );

    // Positive first: the error block really rendered.
    assert!(
        output.contains("throwsA(predicate("),
        "the error block must render: {output}"
    );
    assert!(
        output.contains(
            "// skipped: assertion type 'equals' has no accessor for error field error.status_code in this backend"
        ),
        "{output}"
    );

    let records = crate::e2e::codegen::take_skip_records();
    assert_eq!(records.len(), 1, "got: {records:?}");
    assert_eq!(records[0].language, "dart");
    assert_eq!(records[0].field, "equals");
}

/// Negative control: a lone `error` assertion must leave the generated file marker-free.
#[test]
fn dart_a_lone_error_assertion_renders_no_marker() {
    use crate::e2e::fixture::Assertion;

    let mut fixture = make_fixture("invalid_thing");
    fixture.assertions.push(Assertion {
        assertion_type: "error".into(),
        ..Default::default()
    });

    let mut e2e_config = crate::e2e::config::E2eConfig::default();
    e2e_config.call.function = "parseThing".into();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let dart_first_class_map = crate::e2e::field_access::DartFirstClassMap::default();

    let output = super::test_file::render_test_file(
        "smoke",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &dart_first_class_map,
        &[],
        &config,
        &[],
        &[],
        &[],
        &[],
    );

    assert!(output.contains("throwsA("), "the error block must render: {output}");
    assert!(!output.contains("has no accessor for error field"), "{output}");
}

// --- typed-argument lowering (alef #227) -----------------------------------------------------

/// Render one fixture through the real dart test-file path with an `args` entry that has the
/// default `arg_type` (`"string"`) -- the shape that used to emit a quoted literal regardless of
/// what the parameter it fills is declared as.
///
/// `functions` is the only thing that varies between the two states below: an empty slice with an
/// empty `type_defs` is exactly `TargetParams::IrAbsent`, the state every unconverted caller is in.
fn render_dart_enum_arg_fixture(
    functions: &[crate::core::ir::FunctionDef],
    enums: &[crate::core::ir::EnumDef],
) -> String {
    let mut fixture = make_fixture("upload");
    fixture.input = serde_json::json!({ "purpose": "fine-tune" });

    let mut e2e_config = crate::e2e::config::E2eConfig::default();
    e2e_config.call.function = "upload_file".into();
    e2e_config.call.args = vec![crate::e2e::config::ArgMapping {
        name: "purpose".to_string(),
        field: "input.purpose".to_string(),
        arg_type: "string".to_string(),
        optional: false,
        owned: false,
        element_type: None,
        go_type: None,
        vec_inner_is_ref: false,
        trait_name: None,
    }];

    super::test_file::render_test_file(
        "smoke",
        &[&fixture],
        &e2e_config,
        "dart",
        "samplecli",
        "RustLib",
        "RustLibBridge",
        &crate::e2e::field_access::DartFirstClassMap::default(),
        &[],
        &crate::core::config::ResolvedCrateConfig::default(),
        &[],
        enums,
        functions,
        &[],
    )
}

fn file_purpose_enum() -> crate::core::ir::EnumDef {
    crate::core::ir::EnumDef {
        name: "FilePurpose".to_string(),
        has_serde: true,
        serde_rename_all: Some("kebab-case".to_string()),
        variants: vec![crate::core::ir::EnumVariant {
            name: "FineTune".to_string(),
            ..crate::core::ir::EnumVariant::default()
        }],
        ..crate::core::ir::EnumDef::default()
    }
}

fn upload_file_taking(type_name: &str) -> crate::core::ir::FunctionDef {
    crate::core::ir::FunctionDef {
        name: "upload_file".to_string(),
        params: vec![crate::core::ir::ParamDef {
            name: "purpose".to_string(),
            ty: TypeRef::Named(type_name.to_string()),
            ..crate::core::ir::ParamDef::default()
        }],
        return_type: TypeRef::Named("UploadedFile".to_string()),
        ..crate::core::ir::FunctionDef::default()
    }
}

/// The defect: a fixture string bound for an enum-typed parameter stayed a *string literal*, which
/// the Dart analyzer rejects against a generated `enum`. The variant here is
/// `rename_all = "kebab-case"`, the case a naive camel-casing of the wire value would get wrong. ~keep
#[test]
fn a_string_value_for_an_ir_enum_parameter_names_the_generated_dart_variant() {
    let output = render_dart_enum_arg_fixture(&[upload_file_taking("FilePurpose")], &[file_purpose_enum()]);

    assert!(
        output.contains("FilePurpose.fineTune"),
        "expected the generated Dart enum variant, got:\n{output}"
    );
    assert!(
        !output.contains("'fine-tune'"),
        "the string literal must be replaced, not accompanied, got:\n{output}"
    );
}

/// The other half of the three-state trade. Identical fixture, arg and enum; only the core IR is
/// withheld. The pre-seam lowering must survive verbatim, or every IR-less caller regresses
/// silently -- which is the whole reason `TargetParams` has three states and not two. ~keep
#[test]
fn the_same_string_value_still_renders_as_a_dart_literal_when_the_ir_is_absent() {
    let output = render_dart_enum_arg_fixture(&[], &[file_purpose_enum()]);

    assert!(
        output.contains("'fine-tune'"),
        "the IR-less path must keep today's string literal, got:\n{output}"
    );
    assert!(
        !output.contains("FilePurpose.fineTune"),
        "an absent IR licenses no type claim, got:\n{output}"
    );
}

/// A wire value naming no variant is very often a deliberately invalid value driving the binding's
/// own validation, so it keeps its literal rather than gaining an invented variant. ~keep
#[test]
fn an_unmatched_dart_enum_wire_value_keeps_its_string_literal() {
    let mut unmatched = file_purpose_enum();
    unmatched.variants[0].name = "Assistants".to_string();
    let output = render_dart_enum_arg_fixture(&[upload_file_taking("FilePurpose")], &[unmatched]);

    assert!(
        output.contains("'fine-tune'"),
        "an unmatched wire value must keep its literal, got:\n{output}"
    );
}

/// A declared type that is not an enum at all is not a licence to invent a variant reference: it
/// may be a newtype the Dart binding flattens to a `String`. ~keep
#[test]
fn a_declared_type_that_is_not_an_ir_enum_keeps_the_existing_dart_lowering() {
    let output = render_dart_enum_arg_fixture(&[upload_file_taking("PromptText")], &[file_purpose_enum()]);

    assert!(
        output.contains("'fine-tune'"),
        "a non-enum declared type must keep today's literal, got:\n{output}"
    );
}