I am creating a utility to handle file uploads in webob-based applications. 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). 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). Or is it a better idea to mock it?
First CGI Program Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.
The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator, and also supports the standard dictionary method keys() and the built-in function len() .
An example of a CGI program is one implementing a wiki. If the user agent requests the name of an entry, the Web server executes the CGI program. The CGI program retrieves the source of that entry's page (if one exists), transforms it into HTML, and prints the result.
Your answer fails in python3. Here is my modification. I'm sure it is not perfect, but at least it works on both python2.7 and 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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With