You can use a mocking library such as Mock to complete the task. For example, suppose you want to test the function_to_test function_to_test from your CGI script, you can write the unittest class as follows:
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 unit test, I get:
.. ---------------------------------------------------------------------- Ran 2 tests in 0.003s OK
source share