gregmuellegger/django-autofixture

add regex validation to StringGenerator

Closed this issue · 4 comments

Add the ability to provide a Python regular expression string to the StringGenerator constructor to only allow strings that match the regular expression to be inserted into the database.

For example, in autofixtures.py:

class EntryAutoFixture(AutoFixture):
    field_values = {
        'blog': generators.StringGenerator(
            chars=string.ascii_letters + string.digits + '-',
            match='^[a-zA-Z0-9][a-zA-Z0-9\-]*$',
            min_length=1,
            max_length=40
        ),
    }

This would, in effect, limit strings generated to only containing alphanumeric characters and dashes and the string cannot begin with a dash.

This would be useful where there are regex validators present in Django url configurations and on Django models.

I can provide a Pull Request if this proposal is acceptable.

Hey, the overall idea is quite ok. However I think the risk of running into an infinite loop is way to big. For example a simple regex like ^\d$ will probably make the generator run forever, because the probability of producing exactly one character which is a digit is quite small (I think about 0.003%).

A better solution would be to write a generator for your case that exactly meets your needs and only produces valid inputs.

Ok. I appreciate your time and consideration nonetheless. Thanks.

Thanks for the suggestion to you! Keep me posted with new ideas. Maybe you find another way to solve your usecase?

Yes indeed. I will keep you appraised. I am investigating the django-autofixture codebase and my usecase to re-evaluate my options. Thanks for the follow-up.