How can I set up a small test harness for Python CGI script? I don't want to run a server in order to test it, but I do want to supply various GET/POST inputs for my test.
It appears to me that FieldStorage (or the object behind it) is utterly immutable, so I don't see how to supply the CGI data on the fly in a harness.
You could use a mocking library, such as Mock to do the job. For example, suppose you want to test the
function_to_test
function from your CGI script, you could write a unittest class like this:If I run this code as a unit test I get:
In case you do not want to use an extra library such as Mock: it is possible to set up a
cgi.FieldStorage
object with some test data. The Python3 example below assumes that you expect aPOST
input:The idea comes from https://bugs.python.org/file9507/cgitest.py. There you can find other interesting examples, e.g. forms with file upload etc.
Note that the
__init__
method ofcgi.FieldStorage
is undocumented, or at least I could not find it in the current cgi module documentation.