【问题标题】:How to create cgi.FieldStorage for testing purposes?如何为测试目的创建 cgi.FieldStorage?
【发布时间】:2012-08-20 05:52:53
【问题描述】:
我正在创建一个实用程序来处理基于 webob 的应用程序中的文件上传。我想为它写一些单元测试。
我的问题是 - 由于 webob 使用 cgi.FieldStorage 上传文件,我想以简单的方式创建一个 FieldStorage 实例(不模拟整个请求)。我需要做的最少代码是什么(没什么花哨的,模拟带有“Lorem ipsum”内容的文本文件的上传就可以了)。还是模拟它是一个更好的主意?
【问题讨论】:
标签:
python
unit-testing
file-upload
cgi
webob
【解决方案1】:
您的答案在 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)
【解决方案2】:
经过一番研究,我想出了这样的东西:
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
这对于我的单元测试来说已经足够了。
【解决方案3】:
我正在做这样的事情,因为在我的脚本中我正在使用
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'