Use mock in Python unittest
To test an imported package or class, we need to mock it in our test. This post explains how to use some basic functions of mock in Python unit test.
If we have 2 modules, m1 and m2 as below:
1 |
|
1 |
|
To test m2:
1 |
|
When patching func_m1
from m1
, we are using m2.func_m1
because func_m1
has been imported into m2
.
The result of running code above is:
1 |
|
There’s no output from m1 because func_m1
is replaced by mock_func_m1
.
The with statement can also be written as decorator:
1 |
|
Mock object has several functions to indicate the number of being called and the variables used in calling. Check python unittest mock document for more information.
Change the action or attribute of a mock
A mock can be assigned with an attribute:
1 |
|
A mock can be assigned with an action:
1 |
|
The action of a mock can have side effects.
1 |
|
Using side_effect
can define the action that a function can have every time when it’s called. It’s useful when we test a infinite loop. As code above, we can throw InterruptedError to break the infinite loop.
Mock attribute of a class
If we have a class in m1:
1 |
|
To mock attribute a of Alpha:
1 |
|
Check the calls of mock
We can check if a function of mock is called:
1 |
|
Reset a mock
To reset the calling status of a mock object:
1 |
|