测试文档

本页介绍在为自定义文档模型和表单编写测试时的一些常见模式。

测试文档上传表单

测试文档上传表单时,上传的文件需要通过表单构造函数的 files 参数传入。把文件放在 data 里传不会触发 Django 的文件上传处理。

示例:

from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from wagtail.documents import models
from wagtail.documents.forms import get_document_form


class CustomDocumentFormTest(TestCase):
    def test_limit_upload_file_size(self):
        form_data = {
            "title": "Simple Text Document",
            "tags": [],
        }
        file_data = {
            "file": SimpleUploadedFile(
                "simple.txt", b"hello world" * 1024 * 1024, content_type="text/plain"
            ),
        }
        form_cls = get_document_form(models.Document)
        form = form_cls(form_data, file_data)
        self.assertFormError(
            form, "file", ["The file size exceeds the configured limit (1MB)."]
        )