package com.cottondb.mail import android.app.Application import android.app.Notification import android.app.NotificationManager import android.content.Context import android.content.pm.ServiceInfo import android.os.Looper import androidx.test.core.app.ApplicationProvider import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import java.io.File import java.time.Duration /** An invented key store: what a test kept, in memory. No password here is real. */ private class Kept(vararg held: Pair) : PasswordStore { val map = mutableMapOf(*held) override fun keep(account: String, password: String) { map[account] = password } override fun read(account: String): String? = map[account] override fun forget(account: String) { map.remove(account) } } private fun json(text: String) = Json.parseToJsonElement(text) as JsonObject /** This phone fetches: the decisions, apart from Android (CONTRACT rows 11 and 12). */ class FetchPlanTest { private val accounts = json( """{"rows":[ {"id":"a1","address":"walker@invented.example","kind":"imap","way":"phone"}, {"id":"a2","address":"mac@invented.example","kind":"gmail","way":"mac"}, {"id":"a3","address":"cloud@invented.example","kind":"fastmail","way":"cotton"}, {"id":"a4","address":"me@studio.invented","kind":"domain","way":"phone"}, {"id":"a5","address":"other@invented.example","kind":"icloud","way":"phone"} ]}""", ) @Test fun only_this_phones_accounts_with_a_kept_password_are_read() { val kept = Kept("a1" to "invented-1", "a2" to "invented-2", "a4" to "invented-4") assertEquals(listOf("a1"), FetchPlan.accounts(accounts, kept::has)) assertEquals(emptyList(), FetchPlan.accounts(null, kept::has)) assertEquals(listOf("a1", "a5"), FetchPlan.accounts(accounts) { true }) } @Test fun history_coming_runs_again_soon_and_caught_up_waits_in_front_or_stops_behind() { val landed = Round("a1", "live", 200, "Fetched by this phone · 200 new") val nothing = Round("a1", "live", 0, "Fetched by this phone · 0 new") assertEquals(FetchPlan.SOON_MS, FetchPlan.next(listOf(landed), inFront = false)) assertEquals(FetchPlan.SOON_MS, FetchPlan.next(listOf(nothing, landed), inFront = true)) assertEquals(FetchPlan.FRESH_MS, FetchPlan.next(listOf(nothing), inFront = true)) assertNull(FetchPlan.next(listOf(nothing), inFront = false)) assertEquals(5_000L, FetchPlan.SOON_MS) assertEquals(5 * 60_000L, FetchPlan.FRESH_MS) } @Test fun a_refused_password_or_a_server_out_of_reach_stops_it_until_the_next_open() { val refused = Round("a1", "refused", 0, "Not fetching · your mail server refused the password") val unreachable = Round("a5", "stopped", 0, "Not fetching · couldn't reach the mail server") assertNull(FetchPlan.next(listOf(refused), inFront = true)) assertNull(FetchPlan.next(listOf(refused, unreachable), inFront = true)) assertNull("nothing to read: stop", FetchPlan.next(emptyList(), inFront = true)) // One account still bringing history keeps it going; the failing one is what the line says. val landed = Round("a2", "live", 3, "Fetched by this phone · 3 new") assertEquals(FetchPlan.SOON_MS, FetchPlan.next(listOf(refused, landed), inFront = false)) assertEquals(refused, FetchPlan.said(listOf(landed, refused))) assertEquals(landed, FetchPlan.said(listOf(landed))) assertNull(FetchPlan.said(emptyList())) } @Test fun a_round_reads_as_the_core_answers_it() { val round = Round.of("a1", json("""{"account":"a1","fetched":12,"state":"live","line":"Fetched by this phone · 12 new"}""")) assertEquals(Round("a1", "live", 12, "Fetched by this phone · 12 new"), round) assertFalse(round.failed) assertTrue(Round.of("a1", json("""{"state":"refused","line":"Not fetching"}""")).failed) assertTrue("an answer without a state is a stop", Round.of("a1", json("{}")).failed) } @Test fun an_account_page_says_this_phones_last_round_and_the_core_says_the_rest() { val core = json("""{"line":"Fetched by this phone","state":"live"}""") FetchLog.last.clear() assertEquals(core, statusOf("a1", "phone", core)) FetchLog.keep(null, Round("a1", "stopped", 0, "Not fetching · couldn't reach the mail server")) val shown = statusOf("a1", "phone", core)!! assertEquals("Not fetching · couldn't reach the mail server", shown["line"].toString().trim('"')) assertEquals("stopped", shown["state"].toString().trim('"')) assertEquals("another way says the core's own line", core, statusOf("a1", "mac", core)) FetchLog.forget(null, "a1") assertEquals(core, statusOf("a1", "phone", core)) } } /** The fetcher's service on a (Robolectric) phone: in the foreground as data sync, quiet, and gone when caught up. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [35], application = Application::class) class PostFetchServiceTest { private val app get() = ApplicationProvider.getApplicationContext() private val asked = mutableListOf() private var answers: List> = emptyList() private var front = false private val words = PostFetch.words private val rounds = PostFetch.rounds private val inFront = PostFetch.inFront private val passwords = PostFetch.passwords @Before fun invented() { asked.clear() PostFetch.words = { PostFetch.Words("This phone fetches", "Post", "Fetched by this phone") } // A round takes a moment, as a real one does over the network: the service stands while it runs. PostFetch.rounds = { kotlinx.coroutines.delay(10); asked.add(asked.size); answers.getOrElse(asked.size - 1) { answers.last() } } PostFetch.inFront = { front } } @After fun back() { PostFetch.words = words PostFetch.rounds = rounds PostFetch.inFront = inFront PostFetch.passwords = passwords } private fun idle(by: Duration = Duration.ZERO) { shadowOf(Looper.getMainLooper()).idleFor(by.plusMillis(20)) } @Test fun it_stands_in_the_foreground_as_data_sync_with_a_quiet_ongoing_notice_and_stops_on_a_server_out_of_reach() { answers = listOf(listOf(Round("a1", "stopped", 0, "Not fetching · couldn't reach the mail server"))) val controller = Robolectric.buildService(PostFetchService::class.java).create() controller.startCommand(0, 1) val service = shadowOf(controller.get()) assertEquals(ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, controller.get().foregroundServiceType) val notice = service.lastForegroundNotification assertNotNull(notice) assertTrue("ongoing while it works", notice.flags and Notification.FLAG_ONGOING_EVENT != 0) assertEquals(PostFetchService.CHANNEL, notice.channelId) val channel = app.getSystemService(NotificationManager::class.java).getNotificationChannel(PostFetchService.CHANNEL) assertEquals("quiet: low importance", NotificationManager.IMPORTANCE_LOW, channel.importance) assertNull("no sound", channel.sound) assertFalse("no vibration", channel.shouldVibrate()) idle() assertEquals(1, asked.size) assertTrue("it stops itself", service.isStoppedBySelf) assertTrue("its notice goes with it", service.isForegroundStopped) } @Test fun while_history_comes_it_reads_again_in_five_seconds_then_stops_once_caught_up_behind() { answers = listOf(listOf(Round("a1", "live", 200, "Fetched by this phone · 200 new")), listOf(Round("a1", "live", 0, "Fetched by this phone · 0 new"))) val controller = Robolectric.buildService(PostFetchService::class.java).create() controller.startCommand(0, 1) idle() assertEquals(1, asked.size) assertFalse(shadowOf(controller.get()).isStoppedBySelf) idle(Duration.ofMillis(FetchPlan.SOON_MS)) assertEquals(2, asked.size) assertTrue(shadowOf(controller.get()).isStoppedBySelf) } @Test fun in_front_and_caught_up_it_waits_five_minutes_and_reads_again() { front = true answers = listOf(listOf(Round("a1", "live", 0, "Fetched by this phone · 0 new"))) val controller = Robolectric.buildService(PostFetchService::class.java).create() controller.startCommand(0, 1) idle() assertEquals(1, asked.size) idle(Duration.ofMillis(FetchPlan.FRESH_MS - 1_000)) assertEquals(1, asked.size) idle(Duration.ofMillis(2_000)) assertEquals(2, asked.size) front = false idle(Duration.ofMillis(FetchPlan.FRESH_MS)) assertTrue("Post behind: it stops", shadowOf(controller.get()).isStoppedBySelf) } @Test fun a_second_start_while_it_works_does_not_run_two_rounds_at_once() { answers = listOf(listOf(Round("a1", "live", 5, "Fetched by this phone · 5 new")), listOf(Round("a1", "live", 0, "x"))) val controller = Robolectric.buildService(PostFetchService::class.java).create() controller.startCommand(0, 1) controller.startCommand(0, 2) idle() assertEquals(1, asked.size) } @Test fun it_is_woken_only_when_this_phone_reads_an_account() { val accounts = json("""{"rows":[{"id":"a1","kind":"imap","way":"phone"},{"id":"a2","kind":"gmail","way":"mac"}]}""") val kept = Kept() PostFetch.passwords = { kept } PostFetch.wake(app, accounts) assertEquals(false, PostFetch.started) assertNull(shadowOf(app).nextStartedService) kept.keep("a1", "invented-pass") PostFetch.wake(app, accounts) assertEquals(true, PostFetch.started) assertEquals(PostFetchService::class.java.name, shadowOf(app).nextStartedService?.component?.className) kept.forget("a1") PostFetch.wake(app, accounts) assertEquals(false, PostFetch.started) } @Test fun an_account_moved_off_this_phone_forgets_its_password_and_its_line() { val kept = Kept("a1" to "invented-pass") PostFetch.passwords = { kept } FetchLog.keep(app, Round("a1", "refused", 0, "Not fetching · your mail server refused the password")) PostFetch.forget(app, "a1") assertNull(kept.read("a1")) assertNull(FetchLog.last["a1"]) FetchLog.last.clear() FetchLog.read(app) assertNull("not kept beside the app either", FetchLog.last["a1"]) } @Test fun the_last_round_is_read_back_after_a_new_open_words_only() { FetchLog.keep(app, Round("a7", "stopped", 0, "Not fetching · couldn't reach the mail server")) FetchLog.last.clear() FetchLog.read(app) assertEquals("Not fetching · couldn't reach the mail server", FetchLog.last["a7"]?.line) val kept = app.getSharedPreferences("post-fetch", Context.MODE_PRIVATE).all.values.joinToString() assertFalse("no password beside the app", "invented" in kept) FetchLog.forget(app, "a7") } } /** The fetcher's place in the build: the mail flavour's manifest, and where the password goes. */ class PostFetchSourceTest { private val repo = generateSequence(File("").absoluteFile) { it.parentFile }.first { File(it, "apps/registry.json").isFile } private val mail = File(repo, "apps/android/app/src/mail") @Test fun the_manifest_declares_the_data_sync_service_and_its_leave() { val manifest = File(mail, "AndroidManifest.xml").readText() listOf("android.permission.FOREGROUND_SERVICE\"", "android.permission.FOREGROUND_SERVICE_DATA_SYNC", "android.permission.POST_NOTIFICATIONS").forEach { assertTrue("$it is asked", it in manifest) } assertTrue(Regex("""PostFetchService"\s+android:exported="false"\s+android:foregroundServiceType="dataSync"""").containsMatchIn(manifest)) assertTrue("WorkManager's own service stands as data sync too", Regex("""SystemForegroundService"\s+android:foregroundServiceType="dataSync"""").containsMatchIn(manifest)) } @Test fun the_password_is_sealed_by_the_keystore_and_handed_to_the_core_only_for_cotton() { val fetcher = File(mail, "kotlin/com/cottondb/mail/Fetcher.kt").readText() val pages = File(mail, "kotlin/com/cottondb/mail/YouPages.kt").readText() assertTrue("the shell's Keystore seal", "Sealed(context.applicationContext, flavour, \"post-password-\"" in fetcher) assertTrue("added: the password goes to the core only for Cotton fetches", "if (chosen == \"cotton\") put(\"password\"" in pages) assertTrue("moved: only Cotton fetches hands it over", "if (to == \"cotton\" && password != null) put(\"password\"" in pages) // Nothing logs a request: only codes and kinds of failure reach the log. val logs = Regex("""Log\.[wdie]\([^)]*\)""").findAll(fetcher + pages).map { it.value }.toList() assertTrue("logs say no password: $logs", logs.none { "password" in it.substringAfter(',') && "\$" in it && "code" !in it }) } }