Django 模型中的单元测试外键约束 [英] Unit Test foreign key constraints in Django models

查看:30
本文介绍了Django 模型中的单元测试外键约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了 2 个模型,其中一个通过外键关系引用到另一个模型.我想编写单元测试来确保这种关系.

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)

在测试中我有

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)

这表示测试失败,ValidationError 未引发.

This says test failed, ValidationError not raised.

另外,如果字段不允许为空,我应该如何测试 ValueError.self.assertRaises(ValueError) 不起作用.

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

推荐答案

你想要这样的东西吗?

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)

顺便说一句,您应该在测试方法(名称以 test 开头的方法)中指定 test,而不是在类体中.

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

这篇关于Django 模型中的单元测试外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆