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:
import unittest
import cgi
from mock import patch
def function_to_test():
form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
return "<H1>Error</H1>\nPlease fill in the name and address.\n"
text = "<p>name: {0}\n<p>addr: {1}\n"
return text.format(form["name"].value, form["addr"].value)
@patch('cgi.FieldStorage')
class TestClass(unittest.TestCase):
class TestField(object):
def __init__(self, value):
self.value = value
FIELDS = { "name" : TestField("Bill"), "addr" : TestField("1 Two Street") }
def test_cgi(self, MockClass):
instance = MockClass.return_value
instance.__getitem__ = lambda s, key: TestClass.FIELDS[key]
instance.__contains__ = lambda s, key: key in TestClass.FIELDS
text = function_to_test()
self.assertEqual(text, "<p>name: Bill\n<p>addr: 1 Two Street\n")
def test_err(self, MockClass):
instance = MockClass.return_value
instance.__contains__ = lambda self, key: False
text = function_to_test()
self.assertEqual(text,
"<H1>Error</H1>\nPlease fill in the name and address.\n")
If I run this code as a unit test I get:
..
----------------------------------------------------------------------
Ran 2 tests in 0.003s
OK
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