mock.Mock()
is great. It's the reason that I use Python for small side projects - it makes unit testing a breeze. But over-reliance on mock objects for testing can obscure the meaning of your test (at best), and (at worst) it can create bugs in your test code.
- Use
spec_set
when creating object fakes. - Use
autospec=True
when stubbing method functionality.
Similar to mock.Mock()
, Pytest fixtures (functions defined with the decorator @pytest.fixture()
) can be super handy for writing unit tests, but if they are overused, they can obscure the meaning of what you're testing.
-
Trouble with linters. Fixtures don't play by the same rules as a lot of the rest of Python. This means that they don't always play nicely with linters.
-
It's harder to track down the value that is getting used in a function. When multiple fixtures have the same name, pytest decides which one to use in this order:
- fixtures defined in the same file 2. fixtures defined in conftest.py in local directory
- fixtures defined in conftest.py in parent directory
TODO - figure out github markdown issues
This can be hard to keep track of, since fixtures do not get imported, so linters / IDEs will not catch redefinition errors in the way that they would with a factory method.
-
Use "autouse" sparingly. From pytest docs - "...it's usually better to explicitly declare fixtures you need for a given test [instead of passing
autouse=True
]" -
Avoid using fixtures to create static objects. Fixtures can be used to return static data for your tests. In fact, pytest docs seem to encourage this: "If you want to make test data from files available to your tests, a good way to do this is by loading these data in a fixture for use by your tests. This makes use of the automatic caching mechanisms of pytest."
TODO - add issues with using fixtures to create static objects
TODO - add example