dimanche 12 juillet 2020

Why won't this post request submit a file in Django Tests

I have a test that looks like this:

        with open('/path/testing_file.txt') as fp:
            file = fp
        form = {
            'data1': 'text',
            'data2': 'text2',
            'file': open('/path/testing_file.txt'),
        }
        response = self.client.post('/link', form, follow=True)

'/link' is connected to a view which prints the POST data:

print(request.POST)

In my actual site I submit files with an AJAX request, and it works well. However, when attempting to execute this unit test, the file is not submitted. The print statement prints this:

<QueryDict: {'data1': ['text'], 'data2': ['text2']}>

I tested the output with print(request.body) as well, and the output is messy, but is clear that the file data is getting sent to the request object, as I can see the content of file in the output.

However, since my code works by accessing the file through request.POST['file'] already, I don't want to modify the view code to accommodate a test. So why isn't this working, and how can I properly post a file in django tests?

Aucun commentaire:

Enregistrer un commentaire