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?
mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest. mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.
side_effect: side_effect allows to perform side effects, including raising an exception when a mock is called. patch(): The patch() decorator/ context manager makes it easy to mock classes or objects in a module under test.
With a module variable you can can either set the value directly or use mock. patch .
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. Mock
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With