-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
testlib.py
2616 lines (2196 loc) · 106 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 <http://www.gnu.org/licenses/>.
"""Tools for writing Cockpit test cases."""
import argparse
import base64
import contextlib
import errno
import fnmatch
import glob
import io
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import traceback
import unittest
from collections.abc import Collection, Container, Iterator, Mapping, Sequence
from typing import Any, Callable, ClassVar, Literal, Never, TypedDict, TypeVar
import cdp
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])
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',
'no_retry_when_changed',
'nondestructive',
'onlyImage',
'opts',
'sit',
'skipBrowser',
'skipImage',
'skipOstree',
'test_main',
'timeout',
'todo',
'todoPybridgeRHEL8',
'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
# 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:
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
path = os.path.dirname(__file__)
sizzle_js = os.path.join(path, "../../node_modules/sizzle/dist/sizzle.js")
helpers = [os.path.join(path, "test-functions.js")]
if os.path.exists(sizzle_js):
helpers.append(sizzle_js)
self.cdp = cdp.CDP("C.utf8", verbose=opts.trace, trace=opts.trace,
inject_helpers=helpers,
start_profile=coverage_label is not None)
self.password = "foobar"
self.timeout_factor = int(os.getenv("TEST_TIMEOUT_FACTOR", "1"))
self.failed_pixel_tests = 0
self.allow_oops = False
self.body_clip = None
try:
with open(f'{TEST_DIR}/browser-layouts.json') as fp:
self.layouts = json.load(fp)
except FileNotFoundError:
self.layouts = default_layouts
# Firefox CDP does not support setting EmulatedMedia
# https://bugzilla.mozilla.org/show_bug.cgi?id=1549434
if self.cdp.browser.name != "chromium":
self.layouts = [layout for layout in self.layouts if layout["theme"] != "dark"]
self.current_layout = None
def allow_download(self) -> None:
"""Allow browser downloads"""
if self.cdp.browser.name == "chromium":
self.cdp.invoke("Page.setDownloadBehavior", behavior="allow", downloadPath=self.cdp.download_dir)
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:
self.cdp.invoke("Network.setCookie", **cookie)
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.cdp.invoke("Page.navigate", url="about:blank")
self.cdp.invoke("Page.navigate", url=href)
def set_user_agent(self, ua: str) -> None:
"""Set the user agent of the browser
:param ua: user agent string
:type ua: str
"""
self.cdp.invoke("Emulation.setUserAgentOverride", userAgent=ua)
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(function (e) { return e.getAttribute('data-loaded'); })")
self.cdp.invoke("Page.reload", ignoreCache=ignore_cache)
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
"""
self.cdp.set_frame(name)
def switch_to_top(self) -> None:
"""Switch to the main frame
Switch to the main frame from for example an iframe.
"""
self.cdp.set_frame(None)
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.
"""
r = self.cdp.invoke("Runtime.evaluate", expression='document.querySelector(%s)' % jsquote(selector))
objectId = r["result"]["objectId"]
self.cdp.invoke("DOM.setFileInputFiles", files=files, objectId=objectId)
def raise_cdp_exception(
self, func: str, arg: str, details: Mapping[str, Any], trailer: str | None = None
) -> Never:
# unwrap a typical error string
if details.get("exception", {}).get("type") == "string":
msg = details["exception"]["value"]
elif details.get("text", None):
msg = details.get("text", None)
else:
msg = str(details)
if trailer:
msg += "\n" + trailer
raise Error("%s(%s): %s" % (func, arg, msg))
def inject_js(self, code: str) -> None:
"""Execute JS code that does not return anything
:param code: a string containing JavaScript code
:type code: str
"""
self.cdp.invoke("Runtime.evaluate", expression=code, trace=code,
silent=False, awaitPromise=True, returnByValue=False, no_trace=True)
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)
"""
result = self.cdp.invoke("Runtime.evaluate", expression=code, trace=code,
silent=False, awaitPromise=True, returnByValue=True, no_trace=no_trace)
if "exceptionDetails" in result:
self.raise_cdp_exception("eval_js", code, result["exceptionDetails"])
_type = result.get("result", {}).get("type")
if _type == 'object' and result["result"].get("subtype", "") == "error":
raise Error(result["result"]["description"])
if _type == "undefined":
return None
if _type and "value" in result["result"]:
return result["result"]["value"]
if opts.trace:
print("eval_js(%s): cannot interpret return value %s" % (code, result))
return None
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.cdp.invoke("Network.getCookies")
for c in cookies["cookies"]:
assert isinstance(c, Mapping)
if c["name"] == name:
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)
self.call_js_func('ph_mouse', selector, event, x, y, btn, ctrlKey, shiftKey, altKey, metaKey)
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", 0, 0, 0)
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
"""
self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
self.call_js_func('ph_set_checked', selector, val)
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:
for char in text:
self.cdp.invoke("Input.dispatchKeyEvent", type="keyDown", text=char, key=char)
self.cdp.invoke("Input.dispatchKeyEvent", type="keyUp", text=char, key=char)
def key(self, name: str, repeat: int = 1, modifiers: int = 0) -> None:
"""Press and release a named keyboard key.
Use this function to input special characters or modifiers.
:param name: key name like "Enter", "Delete", or "ArrowLeft"
:param repeat: number of times to repeat this key (default 1)
:param modifiers: bit field: Alt=1, Ctrl=2, Meta/Command=4, Shift=8
"""
args: dict[str, int | str] = {}
if self.cdp.browser.name == "chromium":
# HACK: chromium doesn't understand some key codes in some situations
win_keys = {
"Backspace": 8,
"Enter": 13,
"Escape": 27,
"ArrowDown": 40,
"Insert": 45,
}
if name in win_keys:
args["windowsVirtualKeyCode"] = win_keys[name]
if name == 'Enter':
args["text"] = '\r'
# HACK: chromium needs windowsVirtualKeyCode with modifiers
elif len(name) == 1 and name.isalnum() and modifiers != 0:
args["windowsVirtualKeyCode"] = ord(name.upper())
for _ in range(repeat):
self.cdp.invoke("Input.dispatchKeyEvent", type="keyDown", key=name, modifiers=modifiers, **args)
self.cdp.invoke("Input.dispatchKeyEvent", type="keyUp", key=name, modifiers=modifiers, **args)
def select_from_dropdown(self, selector: str, value: object) -> None:
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_PF4(self, selector: str, value: str) -> None:
self.click(f"{selector}:not([disabled]):not([aria-disabled=true])")
select_entry = f"{selector} + ul button:contains('{value}')"
self.click(select_entry)
if self.is_present(f"{selector}.pf-m-typeahead"):
self.wait_val(f"{selector} > div input[type=text]", value)
else:
self.wait_text(f"{selector} .pf-v5-c-select__toggle-text", value)
def select_PF5(self, selector_button: str, selector: str, value: object) -> None:
self.click(f"{selector_button}:not([disabled]):not([aria-disabled=true])")
select_entry = f"{selector} ul button:contains('{value}')"
self.click(select_entry)
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=2) # Ctrl + a
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-select__toggle-typeahead input", location)
# click away the selection list, to force a state update
self.click(f"{group_identifier} .pf-v5-c-select__toggle-typeahead")
self.wait_not_present(f"{group_identifier} .pf-v5-c-select__menu")
@contextlib.contextmanager
def wait_timeout(self, timeout: int) -> Iterator[None]:
old_timeout = self.cdp.timeout
self.cdp.timeout = timeout
yield
self.cdp.timeout = old_timeout
def wait(self, predicate: Callable[[], _T | None]) -> _T:
for _ in range(self.cdp.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:
count = 0
timeout = self.cdp.timeout * self.timeout_factor
start = time.time()
while True:
count += 1
try:
result = self.cdp.invoke("Runtime.evaluate",
expression="ph_wait_cond(() => %s, %i, %s)" % (cond, timeout * 1000, error_description),
silent=False, awaitPromise=True, trace="wait: " + cond)
if "exceptionDetails" in result:
if self.cdp.browser.name == "firefox" and count < 20 and "ph_wait_cond is not defined" in result["exceptionDetails"].get("text", ""):
time.sleep(0.1)
continue
trailer = "\n".join(self.cdp.get_js_log())
self.raise_cdp_exception("timeout\nwait_js_cond", cond, result["exceptionDetails"], trailer)
if timeout > 0:
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 RuntimeError as e:
data = e.args[0]
if count < 20 and isinstance(data, dict) and "response" in data and data["response"].get("message") in ["Execution context was destroyed.", "Cannot find context with specified id"]:
time.sleep(1)
else:
raise e
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: object) -> 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()
while True:
try:
self._wait_present("iframe.container-frame[name='%s'][data-loaded]" % frame)
self.wait_not_visible(".curtains-ct")
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")
self.wait_not_visible(".curtains-ct")
continue
raise
self.switch_to_frame(frame)
self._wait_present("body")
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
if host:
href = "/@" + host + href
self.open(href, tls=tls)
self.try_login(user=user, password=password, superuser=superuser, legacy_authorized=legacy_authorized)
self._wait_present('#content')
self.wait_visible('#content')
if path:
self.enter_page(path.split("#")[0], host=host)
def logout(self) -> None:
self.assert_no_oops()
self.switch_to_top()
self.wait_visible("#toggle-menu")
if self.is_present("button#machine-reconnect") and self.is_visible("button#machine-reconnect"):
# happens when shutting down cockpit or rebooting machine
self.click("button#machine-reconnect")
else:
# happens when cockpit is still running
self.open_session_menu()
try:
self.click('#logout')
except RuntimeError as e:
# logging out does destroy the current frame context, it races with the CDP driver finishing the command
if "Execution context was destroyed" not in str(e):
raise
self.wait_visible('#login')
self.machine.allow_restart_journal_messages()
def relogin(
self,
path: str | None = None,
user: str | None = None,
*,
password: str | None = None,
superuser: bool | None = None,
wait_remote_session_machine: testvm.Machine | None = None
) -> None:
self.logout()
if wait_remote_session_machine:
wait_remote_session_machine.execute("while pgrep -a cockpit-ssh; do sleep 1; done")
self.try_login(user=user, password=password, superuser=superuser)
self._wait_present('#content')
self.wait_visible('#content')
if path:
if path.startswith("/@"):
host = path[2:].split("/")[0]
else:
host = None
self.enter_page(path.split("#")[0], host=host)
def open_session_menu(self) -> None:
self.wait_visible("#toggle-menu")
if (self.attr("#toggle-menu", "aria-expanded") != "true"):
self.click("#toggle-menu")
def layout_is_mobile(self) -> bool:
if not self.current_layout:
return False
return self.current_layout["shell_size"][0] < 420
def open_superuser_dialog(self) -> None:
if self.layout_is_mobile():
self.open_session_menu()
self.click("#super-user-indicator-mobile button")
else:
self.click("#super-user-indicator button")
def check_superuser_indicator(self, expected: str) -> None:
if self.layout_is_mobile():
self.open_session_menu()
self.wait_text("#super-user-indicator-mobile", expected)
self.click("#toggle-menu")
else:
self.wait_text("#super-user-indicator", expected)
def become_superuser(
self,
user: str | None = None,
password: str | None = None,
passwordless: bool | None = False
) -> None:
cur_frame = self.cdp.cur_frame
self.switch_to_top()
self.open_superuser_dialog()
# In (open)SUSE images, superuser access always requires the root password
if user is None:
user = "root" if "suse" in self.machine.image else "admin"
if passwordless:
self.wait_in_text("div[role=dialog]:contains('Administrative access')", "You now have administrative access.")
self.click("div[role=dialog] button:contains('Close')")
self.wait_not_present("div[role=dialog]:contains('You now have administrative access.')")
else:
self.wait_in_text("div[role=dialog]:contains('Switch to administrative access')", f"Password for {user}:")
self.set_input_text("div[role=dialog]:contains('Switch to administrative access') input", password or "foobar")
self.click("div[role=dialog] button:contains('Authenticate')")
self.wait_not_present("div[role=dialog]:contains('Switch to administrative access')")
self.check_superuser_indicator("Administrative access")
self.switch_to_frame(cur_frame)
def drop_superuser(self) -> None:
cur_frame = self.cdp.cur_frame
self.switch_to_top()
self.open_superuser_dialog()
self.click("div[role=dialog]:contains('Switch to limited access') button:contains('Limit access')")
self.wait_not_present("div[role=dialog]:contains('Switch to limited access')")
self.check_superuser_indicator("Limited access")
self.switch_to_frame(cur_frame)
def click_system_menu(self, path: str, enter: bool = True) -> None:
"""Click on a "System" menu entry with given URL path
Enters the given target frame afterwards, unless enter=False is given
(useful for remote hosts).
"""
self.switch_to_top()
self.click(f"#host-apps a[href='{path}']")
if enter:
# strip off parameters after hash
self.enter_page(path.split('#')[0].rstrip('/'))
def get_pf_progress_value(self, progress_bar_sel: str) -> int:
"""Get numeric value of a PatternFly <ProgressBar> component"""
sel = progress_bar_sel + " .pf-v5-c-progress__indicator"
self.wait_visible(sel)
self.wait_attr_contains(sel, "style", "width:")
style = self.attr(sel, "style")
m = re.search(r"width: (\d+)%;", style)
assert m is not None
return int(m.group(1))
def start_machine_troubleshoot(
self,
new: bool = False,
known_host: bool = False,
password: str | None = None,
expect_closed_dialog: bool = True,
) -> None:
self.click('#machine-troubleshoot')
self.wait_visible('#hosts_setup_server_dialog')
if new:
self.click('#hosts_setup_server_dialog button:contains(Add)')
if not known_host:
self.wait_in_text('#hosts_setup_server_dialog', "You are connecting to")
self.wait_in_text('#hosts_setup_server_dialog', "for the first time.")
self.click("#hosts_setup_server_dialog button:contains('Trust and add host')")
if password:
self.wait_in_text('#hosts_setup_server_dialog', "Unable to log in")
self.set_input_text('#login-custom-password', password)
self.click('#hosts_setup_server_dialog button:contains(Log in)')
if expect_closed_dialog:
self.wait_not_present('#hosts_setup_server_dialog')