Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 902
In78 Avatar asked Sep 20 '20 04:09

In78


People also ask

Can we mock a class in Python?

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.

What is Side_effect in mock Python?

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.

Can you mock a variable Python?

With a module variable you can can either set the value directly or use mock. patch .


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
like image 66
ShadowRanger Avatar answered Oct 18 '22 09:10

ShadowRanger