summaryrefslogtreecommitdiff
path: root/HutchTests/SettingsViewModelTests.swift
blob: 9e4b9124081e52e644eff261d9791792b86f1ace (plain) (blame)
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
import Foundation
import Testing
@testable import Hutch

private final class SettingsViewModelCapturingURLProtocol: URLProtocol, @unchecked Sendable {
    nonisolated(unsafe) static var capturedRequests: [URLRequest] = []

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

    override func startLoading() {
        Self.capturedRequests.append(request)

        let response = HTTPURLResponse(
            url: request.url!,
            statusCode: 401,
            httpVersion: nil,
            headerFields: nil
        )!
        client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
        client?.urlProtocol(self, didLoad: Data())
        client?.urlProtocolDidFinishLoading(self)
    }

    override func stopLoading() {
        // No cleanup is needed because the stub responds immediately in `startLoading()`.
    }

    static func makeSession() -> URLSession {
        let config = URLSessionConfiguration.ephemeral
        config.protocolClasses = [Self.self]
        return URLSession(configuration: config)
    }
}

private struct DeletePGPKeyEnvelope: Decodable {
    let deletePGPKey: DeleteResultPayload?
}

private struct DeleteResultPayload: Decodable {
    let id: Int?
}

@Suite(.serialized)
struct SettingsViewModelTests {

    @Test
    @MainActor
    func deletePGPKeyResponseDecodesNullPayloadWithGraphQLErrors() throws {
        let json = """
        {
            "errors": [
                {
                    "message": "PGP key ID 13629 is set as the user's preferred PGP key - it must be unset before removing the key"
                }
            ],
            "data": {
                "deletePGPKey": null
            }
        }
        """

        let decoded = try JSONDecoder().decode(
            GraphQLResponse<DeletePGPKeyEnvelope>.self,
            from: Data(json.utf8)
        )

        #expect(decoded.data?.deletePGPKey == nil)
        #expect(decoded.errors?.first?.message.contains("preferred PGP key") == true)
    }

    @Test
    @MainActor
    func loadProfileDoesNotRequestSSHKeyFingerprintField() async throws {
        SettingsViewModelCapturingURLProtocol.capturedRequests = []

        let client = SRHTClient(
            session: SettingsViewModelCapturingURLProtocol.makeSession(),
            token: "test-token"
        )
        let viewModel = SettingsViewModel(client: client)

        await viewModel.loadProfile()

        let request = try #require(SettingsViewModelCapturingURLProtocol.capturedRequests.first)
        let body = try #require(request.httpBody)
        let jsonObject = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any])
        let query = try #require(jsonObject["query"] as? String)

        #expect(query.contains("sshKeys"))
        #expect(!query.contains("results { id fingerprint comment created lastUsed }"))
        #expect(!query.contains("fingerprint comment created lastUsed"))
    }
}