Modern Apps git

← Modern-Apps.git

share, chess: batch unit tests; share sleep-polls converted

Commit
58d056c8209826e39cccf64e611988634a1fe193
Author
Vayun Mathur <[email protected]>
When
2026-11-21 22:42 UTC (14 days ago)
Parents
0dbde9a
Share: 18 native-loading classes and 2 ViewModel/singleton
polluters quarantined, 21 batch (225/225 green, 77s -> 43s);
its worst wall-clock sleep-polls now await terminal signals
via the shared DeterministicAwait. Chess: 5 classes load
libmodelrunner through ChessViewModel's Maia probe and 13
pollute via DataStoreUtils/token-store statics; 23 batch
(257/257 green, 74s -> 34s). New native/ViewModel classes
must join the lists (documented per file).

Diff

games/chess/build.gradle.kts
diff --git a/games/chess/build.gradle.kts b/games/chess/build.gradle.ktsindex 79def735a3..4956b4b33e 100644--- a/games/chess/build.gradle.kts+++ b/games/chess/build.gradle.kts@@ -21,6 +21,67 @@ android {     } } +// This module has no Rust of its own, but :library:ml registers+// libmodelrunner (rustNativeLib), so every unit test here has kept+// forkEvery = 1. Only the classes below actually load that library:+// they construct ChessViewModel, whose init launches+// ChessApi.isAvailable() -> MaiaEngine.ensure() ->+// MaiaHandle.inAssets, which touches MlNative.isAvailable+// (System.loadLibrary("modelrunner") via NativeLoader); Y3MainActivityTest+// reaches the same probe by launching MainActivity, whose Game+// destination builds ChessViewModel. Tests that merely call the pure+// MaiaEngine.encodePlanes/moveIndex helpers (MaiaEncodingTest),+// compose boards/screens with fake actions, or drive the pure rules+// never load the library and stay in the main task. Quarantine the+// loaders and the shared-JVM polluters below into+// testDevUnitTestNative (forkEvery = 1); the remaining classes batch+// 20-per-JVM in testDevUnitTest, which depends on the quarantine task+// so the usual invocation still runs everything.+rustNativeTests {+    nativeClasses.addAll(+        listOf(+            "com.vayunmathur.games.chess.ChessDropTest",+            "com.vayunmathur.games.chess.Y3ChessGameFlowTest",+            "com.vayunmathur.games.chess.Y3MainActivityTest",+            "com.vayunmathur.games.chess.util.ChessViewModelTest",+            "com.vayunmathur.games.chess.util.ViewModelCoverageTest",+        )+    )+    // Shared-JVM polluters keep forkEvery = 1 in the same companion task:+    // PuzzleViewModel/LearnViewModel collect their uiState in+    // viewModelScope and persist through the DataStoreUtils+    // process-wide singleton (its init eagerly collects the+    // preferences DataStore), OnlineChessViewModel launches its+    // Lichess event-stream/redirect collectors in init over the same+    // singleton via LichessTokenStore (whose sealerForTest is a+    // process-wide static and whose migration scope is never+    // cancelled), and LearnRepository/PuzzleRepository cache their+    // bundled data process-wide; persisted DataStore state also leaks+    // into classes expecting defaults (the online tests clear the+    // token store in setUp/tearDown for exactly this reason). Audit+    // rule: any test instantiating PuzzleViewModel / LearnViewModel /+    // OnlineChessViewModel, using LichessTokenStore directly, or+    // launching MainActivity (already quarantined as a native loader+    // above) belongs here. All other classes batch.+    isolatedClasses.addAll(+        listOf(+            "com.vayunmathur.games.chess.ChessPass3DrawTest",+            "com.vayunmathur.games.chess.LearnStageScreenTest",+            "com.vayunmathur.games.chess.OnlineScreensTest",+            "com.vayunmathur.games.chess.Y3LearnScreensTest",+            "com.vayunmathur.games.chess.Y3LichessNetTest",+            "com.vayunmathur.games.chess.Y3OnlineScreensTest",+            "com.vayunmathur.games.chess.Y3OnlineVmNetTest",+            "com.vayunmathur.games.chess.auth.AuthCoverageTest",+            "com.vayunmathur.games.chess.auth.LichessTokenStoreTest",+            "com.vayunmathur.games.chess.platform.OnlineChessViewModelTest",+            "com.vayunmathur.games.chess.platform.OnlineStreamCoverageTest",+            "com.vayunmathur.games.chess.platform.OnlineViewModelCoverageTest",+            "com.vayunmathur.games.chess.util.PuzzleAndLearnViewModelTest",+        )+    )+}+ dependencies {     implementation(project(":sdk:games"))     implementation(project(":library:ml"))
share/build.gradle.kts
diff --git a/share/build.gradle.kts b/share/build.gradle.ktsindex 35fb4415bc..766baaea72 100644--- a/share/build.gradle.kts+++ b/share/build.gradle.kts@@ -25,6 +25,64 @@ androidComponents { // See share/src/main/rust/ and share/PROTOCOL_CONTRACT.md. rustNativeLib("share_nearby", "share") +// Only the classes below actually load libshare_nearby: they call+// ShareNativeDiscovery.native* directly, construct ShareSession+// (ShareNative.nativeInit), run TcpTransport listen/connect (which+// creates a ShareSession per socket), drive the Ble/Nsd discovery+// managers (native advertisement/endpoint codecs, NSD service type),+// or touch ShareReceiveController (ensure() builds endpoint info via+// native, transport() is the process-wide TcpTransport). Tests that+// merely read the inlined ShareNative.DEVICE_TYPE_PHONE constant, use+// the pure plist/HTTP/DvZip helpers, compose with FakeActions, or drive+// a per-instance AirDropReceiver/ShareReceiveNotifier never load the+// library and stay in the main task. Quarantine the loaders and the+// shared-JVM polluters below into testDevUnitTestNative+// (forkEvery = 1); the remaining classes batch 20-per-JVM in+// testDevUnitTest, which depends on the quarantine task so the usual+// invocation still runs everything.+rustNativeTests {+    nativeClasses.addAll(+        listOf(+            "com.vayunmathur.share.domain.protocol.ShareSessionTest",+            "com.vayunmathur.share.network.transport.TcpTransportExtraTest",+            "com.vayunmathur.share.network.transport.TcpTransportTest",+            "com.vayunmathur.share.platform.FinalPushTest",+            "com.vayunmathur.share.platform.GapPush2Test",+            "com.vayunmathur.share.platform.GapPush3Test",+            "com.vayunmathur.share.platform.GapPush4Test",+            "com.vayunmathur.share.platform.GapPush5Test",+            "com.vayunmathur.share.platform.GapPush6Test",+            "com.vayunmathur.share.platform.GapPush7Test",+            "com.vayunmathur.share.platform.GapPush8Test",+            "com.vayunmathur.share.platform.GapPush9Test",+            "com.vayunmathur.share.platform.GapPushTest",+            "com.vayunmathur.share.platform.MoreCoverageTest",+            "com.vayunmathur.share.platform.ShareViewModelConnectTest",+            "com.vayunmathur.share.platform.discovery.DiscoveryManagersTest",+            "com.vayunmathur.share.platform.receive.ReceiveComponentsTest",+            "com.vayunmathur.share.protocol.ShareNativeDiscoveryTest",+        )+    )+    // Shared-JVM polluters keep forkEvery = 1 in the same companion task:+    // ShareViewModel turns its combined flows into a viewModelScope+    // stateIn collector (SharingStarted.WhileSubscribed) that is never+    // cleared when the test never calls onCleared, and+    // ShareReceiveController is a process-wide singleton (cached+    // transport/managers/notifier, IO scope, mutable localName) over+    // the DataStoreUtils singleton, whose init eagerly collects the+    // preferences DataStore; persisted DataStore state also leaks into+    // classes expecting defaults. Audit rule: any test instantiating+    // ShareViewModel or launching MainActivity / SharePopupActivity+    // (which build one) belongs here, unless it already loads the+    // native library above. All other classes batch.+    isolatedClasses.addAll(+        listOf(+            "com.vayunmathur.share.platform.ShareViewModelHelpersTest",+            "com.vayunmathur.share.ui.SharePopupAndActivitiesTest",+        )+    )+}+ dependencies {     // ViewModel/Compose already via common-conventions-app; explicit lifecycle for clarity.     implementation(libs.androidx.lifecycle.viewmodel.ktx)
share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.ktindex 0bfc215847..c256dd534e 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt@@ -29,6 +29,7 @@ import com.vayunmathur.share.platform.receive.ShareReceiveController import com.vayunmathur.share.platform.transfer.ShareTransferService import com.vayunmathur.share.protocol.ShareNativeDiscovery import com.vayunmathur.share.ui.SharePopupSheet+import com.vayunmathur.testsupport.awaitWithMainIdle import java.io.File import java.net.InetAddress import kotlinx.coroutines.async@@ -53,16 +54,10 @@ class GapPush2Test {     private fun b64(b: ByteArray) = Base64.encodeToString(b, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)     private fun pump() = Shadows.shadowOf(Looper.getMainLooper()).idle() -    /** Polls [fetch] (pumping the main looper) until it returns a value or times out. */-    private fun <T> awaitNonNull(timeoutMs: Long, sleepMs: Long, fetch: () -> T?): T? {-        val deadline = System.currentTimeMillis() + timeoutMs-        var value: T? = null-        while (value == null && System.currentTimeMillis() < deadline) {-            pump()-            value = fetch()-            if (value == null) Thread.sleep(sleepMs)-        }-        return value+    /** Waits (pumping the main looper) until [fetch] returns a value. */+    private fun <T> awaitNonNull(description: String, fetch: () -> T?): T? {+        awaitWithMainIdle(description) { fetch() != null }+        return fetch()     }      @Test@@ -81,7 +76,7 @@ class GapPush2Test {         val nsd = app.getSystemService(NsdManager::class.java)         val shadow = Shadows.shadowOf(nsd)         // Wait for NSD discovery listener registration (viewModelScope is Main-bound).-        val listener = awaitNonNull(10_000, 50) {+        val listener = awaitNonNull("NSD discovery listener registered") {             shadow.getDiscoveryListeners(SHARE_SERVICE_TYPE)?.firstOrNull()         }         assertNotNull(listener)@@ -91,7 +86,7 @@ class GapPush2Test {         val found = NsdServiceInfo().apply { serviceName = instance; serviceType = SHARE_SERVICE_TYPE }         listener!!.onServiceFound(found)         // Poll for the resolve listener the manager registers in onServiceFound.-        val resolveListener = awaitNonNull(8_000, 50) {+        val resolveListener = awaitNonNull("resolve listener registered") {             shadow.getResolveListeners(found)?.firstOrNull()         }         assertNotNull("resolve listener registered", resolveListener)@@ -114,7 +109,7 @@ class GapPush2Test {         val result = ScanResult(device, record, -50, 1L)         val scanner = bt.adapter.bluetoothLeScanner         // Re-deliver the BLE result until the ViewModel merges it with the NSD leg.-        awaitNonNull(10_000, 100) {+        awaitNonNull("BLE leg merged with NSD leg") {             Shadows.shadowOf(scanner).scanCallbacks.forEach { it.onScanResult(1, result) }             vm.sendUiState.value.discoveredDevices                 .firstOrNull { it.endpointId == "ABCD" && it.source == DiscoverySource.Both }
share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.ktindex 904a391977..50b59c0213 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt@@ -34,6 +34,7 @@ import com.vayunmathur.share.protocol.ShareNativeDiscovery import com.vayunmathur.share.ui.OutgoingFilesCard import com.vayunmathur.share.ui.ShareSendScreen import com.vayunmathur.share.ui.TransferCard+import com.vayunmathur.testsupport.awaitWithMainIdle import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File@@ -64,15 +65,13 @@ class GapPush3Test {     private fun grant(vararg p: String) = Shadows.shadowOf(app).grantPermissions(*p)     private fun pump() = Shadows.shadowOf(Looper.getMainLooper()).idle() -    /** Polls [fetch] until it returns a value or times out. */-    private suspend fun <T> awaitNonNullSuspend(timeoutMs: Long, pollMs: Long, fetch: () -> T?): T? {-        val deadline = System.currentTimeMillis() + timeoutMs-        var value: T? = null-        while (value == null && System.currentTimeMillis() < deadline) {-            value = fetch()-            if (value == null) delay(pollMs)-        }-        return value+    /** Waits (pumping the main looper) until [fetch] returns a value. */+    private fun <T> awaitNonNull(description: String, fetch: () -> T?): T? {+        // Producers here run on Dispatchers.Default/IO (browse collectors,+        // HTTP server), so the step bound must leave them wall time to+        // land: the clock precedent uses 100k steps for background waits.+        awaitWithMainIdle(description, maxSteps = 200_000) { fetch() != null }+        return fetch()     }      @Test@@ -273,7 +272,7 @@ class GapPush3Test {                     // Ignored: collection is cancelled at test end; assertions check collected state.                 }             }-            val listener = awaitNonNullSuspend(10_000, 100) {+            val listener = awaitNonNull("AirDrop discovery listener registered") {                 shadow.getDiscoveryListeners(AIRDROP_SERVICE_TYPE)?.firstOrNull()             }             assertNotNull(listener)@@ -284,7 +283,7 @@ class GapPush3Test {                 serviceName = "vmmac"; serviceType = AIRDROP_SERVICE_TYPE                 port = serverPort; setHost(InetAddress.getByName("127.0.0.1"))             }-            val device = awaitNonNullSuspend(12_000, 300) {+            val device = awaitNonNull("browse emits the Apple peer") {                 shadow.getResolveListeners(found)?.firstOrNull()?.onServiceResolved(resolved)                 emitted.firstOrNull()             }@@ -297,13 +296,13 @@ class GapPush3Test {             delay(400)             vm.connectToDevice(device!!)             // Accept the Ask on the standalone receiver; VM scope is Main-bound so pump.-            val accepted = awaitNonNullSuspend(15_000, 60) {+            val accepted = awaitNonNull("receiver sees the VM Ask") {                 pump()                 receiver.incoming.value.firstOrNull()?.also { receiver.accept(it.sessionHandle, true) }             } != null             assertTrue("receiver should see the VM Ask", accepted)             // Let the upload finish.-            val completed = awaitNonNullSuspend(15_000, 80) {+            val completed = awaitNonNull("upload completes") {                 pump()                 receiver.incoming.value.firstOrNull()?.takeIf { it.state.value == ShareState.Completed }             } != null
share/src/test/java/com/vayunmathur/share/platform/ShareViewModelHelpersTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/ShareViewModelHelpersTest.kt b/share/src/test/java/com/vayunmathur/share/platform/ShareViewModelHelpersTest.ktindex 6b87eb6eac..2bc5a46bbd 100644--- a/share/src/test/java/com/vayunmathur/share/platform/ShareViewModelHelpersTest.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/ShareViewModelHelpersTest.kt@@ -4,6 +4,7 @@ import android.app.Application import android.content.Intent import android.net.Uri import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.testsupport.awaitWithMainIdle import java.io.File import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull@@ -56,12 +57,8 @@ class ShareViewModelHelpersTest {             putExtra(Intent.EXTRA_TEXT, "shared hello text")         }         vm.handleShareIntent(intent)-        // staging is async on IO; poll briefly while pumping the main looper-        val deadline = System.currentTimeMillis() + 8_000-        while (System.currentTimeMillis() < deadline && vm.outgoingUris.value.isEmpty()) {-            org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()-            Thread.sleep(50)-        }+        // Staging is async on IO; wait on the terminal flow value.+        awaitWithMainIdle("outgoing URIs staged from share intent") { vm.outgoingUris.value.isNotEmpty() }         assertEquals(1, vm.outgoingUris.value.size)     }