Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't mock 'os.path.join' with pytest-mock

When I use mock library, e.g. with mock.patch('os.path.join'): everything works, but when I use pytest-mock like this mocker.patch('os.path.join') I get the following error if assertion fails:

It seems that pytest tries to use 'os.path' module, but as it is patched with mocker, it fails and raises the error, am I doing something wrong?

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
like image 286
Bob Avatar asked Aug 25 '17 01:08

Bob


1 Answers

to mock or rather unit test os.path.join you could use monkeypatch since you are already using 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'
like image 150
rachid el kedmiri Avatar answered Nov 04 '22 21:11

rachid el kedmiri