简体   繁体   English

使用其他模型的外键测试Django模型

[英]Test django model with foreign key to another model

I want to test one specific Model without having to worry about the other Model to which it has a Foreign Key (FK) to. 我想测试一个特定的模型而不必担心它具有外键(FK)的另一个模型。

Say my model Bundle needs a Foreign Key to my other model Session: models.py : 假设我的模型捆绑包需要其他模型会话的外键: models.py

class Bundle(ModelCommon):
    session = models.ForeignKey(verbose_name=_('Session'), to=Session, default=None, null=False, blank=False)
    available = models.BooleanField(verbose_name=_('Available'), default=True, null=False, blank=False)

As I try to test my Bundle class with a Mock (because I don't need to care about what field values are in the Session object) on test_models.py : 当我尝试在test_models.py上用Mock测试我的Bundle类时(因为我不需要关心Session对象中的字段值):

def setUp(self):
    MockSession = mock.create_autospec(Session)
    self.test_session = MockSession()
    self.bundle = Bundle(session=self.test_session, name='Mega Bundle', enabled=True, available=True, price=0)

def test_event_enabled_is_default_false(self):
    session = Session()
    self.assertFalse(session.enabled)

I keep getting this message: 我不断收到此消息:

Error
Traceback (most recent call last):
File "test_models.py", line 181, in setUp
    self.bundle = Bundle(session=self.test_session, name='Mega Bundle', enabled=True, available=True, price=0)
    raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute '_state'

Here's the question: What is the absolute correct way to using a Test Double in this situation? 问题是:在这种情况下使用测试倍数的绝对正确方法是什么? Because so far I haven't managed to succeed in using one. 因为到目前为止,我还没有成功使用它。

Looks like you are trying to mock out attributes set in the Session.__init__ through autospec which is not possible. 似乎您正在尝试模拟Session.__init__通过autospec在Session.__init__设置的属性。 You can check more about it in this related question 您可以在此相关问题中查看更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM