Question

I am unable to find specific examples for testing callbacks using pytest in the docs, google, or here on SO. I found this: What is the right way to test callback invocation using Python unittest?; but it's for unittest. I'm guessing that the monkeypatch functionality of pytest is where I should look but I'm new to automated testing and am looking for an example.

def foo(callback):
    callback('Buzz', 'Lightyear')

#--- pytest code ----
def test_foo():
    foo(hello)
    # how do I test that hello was called?
    # how do I test that it was passed the expected arguments?

def hello(first, last):
    return "hello %s %s" % first, last

Thank you in advance.

Was it helpful?

Solution

The idea is still the same.

You need to replace hello() function with a Mock, or, in another words, to "mock" the function.

Then you can use assert_called_with() to check that it was called with specific arguments you need.

OTHER TIPS

Here is my working code after applying the answer supplied by @alecxe.

def foo(callback):
    callback('Buzz', 'Lightyear')

#--- pytest code ---

import mock

def test_foo():
    func = mock.Mock()

    # pass the mocked function as the callback to foo
    foo(func)

    # test that func was called with the correct arguments
    func.assert_called_with('Buzz', 'Lightyear')

Thank you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top