Mock objects
When writing tests, you will often find that you are not only testing your own code, but also the interaction with external resources, such as hardware, databases, web hosts, servers, and others. Some of these can be run safely, but certain tests are too slow, too dangerous, or even impossible to run. In those cases, mock objects are your friends; they can be used to fake anything, so you can be certain that your code still returns the expected results without having any variation from external factors.
Using unittest.mock
The unittest.mock
library provides two base objects, Mock
and MagicMock
, to easily mock any external resources. The Mock
object is just a general generic mock object and MagicMock
is mostly the same, but it has all the Python magic methods such as __contains__
and __len__
defined. In addition to this, it can make your life even easier. This is because in addition to creating mock objects manually, it is possible to patch objects directly using...