mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 15:26:05 +00:00
Initial public NavFrame release with global regional package pipeline
This commit is contained in:
commit
d863f2b940
143 files changed
+17906
No files matched your search
@@ -0,0 +1,41 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class DemoNavigationTest {
|
||||
@Test fun demoIsDeterministicAndAdvancesMotionAndManeuver() {
|
||||
val first = DemoNavigation.stateAt(0)
|
||||
assertEquals(DemoNavigation.stateAt(5_000), DemoNavigation.stateAt(5_000))
|
||||
val later = DemoNavigation.stateAt(5_000)
|
||||
assertNotEquals(first.position, later.position)
|
||||
assertNotEquals(first.bearing, later.bearing)
|
||||
assertTrue(later.distanceToNextManeuverMeters!! < first.distanceToNextManeuverMeters!!)
|
||||
assertTrue(later.remainingDistanceMeters!! < first.remainingDistanceMeters!!)
|
||||
assertNotEquals(first.nextManeuver?.instruction, DemoNavigation.stateAt(30_000).nextManeuver?.instruction)
|
||||
assertTrue(later.nextManeuver!!.instruction.startsWith("DEMO"))
|
||||
assertNull(later.route) // Synthetic road is not represented as a calculated route.
|
||||
}
|
||||
|
||||
@Test fun demoCountdownRestartsCleanlyAndKeepsHeadingInRange() {
|
||||
assertEquals(350, DemoNavigation.stateAt(30_000).distanceToNextManeuverMeters)
|
||||
assertTrue(DemoNavigation.stateAt(29_999).distanceToNextManeuverMeters!! in 0..1)
|
||||
for (elapsed in 0L..300_000L step 500L) {
|
||||
val state = DemoNavigation.stateAt(elapsed)
|
||||
assertTrue(state.bearing >= 0 && state.bearing < 360)
|
||||
assertTrue(state.speed > 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun cameraWidensWithSpeedAndZoomsForUpcomingManeuver() {
|
||||
val policy = TftCameraPolicy()
|
||||
val slow = policy.parameters(NavigationState(speed = 5f, bearing = -1f))
|
||||
val fast = policy.parameters(NavigationState(speed = 25f, bearing = 361f))
|
||||
assertTrue(fast.zoom < slow.zoom)
|
||||
assertEquals(359f, slow.bearingDegrees)
|
||||
assertEquals(1f, fast.bearingDegrees)
|
||||
assertTrue(fast.riderAnchorY in 0.66f..0.8f)
|
||||
val approaching = policy.parameters(NavigationState(speed = 25f, nextManeuver = Maneuver("derecha", 100), distanceToNextManeuverMeters = 100))
|
||||
assertTrue(approaching.zoom > slow.zoom)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class GuidanceLanguageTest {
|
||||
@Test fun regionalAndUnsupportedLocalesUseConsistentSupportedLanguage() {
|
||||
assertEquals(GuidanceLanguage.SPANISH, GuidanceLanguage.resolve("es-MX"))
|
||||
assertEquals(GuidanceLanguage.ENGLISH, GuidanceLanguage.resolve("en-GB"))
|
||||
assertEquals(GuidanceLanguage.GERMAN, GuidanceLanguage.resolve("de_AT"))
|
||||
assertEquals(GuidanceLanguage.ENGLISH, GuidanceLanguage.resolve("ja-JP"))
|
||||
}
|
||||
@Test fun requestUsesSelectedLocaleAndDefaultsRemainSpanish() {
|
||||
val origin = GeoPoint(43.3, -5.8); val destination = GeoPoint(43.4, -5.9)
|
||||
assertTrue(buildValhallaRequest(origin, destination).contains("es-ES"))
|
||||
assertTrue(buildValhallaRequest(origin, destination, language = "fr-CA").contains("fr-FR"))
|
||||
assertTrue(buildValhallaRequest(origin, destination, language = "unsupported").contains("en-US"))
|
||||
}
|
||||
@Test fun englishCheckpointsStatusesAndCameraAlertsDoNotUseSpanish() {
|
||||
val maneuver = Maneuver("Turn left", 100, 15, 1, 2)
|
||||
val route = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), listOf(maneuver), 1000, 100, guidanceLanguage = "en-US")
|
||||
val state = NavigationState(route = route, nextManeuver = maneuver, distanceToNextManeuverMeters = 250, navigationStatus = NavigationStatus.NAVIGATING)
|
||||
assertEquals("En 250 metros, Turn left", VoiceGuidancePolicy().announcement(state))
|
||||
val policy = VoiceGuidancePolicy(GuidanceLanguage.ENGLISH)
|
||||
assertEquals("In 250 meters, Turn left", policy.announcement(state))
|
||||
assertNull(policy.announcement(state))
|
||||
assertEquals("Now, Turn left", policy.announcement(state.copy(distanceToNextManeuverMeters = 20)))
|
||||
assertEquals("You have arrived at your destination.", policy.announcement(state.copy(navigationStatus = NavigationStatus.ARRIVED)))
|
||||
assertTrue(GuidanceLanguage.ENGLISH.camera(200).contains("200 meters"))
|
||||
assertTrue(GuidanceLanguage.SPANISH.camera(200).contains("200 metros"))
|
||||
}
|
||||
@Test fun everySelectableLanguageProvidesLocalizedSpeech() {
|
||||
GuidanceLanguage.entries.forEach { language ->
|
||||
assertTrue(language.maneuver("instruction", 250, false).contains("250"))
|
||||
assertTrue(language.camera(200).contains("200"))
|
||||
assertTrue(language.status(NavigationStatus.GPS_LOST).isNotBlank())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class NominatimGeocodingTest {
|
||||
// Original synthetic fixture following jsonv2's documented numeric strings.
|
||||
private val fixture = """[
|
||||
{"place_id":123,"lat":"43.36","lon":"-5.85","display_name":"Destino de prueba, Asturias, España","licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"},
|
||||
{"lat":"0","lon":"180","display_name":"Punto de prueba"}
|
||||
]"""
|
||||
|
||||
@Test fun `jsonv2 preserves display label coordinates and attribution`() {
|
||||
val results = parseNominatimResults(fixture)
|
||||
assertEquals(2, results.size)
|
||||
assertEquals("Destino de prueba, Asturias, España", results[0].name)
|
||||
assertEquals(GeoPoint(43.36, -5.85), results[0].position)
|
||||
assertTrue(results[0].attribution.contains("ODbL 1.0"))
|
||||
assertEquals("© OpenStreetMap contributors", results[1].attribution)
|
||||
}
|
||||
|
||||
@Test fun `empty list is a successful no match result`() {
|
||||
assertTrue(parseNominatimResults("[]").isEmpty())
|
||||
}
|
||||
|
||||
@Test fun `result count and duplicate labels are bounded`() {
|
||||
val item = """{"lat":"43.36","lon":"-5.85","display_name":"Test"}"""
|
||||
assertEquals(1, parseNominatimResults("[$item,$item]").size)
|
||||
val distinct = (0..5).joinToString(",") { """{"lat":"$it","lon":"0","display_name":"Test $it"}""" }
|
||||
assertEquals(5, parseNominatimResults("[$distinct]").size)
|
||||
rejects { parseNominatimResults("[" + List(41) { item }.joinToString(",") + "]") }
|
||||
}
|
||||
|
||||
@Test fun `strict malformed and backend errors omit private data`() {
|
||||
listOf("", "null", "{}", "[null]", fixture + "{}", "//comment\n$fixture",
|
||||
"""{"error":"private search text"}""").forEach { value -> rejects { parseNominatimResults(value) } }
|
||||
try {
|
||||
parseNominatimResults("""{"error":"private search text"}""")
|
||||
fail("Expected rejection")
|
||||
} catch (error: GeocodingResponseException) {
|
||||
assertFalse(error.message!!.contains("private search text"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `coordinates are strict finite numeric strings within geographic range`() {
|
||||
listOf("NaN", "Infinity", "91", "-91", "1e999", "0x1p0", "", " 43.36").forEach { latitude ->
|
||||
rejects { parseNominatimResults(fixture.replace("43.36", latitude)) }
|
||||
}
|
||||
rejects { parseNominatimResults(fixture.replace("-5.85", "181")) }
|
||||
rejects { parseNominatimResults(fixture.replace("\"lat\":\"43.36\"", "\"lat\":43.36")) }
|
||||
rejects { parseNominatimResults(fixture.replace("\"lon\":\"-5.85\"", "\"lon\":null")) }
|
||||
}
|
||||
|
||||
@Test fun `required names and response sizes are validated`() {
|
||||
rejects { parseNominatimResults("""[{"lat":"0","lon":"0","display_name":" "}]""") }
|
||||
rejects { parseNominatimResults(fixture.replace("Destino de prueba, Asturias, España", "x".repeat(2_049))) }
|
||||
rejects { parseNominatimResults(" ".repeat(512 * 1024 + 1)) }
|
||||
val label = parseNominatimResults("""[{"lat":"0","lon":"0","display_name":"Test\nplace"}]""")[0].name
|
||||
assertEquals("Test place", label)
|
||||
}
|
||||
|
||||
@Test fun `parameters normalize whitespace preserve Unicode and do not carry GPS`() {
|
||||
val params = nominatimSearchParameters(" Peña de prueba ")
|
||||
assertEquals("Peña de prueba", params["q"])
|
||||
assertEquals("jsonv2", params["format"])
|
||||
assertEquals("5", params["limit"])
|
||||
assertEquals("es", params["accept-language"])
|
||||
assertFalse(params.containsKey("viewbox"))
|
||||
assertFalse(params.containsKey("lat"))
|
||||
assertEquals("A&B? q=other", nominatimSearchParameters("A&B? q=other")["q"])
|
||||
}
|
||||
|
||||
@Test fun `invalid explicit query rejected before HTTP`() {
|
||||
listOf("", " ", "x", "x".repeat(201), "Test\u0000place").forEach { query ->
|
||||
try { nominatimSearchParameters(query); fail("Expected query rejection") }
|
||||
catch (_: IllegalArgumentException) { /* expected */ }
|
||||
}
|
||||
}
|
||||
|
||||
private fun rejects(block: () -> Unit) {
|
||||
try { block(); fail("Expected response rejection") }
|
||||
catch (_: GeocodingResponseException) { /* expected */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class OfflinePlaceTest {
|
||||
@Test fun `search matches accents combining forms and irregular spaces`() {
|
||||
assertEquals("cafe alvaro", normalizePlaceSearch(" CAFÉ\u00a0ÁLVARO\n"))
|
||||
assertEquals(normalizePlaceSearch("José"), normalizePlaceSearch("Jose\u0301"))
|
||||
assertEquals("penaflor", normalizePlaceSearch("Peñaflor"))
|
||||
assertEquals("καφες", normalizePlaceSearch("Καφές"))
|
||||
assertEquals("россия", normalizePlaceSearch("Россия"))
|
||||
assertEquals("a b", normalizePlaceSearch("A\u200bB"))
|
||||
assertEquals("", normalizePlaceSearch(" \n\t"))
|
||||
}
|
||||
|
||||
@Test fun `LIKE literal escaping preserves apostrophes and never treats input as SQL`() {
|
||||
assertEquals("100\\% moto\\_x\\\\y", escapePlaceLike("100% moto_x\\y"))
|
||||
assertEquals("o'connor", escapePlaceLike("o'connor"))
|
||||
assertEquals("' or 1=1 --", escapePlaceLike("' or 1=1 --"))
|
||||
}
|
||||
|
||||
@Test fun `business carries raw opening hours and distinct OSM identity without invented details`() {
|
||||
val place = OfflinePlace("w/123", "Taller test", PlaceCategory.WORKSHOP, GeoPoint(43.36, -5.85))
|
||||
assertNull(place.openingHours)
|
||||
assertNull(place.distanceMeters)
|
||||
assertEquals("Talleres", place.category.labelSpanish)
|
||||
assertNotEquals(place, place.copy(id = "n/123"))
|
||||
assertEquals(5, PlaceCategory.entries.size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import com.google.gson.JsonParser
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class RegionalPackTest {
|
||||
private val fixture = """{"schemaVersion":1,"id":"es-test","name":"Region test","version":"2026-09-28.1",
|
||||
"osmTimestamp":"2026-09-28T20:23:05Z","bounds":{"south":42.7,"west":-4.9,"north":43.9,"east":-3.1},
|
||||
"minZoom":6,"maxZoom":14,"attribution":"© OpenStreetMap contributors","mapSchema":"NavFrame Offline/1.0.0",
|
||||
"poiSchema":1,"glyphs":"noto-sans-regular-0-2047","capabilities":["map","poi"],
|
||||
"source":{"provider":"Geofabrik","extractUrl":"https://download.geofabrik.de/europe/spain/cantabria-latest.osm.pbf",
|
||||
"pbfSha256":"${"d".repeat(64)}","coverageUrl":"https://download.geofabrik.de/europe/spain/cantabria.poly",
|
||||
"coverageSha256":"${"e".repeat(64)}","license":"ODbL-1.0","recipe":"NavFrame regional pack 1.0.0","planetiler":"0.10.2","poiBuilder":"NavFrame POI 1.0.0"},
|
||||
"coverage":{"type":"Polygon","coordinates":[[[-4.9,42.7],[-3.1,42.7],[-3.1,43.9],[-4.9,43.9],[-4.9,42.7]]]},
|
||||
"map":{"path":"map.pmtiles","bytes":10000,"sha256":"${"a".repeat(64)}"},
|
||||
"pois":{"path":"pois.sqlite","bytes":4096,"sha256":"${"b".repeat(64)}"}}"""
|
||||
private fun rejects(value: String) {
|
||||
try { parseRegionalManifest(value); fail("Expected rejection") } catch (error: IllegalArgumentException) {
|
||||
assertEquals("Paquete regional inválido o incompatible", error.message)
|
||||
}
|
||||
}
|
||||
@Test fun `manifest has two original schemas local components and bounded sizes`() {
|
||||
val pack = parseRegionalManifest(fixture)
|
||||
assertEquals(14096L, pack.totalBytes)
|
||||
assertEquals("map.pmtiles", pack.map.path)
|
||||
assertEquals("pois.sqlite", pack.pois.path)
|
||||
assertTrue(pack.covers(GeoPoint(43.4, -3.8)))
|
||||
assertFalse(pack.covers(GeoPoint(43.36, -5.85)))
|
||||
}
|
||||
@Test fun `unsupported routing schemas missing attribution and unsafe paths are rejected`() {
|
||||
listOf(
|
||||
fixture.replace("\"schemaVersion\":1", "\"schemaVersion\":2"),
|
||||
fixture.replace("\"poiSchema\":1", "\"poiSchema\":2"),
|
||||
fixture.replace("NavFrame Offline/1.0.0", "OpenMapTiles"),
|
||||
fixture.replace("\"map\",\"poi\"", "\"map\",\"routing\""),
|
||||
fixture.replace("map.pmtiles", "../map.pmtiles"),
|
||||
fixture.replace("© OpenStreetMap contributors", "unknown"),
|
||||
fixture.replace("noto-sans-regular-0-2047", "https://font.invalid"),
|
||||
fixture.replace("es-test", "../../private"),
|
||||
fixture.replace("Geofabrik", "Unknown"),
|
||||
fixture.replace("download.geofabrik.de/europe/spain/cantabria-latest", "attacker.invalid/cantabria-latest"),
|
||||
fixture.replace("ODbL-1.0", "Proprietary"),
|
||||
fixture.replace("NavFrame regional pack 1.0.0", "unknown recipe"),
|
||||
).forEach(::rejects)
|
||||
}
|
||||
@Test fun `numbers hashes dates and JSON must be strict rather than coerced`() {
|
||||
listOf(
|
||||
fixture.replace("10000", "1.5"), fixture.replace("10000", "9223372036854775808"),
|
||||
fixture.replace("10000", "524288001"), fixture.replace("10000", "\"10000\""),
|
||||
fixture.replace("4096", "-1"), fixture.replace("\"maxZoom\":14", "\"maxZoom\":19"),
|
||||
fixture.replace("43.9", "1e309"), fixture.replace("42.7", "44.0"),
|
||||
fixture.replace("2026-09-28T20:23:05Z", "2026-02-30T20:23:05Z"),
|
||||
fixture.replace("a".repeat(64), "G".repeat(64)), fixture + "{}", "// comment\n$fixture",
|
||||
).forEach(::rejects)
|
||||
}
|
||||
@Test fun `actual coverage differentiates irregular regions holes and edge points`() {
|
||||
val root = JsonParser.parseString(fixture).asJsonObject
|
||||
root.add("coverage", JsonParser.parseString("""{"type":"Polygon","coordinates":[
|
||||
[[-4.8,42.8],[-3.2,42.8],[-4.8,43.8],[-4.8,42.8]],
|
||||
[[-4.7,42.9],[-4.6,42.9],[-4.6,43.0],[-4.7,43.0],[-4.7,42.9]]]}"""))
|
||||
val pack = parseRegionalManifest(root.toString())
|
||||
assertTrue(pack.covers(GeoPoint(43.3, -4.7)))
|
||||
assertFalse(pack.covers(GeoPoint(43.7, -3.3))) // Inside bbox, outside triangle.
|
||||
assertFalse(pack.covers(GeoPoint(42.95, -4.65))) // Hole.
|
||||
assertTrue(pack.covers(GeoPoint(42.8, -4.8))) // Outer boundary.
|
||||
assertFalse(pack.covers(GeoPoint(42.9, -4.7))) // Hole boundary.
|
||||
}
|
||||
@Test fun `malformed coverage rings and unbounded coordinates fail closed`() {
|
||||
val root = JsonParser.parseString(fixture).asJsonObject
|
||||
listOf("""{"type":"Polygon","coordinates":[[[-4,43],[-3.5,43],[-4,43.5]]]}""",
|
||||
"""{"type":"Polygon","coordinates":[[[-20,43],[-3.5,43],[-4,43.5],[-20,43]]]}""",
|
||||
"""{"type":"LineString","coordinates":[]}""").forEach {
|
||||
root.add("coverage", JsonParser.parseString(it)); rejects(root.toString())
|
||||
}
|
||||
}
|
||||
@Test fun `worldwide Geofabrik paths and multipolygon coverage parse`() {
|
||||
val root = JsonParser.parseString(fixture).asJsonObject
|
||||
root.add("bounds", JsonParser.parseString("""{"south":-50,"west":-130,"north":75,"east":-30}"""))
|
||||
val source = root.getAsJsonObject("source")
|
||||
source.addProperty("extractUrl", "https://download.geofabrik.de/north-america/us/texas-latest.osm.pbf")
|
||||
source.addProperty("coverageUrl", "https://download.geofabrik.de/north-america/us/texas.poly")
|
||||
root.add("coverage", JsonParser.parseString("""{"type":"MultiPolygon","coordinates":[
|
||||
[[[ -100,30],[-99,30],[-99,31],[-100,31],[-100,30]]],
|
||||
[[[-98,32],[-97,32],[-97,33],[-98,33],[-98,32]]]]}"""))
|
||||
val manifest = parseRegionalManifest(root.toString())
|
||||
assertTrue(manifest.covers(GeoPoint(30.5, -99.5)))
|
||||
assertTrue(manifest.covers(GeoPoint(32.5, -97.5)))
|
||||
assertFalse(manifest.covers(GeoPoint(31.5, -98.5)))
|
||||
}
|
||||
@Test fun `worldwide recipe accepts camera-enabled catalogs without breaking legacy packs`() {
|
||||
val updated = fixture.replace("NavFrame regional pack 1.0.0", "NavFrame regional pack 1.1.0")
|
||||
.replace("NavFrame POI 1.0.0", "NavFrame POI 1.1.0")
|
||||
assertEquals("NavFrame regional pack 1.1.0", parseRegionalManifest(updated).source.recipe)
|
||||
assertEquals("NavFrame regional pack 1.0.0", parseRegionalManifest(fixture).source.recipe)
|
||||
}
|
||||
@Test fun `local catalog validates original entries without fabricated remote endpoints`() {
|
||||
val item = """{"manifest":$fixture,"archive":{"path":"es-test-20260928.navframe","bytes":20000,"sha256":"${"c".repeat(64)}"}}"""
|
||||
val json = """{"schemaVersion":1,"regions":[$item]}"""
|
||||
val catalog = parseRegionalCatalog(json)
|
||||
assertEquals("es-test-20260928.navframe", catalog.regions.single().archive.path)
|
||||
listOf(json.replace("es-test-20260928.navframe", "../../private.navframe"),
|
||||
json.replace("es-test-20260928.navframe", "https://endpoint.invalid/file.navframe"),
|
||||
"""{"schemaVersion":1,"regions":[$item,$item]}""").forEach {
|
||||
try { parseRegionalCatalog(it); fail("Expected rejection") } catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
}
|
||||
@Test fun `global catalog optional release URL and region metadata preserve local entries`() {
|
||||
val item = """{"manifest":$fixture,"archive":{"path":"es-test-20260928.navframe","bytes":20000,
|
||||
"sha256":"${"c".repeat(64)}","url":"https://github.com/example/navframe/releases/download/v1/es-test-20260928.navframe"},
|
||||
"countryCode":"ES","country":"Spain","region":"spain/cantabria","cameraCount":22}"""
|
||||
val entry = parseRegionalCatalog("""{"schemaVersion":1,"regions":[$item]}""").regions.single()
|
||||
assertEquals("https://github.com/example/navframe/releases/download/v1/es-test-20260928.navframe", entry.archive.url)
|
||||
assertEquals("ES", entry.countryCode)
|
||||
assertEquals("Spain", entry.country)
|
||||
assertEquals("spain/cantabria", entry.region)
|
||||
assertEquals(22, entry.cameraCount)
|
||||
|
||||
val old = """{"manifest":$fixture,"archive":{"path":"es-test-20260928.navframe","bytes":20000,"sha256":"${"c".repeat(64)}"}}"""
|
||||
assertNull(parseRegionalCatalog("""{"schemaVersion":1,"regions":[$old]}""").regions.single().archive.url)
|
||||
listOf(item.replace("https://github.com", "http://github.com"), item.replace("\"ES\"", "\"Spain\""), item.replace("\"cameraCount\":22", "\"cameraCount\":-1")).forEach {
|
||||
try { parseRegionalCatalog("""{"schemaVersion":1,"regions":[$it]}"""); fail("Expected rejection") } catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class RenderSchedulerTest {
|
||||
private fun state(speed: Float = 0f, bearing: Float = 0f, lat: Double = 43.0) =
|
||||
NavigationState(position = GeoPoint(lat, -5.0), speed = speed, bearing = bearing)
|
||||
|
||||
@Test fun stationaryUnchangedDoesNotRedrawEvenAfterLongWait() {
|
||||
val scheduler = RenderScheduler()
|
||||
assertTrue(scheduler.renderIfDue(state(), 0))
|
||||
assertFalse(scheduler.renderIfDue(state(), 60_000))
|
||||
}
|
||||
|
||||
@Test fun stationaryPositionAndHeadingJitterDoesNotRedraw() {
|
||||
val scheduler = RenderScheduler()
|
||||
scheduler.renderIfDue(state(), 0)
|
||||
assertFalse(scheduler.renderIfDue(state(bearing = 90f, lat = 43.000005), 5_000))
|
||||
}
|
||||
|
||||
@Test fun stationaryUiChangesRespectOneFpsMaximum() {
|
||||
val scheduler = RenderScheduler()
|
||||
scheduler.renderIfDue(state(), 0)
|
||||
val changed = state().copy(navigationStatus = NavigationStatus.GPS_LOST)
|
||||
assertFalse(scheduler.renderIfDue(changed, 999))
|
||||
assertTrue(scheduler.renderIfDue(changed, 1_000))
|
||||
}
|
||||
|
||||
@Test fun movingPositionUpdatesRespectFiveFpsMaximum() {
|
||||
val scheduler = RenderScheduler()
|
||||
scheduler.renderIfDue(state(speed = 8f), 0)
|
||||
val moved = state(speed = 8f, lat = 43.0001)
|
||||
assertFalse(scheduler.renderIfDue(moved, 199))
|
||||
assertTrue(scheduler.renderIfDue(moved, 200))
|
||||
}
|
||||
|
||||
@Test fun rapidTurnCanRenderAtTenFps() {
|
||||
val scheduler = RenderScheduler()
|
||||
scheduler.renderIfDue(state(speed = 8f), 0)
|
||||
val turned = state(speed = 8f, bearing = 20f)
|
||||
assertFalse(scheduler.renderIfDue(turned, 99))
|
||||
assertTrue(scheduler.renderIfDue(turned, 100))
|
||||
}
|
||||
|
||||
@Test fun compassNorthWrapIsSmallChangeRatherThanRapidTurn() {
|
||||
val scheduler = RenderScheduler()
|
||||
scheduler.renderIfDue(state(speed = 8f, bearing = 359f), 0)
|
||||
assertFalse(scheduler.renderIfDue(state(speed = 8f, bearing = 1f), 50))
|
||||
assertFalse(scheduler.renderIfDue(state(speed = 8f, bearing = 4f), 100))
|
||||
assertTrue(scheduler.renderIfDue(state(speed = 8f, bearing = 4f), 200))
|
||||
}
|
||||
|
||||
@Test fun queuedStateIsReplacedWithLatestWhileThrottled() {
|
||||
val scheduler = RenderScheduler()
|
||||
scheduler.renderIfDue(state(speed = 8f), 0)
|
||||
scheduler.offer(state(speed = 8f, lat = 43.0001))
|
||||
assertNull(scheduler.takeIfDue(100))
|
||||
val newest = state(speed = 8f, lat = 43.0002)
|
||||
scheduler.offer(newest)
|
||||
assertEquals(newest, scheduler.takeIfDue(200))
|
||||
scheduler.markRendered(newest, 200)
|
||||
assertNull(scheduler.takeIfDue(400))
|
||||
}
|
||||
|
||||
@Test fun newManeuverAndLabelChangeRenderWithoutPositionChange() {
|
||||
val scheduler = RenderScheduler()
|
||||
val first = state().copy(nextManeuver = Maneuver("derecha", 350), distanceToNextManeuverMeters = 350)
|
||||
scheduler.renderIfDue(first, 0)
|
||||
assertTrue(scheduler.renderIfDue(first.copy(nextManeuver = Maneuver("izquierda", 350)), 1_000))
|
||||
assertTrue(scheduler.renderIfDue(first.copy(nextManeuver = Maneuver("izquierda", 350), distanceToNextManeuverMeters = 330), 2_000))
|
||||
}
|
||||
|
||||
@Test fun etaOnlyChangesRenderedMinuteRatherThanEverySecond() {
|
||||
val scheduler = RenderScheduler()
|
||||
val first = state().copy(etaEpochMillis = 120_000)
|
||||
scheduler.renderIfDue(first, 0)
|
||||
assertFalse(scheduler.renderIfDue(first.copy(etaEpochMillis = 121_000), 1_000))
|
||||
assertTrue(scheduler.renderIfDue(first.copy(etaEpochMillis = 180_000), 2_000))
|
||||
}
|
||||
|
||||
@Test fun configurablePolicyChangesMovementThresholdAndRate() {
|
||||
val scheduler = RenderScheduler(RenderScheduleConfig(movingMaxFps = 2.0, positionDeltaMeters = 20.0))
|
||||
scheduler.renderIfDue(state(speed = 8f), 0)
|
||||
assertFalse(scheduler.renderIfDue(state(speed = 8f, lat = 43.0001), 100))
|
||||
val moved = state(speed = 8f, lat = 43.0003)
|
||||
assertFalse(scheduler.renderIfDue(moved, 499))
|
||||
assertTrue(scheduler.renderIfDue(moved, 500))
|
||||
}
|
||||
|
||||
@Test fun resetAndRestartedMonotonicClockAllowFirstFrameImmediately() {
|
||||
val scheduler = RenderScheduler()
|
||||
scheduler.renderIfDue(state(), 10_000)
|
||||
assertTrue(scheduler.renderIfDue(state(), 100))
|
||||
scheduler.reset()
|
||||
assertTrue(scheduler.renderIfDue(state(), 101))
|
||||
}
|
||||
|
||||
@Test fun failedRenderDoesNotCommitAndNewerFixSurvivesOlderRenderCompletion() {
|
||||
val scheduler = RenderScheduler()
|
||||
val first = state(speed = 8f)
|
||||
scheduler.offer(first)
|
||||
assertEquals(first, scheduler.takeIfDue(0))
|
||||
// Encoding failed: querying again still yields the first frame, without waiting.
|
||||
assertEquals(first, scheduler.takeIfDue(1))
|
||||
val newest = first.copy(position = GeoPoint(43.0002, -5.0))
|
||||
scheduler.offer(newest)
|
||||
scheduler.markRendered(first, 2)
|
||||
assertNull(scheduler.takeIfDue(100))
|
||||
assertEquals(newest, scheduler.takeIfDue(202))
|
||||
}
|
||||
|
||||
private fun RenderScheduler.renderIfDue(state: NavigationState, nowMs: Long): Boolean {
|
||||
val due = shouldRender(state, nowMs)
|
||||
if (due) markRendered(state, nowMs)
|
||||
return due
|
||||
}
|
||||
|
||||
@Test fun stationaryAccuracyAndBearingAvailabilityChangesAreVisible() {
|
||||
val scheduler = RenderScheduler()
|
||||
val first = state().copy(accuracyMeters = 5f)
|
||||
scheduler.renderIfDue(first, 0)
|
||||
assertFalse(scheduler.renderIfDue(first.copy(accuracyMeters = 6f), 1_000))
|
||||
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = 10f), 2_000))
|
||||
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = null), 3_000))
|
||||
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = null, bearing = Float.NaN), 4_000))
|
||||
}
|
||||
|
||||
@Test fun invalidConfigurationIsRejected() {
|
||||
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(movingMaxFps = Double.NaN) }
|
||||
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(distanceLabelStepMeters = 0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class RouteGuidanceTest {
|
||||
// Equatorial segments are ~111.2m each; original route duration is 30 seconds.
|
||||
private val route = RouteResult(
|
||||
listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.001), GeoPoint(0.001, 0.001)),
|
||||
listOf(Maneuver("Start", 111, 1, 0, 1, 15), Maneuver("Left", 111, 15, 1, 2, 15), Maneuver("Arrive", 0, 4, 2, 2)),
|
||||
222, 30,
|
||||
)
|
||||
private fun fix(lat: Double = 0.0, lon: Double = 0.0, time: Long = 1, accuracy: Float = 5f, speed: Float = 12f) =
|
||||
LocationFix(GeoPoint(lat, lon), 90f, speed, accuracy, time)
|
||||
|
||||
@Test fun `projection yields next turn countdown remaining and estimated ETA`() {
|
||||
val state = RouteGuidanceTracker(route).update(fix(lon = 0.0005), 0, 100_000)
|
||||
assertEquals(NavigationStatus.NAVIGATING, state.navigationStatus)
|
||||
assertEquals("Left", state.nextManeuver!!.instruction)
|
||||
assertEquals(56, state.distanceToNextManeuverMeters!!)
|
||||
assertEquals(167, state.remainingDistanceMeters!!)
|
||||
assertEquals(122_500L, state.etaEpochMillis!!)
|
||||
}
|
||||
|
||||
@Test fun `jitter never moves countdown backwards and crossed turn advances with margin`() {
|
||||
val tracker = RouteGuidanceTracker(route)
|
||||
val a = tracker.update(fix(lon = 0.0008), 0, 0)
|
||||
val jitter = tracker.update(fix(lon = 0.00075, time = 2), 1_000, 1_000)
|
||||
assertEquals(a.remainingDistanceMeters, jitter.remainingDistanceMeters)
|
||||
assertEquals("Left", jitter.nextManeuver!!.instruction)
|
||||
val crossed = tracker.update(fix(lat = 0.0001, lon = 0.001, time = 3), 2_000, 2_000)
|
||||
assertEquals("Arrive", crossed.nextManeuver!!.instruction)
|
||||
assertEquals(100, crossed.distanceToNextManeuverMeters!!)
|
||||
}
|
||||
|
||||
@Test fun `off route requires distinct fresh fixes time and resets after jitter recovery`() {
|
||||
val tracker = RouteGuidanceTracker(route)
|
||||
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005), 0, 0).navigationStatus)
|
||||
// Ticks on the same fix do not satisfy either count or sustained-duration confirmation.
|
||||
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005), 8_000, 8_000).navigationStatus)
|
||||
tracker.update(fix(lat = -0.0005, time = 2), 9_000, 9_000)
|
||||
val outside = tracker.update(fix(lat = -0.0005, time = 3), 10_000, 10_000)
|
||||
assertEquals(NavigationStatus.OFF_ROUTE, outside.navigationStatus)
|
||||
assertNull(outside.nextManeuver)
|
||||
assertNull(outside.distanceToNextManeuverMeters)
|
||||
assertNull(outside.etaEpochMillis)
|
||||
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(time = 4), 11_000, 11_000).navigationStatus)
|
||||
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005, time = 5), 12_000, 12_000).navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `a long gap breaks consecutive deviation evidence`() {
|
||||
val tracker = RouteGuidanceTracker(route)
|
||||
tracker.update(fix(lat = -0.0005), 0, 0)
|
||||
tracker.update(fix(lat = -0.0005, time = 2), 3_000, 0)
|
||||
val resumed = tracker.update(fix(lat = -0.0005, time = 3), 30_000, 0)
|
||||
assertEquals(NavigationStatus.GPS_LOST, resumed.navigationStatus)
|
||||
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005, time = 4), 31_000, 0).navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `accuracy margin rejects jitter at forty five meters with twenty five meter accuracy`() {
|
||||
val tracker = RouteGuidanceTracker(route)
|
||||
for (i in 1..5) {
|
||||
val state = tracker.update(fix(lat = -0.0004, time = i.toLong(), accuracy = 25f), i * 3_000L, 0)
|
||||
assertEquals(NavigationStatus.NAVIGATING, state.navigationStatus)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `poor stale invalid fixes cannot confirm deviation or arrival`() {
|
||||
listOf(Float.NaN, Float.POSITIVE_INFINITY, 26f, -1f).forEach { accuracy ->
|
||||
val state = RouteGuidanceTracker(route).update(fix(accuracy = accuracy), 0, 0)
|
||||
assertEquals(NavigationStatus.GPS_LOST, state.navigationStatus)
|
||||
assertNull(state.nextManeuver)
|
||||
assertNull(state.etaEpochMillis)
|
||||
}
|
||||
val tracker = RouteGuidanceTracker(route)
|
||||
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(), 0, 0, 15_001).navigationStatus)
|
||||
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(lat = Double.NaN), 1_000, 0).navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `arrival requires endpoint geometry repeated fixes and time then stays arrived`() {
|
||||
val tracker = RouteGuidanceTracker(route)
|
||||
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.001, 0.001), 0, 0).navigationStatus)
|
||||
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.001, 0.001), 5_000, 0).navigationStatus)
|
||||
tracker.update(fix(0.001, 0.001, time = 2), 6_000, 0)
|
||||
val arrived = tracker.update(fix(0.001, 0.001, time = 3), 7_000, 0)
|
||||
assertEquals(NavigationStatus.ARRIVED, arrived.navigationStatus)
|
||||
assertNull(arrived.nextManeuver)
|
||||
assertEquals(0, arrived.remainingDistanceMeters!!)
|
||||
assertEquals(NavigationStatus.ARRIVED, tracker.update(fix(0.0009, 0.001, time = 4), 8_000, 0).navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `isolated jump and return cannot advance route or cause reroute`() {
|
||||
val tracker = RouteGuidanceTracker(route)
|
||||
val start = tracker.update(fix(), 0, 0)
|
||||
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(0.001, 0.001, time = 2), 100, 0).navigationStatus)
|
||||
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(time = 3), 200, 0).navigationStatus)
|
||||
val recovered = tracker.update(fix(time = 4), 300, 0)
|
||||
assertEquals(start.remainingDistanceMeters, recovered.remainingDistanceMeters)
|
||||
assertEquals(NavigationStatus.NAVIGATING, recovered.navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `crossing route does not jump forward to distant later branch`() {
|
||||
val crossing = route.copy(geometry = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.002),
|
||||
GeoPoint(0.002, 0.002), GeoPoint(0.002, 0.0), GeoPoint(0.0, 0.0), GeoPoint(0.0, -0.002)), maneuvers = emptyList())
|
||||
val tracker = RouteGuidanceTracker(crossing)
|
||||
val initial = tracker.update(fix(), 0, 0)
|
||||
val next = tracker.update(fix(lon = -0.00005, time = 2), 1_000, 0)
|
||||
assertEquals(initial.remainingDistanceMeters, next.remainingDistanceMeters)
|
||||
assertEquals(NavigationStatus.NAVIGATING, next.navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `dateline projection follows short segment`() {
|
||||
val crossing = RouteResult(listOf(GeoPoint(0.0, 179.999), GeoPoint(0.0, -179.999)), emptyList(), 222, 30)
|
||||
val state = RouteGuidanceTracker(crossing).update(fix(lon = 180.0), 0, 0)
|
||||
assertEquals(111, state.remainingDistanceMeters!!)
|
||||
}
|
||||
|
||||
@Test fun `reroute policy single flight cooldown and retry after suppress loops`() {
|
||||
val policy = ReroutePolicy()
|
||||
val off = NavigationState(navigationStatus = NavigationStatus.OFF_ROUTE)
|
||||
assertTrue(policy.shouldRequest(off, 0))
|
||||
policy.markRequested(0)
|
||||
assertFalse(policy.shouldRequest(off, 100_000))
|
||||
policy.markFinished(1_000, retryAfterMs = 60_000)
|
||||
assertFalse(policy.shouldRequest(off, 60_999))
|
||||
assertTrue(policy.shouldRequest(off, 61_000))
|
||||
assertFalse(policy.shouldRequest(off.copy(navigationStatus = NavigationStatus.GPS_LOST), 61_000))
|
||||
policy.reset()
|
||||
assertTrue(policy.shouldRequest(off, 0))
|
||||
}
|
||||
|
||||
@Test fun `demo is deterministic interpolated and includes guidance then arrival`() {
|
||||
val demo = RouteDemo(route)
|
||||
val state = demo.stateAt(5_000, 100_000)
|
||||
assertEquals(state, demo.stateAt(5_000, 100_000))
|
||||
assertEquals("Left", state.nextManeuver!!.instruction)
|
||||
assertEquals(51, state.distanceToNextManeuverMeters!!)
|
||||
assertEquals(12f, state.speed, 0f)
|
||||
assertEquals(0.0005396, state.position.longitude, 0.000001)
|
||||
assertEquals(90f, state.bearing, 0.1f)
|
||||
val arrived = demo.stateAt(30_000, 130_000)
|
||||
assertEquals(NavigationStatus.ARRIVED, arrived.navigationStatus)
|
||||
assertEquals(route.geometry.last(), arrived.position)
|
||||
assertNull(arrived.nextManeuver)
|
||||
}
|
||||
|
||||
@Test fun `repeated ticks preserve movement baseline until new fix`() {
|
||||
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), emptyList(), 1112, 100)
|
||||
val tracker = RouteGuidanceTracker(longRoute)
|
||||
val original = fix(speed = 30f)
|
||||
tracker.update(original, 0, 0)
|
||||
for (tick in 1..49) tracker.update(original, tick * 100L, 0)
|
||||
val moved = tracker.update(fix(lon = 0.0015, time = 2, speed = 30f), 5_000, 0)
|
||||
assertEquals(NavigationStatus.NAVIGATING, moved.navigationStatus)
|
||||
assertEquals(945, moved.remainingDistanceMeters!!)
|
||||
}
|
||||
|
||||
@Test fun `first acquisition can begin far inside calculated route`() {
|
||||
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), emptyList(), 1112, 100)
|
||||
val tracker = RouteGuidanceTracker(longRoute)
|
||||
val midway = tracker.update(fix(lon = 0.005), 0, 0)
|
||||
assertEquals(556, midway.remainingDistanceMeters!!)
|
||||
assertEquals(534, tracker.update(fix(lon = 0.0052, time = 2), 2_000, 0).remainingDistanceMeters!!)
|
||||
}
|
||||
|
||||
@Test fun `start right and start left are departure instructions not upcoming turns`() {
|
||||
for (startType in 1..3) {
|
||||
val withDeparture = route.copy(maneuvers = listOf(route.maneuvers.first().copy(type = startType)) + route.maneuvers.drop(1))
|
||||
assertEquals("Left", RouteGuidanceTracker(withDeparture).update(fix(), 0, 0).nextManeuver!!.instruction)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `GPS recovery needs two new stable fixes and ignores absent time for movement`() {
|
||||
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.02)), emptyList(), 2224, 100)
|
||||
val tracker = RouteGuidanceTracker(longRoute)
|
||||
tracker.update(fix(speed = 25f), 0, 0)
|
||||
val first = tracker.update(fix(lon = 0.01, time = 2, speed = 25f), 60_000, 0)
|
||||
assertEquals(NavigationStatus.GPS_LOST, first.navigationStatus)
|
||||
assertNull(first.nextManeuver)
|
||||
val second = tracker.update(fix(lon = 0.0101, time = 3, speed = 25f), 61_000, 0)
|
||||
assertEquals(NavigationStatus.NAVIGATING, second.navigationStatus)
|
||||
assertEquals(1101, second.remainingDistanceMeters!!)
|
||||
}
|
||||
|
||||
@Test fun `ambiguous distant on route jump does not show old turn guidance`() {
|
||||
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), emptyList(), 1112, 100)
|
||||
val tracker = RouteGuidanceTracker(longRoute)
|
||||
tracker.update(fix(), 0, 0)
|
||||
tracker.update(fix(lon = 0.005, time = 2), 1_000, 0)
|
||||
val stableButDistant = tracker.update(fix(lon = 0.005, time = 3), 2_000, 0)
|
||||
assertEquals(NavigationStatus.GPS_LOST, stableButDistant.navigationStatus)
|
||||
assertNull(stableButDistant.remainingDistanceMeters)
|
||||
assertNull(stableButDistant.nextManeuver)
|
||||
}
|
||||
|
||||
@Test fun `maneuver arrows use type rather than translated prose`() {
|
||||
assertEquals(ManeuverDirection.LEFT, maneuverDirection(15))
|
||||
assertEquals(ManeuverDirection.RIGHT, maneuverDirection(10))
|
||||
assertEquals(ManeuverDirection.UTURN, maneuverDirection(12))
|
||||
assertEquals(ManeuverDirection.ROUNDABOUT, maneuverDirection(26))
|
||||
assertEquals(ManeuverDirection.ARRIVAL, maneuverDirection(6))
|
||||
assertEquals(ManeuverDirection.UNKNOWN, maneuverDirection(null))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dev.navframe.core
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
class SpeedCameraTest {
|
||||
private val camera = SpeedCamera("n/1", GeoPoint(43.004, -5.0))
|
||||
private val route = RouteResult(listOf(GeoPoint(43.0,-5.0), GeoPoint(43.01,-5.0)), emptyList(), 1100, 100)
|
||||
private fun fix(lat: Double, accuracy: Float = 5f, bearing: Float = 0f) = LocationFix(GeoPoint(lat,-5.0),bearing,15f,accuracy,0)
|
||||
@Test fun approachAlertsOnce() {
|
||||
val engine = SpeedCameraAlertEngine()
|
||||
assertNull(engine.update(fix(43.0),listOf(camera),0,route=route))
|
||||
val alert = engine.update(fix(43.0001),listOf(camera),1000,route=route)
|
||||
assertNotNull(alert)
|
||||
assertNull(engine.update(fix(43.0002),listOf(camera),2000,route=route))
|
||||
}
|
||||
@Test fun uncertainOrStaleGpsAndRecedingDoNotAlert() {
|
||||
for (bad in listOf(fix(43.0001,50f), fix(43.0001,bearing=180f))) {
|
||||
val engine = SpeedCameraAlertEngine()
|
||||
engine.update(fix(43.0),listOf(camera),0,route=route)
|
||||
assertNull(engine.update(bad,listOf(camera),1000,route=route))
|
||||
}
|
||||
val engine = SpeedCameraAlertEngine()
|
||||
engine.update(fix(43.0002),listOf(camera),0,route=route)
|
||||
assertNull(engine.update(fix(43.0001),listOf(camera),1000,route=route))
|
||||
assertNull(engine.update(fix(43.0003),listOf(camera),2000,6000,route))
|
||||
}
|
||||
@Test fun absentRouteAndParallelRoadDoNotAlert() {
|
||||
val engine = SpeedCameraAlertEngine()
|
||||
assertNull(engine.update(fix(43.0),listOf(camera),0))
|
||||
val offRoute = camera.copy(position=GeoPoint(43.004,-5.001))
|
||||
engine.update(fix(43.0),listOf(offRoute),0,route=route)
|
||||
assertNull(engine.update(fix(43.0001),listOf(offRoute),1000,route=route))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class TftSessionRunnerTest {
|
||||
private fun frame(value: Byte) = TftFrame(encodedBytes = byteArrayOf(value), timestampMs = value.toLong())
|
||||
private class Transport : TftTransport {
|
||||
override val connectionState = MutableStateFlow(ConnectionState.DISCONNECTED)
|
||||
var connects = 0
|
||||
var disconnects = 0
|
||||
val sent = mutableListOf<TftFrame>()
|
||||
var connectAction: suspend () -> Unit = {}
|
||||
var sendAction: suspend () -> Unit = {}
|
||||
override suspend fun connect() { connects++; connectAction(); connectionState.value = ConnectionState.CONNECTED }
|
||||
override suspend fun disconnect() { disconnects++; connectionState.value = ConnectionState.DISCONNECTED }
|
||||
override suspend fun sendFrame(frame: TftFrame) { sent += frame; sendAction() }
|
||||
}
|
||||
|
||||
@Test fun slowAckNeverCausesBacklogOrBusyLoop() {
|
||||
val policy = TftSessionPolicy()
|
||||
assertEquals(900L, policy.framePauseMs(100))
|
||||
assertEquals(50L, policy.framePauseMs(2_000))
|
||||
assertEquals(1_000L, policy.framePauseMs(-20))
|
||||
}
|
||||
|
||||
@Test fun movementCadenceSupportsFiveAndTenFpsWithAckBackpressure() {
|
||||
assertEquals(120L, TftSessionPolicy(200).framePauseMs(80))
|
||||
assertEquals(80L, TftSessionPolicy(100).framePauseMs(20))
|
||||
assertEquals(50L, TftSessionPolicy(100).framePauseMs(120))
|
||||
}
|
||||
|
||||
@Test fun changesFromIdleToMovementCadenceWithoutSecondWriter() = runBlocking {
|
||||
val current = Transport()
|
||||
val started = Channel<Unit>(Channel.UNLIMITED)
|
||||
val ack = Channel<Unit>(Channel.UNLIMITED)
|
||||
val waiting = Channel<Long>(Channel.UNLIMITED)
|
||||
val tick = Channel<Unit>(Channel.UNLIMITED)
|
||||
var cadence = 1_000L
|
||||
var now = 0L
|
||||
var cached = frame(1)
|
||||
current.sendAction = { started.send(Unit); ack.receive() }
|
||||
val runner = TftSessionRunner({ current }, { cached }, { TftSessionPolicy(cadence) }, { now },
|
||||
pause = { waiting.send(it); tick.receive() })
|
||||
val job = launch { runner.run() }
|
||||
try {
|
||||
withTimeout(3_000) {
|
||||
started.receive()
|
||||
now = 100
|
||||
ack.send(Unit)
|
||||
assertEquals(900L, waiting.receive())
|
||||
cadence = 200
|
||||
cached = frame(2)
|
||||
tick.send(Unit)
|
||||
started.receive()
|
||||
assertSame(cached, current.sent[1])
|
||||
now = 180
|
||||
ack.send(Unit)
|
||||
assertEquals(120L, waiting.receive())
|
||||
assertEquals(1, current.connects)
|
||||
assertEquals(2, current.sent.size)
|
||||
}
|
||||
} finally { job.cancelAndJoin() }
|
||||
assertEquals(1, current.disconnects)
|
||||
}
|
||||
|
||||
@Test fun invalidCadenceFailsRatherThanCreatingTightLoop() {
|
||||
for (interval in listOf(0L, 99L, 3_001L)) {
|
||||
assertThrows(IllegalArgumentException::class.java) { TftSessionPolicy(interval) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun cachedImageUpdatesOnlyAfterPendingAckAndCadence() = runBlocking {
|
||||
val current = Transport()
|
||||
val sendStarted = Channel<Unit>(Channel.UNLIMITED)
|
||||
val ack = Channel<Unit>(Channel.UNLIMITED)
|
||||
val waiting = Channel<Long>(Channel.UNLIMITED)
|
||||
val tick = Channel<Unit>(Channel.UNLIMITED)
|
||||
current.sendAction = { sendStarted.send(Unit); ack.receive() }
|
||||
var cached = frame(1)
|
||||
val runner = TftSessionRunner({ current }, { cached }, { TftSessionPolicy() }, { 0 },
|
||||
pause = { waiting.send(it); tick.receive() })
|
||||
val job = launch { runner.run() }
|
||||
try {
|
||||
withTimeout(3_000) {
|
||||
sendStarted.receive()
|
||||
cached = frame(2)
|
||||
yield()
|
||||
assertEquals(1, current.sent.size) // No overlapping send while CCU ACK is outstanding.
|
||||
ack.send(Unit)
|
||||
assertEquals(1_000L, waiting.receive())
|
||||
assertEquals(1, current.sent.size) // ACK alone does not bypass cadence.
|
||||
tick.send(Unit)
|
||||
sendStarted.receive()
|
||||
assertSame(cached, current.sent[1])
|
||||
assertEquals(1, current.connects)
|
||||
}
|
||||
} finally { job.cancelAndJoin() }
|
||||
assertEquals(1, current.disconnects)
|
||||
}
|
||||
|
||||
@Test fun failedConnectionsBackOffAndReuseFrameAfterRecovery() = runBlocking {
|
||||
val transports = mutableListOf<Transport>()
|
||||
val retries = mutableListOf<Long>()
|
||||
val reachedSend = CompletableDeferred<Unit>()
|
||||
val hold = CompletableDeferred<Unit>()
|
||||
val cached = frame(7)
|
||||
val runner = TftSessionRunner(
|
||||
transportFactory = {
|
||||
Transport().also {
|
||||
if (transports.size < 5) it.connectAction = { error("CCU unavailable") }
|
||||
else it.sendAction = { reachedSend.complete(Unit); hold.await() }
|
||||
transports += it
|
||||
}
|
||||
}, latestFrame = { cached }, policy = { TftSessionPolicy() }, clockMs = { 0 },
|
||||
pause = { retries += it },
|
||||
)
|
||||
val job = launch { runner.run() }
|
||||
try {
|
||||
withTimeout(3_000) { reachedSend.await() }
|
||||
assertEquals(listOf(1_000L, 2_000L, 4_000L, 8_000L, 15_000L), retries)
|
||||
assertTrue(transports.take(5).all { it.disconnects == 1 })
|
||||
assertSame(cached, transports.last().sent.single())
|
||||
} finally { job.cancelAndJoin() }
|
||||
assertEquals(1, transports.last().disconnects)
|
||||
}
|
||||
|
||||
@Test fun stopDuringRetryPreventsAnotherConnection() = runBlocking {
|
||||
val current = Transport().apply { connectAction = { error("Disconnected") } }
|
||||
val waiting = CompletableDeferred<Unit>()
|
||||
val hold = CompletableDeferred<Unit>()
|
||||
val runner = TftSessionRunner({ current }, { frame(1) }, { TftSessionPolicy() }, { 0 },
|
||||
pause = { waiting.complete(Unit); hold.await() })
|
||||
val job = launch { runner.run() }
|
||||
withTimeout(3_000) { waiting.await() }
|
||||
job.cancelAndJoin()
|
||||
assertEquals(1, current.connects)
|
||||
assertEquals(1, current.disconnects)
|
||||
assertTrue(current.sent.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun successfulFrameResetsBackoffBeforeLaterDrop() = runBlocking {
|
||||
var attempt = 0
|
||||
val retries = mutableListOf<Long>()
|
||||
val stopAtThird = CompletableDeferred<Unit>()
|
||||
val hold = CompletableDeferred<Unit>()
|
||||
val runner = TftSessionRunner(
|
||||
transportFactory = {
|
||||
val number = ++attempt
|
||||
Transport().apply {
|
||||
if (number == 1) connectAction = { error("First handshake failed") }
|
||||
if (number == 2) {
|
||||
var sends = 0
|
||||
sendAction = { if (++sends > 1) error("Link dropped after ACK") }
|
||||
}
|
||||
if (number == 3) connectAction = { stopAtThird.complete(Unit); hold.await() }
|
||||
}
|
||||
}, latestFrame = { frame(1) }, policy = { TftSessionPolicy() }, clockMs = { 0 },
|
||||
pause = {}, onRetry = { _, millis -> retries += millis },
|
||||
)
|
||||
val job = launch { runner.run() }
|
||||
try {
|
||||
withTimeout(3_000) { stopAtThird.await() }
|
||||
assertEquals(listOf(1_000L, 1_000L), retries)
|
||||
} finally { job.cancelAndJoin() }
|
||||
}
|
||||
|
||||
@Test fun transportLocalAckTimeoutRetriesRatherThanCancellingSession() = runBlocking {
|
||||
var attempt = 0
|
||||
val recovered = CompletableDeferred<Unit>()
|
||||
val hold = CompletableDeferred<Unit>()
|
||||
val retryWaits = mutableListOf<Long>()
|
||||
val runner = TftSessionRunner(
|
||||
transportFactory = {
|
||||
val number = ++attempt
|
||||
Transport().apply {
|
||||
sendAction = {
|
||||
if (number == 1) withTimeout(5) { awaitCancellation() }
|
||||
else { recovered.complete(Unit); hold.await() }
|
||||
}
|
||||
}
|
||||
}, latestFrame = { frame(1) }, policy = { TftSessionPolicy() }, clockMs = { 0 },
|
||||
pause = {}, onRetry = { _, millis -> retryWaits += millis },
|
||||
)
|
||||
val job = launch { runner.run() }
|
||||
try {
|
||||
withTimeout(3_000) { recovered.await() }
|
||||
assertTrue(job.isActive)
|
||||
assertEquals(2, attempt)
|
||||
assertEquals(listOf(1_000L), retryWaits)
|
||||
} finally { job.cancelAndJoin() }
|
||||
assertEquals(2, attempt)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import com.google.gson.JsonParser
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ValhallaRouteTest {
|
||||
private val fixture get() = javaClass.getResource("/valhalla-route.json")!!.readText()
|
||||
|
||||
@Test fun `precision six preserves known coordinates`() {
|
||||
val decoded = decodePolyline6("_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI")
|
||||
assertEquals(listOf(GeoPoint(38.5, -120.2), GeoPoint(40.7, -120.95), GeoPoint(43.252, -126.453)), decoded)
|
||||
}
|
||||
|
||||
@Test fun `parse route converts kilometers and preserves segment indices and destination`() {
|
||||
val destination = GeoPoint(43.36031, -5.85012)
|
||||
val route = parseValhallaRoute(fixture, destination)
|
||||
assertEquals(listOf(GeoPoint(43.36, -5.85), GeoPoint(43.3601, -5.8502), GeoPoint(43.3603, -5.8501)), route.geometry)
|
||||
assertEquals(52, route.distanceMeters)
|
||||
assertEquals(17, route.durationSeconds)
|
||||
assertEquals(destination, route.destination)
|
||||
assertEquals(31, route.maneuvers[0].distanceMeters)
|
||||
assertEquals(listOf("Calle de prueba"), route.maneuvers[0].streetNames)
|
||||
assertEquals(10, route.maneuvers[1].type)
|
||||
assertEquals(1, route.maneuvers[1].beginShapeIndex)
|
||||
assertEquals(2, route.maneuvers[1].endShapeIndex)
|
||||
assertEquals(0, route.maneuvers.last().distanceMeters)
|
||||
}
|
||||
|
||||
@Test fun `miles conversion is explicit`() {
|
||||
val route = parseValhallaRoute(fixture.replace("kilometers", "miles").replace("0.052", "1.0"))
|
||||
assertEquals(1609, route.distanceMeters)
|
||||
assertEquals(50, route.maneuvers.first().distanceMeters)
|
||||
}
|
||||
|
||||
@Test fun `multiple legs deduplicate join and rebase indices`() {
|
||||
val root = JsonParser.parseString(fixture).asJsonObject
|
||||
val trip = root.getAsJsonObject("trip")
|
||||
val legs = trip.getAsJsonArray("legs")
|
||||
val next = legs[0].asJsonObject.deepCopy()
|
||||
next.addProperty("shape", "waouqAf~`dJgEoK")
|
||||
val nextManeuvers = next.getAsJsonArray("maneuvers")
|
||||
nextManeuvers.remove(2)
|
||||
nextManeuvers[1].asJsonObject.addProperty("begin_shape_index", 1)
|
||||
nextManeuvers[1].asJsonObject.addProperty("end_shape_index", 1)
|
||||
legs.add(next)
|
||||
val route = parseValhallaRoute(root.toString())
|
||||
assertEquals(4, route.geometry.size)
|
||||
assertEquals(GeoPoint(43.3604, -5.8499), route.geometry.last())
|
||||
assertEquals(2, route.maneuvers[3].beginShapeIndex)
|
||||
assertEquals(3, route.maneuvers[3].endShapeIndex)
|
||||
assertEquals(3, route.maneuvers[4].beginShapeIndex)
|
||||
}
|
||||
|
||||
@Test fun `malformed shape rejected without hanging`() {
|
||||
listOf("", "_", "??_", "!!", "~~~~~~~~~~~~??", "_keqlD???").forEach { shape ->
|
||||
rejects { decodePolyline6(shape) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `malformed JSON measurements status and indices rejected`() {
|
||||
listOf(
|
||||
"{\"trip\":{}", fixture + "{}", "// comment\n$fixture",
|
||||
fixture.replace("\"status\": 0", "\"status\": 442"),
|
||||
fixture.replace("\"length\": 0.052", "\"length\": -1"),
|
||||
fixture.replace("\"length\": 0.052", "\"length\": 1e100"),
|
||||
fixture.replace("\"time\": 17.4", "\"time\": \"17.4\""),
|
||||
fixture.replace("\"end_shape_index\": 2", "\"end_shape_index\": 3"),
|
||||
fixture.replace("\"begin_shape_index\": 1", "\"begin_shape_index\": 3"),
|
||||
fixture.replace("\"type\": 10", "\"type\": 1.5"),
|
||||
fixture.replace("kilometers", "meters"),
|
||||
" ".repeat(2 * 1024 * 1024 + 1),
|
||||
).forEach { json -> rejects { parseValhallaRoute(json) } }
|
||||
}
|
||||
|
||||
@Test fun `disconnected legs rejected`() {
|
||||
val root = JsonParser.parseString(fixture).asJsonObject
|
||||
val legs = root.getAsJsonObject("trip").getAsJsonArray("legs")
|
||||
legs.add(legs[0].deepCopy())
|
||||
rejects { parseValhallaRoute(root.toString()) }
|
||||
}
|
||||
|
||||
@Test fun `coordinate request fixes format language and explicit profile options`() {
|
||||
val origin = GeoPoint(43.36, -5.85)
|
||||
val destination = GeoPoint(43.37, -5.84)
|
||||
val root = JsonParser.parseString(buildValhallaRequest(origin, destination)).asJsonObject
|
||||
assertEquals("motorcycle", root["costing"].asString)
|
||||
assertEquals(0, root.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_tracks"].asInt)
|
||||
assertEquals(0.5, root.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_trails"].asDouble, 0.0)
|
||||
assertEquals("polyline6", root["shape_format"].asString)
|
||||
assertEquals("es-ES", root["language"].asString)
|
||||
assertEquals("kilometers", root["units"].asString)
|
||||
assertEquals(2, root.getAsJsonArray("locations").size())
|
||||
assertEquals("break", root.getAsJsonArray("locations")[0].asJsonObject["type"].asString)
|
||||
val avoid = JsonParser.parseString(buildValhallaRequest(origin, destination, RouteOptions(RouteProfile.AVOID_MOTORWAYS))).asJsonObject
|
||||
assertEquals(0.0, avoid.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_highways"].asDouble, 0.0)
|
||||
val touring = JsonParser.parseString(buildValhallaRequest(origin, destination, RouteOptions(RouteProfile.TOURING))).asJsonObject
|
||||
assertEquals(0.2, touring.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_highways"].asDouble, 0.0)
|
||||
rejects { buildValhallaRequest(GeoPoint(Double.NaN, 0.0), destination) }
|
||||
rejects { buildValhallaRequest(origin, GeoPoint(0.0, 181.0)) }
|
||||
}
|
||||
|
||||
private fun motorcycleOptions(options: RouteOptions) = JsonParser.parseString(
|
||||
buildValhallaRequest(GeoPoint(43.36, -5.85), GeoPoint(43.37, -5.84), options)
|
||||
).asJsonObject.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")
|
||||
|
||||
@Test fun `asphalt preset applies motorcycle surface preference without unsupported hard exclusion`() {
|
||||
val fast = motorcycleOptions(RouteOptions())
|
||||
val asphalt = motorcycleOptions(RouteOptions(RouteProfile.AVOID_UNPAVED))
|
||||
assertEquals(0.5, fast["use_highways"].asDouble, 0.0)
|
||||
assertEquals(0.5, fast["use_trails"].asDouble, 0.0)
|
||||
assertEquals(0.0, asphalt["use_trails"].asDouble, 0.0)
|
||||
assertEquals(fast["use_highways"], asphalt["use_highways"])
|
||||
assertFalse(asphalt.has("exclude_unpaved"))
|
||||
assertFalse(asphalt.has("exclude_highways"))
|
||||
assertFalse(asphalt.has("shortest"))
|
||||
}
|
||||
|
||||
@Test fun `combinable flags persist on presets without changing motorcycle mode`() {
|
||||
val options = RouteOptions(RouteProfile.TOURING, avoidMotorways = true, avoidUnpaved = true, avoidTolls = true)
|
||||
val cost = motorcycleOptions(options)
|
||||
assertEquals(0.0, cost["use_highways"].asDouble, 0.0)
|
||||
assertEquals(0.0, cost["use_trails"].asDouble, 0.0)
|
||||
assertEquals(0.0, cost["use_tolls"].asDouble, 0.0)
|
||||
assertEquals(0, cost["use_tracks"].asInt)
|
||||
val request = JsonParser.parseString(buildValhallaRequest(GeoPoint(0.0, 0.0), GeoPoint(0.1, 0.1), options)).asJsonObject
|
||||
assertEquals("motorcycle", request["costing"].asString)
|
||||
assertFalse(cost.keySet().any { it.startsWith("exclude_") })
|
||||
assertEquals(cost, motorcycleOptions(options.copy()))
|
||||
}
|
||||
|
||||
@Test fun `optional rough maneuver evidence never certifies asphalt from absence`() {
|
||||
assertNull(parseValhallaRoute(fixture).hasUnpaved)
|
||||
val root = JsonParser.parseString(fixture).asJsonObject
|
||||
val maneuvers = root.getAsJsonObject("trip").getAsJsonArray("legs")[0].asJsonObject.getAsJsonArray("maneuvers")
|
||||
maneuvers[0].asJsonObject.addProperty("rough", true)
|
||||
assertEquals(true, parseValhallaRoute(root.toString()).hasUnpaved)
|
||||
maneuvers[0].asJsonObject.addProperty("rough", false)
|
||||
assertNull(parseValhallaRoute(root.toString()).hasUnpaved)
|
||||
maneuvers.forEach { it.asJsonObject.addProperty("rough", false) }
|
||||
assertEquals(false, parseValhallaRoute(root.toString()).hasUnpaved)
|
||||
}
|
||||
|
||||
@Test fun `optional surface evidence rejects coercion instead of trusting backend strings`() {
|
||||
val root = JsonParser.parseString(fixture).asJsonObject
|
||||
val maneuver = root.getAsJsonObject("trip").getAsJsonArray("legs")[0].asJsonObject.getAsJsonArray("maneuvers")[0].asJsonObject
|
||||
listOf("false", "true", "1").forEach {
|
||||
maneuver.addProperty("rough", it)
|
||||
rejects { parseValhallaRoute(root.toString()) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `backend error is sanitized`() {
|
||||
try {
|
||||
parseValhallaRoute("{\"error\":\"private-coordinate-details\",\"error_code\":442}")
|
||||
fail("Expected error")
|
||||
} catch (error: ValhallaRouteException) {
|
||||
assertFalse(error.message!!.contains("private-coordinate-details"))
|
||||
}
|
||||
}
|
||||
|
||||
private fun rejects(block: () -> Unit) {
|
||||
try { block(); fail("Expected invalid routing data to be rejected") }
|
||||
catch (_: ValhallaRouteException) { /* expected */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class VoiceGuidancePolicyTest {
|
||||
private val turn = Maneuver("Gira a la izquierda", 100, 15, 1, 2)
|
||||
private val route = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), listOf(turn), 1000, 100)
|
||||
private fun state(distance: Int = 250, status: NavigationStatus = NavigationStatus.NAVIGATING) =
|
||||
NavigationState(route = route, nextManeuver = turn, distanceToNextManeuverMeters = distance, navigationStatus = status)
|
||||
|
||||
@Test fun `distance checkpoints do not repeat or replay skipped stages`() {
|
||||
val policy = VoiceGuidancePolicy()
|
||||
assertNotNull(policy.announcement(state()))
|
||||
repeat(100) { assertNull(policy.announcement(state(260))) }
|
||||
assertNotNull(policy.announcement(state(25)))
|
||||
assertNull(policy.announcement(state(90)))
|
||||
assertNull(policy.announcement(state(25)))
|
||||
}
|
||||
@Test fun `preview and no route never speak and replacement resets checkpoint`() {
|
||||
val policy = VoiceGuidancePolicy()
|
||||
assertNull(policy.announcement(state(status = NavigationStatus.ROUTE_PREVIEW)))
|
||||
assertNotNull(policy.announcement(state()))
|
||||
assertNotNull(policy.announcement(state().copy(route = route.copy())))
|
||||
assertNull(policy.announcement(NavigationState()))
|
||||
assertNotNull(policy.announcement(state()))
|
||||
}
|
||||
@Test fun `arrival rerouting and poor GPS speak once per route and suppress turns`() {
|
||||
val policy = VoiceGuidancePolicy()
|
||||
for (status in listOf(NavigationStatus.REROUTING, NavigationStatus.GPS_LOST, NavigationStatus.ARRIVED)) {
|
||||
assertNotNull(policy.announcement(state(status = status)))
|
||||
repeat(10) { assertNull(policy.announcement(state(status = status))) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"trip": {
|
||||
"status_message": "Found route between points",
|
||||
"status": 0,
|
||||
"units": "kilometers",
|
||||
"language": "es-ES",
|
||||
"summary": {"length": 0.052, "time": 17.4},
|
||||
"legs": [{
|
||||
"shape": "_onuqA~w`dJgEnKoKgE",
|
||||
"summary": {"length": 0.052, "time": 17.4},
|
||||
"maneuvers": [
|
||||
{"type": 1, "instruction": "Dirígete hacia el norte.", "street_names": ["Calle de prueba"], "length": 0.031, "time": 10.4, "begin_shape_index": 0, "end_shape_index": 1},
|
||||
{"type": 10, "instruction": "Gira a la derecha.", "length": 0.021, "time": 7, "begin_shape_index": 1, "end_shape_index": 2},
|
||||
{"type": 4, "instruction": "Has llegado a tu destino.", "length": 0, "time": 0, "begin_shape_index": 2, "end_shape_index": 2}
|
||||
]
|
||||
}]
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user