Python 如何为测试目的创建cgi.FieldStorage?

Python 如何为测试目的创建cgi.FieldStorage?,python,unit-testing,file-upload,cgi,webob,Python,Unit Testing,File Upload,Cgi,Webob,我正在创建一个实用程序来处理基于webob的应用程序中的文件上载。我想为它写一些单元测试 我的问题是-由于webob使用cgi.FieldStorage上传文件,我想以一种简单的方式创建一个FieldStorage实例(无需模拟整个请求)。它是我所需要的最少代码(没什么特别的,模拟上传带有“Lorem ipsum”内容的文本文件就可以了)。还是模仿它更好?经过一番研究后,我想出了这样的想法: def _create_fs(mimetype, content):

我正在创建一个实用程序来处理基于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)