Simple use of python mock

Record what you use today first, and organize it later.

Suppose the method to be tested:

def target():
    wb = openpyxl.load_workbook('test')
    ws = wb['sheet']
    ws.values
    ...

It can be seen that openpyxl is used in the target to read the excel file, and then process it. I don’t want to read the file anymore during the test. I need to mock openpyxl.
I need to create a class first, which requires support for reading values ​​​​in the form of []. And the returned values ​​must be an iterator, each item is a tuple:

class Values:
    
    @property
    def values(self):
        for k, v in self._values:
            yield k, v
            
    @values.setter
    def values(self, values):
        self._values = values

class LoadWorkbook:
    # 因为要mock的方法接收了一个参数,所以这里也需要接收一个参数
    def __init__(self, workbook):
        pass
    
    # 支持以[]方式读取数据
    def __getitem__(self, item):
        return Values()

Then use in test:

from unitest.mock import patch

...

@patch('openpyxl.load_workbook')
def test_target(mock_load_workbook):
    # mock_load_workbook会代替target方法中的load_workbook
    # 给mock_load_workbook添加副作用,当target中执行load_workbook('test')时
    # 会执行LoadWorkbook('test')
    mock_load_workbook.side_effect = LoadWorkbook
    ...
    

Guess you like

Origin blog.csdn.net/Crazy_zh/article/details/113731780