06:WebTestによる機能テスト(06: Functional Testing with WebTest)

「webtest」を使用してエンドツーエンドのフルスタックテストを作成します。

背景(Background)

単体テストは、テストドリブン開発(TDD)の一般的なアプローチです。しかしWebアプリケーションでは、Webサイトのテンプレートやアプリ全体が提供される品質の重要な部分です。これらをテストする方法が欲しいです。

WebTest は機能テストを行うPythonパッケージです。WebTestを使用するとWSGIアプリケーションに対する完全なHTTPリクエストをシミュレートしたテストを作成して応答内の情報をテストします。

目標(Objectives)

  • 返却されたHTMLの内容をチェックするテストを書く。

手順(Steps)

  1. 最初に前の手順の結果をコピーし、パッケージwebtestをインストールします:

    $ cd ..; cp -r unit_testing functional_testing; cd functional_testing
    $ $VENV/bin/pip install -e .
    $ $VENV/bin/pip install webtest
    
  2. 「functional_testing/tutorial/tests.py」を機能テストを含むように拡張しましょう:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    import unittest
    
    from pyramid import testing
    
    
    class TutorialViewTests(unittest.TestCase):
        def setUp(self):
            self.config = testing.setUp()
    
        def tearDown(self):
            testing.tearDown()
    
        def test_hello_world(self):
            from tutorial import hello_world
    
            request = testing.DummyRequest()
            response = hello_world(request)
            self.assertEqual(response.status_code, 200)
    
    
    class TutorialFunctionalTests(unittest.TestCase):
        def setUp(self):
            from tutorial import main
            app = main({})
            from webtest import TestApp
    
            self.testapp = TestApp(app)
    
        def test_hello_world(self):
            res = self.testapp.get('/', status=200)
            self.assertIn(b'<h1>Hello World!</h1>', res.body)
    

    このファイルが実行可能でないこと、または「pytest」がテストが含まれていない可能性があることを確認してください。

  3. テストをしてください:

    $ $VENV/bin/py.test tutorial/tests.py -q
    ..
    2 passed in 0.25 seconds
    

分析(Analysis)

現在、私たちは探していたエンドツーエンドのテストを持っています。WebTestを使用すると、同じ出力で報告される機能テストを使用して、既存の「pytest」ベースのテスト手法を単純に拡張できます。

エクストラクレジット(Extra credit)

  1. なぜ私たちの機能テスト b'' が使用されますか?