Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RichExceptionChainRepr for richer exception highlighting #8

Merged
merged 5 commits into from
Feb 23, 2022

Conversation

joshuadavidthomas
Copy link
Collaborator

Yanked most of __rich_console__ from Rich's Traceback class and adapted for pytest's ExceptionChainRepr.

I ignored locals for the time being, which I assume I can grab from reprlocals on each ReprEntry.

There's no testing other than the eye test and the code could stand to be cleaned up a bit as well. But! It's working.

image

@joshuadavidthomas joshuadavidthomas linked an issue Feb 18, 2022 that may be closed by this pull request
@nicoddemus
Copy link
Owner

This looks amazing 😍 great work!

About testing: not sure how we can approach testing in pytest-rich in general TBH. Any ideas?

@joshuadavidthomas
Copy link
Collaborator Author

Thanks! 😊

As far as testing, I'm a bit stumped too.

A quick glance through Rich's test suite, most of the traceback tests are testing the print_exception method, so they aren't of any use to us. It does look like Console offers begin_capture and end_capture methods that may come in handy.

Might be worth pinging Will to see if he has any suggestions.

@joshuadavidthomas
Copy link
Collaborator Author

For the time being, could we use a mark on failing tests so that you could manually test the terminal output for tracebacks without breaking CI?

@joshuadavidthomas
Copy link
Collaborator Author

joshuadavidthomas commented Feb 19, 2022

Running this PR on my main Django app, I get this error:

──────────────────────── forsythia/lease/clubs/tests/test_views.py::TestClubList::test_post ────────────────────────
Traceback (most recent call last):
  File "/usr/local/bin/pytest", line 8, in <module>
    sys.exit(console_main())
  File "/usr/local/lib/python3.10/site-packages/_pytest/config/__init__.py", line 188, in console_main
    code = main()
  File "/usr/local/lib/python3.10/site-packages/_pytest/config/__init__.py", line 165, in main
    ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
  File "/usr/local/lib/python3.10/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/usr/local/lib/python3.10/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/usr/local/lib/python3.10/site-packages/pluggy/_callers.py", line 60, in _multicall
    return outcome.get_result()
  File "/usr/local/lib/python3.10/site-packages/pluggy/_result.py", line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/usr/local/lib/python3.10/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/usr/local/lib/python3.10/site-packages/_pytest/main.py", line 315, in pytest_cmdline_main
    return wrap_session(config, _main)
  File "/usr/local/lib/python3.10/site-packages/_pytest/main.py", line 303, in wrap_session
    config.hook.pytest_sessionfinish(
  File "/usr/local/lib/python3.10/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/usr/local/lib/python3.10/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/usr/local/lib/python3.10/site-packages/pluggy/_callers.py", line 60, in _multicall
    return outcome.get_result()
  File "/usr/local/lib/python3.10/site-packages/pluggy/_result.py", line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/usr/local/lib/python3.10/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/usr/local/lib/python3.10/site-packages/pytest_rich.py", line 241, in pytest_sessionfinish
    self.console.print(tb)
  File "/usr/local/lib/python3.10/site-packages/rich/console.py", line 1616, in print
    extend(render(renderable, render_options))
  File "/usr/local/lib/python3.10/site-packages/rich/console.py", line 1254, in render
    for render_output in iter_render:
  File "/usr/local/lib/python3.10/site-packages/pytest_rich.py", line 315, in __rich_console__
    repr_highlighter(
  File "/usr/local/lib/python3.10/site-packages/rich/highlighter.py", line 36, in __call__
    raise TypeError(f"str or Text instance required, not {text!r}")
TypeError: str or Text instance required, not None

Running without pytest-rich:

________________________________________ TestClubList.test_post[data0-201] _________________________________________

self = <forsythia.lease.clubs.tests.test_views.TestClubList object at 0x7f3ded0d7040>
api_client = <rest_framework.test.APIClient object at 0x7f3debb5dc30>
data = {'clubInfo': 'test club 1', 'description': 'test club 1', 'name': 'test club 1'}, expected_status_code = 201

    @pytest.mark.parametrize(
        "data,expected_status_code",
        [
            (
                {
                    "name": "test club 1",
                    "description": "test club 1",
                    "clubInfo": "test club 1",
                },
                status.HTTP_201_CREATED,
            ),
            (
                {
                    "name": "test club 2",
                },
                status.HTTP_201_CREATED,
            ),
            ({}, status.HTTP_400_BAD_REQUEST),
        ],
    )
    def test_post(self, api_client, data, expected_status_code):
        response = api_client.post(self.endpoint, data=data)

>       assert response.status_code != expected_status_code
E       assert 201 != 201
E        +  where 201 = <Response status_code=201, "application/json">.status_code

forsythia/lease/clubs/tests/test_views.py:57: AssertionError

Guess my implementation of _grab_err_msg needs some updating..

@nicoddemus
Copy link
Owner

Guess my implementation of _grab_err_msg needs some updating..

Yeah I guess somewhere there's a None that needs to be handled as text.

@joshuadavidthomas
Copy link
Collaborator Author

First pass at dealing with the error messages.

The original _grab_err_msg function couldn't deal with a plain assertion without a message, e.g. assert 0 vs assert 0, "Some failure". Fixed that and moved it to within the render_chain method for now.

Here are a few screenshots to show progress so far:

image

image

image

@joshuadavidthomas
Copy link
Collaborator Author

From my previously mentioned Django app, it works and looks a lot better:

image

@joshuadavidthomas
Copy link
Collaborator Author

joshuadavidthomas commented Feb 21, 2022

This PR may be in a good spot to merge.

There are still improvments to be done:

  • I'm not 100% in love with how the error messages are displayed, could explore a richer way to output them
  • The code for RichExceptionChainRepr could probably stand to be cleaned up and refactored a bit, _render_chain is doing a lot of heavy lifting that could be split out (rendering error header, code, and message)
  • Along with the refactoring, documentation in docstrings would be useful for future contributors
  • Testing, though that is its own beast...

I think those all should go in as separate issues with their own PRs, in order to avoid this PR's scope from expanding beyond richer exception highlighting.

@joshuadavidthomas
Copy link
Collaborator Author

joshuadavidthomas commented Feb 21, 2022

Additional stray thoughts:

  • May want to rename the header from Traceback to something else (Failed Test Report?), since it's not an actual traceback it's a bit misleading for the header to say it is
  • Still need to include the reprlocals information from the ReprEntry somewhere

So maybe I was fibbing a bit and this PR isn't ready to merge just yet.

@nicoddemus
Copy link
Owner

This PR may be in a good spot to merge.

Agreed, want to mark it as Ready for Review then?

@joshuadavidthomas
Copy link
Collaborator Author

joshuadavidthomas commented Feb 22, 2022

Final tweaks, ready for review!

Comparisions

Built-in pytest TerminalReporter:
image

pytest-rich RichReporter:
image

Built-in pytest TerminalReporter:
image

pytest-rich RichReporter:
image

@joshuadavidthomas joshuadavidthomas marked this pull request as ready for review February 22, 2022 23:02
@joshuadavidthomas joshuadavidthomas changed the title wip: RichExceptionChainRepr Add RichExceptionChainRepr for richer exception highlighting in failed tests Feb 22, 2022
@joshuadavidthomas
Copy link
Collaborator Author

joshuadavidthomas commented Feb 22, 2022

My goal was this PR was to get a good starting point. Here are some areas for improvement:

  • pytest's TerminalReporter shows the entire test function being called, whereas since I adapted from rich's Traceback, RichReporter only shows the last 3 and next 3 lines from the failed line.

image

image

  • TerminalReporter puts the error messages right after the failed lines, whereas RichReporter puts them at the bottom. Switching away from rich's Syntax object would make this easier, as Syntax is apparently not designed to be composed in pieces as detailed by Will here. Though we could slice it after the fact and put the errors in that way, relevant comment from Will.

image

image

Copy link
Owner

@nicoddemus nicoddemus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks awesome!

I didn't review the code in detail, but the results do look great.

Could you please also update the screenshot in assets/? Thanks!

@nicoddemus
Copy link
Owner

Btw your detailed comments for follow ups should probably be moved to their own issues so we don't lose track of them. 👍

@joshuadavidthomas
Copy link
Collaborator Author

Added new issues on where to go from here:

#16
#17

@joshuadavidthomas joshuadavidthomas changed the title Add RichExceptionChainRepr for richer exception highlighting in failed tests Add RichExceptionChainRepr for richer exception highlighting Feb 23, 2022
@joshuadavidthomas joshuadavidthomas merged commit 810befd into main Feb 23, 2022
@joshuadavidthomas joshuadavidthomas deleted the traceback branch February 23, 2022 23:14
@fruch
Copy link

fruch commented Feb 24, 2022

When I ever thought about pytest+rich, this is the feature I had in mind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Better exception highlight in tracebacks
3 participants