| 1 |
from contextlib import contextmanager |
| 2 |
from difflib import unified_diff |
| 3 |
import os |
| 4 |
from pathlib import Path |
| 5 |
import re |
| 6 |
from time import sleep |
| 7 |
from secrets import token_hex |
| 8 |
|
| 9 |
import pytest |
| 10 |
from urwid.display import html_fragment |
| 11 |
|
| 12 |
from cylc.flow.id import Tokens |
| 13 |
from cylc.flow.tui.app import TuiApp |
| 14 |
from cylc.flow.tui.overlay import _get_display_id |
| 15 |
|
| 16 |
|
| 17 |
SCREENSHOT_DIR = Path(__file__).parent / 'screenshots' |
| 18 |
|
| 19 |
|
| 20 |
def configure_screenshot(v_term_size): |
| 21 |
"""Configure Urwid HTML screenshots.""" |
| 22 |
screen = html_fragment.HtmlGenerator() |
| 23 |
screen.set_terminal_properties(256) |
| 24 |
screen.register_palette(TuiApp.palette) |
| 25 |
html_fragment.screenshot_init( |
| 26 |
[tuple(map(int, v_term_size.split(',')))], |
| 27 |
[] |
| 28 |
) |
| 29 |
return screen, html_fragment |
| 30 |
|
| 31 |
|
| 32 |
def format_test_failure(expected, got, description): |
| 33 |
"""Return HTML to represent a screenshot test failure. |
| 34 |
|
| 35 |
Args: |
| 36 |
expected: |
| 37 |
HTML fragment for the expected screenshot. |
| 38 |
got: |
| 39 |
HTML fragment for the test screenshot. |
| 40 |
description: |
| 41 |
Test description. |
| 42 |
|
| 43 |
""" |
| 44 |
diff = '\n'.join(unified_diff( |
| 45 |
expected.splitlines(), |
| 46 |
got.splitlines(), |
| 47 |
fromfile='expected', |
| 48 |
tofile='got', |
| 49 |
)) |
| 50 |
return f''' |
| 51 |
<html> |
| 52 |
<head></head> |
| 53 |
<h2>{description}</h2> |
| 54 |
<table> |
| 55 |
<tr> |
| 56 |
<td><b>Expected</b></td> |
| 57 |
<td><b>Got</b></td> |
| 58 |
</tr> |
| 59 |
<tr> |
| 60 |
<td>{expected}</td> |
| 61 |
<td>{got}</td> |
| 62 |
</tr> |
| 63 |
</table> |
| 64 |
<br /> |
| 65 |
<h4>Diff:</h4> |
| 66 |
<pre>{diff}</pre> |
| 67 |
</html> |
| 68 |
''' |
| 69 |
|
| 70 |
|
| 71 |
class RakiuraSession: |
| 72 |
"""Convenience class for accessing Rakiura functionality.""" |
| 73 |
|
| 74 |
def __init__(self, app, html_fragment, test_dir, test_name): |
| 75 |
self.app = app |
| 76 |
self.html_fragment = html_fragment |
| 77 |
self.test_dir = test_dir |
| 78 |
self.test_name = test_name |
| 79 |
|
| 80 |
def user_input(self, *keys): |
| 81 |
"""Simulate a user pressing keys. |
| 82 |
|
| 83 |
Each "key" is a keyboard button e.g. "x" or "enter". |
| 84 |
|
| 85 |
If you provide more than one key, each one will be pressed, one |
| 86 |
after another. |
| 87 |
|
| 88 |
You can combine keys in a single string, e.g. "ctrl d". |
| 89 |
""" |
| 90 |
return self.app.loop.process_input(keys) |
| 91 |
|
| 92 |
def compare_screenshot( |
| 93 |
self, |
| 94 |
name, |
| 95 |
description, |
| 96 |
retries=3, |
| 97 |
delay=0.1, |
| 98 |
force_update=True, |
| 99 |
): |
| 100 |
"""Take a screenshot and compare it to one taken previously. |
| 101 |
|
| 102 |
To update the screenshot, set the environment variable |
| 103 |
"CYLC_UPDATE_SCREENSHOTS" to "true". |
| 104 |
|
| 105 |
Note, if the comparison fails, "force_update" is called and the |
| 106 |
test is retried. |
| 107 |
|
| 108 |
Arguments: |
| 109 |
name: |
| 110 |
The name to use for the screenshot, this is used in the |
| 111 |
filename for the generated HTML fragment. |
| 112 |
description: |
| 113 |
A description of the test to be used on test failure. |
| 114 |
retries: |
| 115 |
The maximum number of retries for this test before failing. |
| 116 |
delay: |
| 117 |
The delay between retries. This helps overcome timing issues |
| 118 |
with data provision. |
| 119 |
|
| 120 |
Raises: |
| 121 |
Exception: |
| 122 |
If the screenshot does not match the reference. |
| 123 |
|
| 124 |
""" |
| 125 |
filename = SCREENSHOT_DIR / f'{self.test_name}.{name}.html' |
| 126 |
|
| 127 |
exc = None |
| 128 |
for _try in range(retries): |
| 129 |
# load the expected result |
| 130 |
expected = '<screenshot not found>' |
| 131 |
if filename.exists(): |
| 132 |
with open(filename, 'r') as expected_file: |
| 133 |
expected = expected_file.read() |
| 134 |
# update to pick up latest data |
| 135 |
if force_update: |
| 136 |
self.force_update() |
| 137 |
# force urwid to draw the screen |
| 138 |
# (the main loop isn't runing so this doesn't happen automatically) |
| 139 |
self.app.loop.draw_screen() |
| 140 |
# take a screenshot |
| 141 |
screenshot = self.html_fragment.screenshot_collect()[-1] |
| 142 |
|
| 143 |
try: |
| 144 |
if expected != screenshot: |
| 145 |
# screenshot does not match |
| 146 |
# => write an html file with the visual diff |
| 147 |
out = self.test_dir / filename.name |
| 148 |
with open(out, 'w+') as out_file: |
| 149 |
out_file.write( |
| 150 |
format_test_failure( |
| 151 |
expected, |
| 152 |
screenshot, |
| 153 |
description, |
| 154 |
) |
| 155 |
) |
| 156 |
raise Exception( |
| 157 |
'Screenshot differs:' |
| 158 |
'\n* Set "CYLC_UPDATE_SCREENSHOTS=true" to update' |
| 159 |
f'\n* To debug see: file:////{out}' |
| 160 |
) |
| 161 |
|
| 162 |
break |
| 163 |
except Exception as exc_: |
| 164 |
exc = exc_ |
| 165 |
# wait a while to allow the updater to do its job |
| 166 |
sleep(delay) |
| 167 |
else: |
| 168 |
if os.environ.get('CYLC_UPDATE_SCREENSHOTS', '').lower() == 'true': |
| 169 |
with open(filename, 'w+') as expected_file: |
| 170 |
expected_file.write(screenshot) |
| 171 |
else: |
| 172 |
raise exc |
| 173 |
|
| 174 |
def force_update(self): |
| 175 |
"""Run Tui's update method. |
| 176 |
|
| 177 |
This is done automatically by compare_screenshot but you may want to |
| 178 |
call it in a test, e.g. before pressing navigation keys. |
| 179 |
|
| 180 |
With Rakiura, the Tui event loop is not running so the data is never |
| 181 |
refreshed. |
| 182 |
|
| 183 |
You do NOT need to call this method for key presses, but you do need to |
| 184 |
call this if the data has changed (e.g. if you've changed a task state) |
| 185 |
OR if you've changed any filters (because filters are handled by the |
| 186 |
update code). |
| 187 |
""" |
| 188 |
# flush any prior updates |
| 189 |
self.app.get_update() |
| 190 |
# wait for the next update |
| 191 |
while not self.app.update(): |
| 192 |
pass |
| 193 |
|
| 194 |
def wait_until_loaded(self, *ids, retries=20): |
| 195 |
"""Wait until the given ID appears in the Tui tree, then expand them. |
| 196 |
|
| 197 |
Useful for waiting whilst Tui loads a workflow. |
| 198 |
|
| 199 |
Note, this is a blocking wait with no timeout! |
| 200 |
""" |
| 201 |
exc = None |
| 202 |
try: |
| 203 |
ids = self.app.wait_until_loaded(*ids, retries=retries) |
| 204 |
except Exception as _exc: |
| 205 |
exc = _exc |
| 206 |
if ids: |
| 207 |
msg = ( |
| 208 |
'Requested nodes did not appear in Tui after' |
| 209 |
f' {retries} retries: ' |
| 210 |
+ ', '.join(ids) |
| 211 |
) |
| 212 |
if exc: |
| 213 |
msg += f'\n{exc}' |
| 214 |
self.compare_screenshot(f'fail-{token_hex(4)}', msg, 1) |
| 215 |
|
| 216 |
|
| 217 |
@pytest.fixture |
| 218 |
def rakiura(test_dir, request, monkeypatch): |
| 219 |
"""Visual regression test framework for Urwid apps. |
| 220 |
|
| 221 |
Like Cypress but for Tui so named after a NZ island with lots of Tuis. |
| 222 |
|
| 223 |
When called this yields a RakiuraSession object loaded with test |
| 224 |
utilities. All tests have default retries to avoid flaky tests. |
| 225 |
|
| 226 |
Similar to the "start" fixture, which starts a Scheduler without running |
| 227 |
the main loop, rakiura starts Tui without running the main loop. |
| 228 |
|
| 229 |
Arguments: |
| 230 |
workflow_id: |
| 231 |
The "WORKFLOW" argument of the "cylc tui" command line. |
| 232 |
size: |
| 233 |
The virtual terminal size for screenshots as a comma |
| 234 |
separated string e.g. "80,50" for 80 cols wide by 50 rows tall. |
| 235 |
|
| 236 |
Returns: |
| 237 |
A RakiuraSession context manager which provides useful utilities for |
| 238 |
testing. |
| 239 |
|
| 240 |
""" |
| 241 |
return _rakiura(test_dir, request, monkeypatch) |
| 242 |
|
| 243 |
|
| 244 |
@pytest.fixture |
| 245 |
def mod_rakiura(test_dir, request, monkeypatch): |
| 246 |
"""Same as rakiura but configured to view module-scoped workflows. |
| 247 |
|
| 248 |
Note: This is *not* a module-scoped fixture (no need, creating Tui sessions |
| 249 |
is not especially slow), it is configured to display module-scoped |
| 250 |
"scheduler" fixtures (which may be more expensive to create/destroy). |
| 251 |
""" |
| 252 |
return _rakiura(test_dir.parent, request, monkeypatch) |
| 253 |
|
| 254 |
|
| 255 |
def _rakiura(test_dir, request, monkeypatch): |
| 256 |
# make the workflow and scan update intervals match (more reliable) |
| 257 |
# and speed things up a little whilst we're at it |
| 258 |
monkeypatch.setattr( |
| 259 |
'cylc.flow.tui.updater.Updater.BASE_UPDATE_INTERVAL', |
| 260 |
0.1, |
| 261 |
) |
| 262 |
monkeypatch.setattr( |
| 263 |
'cylc.flow.tui.updater.Updater.BASE_SCAN_INTERVAL', |
| 264 |
0.1, |
| 265 |
) |
| 266 |
|
| 267 |
# the user name and the prefix of workflow IDs are both variable |
| 268 |
# so we patch the render functions to make test output stable |
| 269 |
def get_display_id(id_): |
| 270 |
tokens = Tokens(id_) |
| 271 |
return _get_display_id( |
| 272 |
tokens.duplicate( |
| 273 |
user='cylc', |
| 274 |
workflow=tokens.get('workflow', '').rsplit('/', 1)[-1], |
| 275 |
).id |
| 276 |
) |
| 277 |
monkeypatch.setattr('cylc.flow.tui.util.ME', 'cylc') |
| 278 |
monkeypatch.setattr('cylc.flow.tui.app.CYLC_VERSION', '1.2.3') |
| 279 |
monkeypatch.setattr( |
| 280 |
'cylc.flow.tui.util._display_workflow_id', |
| 281 |
lambda data: data['name'].rsplit('/', 1)[-1] |
| 282 |
) |
| 283 |
monkeypatch.setattr( |
| 284 |
'cylc.flow.tui.overlay._get_display_id', |
| 285 |
get_display_id, |
| 286 |
) |
| 287 |
|
| 288 |
# standardise environment for tests |
| 289 |
monkeypatch.setenv('EDITOR', 'nvim') |
| 290 |
monkeypatch.setenv('GEDITOR', 'gvim -f') |
| 291 |
monkeypatch.setenv('PAGER', 'less') |
| 292 |
|
| 293 |
# filter Tui so that only workflows created within our test show up |
| 294 |
id_base = str(test_dir.relative_to(Path("~/cylc-run").expanduser())) |
| 295 |
workflow_filter = re.escape(id_base) + r'/.*' |
| 296 |
|
| 297 |
@contextmanager |
| 298 |
def _rakiura(workflow_id=None, size='80,50'): |
| 299 |
screen, html_fragment = configure_screenshot(size) |
| 300 |
app = TuiApp(screen=screen) |
| 301 |
with app.main( |
| 302 |
workflow_id, |
| 303 |
id_filter=workflow_filter, |
| 304 |
interactive=False, |
| 305 |
): |
| 306 |
yield RakiuraSession( |
| 307 |
app, |
| 308 |
html_fragment, |
| 309 |
test_dir, |
| 310 |
request.function.__name__, |
| 311 |
) |
| 312 |
|
| 313 |
return _rakiura |