mardi 4 avril 2017

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.

Aucun commentaire:

Enregistrer un commentaire