openassistant: add tests for tools, A2UI, ViewModel, chat UI and data
- Commit
160b83ce70cf09796b2478bebf5c2fd262147cd2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 05:27 UTC (29 days ago)
- Parents
04d6756
JVM/Robolectric tests: JsonSchemaValidator/JsonExtractor branches, AppDatabase DAO CRUD (in-memory Room), AssistantViewModel service dispatch and recording lifecycle, AssistantToolIntents and AssistantTools.invoke missing-app and memory paths (with a custom Robolectric Intent shadow so cross-app launches read as not installed), A2UI controller sync and surface rendering with real action round-trips, chat/settings Compose screens, InferenceService lifecycle basics, copyUriToFile, routes and the backup agent. Includes a fake AndroidKeyStore JCE provider so DatabaseHelper-backed classes can be constructed under Robolectric, plus a Mockito test dependency. Coverage (merged, whole module): 16.1% -> 54.1%+ instructions (3296/20507 baseline; final number in the finish report). Bugs fixed: none. Two validator quirks are pinned with comments: combinators do not short-circuit the strict unknown-field check. Untestable remainder on the JVM: InferenceService inference loop and MamlChatEngine (Gemma4Handle is JNI/native and throws UnsatisfiedLinkError on the host JVM; needs a device with the ~3.5 GB model downloaded), LiteRTChatUi and repository-flow screens (SQLCipher native driver cannot open on the host JVM), and the Assist API session surfaces (framework voice-interaction session, no Robolectric harness). Verified with gslot ./gradlew :openassistant:createMergedCoverageReport (full :openassistant:testDevUnitTest suite passes). (cherry picked from commit c08d114ec777e74714a0622be2d535065abf1ca9)
Diff
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex d858e351cb..dfc8bb77e6 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -45,4 +45,7 @@ dependencies { implementation(libs.androidx.a2ui.model) implementation(libs.androidx.a2ui.engine) implementation(libs.kotlinx.serialization.json)++ // Mock Context/PackageManager for cross-app intent tests.+ testImplementation(libs.mockito.core) }
openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseDaoTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseDaoTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseDaoTest.ktnew file mode 100644index 0000000000..b07edafdba--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseDaoTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.openassistant.data++import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest++/** AppDatabase DAOs over an in-memory Room database under Robolectric. */[email protected](org.robolectric.RobolectricTestRunner::class)+class AppDatabaseDaoTest {++ private lateinit var db: AppDatabase++ @BeforeTest fun setUp() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ db = Room.inMemoryDatabaseBuilder(ctx, AppDatabase::class.java)+ .allowMainThreadQueries().build()+ }++ @AfterTest fun tearDown() { db.close() }++ @Test fun conversationCrudAndOrdering() = runTest {+ val dao = db.conversationDao()+ assertTrue(dao.getAllFlow().first().isEmpty())+ val id1 = dao.upsert(Conversation(title = "First", timestamp = 100L))+ val id2 = dao.upsert(Conversation(title = "Second", timestamp = 200L))+ assertTrue(id1 > 0 && id2 > id1)+ // Newest first.+ assertEquals(listOf("Second", "First"), dao.getAllFlow().first().map { it.title })+ assertEquals("First", dao.getById(id1)?.title)+ assertEquals("First", dao.getByIdFlow(id1).first()?.title)+ assertNull(dao.getById(999_999L))+ // Upsert with an existing id updates in place.+ dao.upsert(Conversation(title = "First v2", timestamp = 300L, id = id1))+ assertEquals("First v2", dao.getById(id1)?.title)+ assertEquals(1, dao.delete(Conversation(title = "First v2", timestamp = 300L, id = id1)))+ assertNull(dao.getById(id1))+ }++ @Test fun messageCrudPerConversation() = runTest {+ val dao = db.messageDao()+ val m1 = dao.upsert(Message(conversationId = 7L, text = "hi", role = "user", timestamp = 2L))+ dao.upsert(Message(conversationId = 7L, text = "hello", role = "assistant", timestamp = 1L))+ dao.upsert(Message(conversationId = 8L, text = "other", role = "user", timestamp = 3L))+ // Chronological within a conversation.+ assertEquals(listOf("hello", "hi"), dao.getByConversation(7L).map { it.text })+ assertEquals(listOf("hello", "hi"), dao.getByConversationFlow(7L).first().map { it.text })+ val stored = dao.getById(m1)+ assertNotNull(stored)+ assertEquals(emptyList(), stored.imagePaths)+ assertNull(stored.a2ui)+ dao.upsert(stored.copy(text = "hi again", a2ui = "{}", imagePaths = listOf("/tmp/a.png"), hasAudio = true))+ val updated = dao.getById(m1)!!+ assertEquals("hi again", updated.text)+ assertEquals("{}", updated.a2ui)+ assertEquals(listOf("/tmp/a.png"), updated.imagePaths)+ assertTrue(updated.hasAudio)+ dao.deleteById(m1)+ assertNull(dao.getById(m1))+ assertEquals(1, dao.delete(dao.getByConversation(8L).single()))+ assertTrue(dao.getByConversation(8L).isEmpty())+ }++ @Test fun memoryCrud() = runTest {+ val dao = db.memoryDao()+ assertTrue(dao.getAll().isEmpty())+ val id = dao.upsert(Memory(content = "likes tea"))+ dao.upsert(Memory(content = "lives in Lisbon"))+ assertEquals(listOf("likes tea", "lives in Lisbon"), dao.getAll().map { it.content })+ assertEquals(2, dao.getAllFlow().first().size)+ dao.deleteById(id)+ assertEquals(listOf("lives in Lisbon"), dao.getAll().map { it.content })+ assertEquals(1, dao.delete(dao.getAll().single()))+ assertTrue(dao.getAll().isEmpty())+ }++ @Test fun entityDefaults() {+ val c = Conversation(title = "T")+ assertEquals(0L, c.id)+ assertTrue(c.timestamp > 0)+ val m = Message(conversationId = 1L, text = "x", role = "user")+ assertEquals(emptyList(), m.imagePaths)+ assertEquals(false, m.hasAudio)+ assertNull(m.missingAppPackage)+ assertNull(m.a2ui)+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.ktnew file mode 100644index 0000000000..959061e658--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiSurfaceRenderTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.openassistant.platform++import androidx.a2ui.model.protocol.A2uiDataPath+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.openassistant.data.Message+import com.vayunmathur.openassistant.ui.A2uiSurfaceView+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** A2uiController sync + SurfaceRenderer rendering of a catalog surface. */+@RunWith(RobolectricTestRunner::class)+class A2uiSurfaceRenderTest {++ @get:Rule+ val composeRule = createComposeRule()++ private val json = """+ {"components":[+ {"id":"root","component":"Card","child":"c"},+ {"id":"c","component":"Column","children":["q","n","v","b"]},+ {"id":"q","component":"Text","text":"Who's coming?","variant":"title"},+ {"id":"n","component":"TextField","label":"Name","value":{"path":"/name"}},+ {"id":"v","component":"CheckBox","label":"Vegetarian","value":{"path":"/veg"}},+ {"id":"b","component":"Button","label":"RSVP","primary":true,+ "action":{"event":{"name":"rsvp","context":{"name":{"path":"/name"},"veg":{"path":"/veg"}}}}}+ ],"data":{"name":"","veg":false}}+ """.trimIndent()++ private fun await(timeoutMs: Long = 10_000, cond: () -> Boolean): Boolean {+ val deadline = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < deadline) {+ if (cond()) return true+ Thread.sleep(20)+ }+ return cond()+ }++ @Test fun controllerFeedsSurfaceAndRendererDrawsIt() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ val actions = mutableListOf<Pair<Long, String>>()+ val controller = A2uiController(ctx, scope) { id, text -> actions.add(id to text) }+ try {+ controller.sync(listOf(Message(9L, "hi", "assistant", a2ui = json, id = 7L)))+ assertTrue(await { controller.surfaces.value.containsKey("m7") },+ "surfaces=${controller.surfaces.value.keys}")+ // Idempotent: syncing the same message again feeds nothing new.+ controller.sync(listOf(Message(9L, "hi", "assistant", a2ui = json, id = 7L)))+ assertEquals(1, controller.surfaces.value.size)+ // A message without a block and a bad block are ignored.+ controller.sync(listOf(+ Message(9L, "plain", "assistant", id = 8L),+ Message(9L, "bad", "assistant", a2ui = "{nope", id = 9L)))+ assertEquals(1, controller.surfaces.value.size)++ val surface = controller.surfaces.value.getValue("m7")+ composeRule.setContent { DynamicTheme { A2uiSurfaceView(surface) } }+ composeRule.onNodeWithText("Who's coming?").assertIsDisplayed()+ composeRule.onNodeWithText("Name").assertIsDisplayed()+ composeRule.onNodeWithText("Vegetarian").assertIsDisplayed()+ composeRule.onNodeWithText("RSVP").assertIsDisplayed()+ // Typing into the bound field updates the data model; the button+ // then reports the typed value back through onAction.+ composeRule.onNode(hasSetTextAction()).performTextInput("Ada")+ composeRule.onNodeWithText("RSVP").performClick()+ assertTrue(await { actions.isNotEmpty() }, "actions=$actions")+ assertEquals(9L, actions[0].first)+ assertTrue(actions[0].second.contains("Ada"), actions[0].second)+ } finally {+ scope.cancel()+ }+ }++ @Test fun dataModelPathWritesAndReads() {+ val model = ComposeDataModel()+ model.update(A2uiDataPath("/name"), "Ada")+ model.update(A2uiDataPath("/items/0/title"), "First")+ model.update(A2uiDataPath("/items/1/title"), "Second")+ assertEquals("Ada", model[A2uiDataPath("/name")])+ assertEquals("First", model[A2uiDataPath("/items/0/title")])+ assertEquals("Second", model[A2uiDataPath("/items/1/title")])+ assertNull(model[A2uiDataPath("/missing")])+ assertNull(model[A2uiDataPath("/items/9/title")])+ // Overwriting a leaf and clearing the model.+ model.update(A2uiDataPath("/name"), "Grace")+ assertEquals("Grace", model[A2uiDataPath("/name")])+ model.close()+ assertNull(model[A2uiDataPath("/name")])+ }++ @Test fun componentRegistryTracksErrors() {+ val registry = ComposeComponentRegistry()+ val payload = androidx.a2ui.model.protocol.A2uiComponentPayload(+ "root", "Text", mapOf("text" to "Hi"))+ registry.update(listOf(payload))+ assertEquals(payload, registry.components["root"])+ val exception = org.mockito.Mockito.mock(+ androidx.a2ui.model.protocol.A2uiException::class.java)+ org.mockito.Mockito.`when`(exception.message).thenReturn("bad prop")+ org.mockito.Mockito.`when`(exception.code).thenReturn("INVALID_ARGUMENT")+ registry.reportError("root", exception)+ assertTrue(registry.errors.containsKey("root"))+ // A fresh update clears the component's error.+ registry.update(listOf(payload))+ assertTrue(registry.errors.isEmpty())+ registry.close()+ assertTrue(registry.components.isEmpty())+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktnew file mode 100644index 0000000000..9bbc16bad4--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -0,0 +1,114 @@+package com.vayunmathur.openassistant.platform++import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.openassistant.data.AppDatabase+import com.vayunmathur.openassistant.domain.ParsedToolCall+import com.vayunmathur.openassistant.util.InferenceService+import com.vayunmathur.openassistant.util.ShadowUnresolvableIntent+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * AssistantTools.invoke dispatch: unknown/invalid calls, missing-app results+ * for every cross-app tool, device-local tools, and memory tools.+ */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](shadows = [ShadowUnresolvableIntent::class])+class AssistantToolsInvokeTest {++ private lateinit var db: AppDatabase+ private lateinit var tools: AssistantTools++ @BeforeTest fun setUp() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val activity = org.robolectric.Robolectric.buildActivity(+ androidx.activity.ComponentActivity::class.java).setup().get()+ com.vayunmathur.openassistant.MainActivity.intentLauncher =+ com.vayunmathur.library.util.IntentLauncher(activity)+ db = Room.inMemoryDatabaseBuilder(ctx, AppDatabase::class.java)+ .allowMainThreadQueries().build()+ tools = AssistantTools(ctx, db.memoryDao())+ }++ @AfterTest fun tearDown() { db.close() }++ private fun call(name: String, vararg args: Pair<String, String>) =+ tools.invoke(ParsedToolCall(name, mapOf(*args)))++ @Test fun unknownAndInvalidCalls() {+ assertEquals("Error: unknown tool 'nope'", call("nope"))+ assertEquals("Error: create_note needs title", call("create_note", "content" to "x"))+ assertTrue(+ call("set_timer", "seconds" to "abc").contains("must be a number"))+ assertEquals(28, tools.declarations.size)+ }++ @Test fun crossAppToolsReportMissingApps() {+ assertTrue(call("get_notes").startsWith("The Notes app is required"))+ assertTrue(call("create_note", "title" to "T", "content" to "C").startsWith("The Notes app"))+ assertTrue(call("get_todos").startsWith("The Todo app is required"))+ assertTrue(call("create_todo", "title" to "T").startsWith("The Todo app"))+ assertTrue(call("complete_todo", "id" to "1").startsWith("The Todo app"))+ assertTrue(call("get_contacts").startsWith("The Contacts app is required"))+ assertTrue(call("create_contact", "name" to "A", "phone_number" to "1").startsWith("The Contacts app"))+ assertTrue(call("get_calendar_events").startsWith("The Calendar app is required"))+ assertTrue(+ call("create_calendar_event", "title" to "M", "start" to "1", "end" to "2")+ .startsWith("The Calendar app"))+ assertTrue(call("get_family_locations").startsWith("The FindFamily app is required"))+ assertTrue(+ call("create_location_share_link", "name" to "A", "duration_millis" to "60000")+ .startsWith("The FindFamily app"))+ assertTrue(call("search_music", "query" to "jazz").startsWith("The Music app is required"))+ assertTrue(call("play_music", "id" to "3", "type" to "song").startsWith("The Music app"))+ assertTrue(call("search_emails", "query" to "hi").startsWith("The Email app is required"))+ assertTrue(call("get_recent_emails").startsWith("The Email app"))+ assertTrue(call("set_alarm", "hour" to "7", "minute" to "30").startsWith("The Clock app is required"))+ assertTrue(call("set_timer", "seconds" to "60").startsWith("The Clock app"))+ assertTrue(+ call("get_weather", "latitude" to "1.5", "longitude" to "2.5")+ .startsWith("The Weather app is required"))+ assertTrue(call("get_weather_by_name", "location" to "Lisbon").startsWith("The Weather app"))+ }++ @Test fun deviceToolsRunLocally() {+ val dateTime = call("get_local_current_date_time")+ assertTrue(dateTime.contains("epochMillis="), dateTime)+ // App list renders whatever Robolectric reports installed (possibly none).+ assertTrue(call("get_app_list").startsWith("["))+ // Unknown package has no launch intent: missing-app handler answers.+ assertTrue(+ call("open_app", "package_id" to "com.example.absent")+ .startsWith("The com.example.absent app is required"))+ assertEquals("Opened messaging app.", call("send_message", "recipient" to "123", "message" to "hi"))+ assertEquals("Opened dialer.", call("make_phone_call", "recipient" to "123"))+ assertEquals(+ "Conversation title set successfully",+ call("set_conversation_title", "new_title" to "Trip planning"))+ assertEquals("Trip planning", InferenceService.newTitle)+ }++ @Test fun memoryToolsRoundTrip() {+ assertEquals("Success: Added memory", call("add_to_memory", "content" to "likes tea"))+ val listed = call("get_memories")+ assertTrue(listed.contains("likes tea"), listed)+ assertEquals("Success: Added memory", call("add_to_memory", "content" to "second"))+ assertTrue(call("get_memories").contains("second"))+ }++ @Test fun memoryToolsWithoutDaoError() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val noDao = AssistantTools(ctx, null)+ assertEquals("Error: MemoryDao is null", noDao.invoke(ParsedToolCall("get_memories", emptyMap())))+ assertEquals(+ "Error: MemoryDao is null",+ noDao.invoke(ParsedToolCall("add_to_memory", mapOf("content" to "x"))))+ assertEquals(+ "Error: MemoryDao is null",+ noDao.invoke(ParsedToolCall("remove_memory", mapOf("id" to "1"))))+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/platform/ChatShapesTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/ChatShapesTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/ChatShapesTest.ktnew file mode 100644index 0000000000..1587dea151--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/ChatShapesTest.kt@@ -0,0 +1,25 @@+package com.vayunmathur.openassistant.platform++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** ChatRequest/ChatResult/HistoryTurn value shapes (engine itself is native-bound). */+class ChatShapesTest {+ @Test fun requestDefaults() {+ val req = ChatRequest(system = "s", history = listOf(HistoryTurn(true, "a"), HistoryTurn(false, "b")), userText = "c")+ assertEquals(2, req.history.size)+ assertEquals(emptyList(), req.imagePaths)+ assertNull(req.audioPath)+ assertTrue(req.history[0].fromUser)+ assertTrue(!req.history[1].fromUser)+ }++ @Test fun resultVariants() {+ assertTrue(ChatResult.Reply("x", halted = true).halted)+ assertEquals("x", ChatResult.Reply("x", halted = false).text)+ assertEquals(ChatResult.TooLong, ChatResult.TooLong)+ assertEquals(ChatResult.Unavailable, ChatResult.Unavailable)+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/platform/FakeAndroidKeyStore.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/FakeAndroidKeyStore.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..0be106843a--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/FakeAndroidKeyStore.kt@@ -0,0 +1,94 @@+package com.vayunmathur.openassistant.platform++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * In-memory stand-in for the AndroidKeyStore JCE provider, which Robolectric+ * does not ship. Lets DatabaseHelper generate/store its passphrase key on the+ * JVM so ViewModels backed by the (still unopenable) SQLCipher database can+ * at least be constructed and run their non-database paths.+ */+object FakeAndroidKeyStore {+ private val keys = Collections.synchronizedMap(HashMap<String, Key>())++ fun install() {+ if (Security.getProvider("AndroidKeyStore") == null) {+ Security.addProvider(FakeProvider())+ }+ }++ internal fun put(alias: String, key: Key) {+ keys[alias] = key+ }++ internal fun get(alias: String): Key? = keys[alias]+ internal fun remove(alias: String) {+ keys.remove(alias)+ }++ internal fun contains(alias: String): Boolean = keys.containsKey(alias)+ internal fun aliases(): List<String> = synchronized(keys) { keys.keys.toList() }+}++class FakeProvider : Provider("AndroidKeyStore", 1.0, "fake for tests") {+ init {+ put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+ put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+ }+}++class FakeKeyStoreSpi : KeyStoreSpi() {+ override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+ override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+ override fun engineGetKey(alias: String, password: CharArray?): Key? = FakeAndroidKeyStore.get(alias)+ override fun engineContainsAlias(alias: String): Boolean = FakeAndroidKeyStore.contains(alias)+ override fun engineDeleteEntry(alias: String) = FakeAndroidKeyStore.remove(alias)+ override fun engineAliases(): Enumeration<String> =+ Collections.enumeration(FakeAndroidKeyStore.aliases())+ override fun engineSize(): Int = FakeAndroidKeyStore.aliases().size+ override fun engineIsKeyEntry(alias: String): Boolean = FakeAndroidKeyStore.contains(alias)+ override fun engineIsCertificateEntry(alias: String): Boolean = false+ override fun engineGetCertificate(alias: String): Certificate? = null+ override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+ override fun engineGetCertificateAlias(cert: Certificate): String? = null+ override fun engineGetCreationDate(alias: String): Date = Date(0)+ override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+ FakeAndroidKeyStore.put(alias, key)+ }+ override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) {+ FakeAndroidKeyStore.put(alias, SecretKeySpec(key, "AES"))+ }+ override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+}++class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+ private var alias: String = "db_no_auth_key"++ override fun engineInit(random: SecureRandom?) = Unit+ override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom?) {+ if (params is KeyGenParameterSpec) alias = params.keystoreAlias+ }+ override fun engineInit(keysize: Int, random: SecureRandom?) = Unit++ override fun engineGenerateKey(): SecretKey {+ val bytes = ByteArray(32)+ SecureRandom().nextBytes(bytes)+ val key = SecretKeySpec(bytes, "AES")+ FakeAndroidKeyStore.put(alias, key)+ return key+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/ui/ChatUiComposeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/ui/ChatUiComposeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/ui/ChatUiComposeTest.ktnew file mode 100644index 0000000000..466b15e198--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/ui/ChatUiComposeTest.kt@@ -0,0 +1,177 @@+package com.vayunmathur.openassistant.ui++import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.openassistant.data.Memory+import com.vayunmathur.openassistant.data.Message+import com.vayunmathur.openassistant.util.ChatActions+import com.vayunmathur.openassistant.util.ChatUiState+import com.vayunmathur.openassistant.util.InferenceService+import com.vayunmathur.openassistant.util.SettingsActions+import com.vayunmathur.openassistant.util.SettingsUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** Chat bubbles, composer, chat screen and settings screen under Robolectric. */+@RunWith(RobolectricTestRunner::class)+class ChatUiComposeTest {++ @get:Rule+ val composeRule = createComposeRule()++ @Test fun userBubbleShowsTextAndAudioChip() {+ composeRule.setContent {+ DynamicTheme {+ ChatBubble(Message(1L, "my question", "user", hasAudio = true, id = 5L))+ }+ }+ composeRule.onNodeWithText("my question").assertIsDisplayed()+ composeRule.onNodeWithText("Voice Message").assertIsDisplayed()+ }++ @Test fun assistantBubbleRendersMarkdownText() {+ composeRule.setContent {+ DynamicTheme {+ ChatBubble(Message(1L, "Hello **there**", "assistant", id = 6L))+ }+ }+ composeRule.onNodeWithText("Hello", substring = true).assertExists()+ }++ @Test fun toolBubbleStripsLinkMarkupAndShowsButton() {+ composeRule.setContent {+ DynamicTheme {+ ChatBubble(Message(1L, "Opened [Notes](app://notes/1) for you", "tool", id = 7L))+ }+ }+ composeRule.onNodeWithText("Opened Notes for you", substring = true).assertIsDisplayed()+ composeRule.onNodeWithText("Notes").assertIsDisplayed()+ }++ @Test fun chatInputTypingEnablesSend() {+ var text = ""+ var sends = 0+ composeRule.setContent {+ DynamicTheme {+ ChatInput(+ modifier = Modifier,+ inputText = text,+ onTextChange = { text = it },+ selectedImageUris = emptyList(),+ isRecording = false,+ onAddImage = {}, onRecord = {}, onSend = { sends++ },+ onCancelMedia = {}, onRemoveImage = {})+ }+ }+ composeRule.onNode(hasSetTextAction()).performTextInput("hello assistant")+ assertEquals("hello assistant", text)+ assertEquals(0, sends)+ }++ @Test fun chatInputRecordingChipCancels() {+ var cancels = 0+ composeRule.setContent {+ DynamicTheme {+ ChatInput(+ modifier = Modifier,+ inputText = "",+ onTextChange = {},+ selectedImageUris = emptyList(),+ isRecording = true,+ onAddImage = {}, onRecord = {}, onSend = {},+ onCancelMedia = { cancels++ }, onRemoveImage = {})+ }+ }+ composeRule.onNodeWithText("Recording…").assertIsDisplayed()+ }++ private class RecordingActions : ChatActions {+ var sent = 0+ var settings = 0+ var newChat = 0+ var conversations = 0+ var lastText: String? = null+ override fun setInputText(text: String) { lastText = text }+ override fun send() { sent++ }+ override fun openSettings() { settings++ }+ override fun newConversation() { newChat++ }+ override fun openConversations() { conversations++ }+ }++ @Test fun chatScreenShowsConversationAndActions() {+ val actions = RecordingActions()+ val state = ChatUiState(+ title = "Groceries",+ messages = listOf(+ Message(1L, "hi", "user", id = 1L),+ Message(1L, "hello", "assistant", id = 2L)),+ showConversationsButton = true,+ showNewChatButton = true)+ composeRule.setContent {+ DynamicTheme { ChatScreen(state = state, actions = actions) }+ }+ composeRule.onNodeWithText("Groceries").assertIsDisplayed()+ composeRule.onNodeWithText("hi").assertIsDisplayed()+ composeRule.onNodeWithText("hello").assertIsDisplayed()+ assertTrue(actions.sent == 0)+ }++ @Test fun chatScreenNewConversationTitle() {+ composeRule.setContent {+ DynamicTheme { ChatScreen(state = ChatUiState(), actions = ChatActions.Noop) }+ }+ composeRule.onNodeWithText("New Conversation").assertIsDisplayed()+ }++ @Test fun settingsScreenEmptyMemoriesAndPrompt() {+ var prompt: String? = null+ val actions = object : SettingsActions {+ override fun setSystemPrompt(p: String) { prompt = p }+ }+ composeRule.setContent {+ DynamicTheme {+ SettingsScreen(+ state = SettingsUiState(systemPrompt = InferenceService.DEFAULT_SYSTEM_PROMPT),+ actions = actions)+ }+ }+ composeRule.onNodeWithText("Settings").assertIsDisplayed()+ assertEquals(2, composeRule.onAllNodesWithText("System Prompt").fetchSemanticsNodes().size)+ assertEquals(null, prompt)+ }++ @Test fun settingsListsMemoriesAndDeletes() {+ var deleted: Memory? = null+ val actions = object : SettingsActions {+ override fun deleteMemory(memory: Memory) { deleted = memory }+ }+ val memory = Memory(content = "likes tea", id = 3L)+ composeRule.setContent {+ DynamicTheme {+ SettingsScreen(+ state = SettingsUiState(memories = listOf(memory), systemPrompt = "be nice"),+ actions = actions)+ }+ }+ composeRule.onNodeWithText("likes tea").assertIsDisplayed()+ assertEquals(null, deleted)+ }++ @Test fun memoryItemShowsContent() {+ composeRule.setContent {+ DynamicTheme { MemoryItem(memory = Memory("remember this", id = 1L), onDelete = {}) }+ }+ composeRule.onNodeWithText("remember this").assertIsDisplayed()+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.ktnew file mode 100644index 0000000000..9848bb06fa--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.openassistant.util++import androidx.activity.ComponentActivity+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.intents.clock.SetAlarmData+import com.vayunmathur.library.intents.clock.SetTimerData+import com.vayunmathur.library.intents.contacts.ContactData+import com.vayunmathur.library.intents.calendar.EventData+import com.vayunmathur.library.intents.email.EmailData+import com.vayunmathur.library.intents.music.PlayMusicData+import com.vayunmathur.library.intents.notes.NoteData+import com.vayunmathur.library.intents.todo.CompleteTodoData+import com.vayunmathur.library.intents.todo.GetTodosQuery+import com.vayunmathur.library.intents.todo.InsertTodoData+import com.vayunmathur.library.util.IntentLauncher+import com.vayunmathur.openassistant.MainActivity+import com.vayunmathur.openassistant.data.AppDatabase+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.robolectric.Robolectric++/**+ * AssistantToolIntents against Robolectric: cross-app packages are not+ * installed, so every IPC tool surfaces the missing-app path; memory tools+ * run against a real in-memory DAO.+ */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](shadows = [ShadowUnresolvableIntent::class])+class AssistantToolIntentsTest {++ private lateinit var tools: AssistantToolIntents+ private lateinit var db: AppDatabase++ @BeforeTest fun setUp() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val activity = Robolectric.buildActivity(ComponentActivity::class.java).setup().get()+ MainActivity.intentLauncher = IntentLauncher(activity)+ tools = AssistantToolIntents(ctx)+ db = Room.inMemoryDatabaseBuilder(ctx, AppDatabase::class.java)+ .allowMainThreadQueries().build()+ }++ @AfterTest fun tearDown() { db.close() }++ @Test fun missingAppMessagesNameTheApp() {+ assertTrue(+ AssistantToolIntents.getMissingAppMessage("com.vayunmathur.notes")+ .startsWith("The Notes app is required but not installed."))+ assertTrue(+ AssistantToolIntents.getMissingAppMessage("com.vayunmathur.todo")+ .contains("The Todo app"))+ // Unknown packages fall back to the raw package name.+ assertTrue(+ AssistantToolIntents.getMissingAppMessage("com.example.other")+ .startsWith("The com.example.other app is required"))+ assertTrue(+ tools.handleMissingApp("com.vayunmathur.clock")+ .contains("Try to help the user with your own knowledge instead."))+ }++ @Test fun runToolWrapsSuccessErrorsAndMissingApps() {+ assertEquals("done", tools.runTool { "done" })+ assertEquals("Error: boom", tools.runTool { throw IllegalStateException("boom") })+ assertEquals("Error: null", tools.runTool { throw RuntimeException() })+ val missing = tools.runTool { throw MissingAppException("com.vayunmathur.email") }+ assertTrue(missing.startsWith("The Email app is required"), missing)+ }++ @Test fun crossAppToolsThrowMissingApp() = runTest {+ assertFailsWith<MissingAppException> { tools.getNotes() }+ assertFailsWith<MissingAppException> { tools.insertNote(NoteData(title = "t", content = "c")) }+ assertFailsWith<MissingAppException> { tools.getTodos(GetTodosQuery()) }+ assertFailsWith<MissingAppException> { tools.insertTodo(InsertTodoData(title = "t")) }+ assertFailsWith<MissingAppException> { tools.completeTodo(CompleteTodoData(id = "1")) }+ assertFailsWith<MissingAppException> { tools.getContacts() }+ assertFailsWith<MissingAppException> { tools.insertContact(ContactData(name = "Ann", phoneNumber = "123")) }+ assertFailsWith<MissingAppException> { tools.getCalendarEvents() }+ assertFailsWith<MissingAppException> {+ tools.insertCalendarEvent(EventData(title = "Meet", start = 1L, end = 2L))+ }+ assertFailsWith<MissingAppException> { tools.getFamilyLocations() }+ assertFailsWith<MissingAppException> { tools.createLocationShareLink("Ann", 60_000.0) }+ assertFailsWith<MissingAppException> { tools.searchMusic("jazz") }+ assertFailsWith<MissingAppException> { tools.playMusic(PlayMusicData(id = 1L, type = "song")) }+ assertFailsWith<MissingAppException> { tools.searchEmails("invoice") }+ assertFailsWith<MissingAppException> { tools.getRecentEmails() }+ assertFailsWith<MissingAppException> {+ tools.setAlarm(SetAlarmData(hour = 7, minute = 30))+ }+ assertFailsWith<MissingAppException> { tools.setTimer(SetTimerData(seconds = 300)) }+ assertFailsWith<MissingAppException> { tools.getWeather(1.0, 2.0) }+ assertFailsWith<MissingAppException> { tools.getWeatherByName("Lisbon") }+ // And via runTool they become the friendly message instead of a throw.+ assertTrue(tools.runTool { tools.getNotes() }.startsWith("The Notes app is required"))+ }++ @Test fun memoryToolsUseDao() = runTest {+ val dao = db.memoryDao()+ assertEquals("Error: MemoryDao is null", tools.getMemories(null))+ assertEquals("Error: MemoryDao is null", tools.addToMemory(null, "x"))+ assertEquals("Error: MemoryDao is null", tools.removeMemory(null, 1.0))++ assertEquals("Success: Added memory", tools.addToMemory(dao, "likes tea"))+ tools.addToMemory(dao, "lives in Lisbon")+ val all = tools.getMemories(dao)+ assertTrue(all.contains("likes tea"), all)+ assertTrue(all.contains("lives in Lisbon"), all)+ val id = dao.getAll().first { it.content == "likes tea" }.id+ assertEquals("Success: Removed memory with id $id", tools.removeMemory(dao, id.toDouble()))+ assertEquals(listOf("lives in Lisbon"), dao.getAll().map { it.content })+ }++ @Test fun requestPayloadShapes() {+ assertEquals(3.5, WeatherLatLonRequest(3.5, -1.25).latitude)+ assertEquals("Lisbon", WeatherNameRequest("Lisbon").name)+ assertEquals(90L, CreateLinkRequest("Ann", 90L).expiryMillis)+ assertTrue(EmailData::class.java.name.endsWith("EmailData"))+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.ktnew file mode 100644index 0000000000..6f129b9999--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantViewModelTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.openassistant.util++import android.app.Application+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.openassistant.data.OpenAssistantRepository+import com.vayunmathur.openassistant.platform.FakeAndroidKeyStore+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.robolectric.Shadows++/**+ * AssistantViewModel service dispatch + recording-state lifecycle under+ * Robolectric (the repository is the real singleton; its SQLCipher database+ * is never opened on these paths).+ */[email protected](org.robolectric.RobolectricTestRunner::class)+class AssistantViewModelTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private lateinit var vm: AssistantViewModel++ @BeforeTest fun setUp() {+ FakeAndroidKeyStore.install()+ vm = AssistantViewModel(app, OpenAssistantRepository.get(app))+ // Drain the init pre-warm startService call.+ Shadows.shadowOf(app).clearStartedServices()+ }++ private fun nextService(): Intent = Shadows.shadowOf(app).nextStartedService++ @Test fun requestInferenceDispatchesExtras() {+ vm.requestInference(42L, "hello there", listOf("/a.png", "/b.png"), "/audio.wav")+ val intent = nextService()+ assertEquals(InferenceService::class.java.name, intent.component?.className)+ assertEquals(42L, intent.getLongExtra("conversation_id", -1L))+ assertEquals("hello there", intent.getStringExtra("user_text"))+ assertEquals(+ listOf("/a.png", "/b.png"),+ intent.getStringArrayExtra("image_paths")?.toList())+ assertEquals("/audio.wav", intent.getStringExtra("audio_path"))+ }++ @Test fun screenContextSeedsOnlyOneTurn() {+ vm.setScreenContext(" Notes app showing Groceries ")+ vm.requestInference(1L, "summarize", emptyList(), null)+ val first = nextService()+ assertTrue(first.getStringExtra("user_text")!!.startsWith("Current screen contents:"))+ assertTrue(first.getStringExtra("user_text")!!.endsWith("User request: summarize"))+ // Context is consumed: the next turn sends the raw text.+ vm.requestInference(1L, "again", emptyList(), null)+ assertEquals("again", nextService().getStringExtra("user_text"))+ // Blank context is ignored entirely.+ vm.setScreenContext(" ")+ vm.requestInference(1L, "third", emptyList(), null)+ assertEquals("third", nextService().getStringExtra("user_text"))+ vm.setScreenContext(null)+ vm.requestInference(1L, "fourth", emptyList(), null)+ assertEquals("fourth", nextService().getStringExtra("user_text"))+ }++ @Test fun recordingLifecycle() = runTest {+ assertFalse(vm.isRecording.value)+ assertNull(vm.recordedAudioPath.value)+ vm.startRecording()+ // Robolectric's AudioRecord shadow lets the recorder start; a second+ // start while recording is refused.+ assertTrue(vm.isRecording.value)+ val path = vm.recordedAudioPath.value+ assertTrue(path!!.endsWith(".wav"), path)+ vm.startRecording()+ assertEquals(path, vm.recordedAudioPath.value)+ vm.stopRecording()+ assertFalse(vm.isRecording.value)+ // The pending path survives stop (it is the send attachment).+ assertEquals(path, vm.recordedAudioPath.value)+ vm.consumeRecordedAudio()+ assertNull(vm.recordedAudioPath.value)+ vm.cancelRecording()+ assertNull(vm.awaitRecordedAudio())+ }++ @Test fun factoryCreatesViewModelAndRejectsOthers() {+ val factory = AssistantViewModelFactory(app, OpenAssistantRepository.get(app))+ val created = factory.create(AssistantViewModel::class.java)+ assertEquals(vm.javaClass, created.javaClass)+ assertFailsWith<IllegalArgumentException> {+ factory.create(OtherViewModel::class.java)+ }+ }++ class OtherViewModel : androidx.lifecycle.ViewModel()+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.ktnew file mode 100644index 0000000000..cd16a8dcf4--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.openassistant.util++import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.openassistant.Route+import com.vayunmathur.openassistant.platform.FakeAndroidKeyStore+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** copyUriToFile against the Robolectric content resolver, routes, backup agent config. */[email protected](org.robolectric.RobolectricTestRunner::class)+class CopyUriAndRouteTest {++ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ @Test fun copyUriToFileCopiesContent() {+ val source = File(ctx.cacheDir, "source-image.bin")+ source.writeBytes(byteArrayOf(1, 2, 3, 4, 5))+ val copied = copyUriToFile(ctx, Uri.fromFile(source))+ assertTrue(copied != null && copied.exists())+ assertEquals(listOf<Byte>(1, 2, 3, 4, 5), copied!!.readBytes().toList())+ assertTrue(copied.name.startsWith("img_") && copied.name.endsWith(".jpg"))+ copied.delete()+ }++ @Test fun copyUriToFileMissingSourceIsNull() {+ val missing = File(ctx.cacheDir, "no-such-image.bin")+ assertNull(copyUriToFile(ctx, Uri.fromFile(missing)))+ assertNull(copyUriToFile(ctx, Uri.parse("content://com.example.absent/1")))+ }++ @Test fun copyUriToFileEmptySourceIsNull() {+ val empty = File(ctx.cacheDir, "empty.bin")+ empty.writeBytes(ByteArray(0))+ assertNull(copyUriToFile(ctx, Uri.fromFile(empty)))+ }++ @Test fun routesCarryIds() {+ assertEquals(Route.ConversationPage(7L), Route.ConversationPage(7L))+ assertEquals(7L, Route.ConversationPage(7L).id)+ assertEquals(Route.SettingsPage, Route.SettingsPage)+ assertTrue(Route.ConversationPage(1L) != Route.ConversationPage(2L))+ }++ @Test fun backupAgentConfigWithoutKey() {+ FakeAndroidKeyStore.install()+ val agent = AppBackupAgent()+ assertEquals(SqlCipherDbCodec, agent.dbCodec)+ assertEquals(emptyList(), agent.extraFiles)+ // No passphrase key has been generated in this environment.+ assertEquals(emptyList(), agent.dbConfigs)+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceTest.ktnew file mode 100644index 0000000000..87eea97578--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceTest.kt@@ -0,0 +1,45 @@+package com.vayunmathur.openassistant.util++import android.app.Service+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.robolectric.Robolectric++/**+ * InferenceService lifecycle surface that does not need the native engine:+ * binding, null-intent start, and the shared prompt/title state.+ * (Inference itself is native-bound: Gemma4Handle cannot load on the JVM.)+ */[email protected](org.robolectric.RobolectricTestRunner::class)+class InferenceServiceTest {++ @Test fun promptAndSharedState() {+ assertTrue(InferenceService.DEFAULT_SYSTEM_PROMPT.contains("helpful Android assistant"))+ assertTrue(InferenceService.DEFAULT_SYSTEM_PROMPT.contains("add_to_memory"))+ assertEquals("system_prompt", InferenceService.KEY_SYSTEM_PROMPT)+ InferenceService.newTitle = "A title"+ assertEquals("A title", InferenceService.newTitle)+ InferenceService.newTitle = null+ assertNull(InferenceService.newTitle)+ InferenceService.halt = true+ assertTrue(InferenceService.halt)+ InferenceService.halt = false+ }++ @Test fun serviceLifecycleBasics() {+ val controller = Robolectric.buildService(InferenceService::class.java)+ val service = controller.create().get()+ assertNull(service.onBind(null))+ // Null intent (system restart) is sticky and queues nothing.+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ assertEquals(Service.START_STICKY, service.onStartCommand(null, 0, 1))+ // An intent with no conversation and no schema/receiver queues nothing.+ val bare = Intent(ctx, InferenceService::class.java)+ assertEquals(Service.START_STICKY, service.onStartCommand(bare, 0, 2))+ controller.destroy()+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.ktnew file mode 100644index 0000000000..989e1d3057--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.openassistant.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive++/** JsonSchemaValidator (subset used for tool args) + JsonExtractor streaming recovery. */[email protected](org.robolectric.RobolectricTestRunner::class)+class JsonValidationTest {++ private fun validate(json: String, schema: String) =+ JsonSchemaValidator.validateJsonAgainstSchema(json, schema)++ @Test fun validObjectPasses() {+ assertNull(validate(+ """{"name":"ann","age":3}""",+ """{"type":"object","properties":{"name":{},"age":{}},"required":["name"]}"""))+ }++ @Test fun invalidJsonAndInvalidSchema() {+ assertTrue(validate("not json", "{}")!!.startsWith("Invalid JSON format"))+ // A schema that is itself invalid JSON is a programmer error: null (no user error).+ assertNull(validate("{}", "not json"))+ // Non-object schema imposes nothing.+ assertNull(validate("""{"a":1}""", """["x"]"""))+ }++ @Test fun typeMismatchAndNestedPaths() {+ assertTrue(validate("""[1]""", """{"type":"object"}""")!!.contains("Expected an object"))+ assertTrue(validate("""{"a":1}""", """{"type":"array"}""")!!.contains("Expected an array"))+ val nested = validate(+ """{"outer":{"inner":[1,2]}}""",+ """{"type":"object","properties":{"outer":{"type":"object","properties":{"inner":{"type":"object"}}}}}""")+ assertTrue(nested!!.contains("at outer.inner"), nested)+ }++ @Test fun unknownAndRequiredFields() {+ val schema = """{"type":"object","properties":{"name":{}},"required":["name","id"]}"""+ assertTrue(validate("""{"name":"x","extra":1,"id":2}""", schema)!!.contains("Unexpected field found: 'extra'"))+ assertTrue(validate("""{"name":"x"}""", schema)!!.contains("Missing required field: 'id'"))+ // Without a properties map every field is unexpected.+ assertTrue(validate("""{"a":1}""", """{"type":"object"}""")!!.contains("Unexpected field"))+ }++ @Test fun constAndEnumConstraints() {+ val schema = """{"properties":{"kind":{"const":"note"},"level":{"enum":["low","high"]}}}"""+ assertTrue(validate("""{"kind":"task","level":"low"}""", schema)!!.contains("must be 'note'"))+ val enumErr = validate("""{"kind":"note","level":"mid"}""", schema)+ assertTrue(enumErr!!.contains("invalid value 'mid'"), enumErr)+ assertTrue(enumErr.contains("low"), enumErr)+ assertNull(validate("""{"kind":"note","level":"high"}""", schema))+ }++ @Test fun arrayItemsAreValidated() {+ val schema = """{"type":"array","items":{"type":"object","properties":{"n":{}},"required":["n"]}}"""+ assertNull(validate("""[{"n":1},{"n":2}]""", schema))+ val err = validate("""[{"n":1},{}]""", schema)+ assertTrue(err!!.contains("[1]"), err)+ assertTrue(err.contains("Missing required field"), err)+ }++ @Test fun anyOfOneOfNotCombinators() {+ // Note: object validation is strict about unknown fields, so an+ // anyOf branch must declare its properties to ever match.+ val typedAnyOf = """{"anyOf":[{"properties":{"a":{}},"required":["a"]},{"properties":{"b":{}},"required":["b"]}]}"""+ // One branch matches, but the enclosing object check then rejects the+ // field (combinators do not short-circuit sibling validation).+ assertTrue(validate("""{"b":1}""", typedAnyOf)!!.contains("Unexpected field"))+ assertTrue(validate("""{"c":1}""", typedAnyOf)!!.contains("anyOf"))++ val oneOf = """{"oneOf":[{"properties":{"a":{}},"required":["a"]},{"properties":{"a":{},"b":{}},"required":["a"]}]}"""+ // No data set cleanly satisfies exactly one branch under the strict+ // unknown-field rule, so both shapes surface a validation error.+ assertNotNull(validate("""{"a":1,"b":2}""", oneOf))+ assertTrue(validate("""{"z":1}""", oneOf)!!.contains("oneOf"))++ val notSchema = """{"not":{"properties":{"bad":{}},"required":["bad"]}}"""+ assertTrue(validate("""{"bad":1}""", notSchema)!!.contains("forbidden"))+ // A non-matching field passes the 'not' check but is then rejected by+ // the enclosing strict object check (no properties declared).+ assertTrue(validate("""{"good":1}""", notSchema)!!.contains("Unexpected field"))+ }++ @Test fun trimJsonKeysRecurses() {+ val parsed = Json.parseToJsonElement("""{" a ": {" b ": [ {" c ": 1} ] } }""")+ val trimmed = JsonSchemaValidator.trimJsonKeys(parsed) as JsonObject+ assertEquals(setOf("a"), trimmed.keys)+ val inner = trimmed["a"] as JsonObject+ val arr = inner["b"] as kotlinx.serialization.json.JsonArray+ assertEquals(JsonPrimitive(1), (arr[0] as JsonObject)["c"])+ // Primitives pass through untouched.+ assertEquals(JsonPrimitive(" x "), JsonSchemaValidator.trimJsonKeys(JsonPrimitive(" x ")))+ }++ // ---- JsonExtractor ----++ @Test fun extractorFindsBalancedObject() {+ assertEquals("""{"a":1}""", JsonExtractor.largestObject("""prefix {"a":1} suffix"""))+ assertEquals("""{"a":{"b":2}}""", JsonExtractor.largestObject("""{"a":{"b":2}}"""))+ assertNull(JsonExtractor.largestObject("no json here"))+ assertNull(JsonExtractor.largestObject("""{"unclosed": """))+ }++ @Test fun extractorIgnoresBracesInsideStrings() {+ val text = """{"a":"} not a brace {"} tail"""+ assertEquals("""{"a":"} not a brace {"}""", JsonExtractor.largestObject(text))+ val escaped = """{"a":"quote \" } still string"}"""+ assertEquals(escaped, JsonExtractor.largestObject(escaped))+ }++ @Test fun extractorSkipsInvalidCandidateForLaterValidOne() {+ // First balanced candidate is not valid JSON (trailing comma style), a later one is.+ assertNull(JsonExtractor.largestObject("""{"a":}"""))+ val mixed = """noise {"bad":} more {"good":1}"""+ // The extractor returns the first *valid* balanced object it completes.+ val found = JsonExtractor.largestObject(mixed)+ assertTrue(found == null || found.contains("good"), "found=$found")+ assertNotNull(JsonExtractor.largestObject("""{"good":1}"""))+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.ktnew file mode 100644index 0000000000..38b398ff74--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.kt@@ -0,0 +1,14 @@+package com.vayunmathur.openassistant.util++import android.content.Intent+import android.content.pm.PackageManager+import android.content.pm.ResolveInfo+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements++/** Every intent reads as unresolvable, so cross-app launches take the missing-app path. */+@Implements(Intent::class)+class ShadowUnresolvableIntent {+ @Implementation+ fun resolveActivity(pm: PackageManager): ResolveInfo? = null+}