【发布时间】:2016-05-18 17:02:37
【问题描述】:
我是 Python 新手。我需要在 python 中对 try-except 语句的 except 部分进行单元测试。我正在使用pytest。问题是我不知道如何强制 try 部分引发异常。这是我的代码:
try:
if master_bill_to is False:
master.update(
dbsession,
company_id=master.company_id,
)
except Exception as e:
dbsession.rollback()
raise Conflict(e.message)
调用 master.update 方法对数据库进行更新。但是我如何模拟这段代码,以便它以某种方式在 try 部分引发异常?
我正在尝试将此代码与monkeypatch 一起使用。主对象是 BillTo 类的一个实例,所以我想把它作为第一个参数放到 monkeypatch.setattr 中。
def test_create_bill_to_fails_when_master_update_fails(dbsession, invoice_group1, company1,
monkeypatch):
def raise_flush_error():
raise FlushError
context = TestContext()
monkeypatch.setattr(BillTo, 'update', raise_flush_error)
with pytest.raises(FlushError):
create_bill_to(
context,
dbsession=dbsession,
invoice_group_id=invoice_group1.id,
company_id=company1.id,
)
但由于某种原因,没有引发错误。
【问题讨论】:
-
你试过搜索 Python 模拟吗?
标签: python unit-testing pytest