nicoddemus / pytest-rich

pytest + rich integration (proof of concept)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Better exception highlight in tracebacks

nicoddemus opened this issue · comments

pytest doesn't provide the actual traceback objects during report (this is due to xdist support, because the report objects need to be serialized to be transferred between processes), we currently we only show the text with some simple highlighting.

See if we can leverage rich's traceback highlighting somehow.

Dug in to this a bit last night.

To assemble the Traceback, Rich walks through the actual traceback:

https://github.com/Textualize/rich/blob/8c3e6be424f36522cbb3c4773e58a01f5f39761f/rich/traceback.py#L364-L384

Since we don't have access to the traceback, just pytest's serialized TestReport, I don't immediately see a way to utilize Rich's actual Traceback class.

The easy path I see is, instead of dumping the report.longrepr to markdown, creating a Rich Panel and assembling a console printout using the ExceptionChainRepr info from longrepr that at least resembles the printout from Rich's Traceback.

Thanks for looking into it.

Yeah that seems like a possible solution.

Another solution that comes to mind is borrowing the code from rich that prints a Traceback and copy/change it to work with the contents of ExceptionChainRepr instead.

So, Traceback takes an optional Trace object, that if not supplied grabs the last exception. Could we just translate the contents of ExceptionChainRepr to match the Trace object and throw that in to Traceback?

# rich/traceback.py

@dataclass
class Frame:
    filename: str
    lineno: int
    name: str
    line: str = ""
    locals: Optional[Dict[str, pretty.Node]] = None

@dataclass
class Stack:
    exc_type: str
    exc_value: str
    syntax_error: Optional[_SyntaxError] = None
    is_cause: bool = False
    frames: List[Frame] = field(default_factory=list)

@dataclass
class Trace:
    stacks: List[Stack]

Not sure, but my suggestion is a bit different: search in Rich's codebase for the code that prints Traceback objects, then copy it over and adapt it to print ExceptionChainRepr instead.