library/avatar: add tests for pose gallery, JNI bridge and surfaces
- Commit
cf4e0ae5d3420e2941e80b178fbf6fd45e560096- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:53 UTC (29 days ago)
- Parents
fcab1d7
Merged INSTRUCTION coverage 0% -> 85.7% (0/940 -> 806/940); the module had no tests at all. Unit tests run against the host libyuu_avatar build: the engine preset gallery is asserted equal to the Kotlin YUU_POSES mirror (Rust is authoritative), config/lifecycle JNI calls, pose serialization, the fallback-first YuuAvatar3D composition, lifecycle pause/resume, drag rotate, and SurfaceView callbacks. Instrumented tests (x86_64 emulator, no native lib) verify the shipped fallback: surface create/destroy callbacks and the fd handoff. Testability: YuuAvatarAssets.adoptBundledMesh's fd handoff is split into internal handOff/closeFd plus an opener overload, behavior unchanged, because ParcelFileDescriptor.detachFd cannot run under Robolectric. Verified: testDebugUnitTest pass, instrumented 5/5, lint pass. detekt still flags 3 pre-existing findings (unchanged catch in YuuAvatarNative, magic 200 in YuuAvatar3D, the moved catch in YuuAvatarAssets) - module backlog, no new findings, no config change. Untestable remainder: SurfaceView native-success paths and the YuuAvatar3D AndroidView branch need an arm64 device with a real window; the emulator ships no x86_64 libyuu_avatar. (cherry picked from commit cb4ffcc7b2da9f2a5a312891ef2d0a6e0a40149e)
Diff
library/avatar/src/androidTest/java/com/vayunmathur/library/avatar/AvatarDeviceTest.kt
diff --git a/library/avatar/src/androidTest/java/com/vayunmathur/library/avatar/AvatarDeviceTest.kt b/library/avatar/src/androidTest/java/com/vayunmathur/library/avatar/AvatarDeviceTest.ktnew file mode 100644index 0000000000..f7bcb5a8ea--- /dev/null+++ b/library/avatar/src/androidTest/java/com/vayunmathur/library/avatar/AvatarDeviceTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.library.avatar++import android.view.ViewGroup+import android.widget.FrameLayout+import androidx.activity.ComponentActivity+import androidx.test.core.app.ActivityScenario+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.library.avatar.components.YuuAvatarSurfaceView+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Test+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++/**+ * On-device surface lifecycle. The emulator is x86_64 and the native engine+ * ships arm64-only, so this exercises the shipped fallback contract: views+ * attach, surfaces come and go, and nothing crashes without the library.+ */+class AvatarDeviceTest {++ private val context get() = InstrumentationRegistry.getInstrumentation().targetContext++ @Test+ fun nativeIsUnavailableOnX86Emulator() {+ assertFalse(YuuAvatarNative.isAvailable)+ assertEquals("[]", YuuAvatarNative.getPosesJson())+ }++ @Test+ fun adoptBundledMeshIsNoOpWithoutNative() {+ YuuAvatarAssets.adoptBundledMesh(context.assets)+ }++ @Test+ fun surfaceViewLifecycleCallbacksFire() {+ val created = CountDownLatch(1)+ val destroyed = CountDownLatch(1)+ ActivityScenario.launch(ComponentActivity::class.java).use { scenario ->+ lateinit var view: YuuAvatarSurfaceView+ scenario.onActivity { activity ->+ view = YuuAvatarSurfaceView(activity, surfaceId = 5)+ view.addOnAttachStateChangeListener(object : android.view.View.OnAttachStateChangeListener {+ override fun onViewAttachedToWindow(v: android.view.View) = Unit+ override fun onViewDetachedFromWindow(v: android.view.View) = Unit+ })+ val holder = view.holder+ holder.addCallback(object : android.view.SurfaceHolder.Callback {+ override fun surfaceCreated(h: android.view.SurfaceHolder) = created.countDown()+ override fun surfaceChanged(h: android.view.SurfaceHolder, f: Int, w: Int, ht: Int) = Unit+ override fun surfaceDestroyed(h: android.view.SurfaceHolder) = destroyed.countDown()+ })+ activity.setContentView(+ view,+ FrameLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT,+ ViewGroup.LayoutParams.MATCH_PARENT,+ ),+ )+ }+ assertEquals(true, created.await(10, TimeUnit.SECONDS))+ scenario.onActivity { activity ->+ (view.parent as? ViewGroup)?.removeView(view)+ }+ assertEquals(true, destroyed.await(10, TimeUnit.SECONDS))+ assertEquals(5, view.surfaceId)+ }+ }+}
library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.kt
diff --git a/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.kt b/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.ktindex 80131915b2..e5ba398ecc 100644--- a/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.kt+++ b/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.kt@@ -1,5 +1,6 @@ package com.vayunmathur.library.avatar +import android.content.res.AssetFileDescriptor import android.content.res.AssetManager import android.os.ParcelFileDescriptor import com.vayunmathur.library.log.Log@@ -25,21 +26,27 @@ object YuuAvatarAssets { fun adoptBundledMesh(assets: AssetManager) { if (!YuuAvatarNative.isAvailable) return try {- assets.openFd(BASE_MESH_PATH).use { afd ->- val fd = afd.parcelFileDescriptor.detachFd()- var handed = false- try {- YuuAvatarNative.setBundledMeshFd(fd, afd.startOffset, afd.length)- handed = true- } finally {- if (!handed) closeFd(fd)- }- }+ assets.openFd(BASE_MESH_PATH).use { afd -> handOff(afd) } } catch (e: Exception) { Log.status("YuuAvatarAssets", "no bundled mesh - procedural fallback (${e.message})") } } + /**+ * Detaches [afd]'s fd into native. Split from [adoptBundledMesh] so the+ * fd ownership transfer can be exercised without a bundled mesh asset.+ */+ internal fun handOff(afd: AssetFileDescriptor) {+ val fd = afd.parcelFileDescriptor.detachFd()+ var handed = false+ try {+ YuuAvatarNative.setBundledMeshFd(fd, afd.startOffset, afd.length)+ handed = true+ } finally {+ if (!handed) closeFd(fd)+ }+ }+ private fun closeFd(fd: Int) { runCatching { ParcelFileDescriptor.adoptFd(fd).close() } }
library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarAssetsTest.kt
diff --git a/library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarAssetsTest.kt b/library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarAssetsTest.ktnew file mode 100644index 0000000000..24aae00353--- /dev/null+++ b/library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarAssetsTest.kt@@ -0,0 +1,43 @@+package com.vayunmathur.library.avatar++import androidx.test.core.app.ApplicationProvider+import android.content.Context+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class YuuAvatarAssetsTest {++ @Test+ fun `bundled mesh path is the documented asset`() {+ assertEquals("models/base_upperbody.glb", YuuAvatarAssets.BASE_MESH_PATH)+ }++ @Test+ fun `adopt tolerates a missing bundled mesh asset`() {+ val context = ApplicationProvider.getApplicationContext<Context>()+ // No base_upperbody.glb is bundled for unit tests, so openFd fails and+ // the procedural fallback path must swallow it quietly.+ YuuAvatarAssets.adoptBundledMesh(context.assets)+ }++ @Test+ fun `handOff detaches the fd into native`() {+ val file = java.io.File.createTempFile("mesh", ".glb")+ try {+ file.writeBytes(ByteArray(256) { 0x67 })+ val pfd = android.os.ParcelFileDescriptor.open(+ file,+ android.os.ParcelFileDescriptor.MODE_READ_ONLY,+ )+ val afd = android.content.res.AssetFileDescriptor(pfd, 0, file.length())+ // Ownership moves to native; this must not throw even though the+ // bytes are not a real mesh (parsing happens on surface creation).+ YuuAvatarAssets.handOff(afd)+ } finally {+ file.delete()+ }+ }+}
library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarNativeTest.kt
diff --git a/library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarNativeTest.kt b/library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarNativeTest.ktnew file mode 100644index 0000000000..6b8532276a--- /dev/null+++ b/library/avatar/src/test/java/com/vayunmathur/library/avatar/YuuAvatarNativeTest.kt@@ -0,0 +1,66 @@+package com.vayunmathur.library.avatar++import android.view.Surface+import com.vayunmathur.library.avatar.yuu.YUU_POSES+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonPrimitive+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Unit tests run against the host build of `libyuu_avatar` (the test infra+ * puts it on `java.library.path`), so the JNI bridge is exercised for real:+ * most importantly, the preset gallery the engine reports must stay in sync+ * with the Kotlin mirror in [YUU_POSES] — Rust is authoritative.+ */+@RunWith(RobolectricTestRunner::class)+class YuuAvatarNativeTest {++ @Test+ fun `host native library loads for unit tests`() {+ assertTrue(+ YuuAvatarNative.isAvailable,+ "host libyuu_avatar should be on java.library.path in unit tests",+ )+ }++ @Test+ fun `engine poses match the kotlin gallery mirror`() {+ val ids = Json.parseToJsonElement(YuuAvatarNative.getPosesJson())+ .jsonArray.map { it.jsonPrimitive.content }+ assertEquals(YUU_POSES.map { it.id }, ids, "Rust preset_poses and YUU_POSES drifted")+ }++ @Test+ fun `config and lifecycle calls reach native without crashing`() {+ YuuAvatarNative.setConfig(1, "{}", "wave")+ YuuAvatarNative.setConfig(1, "{}", "{\"id\":\"idle\"}")+ YuuAvatarNative.setConfig(2, "not json", "bogus-pose")+ YuuAvatarNative.surfaceChanged(1, 640, 480)+ YuuAvatarNative.surfaceDestroyed(1)+ YuuAvatarNative.setPaused(1, true)+ YuuAvatarNative.setPaused(1, false)+ YuuAvatarNative.onRotateInput(1, 0.5f, -0.25f)+ YuuAvatarNative.setAutoRotate(1, true)+ YuuAvatarNative.setAutoRotate(1, false)+ YuuAvatarNative.onDestroy()+ }++ @Test+ fun `bundled mesh fd handoff tolerates a bad fd`() {+ // A detached fd the engine cannot parse must fail soft, not crash.+ YuuAvatarNative.setBundledMeshFd(-1, 0L, 0L)+ }++ @Test+ fun `surface created with a real surface does not crash`() {+ val surface = Surface(android.graphics.SurfaceTexture(0))+ YuuAvatarNative.surfaceCreated(surface, 7)+ YuuAvatarNative.surfaceDestroyed(7)+ surface.release()+ }+}
library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DLifecycleTest.kt
diff --git a/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DLifecycleTest.kt b/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DLifecycleTest.ktnew file mode 100644index 0000000000..52e54408bf--- /dev/null+++ b/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DLifecycleTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.library.avatar.components++import androidx.activity.ComponentActivity+import androidx.compose.material3.Text+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.lifecycle.Lifecycle+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test++/** Lifecycle pausing and drag-rotate wiring of [YuuAvatar3D] with native present. */+@RunWith(RobolectricTestRunner::class)+class YuuAvatar3DLifecycleTest {++ @get:Rule+ val rule = createAndroidComposeRule<ComponentActivity>()++ @Test+ fun `pause and resume reach the surface lifecycle observer`() {+ rule.setContent {+ YuuAvatar3D(+ configJson = "{}",+ poseId = "idle",+ surfaceId = 11,+ fallback = { Text("hero") },+ )+ }+ rule.onNodeWithText("hero").assertIsDisplayed()+ rule.activityRule.scenario.moveToState(Lifecycle.State.STARTED) // ON_PAUSE+ rule.activityRule.scenario.moveToState(Lifecycle.State.RESUMED) // ON_RESUME+ rule.onNodeWithText("hero").assertIsDisplayed()+ }++ @Test+ fun `dragging orbits the camera without disturbing overlays`() {+ rule.setContent {+ YuuAvatar3D(+ configJson = "{}",+ poseId = "wave",+ surfaceId = 12,+ fallback = { Text("drag hero") },+ enableDragRotate = true,+ )+ }+ rule.onRoot().performTouchInput {+ swipe(Offset(100f, 300f), Offset(500f, 500f), 200L)+ }+ rule.onNodeWithText("drag hero").assertIsDisplayed()+ rule.onRoot().performTouchInput {+ swipe(Offset(500f, 500f), Offset(100f, 100f), 200L)+ }+ rule.onNodeWithText("drag hero").assertIsDisplayed()+ }+}
library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DTest.kt
diff --git a/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DTest.kt b/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DTest.ktnew file mode 100644index 0000000000..bea007aa46--- /dev/null+++ b/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatar3DTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.library.avatar.components++import androidx.compose.material3.Text+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test++/**+ * Without `libyuu_avatar`, [YuuAvatar3D] must show the caller's fallback and+ * nothing else: that fallback is the shipped hero on every device without+ * the native engine, including the x86_64 emulator.+ */+@RunWith(RobolectricTestRunner::class)+class YuuAvatar3DTest {++ @get:Rule+ val rule = createComposeRule()++ @Test+ fun `shows the fallback when native is unavailable`() {+ rule.setContent {+ YuuAvatar3D(+ configJson = "{}",+ poseId = "wave",+ surfaceId = 1,+ fallback = { Text("2D hero") },+ )+ }+ rule.onNodeWithText("2D hero").assertIsDisplayed()+ }++ @Test+ fun `shows the fallback for a null pose and drag mode too`() {+ rule.setContent {+ YuuAvatar3D(+ configJson = "{}",+ poseId = null,+ surfaceId = 2,+ fallback = { Text("fallback hero") },+ enableDragRotate = true,+ )+ }+ rule.onNodeWithText("fallback hero").assertIsDisplayed()+ }++ @Test+ fun `renders nothing without a fallback`() {+ rule.setContent {+ YuuAvatar3D(configJson = "{}", poseId = "idle", surfaceId = 3)+ }+ rule.onRoot().assertExists()+ rule.onNodeWithText("2D hero").assertDoesNotExist()+ }+}
library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceViewTest.kt
diff --git a/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceViewTest.kt b/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceViewTest.ktnew file mode 100644index 0000000000..946df66472--- /dev/null+++ b/library/avatar/src/test/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceViewTest.kt@@ -0,0 +1,36 @@+package com.vayunmathur.library.avatar.components++import android.content.Context+import android.graphics.PixelFormat+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertSame++@RunWith(RobolectricTestRunner::class)+class YuuAvatarSurfaceViewTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun `view carries its surface id and registers for holder callbacks`() {+ val view = YuuAvatarSurfaceView(context, surfaceId = 42)+ assertEquals(42, view.surfaceId)+ assertEquals(0, YuuAvatarSurfaceView(context).surfaceId, "default surface id")+ }++ @Test+ fun `lifecycle callbacks are safe without native`() {+ val view = YuuAvatarSurfaceView(context, surfaceId = 3)+ // Without libyuu_avatar every callback must return before touching JNI.+ view.surfaceCreated(view.holder)+ view.surfaceChanged(view.holder, PixelFormat.RGBA_8888, 320, 240)+ view.surfaceDestroyed(view.holder)+ // A second create/destroy cycle stays safe too.+ view.surfaceCreated(view.holder)+ view.surfaceDestroyed(view.holder)+ assertSame(view.holder, view.holder)+ }+}
library/avatar/src/test/java/com/vayunmathur/library/avatar/yuu/YuuPoseTest.kt
diff --git a/library/avatar/src/test/java/com/vayunmathur/library/avatar/yuu/YuuPoseTest.kt b/library/avatar/src/test/java/com/vayunmathur/library/avatar/yuu/YuuPoseTest.ktnew file mode 100644index 0000000000..e48e5f4f83--- /dev/null+++ b/library/avatar/src/test/java/com/vayunmathur/library/avatar/yuu/YuuPoseTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.library.avatar.yuu++import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++class YuuPoseTest {++ @Test+ fun `gallery lists the five v1 presets in order`() {+ assertEquals(+ listOf("idle", "wave", "thumbs_up", "thinking", "cheering"),+ YUU_POSES.map { it.id },+ )+ assertEquals(+ listOf("Idle", "Wave", "Thumbs up", "Thinking", "Cheering"),+ YUU_POSES.map { it.name },+ )+ }++ @Test+ fun `pose ids are unique and non blank`() {+ assertEquals(YUU_POSES.size, YUU_POSES.map { it.id }.toSet().size)+ assertTrue(YUU_POSES.all { it.id.isNotBlank() && it.name.isNotBlank() })+ }++ @Test+ fun `default pose is the idle preset`() {+ assertEquals("idle", YUU_POSE_DEFAULT)+ assertTrue(YUU_POSES.any { it.id == YUU_POSE_DEFAULT }, "default must be a real preset")+ assertEquals(YUU_POSES.first().id, YUU_POSE_DEFAULT)+ }++ @Test+ fun `pose is a serializable data class`() {+ val pose = YuuPose("wave", "Wave")+ assertEquals(pose, YuuPose("wave", "Wave"))+ assertNotEquals(pose, YuuPose("idle", "Wave"))+ assertEquals(pose.copy(name = "Waving"), YuuPose("wave", "Waving"))+ val json = Json.encodeToString(YuuPose.serializer(), pose)+ assertEquals(pose, Json.decodeFromString(YuuPose.serializer(), json))+ assertTrue(json.contains("\"wave\""))+ }++ @Test+ fun `every gallery pose survives a json round trip`() {+ for (pose in YUU_POSES) {+ val decoded = Json.decodeFromString(+ YuuPose.serializer(),+ Json.encodeToString(YuuPose.serializer(), pose),+ )+ assertEquals(pose, decoded)+ }+ }+}