-
Notifications
You must be signed in to change notification settings - Fork 27
/
TestLogins.swift
730 lines (605 loc) · 29.9 KB
/
TestLogins.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
import XCGLogger
import XCTest
private let log = XCGLogger.defaultInstance()
class TestSQLiteLogins: XCTestCase {
var db: BrowserDB!
var logins: SQLiteLogins!
let formSubmitURL = "http://submit.me"
let login = Login.createWithHostname("hostname1", username: "username1", password: "password1", formSubmitURL: "http://submit.me")
override func setUp() {
super.setUp()
let files = MockFiles()
self.db = BrowserDB(filename: "testsqlitelogins.db", files: files)
self.logins = SQLiteLogins(db: self.db)
let expectation = self.expectationWithDescription("Remove all logins.")
self.removeAllLogins().upon({ res in expectation.fulfill() })
waitForExpectationsWithTimeout(10.0, handler: nil)
}
func testAddLogin() {
log.debug("Created \(self.login)")
let expectation = self.expectationWithDescription("Add login")
addLogin(login) >>>
getLoginsFor(login.protectionSpace, expected: [login]) >>>
done(expectation)
waitForExpectationsWithTimeout(10.0, handler: nil)
}
func testGetOrder() {
let expectation = self.expectationWithDescription("Add login")
// Different GUID.
let login2 = Login.createWithHostname("hostname1", username: "username2", password: "password2")
login2.formSubmitURL = "http://submit.me"
addLogin(login) >>>
{ self.addLogin(login2) } >>>
getLoginsFor(login.protectionSpace, expected: [login2, login]) >>>
done(expectation)
waitForExpectationsWithTimeout(10.0, handler: nil)
}
func testRemoveLogin() {
let expectation = self.expectationWithDescription("Remove login")
addLogin(login) >>>
removeLogin(login) >>>
getLoginsFor(login.protectionSpace, expected: []) >>>
done(expectation)
waitForExpectationsWithTimeout(10.0, handler: nil)
}
func testRemoveLogins() {
let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL)
let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL)
let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL)
let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL)
func addLogins() -> Success {
addLogin(loginA).value
addLogin(loginB).value
addLogin(loginC).value
addLogin(loginD).value
return succeed()
}
addLogins().value
let guids = [loginA.guid, loginB.guid]
logins.removeLoginsWithGUIDs(guids).value
let result = logins.getAllLogins().value.successValue!
XCTAssertEqual(result.count, 2)
}
func testUpdateLogin() {
let expectation = self.expectationWithDescription("Update login")
let updated = Login.createWithHostname("hostname1", username: "username1", password: "password3", formSubmitURL: formSubmitURL)
updated.guid = self.login.guid
addLogin(login) >>>
updateLogin(updated) >>>
getLoginsFor(login.protectionSpace, expected: [updated]) >>>
done(expectation)
waitForExpectationsWithTimeout(10.0, handler: nil)
}
func testAddInvalidLogin() {
let emptyPasswordLogin = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL)
var result = logins.addLogin(emptyPasswordLogin).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.")
let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "password", formSubmitURL: formSubmitURL)
result = logins.addLogin(emptyHostnameLogin).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.")
let credential = NSURLCredential(user: "username", password: "password", persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: "https://website.com", port: 443, `protocol`: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth")
let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace)
bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me"
result = logins.addLogin(bothFormSubmitURLAndRealm).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.")
let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil)
result = logins.addLogin(noFormSubmitURLOrRealm).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.")
}
func testUpdateInvalidLogin() {
let updated = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL)
updated.guid = self.login.guid
addLogin(login).value
var result = logins.updateLoginByGUID(login.guid, new: updated, significant: true).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.")
let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "", formSubmitURL: formSubmitURL)
emptyHostnameLogin.guid = self.login.guid
result = logins.updateLoginByGUID(login.guid, new: emptyHostnameLogin, significant: true).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.")
let credential = NSURLCredential(user: "username", password: "password", persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: "https://website.com", port: 443, `protocol`: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth")
let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace)
bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me"
bothFormSubmitURLAndRealm.guid = self.login.guid
result = logins.updateLoginByGUID(login.guid, new: bothFormSubmitURLAndRealm, significant: true).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.")
let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil)
noFormSubmitURLOrRealm.guid = self.login.guid
result = logins.updateLoginByGUID(login.guid, new: noFormSubmitURLOrRealm, significant: true).value
XCTAssertNil(result.successValue)
XCTAssertNotNil(result.failureValue)
XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.")
}
func testSearchLogins() {
let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL)
let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL)
let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL)
let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL)
func addLogins() -> Success {
addLogin(loginA).value
addLogin(loginB).value
addLogin(loginC).value
addLogin(loginD).value
return succeed()
}
func checkAllLogins() -> Success {
return logins.getAllLogins() >>== { results in
XCTAssertEqual(results.count, 4)
return succeed()
}
}
func checkSearchHostnames() -> Success {
return logins.searchLoginsWithQuery("pha") >>== { results in
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0]!.hostname, "http://alpha.com")
XCTAssertEqual(results[1]!.hostname, "http://alphabet.com")
return succeed()
}
}
func checkSearchUsernames() -> Success {
return logins.searchLoginsWithQuery("username") >>== { results in
XCTAssertEqual(results.count, 4)
XCTAssertEqual(results[0]!.username, "username2")
XCTAssertEqual(results[1]!.username, "username1")
XCTAssertEqual(results[2]!.username, "username3")
XCTAssertEqual(results[3]!.username, "username4")
return succeed()
}
}
func checkSearchPasswords() -> Success {
return logins.searchLoginsWithQuery("pass") >>== { results in
XCTAssertEqual(results.count, 4)
XCTAssertEqual(results[0]!.password, "password2")
XCTAssertEqual(results[1]!.password, "password1")
XCTAssertEqual(results[2]!.password, "password3")
XCTAssertEqual(results[3]!.password, "password4")
return succeed()
}
}
XCTAssertTrue(addLogins().value.isSuccess)
XCTAssertTrue(checkAllLogins().value.isSuccess)
XCTAssertTrue(checkSearchHostnames().value.isSuccess)
XCTAssertTrue(checkSearchUsernames().value.isSuccess)
XCTAssertTrue(checkSearchPasswords().value.isSuccess)
XCTAssertTrue(removeAllLogins().value.isSuccess)
}
/*
func testAddUseOfLogin() {
let expectation = self.expectationWithDescription("Add visit")
if var usageData = login as? LoginUsageData {
usageData.timeCreated = NSDate.nowMicroseconds()
}
addLogin(login) >>>
addUseDelayed(login, time: 1) >>>
getLoginDetailsFor(login, expected: login as! LoginUsageData) >>>
done(login.protectionSpace, expectation: expectation)
waitForExpectationsWithTimeout(10.0, handler: nil)
}
*/
func done(expectation: XCTestExpectation)() -> Success {
return removeAllLogins()
>>> getLoginsFor(login.protectionSpace, expected: [])
>>> {
expectation.fulfill()
return succeed()
}
}
// Note: These functions are all curried so that we pass arguments, but still chain them below
func addLogin(login: LoginData) -> Success {
log.debug("Add \(login)")
return logins.addLogin(login)
}
func updateLogin(login: LoginData)() -> Success {
log.debug("Update \(login)")
return logins.updateLoginByGUID(login.guid, new: login, significant: true)
}
func addUseDelayed(login: Login, time: UInt32)() -> Success {
sleep(time)
login.timeLastUsed = NSDate.nowMicroseconds()
let res = logins.addUseOfLoginByGUID(login.guid)
sleep(time)
return res
}
func getLoginsFor(protectionSpace: NSURLProtectionSpace, expected: [LoginData]) -> (() -> Success) {
return {
log.debug("Get logins for \(protectionSpace)")
return self.logins.getLoginsForProtectionSpace(protectionSpace) >>== { results in
XCTAssertEqual(expected.count, results.count)
for (index, login) in expected.enumerate() {
XCTAssertEqual(results[index]!.username!, login.username!)
XCTAssertEqual(results[index]!.hostname, login.hostname)
XCTAssertEqual(results[index]!.password, login.password)
}
return succeed()
}
}
}
/*
func getLoginDetailsFor(login: LoginData, expected: LoginUsageData) -> (() -> Success) {
return {
log.debug("Get details for \(login)")
let deferred = self.logins.getUsageDataForLogin(login)
log.debug("Final result \(deferred)")
return deferred >>== { l in
log.debug("Got cursor")
XCTAssertLessThan(expected.timePasswordChanged - l.timePasswordChanged, 10)
XCTAssertLessThan(expected.timeLastUsed - l.timeLastUsed, 10)
XCTAssertLessThan(expected.timeCreated - l.timeCreated, 10)
return succeed()
}
}
}
*/
func removeLogin(login: LoginData)() -> Success {
log.debug("Remove \(login)")
return logins.removeLoginByGUID(login.guid)
}
func removeAllLogins() -> Success {
log.debug("Remove All")
// Because we don't want to just mark them as deleted.
return self.db.run("DELETE FROM \(TableLoginsMirror)") >>>
{ self.db.run("DELETE FROM \(TableLoginsLocal)") }
}
}
class TestSQLiteLoginsPerf: XCTestCase {
var db: BrowserDB!
var logins: SQLiteLogins!
override func setUp() {
super.setUp()
let files = MockFiles()
self.db = BrowserDB(filename: "testsqlitelogins.db", files: files)
self.logins = SQLiteLogins(db: self.db)
}
func testLoginsSearchMatchOnePerf() {
populateTestLogins()
// Measure time to find one entry amongst the 1000 of them
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) {
for _ in 0...5 {
self.logins.searchLoginsWithQuery("username500").value
}
self.stopMeasuring()
}
XCTAssertTrue(removeAllLogins().value.isSuccess)
}
func testLoginsSearchMatchAllPerf() {
populateTestLogins()
// Measure time to find all matching results
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) {
for _ in 0...5 {
self.logins.searchLoginsWithQuery("username").value
}
self.stopMeasuring()
}
XCTAssertTrue(removeAllLogins().value.isSuccess)
}
func testLoginsGetAllPerf() {
populateTestLogins()
// Measure time to find all matching results
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) {
for _ in 0...5 {
self.logins.getAllLogins().value
}
self.stopMeasuring()
}
XCTAssertTrue(removeAllLogins().value.isSuccess)
}
func populateTestLogins() {
for i in 0..<1000 {
let login = Login.createWithHostname("website\(i).com", username: "username\(i)", password: "password\(i)")
addLogin(login).value
}
}
func addLogin(login: LoginData) -> Success {
log.debug("Add \(login)")
return logins.addLogin(login)
}
func removeAllLogins() -> Success {
log.debug("Remove All")
// Because we don't want to just mark them as deleted.
return self.db.run("DELETE FROM \(TableLoginsMirror)") >>>
{ self.db.run("DELETE FROM \(TableLoginsLocal)") }
}
}
class TestSyncableLogins: XCTestCase {
var db: BrowserDB!
var logins: SQLiteLogins!
override func setUp() {
super.setUp()
let files = MockFiles()
self.db = BrowserDB(filename: "testsyncablelogins.db", files: files)
self.logins = SQLiteLogins(db: self.db)
let expectation = self.expectationWithDescription("Remove all logins.")
self.removeAllLogins().upon({ res in expectation.fulfill() })
waitForExpectationsWithTimeout(10.0, handler: nil)
}
func removeAllLogins() -> Success {
log.debug("Remove All")
// Because we don't want to just mark them as deleted.
return self.db.run("DELETE FROM \(TableLoginsMirror)") >>>
{ self.db.run("DELETE FROM \(TableLoginsLocal)") }
}
func testDiffers() {
let guid = "abcdabcdabcd"
let host = "http://example.com"
let user = "username"
let loginA1 = Login(guid: guid, hostname: host, username: user, password: "password1")
loginA1.formSubmitURL = "\(host)/form1/"
loginA1.usernameField = "afield"
let loginA2 = Login(guid: guid, hostname: host, username: user, password: "password1")
loginA2.formSubmitURL = "\(host)/form1/"
loginA2.usernameField = "somefield"
let loginB = Login(guid: guid, hostname: host, username: user, password: "password2")
loginB.formSubmitURL = "\(host)/form1/"
let loginC = Login(guid: guid, hostname: host, username: user, password: "password")
loginC.formSubmitURL = "\(host)/form2/"
XCTAssert(loginA1.isSignificantlyDifferentFrom(loginB))
XCTAssert(loginA1.isSignificantlyDifferentFrom(loginC))
XCTAssert(loginA2.isSignificantlyDifferentFrom(loginB))
XCTAssert(loginA2.isSignificantlyDifferentFrom(loginC))
XCTAssert(!loginA1.isSignificantlyDifferentFrom(loginA2))
}
func testLocalNewStaysNewAndIsRemoved() {
let guidA = "abcdabcdabcd"
let loginA1 = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "password")
loginA1.formSubmitURL = "http://example.com/form/"
loginA1.timesUsed = 1
XCTAssertTrue((self.logins as BrowserLogins).addLogin(loginA1).value.isSuccess)
let local1 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!
XCTAssertNotNil(local1)
XCTAssertEqual(local1!.guid, guidA)
XCTAssertEqual(local1!.syncStatus, SyncStatus.New)
XCTAssertEqual(local1!.timesUsed, 1)
XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess)
// It's still new.
let local2 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!
XCTAssertNotNil(local2)
XCTAssertEqual(local2!.guid, guidA)
XCTAssertEqual(local2!.syncStatus, SyncStatus.New)
XCTAssertEqual(local2!.timesUsed, 2)
// It's removed immediately, because it was never synced.
XCTAssertTrue((self.logins as BrowserLogins).removeLoginByGUID(guidA).value.isSuccess)
XCTAssertNil(self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!)
}
func testApplyLogin() {
let guidA = "abcdabcdabcd"
let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234)
loginA1.formSubmitURL = "http://example.com/form/"
loginA1.timesUsed = 3
XCTAssertTrue(self.logins.applyChangedLogin(loginA1).value.isSuccess)
let local = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!
let mirror = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue!
XCTAssertTrue(nil == local)
XCTAssertTrue(nil != mirror)
XCTAssertEqual(mirror!.guid, guidA)
XCTAssertFalse(mirror!.isOverridden)
XCTAssertEqual(mirror!.serverModified, Timestamp(1234), "Timestamp matches.")
XCTAssertEqual(mirror!.timesUsed, 3)
XCTAssertTrue(nil == mirror!.httpRealm)
XCTAssertTrue(nil == mirror!.passwordField)
XCTAssertTrue(nil == mirror!.usernameField)
XCTAssertEqual(mirror!.formSubmitURL!, "http://example.com/form/")
XCTAssertEqual(mirror!.hostname, "http://example.com")
XCTAssertEqual(mirror!.username!, "username")
XCTAssertEqual(mirror!.password, "password")
// Change it.
let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "newpassword", modified: 2234)
loginA2.formSubmitURL = "http://example.com/form/"
loginA2.timesUsed = 4
XCTAssertTrue(self.logins.applyChangedLogin(loginA2).value.isSuccess)
let changed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue!
XCTAssertTrue(nil != changed)
XCTAssertFalse(changed!.isOverridden)
XCTAssertEqual(changed!.serverModified, Timestamp(2234), "Timestamp is new.")
XCTAssertEqual(changed!.username!, "username")
XCTAssertEqual(changed!.password, "newpassword")
XCTAssertEqual(changed!.timesUsed, 4)
// Change it locally.
let preUse = NSDate.now()
XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess)
let localUsed = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!
let mirrorUsed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue!
XCTAssertNotNil(localUsed)
XCTAssertNotNil(mirrorUsed)
XCTAssertEqual(mirrorUsed!.guid, guidA)
XCTAssertEqual(localUsed!.guid, guidA)
XCTAssertEqual(mirrorUsed!.password, "newpassword")
XCTAssertEqual(localUsed!.password, "newpassword")
XCTAssertTrue(mirrorUsed!.isOverridden) // It's now overridden.
XCTAssertEqual(mirrorUsed!.serverModified, Timestamp(2234), "Timestamp is new.")
XCTAssertTrue(localUsed!.localModified >= preUse) // Local record is modified.
XCTAssertEqual(localUsed!.syncStatus, SyncStatus.Synced) // Uses aren't enough to warrant upload.
// Uses are local until reconciled.
XCTAssertEqual(localUsed!.timesUsed, 5)
XCTAssertEqual(mirrorUsed!.timesUsed, 4)
// Change the password and form URL locally.
let newLocalPassword = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "yupyup")
newLocalPassword.formSubmitURL = "http://example.com/form2/"
let preUpdate = NSDate.now()
// Updates always bump our usages, too.
XCTAssertTrue(self.logins.updateLoginByGUID(guidA, new: newLocalPassword, significant: true).value.isSuccess)
let localAltered = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!
let mirrorAltered = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue!
XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(mirrorUsed!)) // The mirror is unchanged.
XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(localUsed!))
XCTAssertTrue(mirrorAltered!.isOverridden) // It's still overridden.
XCTAssertTrue(localAltered!.isSignificantlyDifferentFrom(localUsed!))
XCTAssertEqual(localAltered!.password, "yupyup")
XCTAssertEqual(localAltered!.formSubmitURL!, "http://example.com/form2/")
XCTAssertTrue(localAltered!.localModified >= preUpdate)
XCTAssertEqual(localAltered!.syncStatus, SyncStatus.Changed) // Changes are enough to warrant upload.
XCTAssertEqual(localAltered!.timesUsed, 6)
XCTAssertEqual(mirrorAltered!.timesUsed, 4)
}
func testDeltas() {
// Shared.
let guidA = "abcdabcdabcd"
let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234)
loginA1.timeCreated = 1200
loginA1.timeLastUsed = 1234
loginA1.timePasswordChanged = 1200
loginA1.formSubmitURL = "http://example.com/form/"
loginA1.timesUsed = 3
let a1a1 = loginA1.deltas(from: loginA1)
XCTAssertEqual(0, a1a1.nonCommutative.count)
XCTAssertEqual(0, a1a1.nonConflicting.count)
XCTAssertEqual(0, a1a1.commutative.count)
let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1235)
loginA2.timeCreated = 1200
loginA2.timeLastUsed = 1235
loginA2.timePasswordChanged = 1200
loginA2.timesUsed = 4
let a1a2 = loginA2.deltas(from: loginA1)
XCTAssertEqual(2, a1a2.nonCommutative.count)
XCTAssertEqual(0, a1a2.nonConflicting.count)
XCTAssertEqual(1, a1a2.commutative.count)
switch a1a2.commutative[0] {
case let .TimesUsed(increment):
XCTAssertEqual(increment, 1)
break
}
switch a1a2.nonCommutative[0] {
case let .FormSubmitURL(to):
XCTAssertNil(to)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
switch a1a2.nonCommutative[1] {
case let .TimeLastUsed(to):
XCTAssertEqual(to, 1235)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
let loginA3 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "something else", modified: 1280)
loginA3.timeCreated = 1200
loginA3.timeLastUsed = 1250
loginA3.timePasswordChanged = 1250
loginA3.formSubmitURL = "http://example.com/form/"
loginA3.timesUsed = 5
let a1a3 = loginA3.deltas(from: loginA1)
XCTAssertEqual(3, a1a3.nonCommutative.count)
XCTAssertEqual(0, a1a3.nonConflicting.count)
XCTAssertEqual(1, a1a3.commutative.count)
switch a1a3.commutative[0] {
case let .TimesUsed(increment):
XCTAssertEqual(increment, 2)
break
}
switch a1a3.nonCommutative[0] {
case let .Password(to):
XCTAssertEqual("something else", to)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
switch a1a3.nonCommutative[1] {
case let .TimeLastUsed(to):
XCTAssertEqual(to, 1250)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
switch a1a3.nonCommutative[2] {
case let .TimePasswordChanged(to):
XCTAssertEqual(to, 1250)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
// Now apply the deltas to the original record and check that they match!
XCTAssertFalse(loginA1.applyDeltas(a1a2).isSignificantlyDifferentFrom(loginA2))
XCTAssertFalse(loginA1.applyDeltas(a1a3).isSignificantlyDifferentFrom(loginA3))
let merged = Login.mergeDeltas(a: (loginA2.serverModified, a1a2), b: (loginA3.serverModified, a1a3))
let mCCount = merged.commutative.count
let a2CCount = a1a2.commutative.count
let a3CCount = a1a3.commutative.count
XCTAssertEqual(mCCount, a2CCount + a3CCount)
let mNCount = merged.nonCommutative.count
let a2NCount = a1a2.nonCommutative.count
let a3NCount = a1a3.nonCommutative.count
XCTAssertLessThanOrEqual(mNCount, a2NCount + a3NCount)
XCTAssertGreaterThanOrEqual(mNCount, max(a2NCount, a3NCount))
let mFCount = merged.nonConflicting.count
let a2FCount = a1a2.nonConflicting.count
let a3FCount = a1a3.nonConflicting.count
XCTAssertLessThanOrEqual(mFCount, a2FCount + a3FCount)
XCTAssertGreaterThanOrEqual(mFCount, max(a2FCount, a3FCount))
switch merged.commutative[0] {
case let .TimesUsed(increment):
XCTAssertEqual(1, increment)
}
switch merged.commutative[1] {
case let .TimesUsed(increment):
XCTAssertEqual(2, increment)
}
switch merged.nonCommutative[0] {
case let .Password(to):
XCTAssertEqual("something else", to)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
switch merged.nonCommutative[1] {
case let .FormSubmitURL(to):
XCTAssertNil(to)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
switch merged.nonCommutative[2] {
case let .TimeLastUsed(to):
XCTAssertEqual(to, 1250)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
switch merged.nonCommutative[3] {
case let .TimePasswordChanged(to):
XCTAssertEqual(to, 1250)
break
default:
XCTFail("Unexpected non-commutative login field.")
}
// Applying the merged deltas gives us the expected login.
let expected = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "something else")
expected.timeCreated = 1200
expected.timeLastUsed = 1250
expected.timePasswordChanged = 1250
expected.formSubmitURL = nil
expected.timesUsed = 6
let applied = loginA1.applyDeltas(merged)
XCTAssertFalse(applied.isSignificantlyDifferentFrom(expected))
XCTAssertFalse(expected.isSignificantlyDifferentFrom(applied))
}
func testLoginsIsSynced() {
let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1")
let serverLoginA = ServerLogin(guid: loginA.guid, hostname: "alpha.com", username: "username1", password: "password1", modified: NSDate.now())
XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? true)
logins.addLogin(loginA).value
XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? false)
logins.applyChangedLogin(serverLoginA).value
XCTAssertTrue(logins.hasSyncedLogins().value.successValue ?? false)
}
}