简体   繁体   English

使用 Django 和 Webtest 测试图像上传

[英]Testing Image upload with Django and Webtest

Does anyone know how I can test the image upload with using WebTest.有谁知道我如何使用 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.任何帮助将不胜感激。

Power was right.权力是对的。 Unfortunately(or not) I found his answer after I spend half an hour debugging the webtest.不幸的是(或没有)我花了半个小时调试 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 webtest/app.py”,第 1028 行,在 _get_file_info 中

ValueError: upload_files need to be a list of tuples of (fieldname, filename, filecontent) or (fieldname, filename); ValueError: upload_files 需要是 (fieldname, filename, filecontent) 或 (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.问题是它没有告诉您它会自动将字段名称附加到元组发送并将 3 个项目元组变成 4 个项目一。 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 )太糟糕了,没有像样的例子,但我希望这也能帮助其他人)

Nowadays selected answer didn't help me.如今选择的答案对我没有帮助。

But I found the way to provide expected files in the .submit() method args但是我找到了在 .submit() 方法 args 中提供预期文件的方法

form.submit(upload_files=[('avatar', '/../file_path.png')])

使用 Python 3:

form["avatar"] = ("avatar.png", open(os.path.join(settings.PROJECT_PATH, '....', 'avatar.png', "rb").read())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM