0

I want to test a view that is suppose to receive files attached with the request. my django test:


TEST_DIR = "myapp/tests/test_data/"
file_name = "some_resume.pdf"
email_data = {
  "sender": "somedude@someprovidercom",
  "recipient": "someotherdude@someotherprovider.com",
  "subject": "New candidate",
  "stripped-html": "Check out this new candidate."
}

api = APIClient()

with open(FILE_DIR + file_name, "rb") as fp:
  response = api.post(
    "/api/v1.0/emails/receive/",
    data=email_data,
    files={"resume": fp},  # pass file handler open with byte mode
    format="multipart",  # use multipart format
  )
  print(response)


# test some stuff

the api response is correct: <Response status_code=200, "application/json">

but when I print the files attached to the request in the View I get nothing:

print(request.FILES)
# <MultiValueDict: {}>

I checked everywhere and the format for my api request looks file. Also, my view works fine when I test with shell sending request with with python requests library. Am I missing anything? Could id be somehow related to my test environment or some obscure middlewares?

Martin Faucheux
  • 884
  • 9
  • 26
  • print response tu see more info, be care about email_data its on correct format – Luis Bote Mar 18 '21 at 08:34
  • I wrote the payload content and the response data that I get, everything is normal – Martin Faucheux Mar 18 '21 at 08:44
  • try it, will give u more info https://stackoverflow.com/questions/10588644/how-can-i-see-the-entire-http-request-thats-being-sent-by-my-python-application – Luis Bote Mar 18 '21 at 08:58
  • You're probably using DRF, so without seeing your view (e.g. to see if you specify any parsers (https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser)), you might want to try and pass the `fp` in the `data=` argument (inside `email_data`). Here's some good discussion on the matter https://stackoverflow.com/questions/24201676/how-can-i-test-binary-file-uploading-with-django-rest-frameworks-test-client/50648293 – Raekkeri Mar 18 '21 at 10:00

0 Answers0