Skip to content

Colota - Android GPS Location tracker

test: add tests for v1.5.0 features (Traccar POST, stationary profiles, WiFi pause, entry delay)

Max Dietrich12b2ba82d8aa
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt
index 2de2d3a5..7f9858ce 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt
@@ -206,4 +206,119 @@ class GeofenceHelperTest {
assertNotNull(result)
assertEquals("Office", result!!.name)
}
+
+ // =========================================================================
+ // getPauseZone
+ // =========================================================================
+
+ @Test
+ fun `getPauseZone returns zone when location inside radius`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)
+
+ val location = mockLocation(52.5001, 13.4001)
+ val result = helper.getPauseZone(location)
+
+ assertNotNull(result)
+ assertEquals("Home", result!!.name)
+ }
+
+ @Test
+ fun `getPauseZone returns null when location outside all zones`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)
+
+ val location = mockLocation(48.0, 11.0)
+ assertNull(helper.getPauseZone(location))
+ }
+
+ @Test
+ fun `getPauseZone returns zone with correct WiFi and motionless settings`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 500.0, pause = true, pauseOnWifi = true, pauseOnMotionless = true, motionlessTimeoutMinutes = 3)
+
+ val location = mockLocation(52.5, 13.4)
+ val result = helper.getPauseZone(location)
+
+ assertNotNull(result)
+ assertTrue(result!!.pauseOnWifi)
+ assertTrue(result.pauseOnMotionless)
+ assertEquals(3, result.motionlessTimeoutMinutes)
+ }
+
+ @Test
+ fun `getPauseZone ignores disabled zones`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 500.0, pause = true)
+ val id = db.readableDatabase.query("geofences", arrayOf("id"), "name = ?", arrayOf("Home"), null, null, null).use {
+ it.moveToFirst(); it.getInt(0)
+ }
+ helper.updateGeofence(id, en = false, name = null, lat = null, lon = null, rad = null, pause = null)
+ helper.invalidateCache()
+
+ val location = mockLocation(52.5, 13.4)
+ assertNull(helper.getPauseZone(location))
+ }
+
+ @Test
+ fun `getPauseZone ignores zones with pause_tracking off`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 500.0, pause = false)
+
+ val location = mockLocation(52.5, 13.4)
+ assertNull(helper.getPauseZone(location))
+ }
+
+ @Test
+ fun `getPauseZone returns first matching zone when overlapping`() {
+ helper.insertGeofence("Inner", 52.5, 13.4, 100.0, pause = true)
+ helper.insertGeofence("Outer", 52.5, 13.4, 500.0, pause = true)
+
+ val location = mockLocation(52.5, 13.4)
+ val result = helper.getPauseZone(location)
+
+ assertNotNull(result)
+ // Returns whichever loads first from DB
+ assertTrue(result!!.name == "Inner" || result.name == "Outer")
+ }
+
+ // =========================================================================
+ // WiFi/motionless field defaults
+ // =========================================================================
+
+ @Test
+ fun `geofence defaults pauseOnWifi to false`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)
+
+ val result = helper.getGeofenceByName("Home")
+
+ assertNotNull(result)
+ assertFalse(result!!.pauseOnWifi)
+ }
+
+ @Test
+ fun `geofence defaults pauseOnMotionless to false`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)
+
+ val result = helper.getGeofenceByName("Home")
+
+ assertNotNull(result)
+ assertFalse(result!!.pauseOnMotionless)
+ }
+
+ @Test
+ fun `geofence defaults motionlessTimeoutMinutes to 10`() {
+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)
+
+ val result = helper.getGeofenceByName("Home")
+
+ assertNotNull(result)
+ assertEquals(10, result!!.motionlessTimeoutMinutes)
+ }
+
+ // =========================================================================
+ // Helpers
+ // =========================================================================
+
+ private fun mockLocation(lat: Double, lon: Double): android.location.Location {
+ return io.mockk.mockk {
+ io.mockk.every { latitude } returns lat
+ io.mockk.every { longitude } returns lon
+ }
+ }
}
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.kt
index 9ce718b7..d912822a 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
@@ -1703,6 +1703,96 @@ class LocationForegroundServiceTest {
method.invoke(service, geofence)
}
+ // =========================================================================
+ // Entry delay calculation
+ // =========================================================================
+
+ @Test
+ fun `entry delay uses 3_5x tracking interval`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ interval = 10000L,
+ filterInaccurateLocations = false
+ ))
+
+ invokeStartEntryDelay(homeGeofence)
+
+ // At 3.5x 10000ms = 35000ms, zone should not be entered yet
+ advanceTimeBy(34999L)
+ assertFalse(getField("insidePauseZone"))
+
+ // At 35001ms, zone should be entered
+ advanceTimeBy(2L)
+ assertTrue(getField("insidePauseZone"))
+ }
+
+ // =========================================================================
+ // WiFi pause event reason
+ // =========================================================================
+
+ @Test
+ fun `enterPauseZone with both WiFi and motionless registers both`() {
+ val dualGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true, motionlessTimeoutMinutes = 5)
+ coEvery { service["registerWifiPause"]() } returns Unit
+ coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
+
+ invokeEnterPauseZone(dualGeofence)
+
+ verify { service["registerWifiPause"]() }
+ verify { service["startMotionlessCountdown"](5) }
+ }
+
+ @Test
+ fun `exitPauseZone clears both WiFi and motionless state`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true))
+ setField("isWifiPaused", true)
+ setField("isMotionlessPaused", true)
+
+ invokeExitPauseZone()
+
+ assertFalse(getField<Boolean>("isWifiPaused"))
+ assertFalse(getField<Boolean>("isMotionlessPaused"))
+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ // =========================================================================
+ // maybeResumeGps - both holds active
+ // =========================================================================
+
+ @Test
+ fun `maybeResumeGps blocked when both wifi and motionless holds active`() = testScope.runTest {
+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true))
+ setField("isWifiPaused", true)
+ setField("isMotionlessPaused", true)
+
+ invokeMaybeResumeGps()
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ // =========================================================================
+ // handleLocationUpdate - Traccar format uses empty field map
+ // =========================================================================
+
+ @Test
+ fun `handleLocationUpdate uses empty field map when apiFormat is traccar_json`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ interval = 5000L,
+ filterInaccurateLocations = false,
+ apiFormat = "traccar_json"
+ ))
+ setField("fieldMap", mapOf("lat" to "latitude", "lon" to "longitude"))
+ 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()) }
+ }
+
// =========================================================================
// Reflection helpers
// =========================================================================
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
index 9172266f..c0b4912e 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
@@ -680,6 +680,83 @@ class ProfileManagerTest {
assertNull(lastStationaryCallback)
}
+ // --- Stationary + other conditions: priority interactions ---
+
+ @Test
+ fun `charging profile overrides stationary when charging starts`() = testScope.runTest {
+ val stationary = stationaryProfile(id = 5, priority = 5)
+ val charging = chargingProfile(id = 1, priority = 10)
+ every { profileHelper.getEnabledProfiles() } returns listOf(charging, stationary)
+
+ val manager = createManager()
+
+ // Become stationary first
+ manager.onLocationUpdate(mockLocation(0.1f))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+ assertEquals("Stationary", switchedProfileName)
+
+ // Start charging - higher priority should take over
+ manager.onChargingStateChanged(true)
+ assertEquals("Charging", switchedProfileName)
+ }
+
+ @Test
+ fun `falls back to stationary profile when charging stops`() = testScope.runTest {
+ val stationary = stationaryProfile(id = 5, priority = 5, deactivationDelay = 0)
+ val charging = chargingProfile(id = 1, priority = 10, deactivationDelay = 0)
+ every { profileHelper.getEnabledProfiles() } returns listOf(charging, stationary)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ // Become stationary
+ manager.onLocationUpdate(mockLocation(0.1f))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+ assertTrue(manager.isStationary)
+
+ // Start charging - charging wins
+ manager.onChargingStateChanged(true)
+ assertEquals("Charging", switchedProfileName)
+
+ // Stop charging - stationary still true, should fall back to stationary profile
+ manager.onChargingStateChanged(false)
+ advanceTimeBy(100) // let 0s deactivation fire
+ assertEquals("Stationary", switchedProfileName)
+ }
+
+ @Test
+ fun `stationary does not evaluate when no stationary profile configured`() = testScope.runTest {
+ val charging = chargingProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(charging)
+
+ val manager = createManager()
+
+ // Feed slow locations - should not start stationary timer
+ manager.onLocationUpdate(mockLocation(0.1f))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+
+ assertFalse(manager.isStationary)
+ }
+
+ @Test
+ fun `speed above profile activates over stationary when moving fast`() = testScope.runTest {
+ val stationary = stationaryProfile(id = 5, priority = 5)
+ val fast = speedAboveProfile(id = 3, threshold = 10f, priority = 15)
+ every { profileHelper.getEnabledProfiles() } returns listOf(fast, stationary)
+
+ val manager = createManager()
+
+ // Feed fast speeds
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(15f))
+ }
+
+ assertEquals("Fast", switchedProfileName)
+ assertFalse(manager.isStationary)
+ }
+
// --- Unknown condition type ---
@Test
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
index bb8270bd..61268508 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
@@ -286,6 +286,111 @@ class NetworkManagerTest {
assertTrue("Expected ISO 8601 format, got: $timestamp", timestamp.contains("T") && timestamp.endsWith("Z"))
}
+ // --- buildTraccarJsonPayload: battery status codes ---
+
+ @Test
+ fun `buildTraccarJsonPayload marks bs=3 full as charging`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("batt", 100); put("bs", 3) // full
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val battery = result.getJSONObject("location").getJSONObject("battery")
+ assertTrue(battery.getBoolean("is_charging"))
+ assertEquals(1.0, battery.getDouble("level"), 0.001)
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload marks bs=1 not charging as not charging`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("batt", 50); put("bs", 1) // not charging
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val battery = result.getJSONObject("location").getJSONObject("battery")
+ assertFalse(battery.getBoolean("is_charging"))
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload marks bs=0 unknown as not charging`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("batt", 50); put("bs", 0)
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val battery = result.getJSONObject("location").getJSONObject("battery")
+ assertFalse(battery.getBoolean("is_charging"))
+ }
+
+ // --- buildTraccarJsonPayload: JSON roundtrip (simulates batch sync path) ---
+
+ @Test
+ fun `buildTraccarJsonPayload produces identical output after JSON string roundtrip`() {
+ val flat = JSONObject().apply {
+ put("id", "my-tracker")
+ put("lat", 52.12345)
+ put("lon", -2.12345)
+ put("acc", 15)
+ put("alt", 380)
+ put("vel", 5.5)
+ put("bear", 90.0)
+ put("batt", 85)
+ put("bs", 2)
+ put("tst", 1739362800L)
+ }
+
+ // Direct path (instant sync)
+ val directResult = invokeBuildTraccarJsonPayload(flat)
+
+ // Roundtrip path (batch sync: toString -> DB -> JSONObject parse)
+ val serialized = flat.toString()
+ val roundtripped = JSONObject(serialized)
+ val roundtripResult = invokeBuildTraccarJsonPayload(roundtripped)
+
+ // All fields must match
+ assertEquals(
+ directResult.getString("device_id"),
+ roundtripResult.getString("device_id")
+ )
+ val directCoords = directResult.getJSONObject("location").getJSONObject("coords")
+ val roundtripCoords = roundtripResult.getJSONObject("location").getJSONObject("coords")
+ assertEquals(directCoords.getDouble("latitude"), roundtripCoords.getDouble("latitude"), 0.00001)
+ assertEquals(directCoords.getDouble("longitude"), roundtripCoords.getDouble("longitude"), 0.00001)
+ assertEquals(directCoords.getDouble("accuracy"), roundtripCoords.getDouble("accuracy"), 0.001)
+ assertEquals(directCoords.getDouble("altitude"), roundtripCoords.getDouble("altitude"), 0.001)
+ assertEquals(directCoords.getDouble("speed"), roundtripCoords.getDouble("speed"), 0.001)
+ assertEquals(directCoords.getDouble("heading"), roundtripCoords.getDouble("heading"), 0.001)
+
+ val directBatt = directResult.getJSONObject("location").getJSONObject("battery")
+ val roundtripBatt = roundtripResult.getJSONObject("location").getJSONObject("battery")
+ assertEquals(directBatt.getDouble("level"), roundtripBatt.getDouble("level"), 0.001)
+ assertEquals(directBatt.getBoolean("is_charging"), roundtripBatt.getBoolean("is_charging"))
+
+ assertEquals(
+ directResult.getJSONObject("location").getString("timestamp"),
+ roundtripResult.getJSONObject("location").getString("timestamp")
+ )
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload handles minimal payload after roundtrip`() {
+ val flat = JSONObject().apply {
+ put("lat", 0.0)
+ put("lon", 0.0)
+ put("tst", 1000L)
+ }
+
+ val roundtripped = JSONObject(flat.toString())
+ val result = invokeBuildTraccarJsonPayload(roundtripped)
+
+ assertEquals("colota", result.getString("device_id"))
+ val coords = result.getJSONObject("location").getJSONObject("coords")
+ assertEquals(0.0, coords.getDouble("latitude"), 0.001)
+ assertFalse(coords.has("speed"))
+ assertFalse(coords.has("heading"))
+ assertFalse(result.getJSONObject("location").has("battery"))
+ }
+
// --- buildQueryString ---
@Test
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.kt
index ba3807b8..669a847a 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
@@ -834,6 +834,122 @@ class SyncManagerTest {
verify(exactly = 0) { dbHelper.getQueuedLocations(any()) }
}
+ // ========================================================================
+ // Async exception isolation (fix: one bad item must not kill the chunk)
+ // ========================================================================
+
+ @Test
+ fun `syncQueue isolates exception in single item without cancelling chunk`() = scope.runTest {
+ mockkObject(LocationServiceModule.Companion)
+ every { LocationServiceModule.sendSyncErrorEvent(any(), any()) } returns true
+
+ syncManager.updateConfig(
+ endpoint = "https://example.com",
+ syncIntervalSeconds = 0,
+ retryIntervalSeconds = 30,
+ maxRetries = 5,
+ isOfflineMode = false,
+ isWifiOnlySync = false,
+ authHeaders = emptyMap()
+ )
+
+ // Item 1 has corrupted payload that will throw JSONException
+ val corrupted = QueuedLocation(1L, 100L, "NOT_VALID_JSON", 0)
+ val valid = QueuedLocation(2L, 101L, """{"lat":52.0}""", 0)
+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(
+ listOf(corrupted, valid),
+ emptyList()
+ )
+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns true
+
+ syncManager.manualFlush()
+
+ // Valid item should still be sent despite corrupted sibling
+ coVerify(atLeast = 1) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }
+ // Corrupted item gets retry increment, valid item gets removed
+ verify { dbHelper.incrementRetryCount(1L, "Send failed") }
+ verify { dbHelper.markLocationsSent(listOf(101L)) }
+
+ unmockkObject(LocationServiceModule.Companion)
+ }
+
+ @Test
+ fun `syncQueue emits error event when items permanently dropped`() = scope.runTest {
+ mockkObject(LocationServiceModule.Companion)
+ every { LocationServiceModule.sendSyncErrorEvent(any(), any()) } returns true
+
+ 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 { LocationServiceModule.sendSyncErrorEvent(
+ match { it.contains("dropped") && it.contains("3") },
+ any()
+ ) }
+
+ unmockkObject(LocationServiceModule.Companion)
+ }
+
+ // ========================================================================
+ // apiFormat passthrough
+ // ========================================================================
+
+ @Test
+ fun `queueAndSend passes apiFormat to sendToEndpoint`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://example.com",
+ syncIntervalSeconds = 0,
+ retryIntervalSeconds = 30,
+ maxRetries = 5,
+ isOfflineMode = false,
+ isWifiOnlySync = false,
+ authHeaders = emptyMap(),
+ httpMethod = "POST",
+ apiFormat = "traccar_json"
+ )
+
+ coEvery { networkManager.isNetworkAvailable() } returns true
+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns true
+
+ syncManager.queueAndSend(1L, JSONObject().put("lat", 52.0))
+
+ coVerify { networkManager.sendToEndpoint(any(), any(), any(), "POST", "traccar_json") }
+ }
+
+ @Test
+ fun `syncQueue passes apiFormat to sendToEndpoint during batch sync`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://example.com",
+ syncIntervalSeconds = 0,
+ retryIntervalSeconds = 30,
+ maxRetries = 5,
+ isOfflineMode = false,
+ isWifiOnlySync = false,
+ authHeaders = emptyMap(),
+ httpMethod = "POST",
+ apiFormat = "traccar_json"
+ )
+
+ val item = QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)
+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(listOf(item), emptyList())
+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns true
+
+ syncManager.manualFlush()
+
+ coVerify { networkManager.sendToEndpoint(any(), any(), any(), "POST", "traccar_json") }
+ }
+
// ========================================================================
// Helpers
// ========================================================================