Add Jellyfin client service layers

This commit is contained in:
Brendan Szymanski 2026-08-04 03:13:25 -04:00
parent 2b88f739f1
commit a5ee2edf5d
47 changed files with 5480 additions and 18 deletions

View file

@ -0,0 +1,101 @@
//
// JellyfinModelTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Testing
@testable import LuminateCore
/// Guards the wire spellings Luminate's domain enums promise the service layer.
///
/// These raw values are the entire contract between ``LuminateCore`` and the generated Jellyfin
/// client: mapping is a `rawValue` round trip, so a typo here silently drops data at runtime rather
/// than failing to compile.
@Suite struct JellyfinModelTests {
@Test("Media kind raw values match the server spellings")
func mediaKindRawValues() {
#expect(JellyfinMediaKind.movie.rawValue == "Movie")
#expect(JellyfinMediaKind.boxSet.rawValue == "BoxSet")
#expect(JellyfinMediaKind.collectionFolder.rawValue == "CollectionFolder")
#expect(JellyfinMediaKind(rawValue: "Episode") == .episode)
#expect(JellyfinMediaKind(rawValue: "MusicAlbum") == nil)
}
@Test("Collection type raw values are lowercase, as the server sends them")
func collectionTypeRawValues() {
#expect(JellyfinCollectionType(rawValue: "tvshows") == .tvShows)
#expect(JellyfinCollectionType(rawValue: "movies") == .movies)
#expect(JellyfinCollectionType(rawValue: "boxsets") == .boxSets)
#expect(JellyfinCollectionType(rawValue: "TvShows") == nil)
#expect(JellyfinCollectionType(rawValue: "music") == nil)
}
@Test("Sort field and item field keep their irregular server spellings")
func irregularRawValues() {
#expect(JellyfinSortField.defaultOrder.rawValue == "Default")
#expect(JellyfinSortField.airedEpisodeOrder.rawValue == "AiredEpisodeOrder")
#expect(JellyfinItemField.isHighDefinition.rawValue == "IsHD")
#expect(JellyfinItemField.providerIDs.rawValue == "ProviderIds")
#expect(JellyfinItemField.parentID.rawValue == "ParentId")
}
@Test("Image type and format raw values match the server spellings")
func imageRawValues() {
#expect(JellyfinImageType.primary.rawValue == "Primary")
#expect(JellyfinImageType.boxRear.rawValue == "BoxRear")
#expect(JellyfinImageFormat.jpg.rawValue == "Jpg")
#expect(JellyfinSortOrder.descending.rawValue == "Descending")
}
@Test("An empty query sends nothing, so the server applies its own defaults")
func emptyQueryIsFullyUnset() {
let query = JellyfinMediaQuery()
#expect(query.userID == nil)
#expect(query.parentID == nil)
#expect(query.includeItemKinds == nil)
#expect(query.sortBy == nil)
#expect(query.limit == nil)
#expect(query.recursive == nil)
#expect(query.enableImageTypes == nil)
}
@Test("Empty list options send nothing")
func emptyListOptionsAreFullyUnset() {
let options = JellyfinListOptions()
#expect(options.userID == nil)
#expect(options.parentID == nil)
#expect(options.seasonID == nil)
#expect(options.season == nil)
#expect(options.limit == nil)
#expect(options.fields == nil)
#expect(options.includeItemKinds == nil)
#expect(options.includeHidden == nil)
#expect(options.groupItems == nil)
}
@Test("Collection defaults are empty rather than nil")
func collectionDefaults() {
#expect(JellyfinMediaPage().items.isEmpty)
#expect(JellyfinMediaPage().totalRecordCount == nil)
#expect(JellyfinMediaItem().imageTags.isEmpty)
#expect(JellyfinMediaItem().backdropImageTags.isEmpty)
#expect(JellyfinLibrary().backdropImageTags.isEmpty)
}
}

View file

@ -0,0 +1,57 @@
//
// UnconfiguredJellyfinServiceTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Testing
@testable import LuminateCore
/// Proves the placeholder service fails loudly instead of silently doing nothing.
///
/// This is what a subtree sees when `.environment(\\.client, ...)` was forgotten, so every route
/// into it -- full-arity requirement and reduced-arity convenience alike -- must throw.
@Suite struct UnconfiguredJellyfinServiceTests {
private let service = UnconfiguredJellyfinService.shared
@Test("Reports itself unauthenticated")
func neverAuthenticated() {
#expect(service.isAuthenticated == false)
}
@Test("A full-arity requirement throws notConfigured")
func requirementThrows() async {
await #expect(throws: JellyfinClientError.notConfigured) {
_ = try await service.publicUsers()
}
}
@Test("A convenience overload forwards to the requirement and still throws")
func convenienceThrows() async {
await #expect(throws: JellyfinClientError.notConfigured) {
_ = try await service.items()
}
await #expect(throws: JellyfinClientError.notConfigured) {
_ = try await service.image(itemID: "x", type: .primary)
}
await #expect(throws: JellyfinClientError.notConfigured) {
_ = try await service.libraries()
}
}
}

View file

@ -0,0 +1,97 @@
//
// AuthenticationMiddlewareTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import HTTPTypes
import OpenAPIRuntime
import Testing
@testable import LuminateServices
/// Records the request a middleware forwarded, so a test can inspect it after the fact.
private actor RequestRecorder {
/// The last forwarded request.
private(set) var request: HTTPRequest?
/// Stores a forwarded request.
///
/// - Parameter request: The request the middleware passed down the chain.
func record(_ request: HTTPRequest) {
self.request = request
}
}
/// Pins the exact `Authorization` header Jellyfin expects.
///
/// Jellyfin rejects the request outright if this string is malformed, and the failure surfaces as a
/// bare 401 with no explanation, so the format is asserted literally rather than by parsing.
@Suite struct AuthenticationMiddlewareTests {
/// Runs `middleware` over a throwaway request and returns the `Authorization` header it set.
///
/// - Parameter middleware: The middleware under test.
/// - Returns: The forwarded request's `Authorization` header, if it set one.
private func authorizationHeader(from middleware: AuthenticationMiddleware) async throws -> String? {
let recorder = RequestRecorder()
let request = HTTPRequest(method: .get, scheme: "http", authority: "localhost", path: "/System/Info/Public")
_ = try await middleware.intercept(
request,
body: nil,
baseURL: URL(string: "http://localhost")!,
operationID: "GetPublicSystemInfo"
) { forwarded, _, _ in
await recorder.record(forwarded)
return (HTTPResponse(status: .ok), nil)
}
return await recorder.request?.headerFields[.authorization]
}
@Test("Builds the MediaBrowser credential string with the token")
func authenticatedHeader() async throws {
let middleware = AuthenticationMiddleware(
clientName: "Luminate",
deviceName: "test-device",
deviceID: "test-device-id",
version: "0.1.0",
token: "test-token"
)
let header = try await authorizationHeader(from: middleware)
#expect(
header
== #"MediaBrowser Client="Luminate", Device="test-device", DeviceId="test-device-id", Version="0.1.0", Token="test-token""#
)
}
@Test("Sends an empty token before sign-in rather than omitting the header")
func unauthenticatedHeader() async throws {
let middleware = AuthenticationMiddleware(
clientName: "Luminate",
deviceName: "test-device",
deviceID: "test-device-id",
version: "0.1.0",
token: nil
)
let header = try await authorizationHeader(from: middleware)
#expect(
header
== #"MediaBrowser Client="Luminate", Device="test-device", DeviceId="test-device-id", Version="0.1.0", Token="""#
)
}
}

View file

@ -0,0 +1,115 @@
//
// JellyfinClientAuthTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import LuminateAPI
import LuminateCore
import Testing
@testable import LuminateServices
/// Covers sign-in: argument validation, payload mapping, and token adoption.
@Suite struct JellyfinClientAuthTests {
/// Builds a client wired to a double, pointed at a URL that is never dialled.
///
/// - Parameter api: The stubbed API.
/// - Returns: A client that routes every call to `api`.
private func makeClient(_ api: MockJellyfinAPI) -> JellyfinClient {
JellyfinClient(
configuration: JellyfinClientConfiguration(
serverURL: URL(string: "http://localhost")!,
deviceName: "test-device",
deviceID: "test-device-id"
),
api: api
)
}
@Test("A successful sign-in maps the result and adopts the token")
func signInAdoptsToken() async throws {
var api = MockJellyfinAPI()
api.authenticateUserByNameOutput = .ok(
.init(
body: .json(
Components.Schemas.AuthenticationResult(
user: .init(value1: Components.Schemas.UserDto(name: "echo", id: "u1", hasPassword: true)),
accessToken: "tok",
serverId: "srv"
)
)
)
)
let client = makeClient(api)
let result = try await client.authenticate(username: "echo", password: "hunter2")
#expect(result.accessToken == "tok")
#expect(result.serverID == "srv")
#expect(result.user?.name == "echo")
#expect(result.user?.id == "u1")
#expect(await client.accessToken == "tok")
#expect(await client.isAuthenticated)
}
@Test("A success with no token is a failure, not an unauthenticated success")
func missingTokenThrows() async {
var api = MockJellyfinAPI()
api.authenticateUserByNameOutput = .ok(
.init(body: .json(Components.Schemas.AuthenticationResult(accessToken: nil)))
)
let client = makeClient(api)
await #expect(throws: JellyfinClientError.missingPayload(operation: "AuthenticateUserByName")) {
_ = try await client.authenticate(username: "echo", password: "hunter2")
}
#expect(await client.isAuthenticated == false)
}
@Test("An empty username is rejected before any request is sent")
func emptyUsernameRejected() async {
let client = makeClient(MockJellyfinAPI())
await #expect(throws: JellyfinClientError.invalidArgument(name: "username")) {
_ = try await client.authenticate(username: "", password: "hunter2")
}
}
@Test("An empty Quick Connect secret is rejected before any request is sent")
func emptySecretRejected() async {
let client = makeClient(MockJellyfinAPI())
await #expect(throws: JellyfinClientError.invalidArgument(name: "secret")) {
_ = try await client.quickConnectState(secret: "")
}
}
@Test("Clearing the token signs the client out")
func clearingTokenSignsOut() async {
let client = makeClient(MockJellyfinAPI())
await client.setAccessToken("tok")
#expect(await client.isAuthenticated)
await client.setAccessToken("")
#expect(await client.accessToken == nil)
#expect(await client.isAuthenticated == false)
}
}

View file

@ -0,0 +1,90 @@
//
// JellyfinClientErrorMappingTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import LuminateAPI
import LuminateCore
import OpenAPIRuntime
import Testing
@testable import LuminateServices
/// Covers the translation from generated HTTP outcomes to ``JellyfinClientError``.
///
/// Every operation hand-writes its status switch, so this pins the shape those switches share.
@Suite struct JellyfinClientErrorMappingTests {
/// Builds a client wired to a double.
///
/// - Parameter api: The stubbed API.
/// - Returns: A client that routes every call to `api`.
private func makeClient(_ api: MockJellyfinAPI) -> JellyfinClient {
JellyfinClient(
configuration: JellyfinClientConfiguration(serverURL: URL(string: "http://localhost")!),
api: api
)
}
@Test("A 401 maps to unauthorized")
func unauthorizedMaps() async {
var api = MockJellyfinAPI()
api.getItemsOutput = .unauthorized(.init())
let client = makeClient(api)
await #expect(throws: JellyfinClientError.unauthorized) {
_ = try await client.items()
}
}
@Test("A 403 maps to forbidden")
func forbiddenMaps() async {
var api = MockJellyfinAPI()
api.getItemsOutput = .forbidden(.init())
let client = makeClient(api)
await #expect(throws: JellyfinClientError.forbidden) {
_ = try await client.items()
}
}
@Test("An undocumented status is reported with its operation and code")
func undocumentedMaps() async {
var api = MockJellyfinAPI()
api.getItemsOutput = .undocumented(statusCode: 418, .init())
let client = makeClient(api)
await #expect(throws: JellyfinClientError.unexpectedStatus(operation: "GetItems", statusCode: 418)) {
_ = try await client.items()
}
}
@Test("A starting server surfaces its Retry-After hint")
func serviceUnavailableCarriesRetryAfter() async {
var api = MockJellyfinAPI()
api.getPublicSystemInfoOutput = .serviceUnavailable(
.init(headers: .init(retryAfter: 5), body: .html(HTTPBody("starting")))
)
let client = makeClient(api)
await #expect(throws: JellyfinClientError.serviceUnavailable(retryAfterSeconds: 5)) {
_ = try await client.publicServerInfo()
}
}
}

View file

@ -0,0 +1,89 @@
//
// JellyfinClientImageTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import LuminateAPI
import LuminateCore
import OpenAPIRuntime
import Testing
@testable import LuminateServices
/// Covers artwork download, which is the one operation returning raw bytes rather than JSON.
@Suite struct JellyfinClientImageTests {
/// Builds a client wired to a double.
///
/// - Parameter api: The stubbed API.
/// - Returns: A client that routes every call to `api`.
private func makeClient(_ api: MockJellyfinAPI) -> JellyfinClient {
JellyfinClient(
configuration: JellyfinClientConfiguration(serverURL: URL(string: "http://localhost")!),
api: api
)
}
@Test("Collects the streamed image body into bytes")
func collectsImageBytes() async throws {
var api = MockJellyfinAPI()
api.getItemImageOutput = .ok(.init(body: .image_Ast_(HTTPBody([0, 1, 2, 255] as [UInt8]))))
let client = makeClient(api)
let data = try await client.image(itemID: "i1", type: .primary)
#expect(data == Data([0, 1, 2, 255]))
}
@Test("An index selects the indexed-image operation")
func indexedImageUsesIndexedOperation() async throws {
var api = MockJellyfinAPI()
api.getItemImageByIndexOutput = .ok(.init(body: .image_Ast_(HTTPBody([9, 9] as [UInt8]))))
let client = makeClient(api)
let data = try await client.image(
itemID: "i1",
type: .backdrop,
index: 2,
request: JellyfinImageRequest(fillWidth: 300)
)
#expect(data == Data([9, 9]))
}
@Test("A missing image maps to notFound")
func missingImageMapsToNotFound() async {
var api = MockJellyfinAPI()
api.getItemImageOutput = .notFound(.init(body: .json(Components.Schemas.ProblemDetails())))
let client = makeClient(api)
await #expect(throws: JellyfinClientError.notFound) {
_ = try await client.image(itemID: "i1", type: .logo)
}
}
@Test("An empty item identifier is rejected before any request is sent")
func emptyItemIdentifierRejected() async {
let client = makeClient(MockJellyfinAPI())
await #expect(throws: JellyfinClientError.invalidArgument(name: "itemID")) {
_ = try await client.image(itemID: "", type: .primary)
}
}
}

View file

@ -0,0 +1,149 @@
//
// JellyfinClientLibraryTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import LuminateAPI
import LuminateCore
import Testing
@testable import LuminateServices
/// Covers the DTO-to-domain mapping that every browse surface depends on.
@Suite struct JellyfinClientLibraryTests {
/// A movie DTO exercising the wrapped enum, image tag, and user data payloads.
private var movieResult: Components.Schemas.BaseItemDtoQueryResult {
Components.Schemas.BaseItemDtoQueryResult(
items: [
Components.Schemas.BaseItemDto(
name: "Arrival",
id: "i1",
overview: "Linguist meets heptapods.",
productionYear: 2016,
_type: .init(value1: .movie),
userData: .init(value1: Components.Schemas.UserItemDataDto(isFavorite: true, played: false)),
imageTags: .init(additionalProperties: ["Primary": "abc", "NotAnImageType": "zzz"]),
backdropImageTags: ["bd1"]
)
],
totalRecordCount: 1,
startIndex: 0
)
}
/// Builds a client wired to a double.
///
/// - Parameter api: The stubbed API.
/// - Returns: A client that routes every call to `api`.
private func makeClient(_ api: MockJellyfinAPI) -> JellyfinClient {
JellyfinClient(
configuration: JellyfinClientConfiguration(serverURL: URL(string: "http://localhost")!),
api: api
)
}
@Test("Maps an item, dropping image tags the client cannot name")
func mapsItems() async throws {
var api = MockJellyfinAPI()
api.getItemsOutput = .ok(.init(body: .json(movieResult)))
let client = makeClient(api)
let page = try await client.items()
#expect(page.totalRecordCount == 1)
let item = try #require(page.items.first)
#expect(item.id == "i1")
#expect(item.name == "Arrival")
#expect(item.kind == .movie)
#expect(item.productionYear == 2016)
#expect(item.imageTags == [.primary: "abc"])
#expect(item.backdropImageTags == ["bd1"])
#expect(item.userData?.isFavorite == true)
#expect(item.userData?.played == false)
}
@Test("Every JSON profile the server may negotiate decodes identically")
func jsonProfilesCollapse() async throws {
var camelCase = MockJellyfinAPI()
camelCase.getItemsOutput = .ok(.init(body: .applicationJsonProfile_Quot_camelcase_quot_(movieResult)))
var pascalCase = MockJellyfinAPI()
pascalCase.getItemsOutput = .ok(.init(body: .applicationJsonProfile_Quot_pascalcase_quot_(movieResult)))
let fromCamelCase = try await makeClient(camelCase).items()
let fromPascalCase = try await makeClient(pascalCase).items()
#expect(fromCamelCase == fromPascalCase)
#expect(fromCamelCase.items.first?.kind == .movie)
}
@Test("Maps libraries and drops unsupported collection types")
func mapsLibraries() async throws {
var api = MockJellyfinAPI()
api.getUserViewsOutput = .ok(
.init(
body: .json(
Components.Schemas.BaseItemDtoQueryResult(
items: [
Components.Schemas.BaseItemDto(
name: "Shows",
id: "l1",
childCount: 12,
collectionType: .init(value1: .tvshows),
imageTags: .init(additionalProperties: ["Primary": "tag1"])
),
Components.Schemas.BaseItemDto(
name: "Music",
id: "l2",
collectionType: .init(value1: .music)
),
]
)
)
)
)
let client = makeClient(api)
let libraries = try await client.libraries()
#expect(libraries.count == 2)
#expect(libraries[0].collectionType == .tvShows)
#expect(libraries[0].primaryImageTag == "tag1")
#expect(libraries[0].childCount == 12)
#expect(libraries[1].collectionType == nil)
}
@Test("A blank search term is rejected before any request is sent")
func blankSearchTermRejected() async {
let client = makeClient(MockJellyfinAPI())
await #expect(throws: JellyfinClientError.invalidArgument(name: "term")) {
_ = try await client.searchHints(term: " ")
}
}
@Test("An empty series identifier is rejected before any request is sent")
func emptySeriesIdentifierRejected() async {
let client = makeClient(MockJellyfinAPI())
await #expect(throws: JellyfinClientError.invalidArgument(name: "seriesID")) {
_ = try await client.seasons(seriesID: "")
}
}
}

View file

@ -0,0 +1,230 @@
//
// MockJellyfinAPI.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import LuminateAPI
import LuminateServices
import Testing
/// A ``JellyfinAPI`` double that answers with pre-baked generated outputs.
///
/// Only the operations a test actually stubs are usable; every other call fails the test with a
/// clear message rather than returning a fabricated success. Outputs are plain `Sendable` values,
/// so the whole double is a `Sendable` struct with no isolation escape hatches.
struct MockJellyfinAPI: JellyfinAPI {
/// The output returned by ``authenticateUserByName(_:)``.
var authenticateUserByNameOutput: Operations.AuthenticateUserByName.Output?
/// The output returned by ``authenticateWithQuickConnect(_:)``.
var authenticateWithQuickConnectOutput: Operations.AuthenticateWithQuickConnect.Output?
/// The output returned by ``getPublicUsers(_:)``.
var getPublicUsersOutput: Operations.GetPublicUsers.Output?
/// The output returned by ``getPublicSystemInfo(_:)``.
var getPublicSystemInfoOutput: Operations.GetPublicSystemInfo.Output?
/// The output returned by ``getSystemInfo(_:)``.
var getSystemInfoOutput: Operations.GetSystemInfo.Output?
/// The output returned by ``getQuickConnectEnabled(_:)``.
var getQuickConnectEnabledOutput: Operations.GetQuickConnectEnabled.Output?
/// The output returned by ``initiateQuickConnect(_:)``.
var initiateQuickConnectOutput: Operations.InitiateQuickConnect.Output?
/// The output returned by ``getQuickConnectState(_:)``.
var getQuickConnectStateOutput: Operations.GetQuickConnectState.Output?
/// The output returned by ``updateUserPassword(_:)``.
var updateUserPasswordOutput: Operations.UpdateUserPassword.Output?
/// The output returned by ``getUserViews(_:)``.
var getUserViewsOutput: Operations.GetUserViews.Output?
/// The output returned by ``getItems(_:)``.
var getItemsOutput: Operations.GetItems.Output?
/// The output returned by ``getItem(_:)``.
var getItemOutput: Operations.GetItem.Output?
/// The output returned by ``getResumeItems(_:)``.
var getResumeItemsOutput: Operations.GetResumeItems.Output?
/// The output returned by ``getNextUp(_:)``.
var getNextUpOutput: Operations.GetNextUp.Output?
/// The output returned by ``getLatestMedia(_:)``.
var getLatestMediaOutput: Operations.GetLatestMedia.Output?
/// The output returned by ``getSeasons(_:)``.
var getSeasonsOutput: Operations.GetSeasons.Output?
/// The output returned by ``getEpisodes(_:)``.
var getEpisodesOutput: Operations.GetEpisodes.Output?
/// The output returned by ``getSearchHints(_:)``.
var getSearchHintsOutput: Operations.GetSearchHints.Output?
/// The output returned by ``getItemImage(_:)``.
var getItemImageOutput: Operations.GetItemImage.Output?
/// The output returned by ``getItemImageByIndex(_:)``.
var getItemImageByIndexOutput: Operations.GetItemImageByIndex.Output?
/// The output returned by ``markPlayedItem(_:)``.
var markPlayedItemOutput: Operations.MarkPlayedItem.Output?
/// The output returned by ``markUnplayedItem(_:)``.
var markUnplayedItemOutput: Operations.MarkUnplayedItem.Output?
/// The output returned by ``markFavoriteItem(_:)``.
var markFavoriteItemOutput: Operations.MarkFavoriteItem.Output?
/// The output returned by ``unmarkFavoriteItem(_:)``.
var unmarkFavoriteItemOutput: Operations.UnmarkFavoriteItem.Output?
/// Returns a stubbed output, or fails the test naming the unstubbed operation.
///
/// - Parameters:
/// - output: The stubbed output for the operation, if the test supplied one.
/// - operation: The operation identifier, used in the failure message.
/// - Returns: The stubbed output.
/// - Throws: An error that fails the test when the operation was not stubbed.
private func unwrap<Output>(_ output: Output?, _ operation: String) throws -> Output {
try #require(output, "MockJellyfinAPI received an unstubbed call to \(operation)")
}
func authenticateUserByName(_ input: Operations.AuthenticateUserByName.Input) async throws
-> Operations.AuthenticateUserByName.Output
{
try unwrap(authenticateUserByNameOutput, "AuthenticateUserByName")
}
func authenticateWithQuickConnect(_ input: Operations.AuthenticateWithQuickConnect.Input) async throws
-> Operations.AuthenticateWithQuickConnect.Output
{
try unwrap(authenticateWithQuickConnectOutput, "AuthenticateWithQuickConnect")
}
func getPublicUsers(_ input: Operations.GetPublicUsers.Input) async throws -> Operations.GetPublicUsers.Output {
try unwrap(getPublicUsersOutput, "GetPublicUsers")
}
func getPublicSystemInfo(_ input: Operations.GetPublicSystemInfo.Input) async throws
-> Operations.GetPublicSystemInfo.Output
{
try unwrap(getPublicSystemInfoOutput, "GetPublicSystemInfo")
}
func getSystemInfo(_ input: Operations.GetSystemInfo.Input) async throws -> Operations.GetSystemInfo.Output {
try unwrap(getSystemInfoOutput, "GetSystemInfo")
}
func getQuickConnectEnabled(_ input: Operations.GetQuickConnectEnabled.Input) async throws
-> Operations.GetQuickConnectEnabled.Output
{
try unwrap(getQuickConnectEnabledOutput, "GetQuickConnectEnabled")
}
func initiateQuickConnect(_ input: Operations.InitiateQuickConnect.Input) async throws
-> Operations.InitiateQuickConnect.Output
{
try unwrap(initiateQuickConnectOutput, "InitiateQuickConnect")
}
func getQuickConnectState(_ input: Operations.GetQuickConnectState.Input) async throws
-> Operations.GetQuickConnectState.Output
{
try unwrap(getQuickConnectStateOutput, "GetQuickConnectState")
}
func updateUserPassword(_ input: Operations.UpdateUserPassword.Input) async throws
-> Operations.UpdateUserPassword.Output
{
try unwrap(updateUserPasswordOutput, "UpdateUserPassword")
}
func getUserViews(_ input: Operations.GetUserViews.Input) async throws -> Operations.GetUserViews.Output {
try unwrap(getUserViewsOutput, "GetUserViews")
}
func getItems(_ input: Operations.GetItems.Input) async throws -> Operations.GetItems.Output {
try unwrap(getItemsOutput, "GetItems")
}
func getItem(_ input: Operations.GetItem.Input) async throws -> Operations.GetItem.Output {
try unwrap(getItemOutput, "GetItem")
}
func getResumeItems(_ input: Operations.GetResumeItems.Input) async throws -> Operations.GetResumeItems.Output {
try unwrap(getResumeItemsOutput, "GetResumeItems")
}
func getNextUp(_ input: Operations.GetNextUp.Input) async throws -> Operations.GetNextUp.Output {
try unwrap(getNextUpOutput, "GetNextUp")
}
func getLatestMedia(_ input: Operations.GetLatestMedia.Input) async throws -> Operations.GetLatestMedia.Output {
try unwrap(getLatestMediaOutput, "GetLatestMedia")
}
func getSeasons(_ input: Operations.GetSeasons.Input) async throws -> Operations.GetSeasons.Output {
try unwrap(getSeasonsOutput, "GetSeasons")
}
func getEpisodes(_ input: Operations.GetEpisodes.Input) async throws -> Operations.GetEpisodes.Output {
try unwrap(getEpisodesOutput, "GetEpisodes")
}
func getSearchHints(_ input: Operations.GetSearchHints.Input) async throws -> Operations.GetSearchHints.Output {
try unwrap(getSearchHintsOutput, "GetSearchHints")
}
func getItemImage(_ input: Operations.GetItemImage.Input) async throws -> Operations.GetItemImage.Output {
try unwrap(getItemImageOutput, "GetItemImage")
}
func getItemImageByIndex(_ input: Operations.GetItemImageByIndex.Input) async throws
-> Operations.GetItemImageByIndex.Output
{
try unwrap(getItemImageByIndexOutput, "GetItemImageByIndex")
}
func markPlayedItem(_ input: Operations.MarkPlayedItem.Input) async throws -> Operations.MarkPlayedItem.Output {
try unwrap(markPlayedItemOutput, "MarkPlayedItem")
}
func markUnplayedItem(_ input: Operations.MarkUnplayedItem.Input) async throws -> Operations.MarkUnplayedItem.Output
{
try unwrap(markUnplayedItemOutput, "MarkUnplayedItem")
}
func markFavoriteItem(_ input: Operations.MarkFavoriteItem.Input) async throws -> Operations.MarkFavoriteItem.Output
{
try unwrap(markFavoriteItemOutput, "MarkFavoriteItem")
}
func unmarkFavoriteItem(_ input: Operations.UnmarkFavoriteItem.Input) async throws
-> Operations.UnmarkFavoriteItem.Output
{
try unwrap(unmarkFavoriteItemOutput, "UnmarkFavoriteItem")
}
}

View file

@ -1,8 +0,0 @@
import Testing
@testable import Luminate
@Test func example() async throws {
// Write your test here and use APIs like `#expect(...)` to check expected conditions.
// Swift Testing Documentation
// https://swiftpackageindex.com/swiftlang/swift-testing/documentation
}

View file

@ -0,0 +1,103 @@
//
// ClientEnvironmentKeyTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import LuminateCore
@_spi(Portico) import Portico
import Testing
@testable import LuminateUI
/// A ``JellyfinService`` that exists only to be told apart from the default.
private final class StubJellyfinService: JellyfinService {
var isAuthenticated: Bool { true }
func publicServerInfo() async throws -> JellyfinServerInfo { JellyfinServerInfo() }
func serverInfo() async throws -> JellyfinServerInfo { JellyfinServerInfo() }
func publicUsers() async throws -> [JellyfinUser] { [] }
func authenticate(username: String, password: String) async throws -> JellyfinAuthentication {
JellyfinAuthentication(accessToken: "stub")
}
func quickConnectEnabled() async throws -> Bool { false }
func initiateQuickConnect() async throws -> JellyfinQuickConnectState { JellyfinQuickConnectState() }
func quickConnectState(secret: String) async throws -> JellyfinQuickConnectState { JellyfinQuickConnectState() }
func authenticateWithQuickConnect(secret: String) async throws -> JellyfinAuthentication {
JellyfinAuthentication(accessToken: "stub")
}
func updateUserPassword(
userID: String?,
currentPassword: String?,
currentPIN: String?,
newPassword: String?,
resetPassword: Bool?
) async throws {}
func libraries(_ options: JellyfinListOptions) async throws -> [JellyfinLibrary] { [] }
func items(_ query: JellyfinMediaQuery) async throws -> JellyfinMediaPage { JellyfinMediaPage() }
func item(id: String, userID: String?) async throws -> JellyfinMediaItem { JellyfinMediaItem() }
func resumeItems(_ options: JellyfinListOptions) async throws -> JellyfinMediaPage { JellyfinMediaPage() }
func nextUp(seriesID: String?, options: JellyfinListOptions) async throws -> JellyfinMediaPage {
JellyfinMediaPage()
}
func latestMedia(_ options: JellyfinListOptions) async throws -> [JellyfinMediaItem] { [] }
func seasons(seriesID: String, options: JellyfinListOptions) async throws -> JellyfinMediaPage {
JellyfinMediaPage()
}
func episodes(seriesID: String, options: JellyfinListOptions) async throws -> JellyfinMediaPage {
JellyfinMediaPage()
}
func searchHints(term: String, options: JellyfinListOptions) async throws -> [JellyfinSearchHint] { [] }
func image(
itemID: String,
type: JellyfinImageType,
index: Int32?,
request: JellyfinImageRequest
) async throws -> Data {
Data()
}
func markPlayed(itemID: String, userID: String?, datePlayed: Date?) async throws -> JellyfinUserData {
JellyfinUserData()
}
func markUnplayed(itemID: String, userID: String?) async throws -> JellyfinUserData { JellyfinUserData() }
func markFavorite(itemID: String, userID: String?) async throws -> JellyfinUserData { JellyfinUserData() }
func unmarkFavorite(itemID: String, userID: String?) async throws -> JellyfinUserData { JellyfinUserData() }
}
/// Guards the `\\.client` environment slot itself.
///
/// No widgets are constructed, so these run on a headless machine without `Gtk.initCheck()`.
@MainActor @Suite struct ClientEnvironmentKeyTests {
@Test("An unresolved slot falls back to the unconfigured service")
func defaultIsUnconfigured() {
#expect(EnvironmentValues().client is UnconfiguredJellyfinService)
}
@Test("The key path routes through the environment subscript")
func keyPathResolvesToABox() {
#expect(EnvironmentValues()._box(for: \.client) != nil)
}
@Test("An injected service replaces the default")
func injectionOverridesDefault() {
var values = EnvironmentValues()
values.client = StubJellyfinService()
#expect(values.client is StubJellyfinService)
}
}