python - 如何模拟补丁 django 模型字段?

标签 python django mocking

我有这两个模型:

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/

相关文章:

python - 是否可以将变量作为 CSS 类传递给 Django html 模板?

python - 具有聚合函数的 Django 查询

c# - Java 中哪个最好;模拟接口(interface)还是模拟类?

flask - 如何模拟用 Python Flask route() 装饰的方法

python - 如何向现有 Tensorflow 数据集对象添加/更改组件名称?

python - conda env 创建失败?

python - 为什么使用 mask=None 或 mask=0 创建一个屏蔽的 numpy 数组这么慢

python - 一种在 python 中访问我的数据库的方法 - 我的问题到底是什么?

python - 如何在 django 中为特定数据库创建模型?

unit-testing - 如何用Moq模拟对具体对象的函数调用?