1

I am looking into using hypothesis for some of my testing. I like that it can generate a large variety of data to find edge cases. However, I'd like to be able to tailor some of my tests just a bit more.

For example, I can define a test to generate integers, but I'm expecting this test to conform to valid zip codes are well. Can I do this? Or, perhaps, more complex conform to non-US zip codes, which are all integers, but others (say, Canada) are not?

The same type of thing would be useful for text fields that are expected to conform to some type of mask (ie. email address).

Right now I have test cases that are decorated like this:

from hypothesis import given, strategies as st
@given(st.integers())

For this particular case, I'd like it to also conform to US zip code rules.

@given(st.text())

For this one I'd like it to generate patterns that are in an email-like format.

Can hypothesis do this type of generation?

NewGuy
  • 3,273
  • 7
  • 43
  • 61

1 Answers1

3

Hypothesis can do more or less any kind of generation you like, but if there aren't built in strategies you need to write one yourself, usually using the @composite decorator. Here's an article from the site on how to do this sort of thing.

For the specific cases emails, there's some ongoing work on providing a good builtin implementation but it probably won't arrive that soon.

I don't know of anything that does zip codes, and doing it properly looks hard, but looking at what other random generators do you can probably just get away with st.integers(501, 99950).map(lambda i: "%05d" % (i,)), which just takes an integer between 501 and 99950 inclusive and formats it as a 5 digit code.

DRMacIver
  • 2,259
  • 1
  • 17
  • 17