Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create cgi.FieldStorage for testing purposes?

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?

like image 451
zefciu Avatar asked Aug 20 '12 05:08

zefciu


People also ask

How do I create a CGI application?

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.

What does CGI FieldStorage do?

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() .

What is CGI programming example?

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.


2 Answers

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)
like image 118
Harut Avatar answered Sep 20 '22 04:09

Harut


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.

like image 29
zefciu Avatar answered Sep 22 '22 04:09

zefciu