Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock os.remove in Python with unittest.mock

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.

like image 674
DaveFar Avatar asked Sep 15 '25 21:09

DaveFar


1 Answers

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.

like image 194
MrBean Bremen Avatar answered Sep 17 '25 13:09

MrBean Bremen