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?
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:
(where
mymodel_module
is the models.py where your model is defined, and which presumably importsos
.)