user3490695
user3490695

Reputation: 149

Unit Test foreign key constraints in Django models

I have 2 models defined, one of which is referenced to other via foreign key relation. I want to write unit tests to ensure this relationship.

class X(models.Model):
    name = models.CharField(unique = True)

class Y(models.Model):
    event = models.ForeignKey(X)

and in tests I have

class TestY(TestCase):
    x = X.objects.create(name="test1")
    x.save()
    y = Y(event=X.objects.create(name="test2"))
    with self.assertRaises(ValidationError):
        if y.full_clean()
            y.save()

    self.assert(0,Y.objects.filter(event__name="test2").count)

This says test failed, ValidationError not raised.

Also, how should I test ValueError in case of field is not allowed to be null. self.assertRaises(ValueError) does not works.

Upvotes: 1

Views: 4242

Answers (1)

falsetru
falsetru

Reputation: 369074

Do you want something like this?

class TestY(TestCase):

    def test_model_relation(self):
        x = X.objects.create(name="test1")
        y = Y(event=X.objects.create(name="test2"))
        y.full_clean()  # `event` correctly set. This should pass
        y.save()
        self.assertEqual(Y.objects.filter(event__name="test2").count(), 1)

    def test_model_relation__event_missing(self):
        x = X.objects.create(name="test1")
        y = Y()  # Y without `event` set
        with self.assertRaises(ValidationError):
            y.full_clean()
            y.save()
        self.assertEqual(Y.objects.filter(event__name="test2").count(), 0)

BTW, you should specify test in test methods (method whose name starts with test), not in class body.

Upvotes: 1

Related Questions