alef 0.72.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
//! Result and streaming assertion rendering for generated Python tests.

use std::fmt::Write as FmtWrite;

use crate::e2e::codegen::field_skip::FieldSkip;
use crate::e2e::config::E2eConfig;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::{Assertion, Fixture};

use super::super::assertions::render_assertion;
use super::super::helpers::resolve_assert_enum_fields;
use super::super::json::value_to_python_string;

/// True when `body` contains at least one line that is not blank and not a
/// `#`-prefixed comment — i.e. an executable `assert` statement. A body made
/// up only of "# skipped: ..." comments is not executable.
fn has_real_assertion(body: &str) -> bool {
    body.lines().any(|line| {
        let trimmed = line.trim();
        !trimmed.is_empty() && !trimmed.starts_with('#')
    })
}

/// When a fixture declares at least one assertion but the rendered body has
/// no executable statement — its only assertion was `not_error`, or every
/// field assertion resolved to a "skipped" comment — inject a real assertion
/// on the result instead of leaving the test vacuous. Fixtures that declare
/// NO assertions at all are left untouched: that's a pre-existing, intentional
/// "just call it" smoke test contract (see
/// `should_discard_result_when_force_bind_result_is_unset_and_unused`). ~keep
fn apply_vacuous_assertion_fallback(
    temp_assertions: &mut String,
    has_declared_assertions: bool,
    result_var: &str,
    returns_void: bool,
) {
    if !has_declared_assertions || has_real_assertion(temp_assertions) {
        return;
    }
    // ~keep A void call's binding return is PyO3's mapping of Rust `()` — Python `None` — on
    // every successful call, so `assert result is not None` would fail every successful call,
    // not just an unsuccessful one: a guaranteed-red test, worse than the vacuous body it was
    // meant to replace. There is no result to assert on; a bare, unbound call statement is
    // already non-vacuous in pytest, since an uncaught exception fails the test on its own.
    if returns_void {
        return;
    }
    let _ = writeln!(temp_assertions, "    assert {result_var} is not None");
}

#[allow(clippy::too_many_arguments)]
pub(super) fn emit_result_and_assertions(
    out: &mut String,
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    call_config: &crate::e2e::config::CallConfig,
    call_expr: &str,
    result_var: &str,
    field_resolver: &FieldResolver,
    result_is_simple: bool,
    is_streaming: bool,
    force_bind_result: bool,
) {
    // Streaming virtual fields resolve against the collected `chunks` list, not
    // the result type.
    //
    // ~keep This used to be preceded by a `let _ = fixture.assertions.iter()
    // .any(...)` closure computing a `has_usable_assertion`-shaped predicate
    // (excluding not_error/error, accepting streaming-virtual and
    // result_is_simple fields) whose result was discarded (`let _ =`) and never
    // referenced anywhere in this function — dead code that looked like a check.
    // The real usability decision lives below, derived from what
    // `apply_vacuous_assertion_fallback`/`temp_assertions` actually render, not
    // a separately maintained predicate that can drift out of sync with it (see
    // the php/typescript/ruby fixes for the same drift in this defect class).
    let chunks_var = "chunks";

    let fields_enum = e2e_config.effective_fields_enum(call_config);
    let assert_enum_fields = resolve_assert_enum_fields(call_config);

    // For streaming fixtures: bind the raw iterator, then drain it into a list.
    // The Python ChatStreamIterator exposes __aiter__/__anext__ (async iterator),
    // so the test function must be `async def` and we use `async for` to drain.
    // Note: chat_stream() itself is NOT a coroutine in Python — it returns the
    // iterator synchronously (blocking on stream acquisition via block_on), so
    // no `await` prefix is used on the call expression.
    if is_streaming {
        let _ = writeln!(out, "    {result_var} = {call_expr}");
        if let Some(collect) = crate::e2e::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(
            "python", result_var, chunks_var,
        ) {
            let _ = writeln!(out, "    {collect}");
        }
        // Render streaming assertions into a buffer first (not directly into `out`) so
        // the vacuous-fallback and strict-availability checks below see the whole body,
        // mirroring the non-streaming branch. Before this, a streaming fixture whose only
        // assertions were non-streaming-virtual field checks rendered NO output at all —
        // not even a skip comment — leaving a vacuously-passing test with no fallback. ~keep
        let mut streaming_assertions = String::new();
        for assertion in &fixture.assertions {
            if assertion.assertion_type == "not_error" || assertion.assertion_type == "error" {
                continue;
            }
            if let Some(f) = &assertion.field
                && crate::e2e::codegen::streaming_assertions::is_streaming_virtual_field(f)
            {
                emit_streaming_virtual_assertion(&mut streaming_assertions, assertion, f, chunks_var);
                continue;
            }
            // Non-streaming-virtual assertions on streaming fixtures are skipped
            // (the result type doesn't have these fields during iteration).
            if let Some(f) = assertion.field.as_deref().filter(|f| !f.is_empty()) {
                let _ = writeln!(
                    streaming_assertions,
                    "    # skipped: {}",
                    FieldSkip::NotAvailableOnStreamingResultType.message(f)
                );
            }
        }
        apply_vacuous_assertion_fallback(
            &mut streaming_assertions,
            !fixture.assertions.is_empty(),
            chunks_var,
            call_config.returns_void,
        );
        crate::e2e::codegen::fail_on_unavailable_field_markers(
            &streaming_assertions,
            "python",
            &fixture.id,
            &fixture.assertions,
        );
        crate::e2e::codegen::fail_on_unsupported_assertion_type_markers(&streaming_assertions, "python", &fixture.id);
        out.push_str(&streaming_assertions);
    } else {
        // For non-streaming: render assertions to a temporary buffer first,
        // then check if result_var is referenced. Only emit the assignment if it is.
        let mut temp_assertions = String::new();

        for assertion in &fixture.assertions {
            // `not_error` has no explicit rendering: an uncaught exception already
            // fails the test, so the check is implicit in the call succeeding.
            if assertion.assertion_type == "not_error" {
                continue;
            }
            render_assertion(
                &mut temp_assertions,
                assertion,
                result_var,
                field_resolver,
                fields_enum,
                assert_enum_fields,
                result_is_simple,
            );
        }

        apply_vacuous_assertion_fallback(
            &mut temp_assertions,
            !fixture.assertions.is_empty(),
            result_var,
            call_config.returns_void,
        );
        crate::e2e::codegen::fail_on_unavailable_field_markers(
            &temp_assertions,
            "python",
            &fixture.id,
            &fixture.assertions,
        );
        crate::e2e::codegen::fail_on_unsupported_assertion_type_markers(&temp_assertions, "python", &fixture.id);

        // Check if result_var appears in actual code (not in comments).
        // Only count lines that start with "assert" or contain actual code tokens.
        // Comments (lines starting with #) are skipped to avoid false positives
        // from strings like "field 'result' not available" in comment text.
        let result_var_used = temp_assertions.lines().any(|line| {
            let trimmed = line.trim();
            !trimmed.starts_with('#') && trimmed.contains(result_var)
        });

        let result_binding =
            (result_var_used || fixture.has_docs_presentation() || force_bind_result).then_some(result_var);
        out.push_str(&crate::e2e::template_env::render(
            "python/call_statement.py.jinja",
            minijinja::context! { result_binding => result_binding, call_expr => call_expr },
        ));
        out.push_str(&temp_assertions);
    }
}

/// Emit a Python assertion for a streaming virtual field using the collected
/// `chunks` list.  Mirrors the pattern in rust/assertions.rs.
fn emit_streaming_virtual_assertion(out: &mut String, assertion: &Assertion, field: &str, chunks_var: &str) {
    use crate::e2e::codegen::streaming_assertions::StreamingFieldResolver;

    let Some(expr) = StreamingFieldResolver::accessor(field, "python", chunks_var) else {
        let _ = writeln!(
            out,
            "    # skipped: {}",
            FieldSkip::NoPythonStreamingAccessor.message(field)
        );
        return;
    };

    match assertion.assertion_type.as_str() {
        "count_min" => {
            if let Some(val) = &assertion.value
                && let Some(n) = val.as_u64()
            {
                let _ = writeln!(out, "    assert len({expr}) >= {n}");
            }
        }
        "count_equals" => {
            if let Some(val) = &assertion.value
                && let Some(n) = val.as_u64()
            {
                let _ = writeln!(out, "    assert len({expr}) == {n}");
            }
        }
        "equals" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_python_string(val);
                let op = if val.is_boolean() || val.is_null() { "is" } else { "==" };
                if val.is_string() {
                    let _ = writeln!(out, "    assert {expr}.strip() {op} {expected}.strip()");
                } else {
                    let _ = writeln!(out, "    assert {expr} {op} {expected}");
                }
            }
        }
        "not_empty" => {
            // Bare truthiness would reject a legitimate 0/0.0/False. Only sized values
            // carry an emptiness notion; everything else just has to be present.
            let _ = writeln!(
                out,
                "    assert {expr} is not None and (not hasattr({expr}, \"__len__\") or len({expr}) > 0)"
            );
        }
        "is_empty" => {
            let _ = writeln!(out, "    assert not {expr}");
        }
        "is_true" => {
            // Normalize "true"/"false" literals to Python's True/False.
            let py_expr = if expr == "true" {
                "True".to_string()
            } else if expr == "false" {
                "False".to_string()
            } else {
                expr.clone()
            };
            let _ = writeln!(out, "    assert {py_expr}");
        }
        "is_false" => {
            let py_expr = if expr == "true" {
                "True".to_string()
            } else if expr == "false" {
                "False".to_string()
            } else {
                expr.clone()
            };
            let _ = writeln!(out, "    assert not {py_expr}");
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_python_string(val);
                let _ = writeln!(out, "    assert {expr} > {expected}");
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_python_string(val);
                let _ = writeln!(out, "    assert {expr} >= {expected}");
            }
        }
        "contains" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_python_string(val);
                let _ = writeln!(out, "    assert {expected} in {expr}");
            }
        }
        other => {
            panic!("Python e2e generator: unsupported assertion type '{other}' on synthetic field '{field}'");
        }
    }
}

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

    fn assertion(assertion_type: &str, field: Option<&str>, value: Option<serde_json::Value>) -> Assertion {
        Assertion {
            skip: None,
            assertion_type: assertion_type.to_string(),
            field: field.map(str::to_string),
            value,
            values: None,
            method: None,
            check: None,
            args: None,
            return_type: None,
        }
    }

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

    #[test]
    fn streaming_virtual_assertion_renders_collected_chunks_access() {
        let mut out = String::new();
        let assertion = assertion("count_min", Some("chunks"), Some(serde_json::Value::from(1)));

        emit_streaming_virtual_assertion(&mut out, &assertion, "chunks", "chunks");

        assert!(out.contains("assert len(chunks) >= 1"), "got: {out}");
    }

    #[test]
    fn not_empty_for_python_streaming_rejects_empty_chunks_but_accepts_zero() {
        let mut out = String::new();
        let assertion = assertion("not_empty", Some("chunks"), None);

        emit_streaming_virtual_assertion(&mut out, &assertion, "chunks", "chunks");

        // Bare `assert chunks` fails on a legitimate 0, 0.0 or False.
        assert_eq!(
            out.trim(),
            "assert chunks is not None and (not hasattr(chunks, \"__len__\") or len(chunks) > 0)"
        );
    }

    #[test]
    fn call_statement_omits_binding_when_the_result_is_unused() {
        let rendered = crate::e2e::template_env::render(
            "python/call_statement.py.jinja",
            minijinja::context! { result_binding => Option::<&str>::None, call_expr => "await process(value)" },
        );

        assert_eq!(rendered, "    await process(value)\n");
        assert!(!rendered.contains("result ="));
        assert!(!rendered.contains("_ ="));
    }

    #[test]
    fn should_bind_result_when_force_bind_result_is_set_with_no_assertions() {
        let fixture = minimal_fixture();
        let e2e_config = E2eConfig::default();
        let call_config = crate::e2e::config::CallConfig::default();
        let field_resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();

        emit_result_and_assertions(
            &mut out,
            &fixture,
            &e2e_config,
            &call_config,
            "await widget_client.create()",
            "result",
            &field_resolver,
            false,
            false,
            true,
        );

        assert!(
            out.contains("result = await widget_client.create()"),
            "expected the call result to be bound so a caller can print it, got: {out}"
        );
    }

    #[test]
    fn should_discard_result_when_force_bind_result_is_unset_and_unused() {
        let fixture = minimal_fixture();
        let e2e_config = E2eConfig::default();
        let call_config = crate::e2e::config::CallConfig::default();
        let field_resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();

        emit_result_and_assertions(
            &mut out,
            &fixture,
            &e2e_config,
            &call_config,
            "await widget_client.create()",
            "result",
            &field_resolver,
            false,
            false,
            false,
        );

        assert!(!out.contains("result ="), "unused result must not be bound, got: {out}");
    }

    #[test]
    fn has_real_assertion_is_false_for_comment_only_body() {
        let body = "    # skipped: field 'foo' not available on result type\n";
        assert!(
            !has_real_assertion(body),
            "comment-only body must not count as asserting"
        );
    }

    #[test]
    fn has_real_assertion_is_true_when_a_real_statement_is_present() {
        let body = "    # skipped: field 'foo' not available on result type\n    assert result.ok\n";
        assert!(has_real_assertion(body), "a real assert line must count as asserting");
    }

    #[test]
    fn vacuous_fallback_is_a_noop_without_declared_assertions() {
        let mut body = String::new();
        apply_vacuous_assertion_fallback(&mut body, false, "result", false);
        assert!(
            body.is_empty(),
            "a fixture with no declared assertions is an intentional smoke test and must stay untouched"
        );
    }

    #[test]
    fn vacuous_fallback_emits_a_real_assertion_when_body_is_empty() {
        let mut body = String::new();
        apply_vacuous_assertion_fallback(&mut body, true, "result", false);
        assert_eq!(body, "    assert result is not None\n");
    }

    #[test]
    fn vacuous_fallback_emits_a_real_assertion_over_comment_only_body() {
        let mut body = "    # skipped: field 'chunks' not available on result type\n".to_string();
        apply_vacuous_assertion_fallback(&mut body, true, "result", false);
        assert!(
            body.contains("assert result is not None"),
            "a comment-only body must still get a real fallback assertion, got: {body}"
        );
    }

    #[test]
    fn vacuous_fallback_leaves_a_real_assertion_untouched() {
        let mut body = "    assert result.count == 1\n".to_string();
        let original = body.clone();
        apply_vacuous_assertion_fallback(&mut body, true, "result", false);
        assert_eq!(
            body, original,
            "a fixture with a real assertion must not get an extra fallback line"
        );
    }

    /// Regression test for the void `not_error` defect: before this fix, a `returns_void`
    /// fixture whose only declared assertion was `not_error` fell into the fallback and emitted
    /// `assert result is not None` — but PyO3 maps a void call's `Ok(())` to Python `None`, so
    /// that assertion FAILED on every successful call, not just an unsuccessful one.
    #[test]
    fn vacuous_fallback_emits_nothing_for_a_void_call() {
        let mut body = String::new();
        apply_vacuous_assertion_fallback(&mut body, true, "result", true);
        assert!(
            body.is_empty(),
            "a void call's result is always None; asserting not-None would fail every successful \
             call, got: {body}"
        );
    }

    /// Regression test for the not_error-only vacuous-test defect: a fixture whose
    /// only declared assertion is `not_error` must bind the call result and emit a
    /// real assertion, not silently discard the result with no assertion at all.
    #[test]
    fn not_error_only_fixture_binds_result_and_emits_real_assertion() {
        let mut fixture = minimal_fixture();
        fixture.assertions = vec![assertion("not_error", None, None)];
        let e2e_config = E2eConfig::default();
        let call_config = crate::e2e::config::CallConfig::default();
        let field_resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();

        emit_result_and_assertions(
            &mut out,
            &fixture,
            &e2e_config,
            &call_config,
            "await widget_client.create()",
            "result",
            &field_resolver,
            false,
            false,
            false,
        );

        assert!(
            out.contains("result = await widget_client.create()"),
            "a not_error-only fixture must bind the result, got: {out}"
        );
        assert!(
            out.contains("assert result is not None"),
            "a not_error-only fixture must emit a real assertion instead of a vacuous body, got: {out}"
        );
    }

    /// Regression test for the void `not_error` defect: before this fix, a `returns_void`
    /// fixture whose only declared assertion was `not_error` bound the result and asserted
    /// `assert result is not None` — but PyO3 maps a void call's `Ok(())` to Python `None`, so
    /// this assertion FAILED every successful call. The correct rendering is a bare, unbound
    /// call statement: an uncaught exception already fails a pytest test on its own.
    #[test]
    fn void_not_error_fixture_emits_a_bare_unbound_call_not_a_guaranteed_failure() {
        let mut fixture = minimal_fixture();
        fixture.assertions = vec![assertion("not_error", None, None)];
        let e2e_config = E2eConfig::default();
        let call_config = crate::e2e::config::CallConfig {
            returns_void: true,
            ..Default::default()
        };
        let field_resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();

        emit_result_and_assertions(
            &mut out,
            &fixture,
            &e2e_config,
            &call_config,
            "await widget_client.prefetch()",
            "result",
            &field_resolver,
            false,
            false,
            false,
        );

        assert!(
            !out.contains("assert result is not None"),
            "a void call's result is always None; asserting not-None would fail every successful \
             call, got: {out}"
        );
        assert!(
            out.contains("await widget_client.prefetch()") && !out.contains("result ="),
            "a void not_error-only fixture must emit a bare, unbound call statement, got: {out}"
        );
    }

    #[test]
    #[should_panic(expected = "unsupported assertion type 'bogus_type' on synthetic field 'chunks'")]
    fn python_streaming_virtual_unsupported_type_fails_loudly() {
        let mut out = String::new();
        let assertion = assertion("bogus_type", Some("chunks"), None);
        emit_streaming_virtual_assertion(&mut out, &assertion, "chunks", "chunks");
    }

    #[test]
    fn python_streaming_virtual_supported_type_renders_assertion() {
        let mut out = String::new();
        let assertion = assertion("greater_than", Some("chunks"), Some(serde_json::Value::from(2)));
        emit_streaming_virtual_assertion(&mut out, &assertion, "chunks", "chunks");
        assert_eq!(out.trim(), "assert chunks > 2");
    }

    /// Regression test for alef task #81, hole 3: the streaming branch of
    /// `emit_result_and_assertions` used to render nothing at all — not even a
    /// skip comment — for a fixture whose only declared assertion was a
    /// non-streaming-virtual field. That left a vacuously-passing streaming test
    /// with an entirely empty body. It must now get the same real fallback
    /// assertion the non-streaming branch has always gotten.
    #[test]
    fn streaming_fixture_whose_only_assertion_is_non_virtual_gets_a_vacuous_fallback() {
        let mut fixture = minimal_fixture();
        fixture.assertions = vec![assertion(
            "equals",
            Some("not_a_streaming_field"),
            Some(serde_json::json!("x")),
        )];
        let e2e_config = E2eConfig::default();
        let call_config = crate::e2e::config::CallConfig::default();
        let field_resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();

        emit_result_and_assertions(
            &mut out,
            &fixture,
            &e2e_config,
            &call_config,
            "chat_stream(request)",
            "result",
            &field_resolver,
            false,
            true,
            false,
        );

        assert!(
            out.contains("not_a_streaming_field' not available on streaming result type"),
            "the dropped field must still be named in a skip comment, got: {out}"
        );
        assert!(
            out.contains("assert chunks is not None"),
            "a streaming fixture with a declared but unusable assertion must still get a real \
             fallback assertion instead of an entirely empty body, got: {out}"
        );
    }

    /// Positive control for the same fix: a streaming fixture whose assertion IS a
    /// real streaming-virtual field must render only the real assertion — no skip
    /// comment, and the vacuous-fallback must not fire (a real assertion is present).
    #[test]
    fn streaming_fixture_with_a_real_streaming_assertion_is_not_touched_by_the_fallback() {
        let mut fixture = minimal_fixture();
        fixture.assertions = vec![assertion("count_min", Some("chunks"), Some(serde_json::json!(1)))];
        let e2e_config = E2eConfig::default();
        let call_config = crate::e2e::config::CallConfig::default();
        let field_resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();

        emit_result_and_assertions(
            &mut out,
            &fixture,
            &e2e_config,
            &call_config,
            "chat_stream(request)",
            "result",
            &field_resolver,
            false,
            true,
            false,
        );

        assert!(out.contains("assert len(chunks) >= 1"), "got: {out}");
        assert!(
            !out.contains("not available"),
            "a real assertion must not trigger the fallback, got: {out}"
        );
    }

    /// Regression test for alef task #81: the non-streaming branch's "skipped: field
    /// not available" comment must survive as the exact marker text the shared
    /// `fail_on_unavailable_field_markers` mechanism (src/e2e/codegen/mod.rs) matches
    /// on, so that arming `ALEF_E2E_STRICT_FIELD_AVAILABILITY` turns it into a
    /// generation-time failure instead of a silently-passing comment. This test does
    /// not set the env var (tests must stay independent of shared process state); the
    /// arming behaviour itself is proven in `mod.rs`'s
    /// `unavailable_field_marker_tests` against the same marker text asserted here.
    #[test]
    fn non_streaming_skip_comment_carries_the_marker_the_strict_mode_matches_on() {
        let mut fixture = minimal_fixture();
        fixture.assertions = vec![assertion(
            "equals",
            Some("nonexistent_field"),
            Some(serde_json::json!("x")),
        )];
        let e2e_config = E2eConfig::default();
        let call_config = crate::e2e::config::CallConfig::default();
        let result_fields: std::collections::HashSet<String> = ["content".to_string()].into_iter().collect();
        let field_resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &result_fields,
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();

        emit_result_and_assertions(
            &mut out,
            &fixture,
            &e2e_config,
            &call_config,
            "widget_client.create()",
            "result",
            &field_resolver,
            false,
            false,
            false,
        );

        assert!(
            out.contains("field 'nonexistent_field' not available on result type"),
            "got: {out}"
        );
    }
}