package com.pitchedapps.frost.db import android.database.sqlite.SQLiteConstraintException import com.pitchedapps.frost.services.NOTIF_CHANNEL_GENERAL import com.pitchedapps.frost.services.NotificationContent import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue class NotificationDbTest : BaseDbTest() { private val dao get() = db.notifDao() private fun cookie(id: Long) = CookieEntity(id, "name$id", "cookie$id") private fun notifContent(id: Long, cookie: CookieEntity, time: Long = id) = NotificationContent( data = cookie, id = id, href = "", title = null, text = "", timestamp = time, profileUrl = null ) @Test fun saveAndRetrieve() { val cookie = cookie(12345L) // Unique unsorted ids val notifs = listOf(0L, 4L, 2L, 6L, 99L, 3L).map { notifContent(it, cookie) } runBlocking { db.cookieDao().insertCookie(cookie) dao.saveNotifications(NOTIF_CHANNEL_GENERAL, notifs) val dbNotifs = dao.selectNotifications(cookie.id, NOTIF_CHANNEL_GENERAL) assertEquals(notifs.sortedByDescending { it.timestamp }, dbNotifs, "Incorrect notification list received") } } /** * Primary key is both id and userId, in the event that the same notification to multiple users has the same id */ @Test fun primaryKeyCheck() { runBlocking { val cookie1 = cookie(12345L) val cookie2 = cookie(12L) val notifs1 = (0L..2L).map { notifContent(it, cookie1) } val notifs2 = notifs1.map { it.copy(data = cookie2) } db.cookieDao().insertCookie(cookie1) db.cookieDao().insertCookie(cookie2) dao.saveNotifications(NOTIF_CHANNEL_GENERAL, notifs1) dao.saveNotifications(NOTIF_CHANNEL_GENERAL, notifs2) } } @Test fun cascadeDeletion() { val cookie = cookie(12345L) // Unique unsorted ids val notifs = listOf(0L, 4L, 2L, 6L, 99L, 3L).map { notifContent(it, cookie) } runBlocking { db.cookieDao().insertCookie(cookie) dao.saveNotifications(NOTIF_CHANNEL_GENERAL, notifs) db.cookieDao().deleteById(cookie.id) val dbNotifs = dao.selectNotifications(cookie.id, NOTIF_CHANNEL_GENERAL) assertTrue(dbNotifs.isEmpty(), "Cascade deletion failed") } } @Test fun latestEpoch() { val cookie = cookie(12345L) // Unique unsorted ids val notifs = listOf(0L, 4L, 2L, 6L, 99L, 3L).map { notifContent(it, cookie) } runBlocking { assertEquals(-1L, dao.latestEpoch(cookie.id, NOTIF_CHANNEL_GENERAL), "Default epoch failed") db.cookieDao().insertCookie(cookie) dao.saveNotifications(NOTIF_CHANNEL_GENERAL, notifs) assertEquals(99L, dao.latestEpoch(cookie.id, NOTIF_CHANNEL_GENERAL), "Latest epoch failed") } } @Test fun insertionWithInvalidCookies() { assertFailsWith(SQLiteConstraintException::class) { runBlocking { dao.saveNotifications(NOTIF_CHANNEL_GENERAL, listOf(notifContent(1L, cookie(2L)))) } } } }