-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
testlib.py
2808 lines (2348 loc) · 113 KB
/
testlib.py
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Cockpit.
#
# Copyright (C) 2013 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <https://www.gnu.org/licenses/>.
"""Tools for writing Cockpit test cases."""
import argparse
import asyncio
import base64
import contextlib
import errno
import fnmatch
import glob
import io
import json
import logging
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import unittest
from collections.abc import Collection, Container, Coroutine, Iterator, Mapping, Sequence
from pathlib import Path
from typing import Any, Callable, ClassVar, Literal, TypedDict, TypeVar
import webdriver_bidi
from lcov import write_lcov
from lib.constants import OSTREE_IMAGES
from machine import testvm
from PIL import Image
_T = TypeVar('_T')
_FT = TypeVar("_FT", bound=Callable[..., Any])
JsonObject = dict[str, Any]
BASE_DIR = os.path.realpath(f'{__file__}/../../..')
TEST_DIR = f'{BASE_DIR}/test'
BOTS_DIR = f'{BASE_DIR}/bots'
os.environ["PATH"] = f"{os.environ.get('PATH')}:{BOTS_DIR}:{TEST_DIR}"
# Be careful when changing this string, check in cockpit-project/bots where it is being used
UNEXPECTED_MESSAGE = "FAIL: Test completed, but found unexpected "
PIXEL_TEST_MESSAGE = "Some pixel tests have failed"
__all__ = (
'PIXEL_TEST_MESSAGE',
'TEST_DIR',
'UNEXPECTED_MESSAGE',
'Browser',
'Error',
'MachineCase',
'arg_parser',
'destructive',
'no_retry_when_changed',
'nondestructive',
'onlyImage',
'opts',
'sit',
'skipBrowser',
'skipImage',
'skipOstree',
'test_main',
'timeout',
'todo',
'wait',
)
# Command line options
opts = argparse.Namespace()
opts.sit = False
opts.trace = False
opts.attachments = None
opts.revision = None
opts.address = None
opts.jobs = 1
opts.fetch = True
opts.coverage = False
# https://w3c.github.io/webdriver/#keyboard-actions for encoding key names
WEBDRIVER_KEYS = {
"Backspace": "\uE003",
"Tab": "\uE004",
"Return": "\uE006",
"Enter": "\uE007",
"Shift": "\uE008",
"Control": "\uE009",
"Alt": "\uE00A",
"Escape": "\uE00C",
"ArrowLeft": "\uE012",
"ArrowUp": "\uE013",
"ArrowRight": "\uE014",
"ArrowDown": "\uE015",
"Insert": "\uE016",
"Delete": "\uE017",
"Meta": "\uE03D",
"F2": "\uE032",
}
# Browser layouts
#
# A browser can be switched into a number of different layouts, such
# as "desktop" and "mobile". A default set of layouts is defined
# here, but projects can override this with a file called
# "test/browser-layouts.json".
#
# Each layout defines the size of the shell (where the main navigation
# is) and also the size of the content iframe (where the actual page
# like "Networking" or "Overview" is displayed).
#
# When the browser layout is switched (by calling Browset.set_layout),
# this will either set the shell size or the content size, depending
# on which frame is current (as set by Browser.enter_page or
# Browser.leave_page).
#
# This makes sure that pixel tests for the whole content iframe are
# always the exact size as specified in the layout definition, and
# don't change size when the navigation stuff in the shell changes.
#
# The browser starts out in the first layout of this list, which is
# "desktop" by default.
class BrowserLayout(TypedDict):
name: str
theme: Literal["light"] | Literal["dark"]
shell_size: tuple[int, int]
content_size: tuple[int, int]
default_layouts: Sequence[BrowserLayout] = (
{
"name": "desktop",
"theme": "light",
"shell_size": (1920, 1200),
"content_size": (1680, 1130)
},
{
"name": "medium",
"theme": "light",
"shell_size": (1280, 768),
"content_size": (1040, 698)
},
{
"name": "mobile",
"theme": "light",
"shell_size": (414, 1920),
"content_size": (414, 1856)
},
{
"name": "dark",
"theme": "dark",
"shell_size": (1920, 1200),
"content_size": (1680, 1130)
},
{
"name": "rtl",
"theme": "light",
"shell_size": (1920, 1200),
"content_size": (1680, 1130)
},
)
def attach(filename: str, move: bool = False) -> None:
"""Put a file into the attachments directory.
:param filename: file to put in attachments directory
:param move: set this to true to move dynamically generated files which
are not touched by destructive tests. (default False)
"""
if not opts.attachments:
return
dest = os.path.join(opts.attachments, os.path.basename(filename))
if os.path.exists(filename) and not os.path.exists(dest):
if move:
shutil.move(filename, dest)
else:
shutil.copy(filename, dest)
def unique_filename(base: str, ext: str) -> str:
for i in range(20):
if i == 0:
f = f"{base}.{ext}"
else:
f = f"{base}-{i}.{ext}"
if not os.path.exists(f):
return f
return f"{base}.{ext}"
class Browser:
driver: webdriver_bidi.WebdriverBidi
browser: str
layouts: Sequence[BrowserLayout]
current_layout: BrowserLayout | None
port: str | int
def __init__(
self,
address: str,
label: str,
machine: 'MachineCase',
pixels_label: str | None = None,
coverage_label: str | None = None,
port: int | str | None = None
) -> None:
if ":" in address:
self.address, _, self.port = address.rpartition(":")
else:
self.address = address
self.port = 9090
if port is not None:
self.port = port
self.default_user = "admin"
self.label = label
self.pixels_label = pixels_label
self.used_pixel_references = set[str]()
self.coverage_label = coverage_label
self.machine = machine
headless = os.environ.get("TEST_SHOW_BROWSER", '0') == '0'
self.browser = os.environ.get("TEST_BROWSER", "chromium")
if self.browser == "chromium":
self.driver = webdriver_bidi.ChromiumBidi(headless=headless)
elif self.browser == "firefox":
self.driver = webdriver_bidi.FirefoxBidi(headless=headless)
else:
raise ValueError(f"unknown browser {self.browser}")
self.loop = asyncio.new_event_loop()
self.bidi_thread = threading.Thread(target=self.asyncio_loop_thread, args=(self.loop,))
self.bidi_thread.start()
self.run_async(self.driver.start_session())
if opts.trace:
logging.basicConfig(level=logging.INFO)
webdriver_bidi.log_command.setLevel(logging.INFO if opts.trace else logging.WARNING)
# not appropriate for --trace, just enable for debugging low-level protocol with browser
# webdriver_bidi.log_proto.setLevel(logging.DEBUG)
test_functions = (Path(__file__).parent / "test-functions.js").read_text()
# Don't redefine globals, this confuses Firefox
test_functions = "if (window.ph_select) return; " + test_functions
self.bidi("script.addPreloadScript", quiet=True, functionDeclaration=f"() => {{ {test_functions} }}")
try:
sizzle_js = (Path(__file__).parent.parent.parent / "node_modules/sizzle/dist/sizzle.js").read_text()
# HACK: injecting sizzle fails on missing `document` in assert()
sizzle_js = sizzle_js.replace('function assert( fn ) {',
'function assert( fn ) { if (true) return true; else ')
# HACK: sizzle tracks document and when we switch frames, it sees the old document
# although we execute it in different context.
sizzle_js = sizzle_js.replace('context = context || document;', 'context = context || window.document;')
self.bidi("script.addPreloadScript", quiet=True, functionDeclaration=f"() => {{ {sizzle_js} }}")
except FileNotFoundError:
pass
if coverage_label:
self.cdp_command("Profiler.enable")
self.cdp_command("Profiler.startPreciseCoverage", callCount=False, detailed=True)
self.password = "foobar"
self.timeout_factor = int(os.getenv("TEST_TIMEOUT_FACTOR", "1"))
self.timeout = 15
self.failed_pixel_tests = 0
self.allow_oops = False
try:
with open(f'{TEST_DIR}/browser-layouts.json') as fp:
self.layouts = json.load(fp)
except FileNotFoundError:
self.layouts = default_layouts
self.current_layout = None
self.valid = True
def run_async(self, coro: Coroutine[Any, Any, Any]) -> JsonObject:
"""Run coro in main loop in our BiDi thread
Wait for the result and return it.
"""
return asyncio.run_coroutine_threadsafe(coro, self.loop).result()
@staticmethod
def asyncio_loop_thread(loop: asyncio.AbstractEventLoop) -> None:
asyncio.set_event_loop(loop)
loop.run_forever()
def kill(self) -> None:
if not self.valid:
return
self.run_async(self.driver.close())
self.loop.call_soon_threadsafe(self.loop.stop)
self.bidi_thread.join()
self.valid = False
def bidi(self, method: str, **params: Any) -> webdriver_bidi.JsonObject:
"""Send a Webdriver BiDi command and return the JSON response"""
try:
return self.run_async(self.driver.bidi(method, **params))
except webdriver_bidi.WebdriverError as e:
raise Error(str(e)) from None
def cdp_command(self, method: str, **params: Any) -> webdriver_bidi.JsonObject:
"""Send a Chrome DevTools Protocol command and return the JSON response"""
if self.browser == "chromium":
assert isinstance(self.driver, webdriver_bidi.ChromiumBidi)
return self.run_async(self.driver.cdp(method, **params))
else:
raise webdriver_bidi.WebdriverError("CDP is only supported in Chromium")
def open(self, href: str, cookie: Mapping[str, str] | None = None, tls: bool = False) -> None:
"""Load a page into the browser.
:param href: the path of the Cockpit page to load, such as "/users". Either PAGE or URL needs to be given.
:param cookie: a dictionary object representing a cookie.
:param tls: load the page using https (default False)
Raises:
Error: When a timeout occurs waiting for the page to load.
"""
if href.startswith("/"):
schema = "https" if tls else "http"
href = "%s://%s:%s%s" % (schema, self.address, self.port, href)
if not self.current_layout and os.environ.get("TEST_SHOW_BROWSER") in [None, "pixels"]:
self.current_layout = self.layouts[0]
size = self.current_layout["shell_size"]
self._set_window_size(size[0], size[1])
if cookie:
c = {**cookie, "value": {"type": "string", "value": cookie["value"]}}
self.bidi("storage.setCookie", cookie=c)
self.switch_to_top()
# Some browsers optimize this away if the current URL is already href
# (e.g. in TestKeys.testAuthorizedKeys). Load the blank page first to always
# force a load.
self.bidi("browsingContext.navigate", context=self.driver.context, url="about:blank", wait="complete")
self.bidi("browsingContext.navigate", context=self.driver.context, url=href, wait="complete")
def set_user_agent(self, ua: str) -> None:
"""Set the user agent of the browser
:param ua: user agent string
:type ua: str
"""
if self.browser == "chromium":
self.cdp_command("Emulation.setUserAgentOverride", userAgent=ua)
else:
raise NotImplementedError
def reload(self, ignore_cache: bool = False) -> None:
"""Reload the current page
:param ignore_cache: if true browser cache is ignored (default False)
:type ignore_cache: bool
"""
self.switch_to_top()
self.wait_js_cond("ph_select('iframe.container-frame').every(e => e.getAttribute('data-loaded'))")
if self.browser == "firefox":
if ignore_cache:
webdriver_bidi.log_command.warning(
"Browser.reload(): ignore_cache==True not yet supported with Firefox, ignoring")
self.bidi("browsingContext.reload", context=self.driver.context, wait="complete")
else:
self.bidi("browsingContext.reload", context=self.driver.context, ignoreCache=ignore_cache,
wait="complete")
self.machine.allow_restart_journal_messages()
def switch_to_frame(self, name: str | None) -> None:
"""Switch to frame in browser tab
Each page has a main frame and can have multiple subframes, usually
iframes.
:param name: frame name
"""
if name is None:
self.switch_to_top()
else:
self.run_async(self.driver.switch_to_frame(name))
def switch_to_top(self) -> None:
"""Switch to the main frame
Switch to the main frame from for example an iframe.
"""
self.driver.switch_to_top()
def allow_download(self) -> None:
"""Allow browser downloads"""
# this is only necessary for headless chromium
if self.browser == "chromium":
self.cdp_command("Browser.setDownloadBehavior", behavior="allow", downloadPath=str(self.driver.download_dir))
def upload_files(self, selector: str, files: Sequence[str]) -> None:
"""Upload a local file to the browser
The selector should select the <input type="file"/> element.
Files is a list of absolute paths to files which should be uploaded.
"""
element = self.eval_js(f"ph_find({jsquote(selector)})")
self.bidi("input.setFiles", context=self.driver.context, element=element, files=files)
def eval_js(self, code: str, no_trace: bool = False) -> Any:
"""Execute JS code that returns something
:param code: a string containing JavaScript code
:param no_trace: do not print information about unknown return values (default False)
"""
return self.bidi("script.evaluate", expression=code, quiet=no_trace,
awaitPromise=True, target={"context": self.driver.context})["result"]
def call_js_func(self, func: str, *args: object) -> Any:
"""Call a JavaScript function
:param func: JavaScript function to call
:param args: arguments for the JavaScript function
"""
return self.eval_js("%s(%s)" % (func, ','.join(map(jsquote, args))))
def set_mock(self, mock: Mapping[str, str], base: str = "") -> None:
"""Replace some DOM elements with mock text
The 'mock' parameter is a dictionary from CSS selectors to the
text that the elements matching the selector should be
replaced with.
XXX - There is no way to easily undo the effects of this
function. There is no coordination with React. This
will improve as necessary.
:param mock: the mock data, see above
:param base: if given, all selectors are relative to this one
"""
self.call_js_func('ph_set_texts', {base + " " + k: v for k, v in mock.items()})
def cookie(self, name: str) -> Mapping[str, object] | None:
"""Retrieve a browser cookie by name
:param name: the name of the cookie
:type name: str
"""
cookies = self.bidi("storage.getCookies", filter={"name": name})["cookies"]
if len(cookies) > 0:
c = cookies[0]
# if we ever need to handle "base64", add that
assert c["value"]["type"] == "string"
c["value"] = c["value"]["value"]
return c
return None
def go(self, url_hash: str) -> None:
self.call_js_func('ph_go', url_hash)
def mouse(
self,
selector: str,
event: str,
x: int = 0,
y: int = 0,
btn: int = 0,
*,
ctrlKey: bool = False,
shiftKey: bool = False,
altKey: bool = False,
metaKey: bool = False
) -> None:
"""Simulate a browser mouse event
:param selector: the element to interact with
:param type: the mouse event to simulate, for example mouseenter, mouseleave, mousemove, click
:param x: the x coordinate
:param y: the y coordinate
:param btn: mouse button to click https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
:param crtlKey: press the ctrl key
:param shiftKey: press the shift key
:param altKey: press the alt key
:param metaKey: press the meta key
"""
self.wait_visible(selector)
# HACK: Chromium clicks don't work with iframes; use our old "synthesize MouseEvent" approach
# https://issues.chromium.org/issues/359616812
# TODO: x and y are not currently implemented: webdriver (0, 0) is the element's center, not top left corner
if self.browser == "chromium" or x != 0 or y != 0:
self.call_js_func('ph_mouse', selector, event, x, y, btn, ctrlKey, shiftKey, altKey, metaKey)
return
# For Firefox and regular clicks, use the BiDi API, which is more realistic -- it doesn't
# sidestep the browser
element = self.call_js_func('ph_find_scroll_into_view', selector)
# btn=2 for context menus doesn't work with ph_mouse(); so translate the old ph_mouse() API
if event == "contextmenu":
assert btn == 0, "contextmenu event can only be done with default 'btn' value"
btn = 2
event = "click"
actions = [{"type": "pointerMove", "x": 0, "y": 0, "origin": {"type": "element", "element": element}}]
down = {"type": "pointerDown", "button": btn}
up = {"type": "pointerUp", "button": btn}
if event == "click":
actions.extend([down, up])
elif event == "dblclick":
actions.extend([down, up, down, up])
elif event == "mouseenter":
actions.insert(0, {"type": "pointerMove", "x": 0, "y": 0, "origin": "viewport"})
elif event == "mouseleave":
actions.append({"type": "pointerMove", "x": 0, "y": 0, "origin": "viewport"})
else:
raise NotImplementedError(f"unknown event {event}")
# modifier keys
ev_id = f"pointer-{self.driver.last_id}"
keys_pre = []
keys_post = []
def key(type_: str, name: str) -> JsonObject:
return {"type": "key", "id": ev_id + type_, "actions": [{"type": type_, "value": WEBDRIVER_KEYS[name]}]}
if altKey:
keys_pre.append(key("keyDown", "Alt"))
keys_post.append(key("keyUp", "Alt"))
if ctrlKey:
keys_pre.append(key("keyDown", "Control"))
keys_post.append(key("keyUp", "Control"))
if shiftKey:
keys_pre.append(key("keyDown", "Shift"))
keys_post.append(key("keyUp", "Shift"))
if metaKey:
keys_pre.append(key("keyDown", "Meta"))
keys_post.append(key("keyUp", "Meta"))
# the actual mouse event
actions = [{
"id": ev_id,
"type": "pointer",
"parameters": {"pointerType": "mouse"},
"actions": actions,
}]
self.bidi("input.performActions", context=self.driver.context, actions=keys_pre + actions + keys_post)
def click(self, selector: str) -> None:
"""Click on a ui element
:param selector: the selector to click on
"""
self.mouse(selector + ":not([disabled]):not([aria-disabled=true])", "click")
def val(self, selector: str) -> Any:
"""Get the value attribute of a selector.
:param selector: the selector to get the value of
"""
self.wait_visible(selector)
return self.call_js_func('ph_val', selector)
def set_val(self, selector: str, val: object) -> None:
"""Set the value attribute of a non disabled DOM element.
This also emits a change DOM change event.
:param selector: the selector to set the value of
:param val: the value to set
"""
self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
self.call_js_func('ph_set_val', selector, val)
def text(self, selector: str) -> str:
"""Get an element's textContent value.
:param selector: the selector to get the value of
"""
self.wait_visible(selector)
return self.call_js_func('ph_text', selector) or ''
def attr(self, selector: str, attr: str) -> Any:
"""Get the value of a given attribute of an element.
:param selector: the selector to get the attribute of
:param attr: the DOM element attribute
"""
self._wait_present(selector)
return self.call_js_func('ph_attr', selector, attr)
def set_attr(self, selector: str, attr: str, val: object) -> None:
"""Set an attribute value of an element.
:param selector: the selector
:param attr: the element attribute
:param val: the value of the attribute
"""
self._wait_present(selector + ':not([disabled]):not([aria-disabled=true])')
self.call_js_func('ph_set_attr', selector, attr, val)
def get_checked(self, selector: str) -> bool:
"""Get checked state of a given selector.
:param selector: the selector
:return: the checked state
"""
self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
return self.call_js_func('ph_get_checked', selector)
def set_checked(self, selector: str, val: bool) -> None:
"""Set checked state of a given selector.
:param selector: the selector
:param val: boolean value to enable or disable checkbox
"""
# avoid ph_set_checked, that doesn't use proper mouse emulation
checked = self.get_checked(selector)
if checked != val:
self.click(selector)
def focus(self, selector: str) -> None:
"""Set focus on selected element.
:param selector: the selector
"""
self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
self.call_js_func('ph_focus', selector)
def blur(self, selector: str) -> None:
"""Remove keyboard focus from selected element.
:param selector: the selector
"""
self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
self.call_js_func('ph_blur', selector)
def input_text(self, text: str) -> None:
actions = []
for c in text:
# quality-of-life special case
if c == '\n':
c = WEBDRIVER_KEYS["Enter"]
actions.append({"type": "keyDown", "value": c})
actions.append({"type": "keyUp", "value": c})
self.bidi("input.performActions", context=self.driver.context, actions=[
{"type": "key", "id": "key-0", "actions": actions}])
def key(self, name: str, repeat: int = 1, modifiers: list[str] | None = None) -> None:
"""Press and release a named keyboard key.
Use this function to input special characters or modifiers.
:param name: ASCII value or key name like "Enter", "Delete", or "ArrowLeft" (entry in WEBDRIVER_KEYS)
:param repeat: number of times to repeat this key (default 1)
:param modifiers: "Shift", "Control", "Alt"
"""
actions = []
actions_pre = []
actions_post = []
keycode = WEBDRIVER_KEYS.get(name, name)
for m in (modifiers or []):
actions_pre.append({"type": "keyDown", "value": WEBDRIVER_KEYS[m]})
actions_post.append({"type": "keyUp", "value": WEBDRIVER_KEYS[m]})
for _ in range(repeat):
actions.append({"type": "keyDown", "value": keycode})
actions.append({"type": "keyUp", "value": keycode})
self.bidi("input.performActions", context=self.driver.context, actions=[
{"type": "key", "id": "key-0", "actions": actions_pre + actions + actions_post}])
def select_from_dropdown(self, selector: str, value: object) -> None:
"""For an actual <select> HTML component"""
self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
text_selector = f"{selector} option[value='{value}']"
self._wait_present(text_selector)
self.set_val(selector, value)
self.wait_val(selector, value)
def select_PF(self, selector: str, value: str, menu_class: str = ".pf-v5-c-menu") -> None:
"""For a PatternFly Select-like component
For things like <Select> or <TimePicker>. Unfortunately none of them render as an actual <select>, but a
<button> or <div> with a detached menu div (which can even be in the parent).
For similar components like the deprecated <Select> you can specify a different menu class.
"""
self.click(selector)
# SelectOption's value does not render to an actual "value" attribute, just a <li> text
self.click(f"{menu_class} button:contains('{value}')")
self.wait_not_present(menu_class)
def select_PF_deprecated(self, selector: str, value: str) -> None:
"""For the deprecated PatternFly Select component"""
self.select_PF(selector, value, menu_class=".pf-v5-c-select__menu")
def set_input_text(
self, selector: str, val: str, append: bool = False, value_check: bool = True, blur: bool = True
) -> None:
self.focus(selector)
if not append:
self.key("a", modifiers=["Control"])
if val == "":
self.key("Backspace")
else:
self.input_text(val)
if blur:
self.blur(selector)
if value_check:
self.wait_val(selector, val)
def set_file_autocomplete_val(self, group_identifier: str, location: str) -> None:
self.set_input_text(f"{group_identifier} .pf-v5-c-menu-toggle input", location)
# select the file
self.wait_text(f"{group_identifier} ul li:nth-child(1) button", location)
self.click(f"{group_identifier} ul li:nth-child(1) button")
self.wait_not_present(f"{group_identifier} .pf-v5-c-menu")
self.wait_val(f"{group_identifier} .pf-v5-c-menu-toggle input", location)
@contextlib.contextmanager
def wait_timeout(self, timeout: int) -> Iterator[None]:
old_timeout = self.timeout
self.timeout = timeout
yield
self.timeout = old_timeout
def wait(self, predicate: Callable[[], _T | None]) -> _T:
for _ in range(self.timeout * self.timeout_factor * 5):
val = predicate()
if val:
return val
time.sleep(0.2)
raise Error('timed out waiting for predicate to become true')
def wait_js_cond(self, cond: str, error_description: str = "null") -> None:
timeout = self.timeout * self.timeout_factor
start = time.time()
last_error = None
for _retry in range(5):
try:
self.bidi("script.evaluate",
expression=f"ph_wait_cond(() => {cond}, {timeout * 1000}, {error_description})",
awaitPromise=True, timeout=timeout + 5, target={"context": self.driver.context})
duration = time.time() - start
percent = int(duration / timeout * 100)
if percent >= 50:
print(f"WARNING: Waiting for {cond} took {duration:.1f} seconds, which is {percent}% of the timeout.")
return
except Error as e:
last_error = e
# can happen when waiting across page reloads
if any(pattern in str(e) for pattern in [
# during page loading
"is not a function",
# chromium
"Execution context was destroyed",
"Cannot find context",
# firefox
"MessageHandlerFrame' destroyed",
]):
if time.time() - start < timeout:
webdriver_bidi.log_command.info("wait_js_cond: Ignoring/retrying %r", e)
time.sleep(1)
continue
break
assert last_error
# rewrite exception to have more context, also for compatibility with existing naughties
raise Error(f"timeout\nwait_js_cond({cond}): {last_error.msg}") from None
def wait_js_func(self, func: str, *args: object) -> None:
self.wait_js_cond("%s(%s)" % (func, ','.join(map(jsquote, args))))
def is_present(self, selector: str) -> bool:
return self.call_js_func('ph_is_present', selector)
def _wait_present(self, selector: str) -> None:
self.wait_js_func('ph_is_present', selector)
def wait_not_present(self, selector: str) -> None:
self.wait_js_func('!ph_is_present', selector)
def is_visible(self, selector: str) -> bool:
return self.call_js_func('ph_is_visible', selector)
def wait_visible(self, selector: str) -> None:
self._wait_present(selector)
self.wait_js_func('ph_is_visible', selector)
def wait_val(self, selector: str, val: object) -> None:
self.wait_visible(selector)
self.wait_js_func('ph_has_val', selector, val)
def wait_not_val(self, selector: str, val: str) -> None:
self.wait_visible(selector)
self.wait_js_func('!ph_has_val', selector, val)
def wait_attr(self, selector: str, attr: str, val: object) -> None:
self._wait_present(selector)
self.wait_js_func('ph_has_attr', selector, attr, val)
def wait_attr_contains(self, selector: str, attr: str, val: str) -> None:
self._wait_present(selector)
self.wait_js_func('ph_attr_contains', selector, attr, val)
def wait_attr_not_contains(self, selector: str, attr: str, val: object) -> None:
self._wait_present(selector)
self.wait_js_func('!ph_attr_contains', selector, attr, val)
def wait_not_attr(self, selector: str, attr: str, val: object) -> None:
self._wait_present(selector)
self.wait_js_func('!ph_has_attr', selector, attr, val)
def wait_not_visible(self, selector: str) -> None:
self.wait_js_func('!ph_is_visible', selector)
def wait_in_text(self, selector: str, text: str) -> None:
self.wait_visible(selector)
self.wait_js_cond("ph_in_text(%s,%s)" % (jsquote(selector), jsquote(text)),
error_description="() => 'actual text: ' + ph_text(%s)" % jsquote(selector))
def wait_not_in_text(self, selector: str, text: str) -> None:
self.wait_visible(selector)
self.wait_js_func('!ph_in_text', selector, text)
def wait_collected_text(self, selector: str, text: str) -> None:
self.wait_js_func('ph_collected_text_is', selector, text)
def wait_text(self, selector: str, text: str) -> None:
self.wait_visible(selector)
self.wait_js_cond("ph_text_is(%s,%s)" % (jsquote(selector), jsquote(text)),
error_description="() => 'actual text: ' + ph_text(%s)" % jsquote(selector))
def wait_text_not(self, selector: str, text: str) -> None:
self.wait_visible(selector)
self.wait_js_func('!ph_text_is', selector, text)
def wait_text_matches(self, selector: str, pattern: str) -> None:
self.wait_visible(selector)
self.wait_js_func('ph_text_matches', selector, pattern)
def wait_popup(self, elem_id: str) -> None:
"""Wait for a popup to open.
:param id: the 'id' attribute of the popup.
"""
self.wait_visible('#' + elem_id)
def wait_language(self, lang: str) -> None:
parts = lang.split("-")
code_1 = parts[0]
code_2 = parts[0]
if len(parts) > 1:
code_2 += "_" + parts[1].upper()
self.wait_js_cond("cockpit.language == '%s' || cockpit.language == '%s'" % (code_1, code_2))
def dialog_cancel(self, sel: str, button: str = "button[data-dismiss='modal']") -> None:
self.click(sel + " " + button)
self.wait_not_visible(sel)
def enter_page(self, path: str, host: str | None = None, reconnect: bool = True) -> None:
"""Wait for a page to become current.
:param path: The identifier the page. This is a string starting with "/"
:type path: str
:param host: The host to connect too
:type host: str
:param reconnect: Try to reconnect
:type reconnect: bool
"""
assert path.startswith("/")
if host:
frame = host + path
else:
frame = "localhost" + path
frame = "cockpit1:" + frame
self.switch_to_top()
def wait_no_curtain() -> None:
# Older shells make the curtain invisible, newer shells
# remove it entirely. Let's cater to both.
self.wait_js_cond('!ph_is_present(".curtains-ct") || !ph_is_visible(".curtains-ct")')
while True:
try:
self._wait_present("iframe.container-frame[name='%s'][data-loaded]" % frame)
wait_no_curtain()
self.wait_visible("iframe.container-frame[name='%s']" % frame)
break
except Error as ex:
if reconnect and ex.msg.startswith('timeout'):
reconnect = False
if self.is_present("#machine-reconnect"):
self.click("#machine-reconnect")
wait_no_curtain()
continue
raise
self.switch_to_frame(frame)
self.wait_visible("body")
def leave_page(self) -> None:
self.switch_to_top()
def try_login(
self,
user: str | None = None,
password: str | None = None,
*,
superuser: bool | None = True,
legacy_authorized: bool | None = None
) -> None:
"""Fills in the login dialog and clicks the button.
This differs from login_and_go() by not expecting any particular result.
:param user: the username to login with
:type user: str
:param password: the password of the user
:type password: str
:param superuser: determines whether the new session will try to get Administrative Access (default true)
:type superuser: bool
:param legacy_authorized: old versions of the login dialog that still
have the "[ ] Reuse my password for magic things" checkbox. Such a
dialog is encountered when testing against old bastion hosts, for
example.
"""
if user is None:
user = self.default_user
if password is None:
password = self.password
self.wait_visible("#login")
self.set_val('#login-user-input', user)
self.set_val('#login-password-input', password)
if legacy_authorized is not None:
self.set_checked('#authorized-input', legacy_authorized)
if superuser is not None:
self.eval_js('window.localStorage.setItem("superuser:%s", "%s");' % (user, "any" if superuser else "none"))
self.click('#login-button')
def login_and_go(
self,
path: str | None = None,
*,
user: str | None = None,
host: str | None = None,
superuser: bool | None = True,
urlroot: str | None = None,
tls: bool = False,
password: str | None = None,
legacy_authorized: bool | None = None
) -> None:
"""Fills in the login dialog, clicks the button and navigates to the given path
:param user: the username to login with
:type user: str
:param password: the password of the user
:type password: str
:param superuser: determines whether the new session will try to get Administrative Access (default true)
:type superuser: bool
:param legacy_authorized: old versions of the login dialog that still
have the "[ ] Reuse my password for magic things" checkbox. Such a
dialog is encountered when testing against old bastion hosts, for
example.
"""
href = path
if not href:
href = "/"
if urlroot:
href = urlroot + href