Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a method is called using pytest

I want to write a unit test to check if a method is being called. Is there any way to do it. Or i am misunderstanding the way mock can be used here? As this way mocked_method is always called but without any args.

@(pytest.parameterize)
def test(jsonrpc_proxy):
    jsonrpc_proxy.method1_call()
    # Method 1 should not call method 2
    with mock.patch('method2') as mocked_method:
        assert ((args),) not in mocked_track.call_args_list

    # do something 
    jsonrpc_proxy.method1_call()
    # Method 1 should call method 2
    with mock.patch('method2') as mocked_method:
        assert ((args),) in mocked_track.call_args_list

PS: I have checked other questions related to it before posting, but i think i am misunderstanding the whole concept about how we use mock in such scenarios. Please enlighten me as i am new to this.

like image 290
Rajat Vij Avatar asked Oct 16 '25 16:10

Rajat Vij


1 Answers

you need to call method1 when method2 is patched, not before that. try moving the call inside the with statement:

with mock.patch('method2') as mocked_method:
    jsonrpc_proxy.method1_call()
    assert ((args),) not in mocked_track.call_args_list
like image 58
DorElias Avatar answered Oct 18 '25 04:10

DorElias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!