Search code examples
pythondjangodjango-testingdjango-tests

Write test for views containing os.remove in django


I have a function based view function in django that receives an ID from a model, retrieve a file address and delete it using os.remove

image = Images.objects.get(id=image_id)
os.remove(image.file)

the image_id is valid and is a part of my fixture.

what's the best way to write a test for this view, without manually creating a file each time I'm testing the code?

Is there a way to change the behavior of os.remove function for test?


Solution

  • Yes. It's called mocking, and there is a Python library for it: mock. Mock is available in the standard library as unittest.mock for Python 3.3+, or standalone for earlier versions.

    So you would do something like this:

    from mock import patch
    ...
    @patch('mymodel_module.os.remove')
    def test_my_method(self, mocked_remove):
        call_my_model_method()
        self.assertTrue(mocked_remove.called)
    

    (where mymodel_module is the models.py where your model is defined, and which presumably imports os.)