pytest-mock

By | 7月 30, 2023

pytest-mock是pytest的插件,提供了mocker fixture,解决无法通过装饰器使用unittest.mock.patch的问题。

安装:pip install pytest-mock

基本使用

import os
from unittest.mock import MagicMock

def test_foo(mocker):
    remove_mock = mocker.patch('os.remove')
    os.remove('/tmp')
    remove_mock.assert_called_with('/tmp')

    listdir_mock: MagicMock = mocker.patch.object(os, 'listdir', autospec=True)
    listdir_mock.return_value = ['a', 'b', 'c']
    assert ['a', 'b', 'c'] == os.listdir('/tmp')

    isfile_mock: MagicMock = mocker.patch('os.path.isfile')
    isfile_mock.return_value = True
    assert os.path.isfile('tmp')

mocker包含的方法有: