Django如何触发类属性的验证以引发异常

时间:2018-06-01 20:08:36

标签: django python-3.x pytest

我有这个功能,我试图测试折扣金额是否大于发票金额,那么应该提出验证错误。 Iam坚持实际触发异常,因为它在测试中被引发。见下文

class Invoice(models.Model):
    @property   
    def inv_amount(self):
        amount = Sum(quantity * price)
        return amount

    @property
    def discount_amount(self):
        amount = Sum(discount)
        return amount  

    def validate_amount(self):
        if self.discount_amount > self.inv_amount:
            raise ValidationError("discount amount cannot be greater")

def_test_validate_amount_greater_than_discount():
    with pytest.raises(ValidationError) as e:
       #Trigger the exception

1 个答案:

答案 0 :(得分:0)

要触发例外,您只需在i.validate_amount()内拨打iwith 发票对象,错误值)。

此外,您可以使用e检查该quantity是否为expected exception

编辑(根据您的问题的评论):

您无法设置属性,但您可以设置值pricediscountInvoice以使其失败,假设这些属于该类的一部分{ {1}}