8.14.2016

Using py.test with Django and Hypothesis

If you're looking to use py.test as your test runner, but still want Hypothesis to correctly work with Django (i.e. make sure the database is in a clean state before each example is tested), use something like this:

class PytestHypothesisBase:
    def start_atomic_example(self):
        self.atomic = transaction.atomic(savepoint=True)
        self.atomic.__enter__()

    def setup_example(self):
        self.start_atomic_example()

    def finish_atomic_example(self):
        transaction.set_rollback(True)
        self.atomic.__exit__(None, None, None)

    def teardown_example(self, ex):
        self.finish_atomic_example()

Hypothesis will run setup_example and teardown_example even when using py.test. This is nice because while inheriting from hypothesis.extra.django.TestCase works with py.test, it causes dependency injection to break, meaning you can't use py.test's nice fixture behaviors. This approach lets you use the @given decorator with py.test fixtures.

No comments:

Post a Comment