Debian Codegraph @

test/verify/check-system-terminal

raw
1 #!/usr/bin/python3 -cimport os, sys; os.execv(os.path.dirname(sys.argv[1]) + "/../common/pywrap", sys.argv)
2
3 #
4 # Copyright (C) 2013 Red Hat, Inc.
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6
7
8 import testlib
9
10
11 def line_sel(i: int) -> str:
12 return f'.terminal .xterm-accessibility-tree div:nth-child({i})'
13
14
15 @testlib.nondestructive
16 class TestTerminal(testlib.MachineCase):
17 def setUp(self) -> None:
18 super().setUp()
19
20 # Make sure we get what we expect
21 self.write_file("/home/admin/.bashrc", r"""
22 PS1="\u@local \W]\$ "
23 PROMPT_COMMAND='printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/\~}"'
24 """, append=True)
25
26 # Remove failed units which will show up in the first terminal line
27 self.machine.execute("systemctl reset-failed")
28
29 def wait_line(self, lineno: int, text: str) -> None:
30 b = self.browser
31 try:
32 b.wait_text(line_sel(lineno), text)
33 except Exception as e:
34 print("-----")
35 for j in range(max(1, lineno - 5), lineno + 5):
36 print(b.text(line_sel(j)))
37 print("-----")
38 raise e
39
40 def clear_terminal(self) -> None:
41 b = self.browser
42 b.input_text("clear")
43 b.wait_js_cond("ph_text('.terminal').indexOf('clear') >= 0")
44 # now wait for clear to take effect
45 b.key("Enter")
46 b.wait_js_cond("ph_text('.xterm-accessibility-tree').indexOf('clear') < 0")
47
48 def testBasic(self) -> None:
49 b = self.browser
50 m = self.machine
51
52 self.login_and_go("/system/terminal")
53 blank_state = ' '
54
55 # Firefox headless does not support WebGL2,
56 # empty state should be visible when WebGL2 is not available
57 if b.browser == "firefox":
58 b.wait_visible(".pf-v6-c-empty-state")
59 b.wait_in_text(".pf-v6-c-empty-state__title-text", "Terminal not available")
60 return
61
62 # wait until first line is not empty
63 n = 1
64 b.wait_visible(".terminal .xterm-accessibility-tree")
65 function_str = "(function (sel) { return ph_text(sel).trim() != '%s'})" % blank_state
66 b.wait_js_func(function_str, line_sel(n))
67
68 self.clear_terminal()
69 # now we should get a clean prompt
70 b.wait_in_text(line_sel(n), '$')
71
72 # cut trailing non-breaking spaces
73 prompt = b.text(line_sel(n))
74
75 # Make sure we are started in home directory
76 # Account for non-standard prompting
77 if "]" not in prompt:
78 self.assertIn(":~$", prompt)
79 else:
80 self.assertIn("~]$", prompt)
81
82 # Run some commands
83 b.input_text("whoami\n")
84 self.wait_line(n + 1, "admin")
85
86 self.wait_line(n + 2, prompt)
87
88 b.input_text('echo -e "1\\u0041"\n')
89 self.wait_line(n + 3, '1A')
90 self.wait_line(n + 4, prompt)
91
92 # non-UTF8 data
93 m.execute(r"echo -e 'hello\xFF\x01\xFF\x02world' > " + self.vm_tmpdir + "/garbage.txt")
94 b.input_text(f'cat {self.vm_tmpdir}/garbage.txt\n')
95 self.wait_line(n + 5, 'helloworld')
96 self.wait_line(n + 6, prompt)
97
98 # The '@' sign is in the default prompt
99 b.wait_in_text(".terminal-title", '@')
100
101 # output flooding
102 b.input_text("seq 1000000\n")
103 with b.wait_timeout(300):
104 b.wait_in_text(".terminal .xterm-accessibility-tree", "9999989999991000000admin@")
105
106 b.assert_pixels("#terminal .terminal-group", "header", ignore=[".terminal-title"])
107 b.assert_pixels("#terminal .xterm-screen", "text")
108
109 # now reset terminal
110 b.click('button:contains("Reset")')
111
112 # assert that the output from earlier is gone
113 self.wait_line(n + 1, blank_state)
114 self.assertNotIn('admin', b.text(line_sel(n + 1)))
115
116 # Check that when we `exit` we can still reconnect with the 'Reset' button
117 b.input_text("exit\n")
118 b.wait_in_text(".terminal .xterm-accessibility-tree", "disconnected")
119 b.click('button:contains("Reset")')
120 self.wait_line(n, prompt)
121 b.wait_not_in_text(".terminal .xterm-accessibility-tree", "disconnected")
122
123 def select_line(sel: str, width: int) -> None:
124 # Select line by dragging mouse
125 # Height on a line is around 14px, so start approx. in the middle of line
126 b.mouse(sel, "mousedown", 0, 7)
127 b.mouse(sel, "mousemove", width, 7)
128 b.mouse(sel, "mouseup", width, 7)
129
130 # Firefox does not support setting of permissions
131 # and therefore we cannot test copy/paste with context menu
132 if b.browser != "firefox":
133 b.grant_permissions("clipboard-read", "clipboard-write")
134
135 # Execute command
136 self.wait_line(n, prompt)
137 b.input_text('echo "XYZ"\n')
138 echo_result_line = n + 1
139
140 self.wait_line(echo_result_line, "XYZ")
141
142 sel = line_sel(echo_result_line)
143
144 # Highlight 40px (3 letters, never wider that ~14px)
145 select_line(sel, 40)
146
147 # Right click to context menu and pick copy
148 b.mouse(sel, "click", btn=2)
149 # Skipping mobile and medium layouts as these are the same with the default desktop layout
150 b.assert_pixels("#terminal .contextMenu", "context-menu", skip_layouts=["mobile", "medium"])
151 b.click('.contextMenu li:first-child button')
152
153 # Right click and pick paste
154 b.mouse(sel, "click", btn=2)
155 b.click('.contextMenu li:nth-child(2) button')
156
157 # Wait for text to show up
158 self.wait_line(echo_result_line + 1, prompt + "XYZ")
159 b.key('Enter')
160 b.wait_in_text(line_sel(echo_result_line + 2), 'XYZ')
161
162 # now reset terminal
163 b.click('button:contains("Reset")')
164
165 # assert that the output from earlier is gone
166 self.wait_line(n + 1, blank_state)
167
168 # Execute another command
169 self.wait_line(n, prompt)
170 b.input_text('echo "foo"\n')
171 echo_result_line = n + 1
172
173 self.wait_line(echo_result_line, "foo")
174
175 sel = line_sel(echo_result_line)
176 # Highlight 40px (3 letters, never wider that ~14px)
177 select_line(sel, 40)
178
179 # Use keyboard shortcuts to copy text
180 b.key("Insert", modifiers=["Control"])
181 b.key("Insert", modifiers=["Shift"])
182
183 # Wait for text to show up
184 self.wait_line(echo_result_line + 1, prompt + "foo")
185 b.key("Backspace", repeat=3)
186
187 # Key-who-must-not-be-named, non-breakable space does weird things,
188 # see https://github.com/cockpit-project/cockpit/issues/21213
189 # this must not crash the session, should be ignored
190 b.input_text("echo space")
191 b.key("Space", modifiers=["Control"])
192 b.key("Enter")
193 self.wait_line(echo_result_line + 2, "space")
194
195 # check that we get a sensible $PATH; this varies across OSes, so don't be too strict about it
196 b.input_text('clear\n')
197 b.input_text("echo $PATH > /tmp/path\n")
198 # don't use wait_line() for the full match here, as line breaks get in the way; just wait until command has run
199 self.wait_line(echo_result_line, prompt)
200 path = m.execute("cat /tmp/path").strip()
201 if m.ws_container:
202 self.assertIn("/usr/local/bin:/usr/bin", path)
203 elif m.image == "arch":
204 self.assertIn("/usr/local/sbin:/usr/local/bin:/usr/bin", path)
205 else:
206 self.assertIn("/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", path)
207 self.assertNotIn(":/.local", path) # would happen with empty $HOME
208
209 def check_theme_select(name: str, style: str) -> None:
210 b.select_from_dropdown("#theme-select + div select", name)
211 b.wait_attr_contains(".xterm-scrollable-element", "style", style)
212
213 # Check that color theme changes
214 white_style = "background-color: rgb(255, 255, 255);"
215
216 check_theme_select("black-theme", "background-color: rgb(0, 0, 0);")
217 check_theme_select("dark-theme", "background-color: rgb(0, 43, 54);")
218 check_theme_select("light-theme", "background-color: rgb(253, 246, 227);")
219 check_theme_select("white-theme", white_style)
220
221 # clear terminal to compare font styling on a clean terminal page
222 self.clear_terminal()
223 b.wait_in_text(line_sel(n), '$')
224
225 # Test changing of font size
226 b.wait_val("#toolbar input", 16)
227 current_style = b.attr(".xterm-accessibility-tree div:first-child", "style")
228 b.click("#toolbar button[aria-label='Increase by one']")
229 new_style = b.attr(".xterm-accessibility-tree div:first-child", "style")
230 self.assertNotEqual(current_style, new_style)
231
232 # Unfocus the terminal before switching away to stop the
233 # cursor from blinking, which hopefully avoids internal
234 # Firefox errors related to canvs rendering in invisible
235 # iframes.
236
237 b.focus("#toolbar input")
238
239 # Relogin and white-style and bigger font should be remembered
240 # Relogin on different page, as reloging on terminal prompts asking if you want to leave the site
241
242 b.go("/system")
243 b.relogin("/system")
244 b.go("/system/terminal")
245 b.enter_page("/system/terminal")
246 b.wait_visible('.terminal')
247 b.wait_in_text(line_sel(n), '$')
248 b.wait_attr_contains(".xterm-scrollable-element", "style", white_style)
249 b.wait_val("#toolbar input", 17)
250 b.wait_attr(".xterm-accessibility-tree div:first-child", "style", new_style)
251 b.click("#toolbar button[aria-label='Decrease by one']")
252 b.wait_val("#toolbar input", 16)
253 b.wait_attr(".xterm-accessibility-tree div:first-child", "style", current_style)
254
255 # Check limit for font size
256 for i in range(15, 5, -1):
257 b.click("#toolbar button[aria-label='Decrease by one']")
258 b.wait_val("#toolbar input", i)
259 b.wait_visible("#toolbar button[aria-label='Decrease by one']:disabled")
260
261 @testlib.skipBrowser("WebGL2 is not supported in firefox headless mode, terminal page will not load", "firefox")
262 def testOnlyTerminal(self) -> None:
263 b = self.browser
264 m = self.machine
265
266 m.write("/etc/cockpit/cockpit.conf", "[WebService]\nShell = /system/terminal.html\n")
267 m.start_cockpit()
268 b.open("/")
269
270 b.try_login("admin", "foobar")
271 b.wait_visible("#terminal")
272
273 # wait until first line is not empty
274 n = 1
275 b.wait_visible(".terminal .xterm-accessibility-tree")
276 b.wait_js_func("(function (sel) { return ph_text(sel).trim() != ' '})", line_sel(n))
277
278 # execute a command we can see the effect of
279 b.wait_js_cond("ph_text('.terminal').indexOf('uid=') == -1")
280 b.input_text("id\n")
281 b.wait_js_cond("ph_text('.terminal').indexOf('uid=') >= 0")
282
283 @testlib.skipBrowser("WebGL2 is not supported in firefox headless mode, terminal page will not load", "firefox")
284 def testOpenPath(self) -> None:
285 b = self.browser
286 m = self.machine
287
288 self.login_and_go("/system/terminal")
289
290 blank_state = ' '
291
292 # Wait until first line is not empty
293 b.wait_visible(".terminal .xterm-accessibility-tree")
294 function_str = "(function (sel) { return ph_text(sel).trim() != '%s'})" % blank_state
295 b.wait_js_func(function_str, line_sel(1))
296
297 self.clear_terminal()
298
299 # Change to directory that exists
300 b.go("#/?path=/tmp")
301 b.wait_visible(".terminal .xterm-accessibility-tree")
302 self.wait_line(1, "disconnected")
303 self.clear_terminal()
304 b.input_text("pwd\n")
305 self.wait_line(2, "/tmp")
306 b.wait_not_present(".pf-v6-c-alert")
307
308 # Error on dir non-exist
309 b.go("#/?path=/doesnotexist")
310 b.wait_in_text(".pf-v6-c-alert", "does not exist")
311 # If there's an error, we shouldn't reset the terminal
312 b.input_text("pwd\n")
313 self.wait_line(4, "/tmp")
314 # Clear the error
315 b.click('.pf-v6-c-alert__action button')
316 b.wait_not_present(".pf-v6-c-alert")
317
318 # Error on change to non-dir
319 b.go("#/?path=/etc%2Fos-release")
320 b.wait_in_text(".pf-v6-c-alert", "not a directory")
321 # If there's an error, we shouldn't reset the terminal
322 b.input_text("pwd\n")
323 self.wait_line(6, "/tmp")
324 # Clear the error
325 b.click('div.pf-v6-c-alert__action button')
326 b.wait_not_present(".pf-v6-c-alert")
327 b.wait_js_cond('window.location.hash == "#/"')
328
329 # Prompt for change if terminal busy
330 b.input_text("sh -c 'echo busybusybusy; echo $$; exec sleep infinity'\n")
331 b.wait_in_text(line_sel(8), 'busybusybusy')
332 pid = b.text(line_sel(9))
333 b.go("#/?path=/tmp")
334 b.wait_in_text(".pf-v6-c-alert.pf-m-danger", "Running process prevents directory change")
335 # Cancel change
336 b.click("button:contains('Cancel')")
337 b.wait_not_present(".pf-v6-c-alert")
338 b.wait_js_cond('window.location.hash == "#/"')
339 # Check busy process is still running
340 m.execute(f"kill -0 {pid}")
341 b.wait_in_text(line_sel(8), 'busybusybusy')
342 # Confirm change
343 b.go("#/?path=/var")
344 b.wait_in_text(".pf-v6-c-alert.pf-m-danger", "Running process prevents directory change")
345 b.click("button:contains('Change directory')")
346 b.wait_not_present(".pf-v6-c-alert.pf-m-danger")
347 self.wait_line(1, "disconnected")
348 self.clear_terminal()
349 b.input_text("pwd\n")
350 self.wait_line(2, "/var")
351 self.assertIn("No such process", m.execute(f"kill -0 {pid} 2>&1 || true"))
352
353 @testlib.skipBrowser("WebGL2 is not supported in firefox headless mode, terminal page will not load", "firefox")
354 def testExternalState(self) -> None:
355 b = self.browser
356 m = self.machine
357
358 self.login_and_go("/playground/terminal")
359
360 b.wait_text('.pf-v6-c-toggle-group__button.pf-m-selected', "Terminal 1")
361
362 # Run something in Terminal 1
363 b.wait_in_text(line_sel(1), "admin@local")
364 b.input_text("echo Terminal 1\n")
365 b.wait_text(line_sel(2), "Terminal 1")
366
367 # Switch to Terminal 2
368 b.click('.pf-v6-c-toggle-group__button:contains("Terminal 2")')
369 b.wait_text('.pf-v6-c-toggle-group__button.pf-m-selected', "Terminal 2")
370 b.wait_not_in_text(".terminal .xterm-accessibility-tree", "Terminal 1")
371
372 # Run something else there
373 b.wait_in_text(line_sel(1), "admin@local")
374 b.input_text("echo Terminal 2\n")
375 b.wait_text(line_sel(2), "Terminal 2")
376
377 # Switch back to Terminal 1, old output should still be there
378 b.click('.pf-v6-c-toggle-group__button:contains("Terminal 1")')
379 b.wait_text('.pf-v6-c-toggle-group__button.pf-m-selected', "Terminal 1")
380 b.wait_text(line_sel(2), "Terminal 1")
381
382 # Reset, this will output "disconnected" and start a new shell
383 # process
384
385 b.input_text("echo $$\n")
386 b.wait_in_text(line_sel(5), "admin@local")
387 old_pid = b.text(line_sel(4))
388
389 b.click('button:contains("Reset")')
390 b.click(".terminal") # Focus the terminal again
391 b.wait_in_text(line_sel(1), "disconnected")
392 b.wait_in_text(line_sel(2), "admin@local")
393 b.input_text("echo $$\n")
394 b.wait_in_text(line_sel(4), "admin@local")
395 new_pid = b.text(line_sel(3))
396
397 # Converting the pid string to int will throw an error if we
398 # have picked up anything other than a number.
399
400 self.assertNotEqual(int(old_pid), int(new_pid))
401
402 # Now we should have four bash processes, one for each tab
403
404 def count_admin_bashes() -> int:
405 return int(m.execute("loginctl user-status admin | grep /bin/bash | wc -l"))
406
407 testlib.wait(lambda: count_admin_bashes() == 4)
408
409 # Remove all terminals, this closes all channels and kills all bash processes
410
411 b.click("label:contains('Show terminals')")
412 b.wait_not_present(".terminal")
413
414 testlib.wait(lambda: count_admin_bashes() == 0)
415
416
417 if __name__ == '__main__':
418 testlib.test_main()