|
| 1 | +package com.parsely.parselyandroid |
| 2 | + |
| 3 | +import androidx.test.core.app.ApplicationProvider |
| 4 | +import kotlin.time.Duration.Companion.seconds |
| 5 | +import kotlinx.coroutines.ExperimentalCoroutinesApi |
| 6 | +import kotlinx.coroutines.cancel |
| 7 | +import kotlinx.coroutines.test.advanceTimeBy |
| 8 | +import kotlinx.coroutines.test.runCurrent |
| 9 | +import kotlinx.coroutines.test.runTest |
| 10 | +import org.assertj.core.api.Assertions.assertThat |
| 11 | +import org.junit.Test |
| 12 | +import org.junit.runner.RunWith |
| 13 | +import org.robolectric.RobolectricTestRunner |
| 14 | + |
| 15 | +@OptIn(ExperimentalCoroutinesApi::class) |
| 16 | +@RunWith(RobolectricTestRunner::class) |
| 17 | +internal class InMemoryBufferTest { |
| 18 | + |
| 19 | + private lateinit var sut: InMemoryBuffer |
| 20 | + private val repository = FakeLocalStorageRepository() |
| 21 | + |
| 22 | + @Test |
| 23 | + fun `when adding a new event, then save it to local storage`() = runTest { |
| 24 | + // given |
| 25 | + val event = mapOf("test" to 123) |
| 26 | + sut = InMemoryBuffer(backgroundScope, repository) |
| 27 | + |
| 28 | + // when |
| 29 | + sut.add(event) |
| 30 | + advanceTimeBy(1.seconds) |
| 31 | + runCurrent() |
| 32 | + backgroundScope.cancel() |
| 33 | + |
| 34 | + // then |
| 35 | + assertThat(repository.getStoredQueue()).containsOnlyOnce(event) |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + fun `when adding multiple events in different intervals, then save all of them to local storage without duplicates`() = |
| 40 | + runTest { |
| 41 | + // given |
| 42 | + val events = (0..2).map { mapOf("test" to it) } |
| 43 | + sut = InMemoryBuffer(backgroundScope, repository) |
| 44 | + |
| 45 | + // when |
| 46 | + sut.add(events[0]) |
| 47 | + advanceTimeBy(1.seconds) |
| 48 | + runCurrent() |
| 49 | + |
| 50 | + sut.add(events[1]) |
| 51 | + advanceTimeBy(0.5.seconds) |
| 52 | + runCurrent() |
| 53 | + |
| 54 | + sut.add(events[2]) |
| 55 | + advanceTimeBy(0.5.seconds) |
| 56 | + runCurrent() |
| 57 | + |
| 58 | + backgroundScope.cancel() |
| 59 | + |
| 60 | + // then |
| 61 | + assertThat(repository.getStoredQueue()).containsOnlyOnceElementsOf(events) |
| 62 | + } |
| 63 | + |
| 64 | + class FakeLocalStorageRepository() : |
| 65 | + LocalStorageRepository(ApplicationProvider.getApplicationContext()) { |
| 66 | + |
| 67 | + private val events = mutableListOf<Map<String, Any?>?>() |
| 68 | + |
| 69 | + override suspend fun insertEvents(toInsert: List<Map<String, Any?>?>) { |
| 70 | + events.addAll(toInsert) |
| 71 | + } |
| 72 | + |
| 73 | + override fun getStoredQueue(): ArrayList<Map<String, Any?>?> { |
| 74 | + return ArrayList(events) |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments