paulocheque / django-dynamic-fixture

A complete library to create dynamic model instances for testing purposes.
http://django-dynamic-fixture.readthedocs.io/
Other
390 stars 67 forks source link

Custom data fixture for specific field on a model #75

Closed zanderle closed 8 years ago

zanderle commented 8 years ago

I think it would be really useful to be able to define custom data fixtures for specific fields on a model. So for example, say I have a following model

class Book(models.Model):
    title = models.CharField(max_length=255)
    number_of_pages = models.IntegerField()

I would want to define special behavior for data generation for field number_of_pages, for example data fixture for number_of_pages could be random between [10,100]. It's different than what already exists in DDF in that it's specific to a model field vs a field in general (http://django-dynamic-fixture.readthedocs.org/en/latest/data_fixtures.html#custom-field-fixture). It would be useful to be able to set something like this.

paulocheque commented 8 years ago

You can use Shelve to store a lambda function.

Something like:

random_number = lambda field: random.choice(range(10, 101))
instance = G(Book, shelve=True, number_of_pages=random_number)

http://django-dynamic-fixture.readthedocs.org/en/latest/data.html#default-shelve-new-in-1-6-0

zanderle commented 8 years ago

That is exactly what I wanted! However, it would still be useful to be able to define shelves globally. Otherwise it has only limited usage (I would have to define shelve in every test file separately, to ensure I can run each test separately).

zanderle commented 8 years ago

Also, how do you use Shelve with related object creation.

For example:

class Character(models.Model):
    name = models.CharField()
    book = models.ForeignKey(Book)

class Book(models.Model):
    title = models.CharField(max_length=255)
    number_of_pages = models.IntegerField()

If I then tried creating Character object with:

instance = G(Character)

It will also create Book, but I have no way of passing Shelve to Book object. So the only way of going around it, is to explicitly define Book first.

I'm sure there is a better way than this?

paulocheque commented 8 years ago

To run globally, you could try the nose plugin: http://django-dynamic-fixture.readthedocs.org/en/latest/nose_plugins.html#ddf-setup-nose-plugin-new-in-1-6-0

About the Book/Character, you could try this:

random_number = lambda field: random.choice(range(10, 101))
G(Character, shelve=True, book__number_of_pages=random_number)