-
Notifications
You must be signed in to change notification settings - Fork 35
/
ComplexSyncTests.swift
798 lines (707 loc) · 36.3 KB
/
ComplexSyncTests.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
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//
// NextSyncTests.swift
// ContentfulPersistence
//
// Created by JP Wright on 12.07.17.
// Copyright © 2017 Contentful GmbH. All rights reserved.
//
@testable import ContentfulPersistence
import Contentful
import XCTest
import Foundation
import CoreData
import OHHTTPStubs
import CoreLocation
class ComplexSyncTests: XCTestCase {
var syncManager: SynchronizationManager!
var client: Client!
lazy var store: CoreDataStore = {
return CoreDataStore(context: self.managedObjectContext)
}()
lazy var managedObjectContext: NSManagedObjectContext = {
return TestHelpers.managedObjectContext(forMOMInTestBundleNamed: "ComplexTest")
}()
// Before each test.
override func setUp() {
HTTPStubs.removeAllStubs()
let persistenceModel = PersistenceModel(spaceType: ComplexSyncInfo.self, assetType: ComplexAsset.self, entryTypes: [SingleRecord.self, Link.self, RecordWithNonOptionalRelation.self])
client = Client(spaceId: "smf0sqiu0c5s",
accessToken: "14d305ad526d4487e21a99b5b9313a8877ce6fbf540f02b12189eea61550ef34")
self.syncManager = SynchronizationManager(client: client,
localizationScheme: .default,
persistenceStore: self.store,
persistenceModel: persistenceModel)
}
// After each test.
override func tearDown() {
HTTPStubs.removeAllStubs()
}
func testUpdatingFieldValueBetweenSyncs() {
let expectation = self.expectation(description: "Initial sync succeeded")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let urlString = request.url!.absoluteString
let queryItems = URLComponents(string: urlString)!.queryItems!
for queryItem in queryItems {
if queryItem.name == "initial" {
let stubPath = OHPathForFile("simple-update-initial-sync.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
} else if queryItem.name == "sync_token" && queryItem.value == "wonDrcKnRgcSOF4-wrDCgcKefWzCgsOxwrfCq8KOfMOdXUPCvEnChwEEO8KFwqHDj8KIKHJYwr0Mw4wKw7UAVcOWYsOtw4nCvTUvDn0pw4gBRMKrGyVxIsOcQMKrwpfDhcOZwq3CkzDDvcKsJ8Oew58fJAQLwr3Cv2MGw4h6LcK_w4whQ8KMwr3ClMOhw5zDjMOswqAyw7XDpXDDsiXCvsKfw7JcwqjDucKmKMODwpDDlyvCrCnCjsOww43ClMKUwq8Xw75pXA" {
let stubPath = OHPathForFile("simple-update-initial-sync-page2.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}
}
let stubPath = OHPathForFile("simple-update-initial-sync.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
var syncSpace: SyncSpace!
client.sync() { result in
switch result {
case .success(let space):
syncSpace = space
self.managedObjectContext.perform {
do {
let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == 'aNt2d7YR4AIwEAMcG4OwI'"))
XCTAssertEqual(records.count, 1)
if let helloRecord = records.first {
XCTAssertFalse(helloRecord.hasChanges, "Record has not yet been saved")
XCTAssertEqual(helloRecord.textBody, "Hello")
}
} catch {
XCTAssert(false, "Fetching posts should not throw an error")
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
HTTPStubs.removeAllStubs()
// ============================NEXT SYNC==================================================
let nextExpectation = self.expectation(description: "Next sync expectation")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
return HTTPStubsResponse(
fileAtPath: OHPathForFile("simple-update-next-sync.json", type(of: self))!,
statusCode: 200,
headers: ["Content-Type": "application/json"]
)
}.name = "Next sync: updated value."
client.sync(for: syncSpace) { result in
switch result {
case .success:
self.managedObjectContext.perform {
do {
let helloSingleRecord: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == 'aNt2d7YR4AIwEAMcG4OwI'"))
XCTAssertEqual(helloSingleRecord.count, 1)
XCTAssertFalse(helloSingleRecord.first!.hasChanges, "Record has not yet been saved")
XCTAssertEqual(helloSingleRecord.first!.textBody, "Hello FooBar")
} catch {
XCTAssert(false, "Fetching posts should not throw an error")
}
nextExpectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
nextExpectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testClearingFieldSetsItToNil() {
let expectation = self.expectation(description: "Initial sync succeeded")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("clear-field-initial-sync.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
var syncSpace: SyncSpace!
client.sync() { result in
switch result {
case .success(let space):
syncSpace = space
self.managedObjectContext.perform {
do {
let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '5GiLOZvY7SiMeUIgIIAssS'"))
XCTAssertEqual(records.count, 1)
if let record = records.first {
XCTAssertFalse(record.hasChanges, "Record has not yet been saved")
XCTAssertEqual(record.textBody, "INITIAL TEXT BODY")
}
} catch {
XCTAssert(false, "Fetching posts should not throw an error")
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
HTTPStubs.removeAllStubs()
// ============================NEXT SYNC==================================================
let nextExpectation = self.expectation(description: "Next sync expectation")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("clear-field-next-sync.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Next sync: updated value."
client.sync(for: syncSpace) { result in
switch result {
case .success:
self.managedObjectContext.perform {
do {
let blankTextBodyRecord: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '5GiLOZvY7SiMeUIgIIAssS'"))
XCTAssertEqual(blankTextBodyRecord.count, 1)
XCTAssertFalse(blankTextBodyRecord.first?.hasChanges ?? false, "Record has not yet been saved")
XCTAssertNil(blankTextBodyRecord.first!.textBody)
} catch {
XCTAssert(false, "Fetching posts should not throw an error")
}
nextExpectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
nextExpectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testLinkResolutionForMultipageSync() {
let expectation = self.expectation(description: "Initial sync succeeded")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let urlString = request.url!.absoluteString
let queryItems = URLComponents(string: urlString)!.queryItems!
for queryItem in queryItems {
if queryItem.name == "initial" {
let stubPath = OHPathForFile("multi-page-link-resolution1.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
} else if queryItem.name == "sync_token" && queryItem.value == "multi-page-link-resolution-token" {
let stubPath = OHPathForFile("multi-page-link-resolution2.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}
}
let stubPath = OHPathForFile("simple-update-initial-sync.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
client.sync() { result in
switch result {
case .success:
self.managedObjectContext.perform {
do {
let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '14XouHzspI44uKCcMicWUY'"))
XCTAssertEqual(records.count, 1)
if let record = records.first {
XCTAssertFalse(record.hasChanges, "Record has not yet been saved")
XCTAssertNotNil(record.linkField)
if let linkedField = record.linkField {
XCTAssertEqual(linkedField.awesomeLinkTitle, "AWESOMELINK!!!")
}
}
} catch {
XCTFail("Fetching SingleRecord should not throw an error")
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testNullifyingLinkBetweenSyncs() {
let expectation = self.expectation(description: "Initial sync succeeded")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("nullified-link-initial.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
var syncSpace: SyncSpace!
client.sync { result in
switch result {
case .success(let space):
syncSpace = space
self.managedObjectContext.perform {
do {
let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '5GiLOZvY7SiMeUIgIIAssS'"))
XCTAssertEqual(records.count, 1)
if let record = records.first {
XCTAssertFalse(record.hasChanges, "Record has not yet been saved")
XCTAssertNotNil(record.linkField)
if let linkedField = record.linkField {
XCTAssertEqual(linkedField.awesomeLinkTitle, "To be nullified")
}
}
}
catch {
XCTFail("Fetching SingleRecord should not throw an error")
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
HTTPStubs.removeAllStubs()
// ============================NEXT SYNC==================================================
let nextExpectation = self.expectation(description: "Next sync expectation")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("nullified-link-next.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Next sync: updated value."
client.sync(for: syncSpace) { result in
switch result {
case .success:
self.managedObjectContext.perform {
do {
let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '5GiLOZvY7SiMeUIgIIAssS'"))
XCTAssertNil(records.first!.linkField)
} catch {
XCTAssert(false, "Fetching posts should not throw an error")
}
nextExpectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
nextExpectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// TODO: Fix all the following tests
// func testDeletingEntryForOneLocaleDeletesCoreDataEntityBetweenSyncs() {
// let expectation = self.expectation(description: "Initial sync succeeded")
//
// stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
// let stubPath = OHPathForFile("deleted-entry-initial.json", ComplexSyncTests.self)
// return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
// }.name = "Initial sync stub"
//
// var syncSpace: SyncSpace!
//
// client.sync { result in
// switch result {
// case .success(let space):
// syncSpace = space
//
// self.managedObjectContext.perform {
// do {
// let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == 'aNt2d7YR4AIwEAMcG4OwI'"))
// XCTAssertEqual(records.count, 1)
// if let record = records.first {
// XCTAssertFalse(record.hasChanges, "Record has not yet been saved")
// XCTAssertEqual(record.textBody, "Hello")
// }
// }
// catch {
// XCTFail("Fetching SingleRecord should not throw an error")
// }
// expectation.fulfill()
// }
//
// case .failure(let error):
// XCTFail("\(error)")
// expectation.fulfill()
// }
// }
// waitForExpectations(timeout: 10.0, handler: nil)
// HTTPStubs.removeAllStubs()
//
// // ============================NEXT SYNC==================================================
// let nextExpectation = self.expectation(description: "Next sync expectation")
//
// stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
// let stubPath = OHPathForFile("deleted-entry-next.json", ComplexSyncTests.self)
// return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
// }.name = "Next sync: updated value."
//
// client.sync(for: syncSpace) { result in
// switch result {
// case .success:
//
// self.managedObjectContext.perform {
// do {
// let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == 'aNt2d7YR4AIwEAMcG4OwI'"))
// XCTAssertNil(records.first)
// XCTAssertEqual(records.count, 0)
// } catch {
// XCTAssert(false, "Fetching SingleRecord should not throw an error")
// }
// nextExpectation.fulfill()
// }
// case .failure(let error):
// XCTFail("\(error)")
// nextExpectation.fulfill()
// }
// }
//
// waitForExpectations(timeout: 10.0, handler: nil)
// }
// func testDeletingEntryForMultiLocaleDeletesCoreDataEntitiesBetweenSyncs() {
// let expectation = self.expectation(description: "Initial sync succeeded")
//
// stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
// let stubPath = OHPathForFile("deleted-entry-initial.json", ComplexSyncTests.self)
// return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
// }.name = "Initial sync stub"
//
// var syncSpace: SyncSpace!
// syncManager.localizationScheme = .all
//
// client.sync { result in
// switch result {
// case .success(let space):
// syncSpace = space
//
// self.managedObjectContext.perform {
// do {
// let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(value: true))
// XCTAssertEqual(records.count, 2)
// if let record = records.filter({ $0.localeCode == "en-US" }).first {
// XCTAssertFalse(record.hasChanges, "Record has not yet been saved")
// XCTAssertEqual(record.textBody, "Hello")
// }
// if let record = records.filter({ $0.localeCode == "es-MX" }).first {
// XCTAssertFalse(record.hasChanges, "Record has not yet been saved")
// XCTAssertEqual(record.textBody, "Hola")
// }
// }
// catch {
// XCTFail("Fetching SingleRecord should not throw an error")
// }
// expectation.fulfill()
// }
//
// case .failure(let error):
// XCTFail("\(error)")
// expectation.fulfill()
// }
// }
// waitForExpectations(timeout: 10.0, handler: nil)
// HTTPStubs.removeAllStubs()
//
// // ============================NEXT SYNC==================================================
// let nextExpectation = self.expectation(description: "Next sync expectation")
//
// stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
// let stubPath = OHPathForFile("deleted-entry-next.json", ComplexSyncTests.self)
// return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
// }.name = "Next sync: updated value."
//
// client.sync(for: syncSpace) { result in
// switch result {
// case .success:
//
// self.managedObjectContext.perform {
// do {
// let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(value: true))
// XCTAssertNil(records.first)
// XCTAssertEqual(records.count, 0)
// } catch {
// XCTAssert(false, "Fetching SingleRecord should not throw an error")
// }
// nextExpectation.fulfill()
// }
// case .failure(let error):
// XCTFail("\(error)")
// nextExpectation.fulfill()
// }
// }
//
// waitForExpectations(timeout: 10.0, handler: nil)
// }
// func testDeletingAssetForOneLocaleDeletesCoreDataEntityBetweenSyncs() {
// let expectation = self.expectation(description: "Initial sync succeeded")
//
// stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
// let stubPath = OHPathForFile("deleted-asset-initial.json", ComplexSyncTests.self)
// return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
// }.name = "Initial sync stub"
//
// var syncSpace: SyncSpace!
//
// client.sync { result in
// switch result {
// case .success(let space):
// syncSpace = space
//
// self.managedObjectContext.perform {
// do {
// let assets: [ComplexAsset] = try self.store.fetchAll(type: ComplexAsset.self, predicate: NSPredicate(format: "id == 'YokO2rWbOoo68QmiEUkqe'"))
// XCTAssertEqual(assets.count, 1)
// if let asset = assets.first {
// XCTAssertFalse(asset.hasChanges, "Asset has not yet been saved")
// XCTAssertEqual(asset.title, "Video asset")
// }
// }
// catch {
// XCTFail("Fetching Asset should not throw an error")
// }
// expectation.fulfill()
// }
//
// case .failure(let error):
// XCTFail("\(error)")
// expectation.fulfill()
// }
// }
// waitForExpectations(timeout: 10.0, handler: nil)
// HTTPStubs.removeAllStubs()
//
// // ============================NEXT SYNC==================================================
// let nextExpectation = self.expectation(description: "Next sync expectation")
//
// stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
// let stubPath = OHPathForFile("deleted-asset-next.json", ComplexSyncTests.self)
// return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
// }.name = "Next sync: updated value."
//
// client.sync(for: syncSpace) { result in
// switch result {
// case .success:
//
// self.managedObjectContext.perform {
// do {
// let assets: [ComplexAsset] = try self.store.fetchAll(type: ComplexAsset.self, predicate: NSPredicate(format: "id == 'YokO2rWbOoo68QmiEUkqe'"))
// XCTAssertNil(assets.first)
// XCTAssertEqual(assets.count, 0)
// } catch {
// XCTAssert(false, "Fetching asset should not throw an error")
// }
// nextExpectation.fulfill()
// }
// case .failure(let error):
// XCTFail("\(error)")
// nextExpectation.fulfill()
// }
// }
//
// waitForExpectations(timeout: 10.0, handler: nil)
// }
func testDeserializingLocation() {
let expectation = self.expectation(description: "Initial sync succeeded")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("location.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
client.sync { result in
switch result {
case .success:
self.managedObjectContext.perform {
do {
let records: [SingleRecord] = try self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '4VTL2TY7rikiS6c2MI2is4'"))
XCTAssertEqual(records.count, 1)
if let record = records.first {
XCTAssertFalse(record.hasChanges, "Record has not yet been saved")
XCTAssertNotNil(record.locationField)
if let locationField = record.locationField {
XCTAssertEqual(locationField.latitude, 34.4208305)
} else {
XCTFail()
}
} else {
XCTFail()
}
}
catch {
XCTFail("Fetching SingleRecord should not throw an error")
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testDeserializingVideoAssetURL() {
let expectation = self.expectation(description: "Initial sync succeeded")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("video-asset.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
client.sync { result in
switch result {
case .success:
self.managedObjectContext.perform {
do {
let assets: [ComplexAsset] = try self.store.fetchAll(type: ComplexAsset.self, predicate: NSPredicate(format: "id == 'YokO2rWbOoo68QmiEUkqe'"))
XCTAssertEqual(assets.count, 1)
if let asset = assets.first {
XCTAssertFalse(asset.hasChanges, "Asset has not yet been saved")
XCTAssertNotNil(asset.urlString)
XCTAssertEqual(asset.urlString ,"https://videos.ctfassets.net/r3rkxrglg2d1/YokO2rWbOoo68QmiEUkqe/5cd5ab8fc90e7b9b4d99d56ea29de768/JP_Swift_Demo.mp4")
} else {
XCTFail()
}
}
catch {
XCTFail("Fetching SingleRecord should not throw an error")
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testEntriesLinkingToSameLinkCanResolveLinks() {
let expectation = self.expectation(description: "Two entries can resolve links to the same asset")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("shared-linked-asset.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
self.client.sync { result in
switch result {
case .success:
// Test first entry can link to asset.
let records: [SingleRecord] = try! self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '4DiVtM6u08uMA2QSgg0OoY'"))
XCTAssertEqual(records.count, 1)
if let linkedAsset = records.first?.assetLinkField {
XCTAssertFalse(linkedAsset.hasChanges, "Asset has not yet been saved")
XCTAssertEqual(linkedAsset.id, "6Wsz8owhtCGSICg44IUYAm")
XCTAssertEqual(linkedAsset.title, "First asset in array")
} else {
XCTFail("There should be a linked asset")
}
// Test second entry can link to same asset
let secondRecordsSet: [SingleRecord] = try! self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '12f37qR1CGOOcqoWOgqC2o'"))
XCTAssertEqual(secondRecordsSet.count, 1)
if let linkedAsset = secondRecordsSet.first?.assetLinkField {
XCTAssertFalse(linkedAsset.hasChanges, "Asset has not yet been saved")
XCTAssertEqual(linkedAsset.id, "6Wsz8owhtCGSICg44IUYAm")
XCTAssertEqual(linkedAsset.title, "First asset in array")
} else {
XCTFail("There should be a linked asset")
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
}
func testResolvingArrayOfLinkedAssets() {
let expectation = self.expectation(description: "Can resolve relationship to linked assets array")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("linked-assets-array.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
self.client.sync { result in
switch result {
case .success:
let records: [SingleRecord] = try! self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '2JFSeiPTZYm4goMSUeYSCU'"))
XCTAssertEqual(records.count, 1)
if let linkedAssetsSet = records.first?.assetsArrayLinkField {
XCTAssertFalse(records.first!.hasChanges, "Record has not yet been saved")
XCTAssertEqual(linkedAssetsSet.count, 2)
XCTAssertEqual((linkedAssetsSet.firstObject as? ComplexAsset)?.title, "First asset in array")
XCTAssertEqual((linkedAssetsSet[1] as? ComplexAsset)?.title, "Second asset in array")
} else {
XCTFail("There should be a linked assets set")
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
}
func testDeserializingArrayOfStrings() {
// TODO:
let expectation = self.expectation(description: "Can deserialize linked strings array")
stub(condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync")) { request -> HTTPStubsResponse in
let stubPath = OHPathForFile("symbols-array.json", ComplexSyncTests.self)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}.name = "Initial sync stub"
self.client.sync { result in
switch result {
case .success:
let records: [SingleRecord] = try! self.store.fetchAll(type: SingleRecord.self, predicate: NSPredicate(format: "id == '2mhGzgf3oQOquo0SyGWCQE'"))
XCTAssertEqual(records.count, 1)
if let linkedStringsData = records.first?.symbolsArray, let linkedStringsArray = NSKeyedUnarchiver.unarchiveObject(with: linkedStringsData) as? [String] {
XCTAssertFalse(records.first!.hasChanges, "Record has not yet been saved")
XCTAssertEqual(linkedStringsArray.count, 5)
XCTAssertEqual(linkedStringsArray.first, "one")
XCTAssertEqual(linkedStringsArray.last, "five")
} else {
XCTFail("There should be an array of linked strings")
}
if let linkedStringsArray = records.first?.symbolsArrayTransformable {
XCTAssertFalse(records.first!.hasChanges, "Record has not yet been saved")
XCTAssertEqual(linkedStringsArray.count, 5)
XCTAssertEqual(linkedStringsArray.first, "one")
XCTAssertEqual(linkedStringsArray.last, "five")
} else {
XCTFail("There should be an array of linked strings")
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
}
func testNonOptionalLinkResolutionForMultipageSync() {
let expectation = self.expectation(description: "Initial sync succeeded")
stub(
condition: isPath("/spaces/smf0sqiu0c5s/environments/master/sync"),
response: { request -> HTTPStubsResponse in
let urlString = request.url!.absoluteString
let queryItems = URLComponents(string: urlString)!.queryItems!
for queryItem in queryItems {
switch queryItem.name {
case "initial":
let stubPath = OHPathForFile(
"multi-page-non-optional-link-resolution1.json",
ComplexSyncTests.self
)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
case "sync_token" where queryItem.value == "multi-page-non-optional-link-resolution-token":
let stubPath = OHPathForFile(
"multi-page-non-optional-link-resolution2.json",
ComplexSyncTests.self
)
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
default:
continue
}
}
XCTFail("Unexpected request cannot be stubbed!")
return HTTPStubsResponse(
error: NSError(domain: "ComplexSyncTests", code: 10, userInfo: nil)
)
}
).name = "Initial sync stub"
client.sync() { result in
switch result {
case .success:
self.managedObjectContext.perform {
do {
let records: [RecordWithNonOptionalRelation] = try self.store.fetchAll(
type: RecordWithNonOptionalRelation.self,
predicate: NSPredicate(format: "id == '15OmnIzspI44uKCcNzcPUS'")
)
XCTAssertEqual(records.count, 1)
if let record = records.first {
XCTAssertEqual(record.nonOptionalLink.awesomeLinkTitle, "Non-optional Link")
XCTAssertFalse(record.hasChanges, "Link has not yet been saved")
XCTAssertFalse(record.nonOptionalLink.hasChanges, "Link has not yet been saved")
}
} catch {
XCTFail("Fetching RecordWithNonOptionalRelation should not throw an error")
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
}
}