Skip to content Skip to sidebar Skip to footer

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 = mod

Solution 1:

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.

Post a Comment for "Unit Test Foreign Key Constraints In Django Models"