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
//! Kotlin assertion rendering helpers.
//!
//! ~keep This file is already over the repo's 1,000-line file-modularization cap. The
//! `not_error_may_assert_presence` unification (routing `not_error` through
//! `not_error_presence::may_assert_presence`) added one parameter to `render_assertion`,
//! required at every call site — the small net growth here is that mechanical churn plus the
//! `not_error` arm's updated doc comment, not new unrelated functionality.
use heck::ToLowerCamelCase;
use std::fmt::Write as FmtWrite;
use crate::e2e::codegen::assertion_type_skip::{
streaming_assertion_type_skip_line, streaming_assertion_value_skip_line,
};
use crate::e2e::codegen::field_skip::{FieldSkip, nested_wildcard_skip_line};
use crate::e2e::escape::escape_kotlin;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::Assertion;
#[allow(clippy::too_many_arguments)]
pub(super) fn render_assertion(
out: &mut String,
assertion: &Assertion,
result_var: &str,
_class_name: &str,
field_resolver: &FieldResolver,
result_is_simple: bool,
result_is_option: bool,
enum_fields: &std::collections::HashSet<String>,
json_scalar_fields: &std::collections::HashSet<String>,
fields_c_types: &std::collections::HashMap<String, String>,
is_streaming: bool,
kotlin_android_style: bool,
not_error_may_assert_presence: bool,
) {
// In streaming context, `usage` and `usage.*` fields must be read from the
// last collected chunk, not from the stream iterator (which has no `usage()` method).
// Route them through `StreamingFieldResolver::accessor("usage", ...)` + deep-tail
// rendering, using `chunks.last().usage()` as the base expression.
if is_streaming
&& let Some(f) = &assertion.field
&& (f == "usage" || f.starts_with("usage."))
{
let stream_lang = if kotlin_android_style {
"kotlin_android"
} else {
"kotlin"
};
let base_expr =
crate::e2e::codegen::streaming_assertions::StreamingFieldResolver::accessor("usage", stream_lang, "chunks")
.unwrap_or_else(|| {
if kotlin_android_style {
"(if (chunks.isEmpty()) null else chunks.last().usage)".to_string()
} else {
"(if (chunks.isEmpty()) null else chunks.last().usage())".to_string()
}
});
// For a deep path like `usage.total_tokens`, render the tail `.total_tokens`
// in a language-appropriate accessor style.
let expr = if let Some(tail) = f.strip_prefix("usage.") {
if kotlin_android_style {
// kotlin-android: data classes use Kotlin property access (no parens).
tail.split('.')
.fold(base_expr, |acc, seg| format!("{acc}?.{}", seg.to_lower_camel_case()))
} else {
// Kotlin/Java: accessor methods have parens.
tail.split('.')
.fold(base_expr, |acc, seg| format!("{acc}?.{}()", seg.to_lower_camel_case()))
}
} else {
base_expr
};
// Determine if the field maps to a 64-bit C type requiring `L` suffix.
let field_is_long = fields_c_types
.get(f.as_str())
.is_some_and(|t| matches!(t.as_str(), "uint64_t" | "int64_t"));
let line = match assertion.assertion_type.as_str() {
"equals" => {
if let Some(expected) = &assertion.value {
let kotlin_val = if field_is_long && expected.is_number() && !expected.is_f64() {
format!("{}L", expected)
} else {
super::values::json_to_kotlin(expected)
};
format!(" assertEquals({kotlin_val}, {expr}!!)\n")
} else {
streaming_assertion_value_skip_line(" ", "//", f, &assertion.assertion_type) + "\n"
}
}
// ~keep This arm covered every assertion type but `equals` and rendered an empty
// string, so a `not_empty`/`greater_than`/... against a streaming `usage.*` path
// disappeared with no line for any funnel to count. The renderer really does only
// implement `equals` here, which is alef's gap to close, not the fixture's.
_ => streaming_assertion_type_skip_line(" ", "//", f, &assertion.assertion_type) + "\n",
};
out.push_str(&line);
return;
}
// Streaming virtual fields resolve against the `chunks` collected-list variable.
// Intercept before is_valid_for_result so they are never skipped.
// Gate on `is_streaming` so non-streaming fixtures (e.g. consumers whose real
// result struct has a literal `chunks` field) don't divert into the virtual
// accessor path — they should fall through to the normal field resolver.
if let Some(f) = &assertion.field
&& is_streaming
&& !f.is_empty()
&& crate::e2e::codegen::streaming_assertions::is_streaming_virtual_field(f)
{
let stream_lang = if kotlin_android_style {
"kotlin_android"
} else {
"kotlin"
};
if let Some(expr) =
crate::e2e::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, stream_lang, "chunks")
{
let line = match assertion.assertion_type.as_str() {
"count_min" => {
if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
format!(" assertTrue({expr}.size >= {n}, \"expected >= {n} chunks\")\n")
} else {
streaming_assertion_value_skip_line(" ", "//", f, &assertion.assertion_type) + "\n"
}
}
"count_equals" => {
if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
format!(
" assertEquals({n}.toLong(), {expr}.size.toLong(), \"expected exactly {n} elements\")\n"
)
} else {
streaming_assertion_value_skip_line(" ", "//", f, &assertion.assertion_type) + "\n"
}
}
"equals" => {
if let Some(serde_json::Value::String(s)) = &assertion.value {
let escaped = escape_kotlin(s);
format!(" assertEquals(\"{escaped}\", {expr})\n")
} else if let Some(b) = assertion.value.as_ref().and_then(|v| v.as_bool()) {
format!(" assertEquals({b}, {expr})\n")
} else {
streaming_assertion_value_skip_line(" ", "//", f, &assertion.assertion_type) + "\n"
}
}
"not_empty" => {
format!(" assertFalse({expr}.isEmpty(), \"expected non-empty\")\n")
}
"is_empty" => {
format!(" assertTrue({expr}.isEmpty(), \"expected empty\")\n")
}
"is_true" => {
format!(" assertTrue({expr} == true, \"expected true\")\n")
}
"is_false" => {
format!(" assertTrue({expr} == false, \"expected false\")\n")
}
"greater_than" => {
if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
format!(" assertTrue({expr} > {n}, \"expected > {n}\")\n")
} else {
streaming_assertion_value_skip_line(" ", "//", f, &assertion.assertion_type) + "\n"
}
}
"contains" => {
if let Some(serde_json::Value::String(s)) = &assertion.value {
let escaped = escape_kotlin(s);
// Use `.toString().lowercase().contains(...)` to mirror the Java
// emitter — `(list as List<String>)` is an unchecked cast that
// succeeds at runtime via erasure but `.contains("Module")` then
// compares `StructureItem`s against a `String` and always returns
// `false`. Stringifying the collection lets the assertion match
// both `List<String>` and `List<ComplexType>` cases uniformly.
format!(
" assertTrue({expr}.toString().lowercase().contains(\"{escaped}\".lowercase()), \"expected to contain: {escaped}\")\n"
)
} else {
streaming_assertion_value_skip_line(" ", "//", f, &assertion.assertion_type) + "\n"
}
}
_ => format!(
"{}\n",
streaming_assertion_type_skip_line(" ", "//", f, &assertion.assertion_type)
),
};
out.push_str(&line);
} else {
// ~keep The accessor returns `None` for reachable inputs (a `stream.has_*_event`
// predicate never resolves through `accessor`, which supplies no item type), and this
// branch used to be absent: the assertion vanished with no line for
// `fail_on_unavailable_field_markers` to see. alef's streaming adapter owns the gap,
// so it is counted, never fatal.
let _ = writeln!(
out,
" // skipped: {}",
FieldSkip::StreamingAssertionOnUnsupportedField.message(f)
);
}
return;
}
// Skip assertions on fields that don't exist on the result type.
if let Some(f) = &assertion.field
&& !f.is_empty()
&& !field_resolver.is_valid_for_result(f)
{
let _ = writeln!(
out,
" // skipped: {}",
FieldSkip::NotAvailableOnResultType.message(f)
);
return;
}
// Discriminated-union navigation (sealed `FormatMetadata` in Kotlin).
// Field paths like `metadata.format.excel.sheet_count` cannot be expressed as
// a flat property chain because `FormatMetadata` is a sealed class with
// variant subclasses (`FormatMetadata.Excel`, `FormatMetadata.Pdf`, …); each
// variant exposes its payload through a `.metadata` property of the variant
// type. Emit an `is`-pattern `when` block that binds the variant, then
// delegate the leaf assertion to `render_discriminated_union_assertion`.
if kotlin_android_style
&& let Some(f) = assertion.field.as_deref().filter(|f| !f.is_empty())
&& let Some((variant_pascal, inner_field)) = super::discriminated::parse_discriminated_union_access(f)
{
let variant_var = format!("format{variant_pascal}");
// Resolve the discriminated-union container (`…metadata.format`) through the
// field resolver so list-result field paths (`results[0].metadata.format.…`)
// index into `.results.first()` like the flat-field assertions do, instead of
// hardcoding `{result_var}.metadata.format` (metadata lives on each result,
// not the top-level ExtractionResult, so batch results would not compile).
let format_path = match f.find(".format") {
Some(idx) => &f[..idx + ".format".len()],
None => f,
};
let container = field_resolver.accessor(format_path, "kotlin_android", result_var);
let _ = writeln!(out, " when (val {variant_var} = {container}) {{");
let _ = writeln!(out, " is FormatMetadata.{variant_pascal} -> {{");
super::discriminated::render_discriminated_union_assertion(out, assertion, &variant_var, &inner_field);
let _ = writeln!(out, " }}");
let _ = writeln!(out, " else -> {{}}");
let _ = writeln!(out, " }}");
return;
}
// Determine if this field is an enum type. `enum_fields` carries the effective
// hand-maintained config (merged with the call-level `type_enum_fields` auto-detect in
// test_method.rs, which itself requires a `result_type` override to anchor). When neither
// names the field, `field_resolver.is_enum` falls back to the IR-derived classification
// (`with_ir_enum_map`, anchored at the call's declared Rust return type via
// `resolve_declared_result_type`) so a consumer that never configured either still gets a
// correct classification. This is purely additive — it only turns a `false` into `true`. ~keep
let field_is_enum = assertion.field.as_deref().is_some_and(|f| {
enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)) || field_resolver.is_enum(f)
});
// Determine if this field's resolved type is an untyped JSON scalar (Kotlin
// `Any?`, from Rust `Option<serde_json::Value>`) rather than `Option<String>`.
// `.orEmpty()` does not resolve on `Any?` — see `field_is_json_scalar` usage
// below, where the string-context expression falls back to a null-safe
// stringify instead.
let field_is_json_scalar = assertion
.field
.as_deref()
.is_some_and(|field| field_resolver.is_json_scalar(field, json_scalar_fields));
// Determine if this field is a display_as_text field (e.g., AssistantContent).
// These fields have a `.text()` accessor that extracts the plain-text representation.
let field_is_display_as_text = assertion
.field
.as_deref()
.is_some_and(|f| field_resolver.is_display_as_text(f));
// Raw field accessor — may end with nullable type if field is optional.
// kotlin_android data classes expose properties (no parens), so use the
// dedicated "kotlin_android" language key for the accessor renderer.
let accessor_lang = if kotlin_android_style {
"kotlin_android"
} else {
"kotlin"
};
// Bracket-wildcard traversal (`links[].link_type`) means "any element", so it must
// render an `any { … }` quantifier. Falling through to `accessor` would lower the
// wildcard to index 0 and silently assert against only the first element. Keyed off
// the fixture path alone — config sets (`fields_json_scalar` etc.) also use the `[]`
// spelling for fields whose fixture paths carry explicit indices. ~keep
if !result_is_simple
&& let Some(f) = assertion.field.as_deref().filter(|f| !f.is_empty())
&& let Some((array_part, elem_part)) = field_resolver.wildcard_split(f)
{
// `wildcard_split` consumes the first `[].` only, so a doubly-nested path leaves a
// second wildcard in `elem_part`. Kotlin's renderer lowers it to `.first()` rather than
// a visible `[0]`, which makes the collapse even harder to spot in review. ~keep
if let Some(line) = nested_wildcard_skip_line(" ", "//", f, &elem_part) {
let _ = writeln!(out, "{line}");
return;
}
let raw_array_accessor = if array_part.is_empty() {
result_var.to_string()
} else {
field_resolver.accessor(&array_part, accessor_lang, result_var)
};
// A nullable array receiver cannot take `.any {}` directly; `orEmpty()` yields an
// empty list, which makes the quantifier false rather than a null-pointer. ~keep
let array_is_nullable =
raw_array_accessor.contains("?.") || (!array_part.is_empty() && field_resolver.is_optional(&array_part));
let array_accessor = if array_is_nullable {
format!("{raw_array_accessor}.orEmpty()")
} else {
raw_array_accessor
};
// Passing the lambda parameter as the result var is what lets a nested element
// sub-path resolve against the loop variable instead of the result. ~keep
let elem_accessor = field_resolver.accessor(&elem_part, accessor_lang, "e");
match assertion.assertion_type.as_str() {
"contains" | "contains_all" | "not_contains" => {
let negated = assertion.assertion_type == "not_contains";
let assert_fn = if negated { "assertFalse" } else { "assertTrue" };
let expectation = if negated {
"expected NOT to contain: "
} else {
"expected to contain: "
};
for expected in assertion.expected_values() {
let kotlin_val = super::values::json_to_kotlin(expected);
let _ = writeln!(
out,
" {assert_fn}({array_accessor}.any {{ e -> {elem_accessor}.toString().contains({kotlin_val}) }}, \"{expectation}\" + {kotlin_val})"
);
}
}
"not_empty" => {
let _ = writeln!(
out,
" assertTrue({array_accessor}.any {{ e -> {elem_accessor}.toString().isNotEmpty() }}, \"expected a non-empty element in '{f}'\")"
);
}
other => {
let _ = writeln!(
out,
" // skipped: unsupported traversal assertion '{other}' on '{f}'"
);
}
}
return;
}
let field_expr = if result_is_simple {
result_var.to_string()
} else {
match &assertion.field {
Some(f) if !f.is_empty() => field_resolver.accessor(f, accessor_lang, result_var),
_ => result_var.to_string(),
}
};
// Whether the accessor may return a nullable type in Kotlin. This is true
// when the leaf field OR any intermediate segment in the path is optional
// (the `?.` safe-call propagates null through the whole chain).
//
// Additionally, if the generated accessor expression itself contains `?.`
// then the return type is `T?` regardless of what the path-resolver says —
// sticky nullability means any `?.` in the chain makes the whole expression
// nullable. This handles cases like `toolCalls()?.first()?.function()?.name()`
// where the `is_optional` prefix lookup misses due to index notation mismatch.
let field_is_optional = !result_is_simple
&& (field_expr.contains("?.")
|| assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
let resolved = field_resolver.resolve(f);
if field_resolver.has_map_access(f) {
// Kotlin's `Map<K, V>.get(key)` always returns `V?`. In the
// kotlin_android target, DTOs are pure Kotlin data classes so
// the nullable propagates through and string operations on
// the result must coalesce or safe-call. In the kotlin/JVM
// target the same map field flows through Java records and
// appears as a platform type, so adding `.orEmpty()` is
// unnecessary but harmless — keep the legacy behaviour for
// JVM to avoid churning unrelated snapshots.
return kotlin_android_style;
}
// Check the leaf field itself.
if field_resolver.is_optional(resolved) {
return true;
}
// Also check every prefix segment: if any intermediate field is
// optional the ?. chain propagates null to the final result.
let mut prefix = String::new();
for part in resolved.split('.') {
// Strip array notation for the lookup key.
let key = part.split('[').next().unwrap_or(part);
if !prefix.is_empty() {
prefix.push('.');
}
prefix.push_str(key);
if field_resolver.is_optional(&prefix) {
return true;
}
}
false
}));
// String-context expression: append .orEmpty() for nullable string fields so
// string operations (contains, trim) don't require a safe-call chain.
// Note: this is only sound when the leaf type is `String?`. For enum-typed
// optional fields (`T?` where `T` is an enum class), `.orEmpty()` is undefined;
// the enum branch below handles those by going through `?.getValue()` first.
// For fields in `json_scalar_fields` (`Any?`, e.g. `Option<serde_json::Value>`),
// `.orEmpty()` is likewise undefined; stringify through `?.toString()` first.
// For display_as_text fields (e.g., AssistantContent), call `.text()` to extract
// the textual representation, which returns `String` (non-nullable).
// Also handle the case where the bare result (no field specified) is nullable
// due to `result_is_option` being true.
let bare_result_is_nullable = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
let string_field_expr = if field_is_display_as_text {
// display_as_text fields have a .text() accessor returning String
if field_is_optional {
format!("{field_expr}?.text().orEmpty()")
} else {
format!("{field_expr}.text()")
}
} else if field_is_json_scalar {
// `.orEmpty()` is a `String?`/`CharSequence?` extension and is undefined on
// `Any?` — stringify through a null-safe call first (`Any?.toString()` is
// always defined), then coalesce the resulting `String?` the same way.
format!("{field_expr}?.toString().orEmpty()")
} else if bare_result_is_nullable {
format!("{field_expr}?.toString().orEmpty()")
} else if field_is_optional {
format!("{field_expr}.orEmpty()")
} else {
field_expr.clone()
};
// Non-null expression: use !! to assert presence for numeric comparisons where
// the fixture guarantees the value is non-null.
let nonnull_field_expr = if field_is_optional {
format!("{field_expr}!!")
} else {
field_expr.clone()
};
// For enum fields, convert to string for comparison.
//
// - JVM (kotlin) mode: The Java facade wraps enums in a Java enum type that
// exposes a `.getValue()` accessor. Use `.getValue()` (with optional-safe
// variant when the field is nullable), mirroring the Java codegen pattern
// `Optional.ofNullable(...).map(v -> v.getValue()).orElse("")`.
//
// - kotlin_android mode: every fieldless `enum class` carries a `fun toWire(): String`
// returning the exact `wire_variant_value` per constant, the same string `@JsonValue`
// serializes. A prior `.name.lowercase()` wrongly assumed every wire value is the
// Kotlin constant name lowercased (`IN_PROGRESS` -> `"in_progress"`); that fails for
// `DataNodeKind` (no `rename_all`): `KEY_VALUE` -> `"keyvalue"`, not `"KeyValue"`. ~keep
let string_expr = if kotlin_android_style {
match (field_is_enum, field_is_optional) {
(true, true) => format!("{field_expr}?.toWire().orEmpty()"),
(true, false) => format!("{field_expr}.toWire()"),
(false, _) => string_field_expr.clone(),
}
} else {
match (field_is_enum, field_is_optional) {
(true, true) => format!("{field_expr}?.getValue().orEmpty()"),
(true, false) => format!("{field_expr}.getValue()"),
(false, _) => string_field_expr.clone(),
}
};
// Determine if this assertion field maps to a 64-bit C type (uint64_t / int64_t),
// which corresponds to Kotlin `Long`. When true, integer literals must be suffixed
// with `L` to avoid a type mismatch between Kotlin `Int` and `Long`.
let field_is_long = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
let resolved = field_resolver.resolve(f);
matches!(
fields_c_types.get(resolved).map(String::as_str),
Some("uint64_t") | Some("int64_t")
)
});
// Determine whether the field's underlying type is a list/collection. For
// `contains` / `contains_all` / `not_contains` assertions on `List<String>`
// fields Kotlin requires a cast to `List<String>` so the `@OnlyInputTypes`
// annotation on `Collection.contains()` can infer `T`. For plain `String`
// fields (e.g. `result.text` on TranscribeTest) the assertion is a
// substring check on a `String` — emitting `(s as List<String>).contains`
// throws ClassCastException at runtime, so the cast must be gated on the
// field actually being a collection. `field_resolver.is_array` is true for
// paths in `fields_array`; `is_collection_root` is true when the field is
// a top-level collection accessor (e.g. `tags` whose entries are tracked
// as `tags[0]` in `fields_array`).
let field_is_collection = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
let resolved = field_resolver.resolve(f);
field_resolver.is_array(f)
|| field_resolver.is_array(resolved)
|| field_resolver.is_collection_root(f)
|| field_resolver.is_collection_root(resolved)
});
match assertion.assertion_type.as_str() {
"equals" => {
if let Some(expected) = &assertion.value {
// Suffix integer literals with `L` when the target field is a Java `long`
// (uint64_t / int64_t in C FFI terms). Without the suffix, Kotlin infers
// the literal as `Int`, causing a type mismatch with `Long` at runtime.
let kotlin_val = if field_is_long && expected.is_number() && !expected.is_f64() {
format!("{}L", expected)
} else {
super::values::json_to_kotlin(expected)
};
if expected.is_string() {
let _ = writeln!(out, " assertEquals({kotlin_val}, {string_expr})");
} else {
let _ = writeln!(out, " assertEquals({kotlin_val}, {nonnull_field_expr})");
}
}
}
"contains" => {
if let Some(expected) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(expected);
if field_is_collection {
// `(list as List<String>)` is an unchecked erasure cast that
// succeeds at runtime even for `List<StructureItem>` etc.
// `.contains("Module")` then compares records against a
// String and always fails. Stringifying the collection
// mirrors the Java emitter (`toString().toLowerCase().contains(...)`)
// and matches both `List<String>` and `List<ComplexType>`.
let _ = writeln!(
out,
" assertTrue({string_expr}.toString().lowercase().contains({kotlin_val}.toString().lowercase()), \"expected to contain: \" + {kotlin_val})"
);
} else {
// String substring check. Use the field expression directly so
// `String.contains(CharSequence)` resolves without a cast.
let _ = writeln!(
out,
" assertTrue({string_expr}.contains({kotlin_val}), \"expected to contain: \" + {kotlin_val})"
);
}
}
}
"contains_all" => {
if let Some(values) = &assertion.values {
for val in values {
let kotlin_val = super::values::json_to_kotlin(val);
if field_is_collection {
let _ = writeln!(
out,
" assertTrue({string_expr}.toString().lowercase().contains({kotlin_val}.toString().lowercase()), \"expected to contain: \" + {kotlin_val})"
);
} else {
let _ = writeln!(
out,
" assertTrue({string_expr}.contains({kotlin_val}), \"expected to contain: \" + {kotlin_val})"
);
}
}
}
}
"not_contains" => {
for expected in assertion.expected_values() {
let kotlin_val = super::values::json_to_kotlin(expected);
if field_is_collection {
let _ = writeln!(
out,
" assertFalse({string_expr}.toString().lowercase().contains({kotlin_val}.toString().lowercase()), \"expected NOT to contain: \" + {kotlin_val})"
);
} else {
let _ = writeln!(
out,
" assertFalse({string_expr}.contains({kotlin_val}), \"expected NOT to contain: \" + {kotlin_val})"
);
}
}
}
"not_empty" => {
// For optional fields, the field type may be a non-String object
// (e.g. DocumentStructure) for which `.orEmpty()` is undefined. A
// null-check is the safe primitive: it works for any reference type
// and matches the Java codegen's `Optional.ofNullable(...).isEmpty()`.
// When the bare result is `T?` (result_is_option) the same null-check
// applies, because `.isEmpty()` is undefined on arbitrary nullable types.
// The JVM Kotlin e2e tests call the Java facade class which returns
// `java.util.Optional<T>` for option results — use `.isPresent` rather
// than `!= null` so the assertion semantics match the JVM return type.
// The kotlin-android wrapper unwraps `Optional<T>` to Kotlin's `T?`
// at the boundary, so its bare-option result is a nullable reference
// and must use `!= null` instead.
let bare_result_is_option =
result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
if bare_result_is_option && !kotlin_android_style {
out.push_str(&crate::e2e::template_env::render(
"kotlin/not_empty_assertion.kt.jinja",
minijinja::context! { predicate => format!("{field_expr}.isPresent") },
));
} else if field_is_collection && (bare_result_is_option || field_is_optional) {
out.push_str(&crate::e2e::template_env::render(
"kotlin/not_empty_assertion.kt.jinja",
minijinja::context! { predicate => format!("{field_expr}?.isNotEmpty() == true") },
));
} else if bare_result_is_option || field_is_optional {
out.push_str(&crate::e2e::template_env::render(
"kotlin/not_empty_assertion.kt.jinja",
minijinja::context! { predicate => format!("{field_expr} != null") },
));
} else {
let _ = writeln!(
out,
" assertFalse({string_field_expr}.isEmpty(), \"expected non-empty value\")"
);
}
}
"is_empty" => {
let bare_result_is_option =
result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
if bare_result_is_option && !kotlin_android_style {
out.push_str(&crate::e2e::template_env::render(
"kotlin/is_empty_assertion.kt.jinja",
minijinja::context! { predicate => format!("{field_expr}.isEmpty") },
));
} else if field_is_collection && (bare_result_is_option || field_is_optional) {
// Symmetric with `not_empty`'s `field_is_collection && (bare_result_is_option ||
// field_is_optional)` branch above: an optional collection reached through
// `field_is_optional` (e.g. `Option<Vec<T>>`) must null-check before calling
// `.isEmpty()`, or a genuinely-empty-but-present collection throws instead of
// asserting true. `?: true` treats a null (absent) collection as empty too,
// matching every other backend's "null counts as empty" semantics for this
// assertion type. ~keep
out.push_str(&crate::e2e::template_env::render(
"kotlin/is_empty_assertion.kt.jinja",
minijinja::context! { predicate => format!("({field_expr}?.isEmpty() ?: true)") },
));
} else if bare_result_is_option || field_is_optional {
out.push_str(&crate::e2e::template_env::render(
"kotlin/is_empty_assertion.kt.jinja",
minijinja::context! { predicate => format!("{field_expr} == null") },
));
} else {
out.push_str(&crate::e2e::template_env::render(
"kotlin/is_empty_assertion.kt.jinja",
minijinja::context! { predicate => format!("{string_field_expr}.isEmpty()") },
));
}
}
"contains_any" => {
if let Some(values) = &assertion.values {
let checks: Vec<String> = values
.iter()
.map(|v| {
let kotlin_val = super::values::json_to_kotlin(v);
format!("{string_expr}.contains({kotlin_val})")
})
.collect();
let joined = checks.join(" || ");
let _ = writeln!(
out,
" assertTrue({joined}, \"expected to contain at least one of the specified values\")"
);
}
}
"greater_than" => {
if let Some(val) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(val);
let _ = writeln!(
out,
" assertTrue({nonnull_field_expr} > {kotlin_val}, \"expected > {kotlin_val}\")"
);
}
}
"less_than" => {
if let Some(val) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(val);
let _ = writeln!(
out,
" assertTrue({nonnull_field_expr} < {kotlin_val}, \"expected < {kotlin_val}\")"
);
}
}
"greater_than_or_equal" => {
if let Some(val) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(val);
let _ = writeln!(
out,
" assertTrue({nonnull_field_expr} >= {kotlin_val}, \"expected >= {kotlin_val}\")"
);
}
}
"less_than_or_equal" => {
if let Some(val) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(val);
let _ = writeln!(
out,
" assertTrue({nonnull_field_expr} <= {kotlin_val}, \"expected <= {kotlin_val}\")"
);
}
}
"starts_with" => {
if let Some(expected) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(expected);
let _ = writeln!(
out,
" assertTrue({string_expr}.startsWith({kotlin_val}), \"expected to start with: \" + {kotlin_val})"
);
}
}
"ends_with" => {
if let Some(expected) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(expected);
let _ = writeln!(
out,
" assertTrue({string_expr}.endsWith({kotlin_val}), \"expected to end with: \" + {kotlin_val})"
);
}
}
"min_length" => {
if let Some(val) = &assertion.value
&& let Some(n) = val.as_u64()
{
// For simple result types (ByteArray), use .size; for String use .length
let length_accessor = if result_is_simple && field_expr == result_var {
"size"
} else {
"length"
};
let _ = writeln!(
out,
" assertTrue({string_field_expr}.{length_accessor} >= {n}, \"expected {length_accessor} >= {n}\")"
);
}
}
"max_length" => {
if let Some(val) = &assertion.value
&& let Some(n) = val.as_u64()
{
// For simple result types (ByteArray), use .size; for String use .length
let length_accessor = if result_is_simple && field_expr == result_var {
"size"
} else {
"length"
};
let _ = writeln!(
out,
" assertTrue({string_field_expr}.{length_accessor} <= {n}, \"expected {length_accessor} <= {n}\")"
);
}
}
"count_min" => {
if let Some(val) = &assertion.value
&& let Some(n) = val.as_u64()
{
let _ = writeln!(
out,
" assertTrue({nonnull_field_expr}.size >= {n}, \"expected at least {n} elements\")"
);
}
}
"count_equals" => {
if let Some(val) = &assertion.value
&& let Some(n) = val.as_u64()
{
let _ = writeln!(
out,
" assertEquals({n}, {nonnull_field_expr}.size, \"expected exactly {n} elements\")"
);
}
}
"is_true" => {
if field_is_optional {
// `T?`: "is_true" means "present" -- `field_expr == true` never type-errors
// in Kotlin (`==` is Any?-to-Any? structural equality) but it also never
// matches a non-Boolean nullable (e.g. `DataNode?`), so the assertion always
// fails at runtime even when the field is present. `!= null` is the
// interpretation that holds for any T, matching the Rust `.is_some()`
// convention for this assertion type. ~keep
let _ = writeln!(
out,
" assertTrue({field_expr} != null, \"expected true (non-null)\")"
);
} else {
let _ = writeln!(out, " assertTrue({field_expr} == true, \"expected true\")");
}
}
"is_false" => {
if field_is_optional {
let _ = writeln!(
out,
" assertTrue({field_expr} == null, \"expected false (null)\")"
);
} else {
let _ = writeln!(out, " assertTrue({field_expr} == false, \"expected false\")");
}
}
"matches_regex" => {
if let Some(expected) = &assertion.value {
let kotlin_val = super::values::json_to_kotlin(expected);
let _ = writeln!(
out,
" assertTrue(Regex({kotlin_val}).containsMatchIn({string_expr}), \"expected value to match regex: \" + {kotlin_val})"
);
}
}
// See `not_error::render_not_error` for why this is not a no-op. WHETHER it may assert
// presence at all is decided once, centrally, by `not_error_presence::may_assert_presence`
// -- passed in as `not_error_may_assert_presence` -- not re-derived here.
"not_error" => {
super::not_error::render_not_error(out, result_var, not_error_may_assert_presence, is_streaming);
}
"error" => {
// Handled at the test method level.
}
"method_result" => {
// Placeholder: Kotlin support for method_result would need sample_language integration.
let _ = writeln!(
out,
" // method_result assertions not yet implemented for Kotlin"
);
}
other => {
panic!("Kotlin e2e generator: unsupported assertion type: {other}");
}
}
}
#[cfg(test)]
mod strict_field_availability_marker_tests {
use super::render_assertion;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::Assertion;
use std::collections::{HashMap, HashSet};
/// Regression test for alef task #81: Kotlin's "skipped: field not available"
/// comment text must survive as the exact marker the shared
/// `crate::e2e::codegen::fail_on_unavailable_field_markers` mechanism matches on
/// (wired into `kotlin/test_method.rs`, shared by `kotlin` and `kotlin_android`),
/// so arming `ALEF_E2E_STRICT_FIELD_AVAILABILITY` turns a dropped field assertion
/// into a generation-time failure instead of a silently-passing comment.
#[test]
fn unavailable_field_skip_comment_carries_the_strict_mode_marker() {
let result_fields: HashSet<String> = ["content".to_string()].into_iter().collect();
let resolver = FieldResolver::new(
&HashMap::new(),
&HashSet::new(),
&result_fields,
&HashSet::new(),
&HashSet::new(),
);
let assertion = Assertion {
assertion_type: "equals".to_string(),
field: Some("nonexistent_field".to_string()),
value: Some(serde_json::json!("x")),
..Assertion::default()
};
let mut out = String::new();
render_assertion(
&mut out,
&assertion,
"result",
"SampleClient",
&resolver,
false,
false,
&HashSet::new(),
&HashSet::new(),
&HashMap::new(),
false,
false,
true,
);
assert!(out.contains("field 'nonexistent_field' not available"), "got: {out}");
}
}
#[cfg(test)]
mod is_true_optional_field_tests {
use super::render_assertion;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::Assertion;
use std::collections::{HashMap, HashSet};
fn render(assertion: &Assertion, optional_field: &str, kotlin_android_style: bool) -> String {
let optional: HashSet<String> = [optional_field.to_string()].into_iter().collect();
let resolver = FieldResolver::new(
&HashMap::new(),
&optional,
&HashSet::new(),
&HashSet::new(),
&HashSet::new(),
);
let mut out = String::new();
render_assertion(
&mut out,
assertion,
"result",
"SampleClient",
&resolver,
false,
false,
&HashSet::new(),
&HashSet::new(),
&HashMap::new(),
false,
kotlin_android_style,
true,
);
out
}
fn is_true_assertion(field: &str) -> Assertion {
Assertion {
assertion_type: "is_true".to_string(),
field: Some(field.to_string()),
..Assertion::default()
}
}
/// `Option<DataNode>` presence on the Kotlin (JVM) target: before the fix this rendered
/// `assertTrue(result.data() == true, ...)`, which compiles (`==` is Any?-to-Any?
/// structural equality) but is always false for a present non-Boolean nullable.
#[test]
fn kotlin_is_true_on_optional_struct_field_checks_presence() {
let out = render(&is_true_assertion("data"), "data", false);
assert_eq!(
out,
" assertTrue(result.data() != null, \"expected true (non-null)\")\n"
);
}
/// Same fixture, kotlin_android target: properties (no `()`), same nullability fix.
#[test]
fn kotlin_android_is_true_on_optional_struct_field_checks_presence() {
let out = render(&is_true_assertion("data"), "data", true);
assert_eq!(
out,
" assertTrue(result.data != null, \"expected true (non-null)\")\n"
);
}
#[test]
fn kotlin_android_is_false_on_optional_struct_field_checks_absence() {
let out = render(
&Assertion {
assertion_type: "is_false".to_string(),
field: Some("data".to_string()),
..Assertion::default()
},
"data",
true,
);
assert_eq!(
out,
" assertTrue(result.data == null, \"expected false (null)\")\n"
);
}
#[test]
fn kotlin_android_is_true_on_non_optional_field_is_unchanged() {
let resolver = FieldResolver::new(
&HashMap::new(),
&HashSet::new(),
&HashSet::new(),
&HashSet::new(),
&HashSet::new(),
);
let mut out = String::new();
render_assertion(
&mut out,
&is_true_assertion("active"),
"result",
"SampleClient",
&resolver,
false,
false,
&HashSet::new(),
&HashSet::new(),
&HashMap::new(),
false,
true,
true,
);
assert_eq!(out, " assertTrue(result.active == true, \"expected true\")\n");
}
}
#[cfg(test)]
mod wildcard_tests {
use super::render_assertion;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::Assertion;
use std::collections::{HashMap, HashSet};
fn array_resolver(field: &str) -> FieldResolver {
let names: HashSet<String> = [field.to_string()].into_iter().collect();
FieldResolver::new(&HashMap::new(), &HashSet::new(), &names, &names, &HashSet::new())
}
fn render_contains(resolver: &FieldResolver, field: &str, value: &str) -> String {
let assertion = Assertion {
assertion_type: "contains".to_string(),
field: Some(field.to_string()),
value: Some(serde_json::Value::String(value.to_string())),
..Assertion::default()
};
let mut out = String::new();
render_assertion(
&mut out,
&assertion,
"result",
"SampleClient",
resolver,
false,
false,
&HashSet::new(),
&HashSet::new(),
&HashMap::new(),
false,
false,
true,
);
out
}
/// Baseline: a single wildcard still quantifies over the whole list, so the refusal added
/// for the nested case cannot have been implemented by refusing wildcards generally. ~keep
#[test]
fn single_wildcard_still_quantifies_over_every_element() {
let out = render_contains(&array_resolver("links"), "links[].url", "example.test");
assert!(out.contains(".any {"), "got: {out}");
assert!(!out.contains(".first()"), "wildcard must not pin element 0, got: {out}");
}
/// `wildcard_split` consumes the first `[].` only, so before the guard the `any {}` ranged
/// over `pages` while its lambda read `e.links().first().url()` — a whole-array claim that
/// only ever inspected element zero of the inner list. Kotlin is the worst case for
/// spotting this in review: `index == 0` renders as `.first()`, never as a literal `[0]`,
/// so an index-free assertion would have passed vacuously. Pre-guard this test fails: the
/// skip line is absent and `.first()` is present. ~keep
#[test]
fn nested_wildcard_should_emit_a_visible_skip_rather_than_an_index_zero_check() {
let out = render_contains(&array_resolver("pages"), "pages[].links[].url", "example.test");
assert_eq!(
out, " // skipped: nested array-wildcard field 'pages[].links[].url' not supported\n",
"got: {out}"
);
}
}