我有这两个模型:
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)
在我的单元测试中:
def test_decline(self):
item = Item.objects.get(...)
with patch('app.models.Transaction.gateway_reference', new='invalid reference'):
item.refund()
但它提示Transaction 类没有属性'gateway_reference'
注意: 我正在为模型类的属性使用类似的补丁,它工作正常,例如。
with patch('app.models.Transaction.abc', new='lalala')
最佳答案
当您使用下面的行实例化模型时
item = Item.objects.get(...)
您已经通过 txn
属性创建了对事务模型的引用。因此在实例化之后修补该命名空间中的类 Transaction
为时已晚。
我会在 item
实例上使用 patch 对象。参见 https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.patch.object
关于python - 如何模拟补丁 django 模型字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27027923/