0

I am using the pytest-django client. The function I am testing needs an image in the FILE attribute of the request. I could call the function directly using the "RequestFactory" helper, but I want to use the pytest-django client. Is there any way to make the change request object that the client makes available to the function in the test? ie, I want to add the image in. Please see the comment in the code.

def test_using_pytest_django_client(client):
    request_factory = RequestFactory()
    request = request_factory.post('/some-fake-url')
    with open('somepicture.png', 'rb') as test_image:
        uploaded_file = UploadedFile(test_image, content_type='image/png')
        request.FILES['1'] = uploaded_file

        endpoint = reverse('the-real-endpoint')
        # Need to somehow make the image available on the request
        # client.request = request does not work
        client.post(endpoint)
Ryan
  • 782
  • 1
  • 10
  • 25
  • a `POST` with the correct content type and data key does the trick, e.g. `client.post('/upload/', {'file_field': io.BytesIO(b'file_contents')}, format='multipart')`. The exact input to `client.post` depends on your endpoint. – hoefling May 08 '19 at 09:57
  • Possible duplicate of [how to unit test file upload in django](https://stackoverflow.com/questions/11170425/how-to-unit-test-file-upload-in-django) – hoefling May 08 '19 at 09:59

0 Answers0