Skip to main content

alef_e2e/codegen/
kotlin_android.rs

1//! Kotlin Android e2e test generator using kotlin.test and JUnit 5.
2//!
3//! Generates host-JVM tests that validate the AAR-bundled Java facade and Kotlin wrapper
4//! via JNA against libkreuzberg_ffi. Tests are emitted to `e2e/kotlin_android/src/test/kotlin/`
5//! without requiring an Android emulator — the tests run directly on the host JVM against
6//! the shared library.
7
8use crate::config::E2eConfig;
9use crate::escape::sanitize_filename;
10use crate::fixture::{Fixture, FixtureGroup};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::ResolvedCrateConfig;
13use alef_core::template_versions::{maven, toolchain};
14use anyhow::Result;
15use heck::ToUpperCamelCase;
16use std::collections::HashSet;
17use std::path::PathBuf;
18
19use super::E2eCodegen;
20use super::kotlin;
21
22/// Kotlin Android e2e code generator.
23/// Emits a host-JVM test project that depends on the AAR-bundled Java facade
24/// and Kotlin wrapper via sourceSets and JNA, without requiring an Android emulator.
25pub struct KotlinAndroidE2eCodegen;
26
27impl E2eCodegen for KotlinAndroidE2eCodegen {
28    fn generate(
29        &self,
30        groups: &[FixtureGroup],
31        e2e_config: &E2eConfig,
32        config: &ResolvedCrateConfig,
33        type_defs: &[alef_core::ir::TypeDef],
34        _enums: &[alef_core::ir::EnumDef],
35    ) -> Result<Vec<GeneratedFile>> {
36        let lang = self.language_name();
37        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
38
39        let mut files = Vec::new();
40
41        // Resolve call config with overrides.
42        let call = &e2e_config.call;
43        let overrides = call.overrides.get(lang);
44        let _module_path = overrides
45            .and_then(|o| o.module.as_ref())
46            .cloned()
47            .unwrap_or_else(|| call.module.clone());
48        let function_name = overrides
49            .and_then(|o| o.function.as_ref())
50            .cloned()
51            .unwrap_or_else(|| call.function.clone());
52        let class_name = overrides
53            .and_then(|o| o.class.as_ref())
54            .cloned()
55            .unwrap_or_else(|| config.name.to_upper_camel_case());
56        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
57        let result_var = &call.result_var;
58
59        // Resolve package config.
60        let kotlin_android_pkg = e2e_config.resolve_package("kotlin_android");
61        let pkg_name = kotlin_android_pkg
62            .as_ref()
63            .and_then(|p| p.name.as_ref())
64            .cloned()
65            .unwrap_or_else(|| config.name.clone());
66
67        // Resolve Kotlin package for generated tests.
68        let _kotlin_android_pkg_path = kotlin_android_pkg
69            .as_ref()
70            .and_then(|p| p.path.as_deref())
71            .unwrap_or("../../packages/kotlin-android");
72        let kotlin_android_version = kotlin_android_pkg
73            .as_ref()
74            .and_then(|p| p.version.as_ref())
75            .cloned()
76            .or_else(|| config.resolved_version())
77            .unwrap_or_else(|| "0.1.0".to_string());
78        // Use the kotlin_android crate's `package` config — not the generic
79        // `config.kotlin_package()` accessor — so the generated tests live in
80        // the same JVM package as the AAR's emitted types and can reference
81        // them by simple name. `kotlin_package()` falls back to a
82        // `com.github.<org>` derivation from the GitHub URL when
83        // `[crates.kotlin] package` is absent, which produces a package
84        // mismatch for AAR consumers that only configure
85        // `[crates.kotlin_android] package`.
86        //
87        // Precedence: `[crates.e2e.packages.kotlin_android].module` (explicit
88        // override) > `[crates.kotlin_android].package` > derived fallback
89        // via `config.kotlin_package()`.
90        let kotlin_pkg_id = kotlin_android_pkg
91            .as_ref()
92            .and_then(|p| p.module.clone())
93            .or_else(|| config.kotlin_android.as_ref().and_then(|c| c.package.clone()))
94            .unwrap_or_else(|| config.kotlin_package());
95
96        // Detect whether any fixture needs the mock-server (HTTP fixtures or
97        // fixtures with a mock_response/mock_responses). When present, emit a
98        // JUnit Platform LauncherSessionListener that spawns the mock-server
99        // before any test runs and a META-INF/services SPI manifest registering
100        // it. Mirrors the Kotlin/JVM e2e pattern exactly.
101        let needs_mock_server = groups
102            .iter()
103            .flat_map(|g| g.fixtures.iter())
104            .any(|f| f.needs_mock_server());
105
106        // Generate build.gradle.kts for the host JVM project.
107        files.push(GeneratedFile {
108            path: output_base.join("build.gradle.kts"),
109            content: render_build_gradle_kotlin_android(
110                &pkg_name,
111                &kotlin_pkg_id,
112                &kotlin_android_version,
113                e2e_config.dep_mode,
114                needs_mock_server,
115            ),
116            generated_header: false,
117        });
118
119        // Generate settings.gradle.kts so Gradle can resolve the AGP
120        // (`com.android.library`) plugin from google()/gradlePluginPortal().
121        // Without this file the e2e project fails at configuration time with
122        // `Plugin [id: 'com.android.library'] was not found in any of the
123        // following sources`.
124        files.push(GeneratedFile {
125            path: output_base.join("settings.gradle.kts"),
126            content: render_settings_gradle_kotlin_android(&pkg_name),
127            generated_header: false,
128        });
129
130        // Generate test files per category. Path mirrors the configured Kotlin
131        // package so the package declaration in each test file matches its
132        // filesystem location.
133        let mut test_base = output_base.join("src").join("test").join("kotlin");
134        for segment in kotlin_pkg_id.split('.') {
135            test_base = test_base.join(segment);
136        }
137        let test_base = test_base.join("e2e");
138
139        if needs_mock_server {
140            files.push(GeneratedFile {
141                path: test_base.join("MockServerListener.kt"),
142                content: kotlin::render_mock_server_listener_kt(&kotlin_pkg_id),
143                generated_header: true,
144            });
145            files.push(GeneratedFile {
146                path: output_base
147                    .join("src")
148                    .join("test")
149                    .join("resources")
150                    .join("META-INF")
151                    .join("services")
152                    .join("org.junit.platform.launcher.LauncherSessionListener"),
153                content: format!("{kotlin_pkg_id}.e2e.MockServerListener\n"),
154                generated_header: false,
155            });
156        }
157
158        // Resolve options_type from override.
159        let options_type = overrides.and_then(|o| o.options_type.clone());
160
161        // Build a map from TypeDef name → set of field names whose Rust type
162        // is a `Named(T)` reference where `T` is NOT itself a known struct.
163        // Those fields are enum-typed and should route through `.getValue()` in
164        // generated assertions automatically, even without an explicit per-call
165        // `enum_fields` override in the alef.toml.
166        let struct_names: HashSet<&str> = type_defs.iter().map(|td| td.name.as_str()).collect();
167        let type_enum_fields: std::collections::HashMap<String, HashSet<String>> = type_defs
168            .iter()
169            .filter_map(|td| {
170                let enum_field_names: HashSet<String> = td
171                    .fields
172                    .iter()
173                    .filter(|field| is_enum_typed(&field.ty, &struct_names))
174                    .map(|field| field.name.clone())
175                    .collect();
176                if enum_field_names.is_empty() {
177                    None
178                } else {
179                    Some((td.name.clone(), enum_field_names))
180                }
181            })
182            .collect();
183
184        for group in groups {
185            let active: Vec<&Fixture> = group
186                .fixtures
187                .iter()
188                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
189                .collect();
190
191            if active.is_empty() {
192                continue;
193            }
194
195            let class_file_name = format!("{}Test.kt", sanitize_filename(&group.category).to_upper_camel_case());
196            let content = kotlin::render_test_file_android(
197                &group.category,
198                &active,
199                &class_name,
200                &function_name,
201                &kotlin_pkg_id,
202                result_var,
203                &e2e_config.call.args,
204                options_type.as_deref(),
205                result_is_simple,
206                e2e_config,
207                &type_enum_fields,
208            );
209            files.push(GeneratedFile {
210                path: test_base.join(&class_file_name),
211                content,
212                generated_header: true,
213            });
214
215            // Instrumented Android test for on-device emulator runs.
216            // Lives in src/androidTest/ and uses @RunWith(AndroidJUnit4::class).
217            let mut android_test_base = output_base.join("src").join("androidTest").join("kotlin");
218            for segment in kotlin_pkg_id.split('.') {
219                android_test_base = android_test_base.join(segment);
220            }
221            let android_test_base = android_test_base.join("e2e");
222            files.push(GeneratedFile {
223                path: android_test_base.join(class_file_name),
224                content: render_android_instrumented_test(
225                    &group.category,
226                    &active,
227                    &class_name,
228                    &function_name,
229                    &kotlin_pkg_id,
230                    result_var,
231                    &pkg_name,
232                ),
233                generated_header: true,
234            });
235        }
236
237        Ok(files)
238    }
239
240    fn language_name(&self) -> &'static str {
241        "kotlin_android"
242    }
243}
244
245// ---------------------------------------------------------------------------
246// Helpers
247// ---------------------------------------------------------------------------
248
249/// Returns true when `ty` is a `Named(T)` reference (or `Optional<Named(T)>`)
250/// where `T` is **not** a known struct name. Such fields are enum-typed and
251/// must route through `.getValue()` in generated assertions.
252fn is_enum_typed(ty: &alef_core::ir::TypeRef, struct_names: &HashSet<&str>) -> bool {
253    use alef_core::ir::TypeRef;
254    match ty {
255        TypeRef::Named(name) => !struct_names.contains(name.as_str()),
256        TypeRef::Optional(inner) => {
257            matches!(inner.as_ref(), TypeRef::Named(name) if !struct_names.contains(name.as_str()))
258        }
259        _ => false,
260    }
261}
262
263// ---------------------------------------------------------------------------
264// Rendering
265// ---------------------------------------------------------------------------
266
267/// Render build.gradle.kts for the kotlin_android e2e project.
268///
269/// This is an Android library project (applies `com.android.library`) so that
270/// the `android { }` DSL — including Gradle Managed Devices — resolves at
271/// Kotlin script compile time. The host-JVM test sources live in
272/// `src/test/kotlin/` and run against the shared native library via JNA.
273fn render_build_gradle_kotlin_android(
274    _pkg_name: &str,
275    kotlin_pkg_id: &str,
276    _pkg_version: &str,
277    _dep_mode: crate::config::DependencyMode,
278    needs_mock_server: bool,
279) -> String {
280    let kotlin_plugin = maven::KOTLIN_JVM_PLUGIN;
281    let android_gradle_plugin = maven::ANDROID_GRADLE_PLUGIN;
282    let junit = maven::JUNIT;
283    let jackson = maven::JACKSON_E2E;
284    // E2E tests run on the host JVM (not Android), so pick a target that
285    // matches the JUnit Jupiter baseline (5.x → JVM 11, 6.x → JVM 17). The
286    // Android library itself still ships at ANDROID_JVM_TARGET for runtime
287    // compat; this only affects the host-side gradle test project.
288    let jvm_target = if junit.starts_with("6.") {
289        "17"
290    } else {
291        toolchain::ANDROID_JVM_TARGET
292    };
293    let jna = maven::JNA;
294    let jspecify = maven::JSPECIFY;
295    let coroutines = maven::KOTLINX_COROUTINES_CORE;
296    let launcher_dep = if needs_mock_server {
297        format!(r#"    testImplementation("org.junit.platform:junit-platform-launcher:{junit}")"#)
298    } else {
299        String::new()
300    };
301
302    format!(
303        r#"import com.android.build.api.dsl.ManagedVirtualDevice
304import org.jetbrains.kotlin.gradle.dsl.JvmTarget
305
306plugins {{
307    id("com.android.library") version "{android_gradle_plugin}"
308    kotlin("android") version "{kotlin_plugin}"
309}}
310
311group = "{kotlin_pkg_id}"
312version = "0.1.0"
313
314android {{
315    namespace = "{kotlin_pkg_id}.e2e"
316    compileSdk = 35
317
318    defaultConfig {{
319        minSdk = 21
320    }}
321
322    compileOptions {{
323        sourceCompatibility = JavaVersion.VERSION_{jvm_target}
324        targetCompatibility = JavaVersion.VERSION_{jvm_target}
325    }}
326
327    sourceSets {{
328        getByName("test") {{
329            // Include the AAR-bundled Java facade as test sources
330            java.srcDir("../../packages/kotlin-android/src/main/java")
331            // Include the AAR-bundled Kotlin wrapper as test sources
332            kotlin.srcDir("../../packages/kotlin-android/src/main/kotlin")
333        }}
334    }}
335
336    testOptions {{
337        // Gradle Managed Virtual Devices for on-device instrumented tests.
338        // Run: ./gradlew pixel6api34DebugAndroidTest
339        managedDevices {{
340            devices {{
341                create<ManagedVirtualDevice>("pixel6api34") {{
342                    device = "Pixel 6"
343                    apiLevel = 34
344                    systemImageSource = "aosp"
345                }}
346            }}
347        }}
348    }}
349}}
350
351kotlin {{
352    compilerOptions {{
353        jvmTarget = JvmTarget.JVM_{jvm_target}
354    }}
355}}
356
357// Repositories declared in settings.gradle.kts via
358// dependencyResolutionManagement (FAIL_ON_PROJECT_REPOS). Re-declaring them
359// here triggers Gradle "repository was added by build file" errors.
360
361dependencies {{
362    // JNA for loading the native library from java.library.path
363    testImplementation("net.java.dev.jna:jna:{jna}")
364
365    // Jackson for JSON assertion helpers
366    testImplementation("com.fasterxml.jackson.core:jackson-annotations:{jackson}")
367    testImplementation("com.fasterxml.jackson.core:jackson-databind:{jackson}")
368    testImplementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:{jackson}")
369
370    // jackson-module-kotlin registers constructors/properties for Kotlin data
371    // classes, which have no default constructor and cannot be deserialized by
372    // plain Jackson without this module.
373    testImplementation("com.fasterxml.jackson.module:jackson-module-kotlin:{jackson}")
374
375    // jspecify for null-safety annotations on wrapped types
376    testImplementation("org.jspecify:jspecify:{jspecify}")
377
378    // Kotlin coroutines for async test helpers
379    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:{coroutines}")
380
381    // JUnit 5 API and engine
382    testImplementation("org.junit.jupiter:junit-jupiter-api:{junit}")
383    testImplementation("org.junit.jupiter:junit-jupiter-engine:{junit}")
384{launcher_dep}
385
386    // Kotlin stdlib test helpers
387    testImplementation(kotlin("test"))
388}}
389
390tasks.withType<Test> {{
391    useJUnitPlatform()
392
393    // Resolve the native library location (e.g., ../../target/release)
394    val libPath = System.getProperty("kb.lib.path") ?: "${{rootDir}}/../../target/release"
395    systemProperty("java.library.path", libPath)
396    systemProperty("jna.library.path", libPath)
397
398    // Resolve fixture paths (e.g. "docx/fake.docx") against test_documents/
399    workingDir = file("${{rootDir}}/../../test_documents")
400}}
401"#
402    )
403}
404
405/// Render `settings.gradle.kts` for the kotlin_android e2e project.
406///
407/// Declares the plugin and dependency repositories Gradle needs to resolve
408/// `com.android.library` (and Kotlin/Android transitive deps). Mirrors the
409/// AAR-side settings emitter at `alef-backend-kotlin-android::gen_settings_gradle`.
410fn render_settings_gradle_kotlin_android(pkg_name: &str) -> String {
411    let project_name = sanitize_gradle_project_name(pkg_name);
412    format!(
413        r#"// Generated by alef. Do not edit by hand.
414
415pluginManagement {{
416    repositories {{
417        google()
418        mavenCentral()
419        gradlePluginPortal()
420    }}
421}}
422
423dependencyResolutionManagement {{
424    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
425    repositories {{
426        google()
427        mavenCentral()
428    }}
429}}
430
431rootProject.name = "{project_name}-e2e"
432"#
433    )
434}
435
436/// Derive a Gradle-safe `rootProject.name` from a registry package coordinate.
437///
438/// Registry-mode `pkg_name` is often a Maven coordinate (`group:artifact`)
439/// because it's used verbatim as a build-script dependency string. Gradle
440/// rejects project names containing any of `[/, \, :, <, >, ", ?, *, |]`,
441/// so we take the artifact segment after the last `:` and replace any
442/// remaining reserved characters with `-`.
443fn sanitize_gradle_project_name(pkg_name: &str) -> String {
444    let artifact = pkg_name.rsplit(':').next().unwrap_or(pkg_name);
445    artifact
446        .chars()
447        .map(|c| match c {
448            '/' | '\\' | ':' | '<' | '>' | '"' | '?' | '*' | '|' => '-',
449            other => other,
450        })
451        .collect()
452}
453
454/// Render an Android instrumented test class for a fixture group.
455///
456/// The generated class uses `@RunWith(AndroidJUnit4::class)` and loads the
457/// native library via `System.loadLibrary` so tests can run on-device via the
458/// Android emulator.
459fn render_android_instrumented_test(
460    category: &str,
461    fixtures: &[&crate::fixture::Fixture],
462    class_name: &str,
463    function_name: &str,
464    kotlin_pkg_id: &str,
465    result_var: &str,
466    lib_name: &str,
467) -> String {
468    let test_class = format!("{}Test", category.to_upper_camel_case());
469    let lib_snake = lib_name.replace('-', "_");
470    let mut out = String::new();
471    out.push_str(&format!("package {kotlin_pkg_id}.e2e\n\n"));
472    out.push_str("import androidx.test.ext.junit.runners.AndroidJUnit4\n");
473    out.push_str("import org.junit.BeforeClass\n");
474    out.push_str("import org.junit.Test\n");
475    out.push_str("import org.junit.runner.RunWith\n\n");
476    out.push_str("@RunWith(AndroidJUnit4::class)\n");
477    out.push_str(&format!("class {test_class} {{\n\n"));
478    out.push_str("    companion object {\n");
479    out.push_str("        @BeforeClass\n");
480    out.push_str("        @JvmStatic\n");
481    out.push_str("        fun loadNativeLibrary() {\n");
482    out.push_str(&format!("            System.loadLibrary(\"{lib_snake}_jni\")\n"));
483    out.push_str("        }\n");
484    out.push_str("    }\n\n");
485    for fixture in fixtures {
486        let test_name = fixture.id.replace(['-', '.', ' '], "_");
487        out.push_str("    @Test\n");
488        out.push_str(&format!("    fun test_{test_name}() {{\n"));
489        out.push_str(&format!("        val client = {class_name}()\n"));
490        out.push_str(&format!(
491            "        val {result_var} = client.{function_name}(/* fixture: {} */)\n",
492            fixture.id
493        ));
494        out.push_str(&format!("        // TODO: assert {result_var} is not an error\n"));
495        out.push_str("    }\n\n");
496    }
497    out.push_str("}\n");
498    out
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    /// Regression: the kotlin-android build.gradle.kts must declare
506    /// `jackson-module-kotlin` so that Jackson can deserialize Kotlin data
507    /// classes (which have no default constructor).  Without it, any test that
508    /// calls `MAPPER.readValue(...)` against a Kotlin data class throws
509    /// `InvalidDefinitionException: No suitable constructor found`.
510    #[test]
511    fn build_gradle_kotlin_android_includes_jackson_module_kotlin() {
512        let output = render_build_gradle_kotlin_android(
513            "liter-llm",
514            "dev.kreuzberg.literllm.android",
515            "1.0.0",
516            crate::config::DependencyMode::Local,
517            false,
518        );
519        assert!(
520            output.contains("jackson-module-kotlin"),
521            "build.gradle.kts must depend on jackson-module-kotlin, got:\n{output}"
522        );
523    }
524
525    /// Regression: the e2e settings.gradle.kts must declare the
526    /// `pluginManagement` block with `google()` and `gradlePluginPortal()` so
527    /// Gradle can resolve `com.android.library`. Missing settings.gradle.kts
528    /// causes `Plugin [id: 'com.android.library'] was not found` at config time.
529    #[test]
530    fn settings_gradle_kotlin_android_declares_plugin_repositories() {
531        let output = render_settings_gradle_kotlin_android("liter-llm");
532        assert!(
533            output.contains("pluginManagement"),
534            "settings.gradle.kts must declare pluginManagement block, got:\n{output}"
535        );
536        assert!(
537            output.contains("google()"),
538            "pluginManagement repositories must include google(), got:\n{output}"
539        );
540        assert!(
541            output.contains("gradlePluginPortal()"),
542            "pluginManagement repositories must include gradlePluginPortal(), got:\n{output}"
543        );
544        assert!(
545            output.contains("rootProject.name = \"liter-llm-e2e\""),
546            "rootProject.name must be derived from pkg_name, got:\n{output}"
547        );
548    }
549
550    /// Regression: registry-mode `pkg_name` may be a Maven coordinate
551    /// (`group:artifact`) because it's used verbatim as a Gradle dependency
552    /// string. Gradle rejects project names containing `:`, so the
553    /// emitter must strip the group prefix when deriving `rootProject.name`.
554    /// Without sanitization Gradle fails at configuration time with
555    /// "The project name '…' must not contain any of the following
556    /// characters: [/, \\, :, <, >, \", ?, *, |]".
557    #[test]
558    fn settings_gradle_kotlin_android_strips_maven_group_from_project_name() {
559        let output = render_settings_gradle_kotlin_android("dev.kreuzberg:html-to-markdown-android");
560        assert!(
561            output.contains("rootProject.name = \"html-to-markdown-android-e2e\""),
562            "rootProject.name must strip Maven group prefix, got:\n{output}"
563        );
564        let project_name_line = output
565            .lines()
566            .find(|line| line.starts_with("rootProject.name"))
567            .expect("rootProject.name line must be emitted");
568        assert!(
569            !project_name_line.contains(':'),
570            "rootProject.name line must not contain Gradle-reserved ':', got:\n{project_name_line}"
571        );
572    }
573}