icelemon
icelemon

Reputation: 865

How to pytest a python function with raise exception

My folder struct looks like this:

|- src
    |- __init__.py
    |- funcA.py
    |- util.py
|- tests
   |- __init__.py
   |- test_funcA.py
   |- test_util.py

My goal is to test a function in funcA.py

def f():
   try:
     helper()
   except Exception as e:
     raise Exception('error: fail to call helper')

The helper function in util.py

def helper():
   try:
     #do something
   except Exception as e:
     raise Exception('error: fail to do something') 

The unit test I write for f() is not cover these two lines except Exception as e: raise Exception('error: fail to call helper')

Here is my testcase for f

def test__f():
    with mock.patch('src.utils.helper', side_effect=Exception('fail to call helper')):
        from src import funcA
        with pytest.raises(Exception):
            funcA.f()

How to write unit test to cover f's raise exception? Thanks

Upvotes: 1

Views: 347

Answers (1)

Davide Moro
Davide Moro

Reputation: 166

I think that the "src.utils.helper" is wrong. I guess you should use "src.funcA.helper".

Upvotes: 1

Related Questions