Python 2.7 已終止支援,並將於 2026 年 1 月 31 日
淘汰。淘汰後,您將無法部署 Python 2.7 應用程式,即使貴機構先前曾使用機構政策重新啟用舊版執行階段的部署作業,也無法部署。現有的 Python 2.7 應用程式在
淘汰日期過後,仍會繼續執行並接收流量。建議您
改用系統支援的最新 Python 版本。
Python 2 適用的處理常式測試
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
適用於 Python 的本機單位測試一文說明如何為應用程式執行單位測試。雖然單位測試非常適合用於測試個別的程式碼單位,但程式碼單位的整合是讓應用程式得以運作的關鍵,因此,整合測試同樣重要。
就 App Engine 應用程式而言,要求處理常式是關鍵的整合點。WSGI 應用程式會將要求路由至適當的處理常式,而處理常式本身則會處理要求資料並產生回應 (如要瞭解詳情,請參閱要求處理常式)。要求處理常式是如同任何其他函式或類別的一般 Python 物件,易於在自動化測試中使用。但由於 WSGI 應用程式將這些要求處理常式包裝成類似 Shell,因此我們會在測試中使用類似的 Shell。
WebTest
我們會在測試中使用 WebTest 架構。WebTest 是針對測試 WSGI 應用程式提供簡易介面的程式庫,因此適用於要求處理常式。其做法是將 WSGI 應用程式包裝在特殊的測試應用程式中,以供後續測試使用。WebTest 可讓您在不具完整 App Engine 環境的情況下與處理常式互動;您可以輕鬆發出要求及修改要求環境。回應也有便於測試的介面。您未必需要使用 WebTest,但 WebTest 確實能讓您事半功倍。
在開始之前,請先在本機電腦或您預計執行處理常式測試的任何電腦上安裝 WebTest。如需操作說明,請前往 http://webtest.pythonpaste.org/#installation
測試簡單的「Hello World」處理常式
首先,我們要測試簡單的「Hello World!」處理常式,該處理常式會以純文字回覆來回應使用者要求。句柄的回應是「Hello World!」,內容類型為「text/plain」:
import webapp2
import webtest
class HelloWorldHandler(webapp2.RequestHandler):
def get(self):
# Create the handler's response "Hello World!" in plain text.
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello World!')
接下來,建立測試案例,然後初始化使用處理常式的測試應用程式:
...
class AppTest(unittest.TestCase):
def setUp(self):
# Create a WSGI application.
app = webapp2.WSGIApplication([('/', HelloWorldHandler)])
# Wrap the app with WebTest’s TestApp.
self.testapp = webtest.TestApp(app)
# Test the handler.
def testHelloWorldHandler(self):
response = self.testapp.get('/')
self.assertEqual(response.status_int, 200)
self.assertEqual(response.normal_body, 'Hello World!')
self.assertEqual(response.content_type, 'text/plain')
正如您所看見的,WebTest 可讓您使用簡單的 get() 呼叫建立 GET 要求 (其他要求方法也有類似的方法)。傳回值為回應物件,您可以使用該物件測試狀態碼、內文、內容類型等項目;如需可執行所有操作的詳細說明,請參閱 WebTest 首頁。
建立使用 App Engine 服務的處理常式測試
現在,讓我們看看如何測試使用 App Engine 服務的處理常式。這表示我們現在必須處理兩個可能會影響到測試的元件:我們使用的處理常式和服務。如適用於 Python 的本機單位測試一文所述,使用 testbed 是在測試中處理服務的最佳方法。
下列範例使用 Memcache,但其原則與 Datastore 或 Task Queue 等其他服務是相同的。
我們測試的處理常式會快取指定的鍵和值。請注意,我們會剖析要求參數中的兩個值。
from google.appengine.api import memcache
from google.appengine.ext import testbed
import webapp2
import webtest
class CacheHandler(webapp2.RequestHandler):
def post(self):
key = self.request.get('key')
value = self.request.get('value')
memcache.set(key, value)
如同前述,請在這項測試中先建立應用程式,並使用 WebTest 進行包裝。此外,請啟用 Testbed 執行個體,並務必在測試後停用。
...
class AppTest(unittest.TestCase):
def setUp(self):
app = webapp2.WSGIApplication([('/cache/', CacheHandler)])
self.testapp = webtest.TestApp(app)
self.testbed = testbed.Testbed()
self.testbed.activate()
def tearDown(self):
self.testbed.deactivate()
def testCacheHandler(self):
# First define a key and value to be cached.
key = 'answer'
value = '42'
self.testbed.init_memcache_stub()
params = {'key': key, 'value': value}
# Then pass those values to the handler.
response = self.testapp.post('/cache/', params)
# Finally verify that the passed-in values are actually stored in Memcache.
self.assertEqual(value, memcache.get(key))
設定測試架構
您可以視需要設定測試架構。您可以如同 App Engine 的單位測試方法,針對使用 WebTest 的處理常式進行測試。唯一的差別在於您必須確定已安裝 WebTest。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-09-04 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[[["\u003cp\u003eThis guide focuses on integration testing for App Engine applications, particularly emphasizing the testing of request handlers, which are crucial integration points.\u003c/p\u003e\n"],["\u003cp\u003eThe WebTest framework is introduced as a tool to simplify testing WSGI-based applications and request handlers by wrapping them in a test app, allowing easy interaction and environment modification.\u003c/p\u003e\n"],["\u003cp\u003eThe article provides examples of testing a simple "Hello World" handler using WebTest, demonstrating how to make requests and assert on the response's status code, body, and content type.\u003c/p\u003e\n"],["\u003cp\u003eTesting handlers that use App Engine services is covered, highlighting the use of testbed to isolate and manage interactions with services like Memcache, ensuring accurate and controlled testing environments.\u003c/p\u003e\n"],["\u003cp\u003eWebTest allows you to make requests using the get() call, and the return value of this is a response object which you can use to test the status code, body, and content type, among other things.\u003c/p\u003e\n"]]],[],null,["# Handler Testing For Python 2\n\nThe [Local Unit\nTesting for Python](/appengine/docs/legacy/standard/python/tools/localunittesting) article described how to run unit tests for your\napplication. While unit tests are great for testing the separate units of your\ncode, the integration of those code units is what makes your application run---so integration testing is just as important.\n\nFor App Engine applications, request handlers are critical integration\npoints. While a WSGI application routes requests to the right handler, the\nhandler itself processes the request data and generates a response (read more\nabout [Request\nHandlers](/appengine/docs/legacy/standard/python/tools/webapp/requesthandlers)). Request handlers are normal Python objects like any other\nfunction or class, which makes them easy to use in automated tests. But because\na WSGI application wraps them like a shell, we will use a similar shell in our\ntests.\n\nWebTest\n-------\n\nFor our tests, we will utilize the\n[WebTest framework](http://webtest.pythonpaste.org). WebTest is a\nlibrary that gives you a simple interface for testing WSGI-based applications\nand therefore the request handlers. It does so by wrapping a WSGI application\nin a special test app which can then be used for testing. WebTest allows you to\ninteract with your handlers without a full App Engine environment; you can\neasily issue requests and modify the request environment. The responses have a\ntest-friendly interface as well. You don't have to use WebTest, but it sure\nmakes your life a lot easier.\n\nBefore you can start, install WebTest on your local machine or wherever you\nintend to run handler tests. Instructions can be found at\n[http://webtest.pythonpaste.org/#installation](http://webtest.pythonpaste.org/en/latest/index.html#installation)\n\nTesting a Simple \"Hello World\"\nHandler\n--------------------------------------\n\nLet's begin with testing a simple \"Hello World!\" handler that responds to a\nuser request with a plain-text reply. The handle's response is \"Hello World!\"\nand the content type is \"text/plain\": \n\n```python\nimport webapp2\nimport webtest\n\nclass HelloWorldHandler(webapp2.RequestHandler):\n def get(self):\n # Create the handler's response \"Hello World!\" in plain text.\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write('Hello World!')\n```\n\nNext, create the test case and initialize a test application that uses your\nhandler: \n\n```python\n...\nclass AppTest(unittest.TestCase):\n def setUp(self):\n # Create a WSGI application.\n app = webapp2.WSGIApplication([('/', HelloWorldHandler)])\n # Wrap the app with WebTest's TestApp.\n self.testapp = webtest.TestApp(app)\n\n # Test the handler.\n def testHelloWorldHandler(self):\n response = self.testapp.get('/')\n self.assertEqual(response.status_int, 200)\n self.assertEqual(response.normal_body, 'Hello World!')\n self.assertEqual(response.content_type, 'text/plain')\n```\n\nAs you can see, WebTest allows you to make GET requests with a simple get()\ncall (other request methods have similar methods). The return value is a\nresponse object with which you can test the status code, body, content type,\nand much more---check out\nthe [WebTest homepage](http://webtest.pythonpaste.org/) for a\ndetailed description of all the things you can do.\n\nCreating a\nHandler Test that Uses an App Engine Service\n-------------------------------------------------------\n\nNow let's have a look at how to test a handler that uses an App Engine\nservice. This means we must now deal with two components that may affect our\ntests: the handler and the service we are using. As described in\nthe [Local Unit Testing\nfor Python](/appengine/docs/legacy/standard/python/tools/localunittesting) article, the best way to deal with services in tests is to\nuse [testbed](/appengine/docs/legacy/standard/python/tools/localunittesting#intro).\n\nThe following example uses Memcache, but it is the same in principle for\nother services like Datastore or Task Queue.\n\nThe handler we test caches the given key and value. Notice that we parse\nboth values from the request parameters. \n\n```python\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import testbed\nimport webapp2\nimport webtest\n\nclass CacheHandler(webapp2.RequestHandler):\n def post(self):\n key = self.request.get('key')\n value = self.request.get('value')\n memcache.set(key, value)\n```\n\nIn the test, just like before, first create an application and wrap it with\nWebTest. Additionally, activate\na [Testbed](/appengine/docs/legacy/standard/python/tools/localunittesting#intro)\ninstance and take care to deactivate after the test. \n\n```python\n...\nclass AppTest(unittest.TestCase):\n\n def setUp(self):\n app = webapp2.WSGIApplication([('/cache/', CacheHandler)])\n self.testapp = webtest.TestApp(app)\n self.testbed = testbed.Testbed()\n self.testbed.activate()\n\n def tearDown(self):\n self.testbed.deactivate()\n\n def testCacheHandler(self):\n # First define a key and value to be cached.\n key = 'answer'\n value = '42'\n self.testbed.init_memcache_stub()\n params = {'key': key, 'value': value}\n # Then pass those values to the handler.\n response = self.testapp.post('/cache/', params)\n # Finally verify that the passed-in values are actually stored in Memcache.\n self.assertEqual(value, memcache.get(key))\n```\n\nSetting Up a Testing Framework\n------------------------------\n\nYou can set up a testing framework if you like. Tests for handlers that use\nWebTest can be\nexecuted [like\nyour unit tests for App Engine](/appengine/docs/legacy/standard/python/tools/localunittesting#setup). The only difference is that you need to\nmake sure you have WebTest installed."]]