jeudi 8 avril 2021

Django testing Forms.FileField

I'm trying to test my Comment Form with FileField.

class CommentForm(forms.ModelForm):
    files = forms.FileField(
        widget=ClearableFileInput(
            attrs={"multiple": True, "class": "form-control", "id": "formFile"}
        ),
        required=False,
        label=_("Files"),
    )

    def __init__(self, *args, **kwargs):
        self.ticket = None
        super().__init__(*args, **kwargs)

    class Meta:
        model = Comment
        fields = ["body", "files"]

        labels = {"body": _("Comment body")}

    def save(self, commit=True, new_status=None):
        instance = super(CommentForm, self).save(commit=False)

        if commit:

            instance.save()

      
            file_list = []
            for file in self.files.getlist("files") or self.initial.get("files") or []:
                file_instance = self.save_attachment(file=file)
                file_list.append(file_instance)

            if len(file_list) > 0:
                async_task(add_attachments, file_list, instance.ticket.get_pk())

Writing test without attachment upload is easy, but problem starts when I want to test my form with files. I could not test whether async_task is called, and when I try to mock files and pass them to the Form, the attachment object does not apper in test database

Here is my test:

    @patch("myapp.forms.comments.async_task", autospec=True)
    def test_create_comment_with_attachment(self, async_task):
        file_mock = mock.MagicMock(spec=File)
        file_mockname = "test_name.pdf"

        form = CommentForm(
            data={
                "body": "Test comment",
                "files": mock.MagicMock(file_mock)
            }
        )

        form.ticket = self.ticket

        self.assertTrue(form.is_valid())
        form.save()
        attachment = Attachment.objects.last()
        print(attachment)

The result of printing attachment is None, while I expected my file_mock to appear.

Can anyone help my with testing attachment upload?

Aucun commentaire:

Enregistrer un commentaire