Skip to content

Commit 8a2d61d

Browse files
committed
test: make async readiness assertion deterministic
1 parent 2016956 commit 8a2d61d

1 file changed

Lines changed: 11 additions & 2 deletions

File tree

‎app/src/test/java/io/nekohasekai/sagernet/database/preference/StoreAsyncReadinessTest.kt‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@ package io.nekohasekai.sagernet.database.preference
33
import kotlinx.coroutines.runBlocking
44
import org.junit.Assert.assertEquals
55
import org.junit.Assert.assertFalse
6+
import org.junit.Assert.assertNotSame
67
import org.junit.Assert.assertTrue
78
import org.junit.Test
89
import java.util.concurrent.CountDownLatch
910
import java.util.concurrent.TimeUnit
1011
import java.util.concurrent.atomic.AtomicBoolean
1112
import java.util.concurrent.atomic.AtomicInteger
13+
import java.util.concurrent.atomic.AtomicReference
1214

1315
/**
1416
* S2-B1 readiness contract. Every assertion is about the store constructor
@@ -22,8 +24,12 @@ class StoreAsyncReadinessTest {
2224
@Volatile var shouldFail: Boolean = false,
2325
) : KeyValuePair.Dao {
2426
val allReads = AtomicInteger(0)
27+
val readStarted = CountDownLatch(1)
28+
val readThread = AtomicReference<Thread?>()
2529
override fun all(): List<KeyValuePair> {
30+
readThread.set(Thread.currentThread())
2631
allReads.incrementAndGet()
32+
readStarted.countDown()
2733
if (shouldFail) throw IllegalStateException("injected prime failure")
2834
if (!latch.await(10, TimeUnit.SECONDS)) error("prime gate not released")
2935
return emptyList()
@@ -37,11 +43,14 @@ class StoreAsyncReadinessTest {
3743
}
3844

3945
@Test
40-
fun constructorDoesNotReadDao() {
46+
fun constructorDoesNotReadDaoOnCallingThread() {
47+
val callingThread = Thread.currentThread()
4148
val dao = BlockingFakeDao(CountDownLatch(1))
4249
val store = RoomPreferenceDataStore(dao, tableSnapshot = dao::all)
4350
assertTrue(store.readiness is RoomPreferenceDataStore.StoreReadiness.Loading)
44-
assertEquals(0, dao.allReads.get())
51+
assertTrue("background DAO read did not start", dao.readStarted.await(5, TimeUnit.SECONDS))
52+
assertNotSame(callingThread, dao.readThread.get())
53+
assertEquals(1, dao.allReads.get())
4554
dao.latch.countDown()
4655
runBlocking { store.awaitReady() }
4756
assertTrue(store.readiness is RoomPreferenceDataStore.StoreReadiness.Ready)

0 commit comments

Comments
 (0)