Better Exception Output in Django’s Test Runner With better-exceptions2021-01-04
Today I learned about the better-exceptions pacakage. It makes exception output better, providing more context and colourization on the terminal.
If you’re using Django’s test framework, you can install better-exceptions during your test runs.
It makes it the plain
assert statement much more usable.
asserts are clearer to write and read than the various
self.assert* functions, so a definite win for tests.
assert statement rewriting is similar to better-exceptions, and it’s definitely a “killer feature” for pytest users.
Whilst I recommend pytest, it can be hard to port existing projects, so using better-exceptions is a nice compromise.
Adding better-exceptions To Django Test Runs
First, you’ll want a custom test runner class.
If you don’t already have one, create one as below, in a file like
Inside that the test runner’s
run_tests() method, you can use a monkey-patch to install
better-exceptions into the unittest
TestResult class, which is responsible for output of tests.
There’s a snippet in the better-exceptions documentation, which I’ve made Python-3-only.
Putting it all together:
Second, configure Django to use your test runner by setting
Then when you run tests, you should see nice colourized output. For example I made this broken test:
Running it I see this output, with better colourization in my terminal:
Note the last frame, which shows that
expected is 3.
If you like better-exceptions, also check out its documentation on use in your Django logging configuration.
May your tests be easy to read and write,
Working on a Django project? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
- Make Django Tests Always Rebuild the Database if It Exists
- How to Use Django's Parallel Testing on macOS With Python 3.8+
- How to Unit Test a Django Form
© 2021 All rights reserved.