Ray
Ray

Reputation: 4929

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.

Upvotes: 1

Views: 3307

Answers (3)

Ray
Ray

Reputation: 4929

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.

Upvotes: 0

Adrian Rutkowski
Adrian Rutkowski

Reputation: 309

Use mock library and side_effect to throw Exception during test case

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

Mock master and raise an exception in the update method.

Upvotes: 0

Related Questions