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
116
117
118
119
120
121
122
123
124
125
126
127
128
@testable import Grain
import XCTest
/// The cache is read during every card's body evaluation to decide whether a
/// gallery is blurred, so it has to resolve labels before anything loads,
/// fetch grain-serve's definitions once, and survive a failure.
@MainActor
final class LabelDefinitionsCacheTests: GrainTestCase {
private var client: XRPCClient!
override func setUp() async throws {
try await super.setUp()
client = XRPCClient(baseURL: URL(string: "https://test.local")!, session: MockURLProtocol.mockSession())
}
override func tearDown() async throws {
MockURLProtocol.handler = nil
try await super.tearDown()
}
/// `social.grain.moderation.describeLabels`, as grain-serve answers it.
private static let described = """
{"did": "did:web:grain.social", "policies": {
"labelValues": ["!takedown", "spoiler", "nudity"],
"labelValueDefinitions": [
{"identifier": "spoiler", "severity": "inform", "blurs": "content", "defaultSetting": "warn",
"locales": [{"lang": "en", "name": "Spoiler", "description": "Plot spoiler"}]},
{"identifier": "nudity", "severity": "inform", "blurs": "media", "defaultSetting": "hide",
"locales": [{"lang": "en", "name": "Nudity", "description": "Content containing nudity."}]}
]
}}
"""
func testItStartsOnTheCopyTheAppCarries() {
let cache = LabelDefinitionsCache()
XCTAssertEqual(
cache.definitions.map(\.identifier),
["copyright", "csae", "gore", "harassment", "misleading", "nudity", "other", "sexual", "spam"]
)
}
func testLoadingReadsGrainServesDefinitions() async {
let seen = Paths()
MockURLProtocol.handler = { request in
seen.append(request.url?.path ?? "")
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (Data(Self.described.utf8), response)
}
let cache = LabelDefinitionsCache()
await cache.loadIfNeeded(client: client, auth: nil)
XCTAssertEqual(seen.all, ["/xrpc/social.grain.moderation.describeLabels"])
XCTAssertEqual(cache.definitions.map(\.identifier), ["spoiler", "nudity"])
XCTAssertEqual(cache.definitions.first?.displayName, "Spoiler")
}
/// What was read stands on the next launch, before anything loads.
func testTheDefinitionsReadAreKeptForTheNextLaunch() async {
MockURLProtocol.respondWithJSON(Self.described)
await LabelDefinitionsCache().loadIfNeeded(client: client, auth: nil)
XCTAssertEqual(LabelDefinitionsCache().definitions.map(\.identifier), ["spoiler", "nudity"])
}
/// Every screen with labels calls this, so it fetches once.
func testItOnlyFetchesOnce() async {
let seen = Paths()
MockURLProtocol.handler = { request in
seen.append(request.url?.path ?? "")
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (Data(Self.described.utf8), response)
}
let cache = LabelDefinitionsCache()
await cache.loadIfNeeded(client: client, auth: nil)
await cache.loadIfNeeded(client: client, auth: nil)
XCTAssertEqual(seen.all.count, 1)
}
/// Offline, the copy the app carries stands, and the next call asks again.
func testAFailedLoadKeepsTheCopyAndIsRetried() async {
MockURLProtocol.respondWithError(statusCode: 500)
let cache = LabelDefinitionsCache()
await cache.loadIfNeeded(client: client, auth: nil)
XCTAssertEqual(cache.definitions, LabelDefinition.all)
MockURLProtocol.respondWithJSON(Self.described)
await cache.loadIfNeeded(client: client, auth: nil)
XCTAssertEqual(cache.definitions.map(\.identifier), ["spoiler", "nudity"])
}
/// A definition beats the built-in fallback for a value both know.
func testADefinitionOverridesTheFallbackTable() {
let cache = LabelDefinitionsCache(definitions: [
LabelDefinition(identifier: "nudity", blurs: "content", defaultSetting: "warn"),
])
let resolved = resolveLabels([ATLabel(src: nil, uri: nil, val: "nudity", cts: nil)], definitions: cache.definitions)
XCTAssertEqual(resolved.action, .warnContent, "Fallback would have given warnMedia")
}
/// Every label has the reason a report for it names, the one grain-serve
/// files under that label.
func testEveryLabelHasAReportReason() {
for definition in LabelDefinition.all {
XCTAssertNotNil(LabelDefinition.reportReasons[definition.identifier], definition.identifier)
}
XCTAssertEqual(LabelDefinition.reasonType(for: "harassment"), "com.atproto.moderation.defs#reasonRude")
XCTAssertEqual(LabelDefinition.reasonType(for: "unheard-of"), "com.atproto.moderation.defs#reasonOther")
}
}
/// The paths the mock was asked for, from outside the main actor.
private final class Paths: @unchecked Sendable {
private let lock = NSLock()
private var paths: [String] = []
func append(_ path: String) {
lock.withLock { paths.append(path) }
}
var all: [String] {
lock.withLock { paths }
}
}