Take and upload screenshot when tests fail. Args: node: The pytest item that failed. call: The pytest call describing when/where the test was invoked. report: The pytest log report object.
(node, call, report)
| 37 | |
| 38 | |
| 39 | def pytest_exception_interact(node, call, report): |
| 40 | """Take and upload screenshot when tests fail. |
| 41 | |
| 42 | Args: |
| 43 | node: The pytest item that failed. |
| 44 | call: The pytest call describing when/where the test was invoked. |
| 45 | report: The pytest log report object. |
| 46 | """ |
| 47 | screenshot_dir = os.environ.get("SCREENSHOT_DIR") |
| 48 | if DISPLAY is None or screenshot_dir is None: |
| 49 | return |
| 50 | |
| 51 | screenshot_dir = Path(screenshot_dir) |
| 52 | screenshot_dir.mkdir(parents=True, exist_ok=True) |
| 53 | safe_filename = re.sub( |
| 54 | r"(?u)[^-\w.]", |
| 55 | "_", |
| 56 | str(node.nodeid).strip().replace(" ", "_").replace(":", "_"), |
| 57 | ) |
| 58 | |
| 59 | try: |
| 60 | DISPLAY.waitgrab().save( |
| 61 | (Path(screenshot_dir) / safe_filename).with_suffix(".png"), |
| 62 | ) |
| 63 | except Exception as e: |
| 64 | print(f"Failed to take screenshot for {node}: {e}") |
| 65 | |
| 66 | |
| 67 | @pytest.fixture( |