【问题标题】:Fixture inheritance in django TestCasedjango TestCase 中的夹具继承
【发布时间】:2015-06-18 12:42:42
【问题描述】:

我有一个非常简单的场景

from django.test import TestCase

class BaseTest(TestCase):
    fixtures = ('users.json',)
    ...


class SpecificTest(BaseTest):
    fixtures = ('transactions.json',)
    ...

事务对用户有一个 FK,当 SpecificTest 尝试加载固定装置时,我得到一个 IntegrityError

IntegrityError: Problem installing fixtures: 
The row in table 'app_transactions' with primary key '1' has an 
invalid foreign key: app_transactions.user_id contains a value '30'   
that does not have a corresponding value in app_user.id.

这个错误意味着BaseTest 中加载的users.json 固定装置没有在transactions.json 固定装置之前加载(如您所料)。我的问题是,子类化测试时加载夹具的正确方法是什么?

Django 1.7

【问题讨论】:

    标签: django django-testing


    【解决方案1】:

    当您在子类中覆盖 fixtures 时,它替换固定装置,它不会扩展它们。

    您可以明确地重复固定装置:

    class SpecificTest(BaseTest):
        fixtures = ('users.json', 'transactions.json',)
    

    或在您的子类中引用BaseTest.fixtures

    class SpecificTest(BaseTest):
        fixtures = BaseTest.fixtures + ('transactions.json',)
    

    【讨论】:

    • 所以如果你使用fixtures,你基本上不能在测试中使用mixins?
    • 您可以在测试用例中使用 mixins,但它不会以您希望的方式加载固定装置。
    • Fixture 使用起来真的很痛苦,而且很快就会过时,尤其是在测试期间。相反,我使用 Factory Boy:factoryboy.readthedocs.org/en/latest
    • 感谢@Alasdair,这非常令人失望。我只是使用exeucte_command 在我自己的setUp 中加载固定装置。感谢@Brandon 的推荐。
    • 不客气。我在 FactoryBoy 上取得了很大的成功。
    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多