我正在尝试为某些具有 FileField 的模型构建测试。模型如下所示:
class SolutionFile(models.Model):
'''
A file from a solution.
'''
solution = models.ForeignKey(Solution)
file = models.FileField(upload_to=make_solution_file_path)
我遇到了两个问题:
当使用
./manage.py dumpdata
将数据保存到fixture时,文件内容不会被保存,只有文件名被保存到fixture中。虽然我发现这是预期的行为,因为文件内容没有保存到数据库中,但我想以某种方式将此信息包含在夹具中以进行测试。我有一个上传文件的测试用例,如下所示:
def test_post_solution_file(self): import tempfile import os filename = tempfile.mkstemp()[1] f = open(filename, 'w') f.write('These are the file contents') f.close() f = open(filename, 'r') post_data = {'file': f} response = self.client.post(self.solution.get_absolute_url()+'add_solution_file/', post_data, follow=True) f.close() os.remove(filename) self.assertTemplateUsed(response, 'tests/solution_detail.html') self.assertContains(response, os.path.basename(filename))
虽然此测试运行良好,但完成后会将上传的文件留在媒体目录中。当然,删除可以在 tearDown()
中处理,但我想知道 Django 是否有另一种处理方式。
我想到的一个解决方案是使用不同的媒体文件夹进行测试,该文件夹必须与测试夹具保持同步。运行测试时,有没有办法在 settings.py
中指定另一个媒体目录?我可以在转储数据中加入某种 Hook ,以便同步媒体文件夹中的文件吗?
那么,是否有更 Pythonic 或 Django 特定的方式来处理涉及文件的单元测试?
最佳答案
Django 提供了一种在 FileFields 上编写测试的好方法,而无需在真实的文件系统中搞砸——使用 SimpleUploadedFile。
from django.core.files.uploadedfile import SimpleUploadedFile
my_model.file_field = SimpleUploadedFile('best_file_eva.txt', b'these are the contents of the txt file')
这是 django 的神奇功能之一——在文档中不显示 :)。但是它被称为 here .
关于python - Django 使用测试夹具测试 FileField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2266503/