Merge branch 'provider-contract' into integration-0.110.9
# Conflicts: # android/app/build.gradle.kts
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/** Step 3 (8 November 2026): the catalogue import through the contract writes exactly what today's import writes. */
|
||||
class CatalogueViaProviderTest {
|
||||
/** A library with the awkward rows real servers have: an episode in the list, a row with no title, a bad id. */
|
||||
private class Awkward : EmbyTransport {
|
||||
val rows = (1..37).map { i -> JSONObject().put("Id", "item$i").put("Type", if (i % 5 == 0) "Series" else "Movie").put("Name", "Fictional $i")
|
||||
.put("ProductionYear", 1980 + i).put("RunTimeTicks", (40L + i) * 60_000 * 10_000).put("OfficialRating", if (i % 3 == 0) "" else "15")
|
||||
.put("Genres", JSONArray().put("Drama")).put("Studios", JSONArray().put(JSONObject().put("Name", "Studio $i")))
|
||||
.put("ProviderIds", JSONObject().put("Imdb", "tt00$i").put("Tmdb", "$i")).put("PremiereDate", "${1980 + i}-01-01T00:00:00Z")
|
||||
.put("OriginalTitle", if (i % 7 == 0) "Original $i" else "").put("Tags", JSONArray().put("tag$i")) } +
|
||||
listOf(JSONObject().put("Id", "ep1").put("Type", "Episode").put("Name", "An episode"), JSONObject().put("Id", "untitled").put("Type", "Movie"),
|
||||
JSONObject().put("Id", "../bad").put("Type", "Movie").put("Name", "Bad id"))
|
||||
override fun execute(request: EmbyRequest): EmbyReply {
|
||||
val q = { k: String -> Regex("[?&]$k=([^&]*)").find(request.path)!!.groupValues[1] }
|
||||
val start = q("StartIndex").toInt(); val limit = q("Limit").toInt()
|
||||
return EmbyReply(200, JSONObject().put("Items", JSONArray(rows.drop(start).take(limit))).put("TotalRecordCount", if (request.path.contains("EnableTotalRecordCount=false")) 0 else rows.size).toString())
|
||||
}
|
||||
}
|
||||
private class Capture : CatalogueSink {
|
||||
var pos = 0L; val writes = mutableListOf<List<Any?>>()
|
||||
override fun position(userId: String) = pos
|
||||
override fun write(userId: String, records: List<CatalogueRecord>, nextStart: Long, total: Long?, finished: Boolean) { writes += listOf(records, nextStart, total, finished); pos = nextStart }
|
||||
}
|
||||
private fun provider(t: EmbyTransport) = EmbyProvider(EmbySampleSession(t, "fixture-token-private", "fixtureuser", EmbySample(emptyList(), 0)), t, "fixtureuser",
|
||||
{ "fixture-token-private" }, ProviderKind.Emby, "fixtureserver1", images = { null })
|
||||
|
||||
@Test fun importThroughTheContractWritesTheSameRecordsPositionsAndTotals() {
|
||||
for (pageSize in listOf(5, 200)) {
|
||||
val t = Awkward(); val today = Capture(); val via = Capture(); val p = provider(t)
|
||||
importCatalogue(t, "fixtureuser", { "fixture-token-private" }, today, maxPages = 50, fetch = { s, _, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, pageSize, w) })
|
||||
importCatalogue(t, "fixtureuser", { "fixture-token-private" }, via, maxPages = 50, fetch = { s, _, w -> cataloguePageVia(p, s, pageSize, w) })
|
||||
assertEquals(today.writes, via.writes)
|
||||
assertEquals(37, today.writes.sumOf { (it[0] as List<*>).size })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theShadowComparisonFindsThemIdenticalAndNeverWrites() {
|
||||
val t = Awkward(); val p = provider(t)
|
||||
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) }, { s, n, w -> cataloguePageVia(p, s, n, w) }, 50)
|
||||
assertTrue(r.getBoolean("identical")); assertEquals(37, r.getInt("records")); assertEquals(40L, r.getLong("positionReached"))
|
||||
assertFalse(r.getBoolean("wroteCatalogue"))
|
||||
assertTrue(r.has("todayMs") && r.has("providerMs") && r.has("heapPeakKb"))
|
||||
}
|
||||
|
||||
@Test fun theShadowComparisonReportsADifferenceByIdOnly() {
|
||||
val t = Awkward(); val p = provider(t)
|
||||
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) },
|
||||
{ s, n, w -> cataloguePageVia(p, s, n, w).let { pg -> CataloguePage(pg.records.map { if (it.id == "item3") it.copy(year = 1900) else it }, pg.rawCount, pg.total) } }, 50)
|
||||
assertFalse(r.getBoolean("identical")); assertEquals(1, r.getInt("mismatches"))
|
||||
assertEquals("item3", r.getJSONArray("firstMismatches").getJSONObject(0).getJSONArray("ids").getString(0))
|
||||
assertFalse(r.toString().contains("Fictional")) // no titles in the report
|
||||
}
|
||||
|
||||
@Test fun theShadowComparisonRecordsAnErrorInsteadOfFailing() {
|
||||
val t = Awkward()
|
||||
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) }, { _, _, _ -> throw EmbyCheckException("down", retryable = true) }, 5)
|
||||
assertFalse(r.getBoolean("identical")); assertTrue(r.getString("error").startsWith("EmbyCheckException"))
|
||||
}
|
||||
|
||||
@Test fun sanitisingKeepsStructureAndRemovesTitles() {
|
||||
val raw = JSONObject().put("Items", JSONArray(Awkward().rows)).put("TotalRecordCount", 40).toString()
|
||||
val clean = sanitiseCataloguePage(raw)
|
||||
assertEquals(40, clean.getJSONArray("Items").length()); assertEquals(40, clean.getInt("TotalRecordCount"))
|
||||
assertFalse(clean.toString().contains("Fictional"))
|
||||
val before = fetchCataloguePage(EmbyTransport { EmbyReply(200, raw) }, "fixtureuser", { "x" }, 0, 200)
|
||||
val after = fetchCataloguePage(EmbyTransport { EmbyReply(200, clean.toString()) }, "fixtureuser", { "x" }, 0, 200)
|
||||
assertEquals(before.records.map { Triple(it.id, it.type, it.runtimeMs) }, after.records.map { Triple(it.id, it.type, it.runtimeMs) })
|
||||
assertEquals(before.rawCount, after.rawCount)
|
||||
assertEquals("tt777", after.records.first { it.id == "item7" }.providerIds["Imdb"]) // "tt007": same length, digits replaced
|
||||
}
|
||||
|
||||
@Test fun theSwitchStartsOff() { assertFalse(ProviderSwitches.catalogue) }
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* A recorded-style Emby/Jellyfin library for the contract (8 November 2026): the replies are shaped exactly as the
|
||||
* server sends them to today's readers (catalogue pages, whole series, collections, evidence, PlaybackInfo). The media
|
||||
* is fictional. [fail] makes every call fail one way: 401s, a dropped connection, or a reply that isn't JSON.
|
||||
*/
|
||||
internal class FixtureEmbyServer(private val fail: ProviderError? = null) : EmbyTransport {
|
||||
val requests = mutableListOf<String>()
|
||||
private val films = (1..9).map { i -> JSONObject().put("Id", "film$i").put("Type", "Movie").put("Name", "Fictional Film $i").put("ProductionYear", 1990 + i)
|
||||
.put("RunTimeTicks", 95L * 60_000 * 10_000).put("OfficialRating", "PG").put("Genres", JSONArray().put("Comedy")).put("PremiereDate", "${1990 + i}-05-01T00:00:00Z") }
|
||||
private val shows = (1..3).map { i -> JSONObject().put("Id", "show$i").put("Type", "Series").put("Name", "Fictional Show $i").put("ProductionYear", 2000 + i) }
|
||||
private val items = films + shows
|
||||
private fun episode(s: Int, e: Int) = JSONObject().put("Id", "ep${s}x$e").put("Type", "Episode").put("Name", "Episode $s.$e").put("SeriesId", "show1")
|
||||
.put("ParentIndexNumber", s).put("IndexNumber", e).put("RunTimeTicks", 30L * 60_000 * 10_000)
|
||||
.put("MediaSources", JSONArray().put(JSONObject().put("Id", "src${s}x$e").put("Container", "mkv").put("RunTimeTicks", 30L * 60_000 * 10_000)))
|
||||
private fun page(rows: List<JSONObject>, total: Int) = EmbyReply(200, JSONObject().put("Items", JSONArray(rows)).put("TotalRecordCount", total).toString())
|
||||
private fun q(path: String, key: String) = Regex("[?&]$key=([^&]*)").find(path)?.groupValues?.get(1)
|
||||
|
||||
override fun execute(request: EmbyRequest): EmbyReply {
|
||||
requests += "${request.method} ${request.path.substringBefore('?')}"
|
||||
when (fail) {
|
||||
ProviderError.Authentication -> return EmbyReply(401, "")
|
||||
ProviderError.Unreachable -> throw EmbyCheckException("The provider did not answer in time (connect to https://bk2.appboxmanager.xyz).", retryable = true)
|
||||
ProviderError.InvalidResponse -> return EmbyReply(200, "<html>fixture-token-private</html>")
|
||||
else -> {}
|
||||
}
|
||||
val p = request.path
|
||||
return when {
|
||||
p.startsWith("/Items/") && p.endsWith("/PlaybackInfo") -> {
|
||||
val id = p.removePrefix("/Items/").removeSuffix("/PlaybackInfo")
|
||||
if (items.none { it.getString("Id") == id } && !id.startsWith("ep")) return EmbyReply(404, "")
|
||||
val direct = id != "film9"
|
||||
EmbyReply(200, JSONObject().put("PlaySessionId", "play1").put("ErrorCode", JSONObject.NULL).put("MediaSources", JSONArray().put(
|
||||
JSONObject().put("Id", "src-$id").put("Container", "mkv").put("SupportsDirectPlay", direct).put("SupportsDirectStream", direct))).toString())
|
||||
}
|
||||
p.startsWith("/Shows/show1/Episodes") -> if (q(p, "Season") == "0") page(listOf(episode(0, 1), episode(0, 2)), 2)
|
||||
else page(((1..2).flatMap { s -> (1..4).map { e -> episode(s, e) } }).drop(q(p, "StartIndex")!!.toInt()), 8)
|
||||
p.startsWith("/Items?") && q(p, "IncludeItemTypes") == "BoxSet" -> page(listOf(JSONObject().put("Id", "set1").put("Name", "Fictional Saga")).drop(q(p, "StartIndex")!!.toInt()), 1)
|
||||
p.startsWith("/Items?") && q(p, "ParentId") == "set1" -> page(listOf("film1", "film2", "film3").map { JSONObject().put("Id", it) }, 3)
|
||||
p.startsWith("/Items?") && q(p, "Ids") != null -> { val ids = q(p, "Ids")!!.split(','); page(items.filter { it.getString("Id") in ids }.map { JSONObject(it.toString()).put("Overview", "A fictional synopsis.") }, ids.size) }
|
||||
p.startsWith("/Items?") && q(p, "IncludeItemTypes") == "Movie,Series" -> {
|
||||
val start = q(p, "StartIndex")!!.toInt(); val limit = q(p, "Limit")!!.toInt()
|
||||
page(items.drop(start).take(limit), items.size)
|
||||
}
|
||||
else -> EmbyReply(404, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pictures as the server sends them, resized to the asked width; only film1 has one. */
|
||||
internal fun fixtureImages(path: String): ByteArray? {
|
||||
if (!path.startsWith("/Items/film1/")) return null
|
||||
val width = minOf(1280, Regex("maxWidth=(\\d+)").find(path)!!.groupValues[1].toInt())
|
||||
return ByteArrayOutputStream().also { ImageIO.write(BufferedImage(width, width * 9 / 16, BufferedImage.TYPE_INT_RGB), "png", it) }.toByteArray()
|
||||
}
|
||||
|
||||
internal fun fixtureEmby(kind: ProviderKind = ProviderKind.Emby, fail: ProviderError? = null, server: FixtureEmbyServer = FixtureEmbyServer(fail)): EmbyProvider {
|
||||
val session = EmbySampleSession(server, "fixture-token-private", "fixtureuser", EmbySample(emptyList(), 0))
|
||||
return EmbyProvider(session, server, "fixtureuser", { "fixture-token-private" }, kind, "fixtureserver1", images = ::fixtureImages)
|
||||
}
|
||||
|
||||
internal fun embyFixture(kind: ProviderKind) = ContractFixture(
|
||||
catalogueSize = 12, series = ItemId("show1"), seriesEpisodes = 8, seriesSpecials = 2, collections = 1,
|
||||
known = listOf(ItemId("film1"), ItemId("show2")), missing = ItemId("gone1"),
|
||||
withArtwork = ItemId("film1"), withoutArtwork = ItemId("film2"), playable = ItemId("film1"), unplayable = ItemId("film9"),
|
||||
secrets = listOf("fixture-token-private", "appboxmanager", "fixtureuser"), failing = { e -> fixtureEmby(kind, e) })
|
||||
|
||||
/** Emby, through today's code, keeps the whole contract. */
|
||||
class EmbyProviderContractTest : MediaProviderContract() {
|
||||
override fun provider(): MediaProvider = fixtureEmby(ProviderKind.Emby)
|
||||
override fun fixture() = embyFixture(ProviderKind.Emby)
|
||||
}
|
||||
|
||||
/** Jellyfin is the same adapter and the same readers; its own path and header differences are covered by EmbyClientTest. */
|
||||
class JellyfinProviderContractTest : MediaProviderContract() {
|
||||
override fun provider(): MediaProvider = fixtureEmby(ProviderKind.Jellyfin)
|
||||
override fun fixture() = embyFixture(ProviderKind.Jellyfin)
|
||||
}
|
||||
|
||||
/** The adapter hands back exactly what today's catalogue import writes: wrapping changed nothing. */
|
||||
class EmbyProviderParityTest {
|
||||
@Test fun catalogueMatchesTodaysImport() {
|
||||
val server = FixtureEmbyServer()
|
||||
val written = mutableListOf<CatalogueRecord>()
|
||||
importCatalogue(server, "fixtureuser", { "fixture-token-private" }, object : CatalogueSink {
|
||||
var pos = 0L
|
||||
override fun position(userId: String) = pos
|
||||
override fun write(userId: String, records: List<CatalogueRecord>, nextStart: Long, total: Long?, finished: Boolean) { written += records; pos = nextStart }
|
||||
}, maxPages = 10)
|
||||
val viaContract = runBlocking { fixtureEmby(server = server).catalogue(PageRequest(0, 200)) }.items
|
||||
assertEquals(written.map { it.id to it.title }, viaContract.map { it.id.value to it.title })
|
||||
assertEquals(written.map { it.runtimeMs }, viaContract.map { it.runtimeMs })
|
||||
assertEquals(written.map { it.year }, viaContract.map { it.year })
|
||||
}
|
||||
|
||||
@Test fun episodesMatchTodaysWholeSeriesRead() {
|
||||
val server = FixtureEmbyServer()
|
||||
val today = readWholeSeries(server, "fixtureuser", { "fixture-token-private" }, SeriesCandidate("show1", "", null, "")).episodes
|
||||
val viaContract = runBlocking { fixtureEmby(server = server).episodes(ItemId("show1")) }
|
||||
assertEquals(today.map { Triple(it.id, it.sourceId, it.mark) }, viaContract.map { Triple(it.id.value, it.sources.single().value, EpisodeMark(it.season, it.episode)) })
|
||||
}
|
||||
|
||||
@Test fun libraryIsTheServersOwnIdNotItsAddress() {
|
||||
assertEquals("emby:fixtureserver1", fixtureEmby().library.value)
|
||||
assertEquals("jellyfin:fixtureserver1", fixtureEmby(ProviderKind.Jellyfin).library.value)
|
||||
}
|
||||
|
||||
@Test fun progressCanBeTurnedOff() {
|
||||
val server = FixtureEmbyServer()
|
||||
val session = EmbySampleSession(server, "fixture-token-private", "fixtureuser", EmbySample(emptyList(), 0))
|
||||
val off = EmbyProvider(session, server, "fixtureuser", { "fixture-token-private" }, ProviderKind.Emby, "fixtureserver1", ::fixtureImages, progressOn = { false })
|
||||
runBlocking { off.prepare(ItemId("film1")); off.reportProgress(ItemId("film1"), 60_000, PlaybackState.Started) }
|
||||
assertEquals(0, server.requests.count { it.contains("/Sessions/Playing") })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* The shared provider contract tests (8 November 2026; "Orbit provider contract proposal", section 5). Written once,
|
||||
* run against every adapter with that adapter's own fixture library; an adapter ships only when all of them pass.
|
||||
* Each check is a plain function in [ProviderContractChecks], so ContractCatchesFlawsTest can prove every check really
|
||||
* fails on the flaw it is there to catch.
|
||||
*/
|
||||
internal class ContractFixture(
|
||||
/** Films and series in the fixture library. */
|
||||
val catalogueSize: Int,
|
||||
/** A series with [seriesEpisodes] regular episodes and [seriesSpecials] specials. */
|
||||
val series: ItemId, val seriesEpisodes: Int, val seriesSpecials: Int,
|
||||
/** A collection-capable provider's collections, or zero. */
|
||||
val collections: Int,
|
||||
/** Items that have details, and one that doesn't exist. */
|
||||
val known: List<ItemId>, val missing: ItemId,
|
||||
/** An item with a picture wider than 400 px, and one with none. */
|
||||
val withArtwork: ItemId, val withoutArtwork: ItemId,
|
||||
/** An item that plays directly, and one the box can't play directly. */
|
||||
val playable: ItemId, val unplayable: ItemId,
|
||||
/** Tokens, passwords and addresses that must never appear in anything loggable. */
|
||||
val secrets: List<String>,
|
||||
/** The same provider set up to fail in a given way (expired sign-in, unreachable, unreadable replies). */
|
||||
val failing: (ProviderError) -> MediaProvider,
|
||||
)
|
||||
|
||||
internal object ProviderContractChecks {
|
||||
private fun check(ok: Boolean, what: () -> String) { if (!ok) throw AssertionError(what()) }
|
||||
private fun everything(p: MediaProvider, pageSize: Int = 7): List<CatalogueItem> = runBlocking {
|
||||
val out = ArrayList<CatalogueItem>(); var start = 0
|
||||
while (true) { val page = p.catalogue(PageRequest(start, pageSize)); out += page.items; start = if (page.next >= 0) page.next else start + page.items.size; if (page.items.isEmpty() || start >= page.total) break }
|
||||
out
|
||||
}
|
||||
|
||||
/** 1. The same item has the same id on every read and across paging: stored bookings depend on it. */
|
||||
fun idsAreStable(p: MediaProvider, f: ContractFixture) {
|
||||
val a = everything(p, 7).map { it.title to it.id }.toSet(); val b = everything(p, 3).map { it.title to it.id }.toSet()
|
||||
check(a == b) { "ids changed between reads" }
|
||||
val e1 = runBlocking { p.episodes(f.series) }.map { it.id }; val e2 = runBlocking { p.episodes(f.series) }.map { it.id }
|
||||
check(e1 == e2) { "episode ids changed between reads" }
|
||||
}
|
||||
|
||||
/** 2. Every id fits today's rule, so it can be stored where Emby ids are stored now. */
|
||||
fun idsFitTheRule(p: MediaProvider, f: ContractFixture) {
|
||||
val ids = everything(p).map { it.id.value } + runBlocking { p.episodes(f.series, includeSpecials = true) }.flatMap { listOf(it.id.value) + it.sources.map { s -> s.value } }
|
||||
check(ids.all(::validMediaId)) { "an id breaks the rule" }
|
||||
check(Regex("(emby|jellyfin|silo|plex|local):.+").matches(p.library.value)) { "library id has no kind" }
|
||||
}
|
||||
|
||||
/** 3. Paging returns every item exactly once, and the total matches. */
|
||||
fun catalogueIsComplete(p: MediaProvider, f: ContractFixture) {
|
||||
val all = everything(p, 4)
|
||||
check(all.size == f.catalogueSize) { "expected ${f.catalogueSize} items, got ${all.size}" }
|
||||
check(all.map { it.id }.toSet().size == all.size) { "an item came back twice" }
|
||||
check(runBlocking { p.catalogue(PageRequest(0, 1)) }.total == f.catalogueSize) { "total doesn't match" }
|
||||
}
|
||||
|
||||
/** 4. Each film and series can be scheduled: a title, a film or series type, and a runtime when there is one. */
|
||||
fun catalogueItemsAreUsable(p: MediaProvider, f: ContractFixture) {
|
||||
everything(p).forEach { item ->
|
||||
check(item.title.isNotBlank()) { "${item.id} has no title" }
|
||||
check(item.type == MediaType.Movie || item.type == MediaType.Series) { "${item.id} is ${item.type} in the catalogue" }
|
||||
check(item.runtimeMs == null || item.runtimeMs > 0) { "${item.id} has a runtime of ${item.runtimeMs}" }
|
||||
}
|
||||
}
|
||||
|
||||
/** 5. Episodes come in season then episode order; specials only when asked. */
|
||||
fun episodesAreInOrder(p: MediaProvider, f: ContractFixture) {
|
||||
val regular = runBlocking { p.episodes(f.series) }
|
||||
check(regular.size == f.seriesEpisodes) { "expected ${f.seriesEpisodes} episodes, got ${regular.size}" }
|
||||
check(regular.none { it.season == 0 }) { "a special came back unasked" }
|
||||
check(regular == regular.sortedWith(compareBy({ it.season }, { it.episode }))) { "episodes out of order" }
|
||||
check(regular.all { it.seriesId == f.series }) { "an episode names another series" }
|
||||
check(runBlocking { p.episodes(f.series, includeSpecials = true) }.size == f.seriesEpisodes + f.seriesSpecials) { "specials missing when asked" }
|
||||
}
|
||||
|
||||
/** 6. Every collection member is in the catalogue; without the capability the list is empty, not an error. */
|
||||
fun collectionsHoldRealMembers(p: MediaProvider, f: ContractFixture) {
|
||||
val page = runBlocking { p.collections(PageRequest(0, 100)) }
|
||||
if (Capability.Collections !in p.capabilities) { check(page.items.isEmpty()) { "collections without the capability" }; return }
|
||||
check(page.items.size == f.collections) { "expected ${f.collections} collections, got ${page.items.size}" }
|
||||
val known = everything(p).map { it.id }.toSet()
|
||||
page.items.forEach { c -> check(c.members.all { it in known }) { "${c.name} has a member that isn't in the catalogue" } }
|
||||
}
|
||||
|
||||
/** 7. Details leave unknown ids out instead of failing, and a full batch works. */
|
||||
fun detailsSkipTheUnknown(p: MediaProvider, f: ContractFixture) {
|
||||
val got = runBlocking { p.details(f.known + f.missing) }.map { it.id }
|
||||
check(got.toSet() == f.known.toSet()) { "details returned $got" }
|
||||
val batch = everything(p).map { it.id }.take(DETAILS_BATCH_MAX)
|
||||
check(runBlocking { p.details(batch) }.size <= batch.size) { "more details than asked" }
|
||||
}
|
||||
|
||||
/** 8. Artwork never throws for a missing picture, and is never wider than asked. */
|
||||
fun artworkIsBounded(p: MediaProvider, f: ContractFixture) {
|
||||
check(runBlocking { p.artwork(f.withoutArtwork, ArtworkKind.Backdrop, 400) } == null) { "a missing picture wasn't null" }
|
||||
check(runBlocking { p.artwork(f.missing, ArtworkKind.Poster, 400) } == null) { "a missing item's picture wasn't null" }
|
||||
val bytes = runBlocking { p.artwork(f.withArtwork, ArtworkKind.Backdrop, 400) }
|
||||
check(bytes != null) { "the picture didn't come back" }
|
||||
val image = ImageIO.read(ByteArrayInputStream(bytes!!))
|
||||
check(image != null && image.width <= 400) { "picture is ${image?.width} px wide, asked for 400" }
|
||||
}
|
||||
|
||||
/** 9. Playback is the original file, played directly: no transcoding asked of the server. */
|
||||
fun playbackIsDirect(p: MediaProvider, f: ContractFixture) {
|
||||
val plan = runBlocking { p.prepare(f.playable) }
|
||||
check(plan.directPlay) { "plan isn't direct play" }
|
||||
check(!Regex("(?i)transcod|/master\\.m3u8|videobitrate|maxstreamingbitrate").containsMatchIn(plan.uri)) { "plan asks the server to transcode" }
|
||||
}
|
||||
|
||||
/** 10. No token, password or address appears in a plan's loggable form or in an error message. */
|
||||
fun credentialsStayOutOfLogs(p: MediaProvider, f: ContractFixture) {
|
||||
val plan = runBlocking { p.prepare(f.playable) }
|
||||
val texts = listOf(plan.loggable(), plan.toString()) + ProviderError.entries.mapNotNull { e ->
|
||||
runCatching { runBlocking { f.failing(e).catalogue(PageRequest(0, 5)) } }.exceptionOrNull()?.let { "${it.message} ${it.cause?.message}" } }
|
||||
f.secrets.forEach { s -> check(texts.none { it.contains(s) }) { "a secret appears in something loggable" } }
|
||||
}
|
||||
|
||||
/** 11. Failures are the same kinds for every provider. */
|
||||
fun errorsAreUniform(p: MediaProvider, f: ContractFixture) {
|
||||
for (e in listOf(ProviderError.Authentication, ProviderError.Unreachable, ProviderError.InvalidResponse)) {
|
||||
val thrown = runCatching { runBlocking { f.failing(e).catalogue(PageRequest(0, 5)) } }.exceptionOrNull()
|
||||
check(thrown is ProviderException && thrown.error == e) { "$e came back as $thrown" }
|
||||
}
|
||||
val gone = runCatching { runBlocking { p.prepare(f.missing) } }.exceptionOrNull()
|
||||
check(gone is ProviderException && gone.error == ProviderError.NotFound) { "a missing item came back as $gone" }
|
||||
val cant = runCatching { runBlocking { p.prepare(f.unplayable) } }.exceptionOrNull()
|
||||
check(cant is ProviderException && cant.error == ProviderError.UnsupportedPlayback) { "an unplayable item came back as $cant" }
|
||||
}
|
||||
|
||||
/** 12. Progress is optional: without the capability, reporting does nothing and never fails. */
|
||||
fun progressIsOptional(p: MediaProvider, f: ContractFixture) {
|
||||
val failure = runCatching { runBlocking { p.reportProgress(f.playable, 60_000, PlaybackState.Progress) } }.exceptionOrNull()
|
||||
check(failure == null) { "reporting progress failed: $failure" }
|
||||
}
|
||||
|
||||
val all: List<Pair<String, (MediaProvider, ContractFixture) -> Unit>> = listOf(
|
||||
"ids are stable" to ::idsAreStable, "ids fit the rule" to ::idsFitTheRule, "catalogue is complete" to ::catalogueIsComplete,
|
||||
"catalogue items are usable" to ::catalogueItemsAreUsable, "episodes are in order" to ::episodesAreInOrder,
|
||||
"collections hold real members" to ::collectionsHoldRealMembers, "details skip the unknown" to ::detailsSkipTheUnknown,
|
||||
"artwork is bounded" to ::artworkIsBounded, "playback is direct" to ::playbackIsDirect,
|
||||
"credentials stay out of logs" to ::credentialsStayOutOfLogs, "errors are uniform" to ::errorsAreUniform,
|
||||
"progress is optional" to ::progressIsOptional)
|
||||
}
|
||||
|
||||
/** Every adapter's contract test extends this, supplying its provider and fixture. */
|
||||
abstract class MediaProviderContract {
|
||||
internal abstract fun provider(): MediaProvider
|
||||
internal abstract fun fixture(): ContractFixture
|
||||
private fun run(check: (MediaProvider, ContractFixture) -> Unit) = check(provider(), fixture())
|
||||
|
||||
@Test fun t01_idsAreStable() = run(ProviderContractChecks::idsAreStable)
|
||||
@Test fun t02_idsFitTheRule() = run(ProviderContractChecks::idsFitTheRule)
|
||||
@Test fun t03_catalogueIsComplete() = run(ProviderContractChecks::catalogueIsComplete)
|
||||
@Test fun t04_catalogueItemsAreUsable() = run(ProviderContractChecks::catalogueItemsAreUsable)
|
||||
@Test fun t05_episodesAreInOrder() = run(ProviderContractChecks::episodesAreInOrder)
|
||||
@Test fun t06_collectionsHoldRealMembers() = run(ProviderContractChecks::collectionsHoldRealMembers)
|
||||
@Test fun t07_detailsSkipTheUnknown() = run(ProviderContractChecks::detailsSkipTheUnknown)
|
||||
@Test fun t08_artworkIsBounded() = run(ProviderContractChecks::artworkIsBounded)
|
||||
@Test fun t09_playbackIsDirect() = run(ProviderContractChecks::playbackIsDirect)
|
||||
@Test fun t10_credentialsStayOutOfLogs() = run(ProviderContractChecks::credentialsStayOutOfLogs)
|
||||
@Test fun t11_errorsAreUniform() = run(ProviderContractChecks::errorsAreUniform)
|
||||
@Test fun t12_progressIsOptional() = run(ProviderContractChecks::progressIsOptional)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Test
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* A reference provider: an in-memory library that keeps the contract, used to prove the contract tests themselves
|
||||
* (8 November 2026). It can be given one flaw at a time, and ContractCatchesFlawsTest shows each check fails on its flaw.
|
||||
* Its media is fictional.
|
||||
*/
|
||||
internal enum class Flaw { None, UnstableIds, PagingRepeats, EpisodesUnordered, SpecialsUnasked, StrayMember, DetailsThrow,
|
||||
WideArtwork, MissingArtworkThrows, Transcodes, LeaksToken, RawErrors, ProgressThrows }
|
||||
|
||||
internal class ReferenceProvider(private val flaw: Flaw = Flaw.None, private val failWith: ProviderError? = null) : MediaProvider {
|
||||
override val kind = ProviderKind.Jellyfin
|
||||
override val library = LibraryId.of(ProviderKind.Jellyfin, "ref0library")
|
||||
override val capabilities = setOf(Capability.Collections)
|
||||
private var reads = 0
|
||||
|
||||
private val films = (1..9).map { CatalogueItem(ItemId("film$it"), MediaType.Movie, "Fictional Film $it", 1990 + it, 95 * 60_000L) }
|
||||
private val shows = (1..3).map { CatalogueItem(ItemId("show$it"), MediaType.Series, "Fictional Show $it", 2000 + it) }
|
||||
private val items get() = films + shows
|
||||
private val episodes = (0..2).flatMap { s -> (1..(if (s == 0) 2 else 4)).map { e ->
|
||||
Episode(ItemId("ep${s}x$e"), ItemId("show1"), s, e, "Episode $s.$e", 30 * 60_000L, listOf(SourceId("src${s}x$e"))) } }
|
||||
|
||||
private fun fail() { failWith?.let { e ->
|
||||
if (flaw == Flaw.RawErrors) throw RuntimeException("GET http://192.168.1.50:8096/Items?api_key=SECRETTOKEN failed")
|
||||
throw ProviderException(e, when (e) { ProviderError.Authentication -> "Sign in again"; ProviderError.Unreachable -> "The library isn't answering"
|
||||
ProviderError.InvalidResponse -> "The library sent something Orbit can't read"; else -> e.name })
|
||||
} }
|
||||
|
||||
override suspend fun catalogue(page: PageRequest): Page<CatalogueItem> {
|
||||
fail(); reads++
|
||||
val list = if (flaw == Flaw.UnstableIds && reads % 2 == 0) items.map { it.copy(id = ItemId(it.id.value + "x")) } else items
|
||||
val from = if (flaw == Flaw.PagingRepeats) maxOf(0, page.start - 1) else page.start
|
||||
return Page(list.drop(from).take(page.limit), list.size, from + minOf(page.limit, maxOf(0, list.size - from)))
|
||||
}
|
||||
override suspend fun episodes(seriesId: ItemId, includeSpecials: Boolean): List<Episode> {
|
||||
fail()
|
||||
val chosen = episodes.filter { it.seriesId == seriesId && (includeSpecials || it.season != 0 || flaw == Flaw.SpecialsUnasked) }
|
||||
return if (flaw == Flaw.EpisodesUnordered) chosen.reversed() else chosen
|
||||
}
|
||||
override suspend fun collections(page: PageRequest): Page<MediaCollection> {
|
||||
fail()
|
||||
val all = listOf(MediaCollection(ItemId("set1"), "Fictional Saga", listOf(ItemId("film1"), ItemId("film2"), ItemId(if (flaw == Flaw.StrayMember) "film99" else "film3"))))
|
||||
return Page(all.drop(page.start).take(page.limit), all.size)
|
||||
}
|
||||
override suspend fun details(ids: List<ItemId>): List<ItemDetails> {
|
||||
fail(); require(ids.size <= DETAILS_BATCH_MAX)
|
||||
if (flaw == Flaw.DetailsThrow && ids.any { it !in items.map { i -> i.id } }) throw ProviderException(ProviderError.NotFound, "unknown item")
|
||||
return ids.filter { id -> items.any { it.id == id } }.map { ItemDetails(it, overview = "A fictional synopsis.") }
|
||||
}
|
||||
override suspend fun artwork(id: ItemId, kind: ArtworkKind, maxWidthPx: Int): ByteArray? {
|
||||
fail()
|
||||
if (id.value != "film1") { if (flaw == Flaw.MissingArtworkThrows) throw ProviderException(ProviderError.NotFound, "no picture"); return null }
|
||||
val width = if (flaw == Flaw.WideArtwork) 1280 else minOf(1280, maxWidthPx)
|
||||
return ByteArrayOutputStream().also { ImageIO.write(BufferedImage(width, width * 9 / 16, BufferedImage.TYPE_INT_RGB), "png", it) }.toByteArray()
|
||||
}
|
||||
override suspend fun prepare(item: ItemId, source: SourceId?): PlaybackPlan {
|
||||
fail()
|
||||
if (item.value == "film9") throw ProviderException(ProviderError.UnsupportedPlayback, "This file's video can't be played directly on this TV")
|
||||
if (items.none { it.id == item } && episodes.none { it.id == item }) throw ProviderException(ProviderError.NotFound, "That programme is no longer in the library")
|
||||
val uri = "http://192.168.1.50:8096/Videos/${item.value}/stream.mkv?static=true" + if (flaw == Flaw.Transcodes) "&VideoBitrate=4000000" else ""
|
||||
// A careless adapter that puts its token somewhere loggable (here the container label) is caught by check 10.
|
||||
return PlaybackPlan(uri, mapOf("X-Emby-Token" to "SECRETTOKEN"), audio = listOf(TrackInfo("1", "eng")),
|
||||
container = if (flaw == Flaw.LeaksToken) "mkv;token=SECRETTOKEN" else "mkv")
|
||||
}
|
||||
override suspend fun reportProgress(item: ItemId, positionMs: Long, state: PlaybackState) {
|
||||
if (flaw == Flaw.ProgressThrows) throw ProviderException(ProviderError.Unreachable, "no progress")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun referenceFixture(flaw: Flaw = Flaw.None) = ContractFixture(
|
||||
catalogueSize = 12, series = ItemId("show1"), seriesEpisodes = 8, seriesSpecials = 2, collections = 1,
|
||||
known = listOf(ItemId("film1"), ItemId("show2")), missing = ItemId("gone1"),
|
||||
withArtwork = ItemId("film1"), withoutArtwork = ItemId("film2"), playable = ItemId("film1"), unplayable = ItemId("film9"),
|
||||
secrets = listOf("SECRETTOKEN", "192.168.1.50"), failing = { e -> ReferenceProvider(flaw, e) })
|
||||
|
||||
/** The reference provider keeps the whole contract. */
|
||||
class ReferenceProviderContractTest : MediaProviderContract() {
|
||||
override fun provider(): MediaProvider = ReferenceProvider()
|
||||
override fun fixture() = referenceFixture()
|
||||
}
|
||||
|
||||
/** Every check fails on the flaw it is there to catch, so a passing adapter really keeps the contract. */
|
||||
class ContractCatchesFlawsTest {
|
||||
private val catches = mapOf(
|
||||
Flaw.UnstableIds to "ids are stable", Flaw.PagingRepeats to "catalogue is complete", Flaw.EpisodesUnordered to "episodes are in order",
|
||||
Flaw.SpecialsUnasked to "episodes are in order", Flaw.StrayMember to "collections hold real members", Flaw.DetailsThrow to "details skip the unknown",
|
||||
Flaw.WideArtwork to "artwork is bounded", Flaw.MissingArtworkThrows to "artwork is bounded", Flaw.Transcodes to "playback is direct",
|
||||
Flaw.LeaksToken to "credentials stay out of logs", Flaw.RawErrors to "credentials stay out of logs", Flaw.ProgressThrows to "progress is optional")
|
||||
|
||||
@Test fun eachCheckCatchesItsFlaw() {
|
||||
for ((flaw, name) in catches) {
|
||||
val check = ProviderContractChecks.all.first { it.first == name }.second
|
||||
val caught = runCatching { check(ReferenceProvider(flaw), referenceFixture(flaw)) }.exceptionOrNull()
|
||||
assertNotNull("'$name' missed $flaw", caught) // an assertion, or the adapter's own exception: either way the test fails
|
||||
}
|
||||
// Raw errors are also caught as non-uniform.
|
||||
val uniform = ProviderContractChecks.all.first { it.first == "errors are uniform" }.second
|
||||
assertNotNull(runCatching { uniform(ReferenceProvider(Flaw.RawErrors), referenceFixture(Flaw.RawErrors)) }.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test fun localIdsAreStableAndDistinct() {
|
||||
assertEquals(localMediaId("Films/Fictional Film (1991)/film.mkv"), localMediaId("/Films/Fictional Film (1991)/film.mkv"))
|
||||
assertEquals(localMediaId("Films\\A\\a.mkv"), localMediaId("Films/A/a.mkv"))
|
||||
val ids = (1..5000).map { localMediaId("Shows/Show/S01/E$it.mkv").value }
|
||||
assertEquals(ids.size, ids.toSet().size); assertEquals(32, ids.first().length); assert(ids.all(::validMediaId))
|
||||
}
|
||||
|
||||
@Test fun libraryIdsNameTheirKind() {
|
||||
assertEquals(ProviderKind.Plex, LibraryId.of(ProviderKind.Plex, "abc123").kind)
|
||||
assert(runCatching { LibraryId("192.168.0.20:8096") }.isFailure) // an address is never a library id
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user