alef 0.71.0

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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
// Test module: debug output to stderr is expected here. ~keep
#![allow(clippy::print_stdout, clippy::print_stderr)]

use crate::e2e::config::{ArgMapping, CallConfig, E2eConfig};
use crate::e2e::fixture::{Assertion, Fixture};

use super::setup::build_args_and_setup;
use super::test_file::{GoTestFileContext, render_test_file};
use super::test_function::{GoTestFunctionContext, render_test_function};
use super::{render_env_setup, render_main_test_go};

fn make_fixture(id: &str) -> Fixture {
    Fixture {
        docs: None,
        requirements: Vec::new(),
        id: id.to_string(),
        category: None,
        description: "test fixture".to_string(),
        tags: vec![],
        skip: None,
        env: None,
        setup: Vec::new(),
        call: None,
        input: serde_json::Value::Null,
        mock_response: Some(crate::e2e::fixture::MockResponse {
            status: 200,
            body: Some(serde_json::Value::Null),
            stream_chunks: None,
            headers: std::collections::BTreeMap::new(),
        }),
        source: String::new(),
        http: None,
        asyncapi: None,
        websocket: None,
        preserve_input_urls: false,
        assertions: vec![Assertion {
            assertion_type: "not_error".to_string(),
            ..Default::default()
        }],
        visitor: None,
        args: vec![],
        assertion_recipes: vec![],
    }
}

// Regression for a bug where the snippet template hardcoded `var typedError *pkg.Error`
// (a pointer). Alef's Go error emitter generates `Error() string` on a value receiver, so
// the concrete error is never a `*Error` and `errors.As` against a pointer target silently
// never matches. Asserting `!body.contains("*pkg.Error")` alone would pass on a body missing
// `typedError` entirely, so this also pins the exact non-pointer declaration. ~keep
#[test]
fn snippet_body_declares_typed_error_by_value_not_by_pointer() {
    let mut fixture = make_fixture("invalid_input");
    fixture.assertions = vec![Assertion {
        assertion_type: "error".to_string(),
        ..Default::default()
    }];
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "parse".to_string(),
            module: "example.com/sample".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };
    let config = crate::core::config::ResolvedCrateConfig::default();

    let body =
        super::snippet::render_snippet_body(&fixture, &e2e_config, &config, &[], &[], &[]).expect("snippet renders");

    assert!(body.contains("var typedError pkg.Error"), "{body}");
    assert!(!body.contains("var typedError *pkg.Error"), "{body}");
}

/// snake_case function names in `[e2e.call]` must be routed through `to_go_name`
/// so the emitted Go call uses the idiomatic CamelCase (e.g. `CleanExtractedText`
/// instead of `clean_extracted_text`).
#[test]
fn test_go_method_name_uses_go_casing() {
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "clean_extracted_text".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };

    let fixture = make_fixture("basic_text");
    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    assert!(
        out.contains("sample_crate.CleanExtractedText("),
        "expected Go-cased method name 'CleanExtractedText', got:\n{out}"
    );
    assert!(
        !out.contains("sample_crate.clean_extracted_text("),
        "must not emit raw snake_case method name, got:\n{out}"
    );
}

/// Regression test for alef task #81: go had no fallback at all for a dropped
/// field assertion — `is_valid_for_result` rejects the field, `render_assertion`
/// emits a skip comment, and (until this fix) nothing else ever consulted that
/// comment. This pins that the skip comment carries the exact marker text the
/// shared `fail_on_unavailable_field_markers` mechanism (src/e2e/codegen/mod.rs)
/// matches on, and — because `out` accumulates every fixture's function in the
/// same buffer (see `test_file.rs`) — that a PRECEDING fixture with no issues does
/// not get misattributed the following fixture's dropped field.
#[test]
fn dropped_field_assertion_carries_the_marker_and_is_correctly_attributed_per_fixture() {
    let e2e_config = E2eConfig {
        result_fields: std::collections::HashSet::from(["content".to_string()]),
        call: CallConfig {
            function: "process".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    let mut out = String::new();

    // First fixture: no field assertions at all — must not pick up anything
    // appended by the second fixture's render.
    render_test_function(
        &mut out,
        &make_fixture("clean_smoke"),
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );
    let clean_len = out.len();

    // Second fixture: asserts on a field absent from `result_fields`.
    let mut dirty_fixture = make_fixture("dirty_smoke");
    dirty_fixture.assertions = vec![Assertion {
        assertion_type: "equals".to_string(),
        field: Some("nonexistent_field".to_string()),
        value: Some(serde_json::json!("x")),
        ..Default::default()
    }];
    render_test_function(
        &mut out,
        &dirty_fixture,
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    assert!(
        !out[..clean_len].contains("not available"),
        "the first fixture's own render must carry no skip marker, got:\n{}",
        &out[..clean_len]
    );
    assert!(
        out[clean_len..].contains("field 'nonexistent_field' not available on result type"),
        "the second fixture's own render must carry the skip marker, got:\n{}",
        &out[clean_len..]
    );
}

/// Regression test for alef task #81: a `!effective_returns_result && result_is_simple`
/// function (no error return to check, plain non-error-returning signature) whose
/// fixture's only declared assertion is `not_error` used to discard the call result
/// to `_` and assert literally nothing — the one Go shape with no fallback of any
/// kind, since the sibling branches (`returns_void`, `returns_result`) both still
/// have a real `if err != nil { t.Fatalf(...) }` check to fall back on. It must now
/// bind the result and assert non-nil instead of silently discarding it.
#[test]
fn declared_not_error_only_fixture_on_a_simple_errorless_call_still_gets_a_real_assertion() {
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "normalize".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: false,
            result_is_simple: true,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };
    // `make_fixture` declares exactly one `not_error` assertion by default — the
    // "declared but unusable here" case this fix targets.
    let fixture = make_fixture("normalize_smoke");
    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    assert!(
        !out.contains("_ = sample_crate.Normalize("),
        "must bind the result instead of discarding it, got:\n{out}"
    );
    assert!(out.contains("result := sample_crate.Normalize("), "got:\n{out}");
    assert!(
        out.contains("if result == nil {") && out.contains("t.Fatalf(\"expected non-nil result\")"),
        "expected a real non-nil fallback assertion, got:\n{out}"
    );
}

/// Positive control for the same fix: a fixture with genuinely zero declared
/// assertions is left exactly as before (deliberate smoke-test contract) — the
/// result is still discarded, since there is nothing to fall back on behalf of.
#[test]
fn zero_declared_assertions_on_a_simple_errorless_call_still_discards_the_result() {
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "normalize".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: false,
            result_is_simple: true,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };
    let mut fixture = make_fixture("normalize_smoke");
    fixture.assertions = Vec::new();
    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    assert!(
        out.contains("_ = sample_crate.Normalize("),
        "a fixture with zero declared assertions is an intentional smoke test and must \
         still discard the result, got:\n{out}"
    );
    assert!(!out.contains("t.Fatalf(\"expected non-nil result\")"), "got:\n{out}");
}

#[test]
fn handle_config_deserialization_uses_resolved_options_type() {
    let args = vec![ArgMapping {
        name: "session".to_string(),
        field: "input.config".to_string(),
        arg_type: "handle".to_string(),
        optional: false,
        owned: false,
        element_type: None,
        go_type: None,
        vec_inner_is_ref: false,
        trait_name: None,
    }];
    let fixture = Fixture {
        docs: None,
        requirements: Vec::new(),
        id: "session_fixture".to_string(),
        category: None,
        description: "test fixture".to_string(),
        tags: vec![],
        skip: None,
        env: None,
        setup: Vec::new(),
        call: None,
        input: serde_json::json!({ "config": { "limit": 3 } }),
        mock_response: None,
        visitor: None,
        args: vec![],
        assertion_recipes: vec![],
        assertions: vec![],
        source: String::new(),
        http: None,
        asyncapi: None,
        websocket: None,
        preserve_input_urls: false,
    };
    let data_enum_names = std::collections::HashSet::new();
    let (package_decls, setup, args_str) = build_args_and_setup(
        &fixture.input,
        &args,
        "pkg",
        Some("SessionConfig"),
        &fixture,
        false,
        false,
        &data_enum_names,
        &crate::core::config::ResolvedCrateConfig::default(),
        &[],
        &[],
        false,
        crate::e2e::codegen::call_ir::TargetParams::IrAbsent,
    )
    .expect("args render");

    let rendered = setup.join("\n");
    assert!(package_decls.is_empty());
    assert_eq!(args_str, "session");
    assert!(rendered.contains("var sessionConfig pkg.SessionConfig"));
    assert!(rendered.contains("pkg.CreateSession(&sessionConfig)"));
    assert!(!rendered.contains("CrawlConfig"));
}

#[test]
fn test_streaming_fixture_emits_collect_snippet() {
    // A streaming fixture should emit `stream, err :=` and the collect loop.
    let streaming_fixture_json = r#"{
            "id": "basic_stream",
            "description": "basic streaming test",
            "call": "chat_stream",
            "input": {"model": "gpt-4", "messages": [{"role": "user", "content": "hello"}]},
            "mock_response": {
                "status": 200,
                "stream_chunks": [{"delta": "hello"}]
            },
            "assertions": [
                {"type": "count_min", "field": "chunks", "value": 1}
            ]
        }"#;
    let fixture: Fixture = serde_json::from_str(streaming_fixture_json).unwrap();
    assert!(fixture.is_streaming_mock(), "fixture should be detected as streaming");

    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "chat_stream".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            r#async: true,
            streaming: Some(crate::core::config::e2e::StreamingConfig::Recipe(
                crate::core::config::e2e::StreamingRecipe {
                    item_type: Some("StreamChunk".to_string()),
                    ..Default::default()
                },
            )),
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };

    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "pkg",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    assert!(out.contains("stream, err :="), "should use stream binding, got:\n{out}");
    assert!(
        out.contains("for chunk := range stream"),
        "should emit collect loop, got:\n{out}"
    );
}

#[test]
fn test_streaming_with_client_factory_and_json_arg() {
    // Covers no returns_result on the call, json_object args
    // (binding_returns_error=true), and client_factory from the Go call override.
    use crate::core::config::e2e::{ArgMapping, CallOverride};
    let streaming_fixture_json = r#"{
            "id": "basic_stream_client",
            "description": "basic streaming test with client",
            "call": "chat_stream",
            "input": {"model": "gpt-4", "messages": [{"role": "user", "content": "hello"}]},
            "mock_response": {
                "status": 200,
                "stream_chunks": [{"delta": "hello"}]
            },
            "assertions": [
                {"type": "count_min", "field": "chunks", "value": 1}
            ]
        }"#;
    let fixture: Fixture = serde_json::from_str(streaming_fixture_json).unwrap();
    assert!(fixture.is_streaming_mock(), "fixture should be detected as streaming");

    let go_override = CallOverride {
        client_factory: Some("CreateClient".to_string()),
        ..Default::default()
    };

    let mut call_overrides = std::collections::HashMap::new();
    call_overrides.insert("go".to_string(), go_override);

    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "chat_stream".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: false, // NOT true — like real demo-client
            r#async: true,
            streaming: Some(crate::core::config::e2e::StreamingConfig::Recipe(
                crate::core::config::e2e::StreamingRecipe {
                    item_type: Some("StreamChunk".to_string()),
                    ..Default::default()
                },
            )),
            args: vec![ArgMapping {
                name: "request".to_string(),
                field: "input".to_string(),
                arg_type: "json_object".to_string(),
                optional: false,
                owned: true,
                element_type: None,
                go_type: None,
                vec_inner_is_ref: false,
                trait_name: None,
            }],
            overrides: call_overrides,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };

    let mut out = String::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "pkg",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &crate::core::config::ResolvedCrateConfig::default(),
            type_defs: &[],
            enums: &[],
            errors: &[],
            functions: &[],
        },
    );

    eprintln!("generated:\n{out}");
    assert!(out.contains("stream, err :="), "should use stream binding, got:\n{out}");
    assert!(
        out.contains("for chunk := range stream"),
        "should emit collect loop, got:\n{out}"
    );
}

/// When `segments` is an optional field (Option<Vec<T>>) and a fixture asserts on
/// `segments[0].id`, the prefix guard must be `result.Segments != nil` — NOT
/// `result.Segments[0] != nil`, which is a compile error for a value-typed element.
#[test]
fn test_indexed_element_prefix_guard_uses_array_not_element() {
    let mut optional_fields = std::collections::HashSet::new();
    optional_fields.insert("segments".to_string());
    let mut array_fields = std::collections::HashSet::new();
    array_fields.insert("segments".to_string());

    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "transcribe".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        fields_optional: optional_fields,
        fields_array: array_fields,
        ..E2eConfig::default()
    };

    let fixture = Fixture {
        docs: None,
        requirements: Vec::new(),
        id: "edge_transcribe_with_timestamps".to_string(),
        category: None,
        description: "Transcription with timestamp segments".to_string(),
        tags: vec![],
        skip: None,
        env: None,
        setup: Vec::new(),
        call: None,
        input: serde_json::Value::Null,
        mock_response: Some(crate::e2e::fixture::MockResponse {
            status: 200,
            body: Some(serde_json::Value::Null),
            stream_chunks: None,
            headers: std::collections::BTreeMap::new(),
        }),
        source: String::new(),
        http: None,
        asyncapi: None,
        websocket: None,
        preserve_input_urls: false,
        assertions: vec![
            Assertion {
                assertion_type: "not_error".to_string(),
                ..Default::default()
            },
            Assertion {
                assertion_type: "equals".to_string(),
                field: Some("segments[0].id".to_string()),
                value: Some(serde_json::Value::Number(serde_json::Number::from(0u64))),
                ..Default::default()
            },
        ],
        visitor: None,
        args: vec![],
        assertion_recipes: vec![],
    };

    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "pkg",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    eprintln!("generated:\n{out}");

    // Must guard on the slice itself — not on the element. Either the nil check on the
    // optional slice or the non-empty precondition is valid Go here; `len(...) > 0` is
    // not, because it would swallow the assertion instead of failing the test.
    assert!(
        out.contains("result.Segments != nil") || out.contains("len(result.Segments) == 0"),
        "guard must be on Segments (the slice), not an element; got:\n{out}"
    );
    // Must NOT emit the invalid element nil check.
    assert!(
        !out.contains("result.Segments[0] != nil"),
        "must not emit Segments[0] != nil for a value-type element; got:\n{out}"
    );
}

/// Regression test: a `result_is_simple` call with a `contains` assertion whose
/// `field` ("result") is not a struct field must still bind the call to the result
/// variable AND emit the `fmt`/`strings` imports.  The assertion renderer ignores
/// the field for `result_is_simple` calls and emits `strings.Contains(fmt.Sprint(result), …)`,
/// so binding to `_` (or omitting the imports) produces uncompilable Go.
#[test]
fn test_result_is_simple_contains_binds_result_and_emits_imports() {
    use crate::core::config::e2e::ArgMapping;

    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "detect_mime_type_from_bytes".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            result_is_simple: true,
            args: vec![ArgMapping {
                name: "content".to_string(),
                field: "input.data".to_string(),
                arg_type: "bytes".to_string(),
                optional: false,
                owned: false,
                element_type: None,
                go_type: None,
                vec_inner_is_ref: false,
                trait_name: None,
            }],
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };

    let fixture = Fixture {
        docs: None,
        requirements: Vec::new(),
        id: "mime_detect_bytes".to_string(),
        category: None,
        description: "Detect MIME type from file bytes".to_string(),
        tags: vec![],
        skip: None,
        env: None,
        setup: Vec::new(),
        call: None,
        input: serde_json::json!({"data": "pdf/fake_memo.pdf"}),
        mock_response: None,
        source: String::new(),
        http: None,
        asyncapi: None,
        websocket: None,
        preserve_input_urls: false,
        assertions: vec![Assertion {
            assertion_type: "contains".to_string(),
            field: Some("result".to_string()),
            value: Some(serde_json::Value::String("pdf".to_string())),
            ..Default::default()
        }],
        visitor: None,
        args: vec![],
        assertion_recipes: vec![],
    };

    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    let out = render_test_file(
        "mime_utilities",
        &[&fixture],
        GoTestFileContext {
            go_module_path: "github.com/example/mylib",
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    assert!(
        out.contains("result, err := sample_crate.DetectMimeTypeFromBytes("),
        "expected the call to bind to `result`, not `_`; got:\n{out}"
    );
    assert!(
        out.contains("strings.Contains(") && out.contains("string("),
        "expected `strings.Contains(string(...))` cast rendering; got:\n{out}"
    );
    assert!(
        !out.contains("\t\"fmt\""),
        "expected fmt import to NOT be emitted (uses string cast not fmt.Sprint); got:\n{out}"
    );
    assert!(
        out.contains("\t\"strings\""),
        "expected the `strings` import to be emitted; got:\n{out}"
    );
}

#[test]
fn main_test_go_http_fixtures_omits_net_http_and_strings_imports() {
    // When needs_mock_server_bootstrap=false (HTTP-fixtures harness path), the bootstrap uses
    // net.DialTimeout + io.Copy for readiness polling.
    // "net/http" and "strings" are NOT referenced, so they must not be imported.
    let out = render_main_test_go("testing_data", false, true, &Default::default());
    assert!(
        !out.contains("\t\"net/http\""),
        "main_test.go (http-fixtures harness path) must NOT import net/http; got:\n{out}"
    );
    assert!(
        !out.contains("\t\"strings\""),
        "main_test.go (http-fixtures harness path) must NOT import strings; got:\n{out}"
    );
    // But it must still import "net" and "io" for the harness path
    assert!(out.contains("\t\"net\""), "must import net; got:\n{out}");
    assert!(out.contains("\t\"io\""), "must import io; got:\n{out}");
}

#[test]
fn main_test_go_non_http_fixtures_includes_net_http_and_strings_imports() {
    // When needs_mock_server_bootstrap=true (mock-server path for function-call fixtures),
    // http.Get (net/http) and strings.HasPrefix/TrimPrefix are used — both must be imported.
    let out = render_main_test_go("testing_data", true, false, &Default::default());
    assert!(
        out.contains("\t\"net/http\""),
        "main_test.go (mock-server bootstrap path) must import net/http; got:\n{out}"
    );
    assert!(
        out.contains("\t\"strings\""),
        "main_test.go (mock-server bootstrap path) must import strings; got:\n{out}"
    );
    // io is now needed for the runTests helper's io.ReadCloser parameter
    assert!(
        out.contains("\t\"io\""),
        "main_test.go (mock-server bootstrap path) must import io for helper; got:\n{out}"
    );
    // And must NOT import "net" (that's http-fixtures harness path only)
    assert!(
        !out.contains("\t\"net\""),
        "main_test.go (mock-server bootstrap path) must NOT import net; got:\n{out}"
    );
}

/// The generated TestMain must set `MOCK_SERVER_NO_STDIN_WATCH=1` on the
/// mock-server subprocess so the server does not treat stdin EOF (from
/// Go's exec.Command defaulting Stdin to /dev/null) as a shutdown signal.
#[test]
fn main_test_go_sets_mock_server_no_stdin_watch_env() {
    let out = render_main_test_go("testing_data", true, false, &Default::default());
    assert!(
        out.contains("MOCK_SERVER_NO_STDIN_WATCH=1"),
        "main_test.go must set MOCK_SERVER_NO_STDIN_WATCH=1 on the mock-server subprocess; got:\n{out}"
    );
    // Must appear as cmd.Env assignment, not as a stray string in a comment.
    assert!(
        out.contains("cmdEnv := os.Environ()")
            && out.contains("cmdEnv = append(cmdEnv, \"MOCK_SERVER_NO_STDIN_WATCH=1\")")
            && out.contains("cmd.Env = cmdEnv"),
        "main_test.go must build cmdEnv before assigning cmd.Env; got:\n{out}"
    );
}

/// Regression test: TestMain must not trigger the 'exitAfterDefer' linter error.
/// This is avoided by extracting deferred cleanup into helper functions that
/// return int before os.Exit is called.
#[test]
fn main_test_go_avoids_exitafterdefer_linter_error() {
    // Mock-server bootstrap path: must have a runTests helper function
    let mock_server_out = render_main_test_go("testing_data", true, false, &Default::default());
    assert!(
        mock_server_out.contains("func runTests(m *testing.M, cmd *exec.Cmd, stdout io.ReadCloser) int"),
        "mock-server bootstrap path must emit runTests helper; got:\n{mock_server_out}"
    );
    assert!(
        mock_server_out.contains("code := runTests(m, cmd, stdout)"),
        "TestMain must call runTests to get int, not inline defer; got:\n{mock_server_out}"
    );
    assert!(
        mock_server_out.contains("os.Exit(code)"),
        "os.Exit must be called AFTER runTests returns; got:\n{mock_server_out}"
    );
    // Must NOT have os.Exit inside a function with defers still in scope
    assert!(
        !mock_server_out.contains("defer func() { _ = cmd.Process.Kill() }()")
            || mock_server_out.contains("func runTests"),
        "defers must be moved out of TestMain scope; got:\n{mock_server_out}"
    );

    // Harness-spawn path: must have runHarnessTests helper
    let harness_out = render_main_test_go("testing_data", false, true, &Default::default());
    assert!(
        harness_out.contains(
            "func runHarnessTests(m *testing.M, cmd *exec.Cmd, stdin io.WriteCloser, stdout io.ReadCloser) int"
        ),
        "harness-spawn path must emit runHarnessTests helper; got:\n{harness_out}"
    );
    assert!(
        harness_out.contains("code := runHarnessTests(m, cmd, stdin, stdout)"),
        "TestMain must call runHarnessTests to get int; got:\n{harness_out}"
    );
    assert!(
        harness_out.contains("os.Exit(code)"),
        "os.Exit must be called AFTER runHarnessTests returns; got:\n{harness_out}"
    );
}

/// A plain `Option<String>` optional field should still emit `string(*field_expr)`.
/// This guards against regressions where the display_as_text path is taken for
/// normal optional string fields.
#[test]
fn test_go_plain_optional_string_uses_string_deref_not_text_accessor() {
    let mut optional = std::collections::HashSet::new();
    optional.insert("content".to_string());
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "chat".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        fields_optional: optional,
        // fields_display_as_text is intentionally empty — plain string field.
        ..E2eConfig::default()
    };
    let fixture = Fixture {
        docs: None,
        requirements: Vec::new(),
        id: "plain_optional_string".to_string(),
        category: None,
        description: "plain optional string field".to_string(),
        tags: vec![],
        skip: None,
        env: None,
        setup: Vec::new(),
        call: None,
        input: serde_json::Value::Null,
        mock_response: Some(crate::e2e::fixture::MockResponse {
            status: 200,
            body: Some(serde_json::Value::Null),
            stream_chunks: None,
            headers: std::collections::BTreeMap::new(),
        }),
        source: String::new(),
        http: None,
        asyncapi: None,
        websocket: None,
        preserve_input_urls: false,
        visitor: None,
        args: vec![],
        assertion_recipes: vec![],
        assertions: vec![Assertion {
            assertion_type: "equals".to_string(),
            field: Some("content".to_string()),
            value: Some(serde_json::Value::String("hello".to_string())),
            ..Default::default()
        }],
    };

    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "pkg",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );
    // Plain optional string: must use `string(*field_expr)`, NOT `.Text()`.
    assert!(
        out.contains("string(*"),
        "plain optional string must use string(*); got:\n{out}"
    );
    assert!(
        !out.contains(".Text()"),
        "plain optional string must NOT use .Text(); got:\n{out}"
    );
}

/// A `display_as_text` field (e.g. `Option<AssistantContent>`) should emit
/// `field_expr.Text()` instead of `string(*field_expr)` for Go optional locals.
#[test]
fn test_go_display_as_text_optional_uses_text_accessor_not_string_deref() {
    let mut optional = std::collections::HashSet::new();
    optional.insert("content".to_string());
    let mut dat = std::collections::HashSet::new();
    dat.insert("content".to_string());
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "chat".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        fields_optional: optional,
        fields_display_as_text: dat,
        ..E2eConfig::default()
    };
    let fixture = Fixture {
        docs: None,
        requirements: Vec::new(),
        id: "display_as_text_content".to_string(),
        category: None,
        description: "display_as_text optional field".to_string(),
        tags: vec![],
        skip: None,
        env: None,
        setup: Vec::new(),
        call: None,
        input: serde_json::Value::Null,
        mock_response: Some(crate::e2e::fixture::MockResponse {
            status: 200,
            body: Some(serde_json::Value::Null),
            stream_chunks: None,
            headers: std::collections::BTreeMap::new(),
        }),
        source: String::new(),
        http: None,
        asyncapi: None,
        websocket: None,
        preserve_input_urls: false,
        visitor: None,
        args: vec![],
        assertion_recipes: vec![],
        assertions: vec![Assertion {
            assertion_type: "equals".to_string(),
            field: Some("content".to_string()),
            value: Some(serde_json::Value::String("Hello, world!".to_string())),
            ..Default::default()
        }],
    };

    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "pkg",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );
    // display_as_text field: must use `.Text()`, NOT `string(*field_expr)`.
    assert!(
        out.contains(".Text()"),
        "display_as_text field must use .Text(); got:\n{out}"
    );
    assert!(
        !out.contains("string(*"),
        "display_as_text field must NOT use string(*); got:\n{out}"
    );
}

#[test]
fn render_env_setup_empty_returns_empty_string() {
    let env = std::collections::HashMap::new();
    let out = render_env_setup(&env);
    assert_eq!(out, "", "empty env should produce empty output");
}

#[test]
fn render_env_setup_single_var_contains_key_and_value() {
    let mut env = std::collections::HashMap::new();
    env.insert("E2E_ALLOW_PRIVATE_NETWORK".to_string(), "true".to_string());
    let out = render_env_setup(&env);
    assert!(
        out.contains("E2E_ALLOW_PRIVATE_NETWORK"),
        "output should contain env var name: {out}"
    );
    assert!(out.contains("true"), "output should contain env var value: {out}");
    assert!(
        out.contains("os.LookupEnv"),
        "output should use os.LookupEnv for setdefault behavior: {out}"
    );
    assert!(out.contains("os.Setenv"), "output should call os.Setenv: {out}");
}

#[test]
fn render_env_setup_multiple_vars_are_sorted() {
    let mut env = std::collections::HashMap::new();
    env.insert("ZEBRA".to_string(), "value1".to_string());
    env.insert("APPLE".to_string(), "value2".to_string());
    env.insert("BANANA".to_string(), "value3".to_string());
    let out = render_env_setup(&env);
    let apple_idx = out.find("APPLE").expect("should contain APPLE");
    let banana_idx = out.find("BANANA").expect("should contain BANANA");
    let zebra_idx = out.find("ZEBRA").expect("should contain ZEBRA");
    assert!(
        apple_idx < banana_idx && banana_idx < zebra_idx,
        "env vars should be sorted alphabetically: {out}"
    );
}

#[test]
fn render_main_test_go_includes_env_setup_at_start() {
    let mut env = std::collections::HashMap::new();
    env.insert("TEST_VAR".to_string(), "test_value".to_string());
    let out = render_main_test_go("test_documents", false, false, &env);

    let dir_idx = out
        .find("dir := filepath.Dir(filename)")
        .expect("should contain dir assignment");
    let test_var_idx = out.find("TEST_VAR").expect("should contain TEST_VAR");

    assert!(dir_idx < test_var_idx, "env setup should come after dir initialization");
}

/// A module path whose last segment is a Go reserved keyword (e.g. `.../packages/go`)
/// must not be emitted verbatim as an import alias — `import go "..."` is a compile
/// error because `go` is a reserved word. The alias is escaped to `go_`.
#[test]
fn render_harness_uses_escaped_alias_for_reserved_keyword_module_segment() {
    let out = super::render_harness_main(&E2eConfig::default(), &[], "github.com/example/acme/packages/go");
    assert!(
        !out.contains("go \"github.com/example/acme/packages/go\""),
        "reserved keyword `go` must not be used as a verbatim import alias, got:\n{out}"
    );
    assert!(
        out.contains("go_ \"github.com/example/acme/packages/go\""),
        "reserved keyword segment `go` should be escaped to alias `go_`, got:\n{out}"
    );
    assert!(
        out.contains("go_.NewApp()"),
        "escaped alias `go_` should be used as the package qualifier, got:\n{out}"
    );
}

/// Render a single test function over `assertions` against a result whose only array
/// field is `results`, so the indexed-assertion emitter is exercised in isolation.
fn render_indexed_assertion_function(assertions: Vec<Assertion>) -> String {
    let mut array_fields = std::collections::HashSet::new();
    array_fields.insert("results".to_string());

    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "extract".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        fields_array: array_fields,
        ..E2eConfig::default()
    };

    let mut fixture = make_fixture("batch_results");
    fixture.assertions = assertions;

    let mut out = String::new();
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "pkg",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );
    out
}

/// A fixture asserting on `results[0]` states that `results` has an element, so the
/// emitted Go must abort on an empty slice and then index unconditionally. Wrapping the
/// assertion in `if len(result.Results) > 0` made the whole check vanish for an empty
/// result, which is how 30 generated Go tests passed without ever asserting anything.
#[test]
fn indexed_assertion_fails_the_test_when_the_collection_is_empty() {
    let out = render_indexed_assertion_function(vec![Assertion {
        assertion_type: "equals".to_string(),
        field: Some("results[0].mime_type".to_string()),
        value: Some(serde_json::Value::String("image/png".to_string())),
        ..Default::default()
    }]);

    let expected = "\tif len(result.Results) == 0 {\n\
         \t\tt.Fatalf(\"expected non-empty %s\", `result.Results`)\n\
         \t}\n\
         \tif string(result.Results[0].MimeType) != `image/png` {\n\
         \t\tt.Errorf(\"equals mismatch: got %v\", result.Results[0].MimeType)\n\
         \t}\n";
    assert!(
        out.contains(expected),
        "expected fatal precondition followed by an unguarded assertion:\n{expected}\ngot:\n{out}"
    );
    assert!(
        !out.contains("if len(result.Results) > 0 {"),
        "the emptiness guard that swallows the assertion must be gone; got:\n{out}"
    );
}

/// `t.Fatalf` aborts the function, so one precondition protects every later index into
/// the same collection. Emitting it per assertion would triple the noise for a fixture
/// that checks three fields of `results[0]`.
#[test]
fn repeated_indexed_assertions_share_one_non_empty_precondition() {
    let out = render_indexed_assertion_function(vec![
        Assertion {
            assertion_type: "equals".to_string(),
            field: Some("results[0].mime_type".to_string()),
            value: Some(serde_json::Value::String("image/png".to_string())),
            ..Default::default()
        },
        Assertion {
            assertion_type: "not_empty".to_string(),
            field: Some("results[0].content".to_string()),
            ..Default::default()
        },
    ]);

    assert_eq!(
        out.matches("t.Fatalf(\"expected non-empty %s\", `result.Results`)")
            .count(),
        1,
        "the precondition should be emitted once per collection; got:\n{out}"
    );
    assert!(
        out.contains("\tif len(result.Results[0].Content) == 0 {\n\t\tt.Errorf(\"expected non-empty value\")\n\t}\n"),
        "the second assertion must still be emitted unguarded; got:\n{out}"
    );
}

/// A fixture that never indexes a collection makes no claim about its length, so no
/// precondition may be invented for it — `not_empty` on the slice itself is the fixture's
/// own way of demanding a non-empty result and must stay a plain, non-fatal check.
#[test]
fn assertion_without_an_index_gets_no_non_empty_precondition() {
    let out = render_indexed_assertion_function(vec![Assertion {
        assertion_type: "not_empty".to_string(),
        field: Some("results".to_string()),
        ..Default::default()
    }]);

    assert!(
        !out.contains("t.Fatalf(\"expected non-empty %s\""),
        "a non-indexed assertion must not gain a fatal precondition; got:\n{out}"
    );
    assert!(
        out.contains("\tif len(result.Results) == 0 {\n\t\tt.Errorf(\"expected non-empty value\")\n\t}\n"),
        "the fixture's own not_empty check must be emitted verbatim; got:\n{out}"
    );
}

/// `len()` does not compile against a Go numeric scalar (e.g. `float64`). A sibling
/// `greater_than_or_equal` assertion against a JSON number on the same field proves the
/// field is a scalar number, so `not_empty` must skip the `len()` call entirely rather than
/// emit code that fails to build. Reverting the fix reintroduces
/// `if len(result.Results[0].QualityScore) == 0 {`, which does not compile.
#[test]
fn not_empty_on_a_numeric_scalar_field_emits_no_len_call() {
    let out = render_indexed_assertion_function(vec![
        Assertion {
            assertion_type: "not_empty".to_string(),
            field: Some("results[0].quality_score".to_string()),
            ..Default::default()
        },
        Assertion {
            assertion_type: "greater_than_or_equal".to_string(),
            field: Some("results[0].quality_score".to_string()),
            value: Some(serde_json::json!(0.0)),
            ..Default::default()
        },
    ]);

    assert!(
        !out.contains("len(result.Results[0].QualityScore)"),
        "not_empty on a numeric scalar must not call len(), which does not compile against \
         a scalar Go type; got:\n{out}"
    );
    assert!(
        !out.contains("t.Errorf(\"expected non-empty value\")"),
        "a numeric scalar always carries a value in Go, so not_empty has nothing to check; got:\n{out}"
    );
}

/// A field with no numeric sibling assertion is presumed sized (string/slice/array/map), so
/// `not_empty` must keep using `len()` — the fix narrows only the proven-scalar case, it does
/// not stop measuring collections and strings.
#[test]
fn not_empty_on_a_sized_field_still_uses_len() {
    let out = render_indexed_assertion_function(vec![Assertion {
        assertion_type: "not_empty".to_string(),
        field: Some("results[0].content".to_string()),
        ..Default::default()
    }]);

    assert!(
        out.contains("\tif len(result.Results[0].Content) == 0 {\n\t\tt.Errorf(\"expected non-empty value\")\n\t}\n"),
        "not_empty on a field with no numeric sibling assertion must still use len(); got:\n{out}"
    );
}

/// Regression test for alef task #86: a `visitor` fixture whose options type resolves
/// from neither `[e2e.call]` nor any `[[crates.trait_bridges]]` entry used to emit a
/// `t.Skip("go: visitor fixture requires trait bridge options_type")` body. That reads
/// as an author-intended skip in `go test` output but is really a config failure, so the
/// emitted suite went green while exercising none of the visitor behavior it claimed.
/// It must now fail at generation time, naming the fixture and the missing options type
/// — mirroring `c/assertions.rs` and `kotlin/args.rs`, which already refuse to emit for
/// an unresolvable trait bridge.
#[test]
#[should_panic(expected = "Go e2e generator: fixture `visitor_smoke` declares a `visitor`")]
fn visitor_fixture_without_trait_bridge_options_type_fails_loudly_instead_of_emitting_a_skip() {
    use crate::e2e::fixture::{CallbackAction, VisitorSpec};

    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "convert".to_string(),
            module: "github.com/example/mylib".to_string(),
            result_var: "result".to_string(),
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };

    let mut fixture = make_fixture("visitor_smoke");
    fixture.visitor = Some(VisitorSpec {
        callbacks: [("visit_element".to_string(), CallbackAction::Skip)]
            .into_iter()
            .collect(),
    });

    let mut out = String::new();
    // No `[[crates.trait_bridges]]` entries declared — nothing supplies an `options_type`.
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );
}

/// Go's `expects_error` branch renders the failure check plus (since the declared-value work) a
/// message-or-type-name comparison, then returns — every other assertion on the fixture used to
/// leave no trace at all in the generated test.
#[test]
fn go_equals_on_an_error_field_is_named_instead_of_dropped() {
    let mut fixture = make_fixture("rate_limited");
    fixture.assertions = vec![
        Assertion {
            assertion_type: "error".to_string(),
            value: Some(serde_json::Value::String("BadRequest".to_string())),
            ..Default::default()
        },
        Assertion {
            assertion_type: "equals".to_string(),
            field: Some("error.status_code".to_string()),
            ..Default::default()
        },
    ];
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "parse".to_string(),
            module: "example.com/sample".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();

    let mut out = String::new();
    let _ = crate::e2e::codegen::take_skip_records();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    // Positive first: the error block really did render, so the absence check below is not
    // vacuously satisfied by a backend that emitted nothing.
    assert!(
        out.contains("t.Errorf(\"expected an error, but call succeeded\")"),
        "the error block must render: {out}"
    );
    assert!(
        out.contains(
            "// skipped: assertion type 'equals' has no accessor for error field error.status_code in this backend"
        ),
        "{out}"
    );

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

/// Negative control: an error fixture with nothing beyond its one `error` assertion must render
/// no marker at all, so the gate stays informative.
#[test]
fn go_a_lone_error_assertion_renders_no_marker() {
    let mut fixture = make_fixture("rejects");
    fixture.assertions = vec![Assertion {
        assertion_type: "error".to_string(),
        ..Default::default()
    }];
    let e2e_config = E2eConfig {
        call: CallConfig {
            function: "parse".to_string(),
            module: "example.com/sample".to_string(),
            returns_result: true,
            ..CallConfig::default()
        },
        ..E2eConfig::default()
    };
    let config = crate::core::config::ResolvedCrateConfig::default();
    let type_defs: Vec<crate::core::ir::TypeDef> = Vec::new();
    let enums: Vec<crate::core::ir::EnumDef> = Vec::new();

    let mut out = String::new();
    render_test_function(
        &mut out,
        &fixture,
        GoTestFunctionContext {
            import_alias: "sample_crate",
            e2e_config: &e2e_config,
            adapters: &[],
            data_enum_names: &std::collections::HashSet::new(),
            config: &config,
            type_defs: &type_defs,
            enums: &enums,
            errors: &[],
            functions: &[],
        },
    );

    assert!(
        out.contains("t.Errorf(\"expected an error, but call succeeded\")"),
        "the error block must render: {out}"
    );
    assert!(!out.contains("has no accessor for error field"), "{out}");
}