简体   繁体   中英

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.

Say my model Bundle needs a Foreign Key to my other model Session: 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 :

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. You can check more about it in this related question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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