如何创建用于测试目的的cgi.FieldStorage?

6

我正在创建一个实用程序来处理基于webob的应用程序中的文件上传。我希望为此编写一些单元测试。

我的问题是 - 由于webob使用cgi.FieldStorage来处理上传的文件,我想以简单的方式创建一个FieldStorage实例(而不是模拟整个请求)。 我需要做最少的代码工作吗(没有花哨的东西,模拟上传“Lorem ipsum”内容的文本文件就可以了)?还是使用mock更好呢?

3个回答

6

你的答案在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)

content 应该是什么类型? - Harsha Biyani

5

经过一些调查,我得出了以下内容:

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             

这对于我的单元测试已经足够了。


content 应该是什么类型? - Harsha Biyani

0

我正在做类似的事情,因为在我的脚本中我正在使用

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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接