首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能用pytest-mock模拟'os.path.join‘

不能用pytest-mock模拟'os.path.join‘
EN

Stack Overflow用户
提问于 2017-08-25 09:45:49
回答 1查看 2.4K关注 0票数 6

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

pytest似乎试图使用'os.path‘模块,但由于它是用mocker打补丁的,它失败了,并引发了错误,我做错了什么吗?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-20 04:07:00

要模拟或者更确切地说单元测试os.path.join,您可以使用monkeypatch,因为您已经在使用py.test,例如source

代码语言:javascript
复制
# 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'
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45873226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档