-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathBlogDashboardServiceTests.swift
337 lines (254 loc) · 11.9 KB
/
BlogDashboardServiceTests.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
import XCTest
import Nimble
@testable import WordPress
/// This test stuite is clashing with other tests
/// Specifically:
/// - [BlogJetpackTest testJetpackSetupDoesntReplaceDotcomAccount]
/// - CommentServiceTests.testFailingFetchCommentLikesShouldCallFailureBlock()
///
/// We weren't able to figure out why but it seems a race condition + Core data
/// For now, renaming the suite to change the execution order solves the issue.
class ZBlogDashboardServiceTests: XCTestCase {
private var contextManager: TestContextManager!
private var context: NSManagedObjectContext!
private var service: BlogDashboardService!
private var remoteServiceMock: DashboardServiceRemoteMock!
private var persistenceMock: BlogDashboardPersistenceMock!
private var postsParserMock: BlogDashboardPostsParserMock!
private let wpComID = 123456
override func setUp() {
super.setUp()
remoteServiceMock = DashboardServiceRemoteMock()
persistenceMock = BlogDashboardPersistenceMock()
contextManager = TestContextManager()
context = contextManager.newDerivedContext()
postsParserMock = BlogDashboardPostsParserMock(managedObjectContext: context)
service = BlogDashboardService(managedObjectContext: context, remoteService: remoteServiceMock, persistence: persistenceMock, postsParser: postsParserMock)
}
override func tearDown() {
super.tearDown()
context = nil
contextManager = nil
}
func testCallServiceWithCorrectIDAndCards() {
let expect = expectation(description: "Request the correct ID")
let blog = newTestBlog(id: wpComID, context: context)
service.fetch(blog: blog) { _ in
XCTAssertEqual(self.remoteServiceMock.didCallWithBlogID, self.wpComID)
XCTAssertEqual(self.remoteServiceMock.didRequestCards, ["todays_stats", "posts"])
expect.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testCreateSectionForPosts() {
let expect = expectation(description: "Parse drafts and scheduled")
remoteServiceMock.respondWith = .withDraftAndSchedulePosts
let blog = newTestBlog(id: wpComID, context: context)
service.fetch(blog: blog) { cards in
let draftPostsCardItem = cards.first(where: {$0.cardType == .draftPosts})
let scheduledPostsCardItem = cards.first(where: {$0.cardType == .scheduledPosts})
// Posts section exists
XCTAssertNotNil(draftPostsCardItem)
XCTAssertNotNil(scheduledPostsCardItem)
// Has published is `true`
XCTAssertTrue(draftPostsCardItem!.apiResponse!.posts!.hasPublished!)
// 3 scheduled item
XCTAssertEqual(draftPostsCardItem!.apiResponse!.posts!.draft!.count, 3)
// 1 scheduled item
XCTAssertEqual(draftPostsCardItem!.apiResponse!.posts!.scheduled!.count, 1)
// Has published is `true`
XCTAssertTrue(scheduledPostsCardItem!.apiResponse!.posts!.hasPublished!)
// 3 scheduled item
XCTAssertEqual(scheduledPostsCardItem!.apiResponse!.posts!.draft!.count, 3)
// 1 scheduled item
XCTAssertEqual(scheduledPostsCardItem!.apiResponse!.posts!.scheduled!.count, 1)
expect.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testTodaysStats() {
let expect = expectation(description: "Parse todays stats")
remoteServiceMock.respondWith = .withDraftAndSchedulePosts
let blog = newTestBlog(id: wpComID, context: context)
service.fetch(blog: blog) { cards in
let todaysStatsItem = cards.first(where: {$0.cardType == .todaysStats})
// Todays stats section exists
XCTAssertNotNil(todaysStatsItem)
// Entity has the correct values
XCTAssertEqual(todaysStatsItem!.apiResponse!.todaysStats!.views, 0)
XCTAssertEqual(todaysStatsItem!.apiResponse!.todaysStats!.visitors, 0)
XCTAssertEqual(todaysStatsItem!.apiResponse!.todaysStats!.likes, 0)
XCTAssertEqual(todaysStatsItem!.apiResponse!.todaysStats!.comments, 0)
expect.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testPersistCardsResponse() {
let expect = expectation(description: "Parse todays stats")
remoteServiceMock.respondWith = .withDraftAndSchedulePosts
let blog = newTestBlog(id: wpComID, context: context)
service.fetch(blog: blog) { snapshot in
XCTAssertEqual(self.persistenceMock.didCallPersistWithCards,
self.dictionary(from: "dashboard-200-with-drafts-and-scheduled.json"))
XCTAssertEqual(self.persistenceMock.didCallPersistWithWpComID, self.wpComID)
expect.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testFetchCardsFromPersistence() {
persistenceMock.respondWith = dictionary(from: "dashboard-200-with-drafts-and-scheduled.json")!
let blog = newTestBlog(id: wpComID, context: context)
let cards = service.fetchLocal(blog: blog)
let hasDrafts = cards.contains(where: {$0.cardType == .draftPosts})
let hasScheduled = cards.contains(where: {$0.cardType == .scheduledPosts})
XCTAssertTrue(hasDrafts)
XCTAssertTrue(hasScheduled)
XCTAssertEqual(persistenceMock.didCallGetCardsWithWpComID, wpComID)
}
// MARK: - Ghost cards
/// Ghost cards shouldn't be displayed when parsing the API response
///
func testDontReturnGhostCardsWhenFetchingFromTheAPI() {
let expect = expectation(description: "Parse drafts and scheduled")
remoteServiceMock.respondWith = .withDraftAndSchedulePosts
let blog = newTestBlog(id: 10, context: context)
service.fetch(blog: blog) { cards in
let hasGhost = cards.contains(where: {$0.cardType == .ghost})
XCTAssertFalse(hasGhost)
expect.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
/// Ghost cards shouldn't be displayed when parsing the cached data
///
func testDontReturnGhostCardsWhenFetchingFromCachedData() {
persistenceMock.respondWith = dictionary(from: "dashboard-200-with-drafts-and-scheduled.json")!
let blog = newTestBlog(id: 11, context: context)
let cards = service.fetchLocal(blog: blog)
let hasGhost = cards.contains(where: {$0.cardType == .ghost})
XCTAssertFalse(hasGhost)
}
/// Ghost cards SHOULD be displayed when there are no cached data
/// and the response didn't came from the API.
///
func testReturnGhostCardsWhenNoCachedData() {
persistenceMock.respondWith = nil
let blog = newTestBlog(id: 12, context: context)
let cards = service.fetchLocal(blog: blog)
let ghostCards = cards.filter({$0.cardType == .ghost})
XCTAssertEqual(ghostCards.count, 1)
}
// MARK: - Error card
/// If the first time load fails, show a failure card
///
func testShowErrorCardWhenFailingToLoad() {
let expect = expectation(description: "Show error card")
remoteServiceMock.respondWith = .error
persistenceMock.respondWith = nil
let blog = newTestBlog(id: 13, context: context)
service.fetch(blog: blog) { _ in } failure: { cards in
let hasError = cards.contains(where: {$0.cardType == .failure})
XCTAssertTrue(hasError)
expect.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
/// If the first time load fails, but a subsequent try
/// succeeds, don't show the failure card
///
func testNotShowErrorCardAfterFailureButThenSuccess() {
let expect = expectation(description: "Show error card")
remoteServiceMock.respondWith = .error
persistenceMock.respondWith = nil
let blog = newTestBlog(id: 14, context: context)
/// Call it once and fails
service.fetch(blog: blog) { _ in } failure: { cards in
self.remoteServiceMock.respondWith = .withDraftAndSchedulePosts
/// Call again and succeeds
self.service.fetch(blog: blog) { cards in
let hasError = cards.contains(where: {$0.cardType == .failure})
XCTAssertFalse(hasError)
expect.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
// MARK: - Local post content
/// We might run into the case where the API returns that
/// there are no posts, but the user has local content.
/// In this case the response is changed to take into account
/// local content.
func testReturnPostsCorrectlyBasedOnLocalContent() {
let expect = expectation(description: "Return local posts")
remoteServiceMock.respondWith = .withoutPosts
postsParserMock.hasDraftsAndScheduled = true
let blog = newTestBlog(id: wpComID, context: context)
service.fetch(blog: blog) { cards in
let hasDrafts = cards.contains(where: {$0.cardType == .draftPosts})
let hasScheduled = cards.contains(where: {$0.cardType == .scheduledPosts})
XCTAssertTrue(hasDrafts)
XCTAssertTrue(hasScheduled)
expect.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func dictionary(from file: String) -> NSDictionary? {
let fileURL: URL = Bundle(for: ZBlogDashboardServiceTests.self).url(forResource: file, withExtension: nil)!
let data: Data = try! Data(contentsOf: fileURL)
return try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
}
private func newTestBlog(id: Int, context: NSManagedObjectContext) -> Blog {
let blog = ModelTestHelper.insertDotComBlog(context: context)
blog.dotComID = id as NSNumber
return blog
}
}
// MARK: - Mocks
class DashboardServiceRemoteMock: DashboardServiceRemote {
enum Response: String {
case withDraftAndSchedulePosts = "dashboard-200-with-drafts-and-scheduled.json"
case withDraftsOnly = "dashboard-200-with-drafts-only.json"
case withoutPosts = "dashboard-200-without-posts.json"
case error = "error"
}
enum Errors: Error {
case unknown
}
var respondWith: Response = .withDraftAndSchedulePosts
var didCallWithBlogID: Int?
var didRequestCards: [String]?
override func fetch(cards: [String], forBlogID blogID: Int, success: @escaping (NSDictionary) -> Void, failure: @escaping (Error) -> Void) {
didCallWithBlogID = blogID
didRequestCards = cards
if let fileURL: URL = Bundle(for: ZBlogDashboardServiceTests.self).url(forResource: respondWith.rawValue, withExtension: nil),
let data: Data = try? Data(contentsOf: fileURL),
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as AnyObject {
success(jsonObject as! NSDictionary)
} else {
failure(Errors.unknown)
}
}
}
class BlogDashboardPersistenceMock: BlogDashboardPersistence {
var didCallPersistWithCards: NSDictionary?
var didCallPersistWithWpComID: Int?
override func persist(cards: NSDictionary, for wpComID: Int) {
didCallPersistWithCards = cards
didCallPersistWithWpComID = wpComID
}
var didCallGetCardsWithWpComID: Int?
var respondWith: NSDictionary? = [:]
override func getCards(for wpComID: Int) -> NSDictionary? {
didCallGetCardsWithWpComID = wpComID
return respondWith
}
}
class BlogDashboardPostsParserMock: BlogDashboardPostsParser {
var hasDraftsAndScheduled = false
override func parse(_ postsDictionary: NSDictionary, for blog: Blog) -> NSDictionary {
guard hasDraftsAndScheduled else {
return postsDictionary
}
return ["has_published": false, "draft": [[:]], "scheduled": [[:]]]
}
}