【发布时间】:2021-01-18 14:54:22
【问题描述】:
我正在为我的Imagefield 模型编写一个测试来检查它的相对路径名,但它没有通过,因为__str__ 方法返回了文件路径+一些不需要的字符。例如,创建为test_image.png 的文件返回为test_image_ak0LKei.png,尽管我明确定义了文件名。每次创建新文件时,附加部分都会发生变化,例如可以返回test_image_HqOXJc4.png。
这只发生在我为测试创建虚拟图像文件时。当我在 Django 的管理员中上传真实图像时,它只是返回文件路径而不做任何修改。我使用 Sqlite 进行测试,使用 Postgres 进行开发,因为开发数据库在 Heroku 中并且不允许创建表
我尝试更改创建虚拟文件的方式,例如使用字节对象,使用来自 django 的 b64decode() 和 SimpleUploadedFile(),但结果是相同的。
我的模型:
class Image(models.Model):
image = models.ImageField(upload_to='post_images/')
alt_tag = models.CharField(max_length=125, blank=True)
def __str__(self):
return self.image.name
我的测试。我尝试的最后一件事是使用下面的静态方法:
class ImageTestCase(TestCase):
@staticmethod
def get_image_file(name='test_image.png', ext='png', size=(50, 50), color=(256, 0, 0)):
file_obj = BytesIO()
image = PIL_IMAGE.new("RGBA", size=size, color=color)
image.save(file_obj, ext)
file_obj.seek(0)
return File(file_obj, name=name)
def setUp(self):
test_image = Image.objects.create(
image = self.get_image_file(),
alt_tag = 'test image'
)
def test_image_category(self):
image1 = Image.objects.get(id=1)
self.assertEqual(str(image1), 'post_images/test_image.jpg')
失败的测试结果:
Traceback (most recent call last):
File "/home/edumats/Projects/blog/blog/posts/test_models.py", line 67, in test_image_category
self.assertEqual(str(image1), 'post_images/test_image.png')
AssertionError: 'post_images/test_image_ak0LKei.png' != 'post_images/test_image.png'
- post_images/test_image_ak0LKei.png
? --------
+ post_images/test_image.png
【问题讨论】:
-
post_images 目录下目前有文件吗?
-
是的,我在文件夹中找到了所有的虚拟文件。 Django 只是重命名它们,因为我试图再次上传同名文件。
标签: django django-models django-testing