简体   繁体   English

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

[英]How to create cgi.FieldStorage for testing purposes?

I am creating a utility to handle file uploads in webob-based applications.我正在创建一个实用程序来处理基于 webob 的应用程序中的文件上传。 I want to write some unit tests for it.我想为它写一些单元测试。

My question is - as webob uses cgi.FieldStorage for uploaded files I would like to create a FieldStorage instance in a simple way (without emulating a whole request).我的问题是 - 由于 webob 使用cgi.FieldStorage上传文件,我想以一种简单的方式创建一个FieldStorage实例(不模拟整个请求)。 What it the minimum code I need to do it (nothing fancy, emulating upload of a text file with "Lorem ipsum" content would be fine).这是我需要做的最少代码(没什么特别的,模拟上传带有“Lorem ipsum”内容的文本文件就可以了)。 Or is it a better idea to mock it?还是嘲笑它更好?

After some research I came up with something like this: 经过一些研究,我想出了类似的东西:

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             

This is sufficient for my unit tests. 这足以进行我的单元测试。

Your answer fails in python3. 你的答案在python3中失败了。 Here is my modification. 这是我的修改。 I'm sure it is not perfect, but at least it works on both python2.7 and python3.5. 我敢肯定它并不完美,但至少它适用于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)

I was doing something like this, since in my script i'm using我正在做这样的事情,因为在我的脚本中我正在使用

import cgi

form = cgi.FieldStorage()

>>> # which result:
>>> FieldStorage(None, None, [])

When your URL contains query string it will look like this:当您的 URL 包含查询字符串时,它将如下所示:

# URL: https://..../index.cgi?test=only
FieldStorage(None, None, [MiniFieldStorage('test', 'only')])

So i was just pushing manually MiniFieldStorage into the form variable所以我只是手动将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.

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