Search code examples
pythonunit-testingfile-uploadcgiwebob

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?


Solution

  • 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.