【问题标题】:How to cover the except portion of a try-except in a python pytest unit test如何在 python pytest 单元测试中覆盖 try-except 的异常部分
【发布时间】: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


【解决方案1】:

在测试用例期间使用模拟库和side_effect 抛出异常

【讨论】:

    【解决方案2】:

    模拟master 并在update 方法中引发异常。

    【讨论】:

      【解决方案3】:

      好的,我想通了。我了解到您必须将参数传递给monkeypatch调用的方法。这些参数必须与被替换或模拟的方法的签名相匹配。实际上,我还使用前缀 fake_ 重命名了该方法以表示模拟。这是我所做的:

      @staticmethod
      def fake_update_flush_error(dbsession, company_id=None, address_id=None, proportion=None,
                                  company_name=None, receiver_name=None, invoice_delivery_method=None,
                                  invoice_delivery_text=None, master_bill_to=False):
          raise FlushError
      
      
      def test_create_bill_to_fails_when_master_update_fails(dbsession, invoice_group1, company1,
                                                             bill_to1, monkeypatch):
      
          context = TestContext()
          monkeypatch.setattr(BillTo, 'update', fake_update_flush_error)
      
          with pytest.raises(Conflict):
              create_bill_to(
                  context,
                  dbsession=dbsession,
                  invoice_group_id=invoice_group1.id,
                  company_id=company1.id,
                  address_id=None,
                  ...
          )
      

      BillTo.update 方法需要所有这些参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多