import UIKit import XCTest @testable import OldFella private final class ChangingAvatarProtocol: URLProtocol { private static let lock = NSLock() private static var counts: [URL: Int] = [:] static func count(for url: URL) -> Int { lock.lock() defer { lock.unlock() } return counts[url, default: 0] } override static func canInit(with request: URLRequest) -> Bool { true } override static func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { let url = request.url! Self.lock.lock() Self.counts[url, default: 0] += 1 let count = Self.counts[url]! Self.lock.unlock() let directives = url.path == "/fresh" ? "max-age=3600" : url.lastPathComponent let response = HTTPURLResponse( url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Cache-Control": directives])! let data = UIGraphicsImageRenderer(size: CGSize(width: 16, height: 16)).image { context in (count == 1 ? UIColor.black : .white).setFill() context.fill(CGRect(x: 0, y: 0, width: 16, height: 16)) }.pngData()! client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: data) client?.urlProtocolDidFinishLoading(self) } override func stopLoading() {} } @MainActor final class AvatarStoreTests: XCTestCase { private func store() -> AvatarStore { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [ChangingAvatarProtocol.self] configuration.urlCache = nil return AvatarStore(session: URLSession(configuration: configuration)) } private func url(_ path: String) -> URL { URL(string: "https://\(UUID().uuidString).example.test/\(path)")! } func testFreshAvatarReusesImageAndBothRingColors() async throws { let store = store() let url = url("fresh") let firstResult = await store.avatar(for: url) let first = try XCTUnwrap(firstResult) let second = await store.avatar(for: url) XCTAssertTrue(first === second) XCTAssertTrue(first === store.cachedAvatar(for: url)) XCTAssertEqual(ChangingAvatarProtocol.count(for: url), 1) XCTAssertEqual(first.ringColors, AvatarRingColors.calculate(for: first.image.cgImage!)) store.clear() XCTAssertNil(store.cachedAvatar(for: url)) let reloaded = await store.avatar(for: url) XCTAssertNotNil(reloaded) XCTAssertFalse(first === reloaded) XCTAssertEqual(ChangingAvatarProtocol.count(for: url), 2) } func testBlueskyAvatarsRequestThumbnailsAndShareTheirCache() async throws { let store = store() let fullSize = URL(string: "https://cdn.bsky.app/img/avatar/\(UUID().uuidString)/max-age=3600")! let thumbnail = AvatarImageURL.thumbnail(fullSize) let firstResult = await store.avatar(for: fullSize) let first = try XCTUnwrap(firstResult) let second = await store.avatar(for: thumbnail) XCTAssertTrue(first === second) XCTAssertTrue(first === store.cachedAvatar(for: fullSize)) XCTAssertTrue(first === store.cachedAvatar(for: thumbnail)) XCTAssertEqual(ChangingAvatarProtocol.count(for: thumbnail), 1) XCTAssertEqual(ChangingAvatarProtocol.count(for: fullSize), 0) store.clear() XCTAssertNil(store.cachedAvatar(for: fullSize)) XCTAssertNil(store.cachedAvatar(for: thumbnail)) } func testExpiredAvatarLoadsChangedImageAndColors() async throws { try await assertRefresh("max-age=0") } func testNoCacheAvatarDoesNotBypassValidation() async throws { try await assertRefresh("no-cache") } func testNoStoreAvatarIsNotRetainedInDecodedCache() async throws { try await assertRefresh("no-store") } func testMissingLifetimeDoesNotKeepDecodedAvatarForever() async throws { try await assertRefresh("public") } private func assertRefresh(_ directive: String) async throws { let store = store() let url = url(directive) let firstResult = await store.avatar(for: url) let first = try XCTUnwrap(firstResult) XCTAssertNil(store.cachedAvatar(for: url)) let secondResult = await store.avatar(for: url) let second = try XCTUnwrap(secondResult) XCTAssertFalse(first.image === second.image) XCTAssertNotEqual(first.ringColors, second.ringColors) XCTAssertEqual(ChangingAvatarProtocol.count(for: url), 2) } }