如何模拟对象属性以及复杂的字段和方法?

Ish*_*att 1 python unit-testing mocking python-2.7

我有一个需要进行单元测试的以下功能。

def read_all_fields(all_fields_sheet):
    entries = []

    for row_index in xrange(2, all_fields_sheet.nrows):
        d = {'size' : all_fields_sheet.cell(row_index,0).value,\
             'type' : all_fields_sheet.cell(row_index,1).value,\
             'hotslide' : all_fields_sheet.cell(row_index,3).value}
        entries.append((all_fields_sheet.cell(row_index,2).value,d))

    return entries
Run Code Online (Sandbox Code Playgroud)

现在,我的 all_fields_sheet 是 xlrd 模块返回的工作表(用于读取 Excel 文件)。

所以,基本上我需要模拟以下属性 nrows cell

我该怎么去绑架它呢?

Mar*_*ers 5

只需直接在模拟对象上模拟调用和属性即可;调整以满足您的测试需求:

mock_sheet = MagicMock()
mock_sheet.nrows = 3  # loop once
cells = [
    MagicMock(value=42),     # row_index, 0
    MagicMock(value='foo'),  # row_index, 1
    MagicMock(value='bar'),  # row_index, 3
    MagicMock(value='spam'), # row_index, 2
]
mock_sheet.cell.side_effect = cells
Run Code Online (Sandbox Code Playgroud)

通过分配一个列表,Mock.side_effect您可以按顺序控制调用.cell()返回的内容。

然后,您可以测试是否使用各种断言方法进行了正确的调用。您可以使用该mock.call()对象来给出精确的期望:

result = read_all_fields(mock_sheet)
self.assertEqual(
    result, 
    [('spam', {'size': 42, 'type': 'foo', 'hotslide': 'bar'})]
)

self.assertEqual(
    mock_sheet.cell.call_args_list,
    [call(2, 0), call(2, 1), call(2, 3), call(2, 2)])
Run Code Online (Sandbox Code Playgroud)

Mock.call_args_list在这里用来匹配精确的调用次数,直接与mock_sheet.cell单独匹配。

演示,假设您的read_all_fields()函数已经定义:

>>> from unittest.mock import MagicMock, call
>>> mock_sheet = MagicMock()
>>> mock_sheet.nrows = 3  # loop once
>>> cells = [
...     MagicMock(value=42),     # row_index, 0
...     MagicMock(value='foo'),  # row_index, 1
...     MagicMock(value='bar'),  # row_index, 3
...     MagicMock(value='spam'), # row_index, 2
... ]
>>> mock_sheet.cell.side_effect = cells
>>> result = read_all_fields(mock_sheet)
>>> result == [('spam', {'size': 42, 'type': 'foo', 'hotslide': 'bar'})]
True
>>> mock_sheet.cell.call_args_list == [call(2, 0), call(2, 1), call(2, 3), call(2, 2)]
True
Run Code Online (Sandbox Code Playgroud)

或者,您可以为该mock_sheet.cell.side_effect属性创建一个函数,以从您之前设置的“工作表”返回值:

cells = [[42, 'foo', 'spam', 'bar']]  # 1 row
def mock_cells(row, cell):
    return MagicMock(value=cells[row - 2][cell])
mock_sheet.cell.side_effect = mock_cells
Run Code Online (Sandbox Code Playgroud)

side_effect是一个函数时,只要被调用就会调用它mock_sheet.cell(),并使用相同的参数。