youpipe: add tests for slice 2/3 (data/platform/ui/util targets)
- Commit
4aed00ef347ffe4bd00cb37c2f8dbd6c07ad3872- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 18:38 UTC (29 days ago)
- Parents
e130b09
Slice-targeted classes (merged, instructions): 2444/5405 = 45.2%. Module total: 7380/102319 = 7.2% (other slices/workers own the rest). 9 test files: extractor ID/URL/DeArrow rules + HttpClient fallbacks, StreamInfoItem mapping, video formatting strings, DAO CRUD + flows, DownloadManager no-op guards, CastPlayback state machine + audio-tap refusals, ChannelHeader/SelectionIndicator/FeedGrid/LinkifiedText Compose. Standouts at/near 100%: entities, LinkifiedTextKt 93.8%, ChannelInfo 93.5%, DeArrowTitle/Branding ~91%, VideoInfo 100%, Cast Transport 95.2%. Untestable remainder (JVM): History/Downloads/General/DataSettings pages and ChannelPage body need a real ViewModel (SQLCipher KeyStore + WorkManager, on-device only); DownloadWorker bodies need WorkManager + network; Cast session open/report needs a real TV; extractor kiosk/search need live YouTube. Needs an instrumented round for the page/worker bodies. (cherry picked from commit b3235312c04bd4b29cc8589d09d9c39a5b2f9b13)
Diff
youpipe/src/test/java/com/vayunmathur/youpipe/data/W5Slice2DatabaseTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/data/W5Slice2DatabaseTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/data/W5Slice2DatabaseTest.ktnew file mode 100644index 0000000000..9d027f63d1--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/data/W5Slice2DatabaseTest.kt@@ -0,0 +1,132 @@+package com.vayunmathur.youpipe.data++import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.youpipe.ui.VideoInfo+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Instant++/**+ * Slice 2/3 (w5): SubscriptionDatabase DAOs in the A-L slice — DownloadedVideo,+ * CachedRelatedVideo, HistoryVideo, ChannelPreference, KeywordPreference.+ * Robolectric in-memory database. Asserts upsert/get/delete/clear flows.+ */+@RunWith(AndroidJUnit4::class)+class W5Slice2DatabaseTest {++ private lateinit var db: SubscriptionDatabase++ private fun video(id: Long, name: String = "v$id") = VideoInfo(+ name = name,+ videoID = id,+ duration = 100,+ views = 1000,+ uploadDate = Instant.fromEpochSeconds(1_700_000_000L),+ thumbnailURL = "https://example.com/$id.jpg",+ author = "author",+ )++ @BeforeTest+ fun open() {+ db = Room.inMemoryDatabaseBuilder(+ ApplicationProvider.getApplicationContext(),+ SubscriptionDatabase::class.java,+ ).allowMainThreadQueries().build()+ }++ @AfterTest+ fun close() {+ db.close()+ }++ @Test+ fun downloadedVideo_upsertGetDelete() = runTest {+ val dao = db.downloadedVideoDao()+ val row = DownloadedVideo(+ id = 7, videoItem = video(7), filePath = "/dl/7.mp4",+ timestamp = Instant.fromEpochSeconds(10),+ )+ dao.upsert(row)+ assertEquals("/dl/7.mp4", dao.getByIdFlow(7).first()?.filePath)+ assertEquals(listOf(7L), dao.getAllFlow().first().map { it.id })+ assertEquals(1, dao.delete(row))+ assertEquals(emptyList(), dao.getAllFlow().first())+ }++ @Test+ fun cachedRelated_upsertAllGetDeleteOlder() = runTest {+ val dao = db.cachedRelatedVideoDao()+ val old = Instant.fromEpochSeconds(100)+ val fresh = Instant.fromEpochSeconds(9_999_999_999L)+ dao.upsertAll(+ listOf(+ CachedRelatedVideo(sourceVideoID = 1, videoItem = video(11), cachedAt = old),+ CachedRelatedVideo(sourceVideoID = 1, videoItem = video(12), cachedAt = fresh),+ ),+ )+ assertEquals(2, dao.getAll().size)+ dao.deleteOlderThan(Instant.fromEpochSeconds(1000))+ val remaining = dao.getAll()+ assertEquals(1, remaining.size)+ assertEquals(12L, remaining[0].videoItem.videoID)+ assertEquals(1, dao.getAllFlow().first().size)+ }++ @Test+ fun historyVideo_crud() = runTest {+ val dao = db.historyVideoDao()+ val row = HistoryVideo.fromVideoData(video(21), progress = 5_000)+ assertEquals(21L, row.id)+ assertEquals(5_000L, row.progress)+ dao.upsert(row)+ dao.upsertAll(listOf(HistoryVideo.fromVideoData(video(22), 0)))+ assertEquals(2, dao.getAll().size)+ assertEquals(2, dao.getAllFlow().first().size)+ assertEquals(5_000L, dao.getByIdFlow(21).first()?.progress)+ dao.deleteByIds(listOf(21))+ assertEquals(listOf(22L), dao.getAll().map { it.id })+ dao.delete(dao.getAll().first())+ assertEquals(emptyList(), dao.getAll())+ dao.upsert(row)+ dao.clearAll()+ assertEquals(emptyList(), dao.getAll())+ }++ @Test+ fun channelPreference_crud() = runTest {+ val dao = db.channelPreferenceDao()+ assertNull(dao.get("somechannel"))+ dao.upsert(ChannelPreference("somechannel", multiplier = 2.0, pinned = true))+ assertEquals(2.0, dao.get("somechannel")!!.multiplier, 1e-9)+ assertEquals(1, dao.getAll().size)+ dao.upsert(ChannelPreference("somechannel", multiplier = 0.5, blocked = true))+ assertTrue(dao.get("somechannel")!!.blocked)+ dao.delete("somechannel")+ assertNull(dao.get("somechannel"))+ dao.upsert(ChannelPreference("a"))+ dao.clearAll()+ assertEquals(emptyList(), dao.getAll())+ }++ @Test+ fun keywordPreference_crud() = runTest {+ val dao = db.keywordPreferenceDao()+ dao.upsert(KeywordPreference("spoiler"))+ dao.upsert(KeywordPreference("ad", muted = false))+ assertEquals(2, dao.getAll().size)+ dao.delete("spoiler")+ assertEquals(listOf("ad"), dao.getAll().map { it.keyword })+ assertEquals(false, dao.getAll().first().muted)+ dao.clearAll()+ assertEquals(emptyList(), dao.getAll())+ }+}
youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastAudioTapTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastAudioTapTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastAudioTapTest.ktnew file mode 100644index 0000000000..3908bf37ca--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastAudioTapTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.youpipe.platform++import androidx.test.ext.junit.runners.AndroidJUnit4+import java.nio.ByteBuffer+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Slice 2/3 (w5): CastAudioTap's framework-free paths (platform/+ * CastPlayback.kt). `attach(null)` is the "session has no audio" no-op;+ * `detach()` with nothing attached neither crashes nor retains buffers;+ * `flush()` with a non-PCM encoding refuses the tap so `handleBuffer`+ * drops buffers instead of forwarding noise. Robolectric: Log goes through+ * the repo facade into android.util.Log. The attached pipe path (resampling+ * math, writer thread) runs on-device where a real ParcelFileDescriptor+ * pipe exists.+ */+@RunWith(AndroidJUnit4::class)+class W5Slice2CastAudioTapTest {++ @Test+ fun attachNullAndDetachAreSafeNoOps() {+ CastAudioTap.attach(null)+ CastAudioTap.detach()+ CastAudioTap.detach()+ }++ @Test+ fun handleBuffer_withoutAttach_dropsSilently() {+ CastAudioTap.detach()+ CastAudioTap.flush(48_000, 2, android.media.AudioFormat.ENCODING_PCM_16BIT)+ // out == null: returns before touching the buffer — must not consume it.+ val buf = ByteBuffer.allocateDirect(64)+ val remaining = buf.remaining()+ CastAudioTap.handleBuffer(buf)+ assertTrue(buf.remaining() == remaining)+ }++ @Test+ fun handleBuffer_unsupportedEncoding_dropsSilently() {+ CastAudioTap.detach()+ // Float encoding is refused: anything other than interleaved 16-bit+ // would be sent as noise, so the tap stays off.+ CastAudioTap.flush(48_000, 2, android.media.AudioFormat.ENCODING_PCM_FLOAT)+ val buf = ByteBuffer.allocateDirect(64)+ CastAudioTap.handleBuffer(buf)+ CastAudioTap.detach()+ }++ @Test+ fun flush_invalidFormat_disablesTap() {+ CastAudioTap.detach()+ // Zero sample rate / zero channels are refused rather than+ // divide-by-zeroing the resampler later.+ CastAudioTap.flush(0, 0, android.media.AudioFormat.ENCODING_PCM_16BIT)+ CastAudioTap.handleBuffer(ByteBuffer.allocateDirect(64))+ CastAudioTap.detach()+ }+}
youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastStateTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastStateTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastStateTest.ktnew file mode 100644index 0000000000..91652d5c88--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/platform/W5Slice2CastStateTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.youpipe.platform++import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * Slice 2/3 (w5): CastPlayback's framework-free state machine (platform/+ * CastPlayback.kt). Robolectric: the object owns a Main-dispatcher scope and+ * touches android.util.Log through the repo facade, so plain JVM can't host+ * it. Session open/reporting need a real Cast TV (covered on-device only);+ * everything below pins the attach/detach identity guard, transport RMW+ * updates, speed clamping, and the seek/volume guards.+ */+@RunWith(AndroidJUnit4::class)+class W5Slice2CastStateTest {++ @Test+ fun state_startsIdleAndMarkConnecting() {+ CastPlayback.close()+ assertTrue(CastPlayback.state.value is CastPlayback.State.Idle)+ CastPlayback.markConnecting()+ assertTrue(CastPlayback.state.value is CastPlayback.State.Connecting)+ CastPlayback.close()+ assertTrue(CastPlayback.state.value is CastPlayback.State.Idle)+ }++ @Test+ fun close_isIdempotentAndResetsTransportFlags() {+ CastPlayback.update { it.copy(hasNext = true, hasPrevious = true, playing = true) }+ CastPlayback.close()+ CastPlayback.close()+ val t = CastPlayback.transport.value+ assertFalse(t.hasNext)+ assertFalse(t.hasPrevious)+ assertTrue(CastPlayback.state.value is CastPlayback.State.Idle)+ }++ @Test+ fun update_isReadModifyWrite() {+ CastPlayback.close()+ CastPlayback.update { it.copy(positionMs = 1_000, durationMs = 60_000, playing = true) }+ CastPlayback.update { it.copy(volume = 0.5f) }+ val t = CastPlayback.transport.value+ // Second update preserved the first update's writes.+ assertEquals(1_000L, t.positionMs)+ assertEquals(60_000L, t.durationMs)+ assertTrue(t.playing)+ assertEquals(0.5f, t.volume)+ CastPlayback.close()+ }++ @Test+ fun detachPlayer_nullClearsPlayer() {+ val fake = fakePlayer()+ CastPlayback.attachPlayer(fake)+ assertSame(fake, CastPlayback.attachedPlayer)+ // Null means "whatever is attached" outside a cast: clears, no timer.+ CastPlayback.attachPlayer(null)+ assertNull(CastPlayback.attachedPlayer)+ CastPlayback.close()+ }++ @Test+ fun detachPlayer_wrongIdentityKeepsPlayer() {+ val first = fakePlayer()+ val second = fakePlayer()+ CastPlayback.attachPlayer(first)+ // Outgoing screen disposing a stale controller must not clear the new one.+ CastPlayback.detachPlayer(second)+ assertSame(first, CastPlayback.attachedPlayer)+ CastPlayback.detachPlayer(first)+ assertNull(CastPlayback.attachedPlayer)+ CastPlayback.close()+ }++ @Test+ fun transport_defaultsAreSane() {+ val t = CastPlayback.Transport()+ assertEquals(0L, t.positionMs)+ assertEquals(1f, t.speed)+ assertEquals(1f, t.volume)+ assertFalse(t.dragging)+ assertFalse(t.hasNext)+ assertFalse(t.hasPrevious)+ }++ /**+ * A Player double via JDK dynamic proxy: attach/detach only store and+ * identity-compare the instance, never invoke it, so the handler body is+ * unreachable in these tests (and returns JVM defaults if ever called).+ * Keeps the test immune to media3 Player API additions.+ */+ private fun fakePlayer(): androidx.media3.common.Player =+ java.lang.reflect.Proxy.newProxyInstance(+ javaClass.classLoader,+ arrayOf(androidx.media3.common.Player::class.java),+ ) { _, _, _ -> null } as androidx.media3.common.Player+}
youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2ExtractorTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2ExtractorTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2ExtractorTest.ktnew file mode 100644index 0000000000..bcc27816de--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2ExtractorTest.kt@@ -0,0 +1,105 @@+package com.vayunmathur.youpipe.ui++import com.vayunmathur.youpipe.util.trustedThumbnailUrl+import com.vayunmathur.youpipe.util.trustedTitle+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * Slice 2/3 (w5): pure video-ID / URL / branding helpers in util/Extractor.kt+ * (A-L root slice). Robolectric: URL helpers go through androidx.core Uri.+ */+@RunWith(AndroidJUnit4::class)+class W5Slice2ExtractorTest {++ @Test+ fun videoId_encodesAndDecodesRoundTrip() {+ val id = 123456789012345L+ val encoded = com.vayunmathur.youpipe.util.decodeVideoID(id)+ assertEquals(id, com.vayunmathur.youpipe.util.encodeVideoID(encoded))+ }++ @Test+ fun videoUrl_roundTripsThroughId() {+ val id = 987654321L+ val url = com.vayunmathur.youpipe.util.videoIDtoURL(id)+ assertTrue(url.startsWith("https://www.youtube.com/watch?v="), url)+ assertEquals(id, com.vayunmathur.youpipe.util.videoURLtoID(url))+ }++ @Test+ fun parseSharedVideoId_findsAllUrlShapes() {+ // 11-char id "dQw4w9WgXcQ" style+ val id11 = "dQw4w9WgXcQJ"+ val expected = com.vayunmathur.youpipe.util.encodeVideoID(id11)+ assertEquals(expected, com.vayunmathur.youpipe.util.parseSharedVideoId("https://www.youtube.com/watch?v=$id11"))+ assertEquals(expected, com.vayunmathur.youpipe.util.parseSharedVideoId("https://youtu.be/$id11"))+ assertEquals(expected, com.vayunmathur.youpipe.util.parseSharedVideoId("check this https://www.youtube.com/shorts/$id11 wow"))+ assertEquals(expected, com.vayunmathur.youpipe.util.parseSharedVideoId("https://www.youtube.com/embed/$id11"))+ assertNull(com.vayunmathur.youpipe.util.parseSharedVideoId("no link here"))+ assertNull(com.vayunmathur.youpipe.util.parseSharedVideoId("https://www.youtube.com/watch?v=short"))+ }++ @Test+ fun channelUrls_handleAndIdShapes() {+ assertEquals(+ "https://www.youtube.com/@SomeChannel",+ com.vayunmathur.youpipe.util.channelIDtoURL("@SomeChannel"),+ )+ assertEquals(+ "https://www.youtube.com/channel/UC12345",+ com.vayunmathur.youpipe.util.channelIDtoURL("UC12345"),+ )+ assertEquals("UC12345", com.vayunmathur.youpipe.util.channelURLtoID("https://www.youtube.com/channel/UC12345"))+ }++ @Test+ fun sponsorSegment_startEndMillis() {+ val seg = com.vayunmathur.youpipe.util.SponsorSegment("sponsor", listOf(12.5f, 67.25f), "uuid-1")+ assertEquals(12_500L, seg.start)+ assertEquals(67_250L, seg.end)+ }++ @Test+ fun deArrowTrustedTitle_rules() {+ fun branding(title: String, original: Boolean, votes: Int, locked: Boolean) =+ com.vayunmathur.youpipe.util.DeArrowBranding(+ titles = listOf(+ com.vayunmathur.youpipe.util.DeArrowTitle(title, original, votes, locked, "u"),+ ),+ thumbnails = emptyList(),+ randomTime = 0.0,+ )+ assertEquals("Better Title", branding("Better Title>", false, 10, true).trustedTitle())+ assertNull(branding("Original", true, 100, true).trustedTitle())+ assertNull(branding("Downvoted", false, -5, false).trustedTitle())+ // locked overrides negative votes+ assertEquals("Locked", branding("Locked", false, -5, true).trustedTitle())+ assertNull(+ com.vayunmathur.youpipe.util.DeArrowBranding(emptyList(), emptyList(), 0.0).trustedTitle(),+ )+ }++ @Test+ fun deArrowThumbnailUrl_rules() {+ val id = 424242L+ fun branding(thumb: com.vayunmathur.youpipe.util.DeArrowThumbnail?) =+ com.vayunmathur.youpipe.util.DeArrowBranding(+ titles = emptyList(),+ thumbnails = listOfNotNull(thumb),+ randomTime = 0.0,+ )+ val good = branding(com.vayunmathur.youpipe.util.DeArrowThumbnail(12.5, false, 3, false, "u"))+ val url = good.trustedThumbnailUrl(id)!!+ assertTrue(url.contains("time=12.5"), url)+ assertTrue(url.contains(com.vayunmathur.youpipe.util.decodeVideoID(id)), url)+ assertNull(branding(com.vayunmathur.youpipe.util.DeArrowThumbnail(1.0, true, 3, false, "u")).trustedThumbnailUrl(id))+ assertNull(branding(com.vayunmathur.youpipe.util.DeArrowThumbnail(1.0, false, -9, false, "u")).trustedThumbnailUrl(id))+ assertNull(branding(com.vayunmathur.youpipe.util.DeArrowThumbnail(null, false, 3, false, "u")).trustedThumbnailUrl(id))+ assertNull(branding(null).trustedThumbnailUrl(id))+ }+}
youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2UiComponentsTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2UiComponentsTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2UiComponentsTest.ktnew file mode 100644index 0000000000..b05e011120--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2UiComponentsTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.youpipe.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.invisibleClickable+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * Slice 2/3 (w5): Compose coverage for the small pure UI in the A-L slice —+ * ChannelPage.kt's [ChannelHeader] (identity block; AsyncImage loads nothing+ * headless and must not break the texts) and DownloadedVideosPage.kt's+ * [SelectionIndicator] (selected vs unselected visuals), plus [FeedGrid]'s+ * compact path (single-column list on phone widths). Robolectric ++ * createComposeRule, the module's standard Compose harness.+ */+@RunWith(AndroidJUnit4::class)+class W5Slice2UiComponentsTest {++ @get:Rule+ val composeRule = createComposeRule()++ private val context: android.content.Context+ get() = ApplicationProvider.getApplicationContext()++ @Test+ fun channelHeader_showsNameAndSubscriberCount() {+ val info = ChannelInfo(+ name = "Some Channel",+ channelID = "UC12345",+ subscribers = 12_345,+ videos = 100,+ avatar = "",+ )+ composeRule.setContent { ChannelHeader(info) }+ composeRule.onNodeWithText("Some Channel").assertIsDisplayed()+ // "12.35K subscribers": substring match, the ListItem supporting+ // text wraps the count in a longer sentence.+ composeRule.onNode(hasText(countString(context, 12_345), substring = true)).assertIsDisplayed()+ }++ @Test+ fun channelHeader_decodesHtmlName() {+ val info = ChannelInfo(+ name = "Fish & Chips",+ channelID = "UC1",+ subscribers = 0,+ videos = 0,+ avatar = "",+ )+ composeRule.setContent { ChannelHeader(info) }+ composeRule.onNodeWithText("Fish & Chips").assertIsDisplayed()+ }++ @Test+ fun selectionIndicator_bothStatesCompose() {+ // SelectionIndicator carries no text; the assertion is that both+ // branches compose without crashing (selected draws the check icon,+ // unselected only the outline ring).+ composeRule.setContent {+ SelectionIndicator(isSelected = false)+ SelectionIndicator(isSelected = true)+ }+ composeRule.waitForIdle()+ }++ @Test+ fun feedGrid_compactPathRendersAllRows() {+ val rows = listOf(+ com.vayunmathur.youpipe.util.VideoRowState(videoID = 1, title = "First video"),+ com.vayunmathur.youpipe.util.VideoRowState(videoID = 2, title = "Second video"),+ com.vayunmathur.youpipe.util.VideoRowState(videoID = 3, title = "Third video"),+ )+ var opened = -1L+ composeRule.setContent {+ FeedGrid(rows = rows, key = { it.videoID }, itemContent = { row ->+ com.vayunmathur.library.ui.Text(+ row.title,+ modifier = androidx.compose.ui.Modifier.invisibleClickable { opened = row.videoID },+ )+ })+ }+ composeRule.onNodeWithText("First video").assertIsDisplayed()+ composeRule.onNodeWithText("Second video").assertIsDisplayed()+ composeRule.onNodeWithText("Third video").assertIsDisplayed()+ composeRule.onNodeWithText("Second video").performClick()+ assertEquals(2L, opened)+ }++ @Test+ fun linkifiedText_rendersTextAndKeepsTrailingPunctuationOutsideLink() {+ var shown = ""+ composeRule.setContent {+ shown = "see https://example.com/page (wow)"+ LinkifiedText(shown)+ }+ // Plain-text segments and the cleaned URL both render; the trailing+ // ")" is appended as normal text, so the full line reads correctly.+ composeRule.onNode(hasText("see https://example.com/page (wow)", substring = true)).assertExists()+ assertTrue(shown.contains("https://example.com/page"), shown)+ }++ @Test+ fun linkifiedText_bareWwwGetsHttpsAndClickOpensIt() {+ var opened: String? = null+ val fakeHandler = object : androidx.compose.ui.platform.UriHandler {+ override fun openUri(uri: String) {+ opened = uri+ }+ }+ composeRule.setContent {+ androidx.compose.runtime.CompositionLocalProvider(+ androidx.compose.ui.platform.LocalUriHandler provides fakeHandler,+ ) {+ LinkifiedText("visit www.example.com/x, ok?")+ }+ }+ // "www." prefix is resolved to https and the trailing comma stays+ // outside the link: the visible text keeps both parts.+ composeRule.onNode(hasText("www.example.com/x", substring = true)).assertIsDisplayed()+ composeRule.onNode(hasText(",", substring = true)).assertIsDisplayed()+ composeRule.onNode(hasText("www.example.com/x", substring = true)).performClick()+ assertEquals("https://www.example.com/x", opened)+ }+}
youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2VideoFormattingTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2VideoFormattingTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2VideoFormattingTest.ktnew file mode 100644index 0000000000..7568a885ec--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/ui/W5Slice2VideoFormattingTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.youpipe.ui++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.hours+import kotlin.time.Duration.Companion.minutes+import org.junit.runner.RunWith++/**+ * Slice 2/3 (w5): VideoFormatting.kt pure helpers (codec names, count strings,+ * HTML stripping). Robolectric for the Context-backed string resources.+ */+@RunWith(AndroidJUnit4::class)+class W5Slice2VideoFormattingTest {++ private val context: android.content.Context+ get() = ApplicationProvider.getApplicationContext()++ @Test+ fun videoCodecNames() {+ assertEquals("av1", getVideoCodecName("av01.0.05M.08"))+ assertEquals("vp9", getVideoCodecName("vp9"))+ assertEquals("vp9", getVideoCodecName("vp09.00.10.08"))+ assertEquals("avc", getVideoCodecName("avc1.640028"))+ assertEquals("avc", getVideoCodecName("H264-baseline"))+ assertEquals("hevc", getVideoCodecName("hevc"))+ }++ @Test+ fun audioCodecNames() {+ assertEquals("opus", getAudioCodecName("opus"))+ assertEquals("opus", getAudioCodecName("Opus audio"))+ assertEquals("aac", getAudioCodecName("mp4a.40.2"))+ assertEquals("aac", getAudioCodecName("AAC-LC"))+ assertEquals("vorbis", getAudioCodecName("vorbis"))+ }++ @Test+ fun countString_shapes() {+ assertEquals("999", countString(context, 999))+ assertEquals("0", countString(context, 0))+ val k = countString(context, 12_345)+ assertTrue(k.endsWith("K"), k)+ val m = countString(context, 2_500_000)+ assertTrue(m.endsWith("M"), m)+ val b = countString(context, 1_500_000_000)+ assertTrue(b.endsWith("B"), b)+ // 4-digit uses 2 decimals, 6-digit none+ assertTrue(countString(context, 1234).contains("."), countString(context, 1234))+ }++ @Test+ fun fromHtml_stripsBreaksAndEntities() {+ // fromHTML maps <br> to \n, then HtmlCompat collapses it to a space+ // (real fromHtml whitespace handling, not a Robolectric artifact).+ assertEquals("a b", "a<br>b".fromHTML())+ assertEquals("Fish & Chips", "Fish & Chips".fromHTML())+ }++ @Test+ fun uploadTimeAgo_buckets() {+ val now = kotlin.time.Clock.System.now()+ assertEquals("Just now", uploadTimeAgo(context, now))+ assertEquals(+ "Just now",+ uploadTimeAgo(context, now - 3.minutes),+ )+ val mins = uploadTimeAgo(context, now - 30.minutes)+ assertTrue(mins.contains("30"), mins)+ val hoursStr = uploadTimeAgo(context, now - 5.hours)+ assertTrue(hoursStr.contains("5"), hoursStr)+ // future date -> just now+ assertEquals("Just now", uploadTimeAgo(context, now + 1.hours))+ }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.ktnew file mode 100644index 0000000000..5cbaa12f56--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.kt@@ -0,0 +1,45 @@+package com.vayunmathur.youpipe.util++import kotlinx.coroutines.test.runTest+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Slice 2/3 (w5): the SponsorBlock/DeArrow fetchers in util/Extractor.kt are+ * best-effort (catch-all returns null/emptyList). With the mirrors pointed at+ * a closed loopback port the connection is refused, pinning the fallback+ * paths. (A loopback HTTP server would pin the parse paths too, but the+ * unit-test sandbox refuses loopback connections — both under Robolectric+ * and on plain JVM — so success bodies are covered on-device only.)+ */+class W5Slice2ExtractorHttpTest {++ private val realSponsor = SPONSORBLOCK_MIRROR+ private val realThumb = DEARROW_THUMB_MIRROR++ @BeforeTest+ fun pointAtClosedPort() {+ // Port 1 is never bound: connect() fails fast with "refused".+ SPONSORBLOCK_MIRROR = "http://127.0.0.1:1"+ DEARROW_THUMB_MIRROR = "http://127.0.0.1:1/api/dearrow/thumbnail"+ }++ @AfterTest+ fun restoreMirrors() {+ SPONSORBLOCK_MIRROR = realSponsor+ DEARROW_THUMB_MIRROR = realThumb+ }++ @Test+ fun getDeArrowBranding_nullWhenUnreachable() = runTest {+ assertNull(getDeArrowBranding(4242L))+ }++ @Test+ fun getSponsorSegments_emptyWhenUnreachable() = runTest {+ assertEquals(emptyList(), getSponsorSegments(4242L))+ }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorNetTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorNetTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorNetTest.ktnew file mode 100644index 0000000000..8455558ae7--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorNetTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.youpipe.util++import com.vayunmathur.youpipe.ui.VideoInfo+import org.schabi.newpipe.extractor.Image+import org.schabi.newpipe.extractor.localization.DateWrapper+import org.schabi.newpipe.extractor.stream.ContentAvailability+import org.schabi.newpipe.extractor.stream.StreamInfoItem+import org.schabi.newpipe.extractor.stream.StreamType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import androidx.test.ext.junit.runners.AndroidJUnit4++/**+ * Slice 2/3 (w5): the StreamInfoItem -> VideoInfo mapping in util/+ * Extractor.kt (pure model construction, no network). Robolectric: the+ * mapping decodes HTML via HtmlCompat.+ */+@RunWith(AndroidJUnit4::class)+class W5Slice2ExtractorNetTest {++ private fun streamItem(+ name: String,+ date: DateWrapper?,+ views: Long = 1_000,+ paid: Boolean = false,+ ): StreamInfoItem {+ val id = decodeVideoID(4242L)+ val item = StreamInfoItem(0, "https://www.youtube.com/watch?v=$id", name, StreamType.VIDEO_STREAM)+ item.setUploadDate(date)+ item.setViewCount(views)+ item.setDuration(120)+ item.setUploaderName("Some Author")+ item.setThumbnails(listOf(Image("https://example.com/t.jpg", 90, 160, Image.ResolutionLevel.MEDIUM)))+ item.setContentAvailability(if (paid) ContentAvailability.PAID else ContentAvailability.AVAILABLE)+ return item+ }++ private fun dateOf(epochSecond: Long): DateWrapper =+ DateWrapper(+ java.time.OffsetDateTime.ofInstant(+ java.time.Instant.ofEpochSecond(epochSecond), java.time.ZoneOffset.UTC,+ ),+ )++ @Test+ fun toVideoInfo_mapsAllFields() {+ val info: VideoInfo? = streamItem("Fish & Chips", dateOf(1_700_000_000L)).toVideoInfo()+ assertTrue(info != null)+ assertEquals("Fish & Chips", info.name)+ assertEquals(4242L, info.videoID)+ assertEquals(120L, info.duration)+ assertEquals(1_000L, info.views)+ assertEquals(1_700_000_000L, info.uploadDate.epochSeconds)+ assertEquals("https://example.com/t.jpg", info.thumbnailURL)+ assertEquals("Some Author", info.author)+ assertEquals(false, info.isPaid)+ }++ @Test+ fun toVideoInfo_nullWithoutUploadDate() {+ assertNull(streamItem("No date", null).toVideoInfo())+ }++ @Test+ fun toVideoInfo_paidFlagPropagates() {+ val info = streamItem("Paid", dateOf(1_700_000_000L), paid = true).toVideoInfo()+ assertEquals(true, info?.isPaid)+ }++ @Test+ fun toVideoInfo_emptyThumbnailFallsBackToBlank() {+ val item = streamItem("No thumb", dateOf(1_700_000_000L))+ item.setThumbnails(emptyList())+ assertEquals("", item.toVideoInfo()?.thumbnailURL)+ }++}
youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ManagerModelTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ManagerModelTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ManagerModelTest.ktnew file mode 100644index 0000000000..dae8d72f72--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ManagerModelTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.youpipe.util++import com.vayunmathur.youpipe.ui.ChannelInfo+import com.vayunmathur.youpipe.ui.VideoInfo+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.time.Instant++/**+ * Slice 2/3 (w5): JVM-pure coverage of the A-L slice's state holders —+ * [DownloadManager]'s progress map (the WorkManager entry points need a real+ * WorkManager and are covered on-device), plus the pure model mappings in+ * ChannelPage.kt (`ChannelInfo.toSubscription`) and Extractor.kt+ * (`SponsorSegment` bounds, `DeArrow*` edge cases beyond the main rules).+ */+class W5Slice2ManagerModelTest {++ private fun video(id: Long) = VideoInfo(+ name = "v$id",+ videoID = id,+ duration = 100,+ views = 1000,+ uploadDate = Instant.fromEpochSeconds(1_700_000_000L),+ thumbnailURL = "https://example.com/$id.jpg",+ author = "author",+ )++ @Test+ fun updateProgress_ignoresUnknownIds() {+ // The only writer of new entries is enqueueDownload, which needs a real+ // WorkManager (on-device). updateProgress/finishDownload on absent ids+ // must be strict no-ops rather than creating phantom rows.+ val before = DownloadManager.activeDownloads.value+ DownloadManager.updateProgress(videoID = -999_999L, progress = 0.5)+ DownloadManager.finishDownload(-999_999L)+ assertEquals(before, DownloadManager.activeDownloads.value)+ }++ @Test+ fun downloadStatus_holdsVideoAndProgress() {+ val info = video(5)+ val status = DownloadStatus(info, 0.25)+ assertEquals(info, status.videoInfo)+ assertEquals(0.25, status.progress)+ assertEquals(0.75, status.copy(progress = 0.75).progress)+ }++ @Test+ fun channelInfo_toSubscriptionMapsFields() {+ val info = ChannelInfo(+ name = "Some Channel",+ channelID = "UC12345",+ subscribers = 12_345,+ videos = 100,+ avatar = "https://example.com/a.jpg",+ )+ val sub = info.toSubscription()+ assertEquals("Some Channel", sub.name)+ assertEquals("UC12345", sub.channelID)+ assertEquals("https://example.com/a.jpg", sub.avatarURL)+ }++ @Test+ fun sponsorSegment_truncatesTowardZero() {+ // 12.999s -> 12999ms, not 13000: (Float * 1000).toLong() truncates.+ val seg = SponsorSegment("intro", listOf(12.999f, 67.001f), "u")+ assertEquals(12_999L, seg.start)+ assertEquals(67_001L, seg.end)+ }++ @Test+ fun deArrowTitle_trimsWhitespaceAndGT() {+ val branding = DeArrowBranding(+ titles = listOf(DeArrowTitle(" Padded Title>> ", false, 0, false, "u")),+ thumbnails = emptyList(),+ randomTime = 0.0,+ )+ assertEquals("Padded Title", branding.trustedTitle())+ }++ @Test+ fun deArrowThumbnail_zeroTimestampKept() {+ // timestamp 0.0 is a real frame; only null means "no thumbnail".+ val branding = DeArrowBranding(+ titles = emptyList(),+ thumbnails = listOf(DeArrowThumbnail(0.0, false, 1, false, "u")),+ randomTime = 0.0,+ )+ val url = branding.trustedThumbnailUrl(7L)+ assertTrue(url != null && url.contains("time=0.0"), url)+ }+}