简体   繁体   中英

How to cover the except portion of a try-except in a python pytest unit test

I'm new to Python. I need to unit test the except part of a try-except statement in python. I'm using pytest. The problem is that I don't know how to force the try part to raise an exception. Here is my code:

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)

The master.update method is called to make an update to the database. But how do I mock this code so that it somehow raises an exception in the try portion?

I'm trying to use monkeypatch with this code. The master object is an instance of the BillTo class so I'm thinking of putting that as the first parameter to 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,
    )

But for some reason, the error is not raised.

使用模拟库和side_effect在测试用例期间引发异常

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

Ok, I figured it out. I learned that you must pass parameters to the method called by monkeypatch. These parameters must match the signature of the method being replaced or mocked. Actually I also renamed the method with a prefix fake_ to denote the mocking. Here is what I did:

@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,
            ...
    )

The BillTo.update method needed all those parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM