This repository was archived by the owner on Feb 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathFindInPageTests.swift
557 lines (503 loc) · 31.2 KB
/
FindInPageTests.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
//
// FindInPageTests.swift
//
// Copyright © 2024 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
class FindInPageTests: UITestCase {
private var app: XCUIApplication!
private var addressBarTextField: XCUIElement!
private var loremIpsumWebView: XCUIElement!
private var findInPageCloseButton: XCUIElement!
private let minimumExpectedMatchingPixelsInFindHighlight = 150
override class func setUp() {
super.setUp()
UITests.firstRun()
saveLocalHTML()
}
override class func tearDown() {
super.tearDown()
removeLocalHTML()
}
override func setUpWithError() throws {
continueAfterFailure = false
app = XCUIApplication()
app.launchEnvironment["UITEST_MODE"] = "1"
addressBarTextField = app.windows.textFields["AddressBarViewController.addressBarTextField"]
loremIpsumWebView = app.windows.webViews["Lorem Ipsum"]
findInPageCloseButton = app.windows.buttons["FindInPageController.closeButton"]
app.launch()
app.typeKey("w", modifierFlags: [.command, .option, .shift]) // Let's enforce a single window
app.typeKey("n", modifierFlags: .command)
}
func test_findInPage_canBeOpenedWithKeyCommand() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
}
func test_findInPage_canBeOpenedWithMenuBarItem() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
let findInPageMenuBarItem = app.menuItems["MainMenu.findInPage"]
XCTAssertTrue(
findInPageMenuBarItem.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find in Page\" main menu bar item in a reasonable timeframe."
)
findInPageMenuBarItem.click()
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" via the menu items Edit->Find->\"Find in Page\", the elements of the \"Find in Page\" interface should exist."
)
}
func test_findInPage_canBeOpenedWithMoreOptionsMenuItem() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
let optionsButton = app.windows.buttons["NavigationBarViewController.optionsButton"]
optionsButton.clickAfterExistenceTestSucceeds()
let findInPageMoreOptionsMenuItem = app.menuItems["MoreOptionsMenu.findInPage"]
XCTAssertTrue(
findInPageMoreOptionsMenuItem.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find More Options \"Find in Page\" menu item in a reasonable timeframe."
)
findInPageMoreOptionsMenuItem.click()
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" via the More Options \"Find in Page\" menu item, the elements of the \"Find in Page\" interface should exist."
)
}
func test_findInPage_canBeClosedWithEscape() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(
findInPageCloseButton.waitForNonExistence(timeout: UITests.Timeouts.elementExistence),
"After closing \"Find in Page\" with escape, the elements of the \"Find in Page\" interface should no longer exist."
)
}
func test_findInPage_canBeClosedWithShiftCommandF() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
app.typeKey("f", modifierFlags: [.command, .shift])
XCTAssertTrue(
findInPageCloseButton.waitForNonExistence(timeout: UITests.Timeouts.elementExistence),
"After closing \"Find in Page\" with escape, the elements of the \"Find in Page\" interface should no longer exist."
)
}
func test_findInPage_canBeClosedWithHideFindMenuItem() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
let findInPageDoneMenuBarItem = app.menuItems["MainMenu.findInPageDone"]
XCTAssertTrue(
findInPageDoneMenuBarItem.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find in Page\" done main menu item in a reasonable timeframe."
)
findInPageDoneMenuBarItem.click()
XCTAssertTrue(
findInPageCloseButton.waitForNonExistence(timeout: UITests.Timeouts.elementExistence),
"After closing \"Find in Page\" with escape, the elements of the \"Find in Page\" interface should no longer exist."
)
}
func test_findInPage_showsCorrectNumberOfOccurrences() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
app.typeText("maximus\r")
let statusField = app.textFields["FindInPageController.statusField"]
XCTAssertTrue(
statusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find in Page\" statusField in a reasonable timeframe."
)
let statusFieldTextContent = try XCTUnwrap(statusField.value as? String)
XCTAssertEqual(statusFieldTextContent, "1 of 4") // Note: this is not a localized test element, and it should have a localization strategy.
}
func test_findInPage_showsFocusAndOccurrenceHighlighting() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
app.typeText("maximus\r")
let statusField = app.textFields["FindInPageController.statusField"]
XCTAssertTrue(
statusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find in Page\" statusField in a reasonable timeframe."
)
let statusFieldTextContent = try XCTUnwrap(statusField.value as? String)
// Note: the following is not a localized test element, but it should have a localization strategy.
XCTAssertEqual(statusFieldTextContent, "1 of 4", "Unexpected status field text content after a \"Find in Page\" operation.")
let webViewWithSelectedWordsScreenshot = loremIpsumWebView.screenshot()
let highlightedPixelsInScreenshot = try XCTUnwrap(webViewWithSelectedWordsScreenshot.image.matchingPixels(of: .findHighlightColor))
XCTAssertGreaterThan(
highlightedPixelsInScreenshot.count,
minimumExpectedMatchingPixelsInFindHighlight,
"There are expected to be more than \(minimumExpectedMatchingPixelsInFindHighlight) pixels of NSColor.findHighlightColor in a screenshot of a \"Find in Page\" search where there is a match, but this test found \(highlightedPixelsInScreenshot) matching pixels."
)
}
func test_findNext_menuItemGoesToNextOccurrence() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
app.typeText("maximus\r")
let statusField = app.textFields["FindInPageController.statusField"]
XCTAssertTrue(
statusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find in Page\" statusField in a reasonable timeframe."
)
let statusFieldTextContent = try XCTUnwrap(statusField.value as? String)
// Note: the following is not a localized test element, but it should have a localization strategy.
XCTAssertEqual(statusFieldTextContent, "1 of 4", "Unexpected status field text content after a \"Find in Page\" operation.")
let findInPageScreenshot = loremIpsumWebView.screenshot()
let highlightedPixelsInFindScreenshot = try XCTUnwrap(findInPageScreenshot.image.matchingPixels(of: .findHighlightColor))
let findHighlightPoints = Set(highlightedPixelsInFindScreenshot.map { $0.point }) // Coordinates of highlighted pixels in the find screenshot
let findNextMenuBarItem = app.menuItems["MainMenu.findNext"]
XCTAssertTrue(
findNextMenuBarItem.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find Next\" main menu bar item in a reasonable timeframe."
)
findNextMenuBarItem.click()
let updatedStatusField = app.textFields["FindInPageController.statusField"]
let updatedStatusFieldTextContent = updatedStatusField.value as! String
XCTAssertTrue(
updatedStatusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find the updated \"Find in Page\" statusField in a reasonable timeframe."
)
XCTAssertEqual(updatedStatusFieldTextContent, "2 of 4", "Unexpected status field text content after a \"Find Next\" operation.")
let findNextScreenshot = loremIpsumWebView.screenshot()
let highlightedPixelsInFindNextScreenshot =
try XCTUnwrap(Set(findNextScreenshot.image
.matchingPixels(of: .findHighlightColor))) // Coordinates of highlighted pixels in the find next screenshot
let findNextHighlightPoints = highlightedPixelsInFindNextScreenshot.map { $0.point }
let pixelSetIntersection = findHighlightPoints
.intersection(findNextHighlightPoints) // If the highlighted text has moved as expected, this should not have many elements
XCTAssertGreaterThan(
highlightedPixelsInFindNextScreenshot.count,
minimumExpectedMatchingPixelsInFindHighlight,
"There are expected to be more than \(minimumExpectedMatchingPixelsInFindHighlight) pixels of NSColor.findHighlightColor in a screenshot of a \"Find in Page\" search where there is a match for a \"Find next\" operation, but this test found \(highlightedPixelsInFindNextScreenshot) matching pixels."
)
XCTAssertTrue(
pixelSetIntersection.count <= findNextHighlightPoints.count / 2,
"When the selection rectangle has moved as expected, fewer than half of the highlighted pixel coordinates from \"Find Next\" should intersect with the highlighted pixel coordinates from the initial \"Find\" operation."
)
}
func test_findNext_nextArrowGoesToNextOccurrence() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
app.typeText("maximus\r")
let statusField = app.textFields["FindInPageController.statusField"]
XCTAssertTrue(
statusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find in Page\" statusField in a reasonable timeframe."
)
let statusFieldTextContent = try XCTUnwrap(statusField.value as? String)
// Note: the following is not a localized test element, but it should have a localization strategy.
XCTAssertEqual(statusFieldTextContent, "1 of 4", "Unexpected status field text content after a \"Find in Page\" operation.")
let findInPageScreenshot = loremIpsumWebView.screenshot()
let highlightedPixelsInFindScreenshot = try XCTUnwrap(findInPageScreenshot.image.matchingPixels(of: .findHighlightColor))
let findHighlightPoints = Set(highlightedPixelsInFindScreenshot.map { $0.point }) // Coordinates of highlighted pixels in the find screenshot
let findInPageNextButton = app.windows.buttons["FindInPageController.nextButton"]
XCTAssertTrue(
findInPageNextButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find Next\" main menu bar item in a reasonable timeframe."
)
findInPageNextButton.click()
let updatedStatusField = app.textFields["FindInPageController.statusField"]
let updatedStatusFieldTextContent = updatedStatusField.value as! String
XCTAssertTrue(
updatedStatusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find the updated \"Find in Page\" statusField in a reasonable timeframe."
)
XCTAssertEqual(updatedStatusFieldTextContent, "2 of 4", "Unexpected status field text content after a \"Find Next\" operation.")
let findNextScreenshot = loremIpsumWebView.screenshot()
let highlightedPixelsInFindNextScreenshot = try XCTUnwrap(findNextScreenshot.image.matchingPixels(of: .findHighlightColor))
let findNextHighlightPoints = highlightedPixelsInFindNextScreenshot.map { $0.point }
let pixelSetIntersection = findHighlightPoints
.intersection(findNextHighlightPoints) // If the highlighted text has moved as expected, this should not have many elements
XCTAssertGreaterThan(
highlightedPixelsInFindNextScreenshot.count,
minimumExpectedMatchingPixelsInFindHighlight,
"There are expected to be more than \(minimumExpectedMatchingPixelsInFindHighlight) pixels of NSColor.findHighlightColor in a screenshot of a \"Find in Page\" search where there is a match, but this test found \(highlightedPixelsInFindNextScreenshot) matching pixels."
)
XCTAssertTrue(
pixelSetIntersection.count <= findNextHighlightPoints.count / 2,
"When the selection rectangle has moved as expected, fewer than half of the highlighted pixel coordinates from \"Find Next\" should intersect with the highlighted pixel coordinates from the initial \"Find\" operation."
)
}
func test_findNext_commandGGoesToNextOccurrence() throws {
XCTAssertTrue(
addressBarTextField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"The Address Bar text field did not exist when it was expected."
)
addressBarTextField.typeURL(Self.loremIpsumFileURL)
XCTAssertTrue(
loremIpsumWebView.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Local \"Lorem Ipsum\" web page didn't load with the expected title in a reasonable timeframe. If this is unexpected, it can also be due to the timeout being too short."
)
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(
findInPageCloseButton.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"After invoking \"Find in Page\" with command-f, the elements of the \"Find in Page\" interface should exist."
)
app.typeText("maximus\r")
let statusField = app.textFields["FindInPageController.statusField"]
XCTAssertTrue(
statusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find \"Find in Page\" statusField in a reasonable timeframe."
)
let statusFieldTextContent = try XCTUnwrap(statusField.value as? String)
// Note: the following is not a localized test element, but it should have a localization strategy.
XCTAssertEqual(statusFieldTextContent, "1 of 4", "Unexpected status field text content after a \"Find in Page\" operation.")
let findInPageScreenshot = loremIpsumWebView.screenshot()
let highlightedPixelsInFindScreenshot = try XCTUnwrap(findInPageScreenshot.image.matchingPixels(of: .findHighlightColor))
let findHighlightPoints = Set(highlightedPixelsInFindScreenshot.map { $0.point }) // Coordinates of highlighted pixels in the find screenshot
app.typeKey("g", modifierFlags: [.command])
let updatedStatusField = app.textFields["FindInPageController.statusField"]
let updatedStatusFieldTextContent = updatedStatusField.value as! String
XCTAssertTrue(
updatedStatusField.waitForExistence(timeout: UITests.Timeouts.elementExistence),
"Couldn't find the updated \"Find in Page\" statusField in a reasonable timeframe."
)
XCTAssertEqual(updatedStatusFieldTextContent, "2 of 4", "Unexpected status field text content after a \"Find Next\" operation.")
let findNextScreenshot = loremIpsumWebView.screenshot()
let highlightedPixelsInFindNextScreenshot = try XCTUnwrap(findNextScreenshot.image.matchingPixels(of: .findHighlightColor))
let findNextHighlightPoints = highlightedPixelsInFindNextScreenshot.map { $0.point }
let pixelSetIntersection = findHighlightPoints
.intersection(findNextHighlightPoints) // If the highlighted text has moved as expected, this should not have many elements
XCTAssertGreaterThan(
highlightedPixelsInFindNextScreenshot.count,
minimumExpectedMatchingPixelsInFindHighlight,
"There are expected to be more than \(minimumExpectedMatchingPixelsInFindHighlight) pixels of NSColor.findHighlightColor in a screenshot of a \"Find in Page\" search where there is a match, but this test found \(highlightedPixelsInFindNextScreenshot) matching pixels."
)
XCTAssertTrue(
pixelSetIntersection.count <= findNextHighlightPoints.count / 2,
"When the selection rectangle has moved as expected, fewer than half of the highlighted pixel coordinates from \"Find Next\" should intersect with the highlighted pixel coordinates from the initial \"Find\" operation."
)
}
}
/// Helpers for the Find in Page tests
private extension FindInPageTests {
/// A shared URL to reference the local HTML file
class var loremIpsumFileURL: URL {
let loremIpsumFileName = "lorem_ipsum.html"
XCTAssertNotNil(
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
"It wasn't possible to obtain a local file URL for the sandbox Documents directory."
)
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let loremIpsumHTMLFileURL = documentsDirectory.appendingPathComponent(loremIpsumFileName)
return loremIpsumHTMLFileURL
}
/// Save a local HTML file for testing find behavor against
class func saveLocalHTML() {
let loremIpsumHTML = """
<html><head>
<title>Lorem Ipsum</title></head><body><table><tr><td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ac sem nisi. Cras fermentum mi vitae turpis efficitur malesuada. Donec eget maxima ligula, et tincidunt sapien. Suspendisse posuere diam maxima, dignissim ex at, fringilla elit. Maecenas enim tellus, ornare non pretium a, sodales nec lectus. Vestibulum quis augue orci. Donec eget mi sed magna consequat auctor a a nulla. Etiam condimentum, neque at congue semper, arcu sem commodo tellus, venenatis finibus ex magna vitae erat. Nunc non enim sit amet mi posuere egestas. Donec nibh nisl, pretium sit amet aliquet, porta id nibh. Pellentesque ullamcorper mauris quam, semper hendrerit mi dictum non. Nullam pulvinar, nulla a maximus egestas, velit mi volutpat neque, vitae placerat eros sapien vitae tellus. Pellentesque malesuada accumsan dolor, ut feugiat enim. Curabitur nunc quam, maximus venenatis augue vel, accumsan eros.</p>
<p>Donec consequat ultrices ante non maximus. Quisque eu semper diam. Nunc ullamcorper eget ex id luctus. Duis metus ex, dapibus sit amet vehicula eget, rhoncus eget lacus. Nulla maximus quis turpis vel pulvinar. Duis neque ligula, tristique et diam ut, fringilla sagittis arcu. Vestibulum suscipit semper lectus, quis placerat ex euismod eu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae;</p>
<p>Maecenas odio orci, eleifend et ipsum nec, interdum dictum turpis. Nunc nec velit diam. Sed nisl risus, imperdiet sit amet tempor ut, laoreet sed lorem. Aenean egestas ullamcorper sem. Sed accumsan vehicula augue, vitae tempor augue tincidunt id. Morbi ullamcorper posuere lacus id tempus. Ut vel tincidunt quam, quis consectetur velit. Mauris id lorem vitae odio consectetur vehicula. Vestibulum viverra scelerisque porta. Vestibulum eu consequat urna. Etiam dignissim ullamcorper faucibus.</p></td></tr></table></body></html>
"""
let loremIpsumData = Data(loremIpsumHTML.utf8)
do {
try loremIpsumData.write(to: loremIpsumFileURL, options: [])
} catch {
XCTFail("It wasn't possible to write out the required local HTML file for the tests: \(error.localizedDescription)")
}
}
/// Remove it when done
class func removeLocalHTML() {
do {
try FileManager.default.removeItem(at: loremIpsumFileURL)
} catch {
XCTFail("It wasn't possible to remove the required local HTML file for the tests: \(error.localizedDescription)")
}
}
}
private extension UInt8 {
func isCloseTo(_ colorValue: UInt8) -> Bool {
// Overflow-safe creation of range +/- 1 around value
let lowerBound: UInt8 = self != 0 ? self &- 1 : 0
let upperBound: UInt8 = self != 255 ? self &+ 1 : 255
switch colorValue {
case lowerBound ... upperBound:
return true
default:
return false
}
}
}
private extension NSImage {
/// Find matching pixels in an NSImage for a specific NSColor
/// - Parameter colorToMatch: the NSColor to match
/// - Returns: An array of Pixel structs
func matchingPixels(of colorToMatch: NSColor) throws -> [Pixel] {
let cgImage = try XCTUnwrap(
cgImage(forProposedRect: nil, context: nil, hints: nil),
"It wasn't possible to obtain the CGImage of the NSImage."
)
let bitmap = NSBitmapImageRep(cgImage: cgImage)
let colorSpace = bitmap.colorSpace
let colorToMatchWithColorSpace = try XCTUnwrap(
colorToMatch.usingColorSpace(colorSpace),
"It wasn't possible to get the color to match in the local colorspace."
) // Compare the color we want to look for in the image after it is in the same colorspace as the image
var bitmapData: UnsafeMutablePointer<UInt8> = try XCTUnwrap(bitmap.bitmapData, "It wasn't possible to obtain the bitmapData of the bitmap.")
var redInImage, greenInImage, blueInImage, alphaInImage: UInt8
let redToMatch = UInt8(colorToMatchWithColorSpace.redComponent * 255.999999) // color components in 0-255 values in this colorspace
let greenToMatch = UInt8(colorToMatchWithColorSpace.greenComponent * 255.999999)
let blueToMatch = UInt8(colorToMatchWithColorSpace.blueComponent * 255.999999)
var pixels: [Pixel] = []
for yPoint in 0 ..< bitmap.pixelsHigh {
for xPoint in 0 ..< bitmap.pixelsWide {
redInImage = bitmapData.pointee
bitmapData = bitmapData.advanced(by: 1)
greenInImage = bitmapData.pointee
bitmapData = bitmapData.advanced(by: 1)
blueInImage = bitmapData.pointee
bitmapData = bitmapData.advanced(by: 1)
alphaInImage = bitmapData.pointee
bitmapData = bitmapData.advanced(by: 1)
if redInImage.isCloseTo(redToMatch), greenInImage.isCloseTo(greenToMatch),
blueInImage.isCloseTo(blueToMatch)
{ // We aren't matching alpha
pixels.append(Pixel(
red: redInImage,
green: greenInImage,
blue: blueInImage,
alpha: alphaInImage,
point: CGPoint(x: xPoint, y: yPoint)
))
}
}
}
return pixels
}
}
/// A struct of pixel color and coordinate values in 0-255 color values
private struct Pixel: Hashable {
var red: UInt8
var green: UInt8
var blue: UInt8
var alpha: UInt8
var point: CGPoint
}
extension CGPoint: Hashable {
/// So we can do set operations with sets of CGPoints
public func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}