~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
272 lines · 12.6 KB Raw History
import SwiftUI
import UIKit
import XCTest

@testable import OldFella

@MainActor
final class SignedInAvatarStoreTests: XCTestCase {
    func testToolbarShowsCachedAvatarBeforeProfileRestoreFinishes() async throws {
        let fixture = Fixture()
        fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
        let first = fixture.makeStore()
        first.update(for: fixture.account)
        _ = try await waitForAvatar(in: first)

        fixture.script.addResponse(304)
        let store = fixture.makeStore()
        let gate = ThreadGate()
        let service = ModerationTestService()
        service.restoredAccount = fixture.account
        service.restoreGate = gate
        let model = AppModel(service: service, signedInAvatar: store)
        let toolbar = AccountAvatar(account: nil, size: 32, showsDuringSessionRestore: true)
        XCTAssertEqual(try pixels(in: toolbar, model: model), [[0, 0, 0, 0]])

        await gate.waitUntilStarted()
        defer { Task { await gate.release() } }
        try await waitUntil { store.launchEntry != nil }
        let preview = try XCTUnwrap(store.launchEntry)
        XCTAssertNil(model.account)
        XCTAssertTrue(try pixels(in: toolbar, model: model).contains([0, 0, 0, 255]))
        XCTAssertEqual(fixture.script.requests.count, 1)

        await gate.release()
        try await waitUntil { !model.isRestoringSession }
        XCTAssertTrue(store.entry === preview)
        XCTAssertNil(store.launchEntry)
        try await waitForRequests(2, in: fixture)
        XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"), "\"first\"")
    }

    func testAvatarPlaceholderUsesTwoGrayColorsInBothAppearances() throws {
        let model = AppModel(service: ModerationTestService())
        let placeholder = AccountAvatar(account: nil, size: 32)
        for (scheme, background, silhouette) in [(ColorScheme.light, 209, 84), (.dark, 69, 184)] {
            let colors = try pixels(in: placeholder, model: model, scheme: scheme)
            for gray in [background, silhouette] {
                XCTAssertTrue(colors.contains { pixel in
                    pixel[3] == 255 && pixel[0] == pixel[1] && pixel[1] == pixel[2] && abs(Int(pixel[0]) - gray) <= 1
                })
            }
        }
    }

    func testRelaunchShowsCachedAvatarAndChecksETag() async throws {
        let fixture = Fixture()
        fixture.script.addImage(.black, headers: ["ETag": "\"first\"", "Last-Modified": Fixture.modified])
        let first = fixture.makeStore()
        first.update(for: fixture.account)
        let original = try await waitForAvatar(in: first)

        fixture.script.addResponse(304)
        let relaunched = fixture.makeStore()
        await relaunched.restore(for: fixture.account)
        let cached = try XCTUnwrap(relaunched.entry)
        XCTAssertEqual(cached.ringColors, original.ringColors)
        try await waitForRequests(2, in: fixture)
        XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"), "\"first\"")
        XCTAssertNil(fixture.script.requests.last?.value(forHTTPHeaderField: "If-Modified-Since"))
        XCTAssertEqual(fixture.script.requests.last?.url, AvatarImageURL.thumbnail(fixture.url))
    }

    func testLastModifiedValidatesCachedImageBeforeDisplayWhenRequired() async throws {
        let fixture = Fixture()
        fixture.script.addImage(.black, headers: ["Cache-Control": "no-cache", "Last-Modified": Fixture.modified])
        let first = fixture.makeStore()
        first.update(for: fixture.account)
        let original = try await waitForAvatar(in: first)

        fixture.script.addResponse(304)
        let relaunched = fixture.makeStore()
        await relaunched.restore(for: fixture.account)
        XCTAssertNil(relaunched.entry)
        let validated = try await waitForAvatar(in: relaunched)
        XCTAssertEqual(validated.ringColors, original.ringColors)
        XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-Modified-Since"), Fixture.modified)
    }

    func testChangedImageAtSameURLReplacesDiskCache() async throws {
        let fixture = Fixture()
        fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
        let first = fixture.makeStore()
        first.update(for: fixture.account)
        let original = try await waitForAvatar(in: first)

        fixture.script.addImage(.white, headers: ["ETag": "\"second\""])
        let relaunched = fixture.makeStore()
        await relaunched.restore(for: fixture.account)
        XCTAssertEqual(relaunched.entry?.ringColors, original.ringColors)
        let replacement = try await waitForAvatar(in: relaunched, differentFrom: original.ringColors)

        fixture.script.addResponse(503)
        let restarted = fixture.makeStore()
        await restarted.restore(for: fixture.account)
        XCTAssertEqual(restarted.entry?.ringColors, replacement.ringColors)
        try await waitForRequests(3, in: fixture)
        XCTAssertEqual(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"), "\"second\"")
    }

    func testNewURLUsesNoOldValidatorAndNoStoreClearsDiskCache() async throws {
        let fixture = Fixture()
        fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
        let first = fixture.makeStore()
        first.update(for: fixture.account)
        let original = try await waitForAvatar(in: first)

        var updated = fixture.account
        updated.avatarURL = fixture.url.deletingLastPathComponent().appending(path: "new.jpeg")
        fixture.script.addImage(.white, headers: ["Cache-Control": "no-store"])
        let relaunched = fixture.makeStore()
        await relaunched.restore(for: updated)
        XCTAssertEqual(relaunched.entry?.ringColors, original.ringColors)
        _ = try await waitForAvatar(in: relaunched, differentFrom: original.ringColors)
        XCTAssertNil(fixture.script.requests.last?.value(forHTTPHeaderField: "If-None-Match"))
        XCTAssertEqual(fixture.script.requests.last?.url, updated.avatarURL.map(AvatarImageURL.thumbnail))

        fixture.script.addResponse(503)
        let restarted = fixture.makeStore()
        await restarted.restore(for: updated)
        XCTAssertNil(restarted.entry)
    }

    func testSessionRestoreUsesCachedAvatarWhenProfileLookupFailsAndSignOutClearsIt() async throws {
        let fixture = Fixture()
        fixture.script.addImage(.black, headers: ["ETag": "\"first\""])
        let first = fixture.makeStore()
        first.update(for: fixture.account)
        let original = try await waitForAvatar(in: first)

        fixture.script.addResponse(503)
        let store = fixture.makeStore()
        let service = ModerationTestService()
        var account = fixture.account
        account.avatarURL = nil
        account.isAvatarURLKnown = false
        service.restoredAccount = account
        let model = AppModel(service: service, signedInAvatar: store)
        try await waitUntil { !model.isRestoringSession }
        XCTAssertTrue(store.matches(model.account))
        XCTAssertEqual(store.entry?.ringColors, original.ringColors)
        account.isAvatarURLKnown = true
        XCTAssertFalse(store.matches(account))
        try await waitForRequests(2, in: fixture)

        await model.signOut()
        XCTAssertNil(store.entry)
        let relaunched = fixture.makeStore()
        fixture.script.addResponse(503)
        await relaunched.restore(for: fixture.account)
        XCTAssertNil(relaunched.entry)
    }

    private func waitForAvatar(in store: SignedInAvatarStore, differentFrom colors: AvatarRingColors? = nil)
        async throws -> AvatarStore.Entry {
        try await waitUntil { store.entry != nil && store.entry?.ringColors != colors }
        return try XCTUnwrap(store.entry)
    }

    private func waitForRequests(_ count: Int, in fixture: Fixture) async throws {
        try await waitUntil { fixture.script.requests.count >= count }
    }

    private func waitUntil(_ condition: () -> Bool) async throws {
        let deadline = ContinuousClock.now + .seconds(5)
        while !condition(), ContinuousClock.now < deadline {
            try await Task.sleep(for: .milliseconds(10))
        }
        _ = try XCTUnwrap(condition() ? true : nil, "The avatar request did not finish in time.")
    }

    private func pixels(in avatar: AccountAvatar, model: AppModel, scheme: ColorScheme = .light) throws -> Set<[UInt8]> {
        let suite = "AvatarRendering.\(UUID().uuidString)"
        let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
        defer { defaults.removePersistentDomain(forName: suite) }
        defaults.set(false, forKey: "hideAvatars")
        let renderer = ImageRenderer(content: avatar.environment(model).environment(\.colorScheme, scheme)
            .defaultAppStorage(defaults))
        let image = try XCTUnwrap(renderer.cgImage)
        let rowBytes = image.width * 4
        var bytes = [UInt8](repeating: 0, count: rowBytes * image.height)
        try bytes.withUnsafeMutableBytes { buffer in
            let context = try XCTUnwrap(CGContext(
                data: buffer.baseAddress, width: image.width, height: image.height,
                bitsPerComponent: 8, bytesPerRow: rowBytes, space: CGColorSpace(name: CGColorSpace.sRGB)!,
                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
            ))
            context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
        }
        return Set(stride(from: 0, to: bytes.count, by: 4).map { Array(bytes[$0..<($0 + 4)]) })
    }

    private struct Fixture {
        static let modified = "Wed, 01 Jan 2025 12:00:00 GMT"
        let url = URL(string: "https://cdn.bsky.app/img/avatar/plain/\(UUID().uuidString)/old.jpeg")!
        let fileURL = FileManager.default.temporaryDirectory.appending(path: "\(UUID().uuidString).plist")
        let script = SignedInAvatarProtocol.Script()

        var account: Account { Account(handle: "demo.bsky.social", displayName: "Demo", id: "demo", avatarURL: url) }

        @MainActor func makeStore() -> SignedInAvatarStore {
            SignedInAvatarProtocol.register(script, for: url.deletingLastPathComponent().lastPathComponent)
            let configuration = URLSessionConfiguration.ephemeral
            configuration.protocolClasses = [SignedInAvatarProtocol.self]
            configuration.urlCache = nil
            return SignedInAvatarStore(fileURL: fileURL, session: URLSession(configuration: configuration))
        }
    }
}

private final class SignedInAvatarProtocol: URLProtocol {
    private static let lock = NSLock()
    private static var scripts: [String: Script] = [:]

    final class Script {
        private let lock = NSLock()
        private var responses: [(Int, [String: String], Data)] = []
        private var recordedRequests: [URLRequest] = []

        var requests: [URLRequest] { lock.withLock { recordedRequests } }

        func addImage(_ color: UIColor, headers: [String: String]) {
            let data = UIGraphicsImageRenderer(size: CGSize(width: 16, height: 16)).image { context in
                color.setFill()
                context.fill(CGRect(x: 0, y: 0, width: 16, height: 16))
            }.pngData()!
            addResponse(200, headers: headers, data: data)
        }

        func addResponse(_ status: Int, headers: [String: String] = [:], data: Data = Data()) {
            lock.withLock { responses.append((status, headers, data)) }
        }

        func nextResponse(for request: URLRequest) -> (Int, [String: String], Data) {
            lock.withLock {
                recordedRequests.append(request)
                return responses.isEmpty ? (500, [:], Data()) : responses.removeFirst()
            }
        }
    }

    static func register(_ script: Script, for id: String) {
        lock.withLock { scripts[id] = script }
    }

    override static func canInit(with request: URLRequest) -> Bool { true }
    override static func canonicalRequest(for request: URLRequest) -> URLRequest { request }
    override func stopLoading() {}

    override func startLoading() {
        let url = request.url!
        let id = url.deletingLastPathComponent().lastPathComponent
        guard let script = Self.lock.withLock({ Self.scripts[id] }) else {
            client?.urlProtocol(self, didFailWithError: URLError(.resourceUnavailable))
            return
        }
        let (status, headers, data) = script.nextResponse(for: request)
        let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!
        client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
        if !data.isEmpty { client?.urlProtocol(self, didLoad: data) }
        client?.urlProtocolDidFinishLoading(self)
    }
}