How to mock a patch in a django model field?
I have two models:
class Transaction(models.Model):
gateway_reference = models.CharField(max_length=255, null=True, blank=True)
...
@property
def abc(self):
...
class Item(models.Model):
txn = models.ForeignKey('Transaction')
def refund(self):
Gateway.refund(self.txn)
In my unittest:
def test_decline(self):
item = Item.objects.get(...)
with patch('app.models.Transaction.gateway_reference', new='invalid reference'):
item.refund()
But he complains that Transaction class does not have the attribute 'gateway_reference'
Note: I am using a similar patch for a property of a model class and it worked fine for example.
with patch('app.models.Transaction.abc', new='lalala')
source to share
When you instantiate the model with the line below
item = Item.objects.get (...)
You have already referenced the transaction model using the attribute txn
. Thus, fixing a class Transaction
in this namespace after instantiation is too late.
I would use the patch object here on the instance item
. See https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.patch.object
source to share