Colota - Android GPS Location tracker
- 4 new test files (LocationServiceModule, DatabaseHelperSQLite, ConditionMonitor, LocationBootReceiver) - 4 expanded/rewritten test files (SyncManager, LocationForegroundService, NotificationHelper, DeviceInfoHelper) - Deleted redundant DatabaseHelperTest - Added Robolectric dependency + config
Max Dietrich3ab0cf16275e
diff --git a/README.md b/README.mdindex a3155e23..167762c6 100644--- a/README.md+++ b/README.md@@ -1,4 +1,4 @@-# Colota+# Colota - GPS Location Tracker[](https://www.gnu.org/licenses/agpl-3.0)  [](https://github.com/dietrichmax/colota/actions/workflows/lint-test.yml) [](https://github.com/dietrichmax/colota/actions/workflows/build-check.yml) [](https://developer.android.com) [](https://reactnative.dev) [](https://www.typescriptlang.org/)diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradleindex 724344f3..65d96a7e 100644--- a/apps/mobile/android/app/build.gradle+++ b/apps/mobile/android/app/build.gradle@@ -186,4 +186,6 @@ dependencies {testImplementation 'io.mockk:mockk:1.14.9'testImplementation 'org.json:json:20240303'testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2'+ testImplementation 'org.robolectric:robolectric:4.14.1'+ testImplementation 'androidx.test:core:1.6.1'}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.ktnew file mode 100644index 00000000..d8d760b2--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt@@ -0,0 +1,382 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.bridge++import android.location.Location+import com.Colota.data.DatabaseHelper+import com.Colota.data.GeofenceHelper+import com.Colota.data.ProfileHelper+import com.Colota.service.LocationForegroundService+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.JavaOnlyMap+import com.facebook.react.bridge.ReactApplicationContext+import com.facebook.react.modules.core.DeviceEventManagerModule+import io.mockk.*+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import java.lang.ref.WeakReference++/**+ * Tests for LocationServiceModule:+ * - Companion object event methods (foreground gating, null context, event emission)+ * - Lifecycle methods (isAppInForeground toggle)+ * - Conditional service action dispatch (triggerProfileRecheck, refreshNotificationIfTracking)+ * - CRUD side effects (cache invalidation + recheck triggers)+ */+@Suppress("DEPRECATION")+class LocationServiceModuleTest {++ private lateinit var mockContext: ReactApplicationContext+ private lateinit var mockEmitter: DeviceEventManagerModule.RCTDeviceEventEmitter++ @Before+ fun setUp() {+ mockEmitter = mockk(relaxed = true)+ mockContext = mockk(relaxed = true) {+ every { hasActiveCatalystInstance() } returns true+ every { getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) } returns mockEmitter+ }++ mockkStatic(Arguments::class)+ every { Arguments.createMap() } returns JavaOnlyMap()++ setCompanionField("reactContextRef", WeakReference(mockContext))+ setCompanionField("isAppInForeground", true)+ setCompanionField("activeProfileName", null)+ }++ @After+ fun tearDown() {+ unmockkStatic(Arguments::class)+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ setCompanionField("isAppInForeground", true)+ setCompanionField("activeProfileName", null)+ }++ // ========================================================================+ // sendLocationEvent+ // ========================================================================++ @Test+ fun `sendLocationEvent returns false when app is backgrounded`() {+ setCompanionField("isAppInForeground", false)+ assertFalse(LocationServiceModule.sendLocationEvent(mockLocation(), 85, 2))+ verify(exactly = 0) { mockEmitter.emit(any(), any()) }+ }++ @Test+ fun `sendLocationEvent returns false when context is null`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ assertFalse(LocationServiceModule.sendLocationEvent(mockLocation(), 85, 2))+ }++ @Test+ fun `sendLocationEvent returns false when no active catalyst`() {+ every { mockContext.hasActiveCatalystInstance() } returns false+ assertFalse(LocationServiceModule.sendLocationEvent(mockLocation(), 85, 2))+ }++ @Test+ fun `sendLocationEvent emits onLocationUpdate when conditions met`() {+ assertTrue(LocationServiceModule.sendLocationEvent(mockLocation(), 85, 2))+ verify { mockEmitter.emit("onLocationUpdate", any()) }+ }++ @Test+ fun `sendLocationEvent returns false on exception`() {+ every {+ mockContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)+ } throws RuntimeException("bridge dead")+ assertFalse(LocationServiceModule.sendLocationEvent(mockLocation(), 85, 2))+ }++ // ========================================================================+ // sendTrackingStoppedEvent+ // ========================================================================++ @Test+ fun `sendTrackingStoppedEvent emits onTrackingStopped`() {+ assertTrue(LocationServiceModule.sendTrackingStoppedEvent("battery_critical"))+ verify { mockEmitter.emit("onTrackingStopped", any()) }+ }++ @Test+ fun `sendTrackingStoppedEvent returns false when no context`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ assertFalse(LocationServiceModule.sendTrackingStoppedEvent("oom_kill"))+ }++ @Test+ fun `sendTrackingStoppedEvent returns false when no catalyst`() {+ every { mockContext.hasActiveCatalystInstance() } returns false+ assertFalse(LocationServiceModule.sendTrackingStoppedEvent("reason"))+ }++ // ========================================================================+ // sendSyncErrorEvent+ // ========================================================================++ @Test+ fun `sendSyncErrorEvent emits onSyncError`() {+ assertTrue(LocationServiceModule.sendSyncErrorEvent("Network failed", 42))+ verify { mockEmitter.emit("onSyncError", any()) }+ }++ @Test+ fun `sendSyncErrorEvent returns false when no context`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ assertFalse(LocationServiceModule.sendSyncErrorEvent("error", 0))+ }++ // ========================================================================+ // sendProfileSwitchEvent+ // ========================================================================++ @Test+ fun `sendProfileSwitchEvent updates activeProfileName`() {+ LocationServiceModule.sendProfileSwitchEvent("Charging", 1)+ assertEquals("Charging", getCompanionField("activeProfileName"))+ }++ @Test+ fun `sendProfileSwitchEvent clears activeProfileName on deactivation`() {+ setCompanionField("activeProfileName", "Charging")+ LocationServiceModule.sendProfileSwitchEvent(null, null)+ assertNull(getCompanionField("activeProfileName"))+ }++ @Test+ fun `sendProfileSwitchEvent updates name even when context is null`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ LocationServiceModule.sendProfileSwitchEvent("Fast", 3)+ assertEquals("Fast", getCompanionField("activeProfileName"))+ }++ @Test+ fun `sendProfileSwitchEvent emits onProfileSwitch`() {+ assertTrue(LocationServiceModule.sendProfileSwitchEvent("Charging", 1))+ verify { mockEmitter.emit("onProfileSwitch", any()) }+ }++ @Test+ fun `sendProfileSwitchEvent returns false when no context but still updates name`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ assertFalse(LocationServiceModule.sendProfileSwitchEvent("Fast", 3))+ assertEquals("Fast", getCompanionField("activeProfileName"))+ }++ // ========================================================================+ // sendSyncProgressEvent+ // ========================================================================++ @Test+ fun `sendSyncProgressEvent emits onSyncProgress`() {+ assertTrue(LocationServiceModule.sendSyncProgressEvent(5, 2, 100))+ verify { mockEmitter.emit("onSyncProgress", any()) }+ }++ @Test+ fun `sendSyncProgressEvent returns false when no context`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ assertFalse(LocationServiceModule.sendSyncProgressEvent(0, 0, 0))+ }++ // ========================================================================+ // sendPauseZoneEvent+ // ========================================================================++ @Test+ fun `sendPauseZoneEvent emits onPauseZoneChange`() {+ assertTrue(LocationServiceModule.sendPauseZoneEvent(true, "Home"))+ verify { mockEmitter.emit("onPauseZoneChange", any()) }+ }++ @Test+ fun `sendPauseZoneEvent returns false when no context`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ assertFalse(LocationServiceModule.sendPauseZoneEvent(false, null))+ }++ @Test+ fun `sendPauseZoneEvent returns false when no catalyst`() {+ every { mockContext.hasActiveCatalystInstance() } returns false+ assertFalse(LocationServiceModule.sendPauseZoneEvent(true, "Office"))+ }++ // ========================================================================+ // Lifecycle methods+ // ========================================================================++ @Test+ fun `onHostResume sets foreground true`() {+ setCompanionField("isAppInForeground", false)+ createModule().onHostResume()+ assertTrue(getCompanionField("isAppInForeground") as Boolean)+ }++ @Test+ fun `onHostPause sets foreground false`() {+ setCompanionField("isAppInForeground", true)+ createModule().onHostPause()+ assertFalse(getCompanionField("isAppInForeground") as Boolean)+ }++ @Test+ fun `onHostDestroy sets foreground false`() {+ setCompanionField("isAppInForeground", true)+ createModule().onHostDestroy()+ assertFalse(getCompanionField("isAppInForeground") as Boolean)+ }++ // ========================================================================+ // triggerProfileRecheck — only dispatches when tracking is enabled+ // ========================================================================++ @Test+ fun `triggerProfileRecheck skips when tracking disabled`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "false"++ invokePrivate(module, "triggerProfileRecheck")++ verify(exactly = 0) { module["startServiceWithAction"](any<String>()) }+ }++ @Test+ fun `triggerProfileRecheck dispatches when tracking enabled`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "true"++ invokePrivate(module, "triggerProfileRecheck")++ verify { module["startServiceWithAction"](LocationForegroundService.ACTION_RECHECK_PROFILES) }+ }++ // ========================================================================+ // refreshNotificationIfTracking — only dispatches when tracking is enabled+ // ========================================================================++ @Test+ fun `refreshNotificationIfTracking skips when not tracking`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "false"++ invokePrivate(module, "refreshNotificationIfTracking")++ verify(exactly = 0) { module["startServiceWithAction"](any<String>()) }+ }++ @Test+ fun `refreshNotificationIfTracking dispatches when tracking`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "true"++ invokePrivate(module, "refreshNotificationIfTracking")++ verify { module["startServiceWithAction"](LocationForegroundService.ACTION_REFRESH_NOTIFICATION) }+ }++ // ========================================================================+ // Module name+ // ========================================================================++ @Test+ fun `getName returns LocationServiceModule`() {+ assertEquals("LocationServiceModule", createModule().getName())+ }++ // ========================================================================+ // getActiveProfile reads companion activeProfileName+ // ========================================================================++ @Test+ fun `getActiveProfile resolves null when no profile active`() {+ setCompanionField("activeProfileName", null)+ val promise = mockk<com.facebook.react.bridge.Promise>(relaxed = true)+ createModule().getActiveProfile(promise)+ verify { promise.resolve(null) }+ }++ @Test+ fun `getActiveProfile resolves profile name when active`() {+ setCompanionField("activeProfileName", "Charging")+ val promise = mockk<com.facebook.react.bridge.Promise>(relaxed = true)+ createModule().getActiveProfile(promise)+ verify { promise.resolve("Charging") }+ }++ // ========================================================================+ // Helpers+ // ========================================================================++ private fun createModule(): LocationServiceModule {+ val unsafeClass = Class.forName("sun.misc.Unsafe")+ val unsafeField = unsafeClass.getDeclaredField("theUnsafe")+ unsafeField.isAccessible = true+ val unsafe = unsafeField.get(null)+ val allocateMethod = unsafeClass.getMethod("allocateInstance", Class::class.java)+ return allocateMethod.invoke(unsafe, LocationServiceModule::class.java) as LocationServiceModule+ }++ /**+ * Creates a spyk module with mocked dbHelper and stubbed startServiceWithAction.+ * Returns the module and its dbHelper for test setup.+ */+ private fun createModuleWithDeps(): Pair<LocationServiceModule, DatabaseHelper> {+ val raw = createModule()+ val module = spyk(raw, recordPrivateCalls = true)+ val dbHelper = mockk<DatabaseHelper>(relaxed = true)+ setField(module, "dbHelper", dbHelper)+ // Stub private method to avoid real Android service start+ every { module["startServiceWithAction"](any<String>()) } returns Unit+ return Pair(module, dbHelper)+ }++ private fun mockLocation(lat: Double = 52.52, lon: Double = 13.405): Location {+ return mockk {+ every { latitude } returns lat+ every { longitude } returns lon+ every { accuracy } returns 10f+ every { speed } returns 1.5f+ every { bearing } returns 90f+ every { time } returns 1700000000000L+ every { hasAltitude() } returns false+ every { hasBearing() } returns true+ }+ }++ private fun setCompanionField(name: String, value: Any?) {+ val field = LocationServiceModule::class.java.getDeclaredField(name)+ field.isAccessible = true+ field.set(null, value)+ }++ private fun getCompanionField(name: String): Any? {+ val field = LocationServiceModule::class.java.getDeclaredField(name)+ field.isAccessible = true+ return field.get(null)+ }++ private fun setField(obj: Any, name: String, value: Any?) {+ val field = obj.javaClass.getDeclaredField(name)+ field.isAccessible = true+ field.set(obj, value)+ }++ private fun getField(obj: Any, name: String): Any? {+ val field = obj.javaClass.getDeclaredField(name)+ field.isAccessible = true+ return field.get(obj)+ }++ private fun invokePrivate(obj: Any, methodName: String) {+ val method = obj.javaClass.getDeclaredMethod(methodName)+ method.isAccessible = true+ method.invoke(obj)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.ktnew file mode 100644index 00000000..78a51239--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt@@ -0,0 +1,710 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.data++import android.content.ContentValues+import android.database.sqlite.SQLiteDatabase+import androidx.test.core.app.ApplicationProvider+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * SQLite integration tests for DatabaseHelper using Robolectric.+ * Tests actual insert/query/delete, onUpgrade migration, WAL mode,+ * transaction handling, and foreign key cascades against a real SQLite DB.+ */+@RunWith(RobolectricTestRunner::class)+class DatabaseHelperSQLiteTest {++ private lateinit var db: DatabaseHelper++ @Before+ fun setUp() {+ // Reset singleton so each test gets a fresh database+ resetSingleton()+ db = DatabaseHelper.getInstance(ApplicationProvider.getApplicationContext())+ }++ @After+ fun tearDown() {+ db.close()+ resetSingleton()+ }++ private fun resetSingleton() {+ val field = DatabaseHelper::class.java.getDeclaredField("INSTANCE")+ field.isAccessible = true+ field.set(null, null)+ }++ // ========================================================================+ // Schema creation — tables and indexes exist+ // ========================================================================++ @Test+ fun `onCreate creates all five tables`() {+ val tables = queryTableNames()+ assertTrue(tables.contains("locations"))+ assertTrue(tables.contains("queue"))+ assertTrue(tables.contains("settings"))+ assertTrue(tables.contains("geofences"))+ assertTrue(tables.contains("tracking_profiles"))+ }++ @Test+ fun `onCreate creates indexes`() {+ val indexes = queryIndexNames()+ assertTrue(indexes.contains("idx_queue_created"))+ assertTrue(indexes.contains("idx_queue_location"))+ assertTrue(indexes.contains("idx_locations_timestamp"))+ assertTrue(indexes.contains("idx_locations_created"))+ assertTrue(indexes.contains("idx_geofences_enabled"))+ assertTrue(indexes.contains("idx_profiles_enabled"))+ assertTrue(indexes.contains("idx_queue_retry"))+ }++ @Test+ fun `onCreate prepopulates default settings`() {+ val settings = db.getAllSettings()+ assertEquals("5000", settings["interval"])+ assertEquals("", settings["endpoint"])+ assertEquals("0", settings["syncInterval"])+ assertEquals("false", settings["tracking_enabled"])+ assertEquals("POST", settings["httpMethod"])+ assertEquals("custom", settings["apiTemplate"])+ }++ // ========================================================================+ // onUpgrade — v1 → v2 migration+ // ========================================================================++ @Test+ fun `onUpgrade from v1 creates profiles table`() {+ val rawDb = db.writableDatabase++ // Drop profiles table to simulate v1 state+ rawDb.execSQL("DROP TABLE IF EXISTS ${DatabaseHelper.TABLE_PROFILES}")+ rawDb.execSQL("DROP INDEX IF EXISTS idx_profiles_enabled")++ // Run upgrade+ db.onUpgrade(rawDb, 1, 2)++ // Verify table was recreated+ val tables = queryTableNames()+ assertTrue(tables.contains("tracking_profiles"))++ // Verify we can insert into it+ val values = ContentValues().apply {+ put("name", "Test")+ put("interval_ms", 5000)+ put("min_update_distance", 0.0)+ put("sync_interval_seconds", 0)+ put("priority", 1)+ put("condition_type", "charging")+ put("enabled", 1)+ put("created_at", System.currentTimeMillis() / 1000)+ }+ val id = rawDb.insert(DatabaseHelper.TABLE_PROFILES, null, values)+ assertTrue(id > 0)+ }++ @Test+ fun `onUpgrade is idempotent for same version`() {+ val rawDb = db.writableDatabase++ // Run upgrade again — CREATE TABLE IF NOT EXISTS should be safe+ db.onUpgrade(rawDb, 1, 2)++ val tables = queryTableNames()+ assertTrue(tables.contains("tracking_profiles"))+ }++ // ========================================================================+ // WAL mode and pragmas+ // ========================================================================++ @Test+ fun `database has WAL journal mode enabled`() {+ val rawDb = db.readableDatabase+ rawDb.rawQuery("PRAGMA journal_mode", null).use { cursor ->+ cursor.moveToFirst()+ assertEquals("wal", cursor.getString(0))+ }+ }++ @Test+ fun `foreign keys are enabled`() {+ val rawDb = db.readableDatabase+ rawDb.rawQuery("PRAGMA foreign_keys", null).use { cursor ->+ cursor.moveToFirst()+ assertEquals(1, cursor.getInt(0))+ }+ }++ // ========================================================================+ // Location CRUD operations+ // ========================================================================++ @Test+ fun `saveLocation inserts and returns valid id`() {+ val id = db.saveLocation(+ latitude = 52.52,+ longitude = 13.405,+ accuracy = 10.0,+ timestamp = 1700000000L+ )+ assertTrue(id > 0)+ }++ @Test+ fun `saveLocation stores all fields correctly`() {+ val id = db.saveLocation(+ latitude = 52.52,+ longitude = 13.405,+ accuracy = 10.5,+ altitude = 34,+ speed = 1.5,+ bearing = 90.0,+ battery = 85,+ battery_status = 2,+ timestamp = 1700000000L,+ endpoint = "https://example.com"+ )++ val rawDb = db.readableDatabase+ rawDb.rawQuery("SELECT * FROM ${DatabaseHelper.TABLE_LOCATIONS} WHERE id = ?", arrayOf(id.toString())).use { cursor ->+ assertTrue(cursor.moveToFirst())+ assertEquals(52.52, cursor.getDouble(cursor.getColumnIndexOrThrow("latitude")), 0.001)+ assertEquals(13.405, cursor.getDouble(cursor.getColumnIndexOrThrow("longitude")), 0.001)+ assertEquals(10.5, cursor.getDouble(cursor.getColumnIndexOrThrow("accuracy")), 0.1)+ assertEquals(34, cursor.getInt(cursor.getColumnIndexOrThrow("altitude")))+ assertEquals(90.0, cursor.getDouble(cursor.getColumnIndexOrThrow("bearing")), 0.1)+ assertEquals(85, cursor.getInt(cursor.getColumnIndexOrThrow("battery")))+ assertEquals(2, cursor.getInt(cursor.getColumnIndexOrThrow("battery_status")))+ assertEquals(1700000000L, cursor.getLong(cursor.getColumnIndexOrThrow("timestamp")))+ assertEquals("https://example.com", cursor.getString(cursor.getColumnIndexOrThrow("endpoint")))+ }+ }++ @Test+ fun `saveLocation handles null optional fields`() {+ val id = db.saveLocation(+ latitude = 52.52,+ longitude = 13.405,+ timestamp = 1700000000L+ )++ val rawDb = db.readableDatabase+ rawDb.rawQuery("SELECT accuracy, altitude, speed FROM ${DatabaseHelper.TABLE_LOCATIONS} WHERE id = ?", arrayOf(id.toString())).use { cursor ->+ assertTrue(cursor.moveToFirst())+ assertTrue(cursor.isNull(0))+ assertTrue(cursor.isNull(1))+ assertTrue(cursor.isNull(2))+ }+ }++ @Test+ fun `getRawMostRecentLocation returns latest by timestamp`() {+ db.saveLocation(latitude = 52.0, longitude = 13.0, accuracy = 5.0, timestamp = 1000L)+ db.saveLocation(latitude = 53.0, longitude = 14.0, accuracy = 10.0, timestamp = 2000L)+ db.saveLocation(latitude = 51.0, longitude = 12.0, accuracy = 15.0, timestamp = 1500L)++ val result = db.getRawMostRecentLocation()+ assertNotNull(result)+ assertEquals(53.0, result!!["latitude"] as Double, 0.001)+ assertEquals(14.0, result["longitude"] as Double, 0.001)+ assertEquals(2000L, result["timestamp"])+ }++ @Test+ fun `getRawMostRecentLocation returns null when empty`() {+ assertNull(db.getRawMostRecentLocation())+ }++ @Test+ fun `deleteLocations removes specified locations`() {+ val id1 = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val id2 = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 2000L)+ val id3 = db.saveLocation(latitude = 54.0, longitude = 15.0, timestamp = 3000L)++ db.deleteLocations(listOf(id1, id3))++ val remaining = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 100, 0)+ assertEquals(1, remaining.size)+ assertEquals(53.0, remaining[0]["latitude"] as Double, 0.001)+ }++ @Test+ fun `deleteLocations is no-op for empty list`() {+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.deleteLocations(emptyList())++ val remaining = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 100, 0)+ assertEquals(1, remaining.size)+ }++ // ========================================================================+ // Queue operations+ // ========================================================================++ @Test+ fun `addToQueue and getQueuedLocations round-trip`() {+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val queueId = db.addToQueue(locId, """{"lat":52.0}""")+ assertTrue(queueId > 0)++ val queued = db.getQueuedLocations(10)+ assertEquals(1, queued.size)+ assertEquals(queueId, queued[0].queueId)+ assertEquals(locId, queued[0].locationId)+ assertEquals("""{"lat":52.0}""", queued[0].payload)+ assertEquals(0, queued[0].retryCount)+ }++ @Test+ fun `getQueuedLocations respects limit`() {+ repeat(5) { i ->+ val locId = db.saveLocation(latitude = 52.0 + i, longitude = 13.0, timestamp = 1000L + i)+ db.addToQueue(locId, """{"lat":${52.0 + i}}""")+ }++ assertEquals(3, db.getQueuedLocations(3).size)+ assertEquals(5, db.getQueuedLocations(10).size)+ }++ @Test+ fun `getQueuedLocations returns oldest first`() {+ val loc1 = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val loc2 = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 2000L)+ db.addToQueue(loc1, """{"id":"first"}""")+ // Slight delay to ensure different created_at+ db.addToQueue(loc2, """{"id":"second"}""")++ val queued = db.getQueuedLocations(10)+ assertEquals("""{"id":"first"}""", queued[0].payload)+ assertEquals("""{"id":"second"}""", queued[1].payload)+ }++ @Test+ fun `removeFromQueueByLocationId deletes matching entries`() {+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.addToQueue(locId, """{"lat":52.0}""")++ val deleted = db.removeFromQueueByLocationId(locId)+ assertEquals(1, deleted)+ assertEquals(0, db.getQueuedCount())+ }++ @Test+ fun `removeBatchFromQueue deletes multiple entries`() {+ val ids = (1..5).map { i ->+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L + i)+ db.addToQueue(locId, """{"i":$i}""")+ }++ db.removeBatchFromQueue(ids.take(3))++ assertEquals(2, db.getQueuedCount())+ }++ @Test+ fun `removeBatchFromQueue is no-op for empty list`() {+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.addToQueue(locId, """{"lat":52.0}""")++ db.removeBatchFromQueue(emptyList())+ assertEquals(1, db.getQueuedCount())+ }++ @Test+ fun `incrementRetryCount updates count and error`() {+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val queueId = db.addToQueue(locId, """{"lat":52.0}""")++ db.incrementRetryCount(queueId, "Network error")++ val queued = db.getQueuedLocations(10)+ assertEquals(1, queued[0].retryCount)++ // Verify error text via raw query+ db.readableDatabase.rawQuery(+ "SELECT last_error FROM ${DatabaseHelper.TABLE_QUEUE} WHERE id = ?",+ arrayOf(queueId.toString())+ ).use { cursor ->+ cursor.moveToFirst()+ assertEquals("Network error", cursor.getString(0))+ }+ }++ @Test+ fun `incrementRetryCount accumulates across multiple calls`() {+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val queueId = db.addToQueue(locId, """{"lat":52.0}""")++ db.incrementRetryCount(queueId, "err1")+ db.incrementRetryCount(queueId, "err2")+ db.incrementRetryCount(queueId, "err3")++ val queued = db.getQueuedLocations(10)+ assertEquals(3, queued[0].retryCount)+ }++ @Test+ fun `getQueuedCount returns correct count`() {+ assertEquals(0, db.getQueuedCount())++ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.addToQueue(locId, """{"lat":52.0}""")+ db.addToQueue(locId, """{"lat":52.0}""")++ assertEquals(2, db.getQueuedCount())+ }++ // ========================================================================+ // Foreign key cascades+ // ========================================================================++ @Test+ fun `deleting location cascades to queue entries`() {+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.addToQueue(locId, """{"lat":52.0}""")+ db.addToQueue(locId, """{"lat":52.0,"v":2}""")+ assertEquals(2, db.getQueuedCount())++ // Delete the location — should cascade to queue+ db.deleteLocations(listOf(locId))++ assertEquals(0, db.getQueuedCount())+ }++ @Test+ fun `clearAllLocations removes both locations and queue entries`() {+ val loc1 = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val loc2 = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 2000L)+ db.addToQueue(loc1, """{"lat":52.0}""")+ db.addToQueue(loc2, """{"lat":53.0}""")++ db.clearAllLocations()++ assertEquals(0, db.getQueuedCount())+ assertNull(db.getRawMostRecentLocation())+ }++ @Test+ fun `clearQueue removes only queued locations not sent ones`() {+ val queued = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val sent = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 2000L)+ db.addToQueue(queued, """{"lat":52.0}""")++ db.clearQueue()++ // Queued location (and its queue entry) should be gone+ assertEquals(0, db.getQueuedCount())+ // Sent location should remain+ val recent = db.getRawMostRecentLocation()+ assertNotNull(recent)+ assertEquals(53.0, recent!!["latitude"] as Double, 0.001)+ }++ @Test+ fun `clearSentHistory removes only unqueued locations`() {+ val queued = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ val sent = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 2000L)+ db.addToQueue(queued, """{"lat":52.0}""")++ val deleted = db.clearSentHistory()+ assertEquals(1, deleted)++ // Queued location should remain+ assertEquals(1, db.getQueuedCount())+ val recent = db.getRawMostRecentLocation()+ assertEquals(52.0, recent!!["latitude"] as Double, 0.001)+ }++ // ========================================================================+ // Transaction handling+ // ========================================================================++ @Test+ fun `prepopulateSettings inserts all defaults in single transaction`() {+ val settings = db.getAllSettings()+ // Verify all expected defaults exist+ assertTrue(settings.containsKey("interval"))+ assertTrue(settings.containsKey("endpoint"))+ assertTrue(settings.containsKey("fieldMap"))+ assertTrue(settings.containsKey("tracking_enabled"))+ assertTrue(settings.containsKey("httpMethod"))+ assertTrue(settings.size >= 16)+ }++ @Test+ fun `saveSetting uses CONFLICT_REPLACE for upsert`() {+ db.saveSetting("tracking_enabled", "true")+ assertEquals("true", db.getSetting("tracking_enabled"))++ db.saveSetting("tracking_enabled", "false")+ assertEquals("false", db.getSetting("tracking_enabled"))+ }++ @Test+ fun `removeBatchFromQueue handles large batches correctly`() {+ val ids = (1..100).map { i ->+ val locId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L + i)+ db.addToQueue(locId, """{"i":$i}""")+ }++ db.removeBatchFromQueue(ids)+ assertEquals(0, db.getQueuedCount())+ }++ // ========================================================================+ // Settings operations+ // ========================================================================++ @Test+ fun `getSetting returns null for missing key`() {+ assertNull(db.getSetting("nonexistent_key"))+ }++ @Test+ fun `getSetting returns default value for missing key`() {+ assertEquals("fallback", db.getSetting("nonexistent_key", "fallback"))+ }++ @Test+ fun `getSetting trims whitespace from values`() {+ db.saveSetting("test_key", " hello ")+ assertEquals("hello", db.getSetting("test_key"))+ }++ @Test+ fun `getAllSettings returns complete map`() {+ db.saveSetting("custom1", "value1")+ db.saveSetting("custom2", "value2")++ val all = db.getAllSettings()+ assertEquals("value1", all["custom1"])+ assertEquals("value2", all["custom2"])+ // Plus prepopulated defaults+ assertTrue(all.size >= 18)+ }++ // ========================================================================+ // getTableData — pagination and type handling+ // ========================================================================++ @Test+ fun `getTableData returns paginated results`() {+ repeat(10) { i ->+ db.saveLocation(latitude = 52.0 + i, longitude = 13.0, timestamp = 1000L + i)+ }++ val page1 = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 3, 0)+ val page2 = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 3, 3)++ assertEquals(3, page1.size)+ assertEquals(3, page2.size)+ // Locations ordered by timestamp DESC — page 1 has newest+ assertNotEquals(page1[0]["timestamp"], page2[0]["timestamp"])+ }++ @Test+ fun `getTableData handles mixed column types`() {+ db.saveLocation(+ latitude = 52.52,+ longitude = 13.405,+ accuracy = 10.0,+ altitude = 34,+ timestamp = 1700000000L,+ endpoint = "https://example.com"+ )++ val data = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 1, 0)+ assertEquals(1, data.size)+ val row = data[0]+ // REAL columns+ assertTrue(row["latitude"] is Double)+ // INTEGER columns+ assertTrue(row["timestamp"] is Long)+ // TEXT columns+ assertTrue(row["endpoint"] is String)+ }++ @Test+ fun `getTableData rejects unknown table names`() {+ try {+ db.getTableData("evil_table; DROP TABLE locations", 10, 0)+ fail("Should throw IllegalArgumentException")+ } catch (e: IllegalArgumentException) {+ assertTrue(e.message!!.contains("Invalid table name"))+ }+ }++ // ========================================================================+ // getLocationsByDateRange+ // ========================================================================++ @Test+ fun `getLocationsByDateRange returns locations in ascending order`() {+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 2000L)+ db.saveLocation(latitude = 54.0, longitude = 15.0, timestamp = 3000L)++ val result = db.getLocationsByDateRange(1000L, 3000L)+ assertEquals(3, result.size)+ assertEquals(1000L, result[0]["timestamp"])+ assertEquals(2000L, result[1]["timestamp"])+ assertEquals(3000L, result[2]["timestamp"])+ }++ @Test+ fun `getLocationsByDateRange filters by range boundaries`() {+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 500L)+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 1000L)+ db.saveLocation(latitude = 54.0, longitude = 15.0, timestamp = 2000L)+ db.saveLocation(latitude = 55.0, longitude = 16.0, timestamp = 3000L)++ val result = db.getLocationsByDateRange(1000L, 2000L)+ assertEquals(2, result.size)+ assertEquals(1000L, result[0]["timestamp"])+ assertEquals(2000L, result[1]["timestamp"])+ }++ @Test+ fun `getLocationsByDateRange returns empty for no matches`() {+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)++ val result = db.getLocationsByDateRange(5000L, 6000L)+ assertTrue(result.isEmpty())+ }++ // ========================================================================+ // Stats and cleanup+ // ========================================================================++ @Test+ fun `getStats returns correct counts`() {+ val loc1 = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = System.currentTimeMillis() / 1000)+ val loc2 = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = System.currentTimeMillis() / 1000)+ db.addToQueue(loc1, """{"lat":52.0}""")++ val (queued, total, today) = db.getStats()+ assertEquals(1, queued)+ assertEquals(2, total)+ assertEquals(2, today)+ }++ @Test+ fun `getStats returns zeros for empty database`() {+ val (queued, total, today) = db.getStats()+ assertEquals(0, queued)+ assertEquals(0, total)+ assertEquals(0, today)+ }++ @Test+ fun `vacuum runs without error`() {+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.vacuum()+ // No exception = pass+ }++ // ========================================================================+ // WAL concurrent access patterns+ // ========================================================================++ @Test+ fun `read during open write transaction does not block`() {+ // Insert baseline data+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)++ // Start a write transaction, then read — should not throw or deadlock+ val rawDb = db.writableDatabase+ rawDb.beginTransaction()+ try {+ val values = ContentValues().apply {+ put("latitude", 53.0)+ put("longitude", 14.0)+ put("timestamp", 2000L)+ put("created_at", System.currentTimeMillis() / 1000)+ }+ rawDb.insert(DatabaseHelper.TABLE_LOCATIONS, null, values)++ // Read while write transaction is open — WAL allows this without blocking.+ // Note: Robolectric uses a single connection, so uncommitted data may be+ // visible here. True WAL isolation requires separate connections.+ val recent = db.getRawMostRecentLocation()+ assertNotNull(recent)++ rawDb.setTransactionSuccessful()+ } finally {+ rawDb.endTransaction()+ }++ // After commit, read sees new data+ val recent = db.getRawMostRecentLocation()+ assertEquals(53.0, recent!!["latitude"] as Double, 0.001)+ }++ @Test+ fun `write transaction rollback does not persist data`() {+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)++ val rawDb = db.writableDatabase+ rawDb.beginTransaction()+ try {+ val values = ContentValues().apply {+ put("latitude", 99.0)+ put("longitude", 99.0)+ put("timestamp", 9999L)+ put("created_at", System.currentTimeMillis() / 1000)+ }+ rawDb.insert(DatabaseHelper.TABLE_LOCATIONS, null, values)+ // Intentionally NOT calling setTransactionSuccessful()+ } finally {+ rawDb.endTransaction()+ }++ // Rolled-back row should not exist+ val data = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 100, 0)+ assertEquals(1, data.size)+ assertEquals(52.0, data[0]["latitude"] as Double, 0.001)+ }++ // ========================================================================+ // Helpers+ // ========================================================================++ private fun queryTableNames(): Set<String> {+ val tables = mutableSetOf<String>()+ db.readableDatabase.rawQuery(+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android_%'",+ null+ ).use { cursor ->+ while (cursor.moveToNext()) {+ tables.add(cursor.getString(0))+ }+ }+ return tables+ }++ private fun queryIndexNames(): Set<String> {+ val indexes = mutableSetOf<String>()+ db.readableDatabase.rawQuery(+ "SELECT name FROM sqlite_master WHERE type='index' AND name NOT LIKE 'sqlite_%'",+ null+ ).use { cursor ->+ while (cursor.moveToNext()) {+ indexes.add(cursor.getString(0))+ }+ }+ return indexes+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperTest.ktdeleted file mode 100644index dc362f82..00000000--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperTest.kt+++ /dev/null@@ -1,173 +0,0 @@-package com.Colota.data--import org.junit.Assert.*-import org.junit.Test--/**- * Tests for DatabaseHelper's pure logic and data class behavior.- * SQLite operations require an Android context (instrumented tests),- * so we test the data model, query construction, and helper logic here.- */-class DatabaseHelperTest {-- // --- QueuedLocation data class ----- @Test- fun `QueuedLocation stores all fields correctly`() {- val ql = QueuedLocation(queueId = 1, locationId = 100, payload = """{"lat":52.0}""", retryCount = 3)- assertEquals(1L, ql.queueId)- assertEquals(100L, ql.locationId)- assertEquals("""{"lat":52.0}""", ql.payload)- assertEquals(3, ql.retryCount)- }-- @Test- fun `QueuedLocation equality works`() {- val a = QueuedLocation(1, 100, """{"lat":52.0}""", 0)- val b = QueuedLocation(1, 100, """{"lat":52.0}""", 0)- assertEquals(a, b)- }-- @Test- fun `QueuedLocation inequality on different retryCount`() {- val a = QueuedLocation(1, 100, """{"lat":52.0}""", 0)- val b = QueuedLocation(1, 100, """{"lat":52.0}""", 1)- assertNotEquals(a, b)- }-- @Test- fun `QueuedLocation copy works`() {- val original = QueuedLocation(1, 100, """{"lat":52.0}""", 0)- val updated = original.copy(retryCount = 5)- assertEquals(5, updated.retryCount)- assertEquals(original.queueId, updated.queueId)- }-- // --- Table name constants ----- @Test- fun `table name constants are correct`() {- assertEquals("locations", DatabaseHelper.TABLE_LOCATIONS)- assertEquals("queue", DatabaseHelper.TABLE_QUEUE)- assertEquals("settings", DatabaseHelper.TABLE_SETTINGS)- assertEquals("geofences", DatabaseHelper.TABLE_GEOFENCES)- }-- // --- ALLOWED_TABLES validation logic ----- @Test- fun `allowed tables include all four tables`() {- val allowedField = DatabaseHelper::class.java.getDeclaredField("ALLOWED_TABLES")- allowedField.isAccessible = true- // It's an instance field, but we can check the constant set by reading from a mock- // Instead, verify the constants match what we expect- val expectedTables = setOf("locations", "queue", "settings", "geofences")- expectedTables.forEach { table ->- // Verify these match the declared constants- assertTrue(- "Table $table should be a valid table name",- table in setOf(- DatabaseHelper.TABLE_LOCATIONS,- DatabaseHelper.TABLE_QUEUE,- DatabaseHelper.TABLE_SETTINGS,- DatabaseHelper.TABLE_GEOFENCES- )- )- }- }-- // --- clearSentHistory SQL logic ----- @Test- fun `clearSentHistory query excludes queued location IDs`() {- // Verify the SQL pattern: "id NOT IN (SELECT location_id FROM queue)"- // This ensures sent (non-queued) locations are deleted, queued ones are kept- val expectedPattern = "id NOT IN (SELECT location_id FROM queue)"- // We can't execute SQL without a real DB, but we can verify the logic:- // A location in the queue should NOT be deleted- // A location NOT in the queue should be deleted- assertTrue("Query pattern documented for reference", expectedPattern.isNotEmpty())- }-- // --- deleteOlderThan cutoff calculation ----- @Test- fun `deleteOlderThan cutoff calculates correctly for 7 days`() {- val days = 7- val now = System.currentTimeMillis()- val cutoff = (now - days * 24 * 60 * 60 * 1000L) / 1000-- // Cutoff should be 7 days ago in Unix seconds- val expectedSecondsAgo = 7 * 24 * 60 * 60L- val actualSecondsAgo = (now / 1000) - cutoff-- assertEquals(expectedSecondsAgo.toDouble(), actualSecondsAgo.toDouble(), 1.0)- }-- @Test- fun `deleteOlderThan cutoff calculates correctly for 30 days`() {- val days = 30- val now = System.currentTimeMillis()- val cutoff = (now - days * 24 * 60 * 60 * 1000L) / 1000-- val expectedSecondsAgo = 30 * 24 * 60 * 60L- val actualSecondsAgo = (now / 1000) - cutoff-- assertEquals(expectedSecondsAgo.toDouble(), actualSecondsAgo.toDouble(), 1.0)- }-- @Test- fun `deleteOlderThan cutoff for 0 days is close to now`() {- val days = 0- val now = System.currentTimeMillis()- val cutoff = (now - days * 24 * 60 * 60 * 1000L) / 1000-- // Cutoff should be very close to current timestamp- assertEquals((now / 1000).toDouble(), cutoff.toDouble(), 1.0)- }-- // --- getTodayStartTimestamp logic ----- @Test- fun `today start timestamp is midnight in seconds`() {- val cal = java.util.Calendar.getInstance().apply {- set(java.util.Calendar.HOUR_OF_DAY, 0)- set(java.util.Calendar.MINUTE, 0)- set(java.util.Calendar.SECOND, 0)- set(java.util.Calendar.MILLISECOND, 0)- }- val todayStart = cal.timeInMillis / 1000-- // Should be a valid Unix timestamp (after year 2020)- assertTrue(todayStart > 1577836800) // 2020-01-01- // Should be at midnight (divisible by 86400 in UTC, but timezone shifts this)- // Just verify it's a reasonable value- assertTrue(todayStart < System.currentTimeMillis() / 1000)- }-- // --- removeBatchFromQueue placeholder generation ----- @Test- fun `batch placeholder generation creates correct SQL`() {- val queueIds = listOf(1L, 2L, 3L, 4L, 5L)- val placeholders = queueIds.joinToString(",") { "?" }- assertEquals("?,?,?,?,?", placeholders)-- val args = queueIds.map { it.toString() }.toTypedArray()- assertArrayEquals(arrayOf("1", "2", "3", "4", "5"), args)- }-- @Test- fun `batch placeholder generation handles single item`() {- val queueIds = listOf(42L)- val placeholders = queueIds.joinToString(",") { "?" }- assertEquals("?", placeholders)- }-- @Test- fun `batch placeholder generation handles empty list`() {- val queueIds = emptyList<Long>()- val placeholders = queueIds.joinToString(",") { "?" }- assertEquals("", placeholders)- }-}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.ktnew file mode 100644index 00000000..4e2b0236--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt@@ -0,0 +1,322 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.service++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.os.BatteryManager+import android.os.Handler+import androidx.car.app.connection.CarConnection+import androidx.lifecycle.LiveData+import androidx.lifecycle.Observer+import io.mockk.*+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test++/**+ * Tests for ConditionMonitor:+ * - readCurrentChargingState (battery status parsing)+ * - start() lifecycle (initial state, receiver registration, car connection)+ * - Charging BroadcastReceiver (power connected/disconnected events)+ * - Car connection lifecycle (start/stop, observer cleanup)+ * - stop() cleanup (unregister, null-safety, exception handling)+ */+class ConditionMonitorTest {++ private lateinit var mockContext: Context+ private lateinit var mockProfileManager: ProfileManager+ private lateinit var mockHandler: Handler+ private lateinit var monitor: ConditionMonitor++ @Before+ fun setUp() {+ mockContext = mockk(relaxed = true)+ mockProfileManager = mockk(relaxed = true)+ mockHandler = mockk(relaxed = true)++ // Execute handler.post() runnables synchronously+ every { mockHandler.post(any()) } answers {+ firstArg<Runnable>().run()+ true+ }++ monitor = createMonitor()+ }++ // ========================================================================+ // readCurrentChargingState+ // ========================================================================++ @Test+ fun `readCurrentChargingState returns true when charging`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_CHARGING)+ assertTrue(callReadCurrentChargingState())+ }++ @Test+ fun `readCurrentChargingState returns true when full`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_FULL)+ assertTrue(callReadCurrentChargingState())+ }++ @Test+ fun `readCurrentChargingState returns false when discharging`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ assertFalse(callReadCurrentChargingState())+ }++ @Test+ fun `readCurrentChargingState returns false when not charging`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_NOT_CHARGING)+ assertFalse(callReadCurrentChargingState())+ }++ @Test+ fun `readCurrentChargingState returns false when unknown`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_UNKNOWN)+ assertFalse(callReadCurrentChargingState())+ }++ @Test+ fun `readCurrentChargingState returns false when null intent`() {+ every { mockContext.registerReceiver(isNull(), any<IntentFilter>()) } returns null+ assertFalse(callReadCurrentChargingState())+ }++ // ========================================================================+ // start — initial state and registration+ // ========================================================================++ @Test+ fun `start notifies profileManager with initial charging state`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_CHARGING)+ monitor.start()+ verify { mockProfileManager.onChargingStateChanged(true) }+ }++ @Test+ fun `start notifies profileManager when initially not charging`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ monitor.start()+ verify { mockProfileManager.onChargingStateChanged(false) }+ }++ @Test+ fun `start registers charging broadcast receiver`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ monitor.start()+ verify { mockContext.registerReceiver(any(), any<IntentFilter>(), any<Int>()) }+ }++ @Test+ fun `start calls stop first to prevent duplicate registrations`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ val oldReceiver = mockk<BroadcastReceiver>()+ setField(monitor, "chargingReceiver", oldReceiver)++ monitor.start()++ verify { mockContext.unregisterReceiver(oldReceiver) }+ }++ @Test+ fun `start begins car connection monitoring`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ monitor.start()+ verify { monitor["startCarConnectionMonitor"]() }+ }++ // ========================================================================+ // Charging receiver — power events+ // ========================================================================++ @Test+ fun `charging receiver notifies profileManager on power connected`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ monitor.start()++ val receiver = getField(monitor, "chargingReceiver") as BroadcastReceiver+ val intent = mockk<Intent> { every { action } returns Intent.ACTION_POWER_CONNECTED }+ receiver.onReceive(mockContext, intent)++ verify { mockProfileManager.onChargingStateChanged(true) }+ }++ @Test+ fun `charging receiver notifies profileManager on power disconnected`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_CHARGING)+ monitor.start()++ val receiver = getField(monitor, "chargingReceiver") as BroadcastReceiver+ val intent = mockk<Intent> { every { action } returns Intent.ACTION_POWER_DISCONNECTED }+ receiver.onReceive(mockContext, intent)++ verify { mockProfileManager.onChargingStateChanged(false) }+ }++ @Test+ fun `charging receiver ignores unrelated actions`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ monitor.start()++ // start() called onChargingStateChanged(false) once+ verify(exactly = 1) { mockProfileManager.onChargingStateChanged(any()) }++ val receiver = getField(monitor, "chargingReceiver") as BroadcastReceiver+ val intent = mockk<Intent> { every { action } returns "com.example.UNRELATED" }+ receiver.onReceive(mockContext, intent)++ // Still only 1 call — the unrelated action was ignored+ verify(exactly = 1) { mockProfileManager.onChargingStateChanged(any()) }+ }++ // ========================================================================+ // stop — cleanup+ // ========================================================================++ @Test+ fun `stop unregisters charging receiver`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ monitor.start()++ val receiver = getField(monitor, "chargingReceiver") as BroadcastReceiver+ monitor.stop()++ verify { mockContext.unregisterReceiver(receiver) }+ assertNull(getField(monitor, "chargingReceiver"))+ }++ @Test+ fun `stop handles already unregistered receiver gracefully`() {+ val receiver = mockk<BroadcastReceiver>()+ setField(monitor, "chargingReceiver", receiver)+ every { mockContext.unregisterReceiver(receiver) } throws IllegalArgumentException("not registered")++ // Should not throw+ monitor.stop()+ assertNull(getField(monitor, "chargingReceiver"))+ }++ @Test+ fun `stop when nothing registered does not crash`() {+ // All fields null from Unsafe allocation — no receivers, no car connection+ monitor.stop()+ }++ @Test+ fun `stop calls stopCarConnectionMonitor`() {+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)+ monitor.start()+ monitor.stop()+ verify { monitor["stopCarConnectionMonitor"]() }+ }++ // ========================================================================+ // Car connection — observer cleanup via stopCarConnectionMonitor+ // ========================================================================++ @Test+ fun `stopCarConnectionMonitor removes observer and clears fields`() {+ val mockLiveData = mockk<LiveData<Int>>(relaxed = true)+ val mockObserver = mockk<Observer<Int>>()+ val mockCarConn = mockk<CarConnection> {+ every { type } returns mockLiveData+ }+ setField(monitor, "carConnection", mockCarConn)+ setField(monitor, "carConnectionObserver", mockObserver)++ // Allow real stopCarConnectionMonitor for this test+ every { monitor["stopCarConnectionMonitor"]() } answers { callOriginal() }++ monitor.stop()++ verify { mockLiveData.removeObserver(mockObserver) }+ assertNull(getField(monitor, "carConnection"))+ assertNull(getField(monitor, "carConnectionObserver"))+ }++ @Test+ fun `stopCarConnectionMonitor skips when observer is null`() {+ val mockCarConn = mockk<CarConnection>(relaxed = true)+ setField(monitor, "carConnection", mockCarConn)+ // carConnectionObserver is null++ every { monitor["stopCarConnectionMonitor"]() } answers { callOriginal() }++ monitor.stop()++ // removeObserver should not be called because observer was null+ verify(exactly = 0) { mockCarConn.type }+ }++ @Test+ fun `stopCarConnectionMonitor skips when connection is null`() {+ val mockObserver = mockk<Observer<Int>>()+ setField(monitor, "carConnectionObserver", mockObserver)+ // carConnection is null++ every { monitor["stopCarConnectionMonitor"]() } answers { callOriginal() }++ monitor.stop()++ // Should complete without crash — observer null check returns early+ // (observer is non-null but connection is null → returns early after observer check)+ }++ // ========================================================================+ // Helpers+ // ========================================================================++ private fun createMonitor(): ConditionMonitor {+ val unsafeClass = Class.forName("sun.misc.Unsafe")+ val unsafeField = unsafeClass.getDeclaredField("theUnsafe")+ unsafeField.isAccessible = true+ val unsafe = unsafeField.get(null)+ val raw = unsafeClass.getMethod("allocateInstance", Class::class.java)+ .invoke(unsafe, ConditionMonitor::class.java) as ConditionMonitor++ val spy = spyk(raw, recordPrivateCalls = true)+ setField(spy, "context", mockContext)+ setField(spy, "profileManager", mockProfileManager)+ setField(spy, "mainHandler", mockHandler)++ // Stub car connection methods — CarConnection cannot be constructed in unit tests+ // because CarConnectionTypeLiveData's static initializer uses Uri.Builder which+ // returns null in the Android test stub environment.+ every { spy["startCarConnectionMonitor"]() } returns Unit+ every { spy["stopCarConnectionMonitor"]() } returns Unit++ return spy+ }++ private fun mockBatteryStatus(status: Int) {+ val batteryIntent = mockk<Intent> {+ every { getIntExtra(BatteryManager.EXTRA_STATUS, -1) } returns status+ }+ every { mockContext.registerReceiver(isNull(), any<IntentFilter>()) } returns batteryIntent+ }++ private fun callReadCurrentChargingState(): Boolean {+ val method = ConditionMonitor::class.java.getDeclaredMethod("readCurrentChargingState")+ method.isAccessible = true+ return method.invoke(monitor) as Boolean+ }++ private fun setField(obj: Any, name: String, value: Any?) {+ val field = ConditionMonitor::class.java.getDeclaredField(name)+ field.isAccessible = true+ field.set(obj, value)+ }++ private fun getField(obj: Any, name: String): Any? {+ val field = ConditionMonitor::class.java.getDeclaredField(name)+ field.isAccessible = true+ return field.get(obj)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationBootReceiverTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationBootReceiverTest.ktnew file mode 100644index 00000000..25cc3362--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationBootReceiverTest.kt@@ -0,0 +1,273 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.service++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.Colota.data.DatabaseHelper+import io.mockk.*+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.runTest+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import kotlin.coroutines.Continuation++/**+ * Tests for LocationBootReceiver:+ * - onReceive action filtering (null, unknown, valid boot actions)+ * - handleBootCompleted logic (tracking disabled/enabled, DB not ready, SecurityException)+ * - waitForDatabaseReady retry logic+ */+@OptIn(ExperimentalCoroutinesApi::class)+class LocationBootReceiverTest {++ private lateinit var receiver: LocationBootReceiver+ private lateinit var mockContext: Context+ private lateinit var mockDbHelper: DatabaseHelper++ @Before+ fun setUp() {+ receiver = LocationBootReceiver()+ mockContext = mockk(relaxed = true)+ mockDbHelper = mockk(relaxed = true)++ mockkObject(DatabaseHelper.Companion)+ every { DatabaseHelper.getInstance(any()) } returns mockDbHelper+ }++ @After+ fun tearDown() {+ unmockkObject(DatabaseHelper.Companion)+ }++ // ========================================================================+ // onReceive — action filtering+ // ========================================================================++ @Test+ fun `onReceive ignores null action`() {+ val spy = spyk(receiver)+ val intent = mockk<Intent> { every { action } returns null }+ spy.onReceive(mockContext, intent)+ verify(exactly = 0) { spy.goAsync() }+ }++ @Test+ fun `onReceive ignores unknown action`() {+ val spy = spyk(receiver)+ val intent = mockk<Intent> { every { action } returns "com.example.RANDOM_ACTION" }+ spy.onReceive(mockContext, intent)+ verify(exactly = 0) { spy.goAsync() }+ }++ @Test+ fun `onReceive calls goAsync for ACTION_BOOT_COMPLETED`() {+ val spy = spyk(receiver)+ val pendingResult = mockk<BroadcastReceiver.PendingResult>(relaxed = true)+ every { spy.goAsync() } returns pendingResult+ every { mockContext.applicationContext } returns mockContext+ mockDbReadyAndDisabled()++ val intent = mockk<Intent> { every { action } returns Intent.ACTION_BOOT_COMPLETED }+ spy.onReceive(mockContext, intent)+ Thread.sleep(500)++ verify { spy.goAsync() }+ verify { pendingResult.finish() }+ }++ @Test+ fun `onReceive calls goAsync for QUICKBOOT_POWERON`() {+ val spy = spyk(receiver)+ val pendingResult = mockk<BroadcastReceiver.PendingResult>(relaxed = true)+ every { spy.goAsync() } returns pendingResult+ every { mockContext.applicationContext } returns mockContext+ mockDbReadyAndDisabled()++ val intent = mockk<Intent> {+ every { action } returns "android.intent.action.QUICKBOOT_POWERON"+ }+ spy.onReceive(mockContext, intent)+ Thread.sleep(500)++ verify { spy.goAsync() }+ verify { pendingResult.finish() }+ }++ @Test+ fun `onReceive always calls finish even on error`() {+ val spy = spyk(receiver)+ val pendingResult = mockk<BroadcastReceiver.PendingResult>(relaxed = true)+ every { spy.goAsync() } returns pendingResult+ every { mockContext.applicationContext } returns mockContext+ every { DatabaseHelper.getInstance(any()) } throws RuntimeException("DB init failed")++ val intent = mockk<Intent> { every { action } returns Intent.ACTION_BOOT_COMPLETED }+ spy.onReceive(mockContext, intent)+ Thread.sleep(500)++ verify { pendingResult.finish() }+ }++ // ========================================================================+ // handleBootCompleted+ // ========================================================================++ @Test+ fun `handleBootCompleted skips when tracking disabled`() = runTest {+ mockDbReadyAndDisabled()++ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)++ verify(exactly = 0) { mockContext.startService(any()) }+ verify(exactly = 0) { mockContext.startForegroundService(any()) }+ }++ @Test+ fun `handleBootCompleted starts service when tracking enabled`() = runTest {+ mockDbReadyAndEnabled()++ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)++ // Build.VERSION.SDK_INT is 0 in unit tests → startService (not startForegroundService)+ verify { mockContext.startService(any()) }+ }++ @Test+ fun `handleBootCompleted loads config from database`() = runTest {+ mockDbReadyAndEnabled()++ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)++ verify { mockDbHelper.getAllSettings() }+ }++ @Test+ fun `handleBootCompleted handles SecurityException gracefully`() = runTest {+ mockDbReadyAndEnabled()+ every { mockContext.startService(any()) } throws SecurityException("Permission denied")++ // Should not throw+ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)+ }++ @Test+ fun `handleBootCompleted skips when database not ready`() = runTest {+ every { mockDbHelper.getSetting("tracking_enabled") } throws RuntimeException("DB locked")++ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)++ verify(exactly = 0) { mockContext.startService(any()) }+ verify(exactly = 0) { mockContext.startForegroundService(any()) }+ }++ @Test+ fun `handleBootCompleted does not start service when tracking setting is missing`() = runTest {+ every { mockDbHelper.getSetting("tracking_enabled") } returns null+ every { mockDbHelper.getSetting("tracking_enabled", "false") } returns "false"++ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)++ verify(exactly = 0) { mockContext.startService(any()) }+ }++ // ========================================================================+ // waitForDatabaseReady+ // ========================================================================++ @Test+ fun `waitForDatabaseReady returns true when db accessible`() = runTest {+ every { mockDbHelper.getSetting("tracking_enabled") } returns "true"++ assertTrue(callWaitForDatabaseReady(mockDbHelper))+ }++ @Test+ fun `waitForDatabaseReady returns false after max retries`() = runTest {+ every { mockDbHelper.getSetting("tracking_enabled") } throws RuntimeException("DB locked")++ assertFalse(callWaitForDatabaseReady(mockDbHelper))+ // Should have been called 3 times (MAX_DB_RETRIES)+ verify(exactly = 3) { mockDbHelper.getSetting("tracking_enabled") }+ }++ @Test+ fun `waitForDatabaseReady retries on failure then succeeds`() = runTest {+ var callCount = 0+ every { mockDbHelper.getSetting("tracking_enabled") } answers {+ callCount+++ if (callCount < 3) throw RuntimeException("DB locked")+ "true"+ }++ assertTrue(callWaitForDatabaseReady(mockDbHelper))+ assertEquals(3, callCount)+ }++ @Test+ fun `waitForDatabaseReady succeeds on first attempt without retrying`() = runTest {+ every { mockDbHelper.getSetting("tracking_enabled") } returns "false"++ assertTrue(callWaitForDatabaseReady(mockDbHelper))+ verify(exactly = 1) { mockDbHelper.getSetting("tracking_enabled") }+ }++ // ========================================================================+ // Helpers+ // ========================================================================++ private fun mockDbReadyAndDisabled() {+ every { mockDbHelper.getSetting("tracking_enabled") } returns "false"+ every { mockDbHelper.getSetting("tracking_enabled", "false") } returns "false"+ }++ private fun mockDbReadyAndEnabled() {+ every { mockDbHelper.getSetting("tracking_enabled") } returns "true"+ every { mockDbHelper.getSetting("tracking_enabled", "false") } returns "true"+ every { mockDbHelper.getAllSettings() } returns mapOf(+ "tracking_enabled" to "true",+ "endpoint" to "https://example.com",+ "interval" to "5000"+ )+ }++ /**+ * Invokes the private suspend function handleBootCompleted via Java reflection.+ * Uses a blocking continuation since the function completes synchronously+ * when mocks don't introduce real delays.+ */+ @Suppress("UNCHECKED_CAST")+ private suspend fun callHandleBootCompleted(context: Context, action: String) {+ val method = LocationBootReceiver::class.java.getDeclaredMethod(+ "handleBootCompleted",+ Context::class.java,+ String::class.java,+ Continuation::class.java+ )+ method.isAccessible = true++ kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<Unit> { cont ->+ method.invoke(receiver, context, action, cont)+ }+ }++ @Suppress("UNCHECKED_CAST")+ private suspend fun callWaitForDatabaseReady(dbHelper: DatabaseHelper): Boolean {+ val method = LocationBootReceiver::class.java.getDeclaredMethod(+ "waitForDatabaseReady",+ DatabaseHelper::class.java,+ Continuation::class.java+ )+ method.isAccessible = true++ return kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<Boolean> { cont ->+ method.invoke(receiver, dbHelper, cont)+ }+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.ktindex d49ba5bf..736d7554 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt@@ -1,144 +1,915 @@package com.Colota.service+import android.app.NotificationManager+import android.location.Location+import com.Colota.bridge.LocationServiceModule+import com.Colota.data.DatabaseHelper+import com.Colota.data.GeofenceHelper+import com.Colota.location.LocationProvider+import com.Colota.location.LocationUpdateCallback+import com.Colota.sync.PayloadBuilder+import com.Colota.sync.SyncManager+import com.Colota.util.DeviceInfoHelper+import com.Colota.util.SecureStorageHelper+import io.mockk.*+import kotlinx.coroutines.*+import kotlinx.coroutines.test.*+import org.json.JSONObject+import org.junit.Afterimport org.junit.Assert.*+import org.junit.Beforeimport org.junit.Test/**- * Tests for LocationForegroundService's pure logic:- * - Battery critical shutdown conditions during tracking- * - Accuracy filter decisions- * - Zone transition state machine+ * Tests for LocationForegroundService logic using mock-injected dependencies.*- * Notification logic tests are in NotificationHelperTest.- * The actual Android Service lifecycle and LocationProvider interactions- * are not tested here (require instrumented tests).+ * Covers:+ * - handleLocationUpdate full pipeline (accuracy filter, zone check, DB save, sync, notification)+ * - Lightweight action handlers (zone recheck, force exit, profile recheck)+ * - enterPauseZone / exitPauseZone state transitions+ * - applyProfileConfig dynamic switching+ * - onDestroy cleanup*/+@OptIn(ExperimentalCoroutinesApi::class)class LocationForegroundServiceTest {- // --- Battery critical during tracking (handleLocationUpdate logic) ---+ private lateinit var locationProvider: LocationProvider+ private lateinit var dbHelper: DatabaseHelper+ private lateinit var geofenceHelper: GeofenceHelper+ private lateinit var syncManager: SyncManager+ private lateinit var payloadBuilder: PayloadBuilder+ private lateinit var deviceInfoHelper: DeviceInfoHelper+ private lateinit var notificationHelper: NotificationHelper+ private lateinit var profileManager: ProfileManager+ private lateinit var conditionMonitor: ConditionMonitor+ private lateinit var secureStorage: SecureStorageHelper+ private lateinit var androidNotificationManager: NotificationManager++ private lateinit var testDispatcher: TestDispatcher+ private lateinit var testScope: TestScope+ private lateinit var service: LocationForegroundService++ @Before+ fun setUp() {+ locationProvider = mockk(relaxed = true)+ dbHelper = mockk(relaxed = true)+ geofenceHelper = mockk(relaxed = true)+ syncManager = mockk(relaxed = true)+ payloadBuilder = mockk(relaxed = true)+ deviceInfoHelper = mockk(relaxed = true)+ notificationHelper = mockk(relaxed = true)+ profileManager = mockk(relaxed = true)+ conditionMonitor = mockk(relaxed = true)+ secureStorage = mockk(relaxed = true)+ androidNotificationManager = mockk(relaxed = true)++ testDispatcher = UnconfinedTestDispatcher()+ Dispatchers.setMain(testDispatcher)+ testScope = TestScope(testDispatcher)++ every { deviceInfoHelper.getCachedBatteryStatus() } returns Pair(80, 2)+ every { deviceInfoHelper.isBatteryCritical(any()) } returns false+ every { deviceInfoHelper.isBatteryCritical() } returns false+ every { geofenceHelper.getPauseZone(any()) } returns null+ every { payloadBuilder.buildPayload(any(), any(), any(), any(), any(), any()) } returns JSONObject()+ every { syncManager.getCachedQueuedCount() } returns 0+ every { syncManager.lastSuccessfulSyncTime } returns 0L+ every { profileManager.getActiveProfileName() } returns null+ every { secureStorage.getAuthHeaders() } returns emptyMap()++ mockkObject(LocationServiceModule)+ every { LocationServiceModule.sendLocationEvent(any(), any(), any()) } returns true+ every { LocationServiceModule.sendPauseZoneEvent(any(), any()) } returns true+ every { LocationServiceModule.sendTrackingStoppedEvent(any()) } returns true+ every { LocationServiceModule.sendProfileSwitchEvent(any(), any()) } returns true++ service = spyk(LocationForegroundService(), recordPrivateCalls = true)+ every { service.stopForeground(any<Int>()) } returns Unit+ @Suppress("DEPRECATION")+ every { service.stopForeground(any<Boolean>()) } returns Unit+ every { service.stopSelf() } returns Unit+ injectDependencies()+ }++ @After+ fun tearDown() {+ testScope.cancel()+ Dispatchers.resetMain()+ unmockkObject(LocationServiceModule)+ }++ private fun injectDependencies() {+ setField("locationProvider", locationProvider)+ setField("dbHelper", dbHelper)+ setField("geofenceHelper", geofenceHelper)+ setField("syncManager", syncManager)+ setField("payloadBuilder", payloadBuilder)+ setField("deviceInfoHelper", deviceInfoHelper)+ setField("notificationHelper", notificationHelper)+ setField("profileManager", profileManager)+ setField("conditionMonitor", conditionMonitor)+ setField("secureStorage", secureStorage)+ setField("notificationManager", androidNotificationManager)+ setField("serviceScope", testScope as CoroutineScope)+ setField("config", ServiceConfig(+ endpoint = "https://example.com",+ interval = 5000L,+ filterInaccurateLocations = true,+ accuracyThreshold = 50.0f,+ syncIntervalSeconds = 0+ ))+ }++ private fun setField(name: String, value: Any?) {+ val field = LocationForegroundService::class.java.getDeclaredField(name)+ field.isAccessible = true+ field.set(service, value)+ }++ @Suppress("UNCHECKED_CAST")+ private fun <T> getField(name: String): T {+ val field = LocationForegroundService::class.java.getDeclaredField(name)+ field.isAccessible = true+ return field.get(service) as T+ }++ private fun mockLocation(+ lat: Double = 52.52,+ lon: Double = 13.405,+ accuracy: Float = 10f,+ altitude: Double = 50.0,+ hasAltitude: Boolean = true,+ speed: Float = 5f,+ bearing: Float = 90f,+ hasBearing: Boolean = true,+ time: Long = System.currentTimeMillis()+ ): Location = mockk {+ every { latitude } returns lat+ every { longitude } returns lon+ every { [email protected] } returns accuracy+ every { [email protected] } returns altitude+ every { hasAltitude() } returns hasAltitude+ every { [email protected] } returns speed+ every { [email protected] } returns bearing+ every { hasBearing() } returns hasBearing+ every { [email protected] } returns time+ }++ // =========================================================================+ // handleLocationUpdate — full pipeline+ // =========================================================================++ @Test+ fun `handleLocationUpdate saves location to DB and queues sync`() = testScope.runTest {+ val location = mockLocation()+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 42L++ invokeHandleLocationUpdate(location)++ verify { dbHelper.saveLocation(+ latitude = 52.52,+ longitude = 13.405,+ accuracy = 10.0,+ altitude = 50,+ speed = 5.0,+ bearing = 90.0,+ battery = 80,+ battery_status = 2,+ timestamp = any(),+ endpoint = "https://example.com"+ ) }+ coVerify { syncManager.queueAndSend(42L, any()) }+ }++ @Test+ fun `handleLocationUpdate sends location event to JS bridge`() = testScope.runTest {+ val location = mockLocation()+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { LocationServiceModule.sendLocationEvent(location, 80, 2) }+ }++ @Test+ fun `handleLocationUpdate builds payload with field map and custom fields`() = testScope.runTest {+ val location = mockLocation()+ val fieldMap = mapOf("lat" to "latitude", "lon" to "longitude")+ val customFields = mapOf("device" to "test")+ setField("fieldMap", fieldMap)+ setField("customFields", customFields)+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { payloadBuilder.buildPayload(location, 80, 2, fieldMap, any(), customFields) }+ }++ @Test+ fun `handleLocationUpdate filters inaccurate location above threshold`() = testScope.runTest {+ val location = mockLocation(accuracy = 75f)++ invokeHandleLocationUpdate(location)++ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ coVerify(exactly = 0) { syncManager.queueAndSend(any(), any()) }+ }++ @Test+ fun `handleLocationUpdate passes location at exactly threshold`() = testScope.runTest {+ val location = mockLocation(accuracy = 50f)+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }++ @Test+ fun `handleLocationUpdate skips filter when filterInaccurateLocations disabled`() = testScope.runTest {+ setField("config", ServiceConfig(+ endpoint = "https://example.com",+ filterInaccurateLocations = false,+ accuracyThreshold = 50f+ ))+ val location = mockLocation(accuracy = 500f)+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }++ @Test+ fun `handleLocationUpdate feeds location to profile manager after accuracy filter`() = testScope.runTest {+ val location = mockLocation(accuracy = 10f)+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { profileManager.onLocationUpdate(location) }+ }++ @Test+ fun `handleLocationUpdate does not feed filtered location to profile manager`() = testScope.runTest {+ val location = mockLocation(accuracy = 75f)++ invokeHandleLocationUpdate(location)++ verify(exactly = 0) { profileManager.onLocationUpdate(any()) }+ }++ @Test+ fun `handleLocationUpdate updates lastKnownLocation`() = testScope.runTest {+ val location = mockLocation()+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ assertEquals(location, getField<Location?>("lastKnownLocation"))+ }++ @Test+ fun `handleLocationUpdate handles null altitude`() = testScope.runTest {+ val location = mockLocation(hasAltitude = false)+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { dbHelper.saveLocation(+ any(), any(), any(),+ altitude = null,+ any(), any(), any(), any(), any(), any()+ ) }+ }++ @Test+ fun `handleLocationUpdate stops service when battery critical during tracking`() = testScope.runTest {+ every { deviceInfoHelper.isBatteryCritical() } returns true+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }++ @Test+ fun `handleLocationUpdate enters pause zone when location is in geofence`() = testScope.runTest {+ every { geofenceHelper.getPauseZone(any()) } returns "Home"+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ assertTrue(getField("insidePauseZone"))+ assertEquals("Home", getField<String?>("currentZoneName"))+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }++ @Test+ fun `handleLocationUpdate skips saving when already inside pause zone`() = testScope.runTest {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ every { geofenceHelper.getPauseZone(any()) } returns "Home"+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }@Test- fun `battery 4 percent discharging triggers stop during tracking`() {- assertTrue(shouldStopForBattery(battery = 4, batteryStatus = 1))+ fun `handleLocationUpdate exits pause zone and resumes saving`() = testScope.runTest {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ every { geofenceHelper.getPauseZone(any()) } returns null+ val location = mockLocation()+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ assertFalse(getField("insidePauseZone"))+ assertNull(getField<String?>("currentZoneName"))+ verify { LocationServiceModule.sendPauseZoneEvent(false, "Home") }+ verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ coVerify { syncManager.queueAndSend(1L, any()) }+ }++ @Test+ fun `handleLocationUpdate converts timestamp to seconds`() = testScope.runTest {+ val timeMs = 1700000000000L+ val location = mockLocation(time = timeMs)+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(),+ timestamp = 1700000000L,+ any()+ ) }}@Test- fun `battery 1 percent discharging triggers stop during tracking`() {- assertTrue(shouldStopForBattery(battery = 1, batteryStatus = 1))+ fun `handleLocationUpdate uses empty field map when none configured`() = testScope.runTest {+ setField("fieldMap", null)+ val location = mockLocation()+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L++ invokeHandleLocationUpdate(location)++ verify { payloadBuilder.buildPayload(any(), any(), any(), emptyMap(), any(), any()) }}+ // =========================================================================+ // Lightweight action handlers+ // =========================================================================+@Test- fun `battery 5 percent discharging does not trigger stop during tracking`() {- // handleLocationUpdate checks battery in 1..4, so 5 is not in range- assertFalse(shouldStopForBattery(battery = 5, batteryStatus = 1))+ fun `ACTION_FORCE_EXIT_ZONE rechecks zone after forced exit`() {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Office")+ val location = mockLocation()+ setField("lastKnownLocation", location)+ every { geofenceHelper.getPauseZone(location) } returns null++ invokeExitPauseZone()+ invokeRecheckZoneWithLocation(location)++ assertFalse(getField("insidePauseZone"))}@Test- fun `battery 0 percent discharging does not trigger stop during tracking`() {- // 0 is not in 1..4 range- assertFalse(shouldStopForBattery(battery = 0, batteryStatus = 1))+ fun `ACTION_FORCE_EXIT_ZONE re-enters if still in zone after recheck`() {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Office")+ val location = mockLocation()+ setField("lastKnownLocation", location)+ every { geofenceHelper.getPauseZone(location) } returns "Office"++ invokeExitPauseZone()+ invokeRecheckZoneWithLocation(location)++ assertTrue(getField("insidePauseZone"))+ assertEquals("Office", getField<String?>("currentZoneName"))}@Test- fun `battery 3 percent charging does not trigger stop during tracking`() {- assertFalse(shouldStopForBattery(battery = 3, batteryStatus = 2))+ fun `ACTION_RECHECK_ZONE with fresh location rechecks immediately`() {+ val freshLocation = mockLocation(time = System.currentTimeMillis())+ setField("lastKnownLocation", freshLocation)+ every { geofenceHelper.getPauseZone(freshLocation) } returns "Park"++ invokeHandleZoneRecheckAction()++ verify { geofenceHelper.invalidateCache() }+ assertTrue(getField("insidePauseZone"))+ assertEquals("Park", getField<String?>("currentZoneName"))}@Test- fun `battery 2 percent full does not trigger stop during tracking`() {- assertFalse(shouldStopForBattery(battery = 2, batteryStatus = 3))+ fun `ACTION_RECHECK_ZONE with stale location requests from provider`() {+ val staleLocation = mockLocation(time = System.currentTimeMillis() - 120_000)+ setField("lastKnownLocation", staleLocation)++ invokeHandleZoneRecheckAction()++ verify { geofenceHelper.invalidateCache() }+ verify { locationProvider.getLastLocation(any(), any()) }}- // --- Accuracy filter logic ---+ @Test+ fun `ACTION_RECHECK_ZONE with no cached location requests from provider`() {+ setField("lastKnownLocation", null)++ invokeHandleZoneRecheckAction()++ verify { locationProvider.getLastLocation(any(), any()) }+ }@Test- fun `location above accuracy threshold is filtered`() {- val filterEnabled = true- val threshold = 50.0f- val locationAccuracy = 75.0f+ fun `ACTION_RECHECK_ZONE exits zone when provider returns no location`() {+ setField("lastKnownLocation", null)+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")- val shouldFilter = filterEnabled && locationAccuracy > threshold- assertTrue(shouldFilter)+ every { locationProvider.getLastLocation(any(), any()) } answers {+ val onSuccess = firstArg<(Location?) -> Unit>()+ onSuccess(null)+ }++ invokeHandleZoneRecheckAction()++ assertFalse(getField("insidePauseZone"))}@Test- fun `location below accuracy threshold passes`() {- val filterEnabled = true- val threshold = 50.0f- val locationAccuracy = 25.0f+ fun `ACTION_RECHECK_ZONE exits zone on provider failure`() {+ setField("lastKnownLocation", null)+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")++ every { locationProvider.getLastLocation(any(), any()) } answers {+ val onFailure = secondArg<(Exception) -> Unit>()+ onFailure(SecurityException("Permission denied"))+ }++ invokeHandleZoneRecheckAction()- val shouldFilter = filterEnabled && locationAccuracy > threshold- assertFalse(shouldFilter)+ assertFalse(getField("insidePauseZone"))}@Test- fun `location at exactly accuracy threshold passes`() {- val filterEnabled = true- val threshold = 50.0f- val locationAccuracy = 50.0f+ fun `ACTION_RECHECK_ZONE provider success updates lastKnownLocation`() {+ setField("lastKnownLocation", null)+ val freshLocation = mockLocation(lat = 48.0, lon = 11.0)+ every { geofenceHelper.getPauseZone(freshLocation) } returns null- val shouldFilter = filterEnabled && locationAccuracy > threshold- assertFalse(shouldFilter)+ every { locationProvider.getLastLocation(any(), any()) } answers {+ val onSuccess = firstArg<(Location?) -> Unit>()+ onSuccess(freshLocation)+ }++ invokeHandleZoneRecheckAction()++ assertEquals(freshLocation, getField<Location?>("lastKnownLocation"))}+ // =========================================================================+ // enterPauseZone / exitPauseZone state transitions+ // =========================================================================+@Test- fun `accuracy filter disabled allows any accuracy`() {- val filterEnabled = false- val threshold = 50.0f- val locationAccuracy = 500.0f+ fun `enterPauseZone sets state and sends event`() {+ val location = mockLocation()+ setField("lastKnownLocation", location)++ invokeEnterPauseZone("Home")- val shouldFilter = filterEnabled && locationAccuracy > threshold- assertFalse(shouldFilter)+ assertTrue(getField("insidePauseZone"))+ assertEquals("Home", getField<String?>("currentZoneName"))+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }}- // --- Zone transition state machine ---+ @Test+ fun `enterPauseZone updates notification with paused status`() {+ val location = mockLocation(lat = 52.0, lon = 13.0)+ setField("lastKnownLocation", location)++ invokeEnterPauseZone("Office")++ verify { notificationHelper.update(+ lat = 52.0,+ lon = 13.0,+ isPaused = true,+ zoneName = "Office",+ queuedCount = any(),+ lastSyncTime = any(),+ activeProfileName = any(),+ forceUpdate = true+ ) }+ }@Test- fun `entering zone when not already in zone triggers enter`() {- val zoneName = "Home"- val insidePauseZone = false+ fun `enterPauseZone handles null lastKnownLocation`() {+ setField("lastKnownLocation", null)- val shouldEnter = zoneName != null && !insidePauseZone- assertTrue(shouldEnter)+ invokeEnterPauseZone("Home")++ verify { notificationHelper.update(+ lat = null,+ lon = null,+ isPaused = true,+ zoneName = "Home",+ queuedCount = any(),+ lastSyncTime = any(),+ activeProfileName = any(),+ forceUpdate = true+ ) }}@Test- fun `exiting zone when inside zone triggers exit`() {- val zoneName: String? = null- val insidePauseZone = true+ fun `exitPauseZone clears state and sends event`() {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")++ invokeExitPauseZone()- val shouldExit = zoneName == null && insidePauseZone- assertTrue(shouldExit)+ assertFalse(getField("insidePauseZone"))+ assertNull(getField<String?>("currentZoneName"))+ verify { LocationServiceModule.sendPauseZoneEvent(false, "Home") }}@Test- fun `staying in same zone does not trigger enter or exit`() {- val zoneName = "Home"- val insidePauseZone = true- val currentZoneName = "Home"+ fun `exitPauseZone updates notification without paused status`() {+ val location = mockLocation(lat = 52.0, lon = 13.0)+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("lastKnownLocation", location)- val shouldEnter = zoneName != null && !insidePauseZone- val shouldExit = zoneName == null && insidePauseZone- val sameZone = zoneName != null && insidePauseZone && zoneName == currentZoneName+ invokeExitPauseZone()- assertFalse(shouldEnter)- assertFalse(shouldExit)- assertTrue(sameZone)+ verify { notificationHelper.update(+ lat = 52.0,+ lon = 13.0,+ isPaused = false,+ zoneName = null,+ queuedCount = any(),+ lastSyncTime = any(),+ activeProfileName = any(),+ forceUpdate = true+ ) }}@Test- fun `changing zones triggers re-enter`() {- val zoneName = "Work"- val insidePauseZone = true- val currentZoneName = "Home"+ fun `zone transition enter then exit restores clean state`() {+ invokeEnterPauseZone("Home")+ assertTrue(getField("insidePauseZone"))- val shouldReEnter = zoneName != null && (!insidePauseZone || zoneName != currentZoneName)- assertTrue(shouldReEnter)+ invokeExitPauseZone()+ assertFalse(getField("insidePauseZone"))+ assertNull(getField<String?>("currentZoneName"))}- // --- Helper methods replicating logic under test ---+ @Test+ fun `zone change from one zone to another updates name`() {+ invokeEnterPauseZone("Home")+ assertEquals("Home", getField<String?>("currentZoneName"))++ invokeEnterPauseZone("Office")+ assertEquals("Office", getField<String?>("currentZoneName"))+ assertTrue(getField("insidePauseZone"))+ }++ // =========================================================================+ // recheckZoneWithLocation — zone recheck state machine+ // =========================================================================++ @Test+ fun `recheckZone enters zone when not currently in zone`() {+ setField("insidePauseZone", false)+ val location = mockLocation()+ every { geofenceHelper.getPauseZone(location) } returns "Park"++ invokeRecheckZoneWithLocation(location)++ assertTrue(getField("insidePauseZone"))+ assertEquals("Park", getField<String?>("currentZoneName"))+ }++ @Test+ fun `recheckZone exits zone when location leaves geofence`() {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ val location = mockLocation()+ every { geofenceHelper.getPauseZone(location) } returns null++ invokeRecheckZoneWithLocation(location)++ assertFalse(getField("insidePauseZone"))+ }++ @Test+ fun `recheckZone changes zone when moving between zones`() {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ val location = mockLocation()+ every { geofenceHelper.getPauseZone(location) } returns "Office"++ invokeRecheckZoneWithLocation(location)++ assertTrue(getField("insidePauseZone"))+ assertEquals("Office", getField<String?>("currentZoneName"))+ }++ @Test+ fun `recheckZone updates notification when staying in same zone`() {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ val location = mockLocation(lat = 52.0, lon = 13.0)+ every { geofenceHelper.getPauseZone(location) } returns "Home"++ invokeRecheckZoneWithLocation(location)++ verify { notificationHelper.update(+ lat = 52.0,+ lon = 13.0,+ isPaused = true,+ zoneName = "Home",+ queuedCount = any(),+ lastSyncTime = any(),+ activeProfileName = any(),+ forceUpdate = true+ ) }+ }++ @Test+ fun `recheckZone updates notification when not in any zone`() {+ setField("insidePauseZone", false)+ val location = mockLocation(lat = 52.0, lon = 13.0)+ every { geofenceHelper.getPauseZone(location) } returns null++ invokeRecheckZoneWithLocation(location)++ verify { notificationHelper.update(+ lat = 52.0,+ lon = 13.0,+ isPaused = false,+ zoneName = null,+ queuedCount = any(),+ lastSyncTime = any(),+ activeProfileName = any(),+ forceUpdate = true+ ) }+ }++ // =========================================================================+ // applyProfileConfig — dynamic config switching+ // =========================================================================++ @Test+ fun `applyProfileConfig updates service config`() {+ invokeApplyProfileConfig(interval = 2000L, distance = 10f, syncInterval = 60)++ val config = getField<ServiceConfig>("config")+ assertEquals(2000L, config.interval)+ assertEquals(10f, config.minUpdateDistance)+ assertEquals(60, config.syncIntervalSeconds)+ }++ @Test+ fun `applyProfileConfig preserves non-profile config fields`() {+ setField("config", ServiceConfig(+ endpoint = "https://my-server.com",+ interval = 5000L,+ minUpdateDistance = 0f,+ accuracyThreshold = 100f,+ filterInaccurateLocations = true,+ maxRetries = 10,+ httpMethod = "GET"+ ))++ invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)++ val config = getField<ServiceConfig>("config")+ assertEquals("https://my-server.com", config.endpoint)+ assertEquals(100f, config.accuracyThreshold)+ assertTrue(config.filterInaccurateLocations)+ assertEquals(10, config.maxRetries)+ assertEquals("GET", config.httpMethod)+ }++ @Test+ fun `applyProfileConfig updates sync manager with new config`() {+ every { secureStorage.getAuthHeaders() } returns mapOf("Authorization" to "Bearer token")+ setField("config", ServiceConfig(+ endpoint = "https://example.com",+ retryIntervalSeconds = 60,+ maxRetries = 3,+ isOfflineMode = true,+ isWifiOnlySync = true,+ httpMethod = "GET"+ ))++ invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)++ verify { syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 30,+ retryIntervalSeconds = 60,+ maxRetries = 3,+ isOfflineMode = true,+ isWifiOnlySync = true,+ authHeaders = mapOf("Authorization" to "Bearer token"),+ httpMethod = "GET"+ ) }+ }++ @Test+ fun `applyProfileConfig restarts location updates`() = testScope.runTest {+ val oldCallback = mockk<LocationUpdateCallback>(relaxed = true)+ setField("locationUpdateCallback", oldCallback)++ mockkStatic(android.os.Looper::class)+ every { android.os.Looper.getMainLooper() } returns mockk(relaxed = true)++ invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)++ verify { locationProvider.removeLocationUpdates(oldCallback) }+ verify { locationProvider.requestLocationUpdates(2000L, 5f, any(), any()) }++ unmockkStatic(android.os.Looper::class)+ }++ @Test+ fun `applyProfileConfig forces notification update`() {+ invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)++ verify { notificationHelper.update(any(), any(), any(), any(), any(), any(), any(), forceUpdate = true) }+ }++ // =========================================================================+ // onDestroy — cleanup+ // =========================================================================++ @Test+ fun `onDestroy stops condition monitor`() {+ invokeOnDestroy()++ verify { conditionMonitor.stop() }+ }++ @Test+ fun `onDestroy removes location updates`() {+ val callback = mockk<LocationUpdateCallback>(relaxed = true)+ setField("locationUpdateCallback", callback)++ invokeOnDestroy()++ verify { locationProvider.removeLocationUpdates(callback) }+ }++ @Test+ fun `onDestroy stops periodic sync`() {+ invokeOnDestroy()++ verify { syncManager.stopPeriodicSync() }+ }++ @Test+ fun `onDestroy cancels service scope`() {+ val scope = getField<CoroutineScope?>("serviceScope")+ assertNotNull(scope)++ invokeOnDestroy()++ assertNull(getField<CoroutineScope?>("serviceScope"))+ }++ @Test+ fun `onDestroy handles null location callback gracefully`() {+ setField("locationUpdateCallback", null)++ invokeOnDestroy()++ verify(exactly = 0) { locationProvider.removeLocationUpdates(any()) }+ }++ @Test+ fun `onDestroy order is monitor then location then sync then scope`() {+ val order = mutableListOf<String>()++ every { conditionMonitor.stop() } answers { order.add("conditionMonitor.stop") }+ every { locationProvider.removeLocationUpdates(any()) } answers { order.add("locationProvider.remove") }+ every { syncManager.stopPeriodicSync() } answers { order.add("syncManager.stop") }++ val callback = mockk<LocationUpdateCallback>(relaxed = true)+ setField("locationUpdateCallback", callback)++ invokeOnDestroy()++ assertEquals("conditionMonitor.stop", order[0])+ assertEquals("locationProvider.remove", order[1])+ assertEquals("syncManager.stop", order[2])+ }++ // =========================================================================+ // stopForegroundServiceWithReason — battery critical path+ // =========================================================================++ @Test+ fun `stopForBattery clears active profile event`() = testScope.runTest {+ every { profileManager.getActiveProfileName() } returns "Charging"+ every { deviceInfoHelper.isBatteryCritical() } returns true+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ verify { LocationServiceModule.sendProfileSwitchEvent(null, null) }+ }++ @Test+ fun `stopForBattery sends tracking stopped event`() = testScope.runTest {+ every { deviceInfoHelper.isBatteryCritical() } returns true+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ verify { LocationServiceModule.sendTrackingStoppedEvent("Battery critical") }+ }++ @Test+ fun `stopForBattery saves tracking_enabled false`() = testScope.runTest {+ every { deviceInfoHelper.isBatteryCritical() } returns true+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ verify { dbHelper.saveSetting("tracking_enabled", "false") }+ }++ @Test+ fun `stopForBattery does not send profile event when no active profile`() = testScope.runTest {+ every { profileManager.getActiveProfileName() } returns null+ every { deviceInfoHelper.isBatteryCritical() } returns true+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ verify(exactly = 0) { LocationServiceModule.sendProfileSwitchEvent(any(), any()) }+ }++ // =========================================================================+ // Helpers — invoke private methods via reflection+ // =========================================================================++ private fun invokeHandleLocationUpdate(location: Location) {+ val method = LocationForegroundService::class.java.getDeclaredMethod(+ "handleLocationUpdate", Location::class.java+ )+ method.isAccessible = true+ method.invoke(service, location)+ }++ private fun invokeEnterPauseZone(zoneName: String) {+ val method = LocationForegroundService::class.java.getDeclaredMethod(+ "enterPauseZone", String::class.java+ )+ method.isAccessible = true+ method.invoke(service, zoneName)+ }++ private fun invokeExitPauseZone() {+ val method = LocationForegroundService::class.java.getDeclaredMethod("exitPauseZone")+ method.isAccessible = true+ method.invoke(service)+ }++ private fun invokeRecheckZoneWithLocation(location: Location) {+ val method = LocationForegroundService::class.java.getDeclaredMethod(+ "recheckZoneWithLocation", Location::class.java+ )+ method.isAccessible = true+ method.invoke(service, location)+ }++ private fun invokeApplyProfileConfig(interval: Long, distance: Float, syncInterval: Int) {+ val method = LocationForegroundService::class.java.getDeclaredMethod(+ "applyProfileConfig", Long::class.java, Float::class.java, Int::class.java+ )+ method.isAccessible = true+ method.invoke(service, interval, distance, syncInterval)+ }++ private fun invokeOnDestroy() {+ val method = LocationForegroundService::class.java.getDeclaredMethod("onDestroy")+ method.isAccessible = true+ method.invoke(service)+ }- private fun shouldStopForBattery(battery: Int, batteryStatus: Int): Boolean {- return battery in 1..4 && batteryStatus == 1+ private fun invokeHandleZoneRecheckAction() {+ val method = LocationForegroundService::class.java+ .getDeclaredMethod("handleZoneRecheckAction")+ method.isAccessible = true+ method.invoke(service)}-}\ No newline at end of file+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.ktindex b4cf4b6f..b3d4a965 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt@@ -1,117 +1,120 @@package com.Colota.service+import io.mockk.*import org.junit.Assert.*+import org.junit.Beforeimport org.junit.Test/**- * Tests for NotificationHelper's pure logic:+ * Tests for NotificationHelper using a real instance with mocked Android deps:* - Status text generation (all branches)* - Time-since-last-sync formatting* - Throttle decisions* - Movement filter decisions- * - Deduplication- * - Initial status text+ * - Title building+ * - Deduplication via update()*/class NotificationHelperTest {+ private lateinit var helper: NotificationHelper++ @Before+ fun setUp() {+ helper = spyk(+ NotificationHelper(mockk(relaxed = true), mockk(relaxed = true))+ )+ // Stub buildTrackingNotification to avoid PendingIntent.getActivity()+ every { helper.buildTrackingNotification(any(), any()) } returns mockk()+ }+// --- formatTimeSinceSync ---@Testfun `time since sync shows Never when no sync happened`() {- assertEquals("Never", formatTimeSinceSync(lastSyncTime = 0L, now = 1000L))+ assertEquals("Never", helper.formatTimeSinceSync(lastSyncTime = 0L, now = 1000L))}@Testfun `time since sync shows Just now for less than 1 min`() {val now = 100000L- val lastSync = now - 30000L- assertEquals("Just now", formatTimeSinceSync(lastSync, now))+ assertEquals("Just now", helper.formatTimeSinceSync(now - 30000L, now))}@Testfun `time since sync shows 1 min ago`() {val now = 100000L- val lastSync = now - 60000L- assertEquals("1 min ago", formatTimeSinceSync(lastSync, now))+ assertEquals("1 min ago", helper.formatTimeSinceSync(now - 60000L, now))}@Testfun `time since sync shows N min ago for less than 1 hour`() {val now = 100000L- val lastSync = now - 1500000L- assertEquals("25 min ago", formatTimeSinceSync(lastSync, now))+ assertEquals("25 min ago", helper.formatTimeSinceSync(now - 1500000L, now))}@Testfun `time since sync shows 1h ago for 60-119 minutes`() {val now = 10000000L- val lastSync = now - 3600000L- assertEquals("1h ago", formatTimeSinceSync(lastSync, now))+ assertEquals("1h ago", helper.formatTimeSinceSync(now - 3600000L, now))}@Testfun `time since sync shows Nh ago for 120+ minutes`() {val now = 10000000L- val lastSync = now - 7200000L- assertEquals("2 h ago", formatTimeSinceSync(lastSync, now))+ assertEquals("2 h ago", helper.formatTimeSinceSync(now - 7200000L, now))}@Testfun `time since sync shows 5h ago for 300 minutes`() {val now = 100000000L- val lastSync = now - 18000000L- assertEquals("5 h ago", formatTimeSinceSync(lastSync, now))+ assertEquals("5 h ago", helper.formatTimeSinceSync(now - 18000000L, now))}// --- buildStatusText ---@Testfun `status text shows Paused with zone name`() {- val text = buildStatusText(true, "Home", 52.0, 13.0, 0, 0L)- assertEquals("Paused: Home", text)+ assertEquals("Paused: Home", helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L))}@Testfun `status text shows Paused Unknown when zone name is null`() {- val text = buildStatusText(true, null, 52.0, 13.0, 0, 0L)- assertEquals("Paused: Unknown", text)+ assertEquals("Paused: Unknown", helper.buildStatusText(true, null, 52.0, 13.0, 0, 0L))}@Testfun `status text shows coordinates when tracking normally`() {- val text = buildStatusText(false, null, 52.51630, 13.37770, 0, 0L)- assertEquals("52.51630, 13.37770", text)+ assertEquals("52.51630, 13.37770", helper.buildStatusText(false, null, 52.51630, 13.37770, 0, 0L))}@Testfun `status text shows Synced when queue empty and has synced`() {- val text = buildStatusText(false, null, 52.0, 13.0, 0, System.currentTimeMillis())+ val text = helper.buildStatusText(false, null, 52.0, 13.0, 0, System.currentTimeMillis())assertEquals("52.00000, 13.00000 (Synced)", text)}@Testfun `status text shows queued count when never synced`() {- val text = buildStatusText(false, null, 52.0, 13.0, 15, 0L)- assertEquals("52.00000, 13.00000 (Queued: 15)", text)+ assertEquals("52.00000, 13.00000 (Queued: 15)", helper.buildStatusText(false, null, 52.0, 13.0, 15, 0L))}@Testfun `status text shows queued count and last sync when both present`() {val now = System.currentTimeMillis()- val text = buildStatusText(false, null, 52.0, 13.0, 7, now - 30000L)- assertEquals("52.00000, 13.00000 (Queued: 7 · Just now)", text)+ assertEquals(+ "52.00000, 13.00000 (Queued: 7 \u00b7 Just now)",+ helper.buildStatusText(false, null, 52.0, 13.0, 7, now - 30000L)+ )}@Testfun `status text shows Searching GPS when no coordinates`() {- val text = buildStatusText(false, null, null, null, 0, 0L)- assertEquals("Searching GPS...", text)+ assertEquals("Searching GPS...", helper.buildStatusText(false, null, null, null, 0, 0L))}@Testfun `status text uses locale-safe coordinate formatting`() {- // Verifies no comma-separated decimals on non-US locales- val text = buildStatusText(false, null, -33.86882, 151.20930, 0, 0L)+ val text = helper.buildStatusText(false, null, -33.86882, 151.20930, 0, 0L)assertTrue(text.contains("-33.86882"))assertTrue(text.contains("151.20930"))assertFalse(text.contains(",209")) // Would appear with German locale@@ -119,133 +122,103 @@ class NotificationHelperTest {@Testfun `paused takes priority over coordinates`() {- val text = buildStatusText(true, "Office", 52.0, 13.0, 5, System.currentTimeMillis())- assertEquals("Paused: Office", text)+ assertEquals(+ "Paused: Office",+ helper.buildStatusText(true, "Office", 52.0, 13.0, 5, System.currentTimeMillis())+ )}// --- shouldThrottle ---@Testfun `throttle suppresses within 10s`() {- assertTrue(shouldThrottle(lastUpdateTime = 1000L, now = 5000L))+ setField("lastUpdateTime", 1000L)+ assertTrue(helper.shouldThrottle(now = 5000L))}@Testfun `throttle allows after 10s`() {- assertFalse(shouldThrottle(lastUpdateTime = 1000L, now = 12000L))+ setField("lastUpdateTime", 1000L)+ assertFalse(helper.shouldThrottle(now = 12000L))}@Testfun `throttle allows at exactly 10s`() {- assertFalse(shouldThrottle(lastUpdateTime = 1000L, now = 11000L))+ setField("lastUpdateTime", 1000L)+ assertFalse(helper.shouldThrottle(now = 11000L))}// --- shouldFilterByMovement ---@Testfun `movement less than 2m is filtered`() {- assertTrue(shouldFilterByMovement(1.5f))+ assertTrue(helper.shouldFilterByMovement(1.5f))}@Testfun `movement of exactly 2m is not filtered`() {- assertFalse(shouldFilterByMovement(2.0f))+ assertFalse(helper.shouldFilterByMovement(2.0f))}@Testfun `movement greater than 2m is not filtered`() {- assertFalse(shouldFilterByMovement(5.0f))+ assertFalse(helper.shouldFilterByMovement(5.0f))}// --- buildTitle ---@Testfun `title shows Colota Tracking when no profile active`() {- assertEquals("Colota Tracking", buildTitle(null))+ assertEquals("Colota Tracking", helper.buildTitle(null))}@Testfun `title includes profile name when active`() {- assertEquals("Colota \u00b7 Charging", buildTitle("Charging"))+ assertEquals("Colota \u00b7 Charging", helper.buildTitle("Charging"))}@Testfun `title includes custom profile name`() {- assertEquals("Colota \u00b7 Fast Driving", buildTitle("Fast Driving"))+ assertEquals("Colota \u00b7 Fast Driving", helper.buildTitle("Fast Driving"))}- // --- Deduplication ---+ // --- Deduplication (via update()) ---@Test- fun `same cache key is deduplicated`() {- assertFalse(shouldUpdate("52.52000, 13.40500-3", "52.52000, 13.40500-3"))+ fun `same state is deduplicated on second update`() {+ assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))+ assertFalse(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))}@Test- fun `different cache key is not deduplicated`() {- assertTrue(shouldUpdate("52.52000, 13.40500-3", "52.52100, 13.40600-3"))+ fun `different coordinates trigger update`() {+ helper.update(lat = 52.52, lon = 13.405, forceUpdate = true)+ assertTrue(helper.update(lat = 52.521, lon = 13.406, forceUpdate = true))}@Testfun `first update always proceeds`() {- assertTrue(shouldUpdate(null, "52.52000, 13.40500-0"))+ assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))}@Test- fun `queue count change triggers update even if text same`() {- assertTrue(shouldUpdate("52.00000, 13.00000 (Synced)-0", "52.00000, 13.00000 (Synced)-5"))+ fun `queue count change triggers update`() {+ val now = System.currentTimeMillis()+ helper.update(lat = 52.0, lon = 13.0, queuedCount = 0, lastSyncTime = now, forceUpdate = true)+ assertTrue(helper.update(lat = 52.0, lon = 13.0, queuedCount = 5, lastSyncTime = now, forceUpdate = true))}@Testfun `profile name change triggers update`() {- assertTrue(shouldUpdate("52.00000, 13.00000-0-null", "52.00000, 13.00000-0-Charging"))- }-- // --- Helper methods that mirror NotificationHelper logic ----- private fun formatTimeSinceSync(lastSyncTime: Long, now: Long): String {- if (lastSyncTime == 0L) return "Never"- val elapsedMs = now - lastSyncTime- val elapsedMinutes = (elapsedMs / 60000).toInt()- return when {- elapsedMinutes < 1 -> "Just now"- elapsedMinutes == 1 -> "1 min ago"- elapsedMinutes < 60 -> "$elapsedMinutes min ago"- elapsedMinutes < 120 -> "1h ago"- else -> "${elapsedMinutes / 60} h ago"- }- }-- private fun buildStatusText(- isPaused: Boolean, zoneName: String?,- lat: Double?, lon: Double?,- queuedCount: Int, lastSyncTime: Long- ): String = when {- isPaused -> "Paused: ${zoneName ?: "Unknown"}"- lat != null && lon != null -> {- val coords = String.format(java.util.Locale.US, "%.5f, %.5f", lat, lon)- if (queuedCount > 0 && lastSyncTime > 0) {- "$coords (Queued: $queuedCount · ${formatTimeSinceSync(lastSyncTime, System.currentTimeMillis())})"- } else if (queuedCount > 0) {- "$coords (Queued: $queuedCount)"- } else if (lastSyncTime > 0) {- "$coords (Synced)"- } else {- coords- }- }- else -> "Searching GPS..."- }-- private fun shouldThrottle(lastUpdateTime: Long, now: Long): Boolean =- (now - lastUpdateTime) < NotificationHelper.THROTTLE_MS-- private fun shouldFilterByMovement(distance: Float): Boolean =- distance < NotificationHelper.MIN_MOVEMENT_METERS-- private fun shouldUpdate(lastText: String?, newText: String): Boolean =- newText != lastText-- private fun buildTitle(activeProfileName: String?): String =- if (activeProfileName != null) "Colota \u00b7 $activeProfileName" else "Colota Tracking"-}\ No newline at end of file+ helper.update(lat = 52.0, lon = 13.0, forceUpdate = true)+ assertTrue(helper.update(lat = 52.0, lon = 13.0, activeProfileName = "Charging", forceUpdate = true))+ }++ // --- Reflection helper ---++ private fun setField(name: String, value: Any?) {+ val field = NotificationHelper::class.java.getDeclaredField(name)+ field.isAccessible = true+ field.set(helper, value)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.ktindex 7ba41b4f..358a254b 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt@@ -1,5 +1,6 @@package com.Colota.sync+import com.Colota.bridge.LocationServiceModuleimport com.Colota.data.DatabaseHelperimport com.Colota.data.QueuedLocationimport io.mockk.*@@ -10,6 +11,7 @@ import org.junit.Afterimport org.junit.Assert.*import org.junit.Beforeimport org.junit.Test+import kotlin.coroutines.Continuation@OptIn(ExperimentalCoroutinesApi::class)class SyncManagerTest {@@ -381,4 +383,374 @@ class SyncManagerTest {val second = syncManager.getCachedQueuedCount()assertEquals(20, second)}++ // ========================================================================+ // Exponential backoff (30s → 60s → 5min → 15min)+ // ========================================================================++ @Test+ fun `applyBackoffDelay waits 30s after 1 failure`() = scope.runTest {+ setField("consecutiveFailures", 1)+ val start = currentTime+ callApplyBackoffDelay()+ assertEquals(30_000L, currentTime - start)+ }++ @Test+ fun `applyBackoffDelay waits 60s after 2 failures`() = scope.runTest {+ setField("consecutiveFailures", 2)+ val start = currentTime+ callApplyBackoffDelay()+ assertEquals(60_000L, currentTime - start)+ }++ @Test+ fun `applyBackoffDelay waits 5min after 3 failures`() = scope.runTest {+ setField("consecutiveFailures", 3)+ val start = currentTime+ callApplyBackoffDelay()+ assertEquals(300_000L, currentTime - start)+ }++ @Test+ fun `applyBackoffDelay waits 15min after 4 or more failures`() = scope.runTest {+ setField("consecutiveFailures", 10)+ val start = currentTime+ callApplyBackoffDelay()+ assertEquals(900_000L, currentTime - start)+ }++ // ========================================================================+ // Batch processing limits and concurrent chunk sending+ // ========================================================================++ @Test+ fun `syncQueue stops processing after 10 batches`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ // Always return items — loop should still stop at batch 10+ val item = QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)+ every { dbHelper.getQueuedLocations(50) } returns listOf(item)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true++ syncManager.manualFlush()++ verify(exactly = 10) { dbHelper.getQueuedLocations(50) }+ }++ @Test+ fun `syncQueue sends all items across chunked groups`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ // 25 items → 3 chunks (10 + 10 + 5)+ val items = (1L..25L).map { QueuedLocation(it, it + 100, """{"lat":52.0}""", 0) }+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(items, emptyList())+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true++ syncManager.manualFlush()++ coVerify(exactly = 25) { networkManager.sendToEndpoint(any(), any(), any(), any()) }+ // 3 chunks → 3 removeBatchFromQueue calls+ verify(exactly = 3) { dbHelper.removeBatchFromQueue(any()) }+ }++ @Test+ fun `syncQueue deletes locations of permanently failed items`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ maxRetries = 3,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ val exceeded = QueuedLocation(1L, 100L, """{"lat":52.0}""", 3)+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(listOf(exceeded), emptyList())++ syncManager.manualFlush()++ verify { dbHelper.deleteLocations(listOf(100L)) }+ }++ // ========================================================================+ // Consecutive failure tracking (3+ failures → error event)+ // ========================================================================++ @Test+ fun `periodic sync increments consecutiveFailures on each failure`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ coEvery { networkManager.isNetworkAvailable() } returns true+ every { dbHelper.getQueuedCount() } returns 5+ // getQueuedLocations returns empty → performSyncAndCheckSuccess sees+ // countBefore=5, countAfter=5 → failure+ every { dbHelper.getQueuedLocations(50) } returns emptyList()++ syncManager.startPeriodicSync()++ // Advance past 2 full iterations:+ // iter 1: delay(1s) + sync + backoff(30s) = 31s+ // iter 2: delay(1s) + sync + backoff(60s) = 61s+ // Total to complete 2 iterations: ~92s+ advanceTimeBy(92_500)++ assertEquals(2, getField("consecutiveFailures"))+ syncManager.stopPeriodicSync()+ }++ @Test+ fun `periodic sync sends error event after 3 consecutive failures`() = scope.runTest {+ mockkObject(LocationServiceModule.Companion)+ every { LocationServiceModule.sendSyncErrorEvent(any(), any()) } returns true++ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ coEvery { networkManager.isNetworkAvailable() } returns true+ every { dbHelper.getQueuedCount() } returns 5+ every { dbHelper.getQueuedLocations(50) } returns emptyList()++ syncManager.startPeriodicSync()++ // Advance past 3 full iterations:+ // iter 1: delay(1s) + sync + backoff(30s) = 31s+ // iter 2: delay(1s) + sync + backoff(60s) = 61s+ // iter 3: delay(1s) + sync (error event fires here) + backoff(300s)+ // Need to reach iter 3's sync: 31 + 61 + 1 = 93s+ advanceTimeBy(93_500)++ verify(atLeast = 1) {+ LocationServiceModule.sendSyncErrorEvent(match { it.contains("3 consecutive") }, 5)+ }+ syncManager.stopPeriodicSync()+ unmockkObject(LocationServiceModule.Companion)+ }++ @Test+ fun `periodic sync does not send error event before 3 failures`() = scope.runTest {+ mockkObject(LocationServiceModule.Companion)+ every { LocationServiceModule.sendSyncErrorEvent(any(), any()) } returns true++ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ coEvery { networkManager.isNetworkAvailable() } returns true+ every { dbHelper.getQueuedCount() } returns 5+ every { dbHelper.getQueuedLocations(50) } returns emptyList()++ syncManager.startPeriodicSync()++ // Only advance through 2 iterations (before 3rd sync)+ advanceTimeBy(92_500)++ verify(exactly = 0) { LocationServiceModule.sendSyncErrorEvent(any(), any()) }+ syncManager.stopPeriodicSync()+ unmockkObject(LocationServiceModule.Companion)+ }++ @Test+ fun `periodic sync resets consecutiveFailures on success`() = scope.runTest {+ setField("consecutiveFailures", 5)++ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ coEvery { networkManager.isNetworkAvailable() } returns true+ // Simulate successful sync: queue count drops to 0 after processing+ var queuedCount = 3+ every { dbHelper.getQueuedCount() } answers { queuedCount }+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(+ listOf(QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)),+ emptyList()+ )+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ every { dbHelper.removeBatchFromQueue(any()) } answers { queuedCount = 0 }++ syncManager.startPeriodicSync()+ advanceTimeBy(2_000)++ assertEquals(0, getField("consecutiveFailures"))+ syncManager.stopPeriodicSync()+ }++ // ========================================================================+ // Periodic sync mode (job scheduling, lifecycle)+ // ========================================================================++ @Test+ fun `startPeriodicSync triggers sync at configured interval`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 60,+ retryIntervalSeconds = 30,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ coEvery { networkManager.isNetworkAvailable() } returns true+ var queuedCount = 3+ every { dbHelper.getQueuedCount() } answers { queuedCount }+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(+ listOf(QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)),+ emptyList()+ )+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ every { dbHelper.removeBatchFromQueue(any()) } answers { queuedCount = 0 }++ syncManager.startPeriodicSync()++ // Before interval elapses — no sync yet+ advanceTimeBy(30_000)+ coVerify(exactly = 0) { networkManager.sendToEndpoint(any(), any(), any(), any()) }++ // After interval elapses — sync happens+ advanceTimeBy(31_000)+ coVerify(atLeast = 1) { networkManager.sendToEndpoint(any(), any(), any(), any()) }+ syncManager.stopPeriodicSync()+ }++ @Test+ fun `startPeriodicSync skips sync when offline`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ maxRetries = 5,+ isOfflineMode = true,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ every { dbHelper.getQueuedCount() } returns 5++ syncManager.startPeriodicSync()+ advanceTimeBy(5_000)++ coVerify(exactly = 0) { networkManager.sendToEndpoint(any(), any(), any(), any()) }+ syncManager.stopPeriodicSync()+ }++ @Test+ fun `startPeriodicSync skips sync when no network`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ coEvery { networkManager.isNetworkAvailable() } returns false+ every { dbHelper.getQueuedCount() } returns 5++ syncManager.startPeriodicSync()+ advanceTimeBy(5_000)++ coVerify(exactly = 0) { networkManager.sendToEndpoint(any(), any(), any(), any()) }+ syncManager.stopPeriodicSync()+ }++ @Test+ fun `stopPeriodicSync prevents further syncs after cancellation`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ maxRetries = 5,+ isOfflineMode = false,+ isWifiOnlySync = false,+ authHeaders = emptyMap()+ )++ coEvery { networkManager.isNetworkAvailable() } returns true+ every { dbHelper.getQueuedCount() } returns 5+ every { dbHelper.getQueuedLocations(50) } returns emptyList()++ syncManager.startPeriodicSync()+ syncManager.stopPeriodicSync()++ advanceTimeBy(10_000)++ // No sync should have been attempted after cancellation+ verify(exactly = 0) { dbHelper.getQueuedLocations(any()) }+ }++ // ========================================================================+ // Helpers+ // ========================================================================++ @Suppress("UNCHECKED_CAST")+ private suspend fun callApplyBackoffDelay() {+ val method = SyncManager::class.java.getDeclaredMethod(+ "applyBackoffDelay",+ Continuation::class.java+ )+ method.isAccessible = true+ kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<Unit> { cont ->+ method.invoke(syncManager, cont)+ }+ }++ private fun setField(name: String, value: Any?) {+ val field = SyncManager::class.java.getDeclaredField(name)+ field.isAccessible = true+ field.set(syncManager, value)+ }++ private fun getField(name: String): Any? {+ val field = SyncManager::class.java.getDeclaredField(name)+ field.isAccessible = true+ return field.get(syncManager)+ }}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/DeviceInfoHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/DeviceInfoHelperTest.ktindex 2c28b90c..14df7ded 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/util/DeviceInfoHelperTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/DeviceInfoHelperTest.kt@@ -1,182 +1,206 @@package com.Colota.util+import android.content.Context+import android.content.Intent+import android.os.BatteryManager+import io.mockk.*import org.junit.Assert.*+import org.junit.Beforeimport org.junit.Test/**- * Tests for DeviceInfoHelper's pure logic methods.- * Battery status parsing and critical threshold checks are tested- * by exercising the logic patterns directly rather than through the- * Android-dependent methods.+ * Tests for DeviceInfoHelper using a real instance:+ * - isBatteryCritical (via spyk + stubbed getCachedBatteryStatus)+ * - getBatteryStatusString (via spyk + stubbed getCachedBatteryStatus)+ * - getBatteryStatus (via mocked battery intent)*/class DeviceInfoHelperTest {- // --- isBatteryCritical logic ---+ private lateinit var context: Context+ private lateinit var helper: DeviceInfoHelper++ @Before+ fun setUp() {+ context = mockk(relaxed = true)+ helper = spyk(DeviceInfoHelper(context))+ }++ // --- isBatteryCritical ---@Testfun `battery at 4 percent discharging is critical`() {- assertTrue(isBatteryCriticalLogic(level = 4, status = 1, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(4, 1)+ assertTrue(helper.isBatteryCritical(5))}@Testfun `battery at 5 percent discharging is not critical`() {- // < threshold, so 5 is NOT < 5- assertFalse(isBatteryCriticalLogic(level = 5, status = 1, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(5, 1)+ assertFalse(helper.isBatteryCritical(5))}@Testfun `battery at 1 percent discharging is critical`() {- assertTrue(isBatteryCriticalLogic(level = 1, status = 1, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(1, 1)+ assertTrue(helper.isBatteryCritical(5))}@Testfun `battery at 0 percent discharging is critical`() {- assertTrue(isBatteryCriticalLogic(level = 0, status = 1, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(0, 1)+ assertTrue(helper.isBatteryCritical(5))}@Testfun `battery at 4 percent charging is not critical`() {- assertFalse(isBatteryCriticalLogic(level = 4, status = 2, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(4, 2)+ assertFalse(helper.isBatteryCritical(5))}@Testfun `battery at 4 percent full is not critical`() {- assertFalse(isBatteryCriticalLogic(level = 4, status = 3, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(4, 3)+ assertFalse(helper.isBatteryCritical(5))}@Testfun `battery at 4 percent unknown status is not critical`() {- assertFalse(isBatteryCriticalLogic(level = 4, status = 0, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(4, 0)+ assertFalse(helper.isBatteryCritical(5))}@Testfun `battery at 50 percent discharging is not critical`() {- assertFalse(isBatteryCriticalLogic(level = 50, status = 1, threshold = 5))+ every { helper.getCachedBatteryStatus() } returns Pair(50, 1)+ assertFalse(helper.isBatteryCritical(5))}@Testfun `custom threshold 10 percent works`() {- assertTrue(isBatteryCriticalLogic(level = 9, status = 1, threshold = 10))- assertFalse(isBatteryCriticalLogic(level = 10, status = 1, threshold = 10))+ every { helper.getCachedBatteryStatus() } returns Pair(9, 1)+ assertTrue(helper.isBatteryCritical(10))+ every { helper.getCachedBatteryStatus() } returns Pair(10, 1)+ assertFalse(helper.isBatteryCritical(10))}@Testfun `custom threshold 1 percent works`() {- assertTrue(isBatteryCriticalLogic(level = 0, status = 1, threshold = 1))- assertFalse(isBatteryCriticalLogic(level = 1, status = 1, threshold = 1))+ every { helper.getCachedBatteryStatus() } returns Pair(0, 1)+ assertTrue(helper.isBatteryCritical(1))+ every { helper.getCachedBatteryStatus() } returns Pair(1, 1)+ assertFalse(helper.isBatteryCritical(1))}- // --- Battery status code mapping ---+ // --- getBatteryStatusString ---@Testfun `battery status string for discharging`() {- assertEquals("Unplugged/Discharging", statusCodeToString(1))+ every { helper.getCachedBatteryStatus() } returns Pair(50, 1)+ assertEquals("50% (Unplugged/Discharging)", helper.getBatteryStatusString())}@Testfun `battery status string for charging`() {- assertEquals("Charging", statusCodeToString(2))+ every { helper.getCachedBatteryStatus() } returns Pair(85, 2)+ assertEquals("85% (Charging)", helper.getBatteryStatusString())}@Testfun `battery status string for full`() {- assertEquals("Full", statusCodeToString(3))+ every { helper.getCachedBatteryStatus() } returns Pair(100, 3)+ assertEquals("100% (Full)", helper.getBatteryStatusString())}@Testfun `battery status string for unknown`() {- assertEquals("Unknown", statusCodeToString(0))+ every { helper.getCachedBatteryStatus() } returns Pair(75, 0)+ assertEquals("75% (Unknown)", helper.getBatteryStatusString())}@Testfun `battery status string for unexpected code`() {- assertEquals("Unknown (99)", statusCodeToString(99))+ every { helper.getCachedBatteryStatus() } returns Pair(60, 99)+ assertEquals("60% (Unknown (99))", helper.getBatteryStatusString())}- // --- Battery percentage calculation ---+ // --- getBatteryStatus (real intent parsing) ---@Test- fun `battery percentage calculation normal case`() {- val pct = calculateBatteryPct(level = 75, scale = 100)- assertEquals(75, pct)- }+ fun `getBatteryStatus parses charging intent correctly`() {+ mockBatteryIntent(level = 75, scale = 100, status = BatteryManager.BATTERY_STATUS_CHARGING)- @Test- fun `battery percentage calculation with non-100 scale`() {- val pct = calculateBatteryPct(level = 150, scale = 200)- assertEquals(75, pct)+ val (level, statusCode) = helper.getBatteryStatus()+ assertEquals(75, level)+ assertEquals(2, statusCode)}@Test- fun `battery percentage calculation at 0`() {- val pct = calculateBatteryPct(level = 0, scale = 100)- assertEquals(0, pct)- }+ fun `getBatteryStatus parses full intent correctly`() {+ mockBatteryIntent(level = 100, scale = 100, status = BatteryManager.BATTERY_STATUS_FULL)- @Test- fun `battery percentage calculation at 100`() {- val pct = calculateBatteryPct(level = 100, scale = 100)- assertEquals(100, pct)+ val (level, statusCode) = helper.getBatteryStatus()+ assertEquals(100, level)+ assertEquals(3, statusCode)}@Test- fun `battery percentage defaults to 100 when level is negative`() {- val pct = calculateBatteryPct(level = -1, scale = 100)- assertEquals(100, pct)+ fun `getBatteryStatus parses discharging intent correctly`() {+ mockBatteryIntent(level = 42, scale = 100, status = BatteryManager.BATTERY_STATUS_DISCHARGING)++ val (level, statusCode) = helper.getBatteryStatus()+ assertEquals(42, level)+ assertEquals(1, statusCode)}@Test- fun `battery percentage defaults to 100 when scale is 0`() {- val pct = calculateBatteryPct(level = 50, scale = 0)- assertEquals(100, pct)+ fun `getBatteryStatus calculates percentage with non-100 scale`() {+ mockBatteryIntent(level = 150, scale = 200, status = BatteryManager.BATTERY_STATUS_CHARGING)++ val (level, _) = helper.getBatteryStatus()+ assertEquals(75, level)}@Test- fun `battery percentage defaults to 100 when scale is negative`() {- val pct = calculateBatteryPct(level = 50, scale = -1)- assertEquals(100, pct)- }+ fun `getBatteryStatus defaults to 100 when level is negative`() {+ mockBatteryIntent(level = -1, scale = 100, status = BatteryManager.BATTERY_STATUS_DISCHARGING)- // --- getBatteryStatusString format ---+ val (level, _) = helper.getBatteryStatus()+ assertEquals(100, level)+ }@Test- fun `battery status string format includes level and status`() {- val result = formatBatteryStatusString(level = 85, status = 2)- assertEquals("85% (Charging)", result)+ fun `getBatteryStatus defaults to 100 when scale is 0`() {+ mockBatteryIntent(level = 50, scale = 0, status = BatteryManager.BATTERY_STATUS_FULL)++ val (level, _) = helper.getBatteryStatus()+ assertEquals(100, level)}@Test- fun `battery status string format for low discharging`() {- val result = formatBatteryStatusString(level = 3, status = 1)- assertEquals("3% (Unplugged/Discharging)", result)+ fun `getBatteryStatus defaults to 100 when scale is negative`() {+ mockBatteryIntent(level = 50, scale = -1, status = BatteryManager.BATTERY_STATUS_FULL)++ val (level, _) = helper.getBatteryStatus()+ assertEquals(100, level)}- // --- Helper methods that replicate the logic under test ---+ @Test+ fun `getBatteryStatus handles null intent`() {+ every { context.registerReceiver(null, any()) } returns null- private fun isBatteryCriticalLogic(level: Int, status: Int, threshold: Int): Boolean {- return level < threshold && status == 1+ val (level, statusCode) = helper.getBatteryStatus()+ assertEquals(100, level)+ assertEquals(0, statusCode)}- private fun statusCodeToString(status: Int): String {- return when (status) {- 0 -> "Unknown"- 1 -> "Unplugged/Discharging"- 2 -> "Charging"- 3 -> "Full"- else -> "Unknown ($status)"- }- }+ // --- Helper ---- private fun calculateBatteryPct(level: Int, scale: Int): Int {- return if (level >= 0 && scale > 0) {- (level * 100) / scale- } else {- 100+ private fun mockBatteryIntent(level: Int, scale: Int, status: Int) {+ val batteryIntent = mockk<Intent> {+ every { getIntExtra(BatteryManager.EXTRA_LEVEL, -1) } returns level+ every { getIntExtra(BatteryManager.EXTRA_SCALE, -1) } returns scale+ every { getIntExtra(BatteryManager.EXTRA_STATUS, -1) } returns status}- }-- private fun formatBatteryStatusString(level: Int, status: Int): String {- val statusText = statusCodeToString(status)- return "$level% ($statusText)"+ every { context.registerReceiver(null, any()) } returns batteryIntent}}diff --git a/apps/mobile/android/app/src/test/resources/robolectric.properties b/apps/mobile/android/app/src/test/resources/robolectric.propertiesnew file mode 100644index 00000000..979b5eeb--- /dev/null+++ b/apps/mobile/android/app/src/test/resources/robolectric.properties@@ -0,0 +1 @@+sdk=34