Search code examples
python-hypothesis

Generate string data from regex


I would like to be able to take a regex and generate conforming data using the python hypothesis library. For example given a regex of

regex = re.compile('[a-zA-Z]')

This would match any english alpha characters. An example generator for this could be.

import hypothesis
import string

hypothesis.strategies.text(alphabet=string.ascii_letters)

But Ideally I want to construct a string that will match any regex passed in.


Solution

  • There's a work in progress pull request for adding this feature. Nothing extant will let you do it easily, but looking at the PR might give you a good idea about how to translate any specific example you need.

    Update: the from_regex strategy was added in Hypothesis 3.19.