Write test for views containing os.remove in django

自作多情 提交于 2019-12-12 01:27:42

问题


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?


回答1:


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.)



来源:https://stackoverflow.com/questions/30313134/write-test-for-views-containing-os-remove-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!