5

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.

2 Answers 2

6

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.

4
  • 1
    The Mock documentation specifically states that its intended for use with unittest so I disqualified this solution before posting. I realize that pytest will work with Mock but I'm looking for a more pytest specific solution. In general, I would prefer to avoid extra package dependencies. For reference, voidspace.org.uk/python/mock: "Mock is very easy to use and is designed for use with unittest."
    – guyja
    Apr 4, 2014 at 14:07
  • 2
    @guyja well, mock module is, generally speaking, the must-have tool if you want a good coverage or test specific difficult-to-reproduce situations. For mock itself it doesn't really matter what testing framework is used. I've been using mock with nose for a long time.
    – alecxe
    Apr 4, 2014 at 14:11
  • 1
    My first reaction to reading the docs for both is that they aim to solve the same set of problems. If Mock is the standard then when/why should I use pytest's monkeypatch capabilities in place of Mock.
    – guyja
    Apr 4, 2014 at 14:16
  • 1
    @guyja as far as I understand, monkeypatch is not that powerful as mock, monkeypatch is mostly for changing global settings, environment variables etc. Mock is a standard - that's why it was included in the python standard library in python3. Hope that helps.
    – alecxe
    Apr 4, 2014 at 14:19
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.