-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathContextManagerTests.swift
More file actions
368 lines (309 loc) · 15.8 KB
/
Copy pathContextManagerTests.swift
File metadata and controls
368 lines (309 loc) · 15.8 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
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
import CoreData
import XCTest
@testable import WordPressData
class ContextManagerTests: XCTestCase {
let storeURL = URL.Helpers.temporaryFile(named: "ContextManagerTests.sqlite")
override func setUpWithError() throws {
if FileManager.default.fileExists(atPath: storeURL.path) {
try FileManager.default.removeItem(at: storeURL)
}
}
func testIterativeMigration130ToLatest() throws {
var objectID: NSManagedObjectID? = .none
// At the time of writing we are at app version 19.9 and model version 140.
// At app version 19.0 we were at model version 137.
// Iterating back 10 version is more than plenty to cover a real world scenario.
try prepareForMigration(withModelName: "WordPress 130") { context in
// Add an object to the DB from a model that looks different between the intial and the
// latest scheme version, so that we fully exercise the migration.
let originalObject = NSEntityDescription.insertNewObject(
forEntityName: Comment.entityName(),
into: context
)
try context.obtainPermanentIDs(for: [originalObject])
try context.save()
XCTAssertFalse(originalObject.objectID.isTemporaryID, "Should be a permanent object")
objectID = originalObject.objectID
}
// Migrate to the latest version
let contextManager = ContextManager(modelName: ContextManagerModelNameCurrent, store: storeURL)
let object = try contextManager.mainContext.existingObject(with: XCTUnwrap(objectID))
XCTAssertNotNil(object, "Object should exist in new PSC")
XCTAssertNoThrow(
object.value(forKey: "authorID"),
"Blog.organizationID exists in latest model version, but we were unable to fetch it"
)
}
func testSaveDerivedContextWithChangesInMainContext() throws {
let contextManager = ContextManager.forTesting()
let derivedContext = contextManager.newDerivedContext()
derivedContext.perform {
_ = WPAccount.fixture(context: derivedContext, userID: 1, username: "First User")
contextManager.saveContextAndWait(derivedContext)
}
let findFirstUser: () throws -> WPAccount? = {
let firstUserQuery = NSFetchRequest<WPAccount>(entityName: "Account")
firstUserQuery.predicate = NSPredicate(format: "userID = 1")
return try contextManager.mainContext.fetch(firstUserQuery).first
}
let firstUserSaved = expectation(for: NSPredicate { _, _ in
(try? findFirstUser()?.username) == "First User"
}, evaluatedWith: nil)
wait(for: [firstUserSaved], timeout: 5)
// Change first user's user name
try findFirstUser()?.mockKeychain()
try findFirstUser()?.username = "First User (Updated)"
// Save another user
let secondUserSaved = expectation(description: "Second user saved")
derivedContext.perform {
_ = WPAccount.fixture(context: derivedContext, userID: 2)
contextManager.saveContextAndWait(derivedContext)
secondUserSaved.fulfill()
}
wait(for: [secondUserSaved], timeout: 1)
// Discard the username change that's made above
contextManager.mainContext.reset()
XCTAssertEqual(try findFirstUser()?.username, "First User")
}
func testSaveUsingBlock() async throws {
let contextManager = ContextManager.forTesting()
let numberOfAccounts: () -> Int = {
contextManager.mainContext.countObjects(ofType: WPAccount.self)
}
XCTAssertEqual(numberOfAccounts(), 0)
try await contextManager.performAndSave { context in
_ = WPAccount.fixture(context: context, userID: 1)
}
XCTAssertEqual(numberOfAccounts(), 1)
let expectedError = NSError.testInstance()
do {
try await contextManager.performAndSave { context in
_ = WPAccount.fixture(context: context, userID: 100)
throw expectedError
}
XCTFail("The above call should throw")
} catch {
XCTAssertEqual(error as NSError, expectedError)
}
XCTAssertEqual(numberOfAccounts(), 1)
// In the translated Swift API of `ContextManager`, there are two `save(_: (NSManagedContext) -> Void)`
// functions. The only difference between them is, one is async function, the other is not.
// When compiling statement `try save { context in doSomething(context) }`, Swift picks which overload to use
// based on the context—there is no syntax or keyword to explicitly pick one ourselves.
//
// From: https://github.com/apple/swift-evolution/blob/main/proposals/0296-async-await.md#overloading-and-overload-resolution
// > "In non-async functions, and closures without any await expression, the compiler selects the non-async overload"
let sync: () -> Void = {
contextManager.performAndSave { context in
_ = WPAccount.fixture(context: context, userID: 2)
}
}
sync()
XCTAssertEqual(numberOfAccounts(), 2)
}
func testSaveUsingBlockWithNestedCalls() {
let contextManager = ContextManager.forTesting()
let accounts: () -> Set<String> = {
let all = (try? contextManager.mainContext.fetch(NSFetchRequest<WPAccount>(entityName: "Account"))) ?? []
return Set(all.map { $0.username })
}
XCTAssertTrue(accounts().isEmpty)
let saveOperations = [
self.expectation(description: "First User is saved"),
self.expectation(description: "Second User is saved"),
]
contextManager.performAndSave({
_ = WPAccount.fixture(context: $0, userID: 1, username: "First User")
contextManager.performAndSave {
_ = WPAccount.fixture(context: $0, userID: 2, username: "Second User")
}
saveOperations[1].fulfill()
XCTAssertEqual(accounts(), ["Second User"])
}, completion: {
saveOperations[0].fulfill()
}, on: .main)
wait(for: saveOperations, timeout: 0.1)
XCTAssertEqual(accounts(), ["First User", "Second User"])
}
func testSaveUsingBlockWithNestedCallsUsingAsyncAPI() {
let contextManager = ContextManager.forTesting()
let accounts: () -> Set<String> = {
let all = (try? contextManager.mainContext.fetch(NSFetchRequest<WPAccount>(entityName: "Account"))) ?? []
return Set(all.map { $0.username })
}
XCTAssertTrue(accounts().isEmpty)
let saveOperations = [
self.expectation(description: "First User is saved"),
self.expectation(description: "Second User is saved"),
]
contextManager.performAndSave({
_ = WPAccount.fixture(context: $0, userID: 1, username: "First User")
contextManager.performAndSave({
_ = WPAccount.fixture(context: $0, userID: 2, username: "Second User")
}, completion: {
saveOperations[1].fulfill()
}, on: .main)
}, completion: {
saveOperations[0].fulfill()
}, on: .main)
wait(for: saveOperations, timeout: 1)
XCTAssertEqual(accounts(), ["First User", "Second User"])
}
func testConcurrencyAsyncAPI() throws {
let contextManager = ContextManager.forTesting()
let iterations = 50
let username = "AsyncAPI"
var allCompleted: [XCTestExpectation] = []
for iter in 1...iterations {
let expectation = self.expectation(description: "Sync API test iteration \(iter) completed")
allCompleted.append(expectation)
contextManager.performAndSave({ context in
do {
try self.createOrUpdateAccount(username: username, newToken: "new-token", in: context)
} catch {
XCTFail("Failed to create/update the account: \(error)")
}
}, completion: { expectation.fulfill() }, on: .main)
}
wait(for: allCompleted, timeout: 1)
let request = WPAccount.fetchRequest()
request.predicate = NSPredicate(format: "username = %@", username)
try XCTAssertEqual(contextManager.mainContext.count(for: request), 1)
}
func testConcurrencyAsyncThrowingAPI() throws {
let contextManager = ContextManager.forTesting()
let iterations = 50
let username = "AsyncAPI"
var allCompleted: [XCTestExpectation] = []
for iter in 1...iterations {
let expectation = self.expectation(description: "Sync API test iteration \(iter) completed")
allCompleted.append(expectation)
contextManager.performAndSave({ context in
try self.createOrUpdateAccount(username: username, newToken: "new-token", in: context)
}, completion: { _ in expectation.fulfill() }, on: .main)
}
wait(for: allCompleted, timeout: 1)
let request = WPAccount.fetchRequest()
request.predicate = NSPredicate(format: "username = %@", username)
try XCTAssertEqual(contextManager.mainContext.count(for: request), 1)
}
func testConcurrencySyncAPI() throws {
let contextManager = ContextManager.forTesting()
let iterations = 50
let username = "SyncAPI"
var allCompleted: [XCTestExpectation] = []
for iter in 1...iterations {
let expectation = self.expectation(description: "Sync API test iteration \(iter) completed")
allCompleted.append(expectation)
DispatchQueue.global().async {
contextManager.performAndSave { context in
do {
try self.createOrUpdateAccount(username: username, newToken: "new-token", in: context)
} catch {
XCTFail("Failed to create/update the account: \(error)")
}
}
expectation.fulfill()
}
}
wait(for: allCompleted, timeout: 3)
let request = WPAccount.fetchRequest()
request.predicate = NSPredicate(format: "username = %@", username)
try XCTAssertNotEqual(contextManager.mainContext.count(for: request), 1, "See the comment in `ContextManager.writerQueue` for details")
}
/// This test case documents a pitfall in `ContextManager.performAndSave(_:)`, where the
/// saved changes aren't immediately accessible on the objects in the main context. This
/// issue doesn't present in `performAndSave(_:completion:on:)`.
func testUpdateUsingSyncAPI() throws {
// First, insert an account into the database.
let contextManager = ContextManager.forTesting()
contextManager.performAndSave { context in
_ = WPAccount.fixture(context: context, userID: 1, username: "First User")
}
// Fetch the account in the main context
let account = try WPAccount.lookup(withUserID: 1, in: contextManager.mainContext)
XCTAssertEqual(account?.username, "First User")
// Update the account in a background context using the `performAndSave` API, which saves the changes synchronously.
var theBackgroundContext: NSManagedObjectContext? = nil
contextManager.performAndSave { context in
theBackgroundContext = context
guard let objectID = account?.objectID, let accountInContext = try? context.existingObject(with: objectID) as? WPAccount else {
XCTFail("Can't find the account")
return
}
accountInContext.mockKeychain()
accountInContext.username = "Updated"
XCTAssertEqual(theBackgroundContext?.hasChanges, true)
}
XCTAssertEqual(theBackgroundContext?.hasChanges, false, "The background context should be saved when `performAndSave` returns")
XCTAssertNotEqual(account?.username, "Updated", "The account object in the main context doesn't get the updated value immediately")
// But eventually (probably in next run loop), it will get the updated value.
let updated = expectation(for: NSPredicate { _, _ in
account?.username == "Updated"
}, evaluatedWith: nil)
wait(for: [updated], timeout: 5)
// The above issue doesn't present in the async version of `performAndSave` API
contextManager.performAndSave({ context in
guard let objectID = account?.objectID, let accountInContext = try? context.existingObject(with: objectID) as? WPAccount else {
XCTFail("Can't find the account")
return
}
accountInContext.mockKeychain()
accountInContext.username = "Updated Again"
}, completion: {
XCTAssertEqual(account?.username, "Updated Again", "The account object in the main context gets the updated value when the completion block is called")
}, on: .main)
}
private func newAccountInContext(context: NSManagedObjectContext) -> WPAccount {
let account = NSEntityDescription.insertNewObject(forEntityName: WPAccount.entityName(), into: context) as! WPAccount
account.username = "username"
account.setValue(true, forKey: "isWpcom")
account.authToken = "authtoken"
account.setValue("http://example.com/xmlrpc.php", forKey: "xmlrpc")
return account
}
private func newBlogInAccount(account: WPAccount) -> Blog {
let blog = NSEntityDescription.insertNewObject(forEntityName: Blog.entityName(), into: account.managedObjectContext!) as! Blog
blog.xmlrpc = "http://test.blog/xmlrpc.php"
blog.url = "http://test.blog/"
blog.account = account
return blog
}
private func createOrUpdateAccount(username: String, newToken: String, in context: NSManagedObjectContext) throws {
var account = try WPAccount.lookup(withUsername: username, in: context)
if account == nil {
// Will this make tests fail because of the default userID in the fixture?
account = WPAccount.fixture(context: context, username: username)
}
account?.mockKeychain()
account?.authToken = newToken
}
/// Insert data into `storeURL` using the context object provided by this function.
///
/// This function ensures created Core Data stack is cleaned up properly, so that the database file
/// is ready to be used by `ContextManager` to perform migration.
private func prepareForMigration(withModelName modelName: String, block: (NSManagedObjectContext) throws -> Void) throws {
let model = try XCTUnwrap(NSManagedObjectModel(contentsOf: XCTUnwrap(urlForModelName(modelName)))).neutralizingEntityClasses()
let container = NSPersistentContainer(name: "WordPress", managedObjectModel: model)
let storeDesc = NSPersistentStoreDescription(url: storeURL)
storeDesc.type = NSSQLiteStoreType
container.persistentStoreDescriptions = [storeDesc]
container.loadPersistentStores { _, error in
XCTAssertNil(error)
}
try block(container.viewContext)
let store = try XCTUnwrap(container.persistentStoreCoordinator.persistentStores.first)
try container.persistentStoreCoordinator.remove(store)
}
fileprivate func urlForModelName(_ name: String) -> URL? {
let bundle = Bundle.wordPressData
var url = bundle.url(forResource: name, withExtension: "mom")
if url == nil {
let momdPaths = bundle.urls(forResourcesWithExtension: "momd", subdirectory: nil)!
for momdPath in momdPaths {
url = bundle.url(forResource: name, withExtension: "mom", subdirectory: momdPath.lastPathComponent)
}
}
return url
}
}