你不能用
ExceptionInfo
在里面
with pytest.raises
上下文。运行预期在上下文中引发的代码,处理外部的异常信息:
with pytest.raises(InvAmtValError) as e:
invoices = InvoiceStats()
invoices.addInvoice(-1.2)
assert str(e) == 'The invoice amount(s) -1.2 is invalid since it is < $0.00'
assert e.type == InvAmtValError # etc
但是,如果您只想断言异常消息,惯用的方法是将预期的消息直接传递给
pytest.raises
以下内容:
expected = 'The invoice amount(s) -1.2 is invalid since it is < $0.00'
with pytest.raises(InvAmtValError, message=expected):
invoices = InvoiceStats()
invoices.addInvoice(-1.2)
expected = 'The invoice amount(s) 100000000.1 is invalid since it is > $100,000,00.00'
with pytest.raises(InvAmtValError, message=expected):
invoices = InvoiceStats()
invoices.addInvoice(100000000.1)
更新。尝试了建议的解决方案,得到:
> invoices.addInvoice(-1.2)
E Failed: DID NOT RAISE
这是因为
addInvoice
方法-它在
try
拦住,然后立即抓住。或者移除
尝试
完全阻止,或重新引发异常:
try:
raise InvAmtValError(amount)
except InvAmtValError as e:
print(str(e))
raise e