django - how to unit test a post request using request.FILES
This video explains
django - how to unit test a post request using request.FILES
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
01:08 Accepted answer (Score 22)
01:36 Answer 2 (Score 43)
01:57 Answer 3 (Score 3)
02:24 Thank you
--
Full question
https://stackoverflow.com/questions/9549...
Answer 2 links:
[Mock]: http://www.voidspace.org.uk/python/mock/...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #unittesting
#avk47
django - how to unit test a post request using request.FILES
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
01:08 Accepted answer (Score 22)
01:36 Answer 2 (Score 43)
01:57 Answer 3 (Score 3)
02:24 Thank you
--
Full question
https://stackoverflow.com/questions/9549...
Answer 2 links:
[Mock]: http://www.voidspace.org.uk/python/mock/...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #unittesting
#avk47
ANSWER 1
Score 44
The way django's testsuite does it is:
from django.core.files.uploadedfile import SimpleUploadedFile
f = SimpleUploadedFile("file.txt", b"file_content")
This way you don't need to create a temp file and write to it, and you don't need to mock a file (not as easy as it sounds).
ACCEPTED ANSWER
Score 23
In the docs, the file field is called attachment, but in yours, it's called file.
You don't need name in your post data either -- that refers to another field called name, not the name of the file that you are uploading.
Try the following:
def test_stuff(self):
myfile = open('....\file.csv','r')
response = self.client.post('/', {'file':myfile})
ANSWER 3
Score 3
Maybe I'm missing something here, but sounds like a job for a good mock library. I personally really like Mock. But, I fall into the camp that believes that your unit tests should be free of all external dependencies (like having to have a file named "file.csv" in a certain location, etc.)