-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomainCacheEngineTests.swift
More file actions
223 lines (193 loc) Β· 8.58 KB
/
Copy pathDomainCacheEngineTests.swift
File metadata and controls
223 lines (193 loc) Β· 8.58 KB
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
//
// DomainCacheEngineTests.swift
// DataTests
//
// Created by λ°λ―Όμ on 3/20/26.
// Copyright Β© 2025 yapp25thTeamTnT. All rights reserved.
//
import CoreData
import XCTest
@testable import Data
final class DomainCacheEngineTests: XCTestCase {
func test_loadSnapshot_returnsFreshStaleAndMissWithoutNetworkOutcomeConcern() async throws {
let storage: InMemoryDomainSnapshotStore = InMemoryDomainSnapshotStore()
let nowProvider: MutableDomainCacheDateProvider = .init(Date(timeIntervalSince1970: 1_700_000_000))
let sut: DomainCacheEngine = DomainCacheEngine(
policy: .init(directoryName: "EngineTests", maxEntryCount: 8, maxSnapshotAge: 60 * 60),
storage: storage,
now: { nowProvider.now() }
)
let key: DomainCacheKey = .init(namespace: "session-A", components: ["profile"])
let miss: DomainCacheReadResult<TestSnapshot> = try await sut.loadSnapshot(
TestSnapshot.self,
key: key,
maxAge: 60
)
guard case .miss = miss else {
return XCTFail("Expected miss")
}
try await sut.saveSnapshot(TestSnapshot(savedAt: nowProvider.now(), value: "fresh"), key: key)
let fresh: DomainCacheReadResult<TestSnapshot> = try await sut.loadSnapshot(
TestSnapshot.self,
key: key,
maxAge: 60
)
guard case .fresh(let freshSnapshot) = fresh else {
return XCTFail("Expected fresh")
}
XCTAssertEqual(freshSnapshot.value, "fresh")
nowProvider.current = nowProvider.current.addingTimeInterval(61)
let stale: DomainCacheReadResult<TestSnapshot> = try await sut.loadSnapshot(
TestSnapshot.self,
key: key,
maxAge: 60
)
guard case .stale(let staleSnapshot) = stale else {
return XCTFail("Expected stale")
}
XCTAssertEqual(staleSnapshot.value, "fresh")
}
func test_saveSnapshot_requestsCleanupForSavedNamespace() async throws {
let storage: InMemoryDomainSnapshotStore = InMemoryDomainSnapshotStore()
let now: Date = Date(timeIntervalSince1970: 1_700_000_000)
let sut: DomainCacheEngine = DomainCacheEngine(
policy: .init(directoryName: "EngineTests", maxEntryCount: 1, maxSnapshotAge: 60),
storage: storage,
now: { now }
)
try await sut.saveSnapshot(
TestSnapshot(savedAt: now, value: "value"),
key: .init(namespace: "session-A", components: ["profile"])
)
let cleanedNamespaces: [String] = await storage.cleanedNamespaces
XCTAssertEqual(cleanedNamespaces, ["session-A"])
}
func test_cleanupSnapshotsAcrossNamespaces_requestsGlobalStorageCleanup() async throws {
let storage: InMemoryDomainSnapshotStore = InMemoryDomainSnapshotStore()
let now: Date = Date(timeIntervalSince1970: 1_700_000_000)
let sut: DomainCacheEngine = DomainCacheEngine(
policy: .init(directoryName: "EngineTests", maxEntryCount: 8, maxSnapshotAge: 60),
storage: storage,
now: { now }
)
try await sut.cleanupSnapshotsAcrossNamespaces()
let globalCleanupDates: [Date] = await storage.globalCleanupDates
XCTAssertEqual(globalCleanupDates, [now])
}
func test_cacheKey_doesNotExposeReversibleSessionNamespace() {
let namespace: String = "Bearer production-session-token"
let legacyNamespaceComponent: String = DomainCacheKey.safeComponent(namespace)
let sut: DomainCacheKey = .init(namespace: namespace, components: ["profile"])
XCTAssertFalse(sut.fileName.contains(namespace))
XCTAssertFalse(sut.fileName.hasPrefix(legacyNamespaceComponent))
XCTAssertFalse(sut.namespaceFilePrefix.hasPrefix(legacyNamespaceComponent))
}
func test_jsonStore_cleanupRemovesLegacyReversibleNamespaceFile() async throws {
let baseDirectory: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("DomainCacheLegacyTests-\(UUID().uuidString)", isDirectory: true)
addTeardownBlock {
try? FileManager.default.removeItem(at: baseDirectory)
}
let policy: DomainCachePolicy = .init(
directoryName: "EngineTests",
maxEntryCount: 8,
maxSnapshotAge: 60 * 60
)
let namespace: String = "Bearer production-session-token"
let legacyNamespace: String = "Bearer retired-session-token"
let legacyFileURL: URL = baseDirectory
.appendingPathComponent(policy.directoryName, isDirectory: true)
.appendingPathComponent(
"\(DomainCacheKey.safeComponent(legacyNamespace))__legacy.json"
)
try FileManager.default.createDirectory(
at: legacyFileURL.deletingLastPathComponent(),
withIntermediateDirectories: true
)
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
try encoder.encode(
TestSnapshot(savedAt: Date(), value: "legacy")
).write(to: legacyFileURL)
let sut: DomainCacheEngine = .init(
policy: policy,
storage: JSONFileDomainSnapshotStore(baseDirectory: baseDirectory)
)
try await sut.saveSnapshot(
TestSnapshot(savedAt: Date(), value: "current"),
key: .init(namespace: namespace, components: ["profile"])
)
XCTAssertFalse(FileManager.default.fileExists(atPath: legacyFileURL.path))
}
func test_coreDataStore_persistsHashedNamespaceInsteadOfSessionToken() async throws {
let namespace: String = "Bearer production-session-token"
let container: DomainCacheContainer = try .inMemory()
let sut: DomainCacheEngine = .init(
policy: .init(directoryName: "EngineTests", maxEntryCount: 8, maxSnapshotAge: 60 * 60),
storage: CoreDataDomainSnapshotStore(container: container)
)
try await sut.saveSnapshot(
TestSnapshot(savedAt: Date(), value: "current"),
key: .init(namespace: namespace, components: ["profile"])
)
let request: NSFetchRequest<NSManagedObject> = .init(
entityName: DomainCacheContainer.Record.entityName
)
let records: [NSManagedObject] = try container.persistentContainer.viewContext.fetch(request)
let persistedNamespace: String? = records.first?.value(
forKey: DomainCacheContainer.Record.namespace
) as? String
XCTAssertEqual(records.count, 1)
XCTAssertNotEqual(persistedNamespace, namespace)
XCTAssertNotEqual(persistedNamespace, DomainCacheKey.safeComponent(namespace))
}
}
private struct TestSnapshot: DomainCacheSnapshot, Equatable {
let savedAt: Date
let value: String
}
private final class MutableDomainCacheDateProvider: @unchecked Sendable {
var current: Date
init(_ current: Date) {
self.current = current
}
func now() -> Date {
current
}
}
private actor InMemoryDomainSnapshotStore: DomainSnapshotStoring {
private var snapshots: [String: Data] = [:]
private let encoder: JSONEncoder = JSONEncoder()
private let decoder: JSONDecoder = JSONDecoder()
private(set) var cleanedNamespaces: [String] = []
private(set) var globalCleanupDates: [Date] = []
init() {
encoder.dateEncodingStrategy = .iso8601
decoder.dateDecodingStrategy = .iso8601
}
func loadSnapshot<Snapshot: DomainCacheSnapshot>(
_ type: Snapshot.Type,
key: DomainCacheKey,
policy: DomainCachePolicy
) async throws -> DomainCacheEnvelope<Snapshot>? {
guard let data: Data = snapshots[key.fileName] else { return nil }
return try decoder.decode(DomainCacheEnvelope<Snapshot>.self, from: data)
}
func saveSnapshot<Snapshot: DomainCacheSnapshot>(
_ snapshot: Snapshot,
key: DomainCacheKey,
policy: DomainCachePolicy
) async throws {
snapshots[key.fileName] = try encoder.encode(DomainCacheEnvelope(snapshot: snapshot))
}
func removeSnapshots(namespace: String, policy: DomainCachePolicy) async throws {
let prefix: String = DomainCacheKey(namespace: namespace, components: []).namespaceFilePrefix
snapshots = snapshots.filter { !$0.key.hasPrefix(prefix) }
}
func cleanupSnapshots(namespace: String, policy: DomainCachePolicy, now: Date) async throws {
cleanedNamespaces.append(namespace)
}
func cleanupSnapshots(policy: DomainCachePolicy, now: Date) async throws {
globalCleanupDates.append(now)
}
}