Reputation: 7467
How do I mock os.remove
with unittest.mock
?
My attempt (using pytest
)
def test_patch_remove():
with patch("os.remove"):
remove('foo')
gives the error
remove('foo') E FileNotFoundError: [Errno 2] No such file or directory: 'foo'
indicating that remove has not been mocked.
Upvotes: 4
Views: 3966
Reputation: 16855
You have two possibilities: either you mock the module os
and use remove
from the module (test_remove1
), or you do from os import remove
, and mock the copy in your own module (test_remove2
):
test_remove.py
import os
from os import remove
from mock import patch
def test_remove1():
with patch('os.remove'):
os.remove('foo')
def test_remove2():
with patch('test_remove.remove'):
remove('foo')
In a real test the import will happen in another module, so the second case has to be adapted to patch that module.
Upvotes: 8