How to cover the except portion of a try-except in a python pytest unit test
<p>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:</p>

<pre><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)
</code></pre>

<p>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?</p>

<p>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.</p>

<pre><code>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,
    )
</code></pre>

<p>But for some reason, the error is not raised.</p>