From 8fa4d507340c0500c853bb9f9c851499ef507766 Mon Sep 17 00:00:00 2001 From: Javier Cicchelli Date: Sun, 25 Oct 2026 20:05:40 +0100 Subject: [PATCH] Added tests for the Amiibo live client and ISO transcoder. --- .../ISODateTimeTranscoderTests.swift | 78 ++++ .../Clients/AmiiboLiveClientTests.swift | 394 ++++++++++++++++++ .../Helpers/Extensions/Date+UTC.swift | 44 ++ .../Helpers/Transports/StubTransport.swift | 72 ++++ 4 files changed, 588 insertions(+) create mode 100644 Tests/AmiiboService/Cases/Internal/Transcoders/ISODateTimeTranscoderTests.swift create mode 100644 Tests/AmiiboService/Helpers/Extensions/Date+UTC.swift create mode 100644 Tests/AmiiboService/Helpers/Transports/StubTransport.swift diff --git a/Tests/AmiiboService/Cases/Internal/Transcoders/ISODateTimeTranscoderTests.swift b/Tests/AmiiboService/Cases/Internal/Transcoders/ISODateTimeTranscoderTests.swift new file mode 100644 index 0000000..f49d70e --- /dev/null +++ b/Tests/AmiiboService/Cases/Internal/Transcoders/ISODateTimeTranscoderTests.swift @@ -0,0 +1,78 @@ +// ===----------------------------------------------------------------------=== +// +// This source file is part of the Amiibo Service open source project +// +// Copyright (c) 2026 Röck+Cöde VoF. and the Amiibo Service project authors +// Licensed under Apache license v2.0 +// +// See LICENSE for license information +// See CONTRIBUTORS for the list of Amiibo Service project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +// ===----------------------------------------------------------------------=== + +@testable import AmiiboService +import Foundation +import Testing + +@Suite("ISO Date Time Transcoder") +struct ISODateTimeTranscoderTests { + + // MARK: Properties + + private let transcoder = ISODateTimeTranscoder() + + // MARK: Decode tests + + @Test("decodes a timestamp as UTC") + func decodesTimestamp() throws { + // GIVEN + let string = "2026-07-24T12:34:56.123000" + + // WHEN + let date = try transcoder.decode(string) + + // THEN + #expect(abs(date.timeIntervalSince(.utc(2026, 7, 24, 12, 34, 56)) - 0.123) < 0.001) + } + + @Test("decodes a date-only string as midnight UTC") + func decodesDate() throws { + // GIVEN + let string = "2014-11-21" + + // WHEN + let date = try transcoder.decode(string) + + // THEN + #expect(date == .utc(2014, 11, 21)) + } + + @Test("throws a decoding error for an unsupported string", arguments: [ + "", "2014-11", "2014-11-21T12:34:56", "2014-11-21T12:34:56Z", "21/11/2014", "yesterday" + ]) + func throwsForUnsupportedString(string: String) { + // GIVEN + // WHEN + // THEN + #expect(throws: DecodingError.self) { + try transcoder.decode(string) + } + } + + // MARK: Encode tests + + @Test("encodes a date as a timestamp") + func encodesTimestamp() throws { + // GIVEN + let date: Date = .utc(2026, 7, 24, 12, 34, 56) + + // WHEN + let string = try transcoder.encode(date) + + // THEN + #expect(string == "2026-07-24T12:34:56.000000") + } + +} diff --git a/Tests/AmiiboService/Cases/Public/Clients/AmiiboLiveClientTests.swift b/Tests/AmiiboService/Cases/Public/Clients/AmiiboLiveClientTests.swift index c523a8b..26acc01 100644 --- a/Tests/AmiiboService/Cases/Public/Clients/AmiiboLiveClientTests.swift +++ b/Tests/AmiiboService/Cases/Public/Clients/AmiiboLiveClientTests.swift @@ -14,6 +14,7 @@ @testable import AmiiboService import Foundation +import HTTPTypes import Testing @Suite("Amiibo Live Client") @@ -66,6 +67,302 @@ struct AmiiboLiveClientTests { } } + @Test( + "maps a response status to the matching service error", + arguments: zip( + Responses.failing, + Responses.expected + ) + ) + func mapsResponseStatus( + response: (status: Int, json: String?), + expected: AmiiboServiceError + ) async { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport( + status: .init(code: response.status), + json: response.json + )) + + // WHEN + // THEN + await #expect(throws: expected) { + try await client.getAmiibos(by: .init()) + } + } + + // MARK: Get Amiibos tests + + @Test("returns amiibos sorted by identifier") + func getAmiibosSorted() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .ok, json: JSON.amiibos)) + + // WHEN + let amiibos = try await client.getAmiibos(by: .init()) + + // THEN + #expect(amiibos.map(\.identifier) == ["0000000000000002", "0100000000040002"]) + #expect(amiibos.map(\.name) == ["Mario", "Zelda"]) + } + + @Test("returns a single amiibo when the response holds an object") + func getAmiibosSingle() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .ok, json: JSON.amiibo)) + + // WHEN + let amiibos = try await client.getAmiibos(by: .init(identifier: "0100000000040002")) + let amiibo = try #require(amiibos.first) + + // THEN + #expect(amiibos.count == 1) + #expect(amiibo.head == "01000000") + #expect(amiibo.tail == "00040002") + #expect(amiibo.name == "Zelda") + #expect(amiibo.type == "Figure") + #expect(amiibo.series == "Super Smash Bros.") + #expect(amiibo.gameCharacter == "Zelda") + #expect(amiibo.gameSeries == "The Legend of Zelda") + #expect(amiibo.imageURL?.host() == "example.com") + #expect(amiibo.platform == nil) + } + + @Test("returns no amiibos when the response holds null") + func getAmiibosNull() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .ok, json: JSON.amiibosNull)) + + // WHEN + let amiibos = try await client.getAmiibos(by: .init(identifier: "0000000000000000")) + + // THEN + #expect(amiibos.isEmpty) + } + + @Test("returns no amiibos when the response holds an empty list") + func getAmiibosEmpty() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .ok, json: JSON.amiibosEmpty)) + + // WHEN + let amiibos = try await client.getAmiibos(by: .init(name: "Something")) + + // THEN + #expect(amiibos.isEmpty) + } + + @Test("decodes release dates as midnight UTC, and missing or null ones as nil") + func getAmiibosRelease() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .ok, json: JSON.amiibos)) + + // WHEN + let amiibos = try await client.getAmiibos(by: .init()) + let mario = try #require(amiibos.first) + let zelda = try #require(amiibos.last) + + // THEN + #expect(mario.release.america == .utc(2014, 11, 21)) + #expect(mario.release.australia == .utc(2014, 11, 29)) + #expect(mario.release.europe == .utc(2014, 11, 28)) + #expect(mario.release.japan == .utc(2014, 12, 6)) + #expect(zelda.release.australia == nil) + #expect(zelda.release.japan == nil) + } + + @Test("maps related games and usages into the platform") + func getAmiibosPlatform() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .ok, json: JSON.amiiboWithGames)) + + // WHEN + let amiibos = try await client.getAmiibos(by: .init(showUsage: true)) + let platform = try #require(amiibos.first?.platform) + let game = try #require(platform.switch.first) + + // THEN + #expect(platform.switch.count == 1) + #expect(platform.switch2.isEmpty) + #expect(platform.threeDS.isEmpty) + #expect(platform.wiiU.count == 1) + #expect(game.identifiers == ["01007EF00011E000"]) + #expect(game.name == "The Legend of Zelda: Breath of the Wild") + #expect(game.usages == [.init(explanation: "Spawns a random selection of items.", isWriteable: false)]) + #expect(platform.wiiU.first?.usages == nil) + } + + @Test("encodes the amiibo filter as query parameters") + func getAmiibosQuery() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport { request in + let path = request.path ?? "" + + #expect(path.hasPrefix("/amiibo?")) + #expect(path.contains("id=0100000000040002")) + #expect(path.contains("head=01000000")) + #expect(path.contains("tail=00040002")) + #expect(path.contains("name=zelda")) + #expect(path.contains("type=0x00")) + #expect(path.contains("amiiboSeries=0x00")) + #expect(path.contains("character=0x0100")) + #expect(path.contains("gameseries=0x010")) + #expect(path.contains("showgames=true")) + #expect(path.contains("showusage=false")) + + return StubTransport.response(status: .ok, json: JSON.amiibosEmpty) + }) + + // WHEN + // THEN + _ = try await client.getAmiibos(by: .init( + head: "01000000", + tail: "00040002", + identifier: "0100000000040002", + name: "zelda", + type: "0x00", + series: "0x00", + gameCharacter: "0x0100", + gameSeries: "0x010", + showGames: true, + showUsage: false + )) + } + + @Test("omits nil filter values from the query") + func getAmiibosEmptyQuery() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport { request in + #expect(request.path == "/amiibo") + + return StubTransport.response(status: .ok, json: JSON.amiibosEmpty) + }) + + // WHEN + // THEN + _ = try await client.getAmiibos(by: .init()) + } + + // MARK: Key-name endpoints tests + + @Test("returns amiibo series sorted by key") + func getAmiiboSeriesSorted() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .ok, json: JSON.keyNameList)) + + // WHEN + let series = try await client.getAmiiboSeries(by: .init()) + + // THEN + #expect(series == [.init(key: "0x00", name: "Second"), .init(key: "0x01", name: "First")]) + } + + @Test("returns a single amiibo series when the response holds an object") + func getAmiiboSeriesSingle() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport { request in + #expect(request.path == "/amiiboseries?key=0x01") + + return StubTransport.response(status: .ok, json: JSON.keyName) + }) + + // WHEN + let series = try await client.getAmiiboSeries(by: .init(key: "0x01")) + + // THEN + #expect(series == [.init(key: "0x01", name: "First")]) + } + + @Test("returns amiibo types sorted by key") + func getAmiiboTypesSorted() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport { request in + #expect(request.path == "/type") + + return StubTransport.response(status: .ok, json: JSON.keyNameList) + }) + + // WHEN + let types = try await client.getAmiiboTypes(by: .init()) + + // THEN + #expect(types == [.init(key: "0x00", name: "Second"), .init(key: "0x01", name: "First")]) + } + + @Test("returns game characters sorted by key") + func getGameCharactersSorted() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport { request in + #expect(request.path == "/character?name=First") + + return StubTransport.response(status: .ok, json: JSON.keyNameList) + }) + + // WHEN + let characters = try await client.getGameCharacters(by: .init(name: "First")) + + // THEN + #expect(characters == [.init(key: "0x00", name: "Second"), .init(key: "0x01", name: "First")]) + } + + @Test("returns game series sorted by key") + func getGameSeriesSorted() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport { request in + #expect(request.path == "/gameseries") + + return StubTransport.response(status: .ok, json: JSON.keyNameList) + }) + + // WHEN + let series = try await client.getGameSeries(by: .init()) + + // THEN + #expect(series == [.init(key: "0x00", name: "Second"), .init(key: "0x01", name: "First")]) + } + + @Test("throws notFound when a key-name endpoint matches nothing") + func getKeyNameNotFound() async { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .notFound, json: JSON.notFound)) + + // WHEN + // THEN + await #expect(throws: AmiiboServiceError.notFound) { + try await client.getGameSeries(by: .init(key: "0xffff")) + } + } + + // MARK: Get Last Updated tests + + @Test("returns the last updated timestamp as UTC") + func getLastUpdated() async throws { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport { request in + #expect(request.path == "/lastupdated") + + return StubTransport.response(status: .ok, json: JSON.lastUpdated) + }) + + // WHEN + let lastUpdated = try await client.getLastUpdated() + + // THEN + #expect(lastUpdated == .utc(2026, 7, 24, 12, 34, 56)) + } + + @Test("throws notAvailable when the last updated endpoint fails") + func getLastUpdatedNotAvailable() async { + // GIVEN + let client = AmiiboLiveClient(transport: StubTransport(status: .internalServerError)) + + // WHEN + // THEN + await #expect(throws: AmiiboServiceError.notAvailable) { + try await client.getLastUpdated() + } + } + } // MARK: - Arguments @@ -90,3 +387,100 @@ private enum TransportErrors { .unknown(String(describing: URLError(.badURL))) ] } + +private enum Responses { + /// Failing responses, with a body where the specification documents one. + static let failing: [(status: Int, json: String?)] = [ + (400, JSON.badRequest), + (404, JSON.notFound), + (500, nil), + (418, nil), + (200, "not json") + ] + /// The service error expected for each failing response. + static let expected: [AmiiboServiceError] = [ + .badRequest, + .notFound, + .notAvailable, + .undocumented(418), + .decoding + ] +} + +// MARK: - Payloads + +private enum JSON { + /// Two amiibos in reverse identifier order; the first lacks `au` and has a null `jp`. + static let amiibos = """ + {"amiibo": [ + { + "amiiboSeries": "Super Smash Bros.", "character": "Zelda", "gameSeries": "The Legend of Zelda", + "head": "01000000", "tail": "00040002", "name": "Zelda", "type": "Figure", + "image": "https://example.com/zelda.png", + "release": {"eu": "2014-11-28", "jp": null, "na": "2014-11-21"} + }, + { + "amiiboSeries": "Super Smash Bros.", "character": "Mario", "gameSeries": "Super Mario", + "head": "00000000", "tail": "00000002", "name": "Mario", "type": "Figure", + "image": "https://example.com/mario.png", + "release": {"au": "2014-11-29", "eu": "2014-11-28", "jp": "2014-12-06", "na": "2014-11-21"} + } + ]} + """ + /// A single amiibo, as returned for an `id` filter. + static let amiibo = """ + {"amiibo": { + "amiiboSeries": "Super Smash Bros.", "character": "Zelda", "gameSeries": "The Legend of Zelda", + "head": "01000000", "tail": "00040002", "name": "Zelda", "type": "Figure", + "image": "https://example.com/zelda.png", + "release": {"au": "2014-12-04", "eu": "2014-11-28", "jp": "2014-12-06", "na": "2014-11-21"} + }} + """ + /// An amiibo with Switch and Wii U games, an empty 3DS list, and no Switch 2 key. + static let amiiboWithGames = """ + {"amiibo": [{ + "amiiboSeries": "Super Smash Bros.", "character": "Zelda", "gameSeries": "The Legend of Zelda", + "head": "01000000", "tail": "00040002", "name": "Zelda", "type": "Figure", + "image": "https://example.com/zelda.png", + "release": {"na": "2014-11-21"}, + "games3DS": [], + "gamesSwitch": [{ + "gameID": ["01007EF00011E000"], + "gameName": "The Legend of Zelda: Breath of the Wild", + "amiiboUsage": [{"Usage": "Spawns a random selection of items.", "write": false}] + }], + "gamesWiiU": [{ + "gameID": ["0005000010145000"], + "gameName": "Super Smash Bros. for Wii U" + }] + }]} + """ + /// The response for an `id` filter that matches nothing. + static let amiibosNull = """ + {"amiibo": null} + """ + /// The response for any other filter that matches nothing. + static let amiibosEmpty = """ + {"amiibo": []} + """ + /// Two key-name items in reverse key order. + static let keyNameList = """ + {"amiibo": [{"key": "0x01", "name": "First"}, {"key": "0x00", "name": "Second"}]} + """ + /// A single key-name item, as returned for a `key` filter. + static let keyName = """ + {"amiibo": {"key": "0x01", "name": "First"}} + """ + /// The last updated timestamp. + static let lastUpdated = """ + {"lastUpdated": "2026-07-24T12:34:56.000000"} + """ + /// The body of a 400 response. + static let badRequest = """ + {"code": 400, "error": "Bad request."} + """ + /// The body of a 404 response. + static let notFound = """ + {"code": 404, "error": "Not found."} + """ +} diff --git a/Tests/AmiiboService/Helpers/Extensions/Date+UTC.swift b/Tests/AmiiboService/Helpers/Extensions/Date+UTC.swift new file mode 100644 index 0000000..4302acd --- /dev/null +++ b/Tests/AmiiboService/Helpers/Extensions/Date+UTC.swift @@ -0,0 +1,44 @@ +// ===----------------------------------------------------------------------=== +// +// This source file is part of the Amiibo Service open source project +// +// Copyright (c) 2026 Röck+Cöde VoF. and the Amiibo Service project authors +// Licensed under Apache license v2.0 +// +// See LICENSE for license information +// See CONTRIBUTORS for the list of Amiibo Service project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +// ===----------------------------------------------------------------------=== + +import Foundation + +extension Date { + + // MARK: Functions + + /// Makes a date from UTC components. + static func utc( + _ year: Int, + _ month: Int, + _ day: Int, + _ hour: Int = 0, + _ minute: Int = 0, + _ second: Int = 0 + ) -> Date { + var calendar = Calendar(identifier: .gregorian) + + calendar.timeZone = .init(secondsFromGMT: 0)! + + return calendar.date(from: .init( + year: year, + month: month, + day: day, + hour: hour, + minute: minute, + second: second + ))! + } + +} diff --git a/Tests/AmiiboService/Helpers/Transports/StubTransport.swift b/Tests/AmiiboService/Helpers/Transports/StubTransport.swift new file mode 100644 index 0000000..2f81a5f --- /dev/null +++ b/Tests/AmiiboService/Helpers/Transports/StubTransport.swift @@ -0,0 +1,72 @@ +// ===----------------------------------------------------------------------=== +// +// This source file is part of the Amiibo Service open source project +// +// Copyright (c) 2026 Röck+Cöde VoF. and the Amiibo Service project authors +// Licensed under Apache license v2.0 +// +// See LICENSE for license information +// See CONTRIBUTORS for the list of Amiibo Service project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +// ===----------------------------------------------------------------------=== + +import Foundation +import HTTPTypes +import OpenAPIRuntime + +/// A transport that answers every request with a canned response, for testing purposes. +struct StubTransport: ClientTransport { + + // MARK: Type aliases + + /// A closure that builds the response for a request. + typealias Handler = @Sendable (HTTPRequest) throws -> (HTTPResponse, HTTPBody?) + + // MARK: Properties + + /// The handler that builds the response. + private let handler: Handler + + // MARK: Initializers + + /// Initializes this transport with a response handler. + init(handler: @escaping Handler) { + self.handler = handler + } + + /// Initializes this transport with a fixed response. + init(status: HTTPResponse.Status, json: String? = nil) { + self.init { _ in + Self.response(status: status, json: json) + } + } + + // MARK: Functions + + func send( + _ request: HTTPRequest, + body: HTTPBody?, + baseURL: URL, + operationID: String + ) async throws -> (HTTPResponse, HTTPBody?) { + try handler(request) + } + + /// Builds a response with a status and an optional JSON body. + static func response( + status: HTTPResponse.Status, + json: String? = nil + ) -> (HTTPResponse, HTTPBody?) { + guard let json else { + return (.init(status: status), nil) + } + + return ( + .init(status: status, headerFields: [.contentType: "application/json"]), + .init(json) + ) + } + +}