# Using Hypothesis with Factory Boy

I gave a talk on the Hypothesis Django Integration last night (video and transcript here). I got some questions asking about integration with Factory Boy.

My answer at the time was that I’ve thought about adding explicit support but there’s nothing to stop you from doing it yourself. I’d like to amend that: There’s nothing to stop you from doing it yourself and it’s so easy to do that I can’t actually imagine how I would improve it with explicit support.

Both Factory Boy and Hypothesis are designed along a “we’re a library, not a framework” approach (the Hypothesis django integration goes a little further in the direction of a framework than I’d like by requiring a custom test runner, but fortunately factory boy does not), so they don’t interfere with eachother. Further, factory boy is set up to take arbitrary values, Hypothesis is set up to provide them, so you can easily feed the latter into the former.

For example, the following defines a strategy that uses a factory boy UserFactory object to parametrize over unsaved user objects with an arbitrary first name:

from hypothesis import given from hypothesis.strategies import builds, text from hypothesis.extra.django import TestCase from myfactories import UserFactory   class TestUser(TestCase): @given(builds(UserFactory.build, first_name=text(max_length=50))) def test_can_save_a_user(self, user): user.save()

Both factory boy and Hypothesis are designed to play well with others, so unless I’m missing something, nothing specific seems necessary to make them play well with each other. This is how it should work.

The only thing that I can imagine people conceivably wanting custom support for is auto deriving strategies for factory boy instances that are using random fields filled by fake factory. It wouldn’t be too hard to do, but I’m not sure it’s worth it. Honestly if you’re doing randomized testing like that, you should be using Hypothesis and its existing fake factory integration to feed your factories instead. It will be a much better experience.

This entry was posted in Hypothesis, Python on by .