How to make a Python mock derive from a base class?

Viewed 311

I am implementing python bindings for some C++ code using pybind11. Now I am trying to write unit tests for the bindings.

There is a class A in C++ with constructor like this:

class A
{
    A(std::unique_ptr<B> B_ptr);
}

It accepts a unique_ptr to an object of class B. class B is an abstract base class which can be derived. I have written bindings such that class B can be derived from Python. Is it possible for a Python mock created using unittest.mock to derive from class B so that A will accept the mock in its constructor?

1 Answers

Mocks can have a spec when defined, which they borrow their reported class from (along with many other basic behaviors). So the simplest way to do this is to do:

mymock = Mock(spec=B())  # Mock borrows behaviors of this instance of B, including class

If you don't want to use spec (which has many other side-effects), you can perform a targeted modification of the reported class. Mocks have an assignable __class__ attribute, so this will make an otherwise blank Mock that reports itself as a subclass of B:

mymock = Mock()
mymock.__class__ = B
Related