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

Unique random fixture #26

Closed drtyrsa closed 10 years ago

drtyrsa commented 11 years ago

Added new fixture algorithm. It will generate unique values, but they won't be the same for the same model instance.

The problem

Imagine following model:

class Product(models.Model):
    global_name = models.CharField(unique=True)
    local_name = models.CharField(unique=True)
    local_only = models.BooleanField(default=False)

    def get_name(self):
        if self.local_only:
            return self.local_name
        return self.global_name

I want to test get_name method, and I write two tests for it:

# ...
def test_get_name_returns_global_name_if_local_only_is_false(self):
    product = N(Product, local_only=False)
    self.assertEqual(product.get_name(), product.global_name)

def test_get_name_returns_local_name_if_local_only_is_true(self):
    product = N(Product, local_only=True)
    self.assertEqual(product.get_name(), product.local_name)

These tests are correct, but, using DDF and sequentional fixture algorithm, they test nothing. global_name and local_name will be the same. I can set them manually in N, but it's additional work to do and I should keep it in mind all the time.

I can't use random fixture algorithm because (as stated in docs) I can get IntegrityError one day and I don't want to.

Solution

Here's unique random fixture algorithm. It guarantees 512 distinct model instances for each model. And their string and numeric fields will be filled random data. The algorithm uses simple sequences like ['1<random_str>', '2<random_str>', ...] for strings or [randint(1, 64), randint(65, 128), ...] for numbers. Actually 512 limitation is caused by range of SmallIntegerField. If for some reason user wants more than 512 objects, another fixture algorithm can be used. And if this limitation is exceeded warning will be output.

I haven't touched the docs, but if this request will be pulled I will update them.

paulocheque commented 11 years ago

Nice! I will merge it as soon as I can.