Skip to content

Colota - Android GPS Location tracker

Add Kotlin unit tests for TimedCache, GeofenceHelper, and PayloadBuilder

Max Dietrichddd581399e3e
diff --git a/.github/workflows/build-check.yml b/.github/workflows/build-check.yml
index 7dafd477..4ac74dd8 100644
--- a/.github/workflows/build-check.yml
+++ b/.github/workflows/build-check.yml
@@ -50,10 +50,16 @@ jobs:
newArchEnabled=true
EOF
- - name: Build GMS Debug APK
+ - name: Run Kotlin unit tests
run: |
cd apps/mobile/android
chmod +x gradlew
+ ./gradlew testGmsDebugUnitTest testFossDebugUnitTest --no-daemon \
+ -Dorg.gradle.jvmargs="-Xmx4096m -XX:MaxMetaspaceSize=512m"
+
+ - name: Build GMS Debug APK
+ run: |
+ cd apps/mobile/android
./gradlew assembleGmsDebug --no-daemon \
-Dorg.gradle.jvmargs="-Xmx4096m -XX:MaxMetaspaceSize=512m"
diff --git a/.github/workflows/build-latest-release.yml b/.github/workflows/build-latest-release.yml
index 6d29e8be..e5df6d21 100644
--- a/.github/workflows/build-latest-release.yml
+++ b/.github/workflows/build-latest-release.yml
@@ -91,10 +91,16 @@ jobs:
test -n "${{ secrets.KEY_ALIAS }}" || exit 1
test -n "${{ secrets.KEY_PASSWORD }}" || exit 1
- - name: Build GMS Release APK
+ - name: Run Kotlin unit tests
run: |
cd apps/mobile/android
chmod +x gradlew
+ ./gradlew testGmsDebugUnitTest testFossDebugUnitTest --no-daemon \
+ -Dorg.gradle.jvmargs="-Xmx4096m -XX:MaxMetaspaceSize=512m"
+
+ - name: Build GMS Release APK
+ run: |
+ cd apps/mobile/android
./gradlew assembleGmsRelease --no-daemon \
-PhermesEnabled=true \
-Pandroid.useAndroidX=true \
diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml
index 42778c00..b54e5551 100644
--- a/.github/workflows/build-release.yml
+++ b/.github/workflows/build-release.yml
@@ -86,10 +86,16 @@ jobs:
test -n "${{ secrets.KEY_ALIAS }}" || exit 1
test -n "${{ secrets.KEY_PASSWORD }}" || exit 1
- - name: Build GMS Release APK
+ - name: Run Kotlin unit tests
run: |
cd apps/mobile/android
chmod +x gradlew
+ ./gradlew testGmsDebugUnitTest testFossDebugUnitTest --no-daemon \
+ -Dorg.gradle.jvmargs="-Xmx4096m -XX:MaxMetaspaceSize=512m"
+
+ - name: Build GMS Release APK
+ run: |
+ cd apps/mobile/android
./gradlew assembleGmsRelease --no-daemon \
-PhermesEnabled=true \
-Pandroid.useAndroidX=true \
diff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.md
index 73117447..0abb72f4 100644
--- a/apps/docs/docs/development/local-setup.md
+++ b/apps/docs/docs/development/local-setup.md
@@ -139,6 +139,38 @@ colota/
└── index.ts # Barrel exports
```
+## Running Tests
+
+### JavaScript Tests
+
+Run the React Native test suite (Jest):
+
+```bash
+npm test -w @colota/mobile
+```
+
+### Kotlin Unit Tests
+
+Run native Android unit tests for both build flavors:
+
+```bash
+cd apps/mobile/android
+./gradlew testGmsDebugUnitTest testFossDebugUnitTest
+```
+
+Test files are located in `apps/mobile/android/app/src/test/java/com/Colota/`. The tests cover:
+
+- **TimedCache** — TTL cache logic
+- **GeofenceHelper** — Haversine distance calculations and radius checks
+- **PayloadBuilder** — JSON payload construction and field map parsing
+
+### Linting and Type Checking
+
+```bash
+npm run lint -w @colota/mobile # ESLint
+npx -w @colota/mobile tsc --noEmit # TypeScript type check
+```
+
## Common Tasks
### Adding a New Screen
diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradle
index 9db94760..b6c74288 100644
--- a/apps/mobile/android/app/build.gradle
+++ b/apps/mobile/android/app/build.gradle
@@ -153,6 +153,10 @@ android {
// F-Droid / open-source variant — no Google Play Services
}
}
+
+ testOptions {
+ unitTests.returnDefaultValues = true
+ }
}
dependencies {
@@ -167,4 +171,8 @@ dependencies {
} else {
implementation jscFlavor
}
+
+ testImplementation 'junit:junit:4.13.2'
+ testImplementation 'io.mockk:mockk:1.13.12'
+ testImplementation 'org.json:json:20240303'
}
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
index 87774713..b192d0cb 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
@@ -30,24 +30,24 @@ class GeofenceHelper(private val context: Context) {
companion object {
private const val TAG = "GeofenceHelper"
- private const val EARTH_RADIUS_METERS = 6371000.0
- }
+ internal const val EARTH_RADIUS_METERS = 6371000.0
- /** Haversine formula — accurate at any distance on Earth. */
- private fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
- val dLat = Math.toRadians(lat2 - lat1)
- val dLon = Math.toRadians(lon2 - lon1)
- val a = sin(dLat / 2).pow(2) +
- cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon / 2).pow(2)
- return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))
- }
+ /** Haversine formula — accurate at any distance on Earth. */
+ internal fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
+ val dLat = Math.toRadians(lat2 - lat1)
+ val dLon = Math.toRadians(lon2 - lon1)
+ val a = sin(dLat / 2).pow(2) +
+ cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon / 2).pow(2)
+ return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))
+ }
- private fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radius: Double): Boolean {
- // Fast bounding-box rejection (lon degrees shrink at higher latitudes)
- val maxLatDeg = radius / 111000.0
- val maxLonDeg = radius / (111000.0 * cos(Math.toRadians(lat1)))
- if (Math.abs(lat1 - lat2) > maxLatDeg || Math.abs(lon1 - lon2) > maxLonDeg) return false
- return calculateDistance(lat1, lon1, lat2, lon2) <= radius
+ internal fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radius: Double): Boolean {
+ // Fast bounding-box rejection (lon degrees shrink at higher latitudes)
+ val maxLatDeg = radius / 111000.0
+ val maxLonDeg = radius / (111000.0 * cos(Math.toRadians(lat1)))
+ if (Math.abs(lat1 - lat2) > maxLatDeg || Math.abs(lon1 - lon2) > maxLonDeg) return false
+ return calculateDistance(lat1, lon1, lat2, lon2) <= radius
+ }
}
fun getPauseZone(location: Location): String? {
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
new file mode 100644
index 00000000..160a2a0e
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt
@@ -0,0 +1,100 @@
+package com.Colota.data
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class GeofenceHelperTest {
+
+ // Known reference distances (verified against online Haversine calculators):
+ // Berlin (52.52, 13.405) → Munich (48.1351, 11.582) ≈ 504 km
+ // New York (40.7128, -74.006) → London (51.5074, -0.1278) ≈ 5,570 km
+ // Same point → 0 m
+
+ @Test
+ fun `calculateDistance returns zero for same point`() {
+ val distance = GeofenceHelper.calculateDistance(52.52, 13.405, 52.52, 13.405)
+ assertEquals(0.0, distance, 0.01)
+ }
+
+ @Test
+ fun `calculateDistance Berlin to Munich is about 504 km`() {
+ val distance = GeofenceHelper.calculateDistance(52.52, 13.405, 48.1351, 11.582)
+ assertEquals(504_000.0, distance, 5000.0) // within 5 km tolerance
+ }
+
+ @Test
+ fun `calculateDistance New York to London is about 5570 km`() {
+ val distance = GeofenceHelper.calculateDistance(40.7128, -74.006, 51.5074, -0.1278)
+ assertEquals(5_570_000.0, distance, 20_000.0) // within 20 km tolerance
+ }
+
+ @Test
+ fun `calculateDistance is symmetric`() {
+ val d1 = GeofenceHelper.calculateDistance(52.52, 13.405, 48.1351, 11.582)
+ val d2 = GeofenceHelper.calculateDistance(48.1351, 11.582, 52.52, 13.405)
+ assertEquals(d1, d2, 0.01)
+ }
+
+ @Test
+ fun `calculateDistance across equator`() {
+ // Quito (0.1807, -78.4678) → Bogota (4.711, -74.0721) ≈ 702 km
+ val distance = GeofenceHelper.calculateDistance(0.1807, -78.4678, 4.711, -74.0721)
+ assertEquals(702_000.0, distance, 5000.0)
+ }
+
+ @Test
+ fun `calculateDistance across date line`() {
+ // Auckland (−36.848, 174.763) → Fiji (−17.713, 177.986) ≈ 2160 km
+ val distance = GeofenceHelper.calculateDistance(-36.848, 174.763, -17.713, 177.986)
+ assertEquals(2_160_000.0, distance, 30_000.0)
+ }
+
+ @Test
+ fun `isWithinRadius returns true for point inside`() {
+ // 100m from Brandenburg Gate (52.5163, 13.3777) — a point 50m away
+ val center = Pair(52.5163, 13.3777)
+ // ~50m north ≈ +0.00045 degrees latitude
+ assertTrue(GeofenceHelper.isWithinRadius(
+ center.first, center.second,
+ center.first + 0.00045, center.second,
+ 100.0
+ ))
+ }
+
+ @Test
+ fun `isWithinRadius returns false for point outside`() {
+ val center = Pair(52.5163, 13.3777)
+ // ~200m north ≈ +0.0018 degrees latitude
+ assertFalse(GeofenceHelper.isWithinRadius(
+ center.first, center.second,
+ center.first + 0.0018, center.second,
+ 100.0
+ ))
+ }
+
+ @Test
+ fun `isWithinRadius returns true for point exactly on boundary`() {
+ val center = Pair(52.5163, 13.3777)
+ val distance = GeofenceHelper.calculateDistance(
+ center.first, center.second,
+ center.first + 0.0009, center.second
+ )
+ // Use the actual distance as radius — should be on boundary
+ assertTrue(GeofenceHelper.isWithinRadius(
+ center.first, center.second,
+ center.first + 0.0009, center.second,
+ distance
+ ))
+ }
+
+ @Test
+ fun `isWithinRadius same point is always within any radius`() {
+ assertTrue(GeofenceHelper.isWithinRadius(52.52, 13.405, 52.52, 13.405, 1.0))
+ }
+
+ @Test
+ fun `bounding box rejects distant points quickly`() {
+ // Berlin to Munich (~504 km) with 1 km radius — should be rejected by bounding box
+ assertFalse(GeofenceHelper.isWithinRadius(52.52, 13.405, 48.1351, 11.582, 1000.0))
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt
new file mode 100644
index 00000000..b4a60432
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt
@@ -0,0 +1,214 @@
+package com.Colota.sync
+
+import android.location.Location
+import io.mockk.every
+import io.mockk.mockk
+import org.json.JSONObject
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+class PayloadBuilderTest {
+
+ private lateinit var builder: PayloadBuilder
+
+ @Before
+ fun setUp() {
+ builder = PayloadBuilder()
+ }
+
+ // --- buildPayload tests ---
+
+ @Test
+ fun `buildPayload uses default field names when no mapping`() {
+ val location = createMockLocation(lat = 52.52, lon = 13.405, acc = 10.5f, speed = 1.2f)
+
+ val payload = builder.buildPayload(
+ location = location,
+ batteryLevel = 85,
+ batteryStatus = 2,
+ fieldMap = emptyMap(),
+ timestamp = 1700000000L
+ )
+
+ assertEquals(52.52, payload.getDouble("lat"), 0.001)
+ assertEquals(13.405, payload.getDouble("lon"), 0.001)
+ assertEquals(11, payload.getInt("acc")) // 10.5 rounded
+ assertEquals(1, payload.getInt("vel")) // 1.2 rounded
+ assertEquals(85, payload.getInt("batt"))
+ assertEquals(2, payload.getInt("bs"))
+ assertEquals(1700000000L, payload.getLong("tst"))
+ }
+
+ @Test
+ fun `buildPayload applies field name mapping`() {
+ val location = createMockLocation(lat = 48.0, lon = 11.0, acc = 5.0f, speed = 0.0f)
+
+ val fieldMap = mapOf("lat" to "latitude", "lon" to "longitude", "tst" to "timestamp")
+ val payload = builder.buildPayload(
+ location = location,
+ batteryLevel = 50,
+ batteryStatus = 1,
+ fieldMap = fieldMap,
+ timestamp = 1700000000L
+ )
+
+ assertEquals(48.0, payload.getDouble("latitude"), 0.001)
+ assertEquals(11.0, payload.getDouble("longitude"), 0.001)
+ assertEquals(1700000000L, payload.getLong("timestamp"))
+ // Unmapped fields keep defaults
+ assertEquals(5, payload.getInt("acc"))
+ }
+
+ @Test
+ fun `buildPayload includes altitude when available`() {
+ val location = createMockLocation(
+ lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f,
+ hasAltitude = true, altitude = 35.7
+ )
+
+ val payload = builder.buildPayload(
+ location = location,
+ batteryLevel = 80,
+ batteryStatus = 2,
+ fieldMap = emptyMap(),
+ timestamp = 1700000000L
+ )
+
+ assertEquals(36, payload.getInt("alt")) // 35.7 rounded
+ }
+
+ @Test
+ fun `buildPayload excludes altitude when not available`() {
+ val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
+
+ val payload = builder.buildPayload(
+ location = location,
+ batteryLevel = 80,
+ batteryStatus = 2,
+ fieldMap = emptyMap(),
+ timestamp = 1700000000L
+ )
+
+ assertFalse(payload.has("alt"))
+ }
+
+ @Test
+ fun `buildPayload includes bearing when available`() {
+ val location = createMockLocation(
+ lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f,
+ hasBearing = true, bearing = 180.5f
+ )
+
+ val payload = builder.buildPayload(
+ location = location,
+ batteryLevel = 80,
+ batteryStatus = 2,
+ fieldMap = emptyMap(),
+ timestamp = 1700000000L
+ )
+
+ assertEquals(180.5, payload.getDouble("bear"), 0.1)
+ }
+
+ @Test
+ fun `buildPayload includes custom fields`() {
+ val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
+ val customFields = mapOf("_type" to "location", "device" to "phone1")
+
+ val payload = builder.buildPayload(
+ location = location,
+ batteryLevel = 80,
+ batteryStatus = 2,
+ fieldMap = emptyMap(),
+ timestamp = 1700000000L,
+ customFields = customFields
+ )
+
+ assertEquals("location", payload.getString("_type"))
+ assertEquals("phone1", payload.getString("device"))
+ }
+
+ // --- parseFieldMap tests ---
+
+ @Test
+ fun `parseFieldMap returns null for null input`() {
+ assertNull(builder.parseFieldMap(null))
+ }
+
+ @Test
+ fun `parseFieldMap returns null for blank input`() {
+ assertNull(builder.parseFieldMap(""))
+ assertNull(builder.parseFieldMap(" "))
+ }
+
+ @Test
+ fun `parseFieldMap parses valid JSON`() {
+ val json = """{"lat":"latitude","lon":"longitude","tst":"timestamp"}"""
+ val result = builder.parseFieldMap(json)
+
+ assertNotNull(result)
+ assertEquals("latitude", result!!["lat"])
+ assertEquals("longitude", result["lon"])
+ assertEquals("timestamp", result["tst"])
+ }
+
+ @Test
+ fun `parseFieldMap returns null for invalid JSON`() {
+ assertNull(builder.parseFieldMap("not json"))
+ }
+
+ // --- parseCustomFields tests ---
+
+ @Test
+ fun `parseCustomFields returns null for null input`() {
+ assertNull(builder.parseCustomFields(null))
+ }
+
+ @Test
+ fun `parseCustomFields returns null for blank input`() {
+ assertNull(builder.parseCustomFields(""))
+ }
+
+ @Test
+ fun `parseCustomFields returns null for empty array`() {
+ assertNull(builder.parseCustomFields("[]"))
+ }
+
+ @Test
+ fun `parseCustomFields parses valid JSON array`() {
+ val json = """[{"key":"_type","value":"location"},{"key":"device","value":"phone1"}]"""
+ val result = builder.parseCustomFields(json)
+
+ assertNotNull(result)
+ assertEquals("location", result!!["_type"])
+ assertEquals("phone1", result["device"])
+ }
+
+ @Test
+ fun `parseCustomFields returns null for invalid JSON`() {
+ assertNull(builder.parseCustomFields("not json"))
+ }
+
+ // --- helpers ---
+
+ private fun createMockLocation(
+ lat: Double,
+ lon: Double,
+ acc: Float,
+ speed: Float,
+ hasAltitude: Boolean = false,
+ altitude: Double = 0.0,
+ hasBearing: Boolean = false,
+ bearing: Float = 0.0f
+ ): Location = mockk {
+ every { latitude } returns lat
+ every { longitude } returns lon
+ every { accuracy } returns acc
+ every { [email protected] } returns speed
+ every { hasAltitude() } returns hasAltitude
+ every { [email protected] } returns altitude
+ every { hasBearing() } returns hasBearing
+ every { [email protected] } returns bearing
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/TimedCacheTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/TimedCacheTest.kt
new file mode 100644
index 00000000..7e74df48
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/TimedCacheTest.kt
@@ -0,0 +1,78 @@
+package com.Colota.util
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class TimedCacheTest {
+
+ @Test
+ fun `get returns loaded value`() {
+ val cache = TimedCache(5000L) { "hello" }
+ assertEquals("hello", cache.get())
+ }
+
+ @Test
+ fun `get returns same value within TTL`() {
+ var callCount = 0
+ val cache = TimedCache(5000L) { callCount++; "value-$callCount" }
+
+ val first = cache.get()
+ val second = cache.get()
+
+ assertEquals(first, second)
+ assertEquals(1, callCount)
+ }
+
+ @Test
+ fun `get reloads value after TTL expires`() {
+ var callCount = 0
+ val cache = TimedCache(50L) { callCount++; "value-$callCount" }
+
+ val first = cache.get()
+ Thread.sleep(100)
+ val second = cache.get()
+
+ assertEquals("value-1", first)
+ assertEquals("value-2", second)
+ assertEquals(2, callCount)
+ }
+
+ @Test
+ fun `invalidate causes reload on next get`() {
+ var callCount = 0
+ val cache = TimedCache(60000L) { callCount++; "value-$callCount" }
+
+ cache.get()
+ assertEquals(1, callCount)
+
+ cache.invalidate()
+ cache.get()
+ assertEquals(2, callCount)
+ }
+
+ @Test
+ fun `works with nullable loader that returns non-null`() {
+ val cache = TimedCache<List<String>>(5000L) { listOf("a", "b") }
+ assertEquals(listOf("a", "b"), cache.get())
+ }
+
+ @Test
+ fun `loader is called exactly once per expiry cycle`() {
+ var callCount = 0
+ val cache = TimedCache(50L) { callCount++ }
+
+ // First cycle
+ cache.get()
+ cache.get()
+ cache.get()
+ assertEquals(1, callCount)
+
+ // Wait for expiry
+ Thread.sleep(100)
+
+ // Second cycle
+ cache.get()
+ cache.get()
+ assertEquals(2, callCount)
+ }
+}