Skip to content

Instantly share code, notes, and snippets.

@macabreb0b
Last active January 31, 2018 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macabreb0b/14366c1ae5be4656a2dc71ff2ff722dd to your computer and use it in GitHub Desktop.
Save macabreb0b/14366c1ae5be4656a2dc71ff2ff722dd to your computer and use it in GitHub Desktop.
Some pytest notes

mocking

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.

  1. Use spec_set when creating object fakes.
  2. Use autospec=True when stubbing method functionality.

fixtures

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.

Some issues with fixtures:

  1. 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.

  2. 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:

    1. fixtures defined in the same file   2. fixtures defined in conftest.py in local directory
    2. 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.

Some best practices:

  1. 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]"

  2. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment