这个问题有点老了,我的回答来自 Django 2.0 和 Python 3.6.6 或更高版本。虽然我认为该技术也适用于旧版本,但 YMMV。
我认为这是一个比它得到赞誉的问题更重要的问题!当您编写好的测试时,需要编写测试文件或生成测试文件只是时间问题。无论哪种方式,您都有污染服务器或开发人员机器的文件系统的危险。 两者都不可取!
我认为this page 上的文章是最佳实践。如果您不关心推理,我将复制/粘贴下面的代码 sn-p (后面有更多注释):
----
首先,让我们编写一个基本的、非常基本的模型
from django.db import models
class Picture(models.Model):
picture = models.ImageField()
然后,让我们编写一个非常非常基本的测试。
from PIL import Image
import tempfile
from django.test import TestCase
from .models import Picture
from django.test import override_settings
def get_temporary_image(temp_file):
size = (200, 200)
color = (255, 0, 0, 0)
image = Image.new("RGBA", size, color)
image.save(temp_file, 'jpeg')
return temp_file
class PictureDummyTest(TestCase):
@override_settings(MEDIA_ROOT=tempfile.TemporaryDirectory(prefix='mediatest').name)
def test_dummy_test(self):
temp_file = tempfile.NamedTemporaryFile()
test_image = get_temporary_image(temp_file)
#test_image.seek(0)
picture = Picture.objects.create(picture=test_image.name)
print "It Worked!, ", picture.picture
self.assertEqual(len(Picture.objects.all()), 1)
----
我对代码 sn-p 进行了一项重要更改:TemporaryDirectory().name。原来的 sn-p 使用了 gettempdir()。 TemporaryDirectory 函数会在每次调用时创建一个具有系统生成名称的新文件夹。该文件夹将被操作系统删除 - 但我们不知道什么时候!这样,我们每次运行都会获得一个新文件夹,因此不会发生名称冲突。注意我必须添加 .name 元素来获取生成的文件夹的名称,因为 MEDIA_ROOT 必须是一个字符串。最后,我添加了 prefix='mediatest',以便在我想在脚本中清理它们时轻松识别所有生成的文件夹。
还有可能对您有用的是,如何将设置覆盖轻松应用于测试类,而不仅仅是一个测试功能。详情请见this page。
在这篇文章之后的 cmets 中还要注意,有些人展示了一种更简单的方法来获取临时文件名,而无需担心使用 NamedTemporaryFile 的媒体设置(仅适用于不使用媒体设置!)。