1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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)
}
}