在Django中编写包含os.remove的视图的测试 [英] Write test for views containing os.remove in django

查看:109
本文介绍了在Django中编写包含os.remove的视图的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有一个基于函数的视图函数,该函数从模型接收ID,检索文件地址,然后使用os.remove删除它.

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)

image_id是有效的,并且是我的固定装置的一部分.

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?

是否可以更改os.remove函数的行为进行测试?

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

推荐答案

是.这称为模拟,并且有一个Python库:模拟. Mock在标准库中以 unittest.mock 的形式提供.对于Python 3.3+,或者对于较早的版本,是独立.

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)

(其中mymodel_module是models.py,其中定义了模型,并且大概会导入os.)

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

这篇关于在Django中编写包含os.remove的视图的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆