forked from ghostery/user-agent-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlobal.swift
715 lines (593 loc) · 30.9 KB
/
Global.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
/* 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 GCDWebServers
import Storage
import WebKit
import SwiftKeychainWrapper
import Shared
import EarlGrey
@testable import Client
let LabelAddressAndSearch = "Address and Search"
extension XCTestCase {
func tester(_ file: String = #file, _ line: Int = #line) -> KIFUITestActor {
return KIFUITestActor(inFile: file, atLine: line, delegate: self)
}
func system(_ file: String = #file, _ line: Int = #line) -> KIFSystemTestActor {
return KIFSystemTestActor(inFile: file, atLine: line, delegate: self)
}
}
extension KIFUITestActor {
/// Looks for a view with the given accessibility hint.
func tryFindingViewWithAccessibilityHint(_ hint: String) -> Bool {
let element = UIApplication.shared.accessibilityElement { element in
return element?.accessibilityHint! == hint
}
return element != nil
}
func waitForViewWithAccessibilityHint(_ hint: String) -> UIView? {
var view: UIView? = nil
autoreleasepool {
wait(for: nil, view: &view, withElementMatching: NSPredicate(format: "accessibilityHint = %@", hint), tappable: false)
}
return view
}
func viewExistsWithLabel(_ label: String) -> Bool {
do {
try self.tryFindingView(withAccessibilityLabel: label)
return true
} catch {
return false
}
}
func viewExistsWithLabelPrefixedBy(_ prefix: String) -> Bool {
let element = UIApplication.shared.accessibilityElement { element in
return element?.accessibilityLabel?.hasPrefix(prefix) ?? false
}
return element != nil
}
/// Waits for and returns a view with the given accessibility value.
func waitForViewWithAccessibilityValue(_ value: String) -> UIView {
var element: UIAccessibilityElement!
run { _ in
element = UIApplication.shared.accessibilityElement { element in
return element?.accessibilityValue == value
}
return (element == nil) ? KIFTestStepResult.wait : KIFTestStepResult.success
}
return UIAccessibilityElement.viewContaining(element)
}
/// Wait for and returns a view with the given accessibility label as an
/// attributed string. See the comment in ReadingListPanel.swift about
/// using attributed strings as labels. (It lets us set the pitch)
func waitForViewWithAttributedAccessibilityLabel(_ label: NSAttributedString) -> UIView {
var element: UIAccessibilityElement!
run { _ in
element = UIApplication.shared.accessibilityElement { element in
if let elementLabel = element?.value(forKey: "accessibilityLabel") as? NSAttributedString {
return elementLabel.isEqual(to: label)
}
return false
}
return (element == nil) ? KIFTestStepResult.wait : KIFTestStepResult.success
}
return UIAccessibilityElement.viewContaining(element)
}
/// There appears to be a KIF bug where waitForViewWithAccessibilityLabel returns the parent
/// UITableView instead of the UITableViewCell with the given label.
/// As a workaround, retry until KIF gives us a cell.
/// Open issue: https://github.com/kif-framework/KIF/issues/336
func waitForCellWithAccessibilityLabel(_ label: String) -> UITableViewCell {
var cell: UITableViewCell!
run { _ in
let view = self.waitForView(withAccessibilityLabel: label)
cell = view as? UITableViewCell
return (cell == nil) ? KIFTestStepResult.wait : KIFTestStepResult.success
}
return cell
}
/**
* Finding views by accessibility label doesn't currently work with WKWebView:
* https://github.com/kif-framework/KIF/issues/460
* As a workaround, inject a KIFHelper class that iterates the document and finds
* elements with the given textContent or title.
*/
func waitForWebViewElementWithAccessibilityLabel(_ text: String) {
run { error in
if self.hasWebViewElementWithAccessibilityLabel(text) {
return KIFTestStepResult.success
}
return KIFTestStepResult.wait
}
}
/**
* Sets the text for a WKWebView input element with the given name.
*/
func enterText(_ text: String, intoWebViewInputWithName inputName: String) {
let webView = getWebViewWithKIFHelper()
var stepResult = KIFTestStepResult.wait
let escaped = text.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavascriptInDefaultContentWorld("KIFHelper.enterTextIntoInputWithName(\"\(escaped)\", \"\(inputName)\");") { success, _ in
stepResult = (success as? Bool) ? KIFTestStepResult.success : KIFTestStepResult.failure
}
run { error in
if stepResult == KIFTestStepResult.failure {
error?.pointee = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Input element not found in webview: \(escaped)"])
}
return stepResult
}
}
/**
* Clicks a WKWebView element with the given label.
*/
func tapWebViewElementWithAccessibilityLabel(_ text: String) {
let webView = getWebViewWithKIFHelper()
var stepResult = KIFTestStepResult.wait
let escaped = text.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavascriptInDefaultContentWorld("KIFHelper.tapElementWithAccessibilityLabel(\"\(escaped)\")") { success, _ in
stepResult = (success as? Bool) ? KIFTestStepResult.success : KIFTestStepResult.failure
}
run { error in
if stepResult == KIFTestStepResult.failure {
error?.pointee = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Accessibility label not found in webview: \(escaped)"])
}
return stepResult
}
}
/**
* Determines whether an element in the page exists.
*/
func hasWebViewElementWithAccessibilityLabel(_ text: String) -> Bool {
let webView = getWebViewWithKIFHelper()
var stepResult = KIFTestStepResult.wait
var found = false
let escaped = text.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavascriptInDefaultContentWorld("KIFHelper.hasElementWithAccessibilityLabel(\"\(escaped)\")") { success, _ in
found = success as? Bool ?? false
stepResult = KIFTestStepResult.success
}
run { _ in return stepResult }
return found
}
fileprivate func getWebViewWithKIFHelper() -> WKWebView {
let webView = waitForView(withAccessibilityLabel: "Web content") as! WKWebView
// Wait for the web view to stop loading.
run { _ in
return webView.isLoading ? KIFTestStepResult.wait : KIFTestStepResult.success
}
var stepResult = KIFTestStepResult.wait
webView.evaluateJavascriptInDefaultContentWorld("typeof KIFHelper") { result, _ in
if let result = result as? String, result == "undefined" {
let bundle = Bundle(for: BrowserTests.self)
let path = bundle.path(forResource: "KIFHelper", ofType: "js")!
if let source = try? String(contentsOfFile: path, encoding: .utf8) {
webView.evaluateJavascriptInDefaultContentWorld(source)
stepResult = KIFTestStepResult.success
} else {
stepResult = KIFTestStepResult.failure
}
} else {
stepResult = KIFTestStepResult.failure
}
}
run { _ in return stepResult }
return webView
}
public func deleteCharacterFromFirstResponser() {
self.enterText(intoCurrentFirstResponder: "\u{0008}")
}
}
class BrowserUtils {
// Needs to be in sync with Client Clearables.
enum Clearable: String {
case History = "Browsing History"
case Cache = "Cache"
case OfflineData = "Offline Website Data"
case Cookies = "Cookies"
case TrackingProtection = "Tracking Protection"
}
internal static let AllClearables = Set([Clearable.History, Clearable.Cache, Clearable.OfflineData, Clearable.Cookies, Clearable.TrackingProtection])
class func resetToAboutHome() {
var error: NSError?
// If there is a popup dialog, close. Otherwise, ignore the error and continue
EarlGrey.selectElement(with: grey_accessibilityLabel("Cancel")).perform(grey_tap(), error: &error)
error = nil
if iPad() {
EarlGrey.selectElement(with: grey_accessibilityID("TopTabsViewController.tabsButton")).perform(grey_tap())
} else {
EarlGrey.selectElement(with: grey_accessibilityID("TabToolbar.tabsButton")).perform(grey_tap())
}
let goPrivateModeBtn = grey_allOf([grey_accessibilityID("TabTrayController.maskButton"), grey_accessibilityValue("Off")])
let goNormalModeBtn = grey_allOf([grey_accessibilityID("TabTrayController.maskButton"), grey_accessibilityValue("On")])
let closeAllBtn = grey_allOf([grey_accessibilityID("TabTrayController.deleteButton.closeAll"), grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)])
// Clear all Private and normal tabs
EarlGrey.selectElement(with: goPrivateModeBtn).assert(grey_notNil(), error: &error)
if (error == nil) { /* in normal mode now, go to Private mode */
EarlGrey.selectElement(with: goPrivateModeBtn).perform(grey_tap())
}
EarlGrey.selectElement(with: grey_accessibilityID("TabTrayController.removeTabsButton")).perform(grey_tap())
EarlGrey.selectElement(with: closeAllBtn).perform(grey_tap())
/* go to Normal mode */
EarlGrey.selectElement(with: goNormalModeBtn).perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityID("TabTrayController.removeTabsButton")).perform(grey_tap())
EarlGrey.selectElement(with: closeAllBtn).perform(grey_tap())
let topsiteAppeared = GREYCondition(name: "Wait for the topsite view", block: {
var errorOrNil: NSError?
let matcher = grey_allOf([grey_accessibilityLabel("Show Tabs"),
grey_sufficientlyVisible()])
EarlGrey.selectElement(with: matcher)
.assert(grey_notNil(), error: &errorOrNil)
let success = errorOrNil == nil
return success
}).wait(withTimeout: 10)
GREYAssertTrue(topsiteAppeared, reason: "Failed to return to topsite view")
}
class func configEarlGrey() {
GREYConfiguration.sharedInstance().setValue(2, forConfigKey: kGREYConfigKeyCALayerMaxAnimationDuration)
GREYConfiguration.sharedInstance().setValue(false, forConfigKey: kGREYConfigKeyActionConstraintsEnabled)
GREYConfiguration.sharedInstance().setValue(2, forConfigKey: kGREYConfigKeyDelayedPerformMaxTrackableDuration)
GREYConfiguration.sharedInstance().setValue(100, forConfigKey: kGREYConfigKeyInteractionTimeoutDuration)
GREYConfiguration.sharedInstance().setValue(["."], forConfigKey: kGREYConfigKeyURLBlacklistRegex)
}
class func dismissFirstRunUI() {
var error: NSError?
let matcher = grey_allOf([
grey_accessibilityID("nextOnboardingButton"), grey_sufficientlyVisible()])
EarlGrey.selectElement(with: matcher).assert(grey_notNil(), error: &error)
if error == nil {
EarlGrey.selectElement(with: matcher).perform(grey_tap())
let buttonMatcher = grey_allOf([
grey_accessibilityID("startBrowsingOnboardingButton"), grey_sufficientlyVisible()])
EarlGrey.selectElement(with: buttonMatcher).assert(grey_notNil(), error: &error)
if error == nil {
EarlGrey.selectElement(with: buttonMatcher).perform(grey_tap())
}
}
}
class func enterUrlAddressBar(typeUrl: String) {
EarlGrey.selectElement(with: grey_accessibilityID("url"))
.inRoot(grey_kindOfClass(UITextField.self))
.perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityID("address"))
.inRoot(grey_kindOfClass(UITextField.self))
.perform(grey_replaceText(typeUrl))
EarlGrey.selectElement(with: grey_accessibilityID("address"))
.inRoot(grey_kindOfClass(UITextField.self))
.perform(grey_typeText("\n"))
}
class func iPad() -> Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
/// Injects a URL and title into the browser's history database.
class func addHistoryEntry(_ title: String, url: URL) {
let info: [AnyHashable: Any] = [
"url": url,
"title": title,
"visitType": VisitType.link.rawValue]
NotificationCenter.default.post(name: .OnLocationChange, object: self, userInfo: info)
}
fileprivate class func clearHistoryItemAtIndex(_ index: IndexPath, tester: KIFUITestActor) {
if let row = tester.waitForCell(at: index, inTableViewWithAccessibilityIdentifier: "History List") {
tester.swipeView(withAccessibilityLabel: row.accessibilityLabel, value: row.accessibilityValue, in: KIFSwipeDirection.left)
tester.tapView(withAccessibilityLabel: "Remove")
}
}
class func openClearPrivateDataDialog(_ swipe: Bool) {
let settings_button = grey_allOf([grey_accessibilityLabel("Settings"),
grey_accessibilityID("menu-Settings")])
if iPad() {
EarlGrey.selectElement(with: grey_accessibilityID("TabToolbar.menuButton")).perform(grey_tap())
} else {
EarlGrey.selectElement(with: grey_accessibilityLabel("Menu")).perform(grey_tap())
}
// Need this for simulator only
if swipe {
EarlGrey.selectElement(with: grey_accessibilityLabel("Set Homepage"))
.perform(grey_swipeFastInDirection(GREYDirection.left))
}
EarlGrey.selectElement(with: settings_button).perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityID("ClearPrivateData"))
.using(searchAction: grey_scrollInDirection(.down, 200),
onElementWithMatcher: grey_accessibilityID("AppSettingsTableViewController.tableView"))
.assert(grey_notNil())
EarlGrey.selectElement(with: grey_accessibilityID("ClearPrivateData")).perform(grey_tap())
}
class func closeClearPrivateDataDialog() {
let back_button = grey_allOf([grey_accessibilityLabel("Settings"),
grey_kindOfClass(NSClassFromString("_UIButtonBarButton")!)])
EarlGrey.selectElement(with: back_button).perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityID("AppSettingsTableViewController.navigationItem.leftBarButtonItem"))
.perform(grey_tap())
}
fileprivate class func acceptClearPrivateData() {
EarlGrey.selectElement(with: grey_allOf([grey_accessibilityLabel("OK"), grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)])).perform(grey_tap())
}
fileprivate class func cancelClearPrivateData() {
EarlGrey.selectElement(with: grey_accessibilityLabel("Cancel")).perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityLabel("Clear Private Data")).perform(grey_tap())
}
class func clearPrivateData(_ clearables: Set<Clearable>? = AllClearables, swipe: Bool? = false) {
openClearPrivateDataDialog(swipe!)
// Disable all items that we don't want to clear.
for clearable in AllClearables {
let switchControl = grey_allOf([grey_accessibilityLabel(clearable.rawValue),
grey_kindOfClass(UISwitch.self)])
let clearablePresent = GREYCondition(name: "Wait for URL field", block: {
var errorOrNil: NSError?
EarlGrey.selectElement(with: switchControl)
.assert(grey_notNil(), error: &errorOrNil)
return errorOrNil == nil
}).wait(withTimeout: 10)
GREYAssertTrue(clearablePresent, reason: "Failed to find clearable")
EarlGrey.selectElement(with: switchControl).perform(grey_turnSwitchOn(clearables!.contains(clearable)))
}
EarlGrey.selectElement(with: grey_accessibilityID("ClearPrivateData")).perform(grey_tap())
acceptClearPrivateData()
closeClearPrivateDataDialog()
}
class func clearHistoryItems(_ tester: KIFUITestActor, numberOfTests: Int = -1) {
resetToAboutHome()
tester.tapView(withAccessibilityLabel: "History")
let historyTable = tester.waitForView(withAccessibilityIdentifier: "History List") as! UITableView
var index = 0
for _ in 0 ..< historyTable.numberOfSections {
for _ in 0 ..< historyTable.numberOfRows(inSection: 0) {
clearHistoryItemAtIndex(IndexPath(row: 0, section: 0), tester: tester)
if numberOfTests > -1 {
index += 1
if index == numberOfTests {
return
}
}
}
}
tester.tapView(withAccessibilityLabel: "Top sites")
}
class func ensureAutocompletionResult(_ tester: KIFUITestActor, textField: UITextField, prefix: String, completion: String) {
// searches are async (and debounced), so we have to wait for the results to appear.
tester.waitForViewWithAccessibilityValue(prefix + completion)
let autocompleteFieldlabel = textField.subviews.first { $0.accessibilityIdentifier == "autocomplete" } as? UILabel
if completion == "" {
XCTAssertTrue(autocompleteFieldlabel == nil, "The autocomplete was empty but the label still exists.")
return
}
XCTAssertTrue(autocompleteFieldlabel != nil, "The autocomplete was not found")
XCTAssertEqual(completion, autocompleteFieldlabel!.text, "Expected prefix matches actual prefix")
}
class func openLibraryMenu(_ tester: KIFUITestActor) {
tester.waitForAnimationsToFinish()
tester.waitForView(withAccessibilityIdentifier: "TabToolbar.menuButton")
tester.tapView(withAccessibilityIdentifier: "TabToolbar.menuButton")
tester.waitForAnimationsToFinish()
tester.tapView(withAccessibilityIdentifier: "menu-library")
}
class func closeLibraryMenu(_ tester: KIFUITestActor) {
if iPad() {
EarlGrey.selectElement(with: grey_accessibilityID("TabToolbar.libraryButton"))
.perform(grey_tap())
} else {
EarlGrey.selectElement(with: grey_accessibilityID("History"))
.perform(grey_swipeFastInDirection(GREYDirection.down))
}
tester.waitForAnimationsToFinish()
}
}
class SimplePageServer {
class func getPageData(_ name: String, ext: String = "html") -> String {
let pageDataPath = Bundle(for: self).path(forResource: name, ofType: ext)!
return try! String(contentsOfFile: pageDataPath, encoding: .utf8)
}
static var useLocalhostInsteadOfIP = false
class func start() -> String {
let webServer: GCDWebServer = GCDWebServer()
webServer.addHandler(forMethod: "GET", path: "/image.png", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
let img = UIImage(named: "goBack")!.pngData()!
return GCDWebServerDataResponse(data: img, contentType: "image/png")
}
for page in ["findPage", "noTitle", "readablePage", "JSPrompt", "blobURL", "firefoxScheme"] {
webServer.addHandler(forMethod: "GET", path: "/\(page).html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
return GCDWebServerDataResponse(html: self.getPageData(page))
}
}
// we may create more than one of these but we need to give them uniquie accessibility ids in the tab manager so we'll pass in a page number
webServer.addHandler(forMethod: "GET", path: "/scrollablePage.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
var pageData = self.getPageData("scrollablePage")
let page = Int((request.query?["page"] as! String))!
pageData = pageData.replacingOccurrences(of: "{page}", with: page.description)
return GCDWebServerDataResponse(html: pageData as String)
}
webServer.addHandler(forMethod: "GET", path: "/numberedPage.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
var pageData = self.getPageData("numberedPage")
let page = Int((request.query?["page"] as! String))!
pageData = pageData.replacingOccurrences(of: "{page}", with: page.description)
return GCDWebServerDataResponse(html: pageData as String)
}
webServer.addHandler(forMethod: "GET", path: "/readerContent.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
return GCDWebServerDataResponse(html: self.getPageData("readerContent"))
}
webServer.addHandler(forMethod: "GET", path: "/loginForm.html", request: GCDWebServerRequest.self) { _ in
return GCDWebServerDataResponse(html: self.getPageData("loginForm"))
}
webServer.addHandler(forMethod: "GET", path: "/navigationDelegate.html", request: GCDWebServerRequest.self) { _ in
return GCDWebServerDataResponse(html: self.getPageData("navigationDelegate"))
}
webServer.addHandler(forMethod: "GET", path: "/localhostLoad.html", request: GCDWebServerRequest.self) { _ in
return GCDWebServerDataResponse(html: self.getPageData("localhostLoad"))
}
webServer.addHandler(forMethod: "GET", path: "/auth.html", request: GCDWebServerRequest.self) { (request: GCDWebServerRequest?) in
// "user:pass", Base64-encoded.
let expectedAuth = "Basic dXNlcjpwYXNz"
let response: GCDWebServerDataResponse
if request?.headers["Authorization"] == expectedAuth && request?.query?["logout"] == nil {
response = GCDWebServerDataResponse(html: "<html><body>logged in</body></html>")!
} else {
// Request credentials if the user isn't logged in.
response = GCDWebServerDataResponse(html: "<html><body>auth fail</body></html>")!
response.statusCode = 401
response.setValue("Basic realm=\"test\"", forAdditionalHeader: "WWW-Authenticate")
}
return response
}
func htmlForImageBlockingTest(imageURL: String) -> String{
let html =
"""
<html><head><script>
function testImage(URL) {
var tester = new Image();
tester.onload = imageFound;
tester.onerror = imageNotFound;
tester.src = URL;
document.body.appendChild(tester);
}
function imageFound() {
alert('image loaded.');
}
function imageNotFound() {
alert('image not loaded.');
}
window.onload = function(e) {
// Disabling TP stats reporting using JS execution on the wkwebview happens async;
// setTimeout(1 sec) is plenty of delay to ensure the JS has executed.
setTimeout(() => { testImage('\(imageURL)'); }, 1000);
}
</script></head>
<body>TEST IMAGE BLOCKING</body></html>
"""
return html
}
// Add tracking protection check page
webServer.addHandler(forMethod: "GET", path: "/tracking-protection-test.html", request: GCDWebServerRequest.self) { (request: GCDWebServerRequest?) in
return GCDWebServerDataResponse(html: htmlForImageBlockingTest(imageURL: "http://ymail.com/favicon.ico"))
}
// Add image blocking test page
webServer.addHandler(forMethod: "GET", path: "/hide-images-test.html", request: GCDWebServerRequest.self) { (request: GCDWebServerRequest?) in
return GCDWebServerDataResponse(html: htmlForImageBlockingTest(imageURL: "https://www.mozilla.com/favicon.ico"))
}
if !webServer.start(withPort: 0, bonjourName: nil) {
XCTFail("Can't start the GCDWebServer")
}
// We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our
// history exclusion code (Bug 1188626).
let webRoot = "http://\(useLocalhostInsteadOfIP ? "localhost" : "127.0.0.1"):\(webServer.port)"
return webRoot
}
}
class SearchUtils {
static func navigateToSearchSettings(_ tester: KIFUITestActor) {
let engine = SearchUtils.getDefaultEngine().shortName
tester.tapView(withAccessibilityIdentifier: "TabToolbar.menuButton")
tester.waitForAnimationsToFinish()
tester.tapView(withAccessibilityLabel: "Settings")
tester.waitForView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityLabel: "Search, \(engine)")
tester.waitForView(withAccessibilityIdentifier: "Search")
}
static func navigateFromSearchSettings(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityLabel: "Done")
}
// Given that we're at the Search Settings sheet, select the named search engine as the default.
// Afterwards, we're still at the Search Settings sheet.
static func selectDefaultSearchEngineName(_ tester: KIFUITestActor, engineName: String) {
tester.tapView(withAccessibilityLabel: "Default Search Engine", traits: UIAccessibilityTraits.button)
tester.waitForView(withAccessibilityLabel: "Default Search Engine")
tester.tapView(withAccessibilityLabel: engineName)
tester.waitForView(withAccessibilityLabel: "Search")
}
// Given that we're at the Search Settings sheet, return the default search engine's name.
static func getDefaultSearchEngineName(_ tester: KIFUITestActor) -> String {
let view = tester.waitForCellWithAccessibilityLabel("Default Search Engine")
return view.accessibilityValue!
}
static func getDefaultEngine() -> OpenSearchEngine! {
guard let userProfile = (UIApplication.shared.delegate as? AppDelegate)?.profile else {
XCTFail("Unable to get a reference to the user's profile")
return nil
}
return userProfile.searchEngines.defaultEngine
}
/*
static func youTubeSearchEngine() -> OpenSearchEngine {
return mockSearchEngine("YouTube", template: "https://m.youtube.com/#/results?q={searchTerms}&sm=", icon: "youtube")!
}
static func mockSearchEngine(_ name: String, template: String, icon: String) -> OpenSearchEngine? {
guard let imagePath = Bundle(for: self).path(forResource: icon, ofType: "ico"),
let imageData = Data(contentsOfFile: imagePath),
let image = UIImage(data: imageData) else {
XCTFail("Unable to load search engine image named \(icon).ico")
return nil
}
return OpenSearchEngine(engineID: nil, shortName: name, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true)
}
*/
static func addCustomSearchEngine(_ engine: OpenSearchEngine) {
guard let userProfile = (UIApplication.shared.delegate as? AppDelegate)?.profile else {
XCTFail("Unable to get a reference to the user's profile")
return
}
userProfile.searchEngines.addSearchEngine(engine)
}
static func removeCustomSearchEngine(_ engine: OpenSearchEngine) {
guard let userProfile = (UIApplication.shared.delegate as? AppDelegate)?.profile else {
XCTFail("Unable to get a reference to the user's profile")
return
}
userProfile.searchEngines.deleteCustomEngine(engine)
}
}
// From iOS 10, below methods no longer works
class DynamicFontUtils {
// Need to leave time for the notification to propagate
static func bumpDynamicFontSize(_ tester: KIFUITestActor) {
let value = UIContentSizeCategory.accessibilityExtraLarge
UIApplication.shared.setValue(value, forKey: "preferredContentSizeCategory")
tester.wait(forTimeInterval: 0.3)
}
static func lowerDynamicFontSize(_ tester: KIFUITestActor) {
let value = UIContentSizeCategory.extraSmall
UIApplication.shared.setValue(value, forKey: "preferredContentSizeCategory")
tester.wait(forTimeInterval: 0.3)
}
static func restoreDynamicFontSize(_ tester: KIFUITestActor) {
let value = UIContentSizeCategory.medium
UIApplication.shared.setValue(value, forKey: "preferredContentSizeCategory")
tester.wait(forTimeInterval: 0.3)
}
}
class PasscodeUtils {
static func resetPasscode() {
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(nil)
}
static func setPasscode(_ code: String, interval: PasscodeInterval) {
let info = AuthenticationKeychainInfo(passcode: code)
info.updateRequiredPasscodeInterval(interval)
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(info)
}
static func enterPasscode(_ tester: KIFUITestActor, digits: String) {
tester.tapView(withAccessibilityLabel: String(digits[digits.startIndex]))
tester.tapView(withAccessibilityLabel: String(digits[digits.index(digits.startIndex, offsetBy: 1)]))
tester.tapView(withAccessibilityLabel: String(digits[digits.index(digits.startIndex, offsetBy: 2)]))
tester.tapView(withAccessibilityLabel: String(digits[digits.index(digits.startIndex, offsetBy: 3)]))
}
}
class HomePageUtils {
static func navigateToHomePageSettings(_ tester: KIFUITestActor) {
tester.waitForAnimationsToFinish()
tester.tapView(withAccessibilityIdentifier: "TabToolbar.menuButton")
tester.tapView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityIdentifier: "Homepage")
}
static func homePageSetting(_ tester: KIFUITestActor) -> String? {
let view = tester.waitForView(withAccessibilityIdentifier: "HomeAsCustomURLTextField")
guard let textField = view as? UITextField else {
XCTFail("View is not a textField: view is \(String(describing: view))")
return nil
}
return textField.text
}
static func navigateFromHomePageSettings(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityLabel: "Done")
}
}