问题描述
我是一个测试菜鸟,我想弄清楚如何编写测试以确认模型形式有效,并将生成Post
的新实例,该实例具有一个图片字段。
我查看了some other条SO帖子,看来我应该使用SimpleUploadedFile来模拟图像字段。我很难理解SimpleUploadedFile的工作方式(尚未找到此应用程序的任何直接文档),并且不同的SO帖子使用了一些外观相似的语法。
我应该指向Django应用程序中某处保存的实际映像的真实文件路径吗,还是创建一个要使用的伪文件?
tests.py
class CreatePost(TestCase):
def test_create_post(self):
data = {
"content": "This is a post,I'm testing it out"
}
files_data = {
"image": SimpleUploadedFile(name='test_image.jpg',content=open(image_path,'rb').read(),content_type='image/jpeg')
}
response = self.client.post("/new",data=data,files=files_data)
self.assertEqual(Post.objects.count(),1)
self.assertRedirects(response,'index')
models.py
class Post(models.Model):
content = models.CharField(max_length=260)
timestamp = models.DateTimeField(auto_now_add=True)
posted_by = models.ForeignKey(User,on_delete=models.CASCADE,related_name="posts")
liked_by = models.ManyToManyField(User,blank=True,related_name="liked_posts")
image = models.ImageField(upload_to='uploads/',verbose_name='image')
def __str__(self):
return f"{self.posted_by} posted {self.content} at {self.timestamp}"
def is_valid_post(self):
return len(self.content) <= 260 and len(self.content) >= 0
class Post_form(ModelForm):
class Meta:
model = Post
fields = ['content','image']
解决方法
我很难理解SimpleUploadedFile的工作原理(尚未找到该应用程序的任何直接文档)
看看SimpleUploadedFile
中的source code吧-它是文件的简单表示,只包含内容,大小和名称。
您无需指向真实图像的真实文件(除非您愿意)。因此,您可以用假数据甚至空的二进制数据open(image_path,'rb').read()
b''
)
还将所有请求字段放在单个数据对象下。
在您的示例中,我没有发现client
的初始化。
总结一下,您的测试最终将看起来像这样:
from django.test import Client,TestCase
class CreatePost(TestCase):
def setUp(self):
self.client = Client()
def test_create_post(self):
data = {
"content": "This is a post,I'm testing it out","image": SimpleUploadedFile(name='test_image.jpg',content=b'',content_type='image/jpeg')
}
response = self.client.post("/new",data=data)
self.assertEqual(Post.objects.count(),1)
self.assertRedirects(response,'index')