Testing Image upload with Django and Webtest
Asked Answered
I

3

6

Does anyone know how I can test the image upload with using WebTest. My current code is:

form['avatar'] =('avatar', os.path.join(settings.PROJECT_PATH, 'static', 'img', 'avatar.png'))
res = form.submit()

In the response I get the following error "Upload a valid image. The file you uploaded was either not an image or a corrupted image.".

Any help will be appreciated.

Incurvate answered 4/12, 2012 at 21:22 Comment(3)
I guess you should pass file's object.Clapper
No, if file object is passed webtest returns "ValueError: File content must be <type 'str'> not <type 'file'>"Incurvate
What happens if you pass image_file.read() ?Clapper
I
6

Power was right. Unfortunately(or not) I found his answer after I spend half an hour debugging the webtest. Here is a bit more information.

Trying to pass only the path to the files brings you the following exception:

webtest/app.py", line 1028, in _get_file_info

ValueError: upload_files need to be a list of tuples of (fieldname, filename, filecontent) or (fieldname, filename); you gave: ...

The problem is that is doesn't told you that it automatically will append the field name to the tuple send and making 3 item tuple into 4 item one. The final solutions was:

avatar = ('avatar',
           file(os.path.join(settings.PROJECT_PATH, '....', 'avatar.png')).read())

Too bad that there is not decent example but I hope this will help anyone else too )

Incurvate answered 4/12, 2012 at 22:19 Comment(1)
You mean open(....) and not file(...)Seale
F
3

Nowadays selected answer didn't help me.

But I found the way to provide expected files in the .submit() method args

form.submit(upload_files=[('avatar', '/../file_path.png')])
Fullblown answered 10/4, 2015 at 10:47 Comment(0)
A
1

With Python 3:

form["avatar"] = ("avatar.png", open(os.path.join(settings.PROJECT_PATH, '....', 'avatar.png', "rb").read())
Amboceptor answered 11/5, 2020 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.