alef-e2e 0.16.60

Fixture-driven e2e test generator for alef
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
//! Regression tests for the kotlin_android e2e codegen bugs:
//!
//! - Bug 2: construct DefaultClient via client_factory before calling methods.
//! - Bug 3: emit Kotlin property access (no parens) for data class fields.
//! - Bug 4: serialize enum values via `.name.lowercase()` instead of `.getValue()`.
//! - Bug 5: streaming collect uses `Flow.toList()` not `asSequence().toList()`,
//!   and chunk assertions use Kotlin property access throughout.

use alef_core::config::NewAlefConfig;
use alef_e2e::codegen::E2eCodegen;
use alef_e2e::codegen::kotlin_android::KotlinAndroidE2eCodegen;
use alef_e2e::fixture::{Assertion, Fixture, FixtureGroup, MockResponse};
use std::collections::HashMap;

fn make_chat_fixture(id: &str) -> Fixture {
    Fixture {
        id: id.to_string(),
        category: Some("chat".to_string()),
        description: "chat test".to_string(),
        tags: Vec::new(),
        skip: None,
        env: None,
        call: Some("chat".to_string()),
        input: serde_json::json!({
            "model": "gpt-4o",
            "messages": [{"role": "user", "content": "hello"}]
        }),
        mock_response: Some(MockResponse {
            status: 200,
            body: Some(serde_json::Value::Null),
            stream_chunks: None,
            headers: HashMap::new(),
        }),
        visitor: None,
        assertions: vec![Assertion {
            assertion_type: "not_error".to_string(),
            field: None,
            value: None,
            values: None,
            method: None,
            check: None,
            args: None,
            return_type: None,
        }],
        source: "chat.json".to_string(),
        http: None,
    }
}

fn make_chat_fixture_with_field_assertion(id: &str, field: &str, expected: &str) -> Fixture {
    Fixture {
        id: id.to_string(),
        category: Some("chat".to_string()),
        description: "chat assertion test".to_string(),
        tags: Vec::new(),
        skip: None,
        env: None,
        call: Some("chat".to_string()),
        input: serde_json::json!({
            "model": "gpt-4o",
            "messages": [{"role": "user", "content": "hello"}]
        }),
        mock_response: Some(MockResponse {
            status: 200,
            body: Some(serde_json::Value::Null),
            stream_chunks: None,
            headers: HashMap::new(),
        }),
        visitor: None,
        assertions: vec![Assertion {
            assertion_type: "equals".to_string(),
            field: Some(field.to_string()),
            value: Some(serde_json::Value::String(expected.to_string())),
            values: None,
            method: None,
            check: None,
            args: None,
            return_type: None,
        }],
        source: "chat.json".to_string(),
        http: None,
    }
}

/// Minimal alef.toml for kotlin_android e2e with java client_factory and chat call.
const TOML_WITH_JAVA_CLIENT_FACTORY: &str = r#"
[workspace]
languages = ["kotlin_android"]

[[crates]]
name = "liter-llm"
sources = ["src/lib.rs"]

[crates.kotlin_android]
package = "dev.kreuzberg.literllm.android"
namespace = "dev.kreuzberg.literllm.android"
artifact_id = "liter-llm-android"
group_id = "dev.kreuzberg"

[crates.e2e]
fixtures = "fixtures"
output = "e2e"

[crates.e2e.call]
function = "chat"
result_var = "result"

[crates.e2e.calls.chat]
function = "chat"
result_var = "result"

[[crates.e2e.calls.chat.args]]
name = "request"
field = "input"
type = "json_object"
owned = true

[crates.e2e.calls.chat.overrides.java]
client_factory = "createClient"
options_type = "ChatCompletionRequest"
options_via = "from_json"

[crates.e2e.packages.kotlin_android]
name = "liter-llm"
"#;

/// alef.toml with explicit enum_fields declaring finish_reason as enum-typed.
/// Uses `fields_array` so `choices` is treated as a list (produces `.first()` access).
const TOML_WITH_ENUM_FIELDS: &str = r#"
[workspace]
languages = ["kotlin_android"]

[[crates]]
name = "liter-llm"
sources = ["src/lib.rs"]

[crates.kotlin_android]
package = "dev.kreuzberg.literllm.android"
namespace = "dev.kreuzberg.literllm.android"
artifact_id = "liter-llm-android"
group_id = "dev.kreuzberg"

[crates.e2e]
fixtures = "fixtures"
output = "e2e"
fields_optional = ["choices.finish_reason"]
fields_array = ["choices"]

[crates.e2e.call]
function = "chat"
result_var = "result"

[crates.e2e.calls.chat]
function = "chat"
result_var = "result"

[[crates.e2e.calls.chat.args]]
name = "request"
field = "input"
type = "json_object"
owned = true

[crates.e2e.calls.chat.overrides.java]
client_factory = "createClient"
options_type = "ChatCompletionRequest"
options_via = "from_json"
enum_fields = { "choices.finish_reason" = "FinishReason" }

[crates.e2e.packages.kotlin_android]
name = "liter-llm"
"#;

/// alef.toml for kotlin_android streaming e2e via chatStream call.
const TOML_WITH_STREAMING: &str = r#"
[workspace]
languages = ["kotlin_android"]

[[crates]]
name = "liter-llm"
sources = ["src/lib.rs"]

[crates.kotlin_android]
package = "dev.kreuzberg.literllm.android"
namespace = "dev.kreuzberg.literllm.android"
artifact_id = "liter-llm-android"
group_id = "dev.kreuzberg"

[crates.e2e]
fixtures = "fixtures"
output = "e2e"

[crates.e2e.call]
function = "chat_stream"
result_var = "result"

[crates.e2e.calls.chat_stream]
function = "chat_stream"
result_var = "result"

[[crates.e2e.calls.chat_stream.args]]
name = "request"
field = "input"
type = "json_object"
owned = true

[crates.e2e.calls.chat_stream.overrides.java]
client_factory = "createClient"
options_type = "ChatCompletionRequest"
options_via = "from_json"

[crates.e2e.packages.kotlin_android]
name = "liter-llm"
"#;

fn render_kotlin_android_chat(toml: &str, fixture: Fixture) -> String {
    let cfg: NewAlefConfig = toml::from_str(toml).expect("config parses");
    let resolved = cfg.clone().resolve().expect("config resolves").remove(0);
    let e2e = cfg.crates[0].e2e.clone().expect("e2e config present");
    let groups = vec![FixtureGroup {
        category: "chat".to_string(),
        fixtures: vec![fixture],
    }];
    let files = KotlinAndroidE2eCodegen
        .generate(&groups, &e2e, &resolved, &[], &[])
        .expect("generation succeeds");
    files
        .iter()
        .find(|f| {
            let p = f.path.to_string_lossy();
            p.contains("ChatTest.kt")
        })
        .expect("ChatTest.kt is emitted")
        .content
        .clone()
}

fn make_streaming_fixture(id: &str) -> Fixture {
    Fixture {
        id: id.to_string(),
        category: Some("chat".to_string()),
        description: "chat stream test".to_string(),
        tags: Vec::new(),
        skip: None,
        env: None,
        call: Some("chat_stream".to_string()),
        input: serde_json::json!({
            "model": "gpt-4o",
            "messages": [{"role": "user", "content": "hello"}],
            "stream": true
        }),
        mock_response: Some(MockResponse {
            status: 200,
            body: None,
            stream_chunks: Some(vec![
                serde_json::json!({"choices": [{"delta": {"content": "hello"}, "finish_reason": null}]}),
                serde_json::json!({"choices": [{"delta": {}, "finish_reason": "stop"}]}),
            ]),
            headers: HashMap::new(),
        }),
        visitor: None,
        assertions: vec![
            Assertion {
                assertion_type: "equals".to_string(),
                field: Some("stream_content".to_string()),
                value: Some(serde_json::Value::String("hello".to_string())),
                values: None,
                method: None,
                check: None,
                args: None,
                return_type: None,
            },
            Assertion {
                assertion_type: "equals".to_string(),
                field: Some("stream_complete".to_string()),
                value: Some(serde_json::Value::Bool(true)),
                values: None,
                method: None,
                check: None,
                args: None,
                return_type: None,
            },
        ],
        source: "chat.json".to_string(),
        http: None,
    }
}

fn render_kotlin_android_streaming(fixture: Fixture) -> String {
    let cfg: NewAlefConfig = toml::from_str(TOML_WITH_STREAMING).expect("config parses");
    let resolved = cfg.clone().resolve().expect("config resolves").remove(0);
    let e2e = cfg.crates[0].e2e.clone().expect("e2e config present");
    let groups = vec![FixtureGroup {
        category: "chat".to_string(),
        fixtures: vec![fixture],
    }];
    let files = KotlinAndroidE2eCodegen
        .generate(&groups, &e2e, &resolved, &[], &[])
        .expect("generation succeeds");
    files
        .iter()
        .find(|f| {
            let p = f.path.to_string_lossy();
            p.contains("ChatTest.kt")
        })
        .expect("ChatTest.kt is emitted")
        .content
        .clone()
}

// ---------------------------------------------------------------------------
// Bug 2: construct DefaultClient via client_factory
// ---------------------------------------------------------------------------

/// Regression for Bug 2: when `[crates.e2e.calls.chat.overrides.java]` has
/// `client_factory = "createClient"` the kotlin_android codegen must also pick
/// that up and emit:
///   val client = LiterLlm.createClient(...)
///   val result = client.chat(...)
///   client.close()
/// rather than a flat `LiterLlm.chat(...)` call.
#[test]
fn kotlin_android_uses_java_client_factory() {
    let fixture = make_chat_fixture("chat_basic");
    let rendered = render_kotlin_android_chat(TOML_WITH_JAVA_CLIENT_FACTORY, fixture);

    assert!(
        rendered.contains("val client = LiterLlm.createClient("),
        "must construct client via factory; got:\n{rendered}"
    );
    assert!(
        rendered.contains("client.chat("),
        "must call chat on client instance; got:\n{rendered}"
    );
    assert!(
        rendered.contains("client.close()"),
        "must close the client; got:\n{rendered}"
    );
    assert!(
        !rendered.contains("LiterLlm.chat("),
        "must NOT call chat as flat function; got:\n{rendered}"
    );
}

// ---------------------------------------------------------------------------
// Bug 3: emit Kotlin property access (no parens) for data class fields
// ---------------------------------------------------------------------------

/// Regression for Bug 3: field accessors in kotlin_android tests must use
/// Kotlin property syntax (`result.choices.first().message.content`) rather
/// than Java getter calls (`result.choices().first().message().content()`).
#[test]
fn kotlin_android_field_access_uses_property_syntax_not_getters() {
    let fixture = make_chat_fixture_with_field_assertion("chat_content", "choices.message.content", "hello");
    let rendered = render_kotlin_android_chat(TOML_WITH_JAVA_CLIENT_FACTORY, fixture);

    // Property access: no parentheses after field names.
    assert!(
        !rendered.contains(".choices()"),
        "must NOT emit .choices() getter call; got:\n{rendered}"
    );
    assert!(
        !rendered.contains(".message()"),
        "must NOT emit .message() getter call; got:\n{rendered}"
    );
    assert!(
        !rendered.contains(".content()"),
        "must NOT emit .content() getter call; got:\n{rendered}"
    );
    // Must use dot-property access.
    assert!(
        rendered.contains(".choices"),
        "must emit .choices property access; got:\n{rendered}"
    );
}

// ---------------------------------------------------------------------------
// Bug 4: serialize enum via .name.lowercase() not .getValue()
// ---------------------------------------------------------------------------

/// Regression for Bug 4: enum-typed fields in kotlin_android tests must be
/// serialized via `.name.lowercase()` (which maps `FinishReason.STOP` to the
/// wire value `"stop"`) rather than `.getValue()` (which does not exist on
/// plain Kotlin `enum class` values).
#[test]
fn kotlin_android_enum_field_uses_name_lowercase_not_get_value() {
    let fixture = make_chat_fixture_with_field_assertion("chat_finish", "choices.finish_reason", "stop");
    let rendered = render_kotlin_android_chat(TOML_WITH_ENUM_FIELDS, fixture);

    assert!(
        !rendered.contains(".getValue()"),
        "must NOT emit .getValue() on kotlin_android enum; got:\n{rendered}"
    );
    assert!(
        rendered.contains(".name") && rendered.contains(".lowercase()"),
        "must emit .name.lowercase() for enum serialization; got:\n{rendered}"
    );
}

// ---------------------------------------------------------------------------
// Bug 5: streaming collect uses Flow.toList() not asSequence().toList()
// ---------------------------------------------------------------------------

/// Regression for Bug 5: kotlin_android streaming tests must collect a
/// `Flow<T>` with `result.toList()` (kotlinx.coroutines suspend extension),
/// not with `result.asSequence().toList()` (which only applies to Java
/// `Iterator<T>`).  Chunk field assertions must also use Kotlin property access
/// (`it.choices?.firstOrNull()?.delta?.content`) rather than Java getter calls
/// (`it.choices()?.firstOrNull()?.delta()?.content()`).
#[test]
fn kotlin_android_streaming_collect_uses_flow_to_list_not_as_sequence() {
    let fixture = make_streaming_fixture("chat_stream_basic");
    let rendered = render_kotlin_android_streaming(fixture);

    // Must collect the Flow with .toList(), not asSequence().toList().
    assert!(
        rendered.contains(".toList()"),
        "must emit .toList() to collect the Flow; got:\n{rendered}"
    );
    assert!(
        !rendered.contains(".asSequence()"),
        "must NOT emit .asSequence() (Java Iterator pattern); got:\n{rendered}"
    );

    // Chunk assertions must use Kotlin property access, not Java getter calls.
    assert!(
        !rendered.contains(".choices()"),
        "must NOT emit .choices() getter call in chunk assertions; got:\n{rendered}"
    );
    assert!(
        !rendered.contains(".delta()"),
        "must NOT emit .delta() getter call in chunk assertions; got:\n{rendered}"
    );
    assert!(
        !rendered.contains(".finishReason()"),
        "must NOT emit .finishReason() getter call in chunk assertions; got:\n{rendered}"
    );

    // Must use dot-property access on chunk fields.
    assert!(
        rendered.contains(".choices"),
        "must emit .choices property access in chunk assertions; got:\n{rendered}"
    );

    // Must import the coroutines Flow.toList extension.
    assert!(
        rendered.contains("import kotlinx.coroutines.flow.toList"),
        "must import kotlinx.coroutines.flow.toList; got:\n{rendered}"
    );
}

// ---------------------------------------------------------------------------
// D: androidTest source set + Gradle Managed Devices
// ---------------------------------------------------------------------------

fn generate_kotlin_android_files(toml: &str, fixture: Fixture) -> Vec<alef_core::backend::GeneratedFile> {
    let cfg: NewAlefConfig = toml::from_str(toml).expect("config parses");
    let resolved = cfg.clone().resolve().expect("config resolves").remove(0);
    let e2e = cfg.crates[0].e2e.clone().expect("e2e config present");
    let groups = vec![FixtureGroup {
        category: "chat".to_string(),
        fixtures: vec![fixture],
    }];
    KotlinAndroidE2eCodegen
        .generate(&groups, &e2e, &resolved, &[], &[])
        .expect("generation succeeds")
}

/// Regression for D: `kotlin_android` codegen must emit an `src/androidTest/`
/// source set alongside the host-JVM `src/test/` source set so that
/// instrumented tests can run on the Android emulator.
#[test]
fn kotlin_android_emits_android_test_source_set() {
    let fixture = make_chat_fixture("chat_basic");
    let files = generate_kotlin_android_files(TOML_WITH_JAVA_CLIENT_FACTORY, fixture);

    let all_paths: Vec<String> = files.iter().map(|f| f.path.to_string_lossy().to_string()).collect();
    let android_test_file = files.iter().find(|f| {
        let p = f.path.to_string_lossy();
        p.contains("androidTest") && p.contains("ChatTest.kt")
    });
    let file = android_test_file.unwrap_or_else(|| {
        panic!(
            "src/androidTest/.../ChatTest.kt must be emitted; got files:\n{}",
            all_paths.join("\n")
        )
    });
    let content = &file.content;

    assert!(
        content.contains("@RunWith(AndroidJUnit4::class)"),
        "androidTest file must use @RunWith(AndroidJUnit4::class); got:\n{content}"
    );
    assert!(
        content.contains("System.loadLibrary"),
        "androidTest file must call System.loadLibrary; got:\n{content}"
    );
    assert!(
        content.contains("import androidx.test.ext.junit.runners.AndroidJUnit4"),
        "androidTest file must import AndroidJUnit4; got:\n{content}"
    );
}

/// Regression for D: the emitted `build.gradle.kts` must apply the Android
/// Gradle Plugin so that the `android { }` DSL — including Managed Devices —
/// resolves at Kotlin script compile time.  Without the AGP in `plugins { }`,
/// every reference to `android`, `testOptions`, `managedDevices`, and
/// `ManagedVirtualDevice` raises "Unresolved reference" at script compilation.
#[test]
fn kotlin_android_build_gradle_applies_android_gradle_plugin() {
    let fixture = make_chat_fixture("chat_basic");
    let files = generate_kotlin_android_files(TOML_WITH_JAVA_CLIENT_FACTORY, fixture);

    let build_gradle = files
        .iter()
        .find(|f| f.path.file_name().and_then(|n| n.to_str()) == Some("build.gradle.kts"))
        .expect("build.gradle.kts must be emitted");
    let content = &build_gradle.content;

    // The AGP plugin must be declared so the `android { }` block compiles.
    assert!(
        content.contains("com.android.library"),
        "build.gradle.kts must apply id(\"com.android.library\"); got:\n{content}"
    );
    assert!(
        content.contains("kotlin(\"android\")"),
        "build.gradle.kts must apply kotlin(\"android\"); got:\n{content}"
    );
    // The managed devices block must still be present for on-device runs.
    assert!(
        content.contains("ManagedVirtualDevice"),
        "build.gradle.kts must import ManagedVirtualDevice; got:\n{content}"
    );
    assert!(
        content.contains("managedDevices"),
        "build.gradle.kts must have managedDevices block; got:\n{content}"
    );
    assert!(
        content.contains("pixel6api34"),
        "build.gradle.kts must declare pixel6api34 managed device; got:\n{content}"
    );
}