[英]How to create cgi.FieldStorage for testing purposes?
我正在创建一个实用程序来处理基于 webob 的应用程序中的文件上传。 我想为它写一些单元测试。
我的问题是 - 由于 webob 使用cgi.FieldStorage
上传文件,我想以一种简单的方式创建一个FieldStorage
实例(不模拟整个请求)。 这是我需要做的最少代码(没什么特别的,模拟上传带有“Lorem ipsum”内容的文本文件就可以了)。 还是嘲笑它更好?
经过一些研究,我想出了类似的东西:
def _create_fs(mimetype, content):
fs = cgi.FieldStorage()
fs.file = fs.make_file()
fs.type = mimetype
fs.file.write(content)
fs.file.seek(0)
return fs
这足以进行我的单元测试。
你的答案在python3中失败了。 这是我的修改。 我敢肯定它并不完美,但至少它适用于python2.7和python3.5。
from io import BytesIO
def _create_fs(self, mimetype, content, filename='uploaded.txt', name="file"):
content = content.encode('utf-8')
headers = {u'content-disposition': u'form-data; name="{}"; filename="{}"'.format(name, filename),
u'content-length': len(content),
u'content-type': mimetype}
environ = {'REQUEST_METHOD': 'POST'}
fp = BytesIO(content)
return cgi.FieldStorage(fp=fp, headers=headers, environ=environ)
我正在做这样的事情,因为在我的脚本中我正在使用
import cgi
form = cgi.FieldStorage()
>>> # which result:
>>> FieldStorage(None, None, [])
当您的 URL 包含查询字符串时,它将如下所示:
# URL: https://..../index.cgi?test=only
FieldStorage(None, None, [MiniFieldStorage('test', 'only')])
所以我只是手动将MiniFieldStorage
推入form
变量
import cgi
fs = cgi.MiniFieldStorage('test', 'only')
>>> fs
MiniFieldStorage('test', 'only')
form = cgi.FieldStorage()
form.list.append(fs)
>>> form
>>> FieldStorage(None, None, [MiniFieldStorage('test', 'only')])
# Now you can call it with same functions
>>> form.getfirst('test')
'only'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.