2011-12-13 82 views
4

如何爲Python CGI腳本設置一個小測試工具?我不想運行服務器來測試它,但我確實想爲我的測試提供各種GET/POST輸入。Python CGI FieldStorage測試工具

在我看來,FieldStorage(或其背後的對象)是完全不可變的,所以我看不到如何在線束中提供CGI數據。

回答

4

您可以使用模擬庫,如Mock來完成這項工作。例如,假設你想從你的CGI腳本測試function_to_test功能,你可以寫一個unittest class這樣的:

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") 

如果我運行此代碼作爲一個單元測試,我得到:

.. 
---------------------------------------------------------------------- 
Ran 2 tests in 0.003s 

OK 
2

如果你不想使用一個額外的庫如Mock:可以用一些測試數據設置一個cgi.FieldStorage對象。下面的Python3的例子假設你指望一個POST輸入:

import unittest 
from io import BytesIO 

class TestForm(unittest.TestCase): 

    def setUp(self): 
     """ 
     Makes a cgi.FieldStorage object 
     with some bogus fields. 
     """ 
     # provide a byte string with the parameters 
     # using the format b"name1=value1&name2=value2..." 
     urlencode_data = b"firstname=Joe&lastname=Bloggs&[email protected]" 
     urlencode_environ = { 
      'CONTENT_LENGTH': str(len(urlencode_data)), 
      'CONTENT_TYPE':  'application/x-www-form-urlencoded', 
      'QUERY_STRING':  '', 
      'REQUEST_METHOD': 'POST', 
     } 
     data = BytesIO(urlencode_data) 
     data.seek(0) 
     self.fs = cgi.FieldStorage(fp=data, environ=urlencode_environ) 

    # unit test methods come here 
    # form fields are accessible via `self.fs` 

思想來自https://bugs.python.org/file9507/cgitest.py。在那裏你可以找到其他有趣的例子,例如形式與文件上傳等。

請注意,cgi.FieldStorage__init__方法是無證的,或者至少我找不到它在current cgi module documentation