WallhavenAPITests.swift

8.5 KB · raw

1import Foundation2import Testing34@testable import Haven56final class MockURLProtocol: URLProtocol, @unchecked Sendable {7  nonisolated(unsafe) static var requestHandler: ((URLRequest) throws -> (URLResponse, Data))?89  override class func canInit(with request: URLRequest) -> Bool { true }1011  override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }1213  override func startLoading() {14    guard let handler = Self.requestHandler else {15      client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse))16      return17    }1819    do {20      let (response, data) = try handler(request)21      client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)22      client?.urlProtocol(self, didLoad: data)23      client?.urlProtocolDidFinishLoading(self)24    } catch {25      client?.urlProtocol(self, didFailWithError: error)26    }27  }2829  override func stopLoading() {}30}3132@Suite("Wallhaven API", .serialized)33@MainActor34struct WallhavenAPITests {35  private func makeAPI() -> WallhavenAPI {36    let configuration = URLSessionConfiguration.ephemeral37    configuration.protocolClasses = [MockURLProtocol.self]38    return WallhavenAPI(session: URLSession(configuration: configuration))39  }4041  private func response(42    for request: URLRequest, statusCode: Int = 200, contentType: String = "application/json"43  ) -> HTTPURLResponse {44    HTTPURLResponse(45      url: request.url!,46      statusCode: statusCode,47      httpVersion: "HTTP/1.1",48      headerFields: ["Content-Type": contentType]49    )!50  }5152  @Test("Search sends every selected filter and decodes the response")53  func searchBuildsExpectedRequest() async throws {54    MockURLProtocol.requestHandler = { request in55      let url = try #require(request.url)56      let components = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false))57      let items = Dictionary(58        uniqueKeysWithValues: (components.queryItems ?? []).map { ($0.name, $0.value ?? "") })5960      #expect(components.path == "/api/v1/search")61      #expect(items["q"] == "mountain lake")62      #expect(items["categories"] == "101")63      #expect(items["purity"] == "110")64      #expect(items["sorting"] == "toplist")65      #expect(items["resolutions"] == "1920x1080,3840x2160")66      #expect(items["ratios"] == "16x9,21x9")67      #expect(items["limit"] == "12")68      #expect(items["page"] == "3")69      return (response(for: request), try encodedSearchResponse(currentPage: 3, lastPage: 9))70    }7172    let (wallpapers, meta) = try await makeAPI().searchWallpapers(73      query: "mountain lake",74      categories: "101",75      purity: "110",76      sorting: .toplist,77      resolutions: ["1920x1080", "3840x2160"],78      ratios: ["16x9", "21x9"],79      limit: 12,80      page: 381    )8283    #expect(wallpapers == [makeWallpaper()])84    #expect(meta?.current_page == 3)85    #expect(meta?.last_page == 9)86  }8788  @Test("Empty filters are omitted and defaults are stable")89  func emptyFiltersAreOmitted() async throws {90    MockURLProtocol.requestHandler = { request in91      let url = try #require(request.url)92      let components = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false))93      let items = Dictionary(94        uniqueKeysWithValues: (components.queryItems ?? []).map { ($0.name, $0.value ?? "") })9596      #expect(items["categories"] == "111")97      #expect(items["purity"] == "100")98      #expect(items["sorting"] == "date_added")99      #expect(items["limit"] == "24")100      #expect(items["page"] == "1")101      #expect(items["resolutions"] == nil)102      #expect(items["ratios"] == nil)103      return (response(for: request), try encodedSearchResponse())104    }105106    _ = try await makeAPI().searchWallpapers(query: "")107  }108109  @Test("Random mode maps to the random sorting query")110  func randomSortingIsEncoded() async throws {111    MockURLProtocol.requestHandler = { request in112      let url = try #require(request.url)113      let components = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false))114      #expect(components.queryItems?.first(where: { $0.name == "sorting" })?.value == "random")115      return (response(for: request), try encodedSearchResponse())116    }117118    _ = try await makeAPI().searchWallpapers(query: "", sorting: .random)119  }120121  @Test("Non-success HTTP responses become API errors")122  func nonSuccessStatusThrowsAPIError() async {123    MockURLProtocol.requestHandler = { request in124      (response(for: request, statusCode: 503), Data("unavailable".utf8))125    }126127    do {128      _ = try await makeAPI().searchWallpapers(query: "")129      Issue.record("Expected a WallhavenError.apiError")130    } catch WallhavenError.apiError {131      // Expected.132    } catch {133      Issue.record("Unexpected error: \(error)")134    }135  }136137  @Test("Failures name the cause instead of an opaque error code")138  func failuresDescribeTheirCause() async {139    let cases: [(Int, String)] = [140      (521, "Wallhaven is unavailable right now (HTTP 521)."),141      (429, "Wallhaven rate limit reached (HTTP 429). Try again in a minute."),142      (404, "Wallhaven rejected the request (HTTP 404)."),143    ]144145    for (status, expected) in cases {146      MockURLProtocol.requestHandler = { request in147        (response(for: request, statusCode: status), Data())148      }149150      do {151        _ = try await makeAPI().searchWallpapers(query: "")152        Issue.record("Expected HTTP \(status) to throw")153      } catch WallhavenError.apiError(let message) {154        #expect(message == expected)155      } catch {156        Issue.record("Unexpected error: \(error)")157      }158    }159  }160161  @Test("Wallhaven's HTML status page is reported as an outage, not a bad response")162  func statusPageIsReportedAsOffline() async {163    MockURLProtocol.requestHandler = { request in164      (165        response(166          for: request,167          contentType: "text/html; charset=utf-8"),168        Data("<!DOCTYPE html><title>wallhaven.cc Status</title>".utf8)169      )170    }171172    do {173      _ = try await makeAPI().searchWallpapers(query: "")174      Issue.record("Expected a status page to throw")175    } catch WallhavenError.apiError(let message) {176      #expect(message == "Wallhaven is offline right now — it's serving its status page.")177    } catch {178      Issue.record("Unexpected error: \(error)")179    }180  }181182  @Test("A body-less response reports an unexpected response")183  func nonHTTPResponseDescribesItself() async {184    MockURLProtocol.requestHandler = { request in185      (186        URLResponse(187          url: request.url!, mimeType: nil, expectedContentLength: 0, textEncodingName: nil),188        Data()189      )190    }191192    do {193      _ = try await makeAPI().searchWallpapers(query: "")194      Issue.record("Expected a non-HTTP response to throw")195    } catch WallhavenError.apiError(let message) {196      #expect(message == "Wallhaven returned an unexpected response.")197    } catch {198      Issue.record("Unexpected error: \(error)")199    }200  }201202  @Test("Every error case carries a human-readable description")203  func errorCasesLocalizeTheirDescriptions() {204    #expect(WallhavenError.invalidURL.localizedDescription == "That isn't a valid Wallhaven URL.")205    #expect(WallhavenError.noData.localizedDescription == "Wallhaven returned no data.")206    #expect(207      WallhavenError.apiError("Wallhaven is unavailable right now (HTTP 521).").localizedDescription208        == "Wallhaven is unavailable right now (HTTP 521).")209    #expect(210      WallhavenError.networkError(URLError(.notConnectedToInternet)).localizedDescription211        .hasPrefix("Couldn't reach Wallhaven: "))212    #expect(213      WallhavenError.decodingError(URLError(.cannotParseResponse)).localizedDescription214        == "Wallhaven sent a response Haven couldn't read.")215  }216217  @Test("Malformed success payloads become decoding errors")218  func malformedPayloadThrowsDecodingError() async {219    MockURLProtocol.requestHandler = { request in220      (response(for: request), Data(#"{"unexpected":true}"#.utf8))221    }222223    do {224      _ = try await makeAPI().searchWallpapers(query: "")225      Issue.record("Expected a WallhavenError.decodingError")226    } catch WallhavenError.decodingError {227      // Expected.228    } catch {229      Issue.record("Unexpected error: \(error)")230    }231  }232233  @Test("Transport failures propagate to the caller")234  func transportFailurePropagates() async {235    MockURLProtocol.requestHandler = { _ in throw URLError(.notConnectedToInternet) }236237    do {238      _ = try await makeAPI().searchWallpapers(query: "")239      Issue.record("Expected a transport error")240    } catch let error as URLError {241      #expect(error.code == .notConnectedToInternet)242    } catch {243      Issue.record("Unexpected error: \(error)")244    }245  }246}