-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PostRepositoryTests.swift
422 lines (349 loc) · 17.5 KB
/
PostRepositoryTests.swift
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
import XCTest
@testable import WordPress
class PostRepositoryTests: CoreDataTestCase {
private var remoteMock: PostServiceRESTMock!
private var repository: PostRepository!
private var blogID: TaggedManagedObjectID<Blog>!
override func setUpWithError() throws {
try super.setUpWithError()
let accountService = AccountService(coreDataStack: contextManager)
let accountID = accountService.createOrUpdateAccount(withUsername: "username", authToken: "token")
try accountService.setDefaultWordPressComAccount(XCTUnwrap(mainContext.existingObject(with: accountID) as? WPAccount))
let blog = try BlogBuilder(mainContext).withAccount(id: accountID).build()
contextManager.saveContextAndWait(mainContext)
blogID = .init(blog)
remoteMock = PostServiceRESTMock()
let remoteFactory = PostServiceRemoteFactoryMock()
remoteFactory.remoteToReturn = remoteMock
repository = PostRepository(coreDataStack: contextManager, remoteFactory: remoteFactory)
}
func testGetPost() async throws {
let post = RemotePost(siteID: 1, status: "publish", title: "Post: Test", content: "This is a test post")
post?.type = "post"
remoteMock.remotePostToReturnOnGetPostWithID = post
let postID = try await repository.getPost(withID: 1, from: blogID)
let isPage = try await contextManager.performQuery { try $0.existingObject(with: postID) is Page }
let title = try await contextManager.performQuery { try $0.existingObject(with: postID).postTitle }
let content = try await contextManager.performQuery { try $0.existingObject(with: postID).content }
XCTAssertFalse(isPage)
XCTAssertEqual(title, "Post: Test")
XCTAssertEqual(content, "This is a test post")
}
func testGetPage() async throws {
let post = RemotePost(siteID: 1, status: "publish", title: "Post: Test", content: "This is a test post")
post?.type = "page"
remoteMock.remotePostToReturnOnGetPostWithID = post
let postID = try await repository.getPost(withID: 1, from: blogID)
let isPage = try await contextManager.performQuery { try $0.existingObject(with: postID) is Page }
let title = try await contextManager.performQuery { try $0.existingObject(with: postID).postTitle }
let content = try await contextManager.performQuery { try $0.existingObject(with: postID).content }
XCTAssertTrue(isPage)
XCTAssertEqual(title, "Post: Test")
XCTAssertEqual(content, "This is a test post")
}
func testDeletePost() async throws {
let postID = try await contextManager.performAndSave { context in
let post = PostBuilder(context).with(status: .trash).withRemote().with(title: "Post: Test").build()
return TaggedManagedObjectID(post)
}
remoteMock.deletePostResult = .success(())
try await repository.delete(postID)
let isPostDeleted = await contextManager.performQuery { context in
(try? context.existingObject(with: postID)) == nil
}
XCTAssertTrue(isPostDeleted)
}
func testDeletePostWithRemoteFailure() async throws {
let postID = try await contextManager.performAndSave { context in
let post = PostBuilder(context).with(status: .trash).withRemote().with(title: "Post: Test").build()
return TaggedManagedObjectID(post)
}
remoteMock.deletePostResult = .failure(NSError.testInstance())
do {
try await repository.delete(postID)
XCTFail("The deletion should fail because of an API failure")
} catch {
// Do nothing
}
let isPostDeleted = await contextManager.performQuery { context in
(try? context.existingObject(with: postID)) == nil
}
XCTAssertTrue(isPostDeleted)
}
func testDeleteHistory() async throws {
let (firstRevision, secondRevision) = try await contextManager.performAndSave { context in
let first = PostBuilder(context).with(status: .trash).withRemote().with(title: "Post: Test").build()
let second = first.createRevision()
second.postTitle = "Edited"
return (TaggedManagedObjectID(first), TaggedManagedObjectID(second))
}
remoteMock.deletePostResult = .success(())
try await repository.delete(firstRevision)
let isPostDeleted = await contextManager.performQuery { context in
(try? context.existingObject(with: firstRevision)) == nil
&& (try? context.existingObject(with: secondRevision)) == nil
}
XCTAssertTrue(isPostDeleted)
}
func testDeleteLatest() async throws {
let (firstRevision, secondRevision) = try await contextManager.performAndSave { context in
let first = PostBuilder(context).with(status: .trash).withRemote().with(title: "Post: Test").build()
let second = first.createRevision()
second.postTitle = "Edited"
return (TaggedManagedObjectID(first), TaggedManagedObjectID(second))
}
remoteMock.deletePostResult = .success(())
try await repository.delete(secondRevision)
let isPostDeleted = await contextManager.performQuery { context in
(try? context.existingObject(with: firstRevision)) == nil
&& (try? context.existingObject(with: secondRevision)) == nil
}
XCTAssertTrue(isPostDeleted)
}
func testTrashPost() async throws {
let postID = try await contextManager.performAndSave { context in
let post = PostBuilder(context).withRemote().with(title: "Post: Test").build()
return TaggedManagedObjectID(post)
}
// No API call should be made, because the post is a local post
let remotePost = RemotePost(siteID: 1, status: "trash", title: "Post: Test", content: "New content")!
remotePost.type = "post"
remoteMock.trashPostResult = .success(remotePost)
try await repository.trash(postID)
let content = try await contextManager.performQuery { context in
(try context.existingObject(with: postID)).content
}
XCTAssertEqual(content, "New content")
}
func testTrashLocalPost() async throws {
let postID = try await contextManager.performAndSave { context in
let post = PostBuilder(context).with(title: "Post: Test").build()
return TaggedManagedObjectID(post)
}
// No API call should be made, because the post is a local post
remoteMock.trashPostResult = .failure(NSError.testInstance())
try await repository.trash(postID)
let status = try await contextManager.performQuery { context in
(try context.existingObject(with: postID)).status
}
XCTAssertEqual(status, .trash)
}
func testTrashTrashedPost() async throws {
let postID = try await contextManager.performAndSave { context in
let post = PostBuilder(context).with(status: .trash).with(title: "Post: Test").build()
return TaggedManagedObjectID(post)
}
// No API call should be made, because the post is a local post
remoteMock.trashPostResult = .failure(NSError.testInstance())
remoteMock.deletePostResult = .failure(NSError.testInstance())
try await repository.trash(postID)
let isPostDeleted = await contextManager.performQuery { context in
(try? context.existingObject(with: postID)) == nil
}
XCTAssertTrue(isPostDeleted)
}
func testTrashingAPostWillUpdateItsRevisionStatusAfterSyncProperty() async throws {
// Arrange
let (postID, revisionID) = try await contextManager.performAndSave { context in
let post = PostBuilder(context).with(statusAfterSync: .publish).withRemote().build()
let revision = post.createRevision()
return (TaggedManagedObjectID(post), TaggedManagedObjectID(revision))
}
let remotePost = RemotePost(siteID: 1, status: "trash", title: "Post: Test", content: "New content")!
remotePost.type = "post"
remoteMock.trashPostResult = .success(remotePost)
// Act
try await repository.trash(postID)
// Assert
let postStatusAfterSync = try await contextManager.performQuery { try $0.existingObject(with: postID).statusAfterSync }
let postStatus = try await contextManager.performQuery { try $0.existingObject(with: postID).status }
let revisionStatusAfterSync = try await contextManager.performQuery { try $0.existingObject(with: revisionID).statusAfterSync }
let revisionStatus = try await contextManager.performQuery { try $0.existingObject(with: revisionID).status }
XCTAssertEqual(postStatusAfterSync, .trash)
XCTAssertEqual(postStatus, .trash)
XCTAssertEqual(revisionStatusAfterSync, .trash)
XCTAssertEqual(revisionStatus, .trash)
}
func testRestorePost() async throws {
let postID = try await contextManager.performAndSave { context in
let post = PostBuilder(context).withRemote().with(status: .trash).with(title: "Post: Test").build()
return TaggedManagedObjectID(post)
}
let remotePost = RemotePost(siteID: 1, status: "draft", title: "Post: Test", content: "New content")!
remotePost.type = "post"
remoteMock.restorePostResult = .success(remotePost)
try await repository.restore(postID, to: .publish)
// The restored post should match the post returned by WordPress API.
let (status, content) = try await contextManager.performQuery { context in
let post = try context.existingObject(with: postID)
return (post.status, post.content)
}
XCTAssertEqual(status, .draft)
XCTAssertEqual(content, "New content")
}
func testRestorePostFailure() async throws {
let postID = try await contextManager.performAndSave { context in
let post = PostBuilder(context).withRemote().with(status: .trash).with(title: "Post: Test").build()
return TaggedManagedObjectID(post)
}
remoteMock.restorePostResult = .failure(NSError.testInstance())
do {
try await repository.restore(postID, to: .publish)
XCTFail("The restore call should throw an error")
} catch {
let status = try await contextManager.performQuery { context in
let post = try context.existingObject(with: postID)
return post.status
}
XCTAssertEqual(status, .trash)
}
}
func testFetchAllPagesStopsOnEmptyAPIResponse() async throws {
// Given two pages of API result: first page returns 100 page instances, and the second page returns an empty result.
remoteMock.remotePostsToReturnOnSyncPostsOfType = [
try (1...100).map {
let post = try XCTUnwrap(RemotePost(siteID: NSNumber(value: $0), status: "publish", title: "Post: Test", content: "This is a test post"))
post.type = "page"
return post
},
[]
]
let pages = try await repository.fetchAllPages(statuses: [.publish], in: blogID).value
XCTAssertEqual(pages.count, 100)
}
func testFetchAllPagesStopsOnNonFullPageAPIResponse() async throws {
// Given two pages of API result: first page returns 100 page instances, and the second page returns 10 (any amount that's less than 100) page instances.
remoteMock.remotePostsToReturnOnSyncPostsOfType = [
try (1...100).map {
let post = try XCTUnwrap(RemotePost(siteID: NSNumber(value: $0), status: "publish", title: "Post: Test", content: "This is a test post"))
post.type = "page"
return post
},
try (1...10).map {
let post = try XCTUnwrap(RemotePost(siteID: NSNumber(value: $0), status: "publish", title: "Post: Test", content: "This is a test post"))
post.type = "page"
return post
},
]
let pages = try await repository.fetchAllPages(statuses: [.publish], in: blogID).value
XCTAssertEqual(pages.count, 110)
}
func testCancelFetchAllPages() async throws {
remoteMock.remotePostsToReturnOnSyncPostsOfType = try (1...10).map { pageNo in
try (1...100).map {
let post = try XCTUnwrap(RemotePost(siteID: NSNumber(value: pageNo * 100 + $0), status: "publish", title: "Post: Test", content: "This is a test post"))
post.type = "page"
return post
}
}
let cancelled = expectation(description: "Fetching task returns cancellation error")
let task = repository.fetchAllPages(statuses: [.publish], in: blogID)
DispatchQueue.global().asyncAfter(deadline: .now() + .microseconds(100)) {
task.cancel()
}
do {
let _ = try await task.value
} catch is CancellationError {
cancelled.fulfill()
}
await fulfillment(of: [cancelled], timeout: 0.3)
}
}
// These mock classes are copied from PostServiceWPComTests. We can't simply remove the `private` in the original class
// definition, because Xcode would complian about 'WordPress' module not found.
private class PostServiceRemoteFactoryMock: PostServiceRemoteFactory {
var remoteToReturn: PostServiceRemote?
override func forBlog(_ blog: Blog) -> PostServiceRemote? {
return remoteToReturn
}
override func restRemoteFor(siteID: NSNumber, context: NSManagedObjectContext) -> PostServiceRemoteREST? {
return remoteToReturn as? PostServiceRemoteREST
}
}
private class PostServiceRESTMock: PostServiceRemoteREST {
enum StubbedBehavior {
case success(RemotePost?)
case fail
}
var remotePostToReturnOnGetPostWithID: RemotePost?
var remotePostsToReturnOnSyncPostsOfType = [[RemotePost]]() // Each element contains an array of RemotePost for one API request.
var remotePostToReturnOnUpdatePost: RemotePost?
var remotePostToReturnOnCreatePost: RemotePost?
var autoSaveStubbedBehavior = StubbedBehavior.success(nil)
// related to fetching likes
var fetchLikesShouldSucceed: Bool = true
var remoteUsersToReturnOnGetLikes = [RemoteLikeUser]()
var totalLikes: NSNumber = 1
var deletePostResult: Result<Void, Error> = .success(())
var trashPostResult: Result<RemotePost, Error> = .failure(NSError.testInstance())
var restorePostResult: Result<RemotePost, Error> = .failure(NSError.testInstance())
private(set) var invocationsCountOfCreatePost = 0
private(set) var invocationsCountOfAutoSave = 0
private(set) var invocationsCountOfUpdate = 0
override func getPostWithID(_ postID: NSNumber!, success: ((RemotePost?) -> Void)!, failure: ((Error?) -> Void)!) {
success(self.remotePostToReturnOnGetPostWithID)
}
override func getPostsOfType(_ postType: String!, options: [AnyHashable: Any]! = [:], success: (([RemotePost]?) -> Void)!, failure: ((Error?) -> Void)!) {
guard !remotePostsToReturnOnSyncPostsOfType.isEmpty else {
failure(testError())
return
}
let result = remotePostsToReturnOnSyncPostsOfType.removeFirst()
DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(50)) {
success(result)
}
}
override func update(_ post: RemotePost!, success: ((RemotePost?) -> Void)!, failure: ((Error?) -> Void)!) {
self.invocationsCountOfUpdate += 1
success(self.remotePostToReturnOnUpdatePost)
}
override func createPost(_ post: RemotePost!, success: ((RemotePost?) -> Void)!, failure: ((Error?) -> Void)!) {
self.invocationsCountOfCreatePost += 1
success(self.remotePostToReturnOnCreatePost)
}
override func trashPost(_ post: RemotePost!, success: ((RemotePost?) -> Void)!, failure: ((Error?) -> Void)!) {
switch self.trashPostResult {
case let .failure(error):
failure(error)
case let .success(remotePost):
success(remotePost)
}
}
override func restore(_ post: RemotePost!, success: ((RemotePost?) -> Void)!, failure: ((Error?) -> Void)!) {
switch self.restorePostResult {
case let .failure(error):
failure(error)
case let .success(remotePost):
success(remotePost)
}
}
override func autoSave(_ post: RemotePost, success: ((RemotePost?, String?) -> Void)!, failure: ((Error?) -> Void)!) {
self.invocationsCountOfAutoSave += 1
switch self.autoSaveStubbedBehavior {
case .fail:
failure(nil)
case .success(let remotePost):
success(remotePost, nil)
}
}
override func getLikesForPostID(_ postID: NSNumber,
count: NSNumber,
before: String?,
excludeUserIDs: [NSNumber]?,
success: (([RemoteLikeUser], NSNumber) -> Void)!,
failure: ((Error?) -> Void)!) {
if self.fetchLikesShouldSucceed {
success(self.remoteUsersToReturnOnGetLikes, self.totalLikes)
} else {
failure(nil)
}
}
override func delete(_ post: RemotePost!, success: (() -> Void)!, failure: ((Error?) -> Void)!) {
switch deletePostResult {
case let .failure(error):
failure(error)
case .success:
success()
}
}
}