django - 在编写 Django 测试用例时访问带注释的查询集

标签 django django-testing

我正在尝试编写一个测试用例,该测试用例使用通过注释添加的属性,但我的测试用例无法使用它,有什么想法可以修复它吗?谢谢

我的模型中的属性:

@property
def amount_net(self):
    net_sum = self.amount_net_sum
    return Decimal(round(net_sum, 2)) if net_sum else Decimal("0.00")

self.mount_net_sum 来自自定义管理器:

class InvoiceManager(models.Manager):

    def get_queryset(self):
        qs = super().get_queryset()
        qs = qs.annotate(amount_net_sum=Sum('line_items__amount_net'))
        return qs

在测试用例中:

self.invoice_test1 = Invoice.objects.create(
            state=InvoiceStatus.NEW, language='en',
            type=InvoiceType.INVOICE,
            created=date(2015, 1, 30),
            recipient=profile, 
        )

self.assertEqual(self.invoice_test1.amount_net, self.line_item_sum_net,
                         'Checks if the invoice calculated and expected values are same')

错误:

AttributeError: 'Invoice' object has no attribute 'amount_net_sum'

最佳答案

对象self.invoice_test1是使用您的代码创建的,它不是从数据库中获取的。因此,您的自定义管理器未被使用,并且该对象未被注释。

如果从数据库重新获取对象,则应该对其进行注释。然后,您可以在 assertEqual 检查中使用重新获取的对象。

self.invoice_test1 = Invoice.objects.get(pk=self.invoice_test1.pk)

您可能应该更改 amount_net 属性来处理对象没有 amount_net_sum 属性的情况,而不是让它引发 AttributeError

关于django - 在编写 Django 测试用例时访问带注释的查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36134295/

相关文章:

python - 从 Django 中 2 个不同表中的 2 个不同值创建 slug 字段

django - django queryset.values_list()中datetime字段到字符串的转换

django - 测试 URL 是否与正确的 View 匹配

python - 使用覆盖率,我如何测试这条线?

python - 在 gitlab ci 上运行 django 测试

django - 如何在 Django 中测试关闭数据库连接的方法?

django - DRF 嵌套序列化器支持空字段

javascript - 通过 javascript 渲染 django View

python - Django:通过 send_mass_mail() 发送 HTML 电子邮件

Django 抽象模型 + DB 迁移 : tests throw "cannot ALTER TABLE because it has pending trigger events"