0

I am doing a Django project where a user uploads a file to my website and then a program takes that data and assigns it to a model. I am attempting to be a good little programmer and test my code as I go, but I appear to have run into a testing issue.

One thing I want to do is limit the file types that the user can upload to .xls files. I wrote a test for this and submit the file to the form like so self.form = self.form({'file' : good_file}). I overrode the clean_file() method that the form uses to to look at the extension and raise a validation error if it's not in the approved file type list. I tried following the example posted here https://docs.djangoproject.com/en/3.1/ref/forms/validation/ and pulling the file from cleaned_data['file'] but all that is there for file is 'file' : None. However when I test a view redirecting to a different page when the user uploads a file like so response = self.client.post('/teacher/add_course', data={'file' : open(file)}) I see the file in clean_file() as 'file' : InMemoryUploadedFile.

So basically I didn't submit the file right in the form test or at least didn't give it to the form in the way that the view did. Can yall tell me what I need to be doing differently?

  • Does this answer your question? [how to unit test file upload in django](https://stackoverflow.com/questions/11170425/how-to-unit-test-file-upload-in-django) – iklinac Feb 13 '21 at 13:24
  • unfortunately no, I use that for testing the view, but the form seems to be different! While I could indirectly test it that way, it would break the rule of isolation I think – UnboltingZero0 Feb 13 '21 at 13:47
  • Form submission is in this case browser doing POST request ( https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) , nothing different than ordinary post except you pass file as parameter using enctype="multipart/form-data" which client.post would automatically encode for you – iklinac Feb 13 '21 at 13:57
  • hmm, so I might need to somehow add that in too? – UnboltingZero0 Feb 13 '21 at 14:14

0 Answers0