Debian Codegraph @

test/common/testlib.py

raw
1 #
2 # Copyright (C) 2013 Red Hat, Inc.
3 # SPDX-License-Identifier: LGPL-2.1-or-later
4
5
6 """Tools for writing Cockpit test cases."""
7
8 import argparse
9 import asyncio
10 import base64
11 import contextlib
12 import errno
13 import fnmatch
14 import glob
15 import io
16 import json
17 import logging
18 import os
19 import re
20 import shutil
21 import socket
22 import subprocess
23 import sys
24 import tempfile
25 import threading
26 import time
27 import traceback
28 import unittest
29 from collections.abc import Collection, Container, Coroutine, Iterator, Mapping, Sequence
30 from dataclasses import dataclass
31 from pathlib import Path
32 from typing import Any, Callable, ClassVar, Literal, TypedDict, TypeVar
33
34 import webdriver_bidi
35 from lcov import write_lcov
36 from lib.constants import OSTREE_IMAGES
37 from machine import testvm
38 from PIL import Image
39 from pixelmatch.contrib.PIL import pixelmatch
40
41 _T = TypeVar('_T')
42 _FT = TypeVar("_FT", bound=Callable[..., Any])
43
44 JsonObject = dict[str, Any]
45
46 BASE_DIR = os.path.realpath(f'{__file__}/../../..')
47 TEST_DIR = f'{BASE_DIR}/test'
48 BOTS_DIR = f'{BASE_DIR}/bots'
49
50 os.environ["PATH"] = f"{os.environ.get('PATH')}:{BOTS_DIR}:{TEST_DIR}"
51
52 # Be careful when changing this string, check in cockpit-project/bots where it is being used
53 UNEXPECTED_MESSAGE = "FAIL: Test completed, but found unexpected "
54 PIXEL_TEST_MESSAGE = "Some pixel tests have failed"
55
56 __all__ = (
57 'PIXEL_TEST_MESSAGE',
58 'TEST_DIR',
59 'UNEXPECTED_MESSAGE',
60 'Browser',
61 'Error',
62 'MachineCase',
63 'arg_parser',
64 'destructive',
65 'no_retry_when_changed',
66 'nondestructive',
67 'onlyImage',
68 'opts',
69 'sit',
70 'skipBrowser',
71 'skipImage',
72 'skipOstree',
73 'test_main',
74 'timeout',
75 'todo',
76 'wait',
77 )
78
79 # Command line options
80 opts = argparse.Namespace()
81 opts.sit = False
82 opts.trace = False
83 opts.attachments = None
84 opts.revision = None
85 opts.address = None
86 opts.fetch = True
87 opts.coverage = False
88
89
90 # https://w3c.github.io/webdriver/#keyboard-actions for encoding key names
91 WEBDRIVER_KEYS = {
92 "Backspace": "\uE003",
93 "Tab": "\uE004",
94 "Return": "\uE006",
95 "Enter": "\uE007",
96 "Shift": "\uE008",
97 "Control": "\uE009",
98 "Alt": "\uE00A",
99 "Escape": "\uE00C",
100 "Space": "\uE00D",
101 "PageUp": "\uE00E",
102 "PageDown": "\uE00F",
103 "End": "\uE010",
104 "Home": "\uE011",
105 "ArrowLeft": "\uE012",
106 "ArrowUp": "\uE013",
107 "ArrowRight": "\uE014",
108 "ArrowDown": "\uE015",
109 "Insert": "\uE016",
110 "Delete": "\uE017",
111 "Meta": "\uE03D",
112 "F2": "\uE032",
113 }
114
115
116 # Browser layouts
117 #
118 # A browser can be switched into a number of different layouts, such
119 # as "desktop" and "mobile". A default set of layouts is defined
120 # here, but projects can override this with a file called
121 # "test/browser-layouts.json".
122 #
123 # Each layout defines the size of the shell (where the main navigation
124 # is) and also the size of the content iframe (where the actual page
125 # like "Networking" or "Overview" is displayed).
126 #
127 # When the browser layout is switched (by calling Browset.set_layout),
128 # this will either set the shell size or the content size, depending
129 # on which frame is current (as set by Browser.enter_page or
130 # Browser.leave_page).
131 #
132 # This makes sure that pixel tests for the whole content iframe are
133 # always the exact size as specified in the layout definition, and
134 # don't change size when the navigation stuff in the shell changes.
135 #
136 # The browser starts out in the first layout of this list, which is
137 # "desktop" by default.
138
139 class BrowserLayout(TypedDict):
140 name: str
141 theme: Literal["light"] | Literal["dark"]
142 shell_size: tuple[int, int]
143 content_size: tuple[int, int]
144
145
146 default_layouts: Sequence[BrowserLayout] = (
147 {
148 "name": "desktop",
149 "theme": "light",
150 "shell_size": (1920, 1200),
151 "content_size": (1680, 1130)
152 },
153 {
154 "name": "medium",
155 "theme": "light",
156 "shell_size": (1280, 768),
157 "content_size": (1040, 698)
158 },
159 {
160 "name": "mobile",
161 "theme": "light",
162 "shell_size": (414, 1920),
163 "content_size": (414, 1856)
164 },
165 {
166 "name": "dark",
167 "theme": "dark",
168 "shell_size": (1920, 1200),
169 "content_size": (1680, 1130)
170 },
171 {
172 "name": "rtl",
173 "theme": "light",
174 "shell_size": (1920, 1200),
175 "content_size": (1680, 1130)
176 },
177 )
178
179
180 def attach(filename: str, move: bool = False) -> None:
181 """Put a file into the attachments directory.
182
183 :param filename: file to put in attachments directory
184 :param move: set this to true to move dynamically generated files which
185 are not touched by destructive tests. (default False)
186 """
187 if not opts.attachments:
188 return
189 dest = os.path.join(opts.attachments, os.path.basename(filename))
190 if os.path.exists(filename) and not os.path.exists(dest):
191 if move:
192 shutil.move(filename, dest)
193 else:
194 shutil.copy(filename, dest)
195
196
197 def unique_filename(base: str, ext: str) -> str:
198 for i in range(20):
199 if i == 0:
200 f = f"{base}.{ext}"
201 else:
202 f = f"{base}-{i}.{ext}"
203 if not os.path.exists(f):
204 return f
205 return f"{base}.{ext}"
206
207
208 class Browser:
209 driver: webdriver_bidi.WebdriverBidi
210 browser: str
211 layouts: Sequence[BrowserLayout]
212 current_layout: BrowserLayout | None
213 port: str | int
214
215 def __init__(
216 self,
217 address: str,
218 label: str,
219 machine: 'MachineCase',
220 pixels_label: str | None = None,
221 coverage_label: str | None = None,
222 port: int | str | None = None
223 ) -> None:
224 if ":" in address:
225 self.address, _, self.port = address.rpartition(":")
226 else:
227 self.address = address
228 self.port = 9090
229 if port is not None:
230 self.port = port
231 self.default_user = "admin"
232 self.label = label
233 self.pixels_label = pixels_label
234 self.used_pixel_references = set[str]()
235 self.coverage_label = coverage_label
236 self.machine = machine
237
238 # HACK: Tests which don't yet get along with real mouse clicks in Chromium
239 # can opt into falling back to the old MouseEvent emulation; this is cheating, but fixing
240 # all the tests at once is too much work. Remove this once all tests in all our projects
241 # got fixed.
242 self.chromium_fake_mouse = False
243
244 headless = os.environ.get("TEST_SHOW_BROWSER", '0') == '0'
245 self.browser = os.environ.get("TEST_BROWSER", "chromium")
246 if self.browser == "chromium":
247 self.driver = webdriver_bidi.ChromiumBidi(headless=headless)
248 elif self.browser == "firefox":
249 self.driver = webdriver_bidi.FirefoxBidi(headless=headless)
250 else:
251 raise ValueError(f"unknown browser {self.browser}")
252 self.loop = asyncio.new_event_loop()
253 self.bidi_thread = threading.Thread(target=self.asyncio_loop_thread, args=(self.loop,))
254 self.bidi_thread.start()
255
256 self.run_async(self.driver.start_session())
257
258 if opts.trace:
259 logging.basicConfig(level=logging.INFO)
260 webdriver_bidi.log_command.setLevel(logging.INFO if opts.trace else logging.WARNING)
261 # not appropriate for --trace, just enable for debugging low-level protocol with browser
262 # webdriver_bidi.log_proto.setLevel(logging.DEBUG)
263
264 test_functions = (Path(__file__).parent / "test-functions.js").read_text()
265 # Don't redefine globals, this confuses Firefox
266 test_functions = "if (window.ph_select) return; " + test_functions
267 self.bidi("script.addPreloadScript", quiet=True, functionDeclaration=f"() => {{ {test_functions} }}")
268
269 try:
270 sizzle_js = (Path(__file__).parent.parent.parent / "node_modules/sizzle/dist/sizzle.js").read_text()
271 # HACK: injecting sizzle fails on missing `document` in assert()
272 sizzle_js = sizzle_js.replace('function assert( fn ) {',
273 'function assert( fn ) { if (true) return true; else ')
274 # HACK: sizzle tracks document and when we switch frames, it sees the old document
275 # although we execute it in different context.
276 sizzle_js = sizzle_js.replace('context = context || document;', 'context = context || window.document;')
277 self.bidi("script.addPreloadScript", quiet=True, functionDeclaration=f"() => {{ {sizzle_js} }}")
278 except FileNotFoundError:
279 pass
280
281 if coverage_label:
282 self.cdp_command("Profiler.enable")
283 self.cdp_command("Profiler.startPreciseCoverage", callCount=False, detailed=True)
284
285 self.password = "foobar"
286 self.timeout_factor = float(os.getenv("TEST_TIMEOUT_FACTOR", "1"))
287 self.timeout = 15
288 self.failed_pixel_tests = 0
289 self.allow_oops = False
290 try:
291 with open(f'{TEST_DIR}/browser-layouts.json') as fp:
292 self.layouts = json.load(fp)
293 except FileNotFoundError:
294 self.layouts = default_layouts
295 self.current_layout = None
296
297 def _is_running(self) -> bool:
298 """True initially, false after calling .kill()"""
299
300 return self.driver.bidi_session is not None
301
302 def have_test_api(self) -> bool:
303 """Check if the browser is running and has a Cockpit page
304
305 I.e. are our test-functions.js available? This is only true after
306 opening cockpit, not for the initial blank page (before login_and_go)
307 or other URLs like Grafana.
308 """
309 if not self._is_running():
310 return False
311 return self.eval_js("!!window.ph_find")
312
313 def run_async(self, coro: Coroutine[Any, Any, Any]) -> JsonObject:
314 """Run coro in main loop in our BiDi thread
315
316 Wait for the result and return it.
317 """
318 return asyncio.run_coroutine_threadsafe(coro, self.loop).result()
319
320 @staticmethod
321 def asyncio_loop_thread(loop: asyncio.AbstractEventLoop) -> None:
322 asyncio.set_event_loop(loop)
323 loop.run_forever()
324
325 def kill(self) -> None:
326 if not self._is_running():
327 return
328 self.run_async(self.driver.close())
329 self.loop.call_soon_threadsafe(self.loop.stop)
330 self.bidi_thread.join()
331
332 def bidi(self, method: str, **params: Any) -> webdriver_bidi.JsonObject:
333 """Send a Webdriver BiDi command and return the JSON response"""
334
335 try:
336 return self.run_async(self.driver.bidi(method, **params))
337 except webdriver_bidi.WebdriverError as e:
338 raise Error(str(e)) from None
339
340 def cdp_command(self, method: str, **params: Any) -> webdriver_bidi.JsonObject:
341 """Send a Chrome DevTools Protocol command and return the JSON response"""
342
343 if self.browser == "chromium":
344 assert isinstance(self.driver, webdriver_bidi.ChromiumBidi)
345 reply = self.run_async(self.driver.cdp(method, **params))
346 if 'error' in reply:
347 raise Error(str(reply['error'])) from None
348 return reply['result']
349 else:
350 raise webdriver_bidi.WebdriverError("CDP is only supported in Chromium")
351
352 def open(self, href: str, cookie: Mapping[str, str] | None = None, tls: bool = False) -> None:
353 """Load a page into the browser.
354
355 :param href: the path of the Cockpit page to load, such as "/users". Either PAGE or URL needs to be given.
356 :param cookie: a dictionary object representing a cookie.
357 :param tls: load the page using https (default False)
358
359 Raises:
360 Error: When a timeout occurs waiting for the page to load.
361 """
362 if href.startswith("/"):
363 schema = "https" if tls else "http"
364 href = f"{schema}://{self.address}:{self.port}{href}"
365
366 if not self.current_layout and os.environ.get("TEST_SHOW_BROWSER") in [None, "pixels"]:
367 self.current_layout = self.layouts[0]
368 size = self.current_layout["shell_size"]
369 self._set_window_size(size[0], size[1])
370 if cookie:
371 c = {**cookie, "value": {"type": "string", "value": cookie["value"]}}
372 self.bidi("storage.setCookie", cookie=c)
373
374 self.switch_to_top()
375 # Some browsers optimize this away if the current URL is already href
376 # (e.g. in TestKeys.testAuthorizedKeys). Load the blank page first to always
377 # force a load.
378 self.bidi("browsingContext.navigate", context=self.driver.context, url="about:blank", wait="complete")
379 self.bidi("browsingContext.navigate", context=self.driver.context, url=href, wait="complete", timeout=30)
380
381 def set_user_agent(self, ua: str) -> None:
382 """Set the user agent of the browser
383
384 :param ua: user agent string
385 :type ua: str
386 """
387 if self.browser == "chromium":
388 self.cdp_command("Emulation.setUserAgentOverride", userAgent=ua)
389 else:
390 raise NotImplementedError
391
392 def reload(self, ignore_cache: bool = False) -> None:
393 """Reload the current page
394
395 :param ignore_cache: if true browser cache is ignored (default False)
396 :type ignore_cache: bool
397 """
398
399 self.switch_to_top()
400 self.wait_js_cond("ph_select('iframe.container-frame').every(e => e.getAttribute('data-loaded'))")
401 if self.browser == "firefox":
402 if ignore_cache:
403 webdriver_bidi.log_command.warning(
404 "Browser.reload(): ignore_cache==True not yet supported with Firefox, ignoring")
405 self.bidi("browsingContext.reload", context=self.driver.context, wait="complete")
406 else:
407 self.bidi("browsingContext.reload", context=self.driver.context, ignoreCache=ignore_cache,
408 wait="complete")
409
410 self.machine.allow_restart_journal_messages()
411
412 def switch_to_frame(self, name: str | None) -> None:
413 """Switch to frame in browser tab
414
415 Each page has a main frame and can have multiple subframes, usually
416 iframes.
417
418 :param name: frame name
419 """
420 if name is None:
421 self.switch_to_top()
422 else:
423 self.run_async(self.driver.switch_to_frame(name))
424
425 def switch_to_top(self) -> None:
426 """Switch to the main frame
427
428 Switch to the main frame from for example an iframe.
429 """
430 self.driver.switch_to_top()
431
432 def allow_download(self) -> None:
433 """Allow browser downloads"""
434 # this is only necessary for headless chromium
435 if self.browser == "chromium":
436 self.cdp_command("Browser.setDownloadBehavior", behavior="allow",
437 downloadPath=str(self.driver.download_dir))
438
439 def upload_files(self, selector: str, files: Sequence[str]) -> None:
440 """Upload a local file to the browser
441
442 The selector should select the <input type="file"/> element.
443 Files is a list of absolute paths to files which should be uploaded.
444 """
445 element = self.eval_js(f"ph_find({jsquote(selector)})")
446 self.bidi("input.setFiles", context=self.driver.context, element=element, files=files)
447
448 def eval_js(self, code: str, no_trace: bool = False) -> Any:
449 """Execute JS code that returns something
450
451 :param code: a string containing JavaScript code
452 :param no_trace: do not print information about unknown return values (default False)
453 """
454 return self.bidi("script.evaluate", expression=code, quiet=no_trace,
455 awaitPromise=True, target={"context": self.driver.context})["result"]
456
457 def call_js_func(self, func: str, *args: object) -> Any:
458 """Call a JavaScript function
459
460 :param func: JavaScript function to call
461 :param args: arguments for the JavaScript function
462 """
463 return self.eval_js("{}({})".format(func, ','.join(map(jsquote, args))))
464
465 def set_mock(self, mock: Mapping[str, str], base: str = "") -> None:
466 """Replace some DOM elements with mock text
467
468 The 'mock' parameter is a dictionary from CSS selectors to the
469 text that the elements matching the selector should be
470 replaced with.
471
472 XXX - There is no way to easily undo the effects of this
473 function. There is no coordination with React. This
474 will improve as necessary.
475
476 :param mock: the mock data, see above
477 :param base: if given, all selectors are relative to this one
478 """
479 self.call_js_func('ph_set_texts', {base + " " + k: v for k, v in mock.items()})
480
481 def cookie(self, name: str) -> Mapping[str, object] | None:
482 """Retrieve a browser cookie by name
483
484 :param name: the name of the cookie
485 :type name: str
486 """
487 cookies = self.bidi("storage.getCookies", filter={"name": name})["cookies"]
488 if len(cookies) > 0:
489 c = cookies[0]
490 # if we ever need to handle "base64", add that
491 assert c["value"]["type"] == "string"
492 c["value"] = c["value"]["value"]
493 return c
494 return None
495
496 def go(self, path_hash: str) -> None:
497 """Change URL to a different path or hash
498
499 This must be called with either a path (starting with `/`) or hash (starting with `#`).
500 """
501 if path_hash.startswith("#"):
502 self.call_js_func('cockpit.location.go', path_hash[1:])
503 elif path_hash.startswith("/"):
504 # this behaves like clicking in the shell menu, i.e. cockpit.jump()
505 self.call_js_func('ph_jump', path_hash)
506 else:
507 raise ValueError(f"go({path_hash}): must be called with a path or hash value")
508
509 def mouse(
510 self,
511 selector: str,
512 event: str,
513 x: int | None = None,
514 y: int | None = None,
515 btn: int = 0,
516 *,
517 ctrlKey: bool = False,
518 shiftKey: bool = False,
519 altKey: bool = False,
520 metaKey: bool = False,
521 scrollVisible: bool = True,
522 synthetic: bool = False,
523 ) -> None:
524 """Do a mouse event in the browser.
525
526 :param selector: the element to interact with
527 :param type: click, dblclick, mousemove; you can also use "mouseenter" (alias for mousemove) or "mouseleave"
528 (but this is just a heuristic by moving the mouse 500x500 pixels away; prefer moving to an explicit
529 target)
530 :param x, y: coordinates; when not given, default to center of element
531 :param btn: mouse button to click https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
532 :param crtlKey: press the ctrl key
533 :param shiftKey: press the shift key
534 :param altKey: press the alt key
535 :param metaKey: press the meta key
536 :param scrollVisible: set to False in rare cases where scrolling an element into view triggers side effects
537 """
538 self.wait_visible(selector)
539
540 # TODO: x and y are not currently implemented: webdriver (0, 0) is the element's center, not top left corner
541 # in these cases, use the old MouseEvent emulation
542 if x is not None or y is not None:
543 synthetic = True
544
545 if self.browser == "chromium" and self.chromium_fake_mouse:
546 synthetic = True
547
548 if synthetic:
549 self.call_js_func('ph_mouse', selector, event, x or 0, y or 0, btn, ctrlKey, shiftKey, altKey, metaKey)
550 return
551
552 # in the general case, use the BiDi API, which is more realistic -- it doesn't sidestep the browser
553 ev_id = f"pointer-{self.driver.last_id}"
554
555 def key(type_: str, name: str) -> JsonObject:
556 return {"type": "key", "id": ev_id + type_, "actions": [{"type": type_, "value": WEBDRIVER_KEYS[name]}]}
557
558 for _retry in range(3):
559 element = self.call_js_func('ph_find_scroll_into_view' if scrollVisible else 'ph_find', selector)
560
561 actions: list[JsonObject] = [
562 {"type": "pointerMove", "x": 0, "y": 0, "origin": {"type": "element", "element": element}}
563 ]
564 down = {"type": "pointerDown", "button": btn}
565 up = {"type": "pointerUp", "button": btn}
566 if event == "click":
567 actions.extend([down, up])
568 elif event == "dblclick":
569 actions.extend([down, up, down, up])
570 elif event in ["mousemove", "mouseenter"]:
571 pass
572 elif event == "mouseleave":
573 # move the mouse someplace else
574 actions = [{"type": "pointerMove", "x": 500, "y": 500, "origin": "pointer"}]
575 else:
576 raise NotImplementedError(f"unknown event {event}")
577
578 # modifier keys
579 keys_pre: list[JsonObject] = []
580 keys_post: list[JsonObject] = []
581
582 if altKey:
583 keys_pre.append(key("keyDown", "Alt"))
584 keys_post.append(key("keyUp", "Alt"))
585 if ctrlKey:
586 keys_pre.append(key("keyDown", "Control"))
587 keys_post.append(key("keyUp", "Control"))
588 if shiftKey:
589 keys_pre.append(key("keyDown", "Shift"))
590 keys_post.append(key("keyUp", "Shift"))
591 if metaKey:
592 keys_pre.append(key("keyDown", "Meta"))
593 keys_post.append(key("keyUp", "Meta"))
594
595 # the actual mouse event
596 actions = [{
597 "id": ev_id,
598 "type": "pointer",
599 "parameters": {"pointerType": "mouse"},
600 "actions": actions,
601 }]
602
603 try:
604 self.bidi("input.performActions", context=self.driver.context, actions=keys_pre + actions + keys_post)
605 break
606 except Error as e:
607 # race condition: if the page re-renders after the wait_visible() but before the mouse event,
608 # the element might not be present anymore; retry then
609 if "no such element" in str(e):
610 webdriver_bidi.log_command.warning(
611 "Browser.mouse(%r, %r): retrying after %s", selector, event, e.msg)
612 # retry, but don't scroll again
613 scrollVisible = False
614 else:
615 raise
616
617 def click(self, selector: str) -> None:
618 """Click on a ui element
619
620 :param selector: the selector to click on
621 """
622 self.mouse(selector + ":not([disabled]):not([aria-disabled=true])", "click")
623
624 def val(self, selector: str) -> Any:
625 """Get the value attribute of a selector.
626
627 :param selector: the selector to get the value of
628 """
629 self.wait_visible(selector)
630 return self.call_js_func('ph_val', selector)
631
632 def set_val(self, selector: str, val: object) -> None:
633 """Set the value attribute of a non disabled DOM element.
634
635 This also emits a change DOM change event.
636
637 :param selector: the selector to set the value of
638 :param val: the value to set
639 """
640 self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
641 self.call_js_func('ph_set_val', selector, val)
642
643 def text(self, selector: str) -> str:
644 """Get an element's textContent value.
645
646 :param selector: the selector to get the value of
647 """
648 self.wait_visible(selector)
649 return self.call_js_func('ph_text', selector) or ''
650
651 def attr(self, selector: str, attr: str) -> Any:
652 """Get the value of a given attribute of an element.
653
654 :param selector: the selector to get the attribute of
655 :param attr: the DOM element attribute
656 """
657 self._wait_present(selector)
658 return self.call_js_func('ph_attr', selector, attr)
659
660 def set_attr(self, selector: str, attr: str, val: object) -> None:
661 """Set an attribute value of an element.
662
663 :param selector: the selector
664 :param attr: the element attribute
665 :param val: the value of the attribute
666 """
667 self._wait_present(selector + ':not([disabled]):not([aria-disabled=true])')
668 self.call_js_func('ph_set_attr', selector, attr, val)
669
670 def get_checked(self, selector: str) -> bool:
671 """Get checked state of a given selector.
672
673 :param selector: the selector
674 :return: the checked state
675 """
676 self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
677 return self.call_js_func('ph_get_checked', selector)
678
679 def set_checked(self, selector: str, val: bool) -> None:
680 """Set checked state of a given selector.
681
682 :param selector: the selector
683 :param val: boolean value to enable or disable checkbox
684 """
685 # avoid ph_set_checked, that doesn't use proper mouse emulation
686 checked = self.get_checked(selector)
687 if checked != val:
688 self.click(selector)
689
690 def focus(self, selector: str) -> None:
691 """Set focus on selected element.
692
693 :param selector: the selector
694 """
695 self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
696 self.call_js_func('ph_focus', selector)
697
698 def blur(self, selector: str) -> None:
699 """Remove keyboard focus from selected element.
700
701 :param selector: the selector
702 """
703 self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
704 self.call_js_func('ph_blur', selector)
705
706 def input_text(self, text: str) -> None:
707 actions: list[JsonObject] = []
708 for c in text:
709 # quality-of-life special case
710 if c == '\n':
711 c = WEBDRIVER_KEYS["Enter"]
712 actions.append({"type": "keyDown", "value": c})
713 actions.append({"type": "keyUp", "value": c})
714 self.bidi("input.performActions", context=self.driver.context, actions=[
715 {"type": "key", "id": "key-0", "actions": actions}])
716
717 def key(self, name: str, repeat: int = 1, modifiers: list[str] | None = None) -> None:
718 """Press and release a named keyboard key.
719
720 Use this function to input special characters or modifiers.
721
722 :param name: ASCII value or key name like "Enter", "Delete", or "ArrowLeft" (entry in WEBDRIVER_KEYS)
723 :param repeat: number of times to repeat this key (default 1)
724 :param modifiers: "Shift", "Control", "Alt"
725 """
726 actions: list[JsonObject] = []
727 actions_pre: list[JsonObject] = []
728 actions_post: list[JsonObject] = []
729 keycode = WEBDRIVER_KEYS.get(name, name)
730
731 for m in (modifiers or []):
732 actions_pre.append({"type": "keyDown", "value": WEBDRIVER_KEYS[m]})
733 actions_post.append({"type": "keyUp", "value": WEBDRIVER_KEYS[m]})
734
735 for _ in range(repeat):
736 actions.append({"type": "keyDown", "value": keycode})
737 actions.append({"type": "keyUp", "value": keycode})
738
739 self.bidi("input.performActions", context=self.driver.context, actions=[
740 {"type": "key", "id": "key-0", "actions": actions_pre + actions + actions_post}])
741
742 def paste(self, val: str) -> None:
743 """Simulate pasting a string into the currently focused element.
744
745 :param val: The text to paste. It will be left in the clipboard.
746 """
747 self.call_js_func("((val) => navigator.clipboard.writeText(val))", val)
748 self.key("v", modifiers=["Control"])
749
750 def select_from_dropdown(self, selector: str, value: object) -> None:
751 """For an actual <select> HTML component"""
752
753 self.wait_visible(selector + ':not([disabled]):not([aria-disabled=true])')
754 text_selector = f"{selector} option[value='{value}']"
755 self._wait_present(text_selector)
756 self.set_val(selector, value)
757 self.wait_val(selector, value)
758
759 def select_PF(self, selector: str, value: str, menu_class: str = ".pf-v6-c-menu") -> None:
760 """For a PatternFly Select-like component
761
762 For things like <Select> or <TimePicker>. Unfortunately none of them render as an actual <select>, but a
763 <button> or <div> with a detached menu div (which can even be in the parent).
764
765 For similar components like the deprecated <Select> you can specify a different menu class.
766 """
767 self.click(selector)
768 # SelectOption's value does not render to an actual "value" attribute, just a <li> text
769 self.click(f"{menu_class} button:contains('{value}')")
770 self.wait_not_present(menu_class)
771
772 def click_button(self, compid: str, prefix: str = "", component: str = "PF6/Button") -> None:
773 """Click on a button identified by its OUIA component id."""
774 self.click(f'{prefix} [data-ouia-component-type="{component}"][data-ouia-component-id="{compid}"]')
775
776 def set_input_text(
777 self, selector: str, val: str, append: bool = False, value_check: bool = True, blur: bool = True, paste: bool = False
778 ) -> None:
779 self.focus(selector)
780 if not append:
781 self.key("a", modifiers=["Control"])
782 if val == "":
783 self.key("Backspace")
784 elif paste:
785 self.paste(val)
786 else:
787 self.input_text(val)
788 if blur:
789 self.blur(selector)
790
791 if value_check:
792 self.wait_val(selector, val)
793
794 def set_file_autocomplete_val(self, group_identifier: str, location: str) -> None:
795 self.set_input_text(f"{group_identifier} .pf-v6-c-menu-toggle input", location)
796 # select the file
797 self.wait_text(".pf-v6-c-menu ul li:nth-child(1) button", location)
798 self.click(".pf-v6-c-menu ul li:nth-child(1) button")
799 self.wait_not_present(".pf-v6-c-menu")
800 self.wait_val(f"{group_identifier} .pf-v6-c-menu-toggle input", location)
801
802 def count(self, selector: str) -> int:
803 """Returns the total count of matches DOM elements.
804
805 :param selector: the selector
806 """
807 return self.call_js_func('ph_count', selector)
808
809 def wait_count(self, selector: str, total: int) -> None:
810 """Wait until the total count matches the selected DOM elements.
811
812 :param selector: the selector
813 :param total: the total amount of elements to wait for
814 """
815 return self.wait_js_func("ph_count_check", selector, total)
816
817 @contextlib.contextmanager
818 def wait_timeout(self, timeout: int) -> Iterator[None]:
819 old_timeout = self.timeout
820 self.timeout = timeout
821 try:
822 yield
823 finally:
824 self.timeout = old_timeout
825
826 def wait(self, predicate: Callable[[], _T | None]) -> _T:
827 for _ in range(int(self.timeout * self.timeout_factor * 5)):
828 val = predicate()
829 if val:
830 return val
831 time.sleep(0.2)
832 raise Error('timed out waiting for predicate to become true')
833
834 def wait_js_cond(self, cond: str, error_description: str = "null") -> None:
835 timeout = self.timeout * self.timeout_factor
836 start = time.time()
837 last_error = None
838 for _retry in range(5):
839 try:
840 self.bidi("script.evaluate",
841 expression=f"ph_wait_cond(() => {cond}, {timeout * 1000}, {error_description})",
842 awaitPromise=True, timeout=timeout + 5, target={"context": self.driver.context})
843
844 duration = time.time() - start
845 percent = int(duration / timeout * 100)
846 if percent >= 50:
847 print(f"WARNING: Waiting for {cond} took {duration:.1f} seconds, "
848 f"which is {percent}% of the timeout.")
849 return
850 except Error as e:
851 last_error = e
852
853 # can happen when waiting across page reloads
854 if any(pattern in str(e) for pattern in [
855 # during page loading
856 "is not a function",
857 # chromium
858 "Execution context was destroyed",
859 "Cannot find context",
860 "Inspected target navigated or closed",
861 "execution contexts cleared",
862 # firefox
863 "MessageHandlerFrame' destroyed",
864 "DiscardedBrowsingContextError",
865 # page helpers not yet loaded
866 "ph_wait_cond is not defined",
867 ]):
868 if time.time() - start < timeout:
869 webdriver_bidi.log_command.info("wait_js_cond: Ignoring/retrying %r", e)
870 time.sleep(1)
871 continue
872
873 break
874
875 assert last_error
876 # rewrite exception to have more context, also for compatibility with existing naughties
877 raise Error(f"timeout\nwait_js_cond({cond}): {last_error.msg}") from None
878
879 def wait_js_func(self, func: str, *args: object) -> None:
880 self.wait_js_cond("{}({})".format(func, ','.join(map(jsquote, args))))
881
882 def is_present(self, selector: str) -> bool:
883 return self.call_js_func('ph_is_present', selector)
884
885 def _wait_present(self, selector: str) -> None:
886 self.wait_js_func('ph_is_present', selector)
887
888 def wait_not_present(self, selector: str) -> None:
889 self.wait_js_func('!ph_is_present', selector)
890
891 def is_visible(self, selector: str) -> bool:
892 return self.call_js_func('ph_is_visible', selector)
893
894 def wait_visible(self, selector: str) -> None:
895 self._wait_present(selector)
896 self.wait_js_func('ph_is_visible', selector)
897
898 def wait_val(self, selector: str, val: object) -> None:
899 self.wait_visible(selector)
900 self.wait_js_func('ph_has_val', selector, val)
901
902 def wait_not_val(self, selector: str, val: str) -> None:
903 self.wait_visible(selector)
904 self.wait_js_func('!ph_has_val', selector, val)
905
906 def wait_attr(self, selector: str, attr: str, val: object) -> None:
907 self._wait_present(selector)
908 self.wait_js_func('ph_has_attr', selector, attr, val)
909
910 def wait_attr_contains(self, selector: str, attr: str, val: str) -> None:
911 self._wait_present(selector)
912 self.wait_js_func('ph_attr_contains', selector, attr, val)
913
914 def wait_attr_not_contains(self, selector: str, attr: str, val: object) -> None:
915 self._wait_present(selector)
916 self.wait_js_func('!ph_attr_contains', selector, attr, val)
917
918 def wait_not_attr(self, selector: str, attr: str, val: object) -> None:
919 self._wait_present(selector)
920 self.wait_js_func('!ph_has_attr', selector, attr, val)
921
922 def wait_not_visible(self, selector: str) -> None:
923 self.wait_js_func('!ph_is_visible', selector)
924
925 def wait_in_text(self, selector: str, text: str) -> None:
926 self.wait_visible(selector)
927 self.wait_js_cond(f"ph_in_text({jsquote(selector)},{jsquote(text)})",
928 error_description="() => 'actual text: ' + ph_text(%s)" % jsquote(selector))
929
930 def wait_not_in_text(self, selector: str, text: str) -> None:
931 self.wait_visible(selector)
932 self.wait_js_func('!ph_in_text', selector, text)
933
934 def wait_collected_text(self, selector: str, text: str) -> None:
935 self.wait_js_func('ph_collected_text_is', selector, text)
936
937 def wait_text(self, selector: str, text: str) -> None:
938 self.wait_visible(selector)
939 self.wait_js_cond(f"ph_text_is({jsquote(selector)},{jsquote(text)})",
940 error_description="() => 'actual text: ' + ph_text(%s)" % jsquote(selector))
941
942 def wait_text_not(self, selector: str, text: str) -> None:
943 self.wait_visible(selector)
944 self.wait_js_func('!ph_text_is', selector, text)
945
946 def wait_text_matches(self, selector: str, pattern: str) -> None:
947 self.wait_visible(selector)
948 self.wait_js_func('ph_text_matches', selector, pattern)
949
950 def wait_popup(self, elem_id: str) -> None:
951 """Wait for a popup to open.
952
953 :param id: the 'id' attribute of the popup.
954 """
955 self.wait_visible('#' + elem_id)
956
957 def wait_language(self, lang: str) -> None:
958 parts = lang.split("-")
959 code_1 = parts[0]
960 code_2 = parts[0]
961 if len(parts) > 1:
962 code_2 += "_" + parts[1].upper()
963 self.wait_js_cond(f"cockpit.language == '{code_1}' || cockpit.language == '{code_2}'")
964
965 def dialog_cancel(self, sel: str, button: str = "button[data-dismiss='modal']") -> None:
966 self.click(sel + " " + button)
967 self.wait_not_visible(sel)
968
969 def enter_page(self, path: str, host: str | None = None, reconnect: bool = True) -> None:
970 """Wait for a page to become current.
971
972 :param path: The identifier the page. This is a string starting with "/"
973 :type path: str
974 :param host: The host to connect too
975 :type host: str
976 :param reconnect: Try to reconnect
977 :type reconnect: bool
978 """
979 assert path.startswith("/")
980 if host:
981 frame = host + path
982 else:
983 frame = "localhost" + path
984 frame = "cockpit1:" + frame
985
986 self.switch_to_top()
987
988 def wait_no_curtain() -> None:
989 # Older shells make the curtain invisible, newer shells
990 # remove it entirely. Let's cater to both.
991 self.wait_js_cond('!ph_is_present(".curtains-ct") || !ph_is_visible(".curtains-ct")')
992
993 while True:
994 try:
995 self._wait_present("iframe.container-frame[name='%s'][data-loaded]" % frame)
996 wait_no_curtain()
997 self.wait_visible("iframe.container-frame[name='%s']" % frame)
998 break
999 except Error as ex:
1000 if reconnect and ex.msg.startswith('timeout'):
1001 reconnect = False
1002 if self.is_present("#machine-reconnect"):
1003 self.click("#machine-reconnect")
1004 wait_no_curtain()
1005 continue
1006 raise
1007
1008 self.switch_to_frame(frame)
1009 self.wait_visible("body")
1010
1011 def leave_page(self) -> None:
1012 self.switch_to_top()
1013
1014 def try_login(
1015 self,
1016 user: str | None = None,
1017 password: str | None = None,
1018 *,
1019 superuser: bool | None = True,
1020 legacy_authorized: bool | None = None
1021 ) -> None:
1022 """Fills in the login dialog and clicks the button.
1023
1024 This differs from login_and_go() by not expecting any particular result.
1025
1026 :param user: the username to login with
1027 :type user: str
1028 :param password: the password of the user
1029 :type password: str
1030 :param superuser: determines whether the new session will try to get Administrative Access (default true)
1031 :type superuser: bool
1032 :param legacy_authorized: old versions of the login dialog that still
1033 have the "[ ] Reuse my password for magic things" checkbox. Such a
1034 dialog is encountered when testing against old bastion hosts, for
1035 example.
1036 """
1037 if user is None:
1038 user = self.default_user
1039 if password is None:
1040 password = self.password
1041 self.wait_visible("#login")
1042 self.set_val('#login-user-input', user)
1043 self.set_val('#login-password-input', password)
1044 if legacy_authorized is not None:
1045 self.set_checked('#authorized-input', legacy_authorized)
1046 if superuser is not None:
1047 self.eval_js('window.localStorage.setItem("superuser:{}", "{}");'.format(user, "any" if superuser else "none"))
1048 self.click('#login-button')
1049
1050 def login_and_go(
1051 self,
1052 path: str | None = None,
1053 *,
1054 user: str | None = None,
1055 host: str | None = None,
1056 superuser: bool | None = True,
1057 urlroot: str | None = None,
1058 tls: bool = False,
1059 password: str | None = None,
1060 legacy_authorized: bool | None = None
1061 ) -> None:
1062 """Fills in the login dialog, clicks the button and navigates to the given path
1063
1064 :param user: the username to login with
1065 :type user: str
1066 :param password: the password of the user
1067 :type password: str
1068 :param superuser: determines whether the new session will try to get Administrative Access (default true)
1069 :type superuser: bool
1070 :param legacy_authorized: old versions of the login dialog that still
1071 have the "[ ] Reuse my password for magic things" checkbox. Such a
1072 dialog is encountered when testing against old bastion hosts, for
1073 example.
1074 """
1075 href = path
1076 if not href:
1077 href = "/"
1078 if urlroot:
1079 href = urlroot + href
1080 if host:
1081 href = "/@" + host + href
1082 self.open(href, tls=tls)
1083
1084 self.try_login(user=user, password=password, superuser=superuser, legacy_authorized=legacy_authorized)
1085
1086 self.wait_visible('#content')
1087 if path:
1088 self.enter_page(path.split("#")[0], host=host)
1089
1090 def logout(self) -> None:
1091 self.assert_no_oops()
1092 self.switch_to_top()
1093
1094 self.wait_visible("#toggle-menu")
1095 if self.is_present("button#machine-reconnect") and self.is_visible("button#machine-reconnect"):
1096 # happens when shutting down cockpit or rebooting machine
1097 self.click("button#machine-reconnect")
1098 else:
1099 # happens when cockpit is still running
1100 self.open_session_menu()
1101 try:
1102 # HACK: real events seem to get lost occasionally, so
1103 # let's use the more reliable synthetic ones.
1104 self.mouse('#logout', "click", synthetic=True)
1105 except RuntimeError as e:
1106 # logging out does destroy the current frame context, it races with the driver finishing the command
1107 if "Execution context was destroyed" not in str(e):
1108 raise
1109 self.wait_visible('#login')
1110
1111 self.machine.allow_restart_journal_messages()
1112
1113 def relogin(
1114 self,
1115 path: str | None = None,
1116 user: str | None = None,
1117 *,
1118 password: str | None = None,
1119 superuser: bool | None = None,
1120 wait_remote_session_machine: testvm.Machine | None = None
1121 ) -> None:
1122 self.logout()
1123 if wait_remote_session_machine:
1124 wait_remote_session_machine.execute("while pgrep -af '[c]ockpit.beiboot'; do sleep 1; done")
1125 self.try_login(user=user, password=password, superuser=superuser)
1126 self.wait_visible('#content')
1127 if path:
1128 if path.startswith("/@"):
1129 host = path[2:].split("/")[0]
1130 else:
1131 host = None
1132 self.enter_page(path.split("#")[0], host=host)
1133
1134 def open_session_menu(self) -> None:
1135 self.wait_visible("#toggle-menu")
1136 if (self.attr("#toggle-menu", "aria-expanded") != "true"):
1137 self.click("#toggle-menu")
1138 # Replace with "#toggle-menu-menu" when all our images have Cockpit > 317
1139 self.wait_visible("button.display-language-menu")
1140
1141 def layout_is_mobile(self) -> bool:
1142 if not self.current_layout:
1143 return False
1144 return self.current_layout["shell_size"][0] < 420
1145
1146 def open_superuser_dialog(self) -> None:
1147 if self.layout_is_mobile():
1148 self.open_session_menu()
1149 self.click("#super-user-indicator-mobile button")
1150 else:
1151 self.click("#super-user-indicator button")
1152
1153 def check_superuser_indicator(self, expected: str) -> None:
1154 if self.layout_is_mobile():
1155 self.open_session_menu()
1156 self.wait_text("#super-user-indicator-mobile", expected)
1157 self.click("#toggle-menu")
1158 else:
1159 self.wait_text("#super-user-indicator", expected)
1160
1161 def become_superuser(
1162 self,
1163 user: str | None = None,
1164 password: str | None = None,
1165 passwordless: bool | None = False
1166 ) -> None:
1167 with self.driver.restore_context():
1168 self.switch_to_top()
1169 self.open_superuser_dialog()
1170
1171 # In (open)SUSE images, superuser access always requires the root password
1172 if user is None:
1173 user = "root" if "suse" in self.machine.image else "admin"
1174
1175 if passwordless:
1176 self.wait_in_text("div[role=dialog]", "Administrative access")
1177 self.wait_in_text("div[role=dialog] .pf-v6-c-modal-box__body", "You now have administrative access.")
1178 # there should be only one ("Close") button
1179 self.click("div[role=dialog] .pf-v6-c-modal-box__footer button")
1180 else:
1181 self.wait_in_text("div[role=dialog]", "Switch to administrative access")
1182 self.wait_in_text("div[role=dialog]", "Password")
1183 self.set_input_text("div[role=dialog] input", password or "foobar")
1184 self.click("div[role=dialog] button.pf-m-primary")
1185
1186 self.wait_not_present("div[role=dialog]")
1187
1188 self.check_superuser_indicator("Administrative access")
1189
1190 def drop_superuser(self) -> None:
1191 with self.driver.restore_context():
1192 self.switch_to_top()
1193 self.open_superuser_dialog()
1194 self.wait_in_text("div[role=dialog]", "Switch to limited access")
1195 self.click("div[role=dialog] button.pf-m-primary")
1196 self.wait_not_present("div[role=dialog]")
1197 self.check_superuser_indicator("Limited access")
1198
1199 def click_system_menu(self, path: str, enter: bool = True) -> None:
1200 """Click on a "System" menu entry with given URL path
1201
1202 Enters the given target frame afterwards, unless enter=False is given
1203 (useful for remote hosts).
1204 """
1205 self.switch_to_top()
1206 self.click(f"#host-apps a[href='{path}']")
1207 if enter:
1208 # strip off parameters after hash
1209 self.enter_page(path.split('#')[0].rstrip('/'))
1210
1211 def get_pf_progress_value(self, progress_bar_sel: str) -> int:
1212 """Get numeric value of a PatternFly <ProgressBar> component"""
1213 sel = progress_bar_sel + " .pf-v6-c-progress__indicator"
1214 self.wait_visible(sel)
1215 self.wait_attr_contains(sel, "style", "width:")
1216 style = self.attr(sel, "style")
1217 m = re.search(r"width: (\d+)%;", style)
1218 assert m is not None
1219 return int(m.group(1))
1220
1221 def get_raw_pf_progress_value(self, progress_bar_sel: str) -> int:
1222 """
1223 Get raw numeric value of a PatternFly <ProgressBar> component
1224
1225 Value from aria-valuenow which is set by PatternFly
1226 """
1227 sel = progress_bar_sel + " .pf-v6-c-progress__bar"
1228 self.wait_visible(f"{sel}[aria-valuenow]")
1229 component_value = self.attr(sel, "aria-valuenow")
1230 assert component_value is not None
1231 return int(component_value)
1232
1233 def start_machine_troubleshoot(
1234 self,
1235 new: bool = False,
1236 known_host: bool = False,
1237 password: str | None = None,
1238 expect_closed_dialog: bool = True,
1239 expect_warning: bool = True,
1240 expect_curtain: bool = True
1241 ) -> None:
1242 if expect_curtain:
1243 self.click('#machine-troubleshoot')
1244
1245 if not new and expect_warning:
1246 self.wait_visible('#hosts_connect_server_dialog')
1247 self.click("#hosts_connect_server_dialog button.pf-m-warning")
1248
1249 self.wait_visible('#hosts_setup_server_dialog')
1250 if new:
1251 self.wait_text("#hosts_setup_server_dialog button.pf-m-primary", "Add")
1252 self.click("#hosts_setup_server_dialog button.pf-m-primary")
1253 if expect_warning:
1254 self.wait_visible('#hosts_connect_server_dialog')
1255 self.click("#hosts_connect_server_dialog button.pf-m-warning")
1256 if not known_host:
1257 self.wait_in_text('#hosts_setup_server_dialog', "You are connecting to")
1258 self.wait_in_text('#hosts_setup_server_dialog', "for the first time.")
1259 self.wait_text("#hosts_setup_server_dialog button.pf-m-primary", "Trust and add host")
1260 self.click("#hosts_setup_server_dialog button.pf-m-primary")
1261 if password:
1262 self.wait_in_text('#hosts_setup_server_dialog', "Unable to log in")
1263 self.set_input_text('#login-custom-password', password)
1264 self.wait_text("#hosts_setup_server_dialog button.pf-m-primary", "Log in")
1265 self.click("#hosts_setup_server_dialog button.pf-m-primary")
1266 if expect_closed_dialog:
1267 self.wait_not_present('#hosts_setup_server_dialog')
1268
1269 def add_machine(self, address: str, known_host: bool = False, password: str | None = "foobar",
1270 expect_warning: bool = True) -> None:
1271 self.switch_to_top()
1272 self.go(f"/@{address}")
1273 self.start_machine_troubleshoot(new=True,
1274 known_host=known_host,
1275 password=password,
1276 expect_warning=expect_warning)
1277 self.enter_page("/system", host=address)
1278
1279 def grant_permissions(self, *args: str) -> None:
1280 """Grant permissions to the browser"""
1281
1282 # BiDi permission extension:
1283 # https://www.w3.org/TR/permissions/#automation-webdriver-bidi
1284 for perm in args:
1285 self.bidi("permissions.setPermission", descriptor={"name": perm}, state="granted",
1286 origin=f"http://{self.address}:{self.port}")
1287
1288 def snapshot(self, title: str, label: str | None = None) -> None:
1289 """Take a snapshot of the current screen and save it as a PNG and HTML.
1290
1291 Arguments:
1292 title: Used for the filename.
1293 """
1294 if self._is_running():
1295 filename = unique_filename(f"{label or self.label}-{title}", "png")
1296 try:
1297 ret = self.bidi("browsingContext.captureScreenshot", quiet=True,
1298 context=self.driver.top_context, origin="document")
1299 with open(filename, 'wb') as f:
1300 f.write(base64.standard_b64decode(ret["data"]))
1301 attach(filename, move=True)
1302 print("Wrote screenshot to " + filename)
1303 except Error as e:
1304 print("Screenshot not available:", e)
1305
1306 filename = unique_filename(f"{label or self.label}-{title}", "html")
1307 try:
1308 html = self.eval_js("document.documentElement.outerHTML", no_trace=True)
1309 with open(filename, 'wb') as f:
1310 f.write(html.encode())
1311 attach(filename, move=True)
1312 print("Wrote HTML dump to " + filename)
1313 except Error as e:
1314 print("HTML dump not available:", e)
1315
1316 def _set_window_size(self, width: int, height: int) -> None:
1317 self.bidi("browsingContext.setViewport", context=self.driver.top_context,
1318 viewport={"width": width, "height": height})
1319
1320 def _set_emulated_media_theme(self, name: str) -> None:
1321 # https://bugzilla.mozilla.org/show_bug.cgi?id=1549434
1322 if self.browser == "chromium":
1323 self.cdp_command("Emulation.setEmulatedMedia", features=[{'name': 'prefers-color-scheme', 'value': name}])
1324
1325 def _set_direction(self, direction: str) -> None:
1326 with self.driver.restore_context():
1327 if self.is_present("#shell-page"):
1328 self.switch_to_top()
1329 self.set_attr("#shell-page", "dir", direction)
1330 self.set_attr("html", "dir", direction)
1331
1332 def set_layout(self, name: str) -> None:
1333 layout = next(lo for lo in self.layouts if lo["name"] == name)
1334 if layout != self.current_layout:
1335 if layout["name"] == "rtl":
1336 self._set_direction("rtl")
1337 elif layout["name"] != "rtl" and self.current_layout and self.current_layout["name"] == "rtl":
1338 self._set_direction("ltr")
1339
1340 self.current_layout = layout
1341 size = layout["shell_size"]
1342 self._set_window_size(size[0], size[1])
1343 self._adjust_window_for_fixed_content_size()
1344 self._set_emulated_media_theme(layout["theme"])
1345
1346 def _adjust_window_for_fixed_content_size(self) -> None:
1347 assert self.current_layout is not None
1348
1349 if self.eval_js("window.name").startswith("cockpit1:"):
1350 # Adjust the window size further so that the content is
1351 # exactly the expected size. This will make sure that
1352 # pixel tests of the content will not be affected by
1353 # changes in shell navigation elements around it. It is
1354 # important that we do this only after getting the shell
1355 # into about the right size so that it switches into the
1356 # right layout mode.
1357 shell_size = self.current_layout["shell_size"]
1358 want_size = self.current_layout["content_size"]
1359 have_size = self.eval_js("[ document.body.offsetWidth, document.body.offsetHeight ]")
1360 delta = (want_size[0] - have_size[0], want_size[1] - have_size[1])
1361 if delta[0] != 0 or delta[1] != 0:
1362 self._set_window_size(shell_size[0] + delta[0], shell_size[1] + delta[1])
1363
1364 def assert_pixels_in_current_layout(
1365 self,
1366 selector: str,
1367 key: str,
1368 *,
1369 ignore: Collection[str] = (),
1370 mock: Mapping[str, str] | None = None,
1371 sit_after_mock: bool = False,
1372 scroll_into_view: str | None = None,
1373 wait_animations: bool = True,
1374 wait_delay: float = 0.5,
1375 chrome_hack_double_shots: bool = False,
1376 abs_tolerance: float = 20
1377 ) -> None:
1378 """Compare the given element with its reference in the current layout"""
1379
1380 if not (Image and self.pixels_label):
1381 return
1382
1383 assert self.current_layout is not None
1384 self._adjust_window_for_fixed_content_size()
1385 self.call_js_func('ph_scrollIntoViewIfNeeded', scroll_into_view or selector)
1386 self.call_js_func('ph_blur_active')
1387
1388 # Wait for all animations to be over. This is done by
1389 # counting them all over and over again until there are zero.
1390 # Calling `.finish()` on all animations would miss those that
1391 # are created while we wait, and would also fail with an
1392 # exception if any unlimited animations are present, like
1393 # spinners.
1394 #
1395 # There is another complication with tooltips. They are shown
1396 # on top of certain elements, but are not DOM children of
1397 # these elements. Also, Patternfly sometimes creates tooltips
1398 # on dialog titles that are too long for the dialog, but only
1399 # a little bit after the dialog has appeared.
1400 #
1401 # We don't want to predict whether tooltips will appear, and
1402 # thus we can't wait for them to be present before waiting for
1403 # their fade-in animation to be over.
1404 #
1405 # But we know that tooltips fade in within 300ms, so we just
1406 # wait half a second to and side-step all that complexity.
1407
1408 if wait_animations:
1409 time.sleep(wait_delay)
1410 self.wait_js_cond('ph_count_animations(%s) == 0' % jsquote(selector))
1411
1412 if mock is not None:
1413 self.set_mock(mock, base=selector)
1414 if sit_after_mock:
1415 sit()
1416
1417 rect = self.call_js_func('ph_element_clip', selector)
1418
1419 def relative_clips(sels: Collection[str]) -> Collection[tuple[int, int, int, int]]:
1420 return [(
1421 r['x'] - rect['x'],
1422 r['y'] - rect['y'],
1423 r['x'] - rect['x'] + r['width'],
1424 r['y'] - rect['y'] + r['height'])
1425 for r in self.call_js_func('ph_selector_clips', sels)]
1426
1427 reference_dir = os.path.join(TEST_DIR, 'reference')
1428 if not os.path.exists(os.path.join(reference_dir, '.git')):
1429 raise SystemError("Pixel test references are missing, please run: test/common/pixel-tests pull")
1430
1431 ignore_rects = relative_clips([f"{selector} {item}" for item in ignore])
1432 base = self.pixels_label + "-" + key
1433 if self.current_layout != self.layouts[0]:
1434 base += "-" + self.current_layout["name"]
1435 filename = base + "-pixels.png"
1436 ref_filename = os.path.join(reference_dir, filename)
1437 self.used_pixel_references.add(ref_filename)
1438 rect["type"] = "box"
1439 ret = self.bidi("browsingContext.captureScreenshot", quiet=True,
1440 context=self.driver.top_context,
1441 clip=rect)
1442 if chrome_hack_double_shots:
1443 # HACK - https://github.com/cockpit-project/cockpit/issues/21577
1444 #
1445 # There is some really evil Chromium bug that often hides the
1446 # primary button in dialog screenshots. But funnily, calling
1447 # captureScreenshot a second time will give us the correct
1448 # rendering, every time.
1449 #
1450 # This doesn't seem to be a race between the page changing and
1451 # us taking screenshots. No amount of waiting here helps
1452 # fully. The second call to captureScreenshot seems to indeed
1453 # trigger something that renders the page again, and correctly
1454 # this time.
1455 #
1456 ret1 = ret
1457 ret = self.bidi("browsingContext.captureScreenshot", quiet=True,
1458 context=self.driver.top_context,
1459 clip=rect)
1460 if ret1["data"] != ret["data"]:
1461 print("WARNING: Inconsistent screenshots for", base)
1462 png_now = base64.standard_b64decode(ret["data"])
1463 png_ref = os.path.exists(ref_filename) and open(ref_filename, "rb").read()
1464 if not png_ref:
1465 with open(filename, 'wb') as f:
1466 f.write(png_now)
1467 attach(filename, move=True)
1468 print("New pixel test reference " + filename)
1469 self.failed_pixel_tests += 1
1470 else:
1471 img_now = Image.open(io.BytesIO(png_now))
1472 img_ref = Image.open(io.BytesIO(png_ref))
1473 img_delta = Image.new("RGBA",
1474 (max(img_now.size[0], img_ref.size[0]), max(img_now.size[1], img_ref.size[1])),
1475 (255, 0, 0, 255))
1476
1477 # The current snapshot and the reference don't need to
1478 # be perfectly identical. They might differ in the
1479 # following ways:
1480 #
1481 # - A pixel in the reference image might be
1482 # transparent. These pixels are ignored.
1483 #
1484 # - The call to assert_pixels specifies a list of
1485 # rectangles (via CSS selectors). Pixels within those
1486 # rectangles (and slightly outside) are ignored. Pixels
1487 # just outside the rectangles are also ignored to avoid
1488 # issues with rounding coordinates.
1489 #
1490 # - The RGB values of pixels can differ by up to 2.
1491 #
1492 # - There can be up to 20 different pixels
1493 #
1494 # Pixels that are different but have been ignored are
1495 # marked in the delta image in green.
1496
1497 def img_eq(ref: Image.Image, now: Image.Image, delta: Image.Image) -> str | None:
1498 if ref.size != now.size:
1499 return f"size mismatch: reference {ref.size[0]}x{ref.size[1]}, now {now.size[0]}x{now.size[1]}"
1500
1501 diff_count = pixelmatch(
1502 img1=ref, img2=now, output=delta, aa_color=(222, 172, 0), masked_areas=ignore_rects, alpha=0.6
1503 )
1504
1505 if diff_count > abs_tolerance:
1506 return f"differs by {diff_count} pixels, tolerance {abs_tolerance}"
1507 return None
1508
1509 reason = img_eq(img_ref, img_now, img_delta)
1510
1511 if reason:
1512 img_now.save(filename)
1513 attach(filename, move=True)
1514 ref_filename_for_attach = base + "-reference.png"
1515 img_ref.save(ref_filename_for_attach)
1516 attach(ref_filename_for_attach, move=True)
1517 delta_filename = base + "-delta.png"
1518 img_delta.save(delta_filename)
1519 attach(delta_filename, move=True)
1520 print(f"Pixel test {base} failed: {reason}")
1521 self.failed_pixel_tests += 1
1522
1523 def assert_pixels(
1524 self,
1525 selector: str,
1526 key: str,
1527 *,
1528 ignore: Collection[str] = (),
1529 mock: Mapping[str, str] | None = None,
1530 sit_after_mock: bool = False,
1531 skip_layouts: Container[str] = (),
1532 scroll_into_view: str | None = None,
1533 wait_animations: bool = True,
1534 wait_after_layout_change: bool = False,
1535 wait_delay: float = 0.5,
1536 layout_change_hook: Callable[[], None] | None = None,
1537 chrome_hack_double_shots: bool = False,
1538 abs_tolerance: float = 20
1539 ) -> None:
1540 """Compare the given element with its reference in all layouts"""
1541
1542 if ignore is None:
1543 ignore = []
1544
1545 if not (Image and self.pixels_label):
1546 return
1547
1548 # If the page overflows make sure to not show a scrollbar
1549 # Don't apply this hack for login and terminal as they don't use PF Page
1550 if not self.is_present("#login-details") and not self.is_present("#system-terminal-page"):
1551 classes = self.attr("body", "class")
1552 self.set_attr("body", "class", f"{classes} pixel-test")
1553
1554 # move the mouse to a harmless place where it doesn't accidentally focus anything (as that changes UI)
1555 self.bidi("input.performActions", context=self.driver.context, actions=[{
1556 "id": "move-away",
1557 "type": "pointer",
1558 "parameters": {"pointerType": "mouse"},
1559 "actions": [{"type": "pointerMove", "x": 2000, "y": 0, "origin": "viewport"}]
1560 }])
1561
1562 if self.current_layout:
1563 previous_layout = self.current_layout["name"]
1564 for layout in self.layouts:
1565 if layout["name"] not in skip_layouts:
1566 self.set_layout(layout["name"])
1567 if wait_after_layout_change:
1568 time.sleep(wait_delay)
1569 if layout_change_hook:
1570 layout_change_hook()
1571 self.assert_pixels_in_current_layout(selector, key, ignore=ignore,
1572 mock=mock, sit_after_mock=sit_after_mock,
1573 scroll_into_view=scroll_into_view,
1574 wait_animations=wait_animations,
1575 wait_delay=wait_delay,
1576 chrome_hack_double_shots=chrome_hack_double_shots,
1577 abs_tolerance=abs_tolerance)
1578
1579 self.set_layout(previous_layout)
1580
1581 def assert_no_unused_pixel_test_references(self) -> None:
1582 """Check whether all reference images in test/reference have been used."""
1583
1584 if not (Image and self.pixels_label):
1585 return
1586
1587 pixel_references = set(glob.glob(os.path.join(TEST_DIR, "reference", self.pixels_label + "-*-pixels.png")))
1588 unused = pixel_references - self.used_pixel_references
1589 for u in unused:
1590 print("Unused reference image " + os.path.basename(u))
1591 self.failed_pixel_tests += 1
1592
1593 def get_js_log(self) -> Sequence[str]:
1594 """Return the current javascript log"""
1595
1596 if self._is_running():
1597 return [str(log) for log in self.driver.logs]
1598 return []
1599
1600 def copy_js_log(self, title: str, label: str | None = None) -> None:
1601 """Copy the current javascript log"""
1602
1603 logs = self.get_js_log()
1604 if logs:
1605 filename = unique_filename(f"{label or self.label}-{title}", "js.log")
1606 with open(filename, 'wb') as f:
1607 f.write('\n'.join(logs).encode())
1608 attach(filename, move=True)
1609 print("Wrote JS log to " + filename)
1610
1611 def write_coverage_data(self) -> None:
1612 if self.coverage_label and self._is_running():
1613 coverage = self.cdp_command("Profiler.takePreciseCoverage")
1614 write_lcov(coverage['result'], self.coverage_label)
1615
1616 def assert_no_oops(self) -> None:
1617 if self.allow_oops:
1618 return
1619
1620 if self.have_test_api():
1621 self.switch_to_top()
1622 if self.eval_js("!!document.getElementById('navbar-oops')"):
1623 assert not self.is_visible("#navbar-oops"), "Cockpit shows an Oops"
1624
1625
1626 class MachineCase(unittest.TestCase):
1627 image = testvm.DEFAULT_IMAGE
1628 libexecdir: str | None = None
1629 sshd_socket: str | None = None
1630 runner = None
1631 machine: testvm.Machine
1632 machines: Mapping[str, testvm.Machine]
1633 machine_class: type[testvm.VirtMachine] | None = None
1634 browser: Browser
1635 network = None
1636 journal_start: str | None = None
1637
1638 # provision is a dictionary of dictionaries, one for each additional machine to be created, e.g.:
1639 # provision = { 'openshift' : { 'image': 'openshift', 'memory_mb': 1024 } }
1640 # These will be instantiated during setUp, and replaced with machine objects
1641 provision: ClassVar[Mapping[str, Mapping[str, Any]] | None] = None
1642
1643 global_machine = None
1644
1645 @classmethod
1646 def get_global_machine(cls) -> testvm.Machine:
1647 if cls.global_machine:
1648 return cls.global_machine
1649 cls.global_machine = cls().new_machine(restrict=True, cleanup=False)
1650 if opts.trace:
1651 print(f"Starting global machine {cls.global_machine.label}")
1652 cls.global_machine.start()
1653 return cls.global_machine
1654
1655 @classmethod
1656 def kill_global_machine(cls) -> None:
1657 if cls.global_machine:
1658 cls.global_machine.kill()
1659 cls.global_machine = None
1660
1661 def label(self) -> str:
1662 return self.__class__.__name__ + '-' + self._testMethodName
1663
1664 def new_machine(
1665 self,
1666 image: str | None = None,
1667 forward: Mapping[str, int] | None = None,
1668 restrict: bool = True,
1669 cleanup: bool = True,
1670 inherit_machine_class: bool = True,
1671 **kwargs: Any
1672 ) -> testvm.Machine:
1673 machine_class = (inherit_machine_class and self.machine_class) or testvm.VirtMachine
1674
1675 if opts.address:
1676 if forward:
1677 raise unittest.SkipTest("Cannot run this test when specific machine address is specified")
1678 machine = testvm.Machine(address=opts.address, image=image or self.image,
1679 verbose=opts.trace, browser=opts.browser)
1680 if cleanup:
1681 self.addCleanup(machine.disconnect)
1682 else:
1683 if image is None:
1684 image = os.path.join(TEST_DIR, "images", self.image)
1685 if not os.path.exists(image):
1686 raise FileNotFoundError("Can't run tests without a prepared image; use test/image-prepare")
1687 if not self.network:
1688 network = testvm.VirtNetwork(image=image)
1689 if cleanup:
1690 self.addCleanup(network.kill)
1691 self.network = network
1692 networking = self.network.host(restrict=restrict, forward=forward or {})
1693 machine = machine_class(verbose=opts.trace, networking=networking, image=image, **kwargs)
1694 image_file = machine.image_file
1695 if opts.fetch and not os.path.exists(image_file):
1696 machine.pull(image_file)
1697 if cleanup:
1698 self.addCleanup(machine.kill)
1699 return machine
1700
1701 def new_browser(self, machine: testvm.Machine | None = None, coverage: bool = False) -> Browser:
1702 if machine is None:
1703 machine = self.machine
1704 label = self.label() + "-" + machine.label
1705 pixels_label = None
1706 if os.environ.get("TEST_BROWSER", "chromium") == "chromium" and not self.is_devel_build():
1707 try:
1708 with open(f'{TEST_DIR}/reference-image') as fp:
1709 reference_image = fp.read().strip()
1710 except FileNotFoundError:
1711 # no "reference-image" file available; this most likely means that
1712 # there are no pixel tests to execute
1713 pass
1714 else:
1715 if machine.image == reference_image:
1716 pixels_label = self.label()
1717 browser = Browser(machine.web_address,
1718 label=label, pixels_label=pixels_label, coverage_label=self.label() if coverage else None,
1719 port=machine.web_port, machine=self)
1720 self.addCleanup(browser.kill)
1721 return browser
1722
1723 def getError(self) -> str | None:
1724 # errors is a list of (method, exception) calls (usually multiple
1725 # per method); None exception means success
1726 errors = []
1727 assert hasattr(self, '_outcome')
1728 if hasattr(self._outcome, 'errors'):
1729 assert hasattr(self, '_feedErrorsToResult')
1730 # Python 3.4 - 3.10 (These two methods have no side effects)
1731 result = self.defaultTestResult()
1732 errors = result.errors
1733 self._feedErrorsToResult(result, self._outcome.errors)
1734 elif hasattr(self._outcome, 'result') and getattr(self._outcome.result, '_excinfo', None) is not None:
1735 # pytest emulating unittest
1736 if isinstance(self._outcome.result._excinfo, str):
1737 return self._outcome.result._excinfo
1738 else:
1739 assert isinstance(self._outcome.result._excinfo, list)
1740 return str(self._outcome.result._excinfo[0])
1741
1742 else:
1743 # Python 3.11+ now records errors and failures separate
1744 errors = getattr(self._outcome.result, 'errors', []) + getattr(self._outcome.result, 'failures', [])
1745
1746 try:
1747 return errors[0][1]
1748 except IndexError:
1749 return None
1750
1751 def is_nondestructive(self) -> bool:
1752 test_method = getattr(self.__class__, self._testMethodName)
1753 return get_decorator(test_method, self.__class__, "nondestructive")
1754
1755 def is_devel_build(self) -> bool:
1756 return os.environ.get('NODE_ENV') == 'development'
1757
1758 def disable_preload(self, *packages: str, machine: testvm.Machine | None = None) -> None:
1759 if machine is None:
1760 machine = self.machine
1761 for pkg in packages:
1762 machine.write(f"/etc/cockpit/{pkg}.override.json", '{ "preload": [ ] }')
1763
1764 def enable_preload(self, package: str, *pages: str) -> None:
1765 pages_str = ', '.join(f'"{page}"' for page in pages)
1766 self.machine.write(f"/etc/cockpit/{package}.override.json", f'{{ "preload": [ {pages_str} ] }}')
1767
1768 def system_before(self, version: int) -> bool:
1769 try:
1770 v = self.machine.execute("""rpm -q --qf '%{V}' cockpit-system ||
1771 dpkg-query -W -f '${source:Upstream-Version}' cockpit-system ||
1772 (pacman -Q cockpit | cut -f2 -d' ' | cut -f1 -d-)
1773 """).split(".")
1774 except subprocess.CalledProcessError:
1775 return False
1776
1777 return int(v[0]) < version
1778
1779 def setUp(self) -> None:
1780 self.allowed_messages = self.default_allowed_messages
1781 self.allowed_console_errors = self.default_allowed_console_errors
1782 self.allow_core_dumps = False
1783
1784 if os.getenv("MACHINE"):
1785 # apply env variable together if MACHINE envvar is set
1786 opts.address = os.getenv("MACHINE")
1787 if self.is_nondestructive():
1788 pass
1789 elif os.getenv("DESTRUCTIVE") and not self.is_nondestructive():
1790 print("Run destructive test, be careful, may lead to upredictable state of machine")
1791 else:
1792 raise unittest.SkipTest("Skip destructive test by default")
1793 if os.getenv("BROWSER"):
1794 opts.browser = os.getenv("BROWSER")
1795 if os.getenv("TRACE"):
1796 opts.trace = True
1797 if os.getenv("SIT"):
1798 opts.sit = True
1799
1800 if opts.address and self.provision is not None:
1801 raise unittest.SkipTest("Cannot provision multiple machines if a specific machine address is specified")
1802
1803 self.machines = {}
1804 provision = self.provision or {'machine1': {}}
1805 self.tmpdir = tempfile.mkdtemp()
1806 # automatically cleaned up for @nondestructive tests, but you have to create it yourself
1807 self.vm_tmpdir = "/var/lib/cockpittest"
1808
1809 if self.is_nondestructive() and not opts.address:
1810 if self.provision:
1811 raise unittest.SkipTest("Cannot provision machines if test is marked as nondestructive")
1812 self.machine = self.machines['machine1'] = MachineCase.get_global_machine()
1813 else:
1814 MachineCase.kill_global_machine()
1815 first_machine = True
1816 # First create all machines, wait for them later
1817 for key in sorted(provision.keys()):
1818 options = dict(provision[key])
1819 options.pop('address', None)
1820 options.pop('address6', None)
1821 options.pop('dns', None)
1822 options.pop('dhcp', None)
1823 machine = self.new_machine(**options)
1824 self.machines[key] = machine
1825 if first_machine:
1826 first_machine = False
1827 self.machine = machine
1828 if opts.trace:
1829 print(f"Starting {key} {machine.label}")
1830 machine.start()
1831
1832 self.danger_btn_class = '.pf-m-danger'
1833 self.primary_btn_class = '.pf-m-primary'
1834 self.default_btn_class = '.pf-m-secondary'
1835
1836 # Now wait for the other machines to be up
1837 for key in self.machines.keys():
1838 machine = self.machines[key]
1839 machine.wait_boot()
1840 address = provision[key].get("address", None)
1841 address6 = provision[key].get("address6", None)
1842 if address is not None or address6 is not None:
1843 machine.set_address(address, address6)
1844 dns = provision[key].get("dns")
1845 if address or dns:
1846 machine.set_dns(dns)
1847 dhcp = provision[key].get("dhcp", False)
1848 if dhcp:
1849 machine.dhcp_server()
1850
1851 m = self.machine
1852 self.journal_start = m.journal_cursor()
1853 self.browser = self.new_browser(coverage=opts.coverage)
1854 # fail tests on criticals
1855 m.write("/etc/cockpit/cockpit.conf", "[Log]\nFatal = criticals\n")
1856 if self.is_nondestructive():
1857 self.nonDestructiveSetup()
1858
1859 # Pages with debug enabled are huge and loading/executing them is heavy for browsers
1860 # To make it easier for browsers and thus make tests quicker, disable packagekit and systemd preloads
1861 if self.is_devel_build():
1862 self.disable_preload("packagekit", "systemd")
1863
1864 image = m.image
1865
1866 if image.startswith(('debian', 'ubuntu')) or image == 'arch':
1867 self.libexecdir = '/usr/lib/cockpit'
1868 else:
1869 self.libexecdir = '/usr/libexec'
1870
1871 if image.startswith(('debian', 'ubuntu')):
1872 self.sshd_service = 'ssh.service'
1873 self.sshd_socket = 'ssh.socket'
1874 else:
1875 self.sshd_service = 'sshd.service'
1876 if image == 'arch':
1877 self.sshd_socket = None
1878 else:
1879 self.sshd_socket = 'sshd.socket'
1880 self.restart_sshd = f'systemctl try-restart {self.sshd_service}'
1881
1882 # only enabled by default on released OSes; see pkg/shell/manifest.json
1883 self.multihost_enabled = image.startswith(("rhel-9", "centos-9"))
1884
1885 # sudo-rs behaves quite differently, tests need to adapt
1886 self.has_sudo_rs = image.startswith("ubuntu") and image not in ["ubuntu-stable"]
1887
1888 def nonDestructiveSetup(self) -> None:
1889 """generic setUp/tearDown for @nondestructive tests"""
1890
1891 m = self.machine
1892
1893 # helps with mapping journal output to particular tests
1894 name = f"{self.__class__.__name__}.{self._testMethodName}"
1895 m.execute("logger -p user.info 'COCKPITTEST: start %s'" % name)
1896 self.addCleanup(m.execute, "logger -p user.info 'COCKPITTEST: end %s'" % name)
1897
1898 # core dumps get copied per-test, don't clobber subsequent tests with them
1899 self.addCleanup(m.execute, "find /var/lib/systemd/coredump -type f -delete")
1900
1901 # temporary directory in the VM
1902 self.addCleanup(m.execute, f"""
1903 if [ -d {self.vm_tmpdir} ]; then
1904 findmnt --list --noheadings --output TARGET | grep ^{self.vm_tmpdir} | xargs -r umount
1905 rm -r {self.vm_tmpdir}
1906 fi""")
1907
1908 # users/groups/home dirs
1909 self.restore_file("/etc/passwd")
1910 self.restore_file("/etc/group")
1911 self.restore_file("/etc/shadow")
1912 self.restore_file("/etc/gshadow")
1913 self.restore_file("/etc/subuid")
1914 self.restore_file("/etc/subgid")
1915 self.restore_file("/var/log/wtmp")
1916
1917 def get_home_dirs() -> Sequence[str]:
1918 return m.execute("if [ -d /home ]; then ls /home; fi").strip().split()
1919
1920 initial_home_dirs = get_home_dirs()
1921
1922 def cleanup_home_dirs() -> None:
1923 for d in get_home_dirs():
1924 if d not in initial_home_dirs:
1925 m.execute("rm -r /home/" + d)
1926 self.addCleanup(cleanup_home_dirs)
1927
1928 if m.image == "arch":
1929 # arch configures pam_faillock by default
1930 self.addCleanup(m.execute, "rm -rf /run/faillock")
1931
1932 # cockpit configuration
1933 self.restore_dir("/etc/cockpit")
1934
1935 # for storage tests
1936 self.restore_file("/etc/fstab")
1937 self.restore_file("/etc/crypttab")
1938
1939 if not m.ws_container:
1940 # tests expect cockpit.service to not run at start; also, avoid log leakage into the next test
1941 self.addCleanup(m.execute, "systemctl stop --quiet cockpit")
1942
1943 # The sssd daemon seems to get confused when we restore
1944 # backups of /etc/group etc and stops following updates to it.
1945 # Let's restart the daemon to reset that condition.
1946 m.execute("systemctl try-restart sssd || true")
1947
1948 # reset scsi_debug (see e. g. StorageHelpers.add_ram_disk()
1949 # this needs to happen very late in the cleanup, so that test cases can clean up the users of that disk first
1950 # right after unmounting the device is often still busy, so retry a few times
1951 self.addCleanup(self.machine.execute,
1952 "set -e; [ -e /sys/module/scsi_debug ] || exit 0; "
1953 "for dev in $(ls /sys/bus/pseudo/drivers/scsi_debug/adapter*/host*/target*/*:*/block); do "
1954 " for s in /sys/block/*/slaves/${dev}*; do [ -e $s ] || break; "
1955 " d=/dev/$(dirname $(dirname ${s#/sys/block/})); "
1956 " while fuser --mount $d --kill; do sleep 0.1; done; "
1957 " umount $d || true; dmsetup remove --force $d || true; "
1958 " done; "
1959 " while fuser --mount /dev/$dev --kill; do sleep 0.1; done; "
1960 " umount /dev/$dev || true; "
1961 " swapon --show=NAME --noheadings | grep $dev | xargs -r swapoff; "
1962 "done; until rmmod scsi_debug; do sleep 0.2; done", stdout=None)
1963
1964 def _terminate_sessions(self) -> None:
1965 m = self.machine
1966
1967 # on OSTree we don't get "web console" sessions with the cockpit/ws container; just SSH; but also, some tests start
1968 # admin sessions without Cockpit
1969 m.execute("""for u in $(loginctl --no-legend list-users | awk '{ if ($2 != "root") print $1 }'); do
1970 loginctl terminate-user $u 2>/dev/null || true
1971 loginctl kill-user $u 2>/dev/null || true
1972 pkill -9 -u $u || true
1973 while pgrep -u $u; do sleep 0.2; done
1974 while mountpoint -q /run/user/$u && ! umount /run/user/$u; do sleep 0.2; done
1975 rm -rf /run/user/$u
1976 done""")
1977
1978 # Terminate all other Cockpit sessions
1979 sessions = m.execute("loginctl --no-legend list-sessions | awk '/web console/ { print $1 }'").strip().split()
1980 for s in sessions:
1981 # Don't insist that terminating works, the session might be gone by now.
1982 m.execute(f"loginctl kill-session {s} || true; loginctl terminate-session {s} || true")
1983
1984 # Restart logind to mop up empty "closing" sessions; https://github.com/systemd/systemd/issues/26744
1985 m.execute("systemctl stop systemd-logind")
1986
1987 # Wait for sessions to be gone
1988 sessions = m.execute("loginctl --no-legend list-sessions | awk '/web console/ { print $1 }'").strip().split()
1989 for s in sessions:
1990 try:
1991 m.execute(f"while loginctl show-session {s}; do sleep 0.2; done", timeout=30)
1992 except RuntimeError:
1993 # show the status in debug logs, to see what's wrong
1994 m.execute(f"loginctl session-status {s}; systemd-cgls", stdout=None)
1995 raise
1996
1997 # terminate all systemd user services for users who are not logged in
1998 # since systemd 256 we stop user@*.service now also stops the root session (uid 0)
1999 m.execute("cd /run/systemd/users/; "
2000 "for f in $(ls); do [ $f -le 500 ] || systemctl stop user@$f; done")
2001
2002 # Clean up "closing" sessions again, and clean user id cache for non-system users
2003 m.execute("systemctl stop systemd-logind; cd /run/systemd/users/; "
2004 "for f in $(ls); do [ $f -le 500 ] || rm $f; done")
2005
2006 def tearDown(self) -> None:
2007 error = self.getError()
2008
2009 if error:
2010 print(error, file=sys.stderr)
2011 try:
2012 self.snapshot("FAIL")
2013 self.copy_js_log("FAIL")
2014 self.copy_journal("FAIL")
2015 self.copy_cores("FAIL")
2016 except (OSError, RuntimeError):
2017 # failures in these debug artifacts should not skip cleanup actions
2018 sys.stderr.write("Failed to generate debug artifact:\n")
2019 traceback.print_exc(file=sys.stderr)
2020
2021 if opts.sit:
2022 sit(self.machines)
2023
2024 if self.browser:
2025 self.browser.write_coverage_data()
2026
2027 if self.machine.ssh_reachable:
2028 self.check_journal_messages()
2029 if not error:
2030 self.check_browser_errors()
2031 self.check_pixel_tests()
2032
2033 if self.is_nondestructive():
2034 self._terminate_sessions()
2035
2036 shutil.rmtree(self.tmpdir, ignore_errors=True)
2037
2038 def enable_multihost(self, machine: testvm.Machine) -> None:
2039 if isBeibootLogin():
2040 raise NotImplementedError("multi-host config change not currently implemented for beiboot scenario")
2041 if not self.multihost_enabled:
2042 machine.write("/etc/cockpit/cockpit.conf",
2043 '[WebService]\nAllowMultiHost=yes\n')
2044 machine.restart_cockpit()
2045
2046 def login_and_go(
2047 self,
2048 path: str | None = None,
2049 *,
2050 user: str | None = None,
2051 password: str | None = None,
2052 host: str | None = None,
2053 superuser: bool = True,
2054 urlroot: str | None = None,
2055 tls: bool = False,
2056 enable_root_login: bool = False
2057 ) -> None:
2058 if enable_root_login:
2059 self.enable_root_login()
2060 self.machine.start_cockpit(tls=tls)
2061 # first load after starting cockpit tends to take longer, due to on-demand service start
2062 with self.browser.wait_timeout(30):
2063 self.browser.login_and_go(path, user=user, password=password, host=host, superuser=superuser,
2064 urlroot=urlroot, tls=tls)
2065
2066 # List of allowed journal messages during tests; these need to match the *entire* message
2067 default_allowed_messages = [
2068 # Reauth stuff
2069 '.*Reauthorizing unix-user:.*',
2070 '.*user .* was reauthorized.*',
2071
2072 # Happens when the user logs out during reauthorization
2073 "Error executing command as another user: Not authorized",
2074 "This incident has been reported.",
2075
2076 # Reboots are ok
2077 "-- Reboot --",
2078
2079 # Sometimes D-Bus goes away before us during shutdown
2080 "Lost the name com.redhat.Cockpit on the session message bus",
2081 "GLib-GIO:ERROR:gdbusobjectmanagerserver\\.c:.*:g_dbus_object_manager_server_emit_interfaces_.*: assertion failed \\(error == NULL\\): The connection is closed \\(g-io-error-quark, 18\\)",
2082 "Error sending message: The connection is closed",
2083
2084 # PAM noise
2085 "cockpit-session: pam: Creating directory .*",
2086 "cockpit-session: pam: Changing password for .*",
2087
2088 # btmp tracking
2089 "cockpit-session: pam: Last failed login:.*",
2090 "cockpit-session: pam: Last login: .*",
2091 "cockpit-session: pam: There .* failed login attempts? since the last successful login.",
2092
2093 # pam_lastlog complaints
2094 ".*/var/log/lastlog: No such file or directory",
2095
2096 # ssh messages may be dropped when closing
2097 '10.*: dropping message while waiting for child to exit',
2098
2099 # pkg/packagekit/autoupdates.jsx backend check often gets interrupted by logout
2100 "xargs: basename: terminated by signal 13",
2101
2102 # SELinux messages to ignore
2103 "(audit: )?type=1403 audit.*",
2104 "(audit: )?type=1404 audit.*",
2105 "(audit: )?type=1405 audit.*",
2106
2107 # apparmor loading
2108 "(audit: )?type=1400.*apparmor=\"STATUS\".*",
2109
2110 # apparmor noise
2111 "(audit: )?type=1400.*apparmor=\"ALLOWED\".*",
2112
2113 # Messages from systemd libraries when they are in debug mode
2114 'Successfully loaded SELinux database in.*',
2115 'calling: info',
2116 'Sent message type=method_call sender=.*',
2117 'Got message type=method_return sender=.*',
2118
2119 # Various operating systems see this from time to time
2120 "Journal file.*truncated, ignoring file.",
2121
2122 # our core dump retrieval is not entirely reliable
2123 "Failed to send coredump datagram:.*",
2124
2125 # Something crashed, but we don't have more info. Don't fail on that
2126 "Failed to get (COMM|EXE).*: No such process",
2127
2128 # several tests change the host name
2129 "sudo: unable to resolve host.*",
2130
2131 # The usual sudo finger wagging
2132 "We trust you have received the usual lecture from the local System",
2133 "Administrator. It usually boils down to these three things:",
2134 r"#1\) Respect the privacy of others.",
2135 r"#2\) Think before you type.",
2136 r"#3\) With great power comes great responsibility.",
2137 "For security reasons, the password you type will not be visible",
2138
2139 # starting out with empty PCP logs and pmlogger not running causes these metrics channel messages
2140 "(direct|pcp-archive): no such metric: .*: Unknown metric name",
2141 "(direct|pcp-archive): instance name lookup failed:.*",
2142 "(direct|pcp-archive): couldn't create pcp archive context for.*",
2143
2144 # PCP Python bridge
2145 "cockpit.channels.pcp-ERROR: no such metric: .*",
2146
2147 # timedatex.service shuts down after timeout, runs into race condition with property watching
2148 ".*org.freedesktop.timedate1: couldn't get all properties.*Error:org.freedesktop.DBus.Error.NoReply.*",
2149
2150 # Ubuntu 25.10 triggers systemd-detect-virt apparmor violations
2151 '.*apparmor="DENIED" operation="capable" class="cap" profile="systemd-detect-virt".*',
2152 # similar on 26.04
2153 '.*apparmor="DENIED" operation="sendmsg" class="file" profile="systemd-detect-virt".*',
2154 ]
2155
2156 default_allowed_messages += os.environ.get("TEST_ALLOW_JOURNAL_MESSAGES", "").split(",")
2157
2158 # List of allowed console.error() messages during tests; these match substrings
2159 default_allowed_console_errors = [
2160 # HACK: These should be fixed, but debugging these is not trivial, and the impact is very low
2161 "Warning: .* setState.*on an unmounted component",
2162 "Warning: Can't perform a React state update on an unmounted component",
2163 "Warning: Cannot update a component.*while rendering a different component",
2164 "Warning: A component is changing an uncontrolled input to be controlled",
2165 "Warning: A component is changing a controlled input to be uncontrolled",
2166 "Warning: Can't call.*on a component that is not yet mounted. This is a no-op",
2167 "Warning: Cannot update during an existing state transition",
2168 r"Warning: You are calling ReactDOMClient.createRoot\(\) on a container that has already been passed to createRoot",
2169
2170 # FIXME: PatternFly complains about these, but https://www.a11y-collective.com/blog/the-first-rule-for-using-aria/
2171 # and https://www.accessibility-developer-guide.com/knowledge/aria/bad-practices/
2172 "aria-label",
2173
2174 # PackageKit crashes a lot; let that not be the sole reason for failing a test
2175 "error: Could not determine kpatch packages:.*PackageKit crashed",
2176 ]
2177
2178 env_allow = os.environ.get("TEST_ALLOW_BROWSER_ERRORS")
2179 if env_allow:
2180 default_allowed_console_errors += env_allow.split(",")
2181
2182 def allow_journal_messages(self, *patterns: str) -> None:
2183 """Don't fail if the journal contains a entry completely matching the given regexp"""
2184 for p in patterns:
2185 self.allowed_messages.append(p)
2186
2187 def allow_hostkey_messages(self) -> None:
2188 self.allow_journal_messages('.*: .* host key for server is not known: .*',
2189 '.*: refusing to connect to unknown host: .*',
2190 '.*: .* host key for server has changed to: .*',
2191 '.*: host key for this server changed key type: .*',
2192 '.*: failed to retrieve resource: hostkey-unknown')
2193
2194 def allow_restart_journal_messages(self) -> None:
2195 self.allow_journal_messages(".*Connection reset by peer.*",
2196 "connection unexpectedly closed by peer",
2197 ".*gnutls_handshake failed.*",
2198 # stopping the unit while requests are pending removes the .sock files
2199 "cockpit-tls: .* No such file or directory",
2200 ".*Broken pipe.*",
2201 "g_dbus_connection_real_closed: Remote peer vanished with error: Underlying GIOStream returned 0 bytes on an async read \\(g-io-error-quark, 0\\). Exiting.",
2202 "cockpit-session: .*timed out.*",
2203 "ignoring failure from session process:.*",
2204 "peer did not close io when expected",
2205 "request timed out, closing",
2206 "PolicyKit daemon disconnected from the bus.",
2207 ".*couldn't create polkit session subject: No session for pid.*",
2208 "We are no longer a registered authentication agent.",
2209 ".*: failed to retrieve resource: terminated",
2210 ".*: external channel failed:.*",
2211 ".*: truncated data in external channel",
2212 'audit:.*denied.*comm="systemd-user-se".*nologin.*',
2213 ".*No session for cookie",
2214
2215 'localhost: dropping message while waiting for child to exit',
2216 '.*: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: .*',
2217 '.*g_dbus_connection_call_finish_internal.*G_IS_DBUS_CONNECTION.*',
2218 '.*Message recipient disconnected from message bus without replying.*',
2219 '.*Unable to shutdown socket: Transport endpoint is not connected.*',
2220
2221 # If restarts or reloads happen really fast, the code in python.js
2222 # that figures out which python to use crashes with SIGPIPE,
2223 # and this is the resulting message
2224 'which: no python in .*'
2225 )
2226
2227 # happens when logging out quickly while tracer is running
2228 self.allow_browser_errors("Tracer failed:.*internal-error")
2229
2230 def check_journal_messages(self, machine: testvm.Machine | None = None) -> None:
2231 """Check for unexpected journal entries."""
2232 machine = machine or self.machine
2233 # on main machine, only consider journal entries since test case start
2234 cursor = self.journal_start if machine == self.machine else None
2235
2236 # Journald does not always set trusted fields like
2237 # _SYSTEMD_UNIT or _EXE correctly for the last few messages of
2238 # a dying process, so we filter by the untrusted but reliable
2239 # SYSLOG_IDENTIFIER instead.
2240
2241 matches = [
2242 "SYSLOG_IDENTIFIER=cockpit-ws",
2243 "SYSLOG_IDENTIFIER=cockpit-tls",
2244 "SYSLOG_IDENTIFIER=cockpit-bridge",
2245 "SYSLOG_IDENTIFIER=cockpit/ssh",
2246 # also catch GLIB_DOMAIN=<library> which apply to cockpit-ws (but not to -bridge, too much random noise)
2247 "_COMM=cockpit-ws",
2248 "GLIB_DOMAIN=cockpit-ws",
2249 "GLIB_DOMAIN=cockpit-bridge",
2250 ]
2251
2252 if not self.allow_core_dumps:
2253 matches += ["SYSLOG_IDENTIFIER=systemd-coredump"]
2254 self.allowed_messages.append("Resource limits disable core dumping for process.*")
2255 # can happen on shutdown when /run/systemd/coredump is gone already
2256 self.allowed_messages.append("Failed to connect to coredump service: No such file or directory")
2257 self.allowed_messages.append("Failed to connect to coredump service: Connection refused")
2258
2259 messages = machine.journal_messages(matches, 6, cursor=cursor)
2260
2261 if "TEST_AUDIT_NO_SELINUX" not in os.environ:
2262 messages += machine.audit_messages("14", cursor=cursor) # 14xx is selinux
2263
2264 self.allowed_messages += self.machine.allowed_messages()
2265
2266 all_found = True
2267 first = None
2268 for m in messages:
2269 # remove leading/trailing whitespace
2270 m = m.strip()
2271 # Ignore empty lines
2272 if not m:
2273 continue
2274 found = False
2275
2276 # When coredump could not be generated, we cannot do much with info about there being a coredump
2277 # Ignore this message and all subsequent core dumps
2278 # If there is more than just one line about coredump, it will fail and show this messages
2279 if m.startswith("Failed to generate stack trace"):
2280 self.allowed_messages.append("Process .* of user .* dumped core.*")
2281 continue
2282
2283 for p in self.allowed_messages:
2284 match = re.match(p, m)
2285 if match and match.group(0) == m:
2286 found = True
2287 break
2288 if not found:
2289 all_found = False
2290 if not first:
2291 first = m
2292 print(m)
2293 if not all_found:
2294 assert first is not None
2295 self.copy_js_log("FAIL")
2296 self.copy_journal("FAIL")
2297 self.copy_cores("FAIL")
2298 if not self.getError():
2299 # fail test on the unexpected messages
2300 raise Error(UNEXPECTED_MESSAGE + "journal messages:\n" + first)
2301
2302 def allow_browser_errors(self, *patterns: str) -> None:
2303 """Don't fail if the test caused a console error contains the given regexp"""
2304 for p in patterns:
2305 self.allowed_console_errors.append(p)
2306
2307 def check_browser_errors(self) -> None:
2308 if not self.browser:
2309 return
2310 for log in self.browser.get_js_log():
2311 if not log.startswith("error: "):
2312 continue
2313 # errors are fatal in general; they need to be explicitly whitelisted
2314 for p in self.allowed_console_errors:
2315 if re.search(p, log):
2316 break
2317 else:
2318 raise Error(UNEXPECTED_MESSAGE + "browser errors:\n" + log)
2319
2320 self.browser.assert_no_oops()
2321
2322 def check_pixel_tests(self) -> None:
2323 if self.browser:
2324 self.browser.assert_no_unused_pixel_test_references()
2325 if self.browser.failed_pixel_tests > 0:
2326 raise Error(PIXEL_TEST_MESSAGE)
2327
2328 def snapshot(self, title: str, label: str | None = None) -> None:
2329 """Take a snapshot of the current screen and save it as a PNG.
2330
2331 Arguments:
2332 title: Used for the filename.
2333 """
2334 if self.browser is not None:
2335 try:
2336 self.browser.snapshot(title, label)
2337 except Error:
2338 # this usually runs in exception handlers; raising an exception here skips cleanup handlers, so don't
2339 sys.stderr.write("Unexpected exception in snapshot():\n")
2340 sys.stderr.write(traceback.format_exc())
2341
2342 def copy_js_log(self, title: str, label: str | None = None) -> None:
2343 if self.browser is not None:
2344 try:
2345 self.browser.copy_js_log(title, label)
2346 except RuntimeError:
2347 # this usually runs in exception handlers; raising an exception here skips cleanup handlers, so don't
2348 sys.stderr.write("Unexpected exception in copy_js_log():\n")
2349 sys.stderr.write(traceback.format_exc())
2350
2351 def copy_journal(self, title: str, label: str | None = None) -> None:
2352 for _, m in self.machines.items():
2353 if m.ssh_reachable:
2354 log = unique_filename(f"{label or self.label()}-{m.label}-{title}", "log.gz")
2355 with open(log, "w") as fp:
2356 m.execute("journalctl|gzip", stdout=fp)
2357 print("Journal extracted to %s" % (log))
2358 attach(log, move=True)
2359
2360 def copy_cores(self, title: str, label: str | None = None) -> None:
2361 if self.allow_core_dumps:
2362 return
2363 for _, m in self.machines.items():
2364 if m.ssh_reachable:
2365 directory = f"{label or self.label()}-{m.label}-{title}.core"
2366 dest = os.path.abspath(directory)
2367 # overwrite core dumps from previous retries
2368 if os.path.exists(dest):
2369 shutil.rmtree(dest)
2370 m.download_dir("/var/lib/systemd/coredump", dest)
2371 try:
2372 os.rmdir(dest)
2373 except OSError as ex:
2374 if ex.errno == errno.ENOTEMPTY:
2375 print("Core dumps downloaded to %s" % (dest))
2376 # Enable this to temporarily(!) create artifacts for core dumps, if a crash is hard to reproduce
2377 # attach(dest, move=True)
2378
2379 def settle_cpu(self) -> None:
2380 """Wait until CPU usage in the VM settles down
2381
2382 Wait until the process with the highest CPU usage drops below 20%
2383 usage. Wait for up to a minute, then return. There is no error if the
2384 CPU stays busy, as usually a test then should just try to run anyway.
2385 """
2386 for _ in range(20):
2387 # get the CPU percentage of the most busy process
2388 busy_proc = self.machine.execute("ps --no-headers -eo pcpu,pid,args | sort -k 1 -n -r | head -n1")
2389 if float(busy_proc.split()[0]) < 20.0:
2390 break
2391 time.sleep(3)
2392
2393 def sed_file(self, expr: str, path: str, apply_change_action: str | None = None) -> None:
2394 """sed a file on primary machine
2395
2396 This is safe for @nondestructive tests, the file will be restored during cleanup.
2397
2398 The optional apply_change_action will be run both after sedding and after restoring the file.
2399 """
2400 m = self.machine
2401 m.execute(f"sed -i.cockpittest '{expr}' {path}")
2402 if apply_change_action:
2403 m.execute(apply_change_action)
2404
2405 if self.is_nondestructive():
2406 if apply_change_action:
2407 self.addCleanup(m.execute, apply_change_action)
2408 self.addCleanup(m.execute, f"mv {path}.cockpittest {path}")
2409
2410 def file_exists(self, path: str) -> bool:
2411 """Check if file exists on test machine"""
2412 return self.machine.execute(f"if test -e {path}; then echo yes; fi").strip() != ""
2413
2414 def restore_dir(
2415 self,
2416 path: str,
2417 post_restore_action: str | None = None,
2418 reboot_safe: bool = False,
2419 restart_unit: str | None = None
2420 ) -> None:
2421 """Backup/restore a directory for a nondestructive test
2422
2423 This takes care to not ever touch the original content on disk, but uses transient overlays.
2424 As this uses a bind mount, it does not work for files that get changed atomically (with mv);
2425 use restore_file() for these.
2426
2427 `restart_unit` will be stopped before restoring path, and restarted afterwards if it was running.
2428 The optional post_restore_action will run after restoring the original content.
2429
2430 If the directory needs to survive reboot, `reboot_safe=True` needs to be specified; then this
2431 will just backup/restore the directory instead of bind-mounting, which is less robust.
2432 """
2433 if not self.is_nondestructive():
2434 return # skip for efficiency reasons
2435
2436 exe = self.machine.execute
2437
2438 if not self.file_exists(path):
2439 self.addCleanup(exe, f"rm -rf '{path}'")
2440 return
2441
2442 backup = os.path.join(self.vm_tmpdir, path.replace('/', '_'))
2443 exe(f"mkdir -p {self.vm_tmpdir}; cp -a {path}/ {backup}/")
2444
2445 if not reboot_safe:
2446 exe(f"mount -o bind {backup} {path}")
2447
2448 if restart_unit:
2449 restart_stamp = f"/run/cockpit_restart_{restart_unit}"
2450 self.addCleanup(
2451 exe,
2452 f"if [ -e {restart_stamp} ]; then systemctl start {restart_unit}; rm {restart_stamp}; fi"
2453 )
2454
2455 if post_restore_action:
2456 self.addCleanup(exe, post_restore_action)
2457
2458 if reboot_safe:
2459 self.addCleanup(exe, f"rm -rf {path}; mv {backup} {path}")
2460 else:
2461 # HACK: a lot of tests call this on /home/...; that restoration happens before killing all user
2462 # processes in nonDestructiveSetup(), so we have to do it lazily
2463 if path.startswith("/home"):
2464 cmd = f"umount -lf {path}"
2465 else:
2466 cmd = f"umount {path} || {{ fuser -uvk {path} {path}/* >&2 || true; sleep 1; umount {path}; }}"
2467 self.addCleanup(exe, cmd)
2468
2469 if restart_unit:
2470 self.addCleanup(exe, f"if systemctl --quiet is-active {restart_unit}; then touch {restart_stamp}; fi; "
2471 f"systemctl stop {restart_unit}")
2472
2473 def restore_file(self, path: str, post_restore_action: str | None = None) -> None:
2474 """Backup/restore a file for a nondestructive test
2475
2476 This is less robust than restore_dir(), but works for files that need to get changed atomically.
2477
2478 If path does not currently exist, it will be removed again on cleanup.
2479 """
2480 if not self.is_nondestructive():
2481 return # skip for efficiency reasons
2482
2483 if post_restore_action:
2484 self.addCleanup(self.machine.execute, post_restore_action)
2485
2486 if self.file_exists(path):
2487 backup = os.path.join(self.vm_tmpdir, path.replace('/', '_'))
2488 self.machine.execute(f"mkdir -p {self.vm_tmpdir}; cp -a {path} {backup}")
2489 self.addCleanup(self.machine.execute, f"mv {backup} {path}")
2490 else:
2491 self.addCleanup(self.machine.execute, f"rm -f {path}")
2492
2493 def write_file(
2494 self,
2495 path: str,
2496 content: str,
2497 append: bool = False,
2498 owner: str | None = None,
2499 perm: str | None = None,
2500 post_restore_action: str | None = None
2501 ) -> None:
2502 """Write a file on primary machine
2503
2504 This is safe for @nondestructive tests, the file will be removed during cleanup.
2505
2506 If @append is True, append to existing file instead of replacing it.
2507 @owner is the desired file owner as chown shell string (e.g. "admin:nogroup")
2508 @perm is the desired file permission as chmod shell string (e.g. "0600")
2509 """
2510 m = self.machine
2511 self.restore_file(path, post_restore_action=post_restore_action)
2512 m.write(path, content, append=append, owner=owner, perm=perm)
2513
2514 def enable_root_login(self) -> None:
2515 """Enable root login
2516
2517 By default root login is disabled in cockpit, removing the root entry of
2518 /etc/cockpit/disallowed-users allows root to login.
2519 """
2520
2521 disallowed_conf = '/etc/cockpit/disallowed-users'
2522 if not self.machine.ws_container and self.file_exists(disallowed_conf):
2523 self.sed_file('/root/d', disallowed_conf)
2524
2525 def get_sudo_user(self) -> str:
2526 # In (open)SUSE images, superuser access always requires the root password
2527 return "root" if "suse" in self.image else "admin"
2528
2529 def reboot(self, timeout_sec: int | None = None) -> None:
2530 self.allow_restart_journal_messages()
2531 if timeout_sec is None:
2532 self.machine.reboot()
2533 else:
2534 self.machine.reboot(timeout_sec=timeout_sec)
2535
2536 def wait_reboot(self, timeout_sec: int | None = None) -> None:
2537 self.allow_restart_journal_messages()
2538 if timeout_sec is None:
2539 self.machine.wait_reboot()
2540 else:
2541 self.machine.wait_reboot(timeout_sec=timeout_sec)
2542
2543 def setup_provisioned_hosts(self, disable_preload: bool = False) -> None:
2544 """Setup provisioned hosts for testing
2545
2546 This sets the hostname of all machines to the name given in the
2547 provision dictionary and optionally disabled preload.
2548 """
2549 for name, m in self.machines.items():
2550 m.execute(f"hostnamectl set-hostname {name}")
2551 if disable_preload:
2552 self.disable_preload("packagekit", "playground", "systemd", machine=m)
2553
2554 @staticmethod
2555 def authorize_pubkey(machine: testvm.Machine, account: str, pubkey: str) -> None:
2556 machine.execute(f"a={account} d=/home/$a/.ssh; mkdir -p $d; chown $a:$a $d; chmod 700 $d")
2557 machine.write(f"/home/{account}/.ssh/authorized_keys", pubkey)
2558 machine.execute(f"a={account}; chown $a:$a /home/$a/.ssh/authorized_keys")
2559
2560 @staticmethod
2561 def get_pubkey(machine: testvm.Machine, account: str) -> str:
2562 return machine.execute(f"cat /home/{account}/.ssh/id_rsa.pub")
2563
2564 def setup_ssh_auth(self) -> None:
2565 self.machine.execute("d=/home/admin/.ssh; mkdir -p $d; chown admin:admin $d; chmod 700 $d")
2566 self.machine.execute("test -f /home/admin/.ssh/id_rsa || ssh-keygen -f /home/admin/.ssh/id_rsa -t rsa -N ''")
2567 self.machine.execute("chown admin:admin /home/admin/.ssh/id_rsa*")
2568 pubkey = self.get_pubkey(self.machine, "admin")
2569
2570 for m in self.machines:
2571 self.authorize_pubkey(self.machines[m], "admin", pubkey)
2572
2573
2574 ###########################
2575 # Global helper functions
2576 #
2577
2578
2579 def jsquote(js: object) -> str:
2580 return json.dumps(js)
2581
2582
2583 def get_decorator(method: object, class_: object, name: str, default: Any = None) -> Any:
2584 """Get decorator value of a test method or its class
2585
2586 Return None if the decorator was not set.
2587 """
2588 attr = "_testlib__" + name
2589 return getattr(method, attr, getattr(class_, attr, default))
2590
2591
2592 ###########################
2593 # Test decorators
2594 #
2595
2596
2597 def skipBrowser(reason: str, *browsers: str) -> Callable[[_FT], _FT]:
2598 """Decorator for skipping a test on given browser(s)
2599
2600 Skips a test for provided *reason* on *browsers*.
2601 """
2602 browser = os.environ.get("TEST_BROWSER", "chromium")
2603 if browser in browsers:
2604 return unittest.skip(f"{browser}: {reason}")
2605 return lambda testEntity: testEntity
2606
2607
2608 def skipImage(reason: str, *images: str) -> Callable[[_FT], _FT]:
2609 """Decorator for skipping a test for given image(s)
2610
2611 Skip a test for a provided *reason* for given *images*. These
2612 support Unix shell style patterns via fnmatch.fnmatch.
2613
2614 Example: @skipImage("no btrfs support on RHEL", "rhel-*")
2615 """
2616 if any(fnmatch.fnmatch(testvm.DEFAULT_IMAGE, img) for img in images):
2617 return unittest.skip(f"{testvm.DEFAULT_IMAGE}: {reason}")
2618 return lambda testEntity: testEntity
2619
2620
2621 def onlyImage(reason: str, *images: str) -> Callable[[_FT], _FT]:
2622 """Decorator to only run a test on given image(s)
2623
2624 Only run this test on provided *images* for *reason*. These
2625 support Unix shell style patterns via fnmatch.fnmatch.
2626 """
2627 if not any(fnmatch.fnmatch(testvm.DEFAULT_IMAGE, arg) for arg in images):
2628 return unittest.skip(f"{testvm.DEFAULT_IMAGE}: {reason}")
2629 return lambda testEntity: testEntity
2630
2631
2632 def skipOstree(reason: str) -> Callable[[_FT], _FT]:
2633 """Decorator for skipping a test on OSTree images
2634
2635 Skip test for *reason* on OSTree images defined in OSTREE_IMAGES in bots/lib/constants.py.
2636 """
2637 if testvm.DEFAULT_IMAGE in OSTREE_IMAGES:
2638 return unittest.skip(f"{testvm.DEFAULT_IMAGE}: {reason}")
2639 return lambda testEntity: testEntity
2640
2641
2642 def isBeibootLogin() -> bool:
2643 return "ws-container" in os.getenv("TEST_SCENARIO", "")
2644
2645
2646 def skipWsContainer(reason: str) -> Callable[[_FT], _FT]:
2647 """Decorator for skipping a test with cockpit/ws"""
2648 if testvm.DEFAULT_IMAGE in OSTREE_IMAGES or isBeibootLogin():
2649 return unittest.skip(f"{testvm.DEFAULT_IMAGE}: {reason}")
2650 return lambda testEntity: testEntity
2651
2652
2653 def skipBeiboot(reason: str) -> Callable[[_FT], _FT]:
2654 """Decorator for skipping a test with cockpit/ws in beiboot mode"""
2655 if isBeibootLogin():
2656 return unittest.skip(f"{testvm.DEFAULT_IMAGE}: {reason}")
2657 return lambda testEntity: testEntity
2658
2659
2660 def skipDaily(reason: str) -> Callable[[_FT], _FT]:
2661 """Decorator for skipping a test with fedora-*/nightly"""
2662 if "daily" in os.getenv("TEST_SCENARIO", ""):
2663 return unittest.skip(f"{testvm.DEFAULT_IMAGE}: {reason}")
2664 return lambda testEntity: testEntity
2665
2666
2667 def nondestructive(testEntity: _T) -> _T:
2668 """Tests decorated as nondestructive will all run against the same VM
2669
2670 Can be used on test classes and individual test methods.
2671 """
2672 setattr(testEntity, '_testlib__nondestructive', True)
2673 return testEntity
2674
2675
2676 def destructive(testEntity: _T) -> _T:
2677 """Tests decorated as destructive will get their own VM
2678
2679 Can be used on test classes and individual test methods.
2680 """
2681 setattr(testEntity, '_testlib__nondestructive', False)
2682 return testEntity
2683
2684
2685 def no_retry_when_changed(testEntity: _T) -> _T:
2686 """Tests decorated with no_retry_when_changed will only run once if they've been changed
2687
2688 Tests that have been changed are expected to succeed 3 times, if the test
2689 takes a long time, this prevents timeouts. Can be used on test classes and
2690 individual methods.
2691 """
2692 setattr(testEntity, '_testlib__no_retry_when_changed', True)
2693 return testEntity
2694
2695
2696 def todo(reason: str = '') -> Callable[[_T], _T]:
2697 """Tests decorated with @todo are expected to fail.
2698
2699 An optional reason can be given, and will appear in the TAP output if run
2700 via run-tests.
2701 """
2702 def wrapper(testEntity: _T) -> _T:
2703 setattr(testEntity, '_testlib__todo', reason)
2704 return testEntity
2705 return wrapper
2706
2707
2708 def timeout(seconds: int) -> Callable[[_T], _T]:
2709 """Change default test timeout of 600s, for long running tests
2710
2711 Can be applied to an individual test method or the entire class. This only
2712 applies to test/common/run-tests, not to calling check-* directly.
2713 """
2714 def wrapper(testEntity: _T) -> _T:
2715 setattr(testEntity, '_testlib__timeout', seconds)
2716 return testEntity
2717 return wrapper
2718
2719
2720 class TapRunner:
2721 def __init__(self, verbosity: int = 1):
2722 self.verbosity = verbosity
2723
2724 def runOne(self, test: unittest.TestCase) -> unittest.TestResult:
2725 result = unittest.TestResult()
2726 print('# ----------------------------------------------------------------------')
2727 print('#', test)
2728 try:
2729 unittest.TestSuite([test]).run(result)
2730 except KeyboardInterrupt:
2731 result.addError(test, sys.exc_info())
2732 return result
2733 except Exception:
2734 result.addError(test, sys.exc_info())
2735 sys.stderr.write(f"Unexpected exception while running {test}\n")
2736 sys.stderr.write(traceback.format_exc())
2737 return result
2738 else:
2739 result.printErrors()
2740
2741 if result.skipped:
2742 print(f"# Result {test} skipped: {result.skipped[0][1]}")
2743 elif result.wasSuccessful():
2744 print(f"# Result {test} succeeded")
2745 else:
2746 for failure in result.failures:
2747 print(failure[1])
2748 for error in result.errors:
2749 print(error[1])
2750 print(f"# Result {test} failed")
2751 return result
2752
2753 def run(self, testable: unittest.TestSuite) -> int:
2754 tests: list[unittest.TestCase] = []
2755
2756 # The things to test
2757 def collapse(test: unittest.TestCase | unittest.TestSuite, tests: list[unittest.TestCase]) -> None:
2758 if isinstance(test, unittest.TestCase):
2759 tests.append(test)
2760 else:
2761 for t in test:
2762 collapse(t, tests)
2763 collapse(testable, tests)
2764 test_count = len(tests)
2765
2766 # For statistics
2767 start = time.time()
2768 failures = 0
2769 skips = []
2770 while tests:
2771 # The next test to test
2772 test = tests.pop(0)
2773 result = self.runOne(test)
2774 if not result.wasSuccessful():
2775 failures += 1
2776 skips += result.skipped
2777
2778 # Report on the results
2779 duration = int(time.time() - start)
2780 hostname = socket.gethostname().split(".")[0]
2781 details = f"[{duration}s on {hostname}]"
2782
2783 MachineCase.kill_global_machine()
2784
2785 # Return 77 if all tests were skipped
2786 if len(skips) == test_count:
2787 skipstr = ", ".join([f"{s[0]!s} {s[1]}" for s in skips])
2788 sys.stdout.write(f"# SKIP {skipstr}\n")
2789 return 77
2790 if failures:
2791 plural = "S" if failures > 1 else ""
2792 sys.stdout.write(f"# {failures} TEST{plural} FAILED {details}\n")
2793 return 1
2794 else:
2795 plural = "S" if test_count > 1 else ""
2796 sys.stdout.write(f"# {test_count} TEST{plural} PASSED {details}\n")
2797 return 0
2798
2799
2800 def print_tests(tests: unittest.TestSuite | Collection[unittest.TestSuite | unittest.TestCase]) -> None:
2801 assert hasattr(unittest.loader, '_FailedTest')
2802 for test in tests:
2803 if isinstance(test, unittest.TestSuite):
2804 print_tests(test)
2805 elif isinstance(test, unittest.loader._FailedTest):
2806 name = test.id().replace("unittest.loader._FailedTest.", "")
2807 print(f"Error: '{name}' does not match a test", file=sys.stderr)
2808 else:
2809 print(test.id().replace("__main__.", ""))
2810
2811
2812 @dataclass
2813 class TestlibArgs:
2814 coverage: bool
2815 enable_network: bool
2816 fetch: bool
2817 list: bool
2818 sit: bool
2819 trace: bool
2820 verbosity: int
2821 tests: Sequence[str]
2822
2823
2824 def arg_parser(enable_sit: bool = True) -> argparse.ArgumentParser:
2825 parser = argparse.ArgumentParser(description='Run Cockpit test(s)')
2826 parser.add_argument('-v', '--verbose', dest="verbosity", action='store_const',
2827 const=2, help='Verbose output')
2828 parser.add_argument('-t', "--trace", dest='trace', action='store_true',
2829 help='Trace machine boot and commands')
2830 parser.add_argument('-q', '--quiet', dest='verbosity', action='store_const',
2831 const=0, help='Quiet output')
2832 if enable_sit:
2833 parser.add_argument('-s', "--sit", dest='sit', action='store_true',
2834 help="Sit and wait after test failure")
2835 else:
2836 parser.set_defaults(sit=False)
2837 parser.add_argument('--nonet', dest="fetch", action="store_false",
2838 help="Don't go online to download images or data")
2839 parser.add_argument('--enable-network', dest='enable_network', action='store_true',
2840 help="Enable network access for tests")
2841 parser.add_argument('--coverage', action='store_true',
2842 help="Collect code coverage data")
2843 parser.add_argument("-l", "--list", action="store_true", help="Print the list of tests that would be executed")
2844 # TMT compatibility, pass testnames as whitespace separated list
2845 parser.add_argument('tests', nargs='*', default=os.getenv("TEST_NAMES", '').split())
2846
2847 parser.set_defaults(verbosity=1, fetch=True)
2848 return parser
2849
2850
2851 def test_main(
2852 options: argparse.Namespace | None = None, # ruff: ignore[pytest-parameter-with-default-argument]
2853 suite: unittest.TestSuite | None = None, # ruff: ignore[pytest-parameter-with-default-argument]
2854 attachments: str | None = None, # ruff: ignore[pytest-parameter-with-default-argument]
2855 ) -> int:
2856 """
2857 Run all test cases, as indicated by arguments.
2858
2859 If no arguments are given on the command line, all test cases are
2860 executed. Otherwise only the given test cases are run.
2861 """
2862
2863 global opts
2864
2865 # Turn off python stdout buffering
2866 buf_arg = 0
2867 os.environ['PYTHONUNBUFFERED'] = '1'
2868 buf_arg = 1
2869 sys.stdout.flush()
2870 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buf_arg)
2871
2872 parser = arg_parser()
2873 parser.add_argument('--machine', metavar="hostname[:port]", dest="address",
2874 default=None, help="Run this test against an already running machine")
2875 parser.add_argument('--browser', metavar="hostname[:port]", dest="browser",
2876 default=None, help="When using --machine, use this cockpit web address")
2877
2878 if options is None:
2879 options = parser.parse_args()
2880 standalone = True
2881 else:
2882 standalone = False
2883
2884 # Sit should always imply verbose
2885 if options.sit:
2886 options.verbosity = 2
2887
2888 # Have to copy into opts due to python globals across modules
2889 for (key, value) in vars(options).items():
2890 setattr(opts, key, value)
2891
2892 opts.address = getattr(opts, "address", None)
2893 opts.browser = getattr(opts, "browser", None)
2894 opts.attachments = os.environ.get("TEST_ATTACHMENTS", attachments)
2895 if opts.attachments:
2896 os.makedirs(opts.attachments, exist_ok=True)
2897
2898 import __main__
2899 if len(opts.tests) > 0:
2900 if suite:
2901 parser.error("tests may not be specified when running a predefined test suite")
2902 suite = unittest.TestLoader().loadTestsFromNames(opts.tests, module=__main__)
2903 elif not suite:
2904 suite = unittest.TestLoader().loadTestsFromModule(__main__)
2905
2906 if options.list:
2907 print_tests(suite)
2908 return 0
2909
2910 attach(os.path.join(TEST_DIR, "common/pixeldiff.html"))
2911 attach(os.path.join(TEST_DIR, "common/link-patterns.json"))
2912
2913 runner = TapRunner(verbosity=opts.verbosity)
2914 ret = runner.run(suite)
2915 if not standalone:
2916 return ret
2917 sys.exit(ret)
2918
2919
2920 class Error(Exception):
2921 def __init__(self, msg: str) -> None:
2922 self.msg = msg
2923
2924 def __str__(self) -> str:
2925 return self.msg
2926
2927
2928 def wait(func: Callable[[], _T | None], msg: str | None = None, delay: int = 1, tries: int = 60) -> _T:
2929 """Wait for FUNC to return something truthy, and return that.
2930
2931 FUNC is called repeatedly until it returns a true value or until a
2932 timeout occurs. In the latter case, a exception is raised that
2933 describes the situation. The exception is either the last one
2934 thrown by FUNC, or includes MSG, or a default message.
2935
2936 :param func: The function to call
2937 :param msg: A error message to use when the timeout occurs. Defaults
2938 to a generic message.
2939 :param delay: How long to wait between calls to FUNC, in seconds. (default 1)
2940 :param tries: How often to call FUNC. (defaults 60)
2941 :raises Error: When a timeout occurs.
2942 """
2943
2944 t = 0
2945 while t < tries:
2946 try:
2947 val = func()
2948 if val:
2949 return val
2950 except Exception:
2951 if t == tries - 1:
2952 raise
2953 t = t + 1
2954 time.sleep(delay)
2955 raise Error(msg or "Condition did not become true.")
2956
2957
2958 def sit(machines: Mapping[str, testvm.Machine] = {}) -> None:
2959 """
2960 Wait until the user confirms to continue.
2961
2962 The current test case is suspended so that the user can inspect
2963 the browser.
2964 """
2965
2966 for machine in machines.values():
2967 sys.stderr.write(machine.diagnose())
2968 print("Press RET to continue...")
2969 sys.stdin.readline()