编写用于大文件大小的测试。Django REST框架

huangapple go评论69阅读模式
英文:

Write test for large file size. Django rest framwork

问题

在我的Django应用程序中,有一个处理文件上传的端点。在序列化器中,我定义了文件大小验证如下:

extra_kwargs = {
    "image_file": {
        "validators": [
            get_file_size_validator(1e8),
        ],
    },
}

验证器函数如下所示:

def get_file_size_validator(file_size):
    def validator_func(file):
        if file_size < file.size:
            raise ValidationError(f"Maximum file size is {file_size}")

    return validator_func

我想编写一个测试,测试用户无法上传大文件。

我迄今为止尝试过的方法:

  1. SimpleUploadedFile("foo.pdf", b"aaaaa" * (9**10), content_type="image/jpeg")
  2. InMemoryUploadedFile(BytesIO(b"large_content"), None, "foo.jpg", "image/jpeg", lambda: 1e9, None, None)
  3. 使用mock.patch.object(InMemoryUploadedFile, "size", return_value=1e9):
  4. os.path.getsize模拟为这里推荐的方式:https://stackoverflow.com/a/35246275/1847898

第一个解决方案导致MemoryError,对于其他所有解决方案,validator_func中的文件大小都返回13。

有什么想法如何实现这一目标?

英文:

In my Django application there is an endpoint that handles file upload. In the serializer I define the file size validation like below

extra_kwargs = {
    &quot;image_file&quot;: {
        &quot;validators&quot;: [
            get_file_size_validator(1e8),
        ],
               
},

The validator function looks like this

def get_file_size_validator(file_size):
    def validator_func(file):
        if file_size &lt; file.size:
            raise ValidationError(f&quot;Maximum file size is {file_size}&quot;)

    return validator_func

I would like to write a test where I want to test that user cannot upload large files.

What I have tried so far.

  1. SimpleUploadedFile(&quot;foo.pdf&quot;, b&quot;aaaaa&quot; * (9**10), content_type=&quot;image/jpeg&quot;)
  2. InMemoryUploadedFile(BytesIO(b&quot;large_content&quot;), None, &quot;foo.jpg&quot;, &quot;image/jpeg&quot;, lambda: 1e9, None, None)
  3. Used mock.patch.object(InMemoryUploadedFile, &quot;size&quot;, return_value=1e9):
  4. Mocked os.path.getsize as recommended here https://stackoverflow.com/a/35246275/1847898

The first solution gives me MemoryError and for all the others file size is returned as 13 in validator_func

Any ideas how I can achieve this?

答案1

得分: 2

你应该模拟MemoryFileUploadHandler.file_complete方法,而不是SimpleUploadedFileInMemoryUploadedFile

from unittest.mock import patch

from django.core.files.uploadedfile import InMemoryUploadedFile, SimpleUploadedFile
from rest_framework.test import APITestCase


class TestUploadAPI(APITestCase):
    url = &quot;/api/to/the/end-point/&quot;

    @patch(&quot;django.core.files.uploadhandler.MemoryFileUploadHandler.file_complete&quot;)
    def test_validate_size(self, mock_file_complete):
        file_name = &quot;any-file-name&quot;
        file_content_type = &quot;image/png&quot;
        max_size = 1e8

        mock_file_complete.return_value = InMemoryUploadedFile(
            file=b&quot;&quot;,
            field_name=None,
            name=file_name,
            content_type=file_content_type,
            size=max_size + 1,
            charset=None,
        )

        file = SimpleUploadedFile(
            name=file_name,
            content=b&quot;&quot;,
            content_type=file_content_type,
        )
        response = self.client.post(self.url, {&quot;file&quot;: file})

        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            response.json(),
            {
                &quot;file&quot;: [&quot;Maximum file size is 100000000.0&quot;],
            },
        )
        mock_file_complete.assert_called_once()
英文:

You should mock the MemoryFileUploadHandler.file_complete method instead of SimpleUploadedFile or InMemoryUploadedFile.

from unittest.mock import patch

from django.core.files.uploadedfile import InMemoryUploadedFile, SimpleUploadedFile
from rest_framework.test import APITestCase


class TestUploadAPI(APITestCase):
    url = &quot;/api/to/the/end-point/&quot;

    @patch(&quot;django.core.files.uploadhandler.MemoryFileUploadHandler.file_complete&quot;)
    def test_validate_size(self, mock_file_complete):
        file_name = &quot;any-file-name&quot;
        file_content_type = &quot;image/png&quot;
        max_size = 1e8

        mock_file_complete.return_value = InMemoryUploadedFile(
            file=b&quot;&quot;,
            field_name=None,
            name=file_name,
            content_type=file_content_type,
            size=max_size + 1,
            charset=None,
        )

        file = SimpleUploadedFile(
            name=file_name,
            content=b&quot;&quot;,
            content_type=file_content_type,
        )
        response = self.client.post(self.url, {&quot;file&quot;: file})

        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            response.json(),
            {
                &quot;file&quot;: [&quot;Maximum file size is 100000000.0&quot;],
            },
        )
        mock_file_complete.assert_called_once()

huangapple
  • 本文由 发表于 2023年7月13日 12:09:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定