198 lines · 9.7 KB · KotlinRaw
package com.cottondb.mailimport android.app.Applicationimport android.app.Notificationimport android.app.NotificationManagerimport android.content.Contextimport android.content.Intentimport androidx.test.core.app.ApplicationProviderimport kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Beforeimport org.junit.Testimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.Shadows.shadowOfimport org.robolectric.annotation.Configimport java.io.File/** `mail.fetch`'s `notify` read as the core answers it (CONTRACT row 17): who wrote, the subject, the mail, the conversation. */class RingOfTest { private fun json(text: String) = Json.parseToJsonElement(text) as JsonObject @Test fun each_item_is_one_ring_in_order() { val answer = json( """{"account":"a1","fetched":3,"state":"live","line":"Fetched by this phone · 3 new","notify":[ {"id":"e1","thread":"t1","title":"Priya Nair","body":"Flat papers"}, {"id":"e2","thread":"t2","title":"walker@invented.example","body":"(no subject)"} ]}""", ) assertEquals( listOf(Ring("e1", "t1", "Priya Nair", "Flat papers"), Ring("e2", "t2", "walker@invented.example", "(no subject)")), Ring.of(answer), ) assertEquals("the round carries them", Ring.of(answer), Round.of("a1", answer).rings) } @Test fun nothing_to_ring_without_notify_or_without_an_id_or_words() { assertEquals(emptyList<Ring>(), Ring.of(json("""{"state":"live"}"""))) assertEquals(emptyList<Ring>(), Ring.of(json("""{"notify":[]}"""))) assertEquals(emptyList<Ring>(), Ring.of(null)) val odd = json("""{"notify":[{"thread":"t1","title":"No id","body":"x"},{"id":"e3","title":"","body":" "},{"id":"e4","thread":"","title":"Asha","body":"Tea"}]}""") assertEquals("a blank conversation is none", listOf(Ring("e4", null, "Asha", "Tea")), Ring.of(odd)) assertEquals("an old answer still reads", Round("a1", "live", 0, "x"), Round.of("a1", json("""{"state":"live","fetched":0,"line":"x"}"""))) }}/** The rings on a (Robolectric) phone: one per mail, never while Post is in front, a tap opening the conversation. */@RunWith(RobolectricTestRunner::class)@Config(sdk = [35], application = Application::class)class PostRingsTest { private val app get() = ApplicationProvider.getApplicationContext<Application>() private val manager get() = app.getSystemService(NotificationManager::class.java) private var front = false private val inFront = PostRings.inFront private val channelName = PostRings.channelName private val priya = Ring("e1", "t1", "Priya Nair", "Flat papers") @Before fun invented() { PostRings.inFront = { front } PostRings.channelName = { "New mail" } PostRings.opening = null PostRings.armed = false } @After fun back() { PostRings.inFront = inFront PostRings.channelName = channelName PostRings.opening = null PostRings.armed = false } private fun rung(): List<Notification> = shadowOf(manager).allNotifications.filter { it.channelId == PostRings.CHANNEL } @Test fun behind_each_mail_rings_once_with_who_wrote_and_the_subject() = runBlocking { assertEquals(2, PostRings.ring(app, listOf(priya, Ring("e2", "t2", "Asha Rao", "Tea on Sunday")))) val shown = rung() assertEquals(2, shown.size) val first = shadowOf(manager).getNotification(PostRings.tag(priya), PostRings.NOTICE) assertNotNull(first) assertEquals("Priya Nair", first.extras.getCharSequence(Notification.EXTRA_TITLE).toString()) assertEquals("Flat papers", first.extras.getCharSequence(Notification.EXTRA_TEXT).toString()) assertTrue("it goes when tapped", first.flags and Notification.FLAG_AUTO_CANCEL != 0) assertEquals(Notification.CATEGORY_EMAIL, first.category) assertEquals("New mail", manager.getNotificationChannel(PostRings.CHANNEL).name.toString()) // The same mail named again (a round heard twice) is still one notification: its tag is the mail's. PostRings.ring(app, listOf(priya)) assertEquals(2, rung().size) } @Test fun nothing_rings_while_post_is_in_front() = runBlocking { front = true assertEquals(0, PostRings.ring(app, listOf(priya))) assertTrue(rung().isEmpty()) front = false assertEquals(0, PostRings.ring(app, emptyList())) assertTrue(rung().isEmpty()) } @Test fun nothing_rings_where_post_may_not_notify() = runBlocking { shadowOf(manager).setNotificationsEnabled(false) assertEquals(0, PostRings.ring(app, listOf(priya))) assertTrue(rung().isEmpty()) shadowOf(manager).setNotificationsEnabled(true) } @Test fun a_tap_opens_that_conversation() = runBlocking { PostRings.ring(app, listOf(priya)) val tap = shadowOf(shadowOf(manager).getNotification(PostRings.tag(priya), PostRings.NOTICE).contentIntent).savedIntent assertEquals(PostRings.OPEN, tap.action) assertEquals("t1", tap.getStringExtra(PostRings.THREAD)) assertEquals(MainActivity::class.java.name, tap.component?.className) PostRings.took(tap, debug = false) assertEquals("t1", PostRings.opening) // Recents handing the same intent again is no new tap. PostRings.opening = null PostRings.took(Intent(tap).addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY), debug = false) assertNull(PostRings.opening) } @Test fun the_walk_ring_is_a_dev_builds_only() { val walk = Intent(Intent.ACTION_MAIN).putExtra(PostRings.RING, true) PostRings.took(walk, debug = false) assertFalse("a release build never arms it", PostRings.armed) PostRings.took(walk, debug = true) assertTrue(PostRings.armed) } @Test fun leave_to_notify_is_asked_once_and_only_where_it_is_not_given() { val prefs = app.getSharedPreferences("post-rings", Context.MODE_PRIVATE) prefs.edit().clear().commit() assertFalse("before Android 13 there is nothing to ask", PostRings.askOnce(app, sdk = 32)) assertTrue(PostRings.askOnce(app, sdk = 35)) assertFalse("asked once", PostRings.askOnce(app, sdk = 35)) prefs.edit().clear().commit() shadowOf(app).grantPermissions(android.Manifest.permission.POST_NOTIFICATIONS) assertFalse("given already", PostRings.askOnce(app, sdk = 35)) prefs.edit().clear().commit() }}/** Where the rings sit in Post: the fetcher's rounds, the ask at account add only, the tap, the Dev walk. */class PostRingsSourceTest { private val repo = generateSequence(File("").absoluteFile) { it.parentFile }.first { File(it, "apps/registry.json").isFile } private val dir = File(repo, "apps/android/app/src/mail/kotlin/com/cottondb/mail") private fun src(name: String) = File(dir, name).readText() @Test fun every_fetch_round_rings_its_notify() { val fetcher = src("Fetcher.kt") assertTrue(fetcher.contains("rings = Ring.of(answer)")) assertTrue("the service's rounds and the worker's both run PostRounds", fetcher.contains("PostRings.ring(context, round.rings)")) assertTrue(src("Rings.kt").contains("if (rings.isEmpty() || inFront()) return 0")) } @Test fun leave_to_notify_is_asked_only_when_an_account_this_phone_fetches_is_added() { val all = dir.listFiles()!!.filter { it.extension == "kt" }.associate { it.name to it.readText() } val askers = all.filter { (_, text) -> text.contains("state.askNotifications()") }.keys assertEquals(setOf("YouPages.kt"), askers) val pages = all.getValue("YouPages.kt") // Added with This phone fetches, or an account moved to it: nowhere else. assertEquals(2, pages.split("state.askNotifications()").size - 1) assertTrue(pages.contains("if (chosen == \"phone\") { PostFetch.keep(context, id, password); state.askNotifications() }")) assertTrue(pages.contains("if (to == \"phone\" && password != null) { PostFetch.keep(context, id, password); state.askNotifications() }")) // Never at launch: nothing in Post's root or its activity raises the ask itself. listOf("PostApp.kt", "MailApplication.kt").forEach { assertFalse(it, all.getValue(it).contains("askingNotifications = true")) } assertTrue(all.getValue("PostState.kt").contains("if (PostRings.askOnce(shell.context)) shell.askingNotifications = true")) assertTrue(File(repo, "apps/android/app/src/mail/AndroidManifest.xml").readText().contains("android.permission.POST_NOTIFICATIONS")) } @Test fun a_tap_reaches_posts_root_and_the_walk_ring_stays_out_of_release() { val activity = src("MailApplication.kt") assertTrue(activity.contains("PostRings.took(intent, BuildConfig.DEBUG)")) val root = src("PostApp.kt") assertTrue(root.contains("state.openRung(it)")) assertTrue(root.contains("if (com.cottondb.app.BuildConfig.DEBUG) LaunchedEffect(PostRings.armed)")) // Disarmed after the newest is read: disarming first restarted the effect and cancelled the read (walk, 26 Nov). assertTrue(root.indexOf("val newest = state.newestRing()") in 0 until root.indexOf("PostRings.armed = false")) // The walk rings through the same path a round does. assertTrue(src("Rings.kt").contains("app.scope.launch { ring(app, listOf(newest)) }")) }}