Python 2.7 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Python 2.7 アプリケーションをデプロイできなくなります。既存の Python 2.7 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Python に移行することをおすすめします。
Python 2 でのハンドラのテスト
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
Python のローカル ユニットテストの記事で、アプリケーションのユニットテストの実行方法を説明しました。ユニットテストではコードのユニットを個別にテストしますが、統合テストではアプリケーション全体をテストします。統合テストはユニットテストと同様に重要です。
App Engine アプリケーションでは、リクエスト ハンドラが重要な統合ポイントになります。WSGI アプリケーションが適切なハンドラにリクエストを転送する一方、ハンドラはリクエスト データを処理し、レスポンスを生成します(リクエスト ハンドラを参照)。リクエスト ハンドラは通常の Python オブジェクトです。他の関数やクラスと同様に、自動的なテストで簡単に利用できます。ただし、シェルのように WSGI アプリケーションでラッピングされるため、このテストでも類似したシェルを使用します。
WebTest
このテストでは、WebTest フレームワークを使用します。WebTest は、WSGI ベースのアプリケーションやリクエスト ハンドラのテストを行う簡単なインターフェースを提供するライブラリです。テストを行うには、WSGI アプリケーションを特別なテストアプリにラッピングします。WebTest を使用すると、完全な App Engine 環境がなくてもハンドラを操作できます。リクエストの送信やリクエスト環境の変更を簡単に行うことができます。レスポンスには、テストに役立つインターフェースも含まれます。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 サービスを使用するハンドラのテストを行いましょう。このテストでは、ハンドラとサービスの 2 つのコンポーネントを使用します。Python のローカル単体テストの記事にあるように、テストでサービスを扱うには testbed を使用するのが最適な方法です。
次の例では Memcache を使用していますが、基本的にはデータストアやタスクキューなどの他のサービスの場合も同様です。
テスト対象のハンドラは、特定のキーと値をキャッシュします。ここでは、リクエスト パラメータの両方の値を解析しています。
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))
テスト用フレームワークの設定
必要に応じてテスト用フレームワークを設定できます。WebTest を使用するハンドラのテストは、App Engine のユニットテストと同様に実行できます。ただし、WebTest がインストールされている必要があります。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-09-04 UTC。
[[["わかりやすい","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 UTC。"],[[["\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."]]