Mock object but also assert method calls?

Thomas Lehmann thomas.lehmann.private at
Thu Aug 13 17:58:38 CEST 2015


How about asserting that test2 of class Bar is called?
Of course I can do a patch for a concrete method but
I was looking for something like:

    mocked_object.assert_method_called_with(name="test2", "hello")

If find following totally different to the normal API which
is provided by the mock library:

assert call().test2("hello") in mocked_objects.mock_calls

Is there a better way?

Foo delegates calls to Bar.

    from mock import patch
    with patch("__main__.Bar") as mocked_object:
        foo = Foo()
        # print all calls (c'tor as well as normal methods)
        for name, args, kwargs in mocked_object.mock_calls:
            print(name, args, kwargs)


<class '__main__.Bar'>
test1: Foo has been called
test2: Foo has been called with value hello
[call(), call().test1(), call().test2('hello')]
('', (), {})
('().test1', (), {})
('().test2', ('hello',), {})

More information about the Python-list mailing list