Tusky-App-Android/app/src/test/java/com/keylesspalace/tusky/BottomSheetActivityTest.kt

320 lines
11 KiB
Kotlin
Raw Normal View History

/* Copyright 2018 Levi Bard
*
* This file is a part of Tusky.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
import at.connyduck.calladapter.networkresult.NetworkResult
import com.keylesspalace.tusky.entity.SearchResult
import com.keylesspalace.tusky.entity.Status
import com.keylesspalace.tusky.entity.TimelineAccount
import com.keylesspalace.tusky.network.MastodonApi
import java.util.Date
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.ArgumentMatchers.anyBoolean
import org.mockito.Mockito.eq
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
@OptIn(ExperimentalCoroutinesApi::class)
class BottomSheetActivityTest {
@get:Rule
val instantTaskExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var activity: FakeBottomSheetActivity
private lateinit var apiMock: MastodonApi
private val accountQuery = "http://mastodon.foo.bar/@User"
private val statusQuery = "http://mastodon.foo.bar/@User/345678"
private val nonexistentStatusQuery = "http://mastodon.foo.bar/@User/345678000"
private val nonMastodonQuery = "http://medium.com/@correspondent/345678"
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
private val emptyResult = NetworkResult.success(SearchResult(emptyList(), emptyList(), emptyList()))
private val account = TimelineAccount(
id = "1",
localUsername = "admin",
username = "admin",
displayName = "Ad Min",
note = "This is their bio",
url = "http://mastodon.foo.bar/@User",
avatar = ""
)
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
private val accountResult = NetworkResult.success(SearchResult(listOf(account), emptyList(), emptyList()))
private val status = Status(
id = "1",
url = statusQuery,
account = account,
inReplyToId = null,
inReplyToAccountId = null,
reblog = null,
content = "omgwat",
createdAt = Date(),
editedAt = null,
emojis = emptyList(),
reblogsCount = 0,
favouritesCount = 0,
repliesCount = 0,
reblogged = false,
favourited = false,
bookmarked = false,
sensitive = false,
spoilerText = "",
visibility = Status.Visibility.PUBLIC,
attachments = ArrayList(),
mentions = emptyList(),
tags = emptyList(),
application = null,
pinned = false,
muted = false,
poll = null,
card = null,
language = null,
Replace Gson library with Moshi (#4309) **! ! Warning**: Do not merge before testing every API call and database read involving JSON ! **Gson** is obsolete and has been superseded by **Moshi**. But more importantly, parsing Kotlin objects using Gson is _dangerous_ because Gson uses Java serialization and is **not Kotlin-aware**. This has two main consequences: - Fields of non-null types may end up null at runtime. Parsing will succeed, but the code may crash later with a `NullPointerException` when trying to access a field member; - Default values of constructor parameters are always ignored. When absent, reference types will be null, booleans will be false and integers will be zero. On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin Serialization** will validate at parsing time that all received fields comply with the Kotlin contract and avoid errors at runtime, making apps more stable and schema mismatches easier to detect (as long as logs are accessible): - Receiving a null value for a non-null type will generate a parsing error; - Optional types are declared explicitly by adding a default value. **A missing value with no default value declaration will generate a parsing error.** Migrating the entity declarations from Gson to Moshi will make the code more robust but is not an easy task because of the semantic differences. With Gson, both nullable and optional fields are represented with a null value. After converting to Moshi, some nullable entities can become non-null with a default value (if they are optional and not nullable), others can stay nullable with no default value (if they are mandatory and nullable), and others can become **nullable with a default value of null** (if they are optional _or_ nullable _or_ both). That third option is the safest bet when it's not clear if a field is optional or not, except for lists which can usually be declared as non-null with a default value of an empty list (I have yet to see a nullable array type in the Mastodon API). Fields that are currently declared as non-null present another challenge. In theory, they should remain as-is and everything will work fine. In practice, **because Gson is not aware of nullable types at all**, it's possible that some non-null fields currently hold a null value in some cases but the app does not report any error because the field is not accessed by Kotlin code in that scenario. After migrating to Moshi however, parsing such a field will now fail early if a null value or no value is received. These fields will have to be identified by heavily testing the app and looking for parsing errors (`JsonDataException`) and/or by going through the Mastodon documentation. A default value needs to be added for missing optional fields, and their type could optionally be changed to nullable, depending on the case. Gson is also currently used to serialize and deserialize objects to and from the local database, which is also challenging because backwards compatibility needs to be preserved. Fortunately, by default Gson omits writing null fields, so a field of type `List<T>?` could be replaced with a field of type `List<T>` with a default value of `emptyList()` and reading back the old data should still work. However, nullable lists that are written directly (not as a field of another object) will still be serialized to JSON as `"null"` so the deserializing code must still be handling null properly. Finally, changing the database schema is out of scope for this pull request, so database entities that also happen to be serialized with Gson will keep their original types even if they could be made non-null as an improvement. In the end this is all for the best, because the app will be more reliable and errors will be easier to detect by showing up earlier with a clear error message. Not to mention the performance benefits of using Moshi compared to Gson. - Replace Gson reflection with Moshi Kotlin codegen to generate all parsers at compile time. - Replace custom `Rfc3339DateJsonAdapter` with the one provided by moshi-adapters. - Replace custom `JsonDeserializer` classes for Enum types with `EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to support fallback values. - Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter` which works with any type. Any nullable field may now be annotated with `@Guarded`. - Remove Proguard rules related to Json entities. Each Json entity needs to be annotated with `@JsonClass` with no exception, and adding this annotation will ensure that R8/Proguard will handle the entities properly. - Replace some nullable Boolean fields with non-null Boolean fields with a default value where possible. - Replace some nullable list fields with non-null list fields with a default value of `emptyList()` where possible. - Update `TimelineDao` to perform all Json conversions internally using `Converters` so no Gson or Moshi instance has to be passed to its methods. - ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and deserialize `DraftAttachment` which is a special entity that supports more than one json name per field. A custom adapter is necessary because there is not direct equivalent of `@SerializedName(alternate = [...])` in Moshi.~~ Remove alternate names for some `DraftAttachment` fields which were used as a workaround to deserialize local data in 2-years old builds of Tusky. - Update tests to make them work with Moshi. - Simplify a few `equals()` implementations. - Change a few functions to `val`s - Turn `NetworkModule` into an `object` (since it contains no abstract methods). Please test the app thoroughly before merging. There may be some fields currently declared as mandatory that are actually optional.
2024-04-02 21:01:04 +02:00
filtered = emptyList()
)
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
private val statusResult = NetworkResult.success(SearchResult(emptyList(), listOf(status), emptyList()))
@Before
fun setup() {
apiMock = mock {
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
onBlocking { search(eq(accountQuery), eq(null), anyBoolean(), eq(null), eq(null), eq(null)) } doReturn accountResult
onBlocking { search(eq(statusQuery), eq(null), anyBoolean(), eq(null), eq(null), eq(null)) } doReturn statusResult
onBlocking { search(eq(nonexistentStatusQuery), eq(null), anyBoolean(), eq(null), eq(null), eq(null)) } doReturn accountResult
onBlocking { search(eq(nonMastodonQuery), eq(null), anyBoolean(), eq(null), eq(null), eq(null)) } doReturn emptyResult
}
activity = FakeBottomSheetActivity(apiMock)
}
@Test
fun beginEndSearch_setIsSearching_isSearchingAfterBegin() {
activity.onBeginSearch("https://mastodon.foo.bar/@User")
assertTrue(activity.isSearching())
}
@Test
fun beginEndSearch_setIsSearching_isNotSearchingAfterEnd() {
val validUrl = "https://mastodon.foo.bar/@User"
activity.onBeginSearch(validUrl)
activity.onEndSearch(validUrl)
assertFalse(activity.isSearching())
}
@Test
fun beginEndSearch_setIsSearching_doesNotCancelSearchWhenResponseFromPreviousSearchIsReceived() {
val validUrl = "https://mastodon.foo.bar/@User"
val invalidUrl = ""
activity.onBeginSearch(validUrl)
activity.onEndSearch(invalidUrl)
assertTrue(activity.isSearching())
}
@Test
fun cancelActiveSearch() {
val url = "https://mastodon.foo.bar/@User"
activity.onBeginSearch(url)
activity.cancelActiveSearch()
assertFalse(activity.isSearching())
}
@Test
fun getCancelSearchRequested_detectsURL() {
val firstUrl = "https://mastodon.foo.bar/@User"
val secondUrl = "https://mastodon.foo.bar/@meh"
activity.onBeginSearch(firstUrl)
activity.cancelActiveSearch()
activity.onBeginSearch(secondUrl)
assertTrue(activity.getCancelSearchRequested(firstUrl))
assertFalse(activity.getCancelSearchRequested(secondUrl))
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_inIdealConditions_returnsRequestedResults_forAccount() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
activity.viewUrl(accountQuery)
testScheduler.advanceTimeBy(100.milliseconds)
assertEquals(account.id, activity.accountId)
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_inIdealConditions_returnsRequestedResults_forStatus() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
activity.viewUrl(statusQuery)
testScheduler.advanceTimeBy(100.milliseconds)
assertEquals(status.id, activity.statusId)
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_inIdealConditions_returnsRequestedResults_forNonMastodonURL() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
activity.viewUrl(nonMastodonQuery)
testScheduler.advanceTimeBy(100.milliseconds)
assertEquals(nonMastodonQuery, activity.link)
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_withNoResults_appliesRequestedFallbackBehavior() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
for (fallbackBehavior in listOf(
PostLookupFallbackBehavior.OPEN_IN_BROWSER,
PostLookupFallbackBehavior.DISPLAY_ERROR
)) {
activity.viewUrl(nonMastodonQuery, fallbackBehavior)
testScheduler.advanceTimeBy(100.milliseconds)
assertEquals(nonMastodonQuery, activity.link)
assertEquals(fallbackBehavior, activity.fallbackBehavior)
}
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_doesNotRespectUnrelatedResult() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
activity.viewUrl(nonexistentStatusQuery)
testScheduler.advanceTimeBy(100.milliseconds)
assertEquals(nonexistentStatusQuery, activity.link)
assertEquals(null, activity.accountId)
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_withCancellation_doesNotLoadUrl_forAccount() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
activity.viewUrl(accountQuery)
assertTrue(activity.isSearching())
activity.cancelActiveSearch()
assertFalse(activity.isSearching())
assertEquals(null, activity.accountId)
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_withCancellation_doesNotLoadUrl_forStatus() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
activity.viewUrl(accountQuery)
activity.cancelActiveSearch()
assertEquals(null, activity.accountId)
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_withCancellation_doesNotLoadUrl_forNonMastodonURL() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
activity.viewUrl(nonMastodonQuery)
activity.cancelActiveSearch()
assertEquals(null, activity.searchUrl)
} finally {
Dispatchers.resetMain()
}
}
@Test
Replace RxJava3 code with coroutines (#4290) This pull request removes the remaining RxJava code and replaces it with coroutine-equivalent implementations. - Remove all duplicate methods in `MastodonApi`: - Methods returning a RxJava `Single` have been replaced by suspending methods returning a `NetworkResult` in order to be consistent with the new code. - _sync_/_async_ method variants are replaced with the _async_ version only (suspending method), and `runBlocking{}` is used to make the async variant synchronous. - Create a custom coroutine-based implementation of `Single` for usage in Java code where launching a coroutine is not possible. This class can be deleted after remaining Java code has been converted to Kotlin. - `NotificationsFragment.java` can subscribe to `EventHub` events by calling the new lifecycle-aware `EventHub.subscribe()` method. This allows using the `SharedFlow` as single source of truth for all events. - Rx Autodispose is replaced by `lifecycleScope.launch()` which will automatically cancel the coroutine when the Fragment view/Activity is destroyed. - Background work is launched in the existing injectable `externalScope`, since using `GlobalScope` is discouraged. `externalScope` has been changed to be a `@Singleton` and to use the main dispatcher by default. - Transform `ShareShortcutHelper` to an injectable utility class so it can use the application `Context` and `externalScope` as provided dependencies to launch a background coroutine. - Implement a custom Glide extension method `RequestBuilder.submitAsync()` to do the same thing as `RequestBuilder.submit().get()` in a non-blocking way. This way there is no need to switch to a background dispatcher and block a background thread, and cancellation is supported out-of-the-box. - An utility method `Fragment.updateRelativeTimePeriodically()` has been added to remove duplicate logic in `TimelineFragment` and `NotificationsFragment`, and the logic is now implemented using a simple coroutine instead of `Observable.interval()`. Note that the periodic update now happens between onStart and onStop instead of between onResume and onPause, since the Fragment is not interactive but is still visible in the started state. - Rewrite `BottomSheetActivityTest` using coroutines tests. - Remove all RxJava library dependencies.
2024-02-29 15:28:48 +01:00
fun search_withPreviousCancellation_completes() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
// begin/cancel account search
activity.viewUrl(accountQuery)
activity.cancelActiveSearch()
// begin status search
activity.viewUrl(statusQuery)
// ensure that search is still ongoing
assertTrue(activity.isSearching())
// return searchResults
testScheduler.advanceTimeBy(100.milliseconds)
// ensure that the result of the status search was recorded
// and the account search wasn't
assertEquals(status.id, activity.statusId)
assertEquals(null, activity.accountId)
} finally {
Dispatchers.resetMain()
}
}
class FakeBottomSheetActivity(api: MastodonApi) : BottomSheetActivity() {
var statusId: String? = null
var accountId: String? = null
var link: String? = null
var fallbackBehavior: PostLookupFallbackBehavior? = null
init {
mastodonApi = api
bottomSheet = mock()
}
override fun openLink(url: String) {
this.link = url
}
override fun viewAccount(id: String) {
this.accountId = id
}
override fun viewThread(statusId: String, url: String?) {
this.statusId = statusId
}
override fun performUrlFallbackAction(url: String, fallbackBehavior: PostLookupFallbackBehavior) {
this.link = url
this.fallbackBehavior = fallbackBehavior
}
}
}