When testing code that outputs to the terminal through either standard out (stdout) or standard error (stderr), you might want to capture that output and make assertions on it. To do so, use contextlib.redirect_stdout() and contextlib.redirect_stderr() to redirect the respective output streams to in-memory buffers that you can then inspect and assert on.
A neat testing pattern is writing common tests in a base class and then applying them to multiple objects through subclassing. Doing so can help you test smarter and cover more code with less boilerplate.
A few days ago, I blogged about debugging unraisable exceptions with Rich. Here’s a sequel on testing that some block of code doesn’t trigger any unraisable exceptions.
Sometimes, tests need temporary files or directories. You can do this in Python’s unittest with the standard library tempfile module. Let’s look at some recipes to do so within individual tests and setUp().
Python 3.11 only made one change to unittest, but it’s a good one: context manager methods. These methods can simplify setup and teardown logic in many cases, such as dynamic use of unittest.mock.
Django 4.0 had its first alpha release last week and the final release should be out in December. It contains an abundance of new features, which you can check out in the release notes. In this post we’ll look at the changes to testing in a bit more depth.
You run your tests with manage.py test. You know what happens inside your tests, since you write them. But how does the test runner work to execute them, and put the dots, Es, and Fs on your screen?