| 1 |
import inspect |
| 2 |
import subprocess |
| 3 |
import sys |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
|
| 8 |
def pytest_configure(config): |
| 9 |
# stash it somewhere global-ish |
| 10 |
from polymorphic import tests |
| 11 |
|
| 12 |
tests.HEADLESS = not config.getoption("--headed") |
| 13 |
|
| 14 |
|
| 15 |
def first_breakable_line(obj) -> tuple[str, int]: |
| 16 |
""" |
| 17 |
Return the absolute line number of the first executable statement |
| 18 |
in a function or bound method. |
| 19 |
""" |
| 20 |
import ast |
| 21 |
import textwrap |
| 22 |
|
| 23 |
func = obj.__func__ if inspect.ismethod(obj) else obj |
| 24 |
|
| 25 |
source = inspect.getsource(func) |
| 26 |
source = textwrap.dedent(source) |
| 27 |
filename = inspect.getsourcefile(func) |
| 28 |
assert filename |
| 29 |
_, start_lineno = inspect.getsourcelines(func) |
| 30 |
|
| 31 |
tree = ast.parse(source) |
| 32 |
|
| 33 |
for node in tree.body[0].body: |
| 34 |
if ( |
| 35 |
isinstance(node, ast.Expr) |
| 36 |
and isinstance(node.value, ast.Constant) |
| 37 |
and isinstance(node.value.value, str) |
| 38 |
): |
| 39 |
continue |
| 40 |
|
| 41 |
return filename, start_lineno + node.lineno - 1 |
| 42 |
|
| 43 |
# fallback: just return the line after the def |
| 44 |
return filename, start_lineno + 1 |
| 45 |
|
| 46 |
|
| 47 |
def pytest_runtest_call(item): |
| 48 |
# --trace cli option does not work for unittest style tests so we implement it here |
| 49 |
test = getattr(item, "obj", None) |
| 50 |
if item.config.option.trace and inspect.ismethod(test): |
| 51 |
from IPython.terminal.debugger import TerminalPdb |
| 52 |
|
| 53 |
try: |
| 54 |
file = inspect.getsourcefile(test) |
| 55 |
assert file |
| 56 |
dbg = TerminalPdb() |
| 57 |
dbg.set_break(*first_breakable_line(test)) |
| 58 |
dbg.cmdqueue.append("continue") |
| 59 |
dbg.set_trace() |
| 60 |
except (OSError, AssertionError): |
| 61 |
pass |
| 62 |
|
| 63 |
|
| 64 |
def _install_playwright_browsers() -> None: |
| 65 |
cmd = [sys.executable, "-m", "playwright", "install", "chromium"] |
| 66 |
subprocess.run(cmd, check=True) |
| 67 |
|
| 68 |
|
| 69 |
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None: |
| 70 |
any_ui = any(item.get_closest_marker("ui") is not None for item in items) |
| 71 |
|
| 72 |
if any_ui and not getattr(config, "_did_install_playwright", False): |
| 73 |
setattr(config, "_did_install_playwright", True) |
| 74 |
_install_playwright_browsers() |