This is the 30th day of my participation in the August Challenge

1. Introduction of Patch

The Patch library is a function decorator provided by the Mock library and can be used with great flexibility. Patch can create a simulation and pass it to the decorator function. For simulation of complex situations, Patch mode can also be used for simulation. You can also Patch simulated objects using Patch decorators, but pay attention to scope.

def patch(
        target, new=DEFAULT, spec=None, create=False,
        spec_set=None, autospec=None, new_callable=None, **kwargs
    ):
Copy the code

Several parameters are explained in detail here

Target: Must be a string in the format of package name. Module name. Class name (or function name).

New: You can select the type of Mock to initialize. The default is MagicMock

Spec =True or spec_set=True is used to set a Mock object to a spec/spec_set object

New_callable: Used to set a Mock object to callable, also using the MagicMock type by default

2. Simple use case for Patch

Sometimes the interface to be tested is not completed and cannot be tested directly, but the structural use case that returns the result is clear, so Patch processing can be carried out for this returned function. Specific examples are as follows:

D:\python_record\tool.py

#! /usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/8/8 15:50 # @Author : ywb # @Site : # @File : Tool.py # @software: PyCharm def load_cheers(): return "This is an uncompleted function that will not actually be called"Copy the code

D:\python_record\get_cheer_data.py

#! /usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/8/8 18:17 # @Author : ywb # @Site : # @File : get_cheer_data.py # @Software: PyCharm from tool import load_cheers def create_cheers(): result = load_cheers() return resultCopy the code

D:\python_record\test_get_cheer_data.py

#! /usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/8/8 18:20 # @Author : ywb # @Site : # @File : test_get_cheer_data.py # @Software: PyCharm import unittest from unittest import mock from get_cheer_data import create_cheers class GetCheerDataTest(unittest.TestCase): @mock.patch('get_cheer_data.load_cheers') def test_get_cheer_data(self, mock_load): Mock_load. return_value = 'here is a return value simulated from the real load_cheers function' self.assertequal (create_cheers(), 'Here is a mock return value for the real load_cheers function ') if __name__ == '__main__': unittest.main()Copy the code

result:

Testing started at 18:25 ... D: \ \ software \ python python. Exe "D: \ software \ PyCharm 2019.3.4 \ plugins \ python \ helpers \ pycharm_jb_unittest_runner py" - a path  D:/python_record/test_get_cheer_data.py Launching unittests with arguments python -m unittest D:/python_record/test_get_cheer_data.py in D:\python_record Ran 1 test in 0.003s OK Process finished with exit code 0Copy the code

3.Patch usage summary

Patch mainly modifies the class method or function that replaces multiple nested calls and can be specified as any function method in the domain. This function decorator is designed to solve the problem of unit tests and related tests failing when the Mock simply replaces the upper-level calling function or class method when the later dependent calling function changes.

In this example, you should use a mock object if you test the load_cheers() method directly. However, to test load_cheers() by calling create_cheers(), you can only use the Patch function decorator. Of course, you can test load_cheers() directly with a mock object, but the code is a lot of maintenance. And labor-intensive, once the dependency changes, the momentum is quite large.