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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
|
// swiftlint:disable file_length
import XCTest
final class ViewDerivedDataTests: XCTestCase { // swiftlint:disable:this type_body_length
func testGenericListViewDerivedCollectionsAreReferencedOncePerRenderPass() throws {
let source = try loadSource(at: "Sora/Views/Generic/GenericListView.swift")
let normalizedSource = strippingCommentsAndStrings(from: source)
let filteredItemsUsages = referenceCount(
for: "filteredItems",
in: normalizedSource
)
let sortedFilteredItemsUsages = referenceCount(
for: "sortedFilteredItems",
in: normalizedSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertLessThanOrEqual(
filteredItemsUsages,
1,
"filteredItems should be consumed once per dependency change."
)
// swiftlint:disable:next prefer_nimble
XCTAssertLessThanOrEqual(
sortedFilteredItemsUsages,
1,
"sortedFilteredItems should be consumed once per dependency change."
)
}
func testPostGridViewDerivedCollectionsAreReferencedOncePerRenderPass() throws {
let source = try loadSource(at: "Sora/Views/Post/Grid/PostGridView.swift")
let normalizedSource = strippingCommentsAndStrings(from: source)
let activePostsUsages = referenceCount(
for: "activePosts",
in: normalizedSource
)
let getColumnsDataUsages = invocationCount(
forFunction: "getColumnsData",
in: normalizedSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertLessThanOrEqual(
activePostsUsages,
1,
"activePosts-derived data should be consumed once per dependency change."
)
// swiftlint:disable:next prefer_nimble
XCTAssertLessThanOrEqual(
getColumnsDataUsages,
1,
"getColumnsData should be invoked once per dependency change."
)
}
func testFavoritesViewDerivedCollectionsAreReferencedOncePerRenderPass() throws {
let source = try loadSource(at: "Sora/Views/FavoritesView.swift")
let normalizedSource = strippingCommentsAndStrings(from: source)
let filteredFavoritesUsages = referenceCount(
for: "filteredFavorites",
in: normalizedSource
)
let sortedFilteredFavoritesUsages = referenceCount(
for: "sortedFilteredFavorites",
in: normalizedSource
)
let inlinePostMappingCount = tokenCount(
matching: #"\bsortedFilteredFavorites\s*\.\s*map\s*\{"#,
in: normalizedSource
)
let columnsSplitterUsages = invocationCount(
forFunction: "getColumnsData",
in: normalizedSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertLessThanOrEqual(
filteredFavoritesUsages,
1,
"filteredFavorites should be consumed once per dependency change."
)
// swiftlint:disable:next prefer_nimble
XCTAssertLessThanOrEqual(
sortedFilteredFavoritesUsages,
1,
"sortedFilteredFavorites should be consumed once per dependency change."
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
inlinePostMappingCount,
0,
"Favorites grid should not remap sorted favorites to posts inline on each cell render."
)
// swiftlint:disable:next prefer_nimble
XCTAssertLessThanOrEqual(
columnsSplitterUsages,
1,
"Favorites grid column distribution should be derived once per dependency change."
)
}
func testFolderMenuHierarchyIsSharedAcrossConsumers() throws {
let consumerPaths = [
"Sora/Views/Generic/GenericListView.swift",
"Sora/Views/FavoritesView.swift",
"Sora/Views/Post/Grid/PostGridView.swift",
"Sora/Views/BookmarkMenuButtonView.swift",
"Sora/Views/FavoriteMenuButtonView.swift",
]
for consumerPath in consumerPaths {
let source = try loadSource(at: consumerPath)
let sharedMenuUsages = tokenCount(
matching: #"\bFolderMenuView\s*\("#,
in: source
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
sharedMenuUsages,
0,
"\(consumerPath) should use FolderMenuView for folder hierarchy rendering."
)
}
}
func testSearchSuggestionsCacheIsBuiltFromItemsChanges() throws {
let source = try loadSource(at: "Sora/Views/SearchSuggestionsView.swift")
let normalizedSource = strippingCommentsAndStrings(from: source)
let stateCacheCount = tokenCount(
matching: #"\@State\s+private\s+var\s+cachedTags"#,
in: normalizedSource
)
let itemsMapCount = tokenCount(
matching: #"\bcachedTags\s*=\s*items\s*\.\s*map"#,
in: normalizedSource
)
let itemsChangeObserverCount = tokenCount(
matching: #"\.onChange\s*\(\s*of:\s*itemsCacheKey\s*\)"#,
in: normalizedSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
stateCacheCount,
0,
"Search suggestions should keep preprocessed tags in view state."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
itemsMapCount,
0,
"Search suggestions should build cached tags from items."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
itemsChangeObserverCount,
0,
"Search suggestions should refresh cached tags only when items change."
)
}
func testPostDetailsImageActionsUseAsyncCachedImageLoading() throws {
let source = try loadSource(at: "Sora/Views/Post/Details/PostDetailsImageView.swift")
let normalizedSource = strippingCommentsAndStrings(from: source)
let synchronousLoadCount = tokenCount(
matching: #"\bNSData\s*\(\s*contentsOf:"#,
in: normalizedSource
)
let cachedLoaderCount = tokenCount(
matching: #"\bImageCacheManager\s*\.\s*shared\s*\.\s*loadImageData\s*\("#,
in: normalizedSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
synchronousLoadCount,
0,
"Post details image actions should avoid synchronous NSData file or network loads."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
cachedLoaderCount,
0,
"Post details image actions should use cache-backed async image loading."
)
}
func testListViewsAvoidComparatorRandomShuffleSorting() throws {
let listViewSource = try loadSource(at: "Sora/Views/Generic/GenericListView.swift")
let favoritesViewSource = try loadSource(at: "Sora/Views/FavoritesView.swift")
let normalizedListViewSource = strippingCommentsAndStrings(from: listViewSource)
let normalizedFavoritesViewSource = strippingCommentsAndStrings(from: favoritesViewSource)
let listViewComparatorRandomCount = tokenCount(
matching: #"\bBool\s*\.\s*random\s*\("#,
in: normalizedListViewSource
)
let favoritesViewComparatorRandomCount = tokenCount(
matching: #"\bBool\s*\.\s*random\s*\("#,
in: normalizedFavoritesViewSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
listViewComparatorRandomCount,
0,
"Generic list sorting should not use comparator-based random ordering."
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
favoritesViewComparatorRandomCount,
0,
"Favorites sorting should not use comparator-based random ordering."
)
}
func testBooruManagerRemovesUnusedXMLParserPoolPaths() throws {
let source = try loadSource(at: "Sora/Data/Booru/BooruManager.swift")
let normalizedSource = strippingCommentsAndStrings(from: source)
let poolStorageCount = tokenCount(
matching: #"\bxmlParserPool\b"#,
in: normalizedSource
)
let lockStorageCount = tokenCount(
matching: #"\bparserPoolLock\b"#,
in: normalizedSource
)
let parserFactoryCount = invocationCount(
forFunction: "xmlParser",
in: normalizedSource
)
let parserReturnCount = invocationCount(
forFunction: "returnXMLParser",
in: normalizedSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
poolStorageCount,
0,
"BooruManager should not keep an unused XML parser pool."
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
lockStorageCount,
0,
"BooruManager should not keep an unused parser pool lock."
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
parserFactoryCount,
0,
"BooruManager should not expose unused xml parser factory paths."
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
parserReturnCount,
0,
"BooruManager should not expose unused xml parser return paths."
)
}
func testBooruManagerDanbooruPostsUseQueryParamAuthentication() throws {
let source = try loadSource(at: "Sora/Data/Booru/BooruManager.swift")
let urlBuilderSection = try extractFunction(
named: "func url(forPosts page: Int, limit: Int, tags: [String]) -> URL?",
from: source
)
let danbooruLoginQueryCount = tokenCount(
matching: #"case\s+\.danbooru[\s\S]*URLQueryItem\(name:\s*"login""#,
in: urlBuilderSection
)
let danbooruAPIKeyQueryCount = tokenCount(
matching: #"case\s+\.danbooru[\s\S]*URLQueryItem\(name:\s*"api_key""#,
in: urlBuilderSection
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
danbooruLoginQueryCount,
0,
"Danbooru requests should authenticate with a `login` query parameter."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
danbooruAPIKeyQueryCount,
0,
"Danbooru requests should authenticate with an `api_key` query parameter."
)
}
func testBooruManagerDanbooruPostsIncludeLimitParameter() throws {
let source = try loadSource(at: "Sora/Data/Booru/BooruManager.swift")
let urlBuilderSection = try extractFunction(
named: "func url(forPosts page: Int, limit: Int, tags: [String]) -> URL?",
from: source
)
let danbooruCaseStart = try XCTUnwrap(urlBuilderSection.range(of: "case .danbooru:")?.lowerBound)
let danbooruCaseEnd = try XCTUnwrap(
urlBuilderSection.range(of: "case .moebooru:", range: danbooruCaseStart..<urlBuilderSection.endIndex)?
.lowerBound
)
let danbooruSection = String(urlBuilderSection[danbooruCaseStart..<danbooruCaseEnd])
let danbooruLimitQueryCount = tokenCount(
matching: #"URLQueryItem\(name:\s*"limit""#,
in: danbooruSection
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
danbooruLimitQueryCount,
0,
"Danbooru requests should include a `limit` query parameter."
)
}
func testBooruManagerDanbooruPostsUseBeforeCursorPagination() throws {
let source = try loadSource(at: "Sora/Data/Booru/BooruManager.swift")
let urlBuilderSection = try extractFunction(
named: "func url(forPosts page: Int, limit: Int, tags: [String]) -> URL?",
from: source
)
let danbooruCaseStart = try XCTUnwrap(urlBuilderSection.range(of: "case .danbooru:")?.lowerBound)
let danbooruCaseEnd = try XCTUnwrap(
urlBuilderSection.range(of: "case .moebooru:", range: danbooruCaseStart..<urlBuilderSection.endIndex)?
.lowerBound
)
let danbooruSection = String(urlBuilderSection[danbooruCaseStart..<danbooruCaseEnd])
let pageTokenFunctionSection = try extractFunction(
named: "private func danbooruPageToken(for page: Int) -> String",
from: source
)
let danbooruCursorPageQueryCount = tokenCount(
matching: #"URLQueryItem\(name:\s*"page",\s*value:\s*danbooruPageToken\(for:\s*page\)\)"#,
in: danbooruSection
)
let beforeCursorCount = tokenCount(
matching: #""b\\\#\("#,
in: pageTokenFunctionSection
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
danbooruCursorPageQueryCount,
0,
"Danbooru requests should derive the `page` query using a cursor-aware token helper."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
beforeCursorCount,
0,
"Danbooru cursor pagination should build `page=b<id>` for subsequent pages."
)
}
func testBooruManagerValidatesHTTPStatusCodesForRequests() throws {
let source = try loadSource(at: "Sora/Data/Booru/BooruManager.swift")
let requestURLSection = try extractFunction(
named: "func requestURL(_ url: URL) async throws -> Data",
from: source
)
let statusValidationCount = tokenCount(
matching: #"\.validate\(statusCode:\s*200\.\.<300\)"#,
in: requestURLSection
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
statusValidationCount,
0,
"BooruManager should validate HTTP status codes to avoid silent API failures."
)
}
func testBooruManagerDanbooruFallsBackToUnauthenticatedRequestsOnUnauthorized() throws {
let source = try loadSource(at: "Sora/Data/Booru/BooruManager.swift")
let retrySection = try extractFunction(
named: "private func fetchPostsWithRetry(url: URL) async -> [BooruPost]",
from: source
)
let credentialStripperSection = try extractFunction(
named: "private static func removingDanbooruCredentials(from url: URL) -> URL?",
from: source
)
let unauthorizedResponseCheckCount = tokenCount(
matching: #"responseCode\s*==\s*401"#,
in: retrySection
)
let fallbackInvocationCount = tokenCount(
matching: #"removingDanbooruCredentials\(from:\s*requestURL\)"#,
in: retrySection
)
let strippedQueryItemCount = tokenCount(
matching: #"queryItem\.name\s*!=\s*"login"\s*&&\s*queryItem\.name\s*!=\s*"api_key""#,
in: credentialStripperSection
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
unauthorizedResponseCheckCount,
0,
"Danbooru fetch retries should detect unauthorized responses."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
fallbackInvocationCount,
0,
"Danbooru fetch retries should retry without credentials after unauthorized responses."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
strippedQueryItemCount,
0,
"Credential fallback should remove both `login` and `api_key` query parameters."
)
}
func testDanbooruPostModelUsesOptionalVisibilityDependentFields() throws {
let source = try loadSource(at: "Sora/Data/Danbooru/DanbooruPost.swift")
let optionalFileURLCount = tokenCount(matching: #"let\s+fileURL:\s+String\?"#, in: source)
let optionalLargeFileURLCount = tokenCount(matching: #"let\s+largeFileURL:\s+String\?"#, in: source)
let optionalPreviewURLCount = tokenCount(
matching: #"let\s+previewFileURL:\s+String\?"#,
in: source
)
let optionalMD5Count = tokenCount(matching: #"let\s+md5:\s+String\?"#, in: source)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
optionalFileURLCount,
0,
"Danbooru model should decode visibility-dependent file URLs as optional."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
optionalLargeFileURLCount,
0,
"Danbooru model should decode visibility-dependent large file URLs as optional."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
optionalPreviewURLCount,
0,
"Danbooru model should decode visibility-dependent preview URLs as optional."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
optionalMD5Count,
0,
"Danbooru model should decode visibility-dependent MD5 values as optional."
)
}
func testDanbooruParserUsesLossyDecodingForMixedRecordValidity() throws {
let source = try loadSource(at: "Sora/Data/Danbooru/DanbooruPostParser.swift")
let lossyDecoderUsageCount = tokenCount(
matching: #"\[FailableDecodable<DanbooruPost>\]\.self"#,
in: source
)
let malformedRecordDebugCount = tokenCount(
matching: #"dropped\s*\\\#\(droppedRecordCount\)\s*malformed records"#,
in: source
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
lossyDecoderUsageCount,
0,
"Danbooru parser should decode lossily so one malformed item doesn't drop the entire page."
)
// swiftlint:disable:next prefer_nimble
XCTAssertGreaterThan(
malformedRecordDebugCount,
0,
"Danbooru parser should log dropped malformed records for observability."
)
}
func testThumbnailGridViewAvoidsDirectColumnArrayIndexing() throws {
let source = try loadSource(at: "Sora/Views/Shared/ThumbnailGridView.swift")
let normalizedSource = strippingCommentsAndStrings(from: source)
let directColumnIndexingCount = tokenCount(
matching: #"\bcolumnsData\s*\[\s*columnIndex\s*\]"#,
in: normalizedSource
)
// swiftlint:disable:next prefer_nimble
XCTAssertEqual(
directColumnIndexingCount,
0,
"Thumbnail grid should avoid direct column indexing that can crash when column and data counts drift."
)
}
private func referenceCount(for symbol: String, in source: String) -> Int {
let totalMatches = tokenCount(matching: #"\b\#(symbol)\b"#, in: source)
let declarationMatches = tokenCount(matching: #"\b(?:var|let)\s+\#(symbol)\b"#, in: source)
return max(0, totalMatches - declarationMatches)
}
private func invocationCount(forFunction name: String, in source: String) -> Int {
let totalMatches = tokenCount(matching: #"\b\#(name)\s*\("#, in: source)
let declarationMatches = tokenCount(matching: #"\bfunc\s+\#(name)\s*\("#, in: source)
return max(0, totalMatches - declarationMatches)
}
}
|