2017-08-25 77 views
2

当我使用模拟库时,例如with mock.patch('os.path.join'):一切正常,但是当我使用pytest-模拟这样mocker.patch('os.path.join')我收到以下错误,如果断言失败:不能用pytest-mock模拟'os.path.join'

似乎pytest尝试使用“os.path中”模块,但因为它是修补与模仿者,它失败并引发错误,我做错了什么?

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 

回答

0

嘲笑或者说单元测试os.path.join你,因为你已经在使用可以使用猴补丁py.test e.g 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'