8 Posts Tagged ‘unittest’

(All tags.)


Python: capture stdout and stderr in unittest

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.

Read more...

Python: sharing common tests in unittest

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.

Read more...

Python: test for unraisable exceptions with unittest.mock

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.

Read more...

Python: create temporary files and directories in unittest

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().

Read more...

Python: unittest’s new context methods from Python 3.11 (with backports)

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.

Read more...

New Testing Features in Django 4.0

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.

Read more...

Python: mock environment variables with unittest

Sometimes, tests need to change environment variables. This is straightforward in tests using Python’s unittest, thanks to os.environ quacking like a dict, and the mock.patch.dict decorator/context manager.

Read more...

Django: what happens when you run manage.py test?

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?

Read more...