使用 Django 测试上传图像时出现 MultiValueDictKeyError

MultiValueDictKeyError when upload an Image using Django Test

您好,我正在尝试制作一个测试用例来测试我上传的图片 API。但是我想当我传递 request.FILES

的文件时我没有返回任何东西
#models.py
class Image(models.Model):
    name = models.CharField(max_length=200)
    imagefile = models.ImageField(
        null=True,
        blank=True,
        max_length=500,
        upload_to='temp/images/')
    def __str__(self):
        return self.name

#views.py
class ImagesView(APIView):
    def post(self, request):
        print("DATA!!!", request.data)
        print("FILE!!!", request.FILES)
        params = Image(
            imagefile=request.FILES['image'])
        params.save()
        print(params)

        return Response({"status": "ok"})

#test.py
class CanalImagesApiTests(TestCase):
    fixtures = []
    def test_post_image(self):
        c = Client()
        response = c.post('/admin/login/', {'username': 'admin', 'password': 'passwrd'})
        filename = 'data/sample_image.jpg'
        name = 'sample_image.jpg'
        data = {"data": "passthis"}
        print(to_upload)
        with open(filename, 'rb') as f:
            c.post('/images/', data=data, files={"name": name, "image": f}, format='multipart')
        response = c.get('/images/')
        results = response.json()

我的 request.FILES 是空的:<MultiValueDict: {}> 我的测试出现错误:django.utils.datastructures.MultiValueDictKeyError: 'image'

  • 您可以在数据字典中传递一个文件对象。
  • 不需要
  • files 参数。 format参数表示输出格式,不是输入格式。
  • 如果您正在测试 Django REST Framework API,则可以使用 APITestCase 而不是 TestCase。这使您可以测试某些方法,例如 PUT
from rest_framework import status
from rest_framework.test import APITestCase


class CanalImagesApiTests(APITestCase):
    def test_post_image(self):
        with open('data/sample_image.png', 'rb') as f:
            data = {
                "data": "passthis",
                "image": f,
            }

            response = self.client.post('/images/', data=data)
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.json(), {"status": "ok"})

测试结果(通过):

DATA!!! <QueryDict: {'data': ['passthis'], 'image': [<InMemoryUploadedFile: sample_image.png (image/png)>]}>
FILE!!! <MultiValueDict: {'image': [<InMemoryUploadedFile: sample_image.png (image/png)>]}>