当我使用mock库时,例如with mock.patch('os.path.join'):,一切正常,但是当我像这样使用pytest-mock时,如果断言失败,我会得到以下错误:
pytest似乎试图使用'os.path‘模块,但由于它是用mocker打补丁的,它失败了,并引发了错误,我做错了什么吗?
AssertionError: Expected 'transform_file' to be called once. Called 0 times.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 890, in _find_spec
AttributeError: 'AssertionRewritingHook' object has no attribute 'find_spec'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\anaconda\lib\site-packages\py\_path\common.py", line 29, in fspath
return path_type.__fspath__(path)
AttributeError: type object 'MagicMock' has no attribute '__fspath__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\anaconda\lib\site-packages\py\_path\local.py", line 152, in __init__
path = fspath(path)
File "c:\anaconda\lib\site-packages\py\_path\common.py", line 42, in fspath
+ path_type.__name__)
TypeError: expected str, bytes or os.PathLike object, not MagicMock
... etc etc发布于 2017-09-20 04:07:00
要模拟或者更确切地说单元测试os.path.join,您可以使用monkeypatch,因为您已经在使用py.test,例如source
# content of test_module.py
import os.path
def getssh(): # pseudo application code
return os.path.join(os.path.expanduser("~admin"), '.ssh')
def test_mytest(monkeypatch):
def mockreturn(path):
return '/abc'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
x = getssh()
assert x == '/abc/.ssh'https://stackoverflow.com/questions/45873226
复制相似问题