Fork me on GitHub

This is the index page for a series of posts about our approach to Python unit tests at Hypothesis:

  1. Running the Hypothesis Python Tests
  2. Debugging Failing Tests with pytest
  3. Writing Simple Python Unit Tests
  4. Arrange, Act, Assert
  5. Python Test Factories with factory_boy
  6. Testing that an Exception is Raised with pytest.raises
  7. Parametrizing Python Tests
  8. Basic pytest Fixtures
  9. Advanced pytest Fixtures
  10. Python’s unittest.mock
  11. Hypothesis’s patch Fixture
  12. sentinel: Unique Objects for Tests
  13. The Problem with Mocks
  14. usefixtures as a Class Decorator
  15. When and When Not to Use Mocks
  16. Matcher Objects in Python Tests

While this tutorial is based on Hypothesis’s approach and the examples are taken from Hypothesis’s tests, most of it should be applicable to Python unit testing generally.

These posts are aimed at intermediate Python developers, not complete beginners. Basic knowledge of Python programming and virtualenv are assumed, for example.

In a large, real-world project like Hypothesis the tests contain a lot of things that might be unfamiliar - factories, parametrize, mocks, sentinel, patch, usefixtures and test method arguments that seem to come from nowhere. One of the aims of this tutorial is to introduce you to all these, so that you can read the Hypothesis test code and understand what’s going on.

Knowing how and when to use all of these tools will help you to write better tests. We’ll also cover a few more advanced aspects of writing good tests, as opposed to bad ones, particularly when we talk about how to organize your tests; the arrange, act, assert pattern and test naming; fixtures; and how and when to use mocks.

Finally, we’ll touch even less on the important but difficult topic of how to design good code that works well and is easy to test.