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