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包含的方法有:
- mocker.patch
- mocker.patch.object
- mocker.patch.multiple
- mocker.patch.dict
- mocker.stopall
- mocker.stop
mocker.resetall()
: calls reset_mock() in all mocked objects up to this point.