Python Falcon - 測試



Falcon 的測試模組是一個用於 Falcon 應用的功能測試框架。它包含各種測試類和實用函式來支援功能測試。該測試框架同時支援unittestpytest

我們將使用以下指令碼 (myapp.py) 來演示測試功能。它包含一個HelloResource類,其中有一個on_get()響應器,它渲染一個“Hello World”的JSON響應。create()函式返回添加了註冊到'/' URL 的路由的 Falcon 應用物件。

from waitress import serve
import falcon
import json
class HelloResource:
   def on_get(self, req, resp):
      """Handles GET requests"""
      resp.text=json.dumps({"message":"Hello World"})

   # This is the default status
   resp.status = falcon.HTTP_200

   # Default is JSON, so override
   resp.content_type = falcon.MEDIA_JSON 
def create():
   app = falcon.App()
   hello = HelloResource()
   app.add_route('/', hello)
   return app
app=create()
if __name__ == '__main__':
   serve(app, host='0.0.0.0', port=8000)

使用 unittest

testing.TestCase 擴充套件了 unittest 以便於對使用 Falcon 編寫的 WSGI/ASGI 應用程式進行功能測試。我們需要繼承這個基類並編寫測試。

TestCase 子類中的測試函式名稱為simulate_*(),其中'*'代表 HTTP 方法,例如 GET、POST 等。這意味著,我們必須獲取simulate_get()函式的結果,並透過斷言函式將其與預期結果進行比較。

simulate_*()函式接收兩個引數。

simulate_*(app, route)

以下是test-myapp.py的程式碼。它執行simulate_get()函式,並將其結果與預期結果進行斷言,並指示測試是否失敗或透過。

from falcon import testing
import myapp
class MyTestCase(testing.TestCase):
   def setUp(self):
      super(MyTestCase, self).setUp()
      self.app = myapp.create()
class TestMyApp(MyTestCase):
   def test_get_message(self):
      doc = {'message': 'Hello world!'}
      result = self.simulate_get('/')
      self.assertEqual(result.json, doc)
if '__name__'=='__main__':
   unittest.main()

使用以下命令執行上述測試:

python -m unittest test-myapp.py
F
==============================================================
FAIL: test_get_message (test-myapp.TestMyApp)
--------------------------------------------------------------
Traceback (most recent call last):
   File "E:\falconenv\test-myapp.py", line 17, in test_get_message
   self.assertEqual(result.json, doc)
AssertionError: {'message': 'Hello World'} != {'message':
'Hello world!'}
- {'message': 'Hello World'}
? ^
+ {'message': 'Hello world!'}
? ^ +
--------------------------------------------------------------
Ran 1 test in 0.019s
FAILED (failures=1)

使用 Pytest

要使用 PyTest 框架進行測試,需要使用 PIP 實用程式安裝它。

pip3 install pytest

要執行test函式,我們需要一個testing.TestClient類的物件。它模擬了 WSGI 和 ASGI 應用程式的請求。這個物件首先透過將 Falcon 應用程式物件作為引數來獲得。

我們執行simulate_*()函式,並將其結果與預期輸出進行斷言,以確定測試是否失敗或透過。在這兩個示例中,測試都因為“Hello World”訊息中“W”的大小寫不同而失敗。響應器返回的是大寫“W”,而測試函式使用的是小寫“w”。

from falcon import testing
import pytest
import myapp
@pytest.fixture()
def client():
   return testing.TestClient(myapp.create())
def test_get_message(client):
   doc = {'message': 'Hello world!'}
   result = client.simulate_get('/')
   assert result.json == doc

使用以下命令執行上述測試:

pytest test-myapp.py –v
=========== test session starts ==========================
platform win32 -- Python 3.8.6, pytest-7.1.2, pluggy-1.0.0 --
e:\falconenv\scripts\python.exe
cachedir: .pytest_cache
rootdir: E:\falconenv
plugins: anyio-3.5.0
collected 1 item
test-myapp.py::test_get_message FAILED
[100%]
==================== FAILURES =======================
_____________________________________________________
test_get_message
_____________________________________________________
client = <falcon.testing.client.TestClient object at 0x0000000003EAA6A0>
def test_get_message(client):
   doc = {'message': 'Hello world!'}
   result = client.simulate_get('/')
> assert result.json == doc
E AssertionError: assert {'message': 'Hello World'} ==
{'message': 'Hello world!'}
E Differing items:
E {'message': 'Hello World'} != {'message': 'Hello world!'}
E Full diff:
E - {'message': 'Hello world!'}
E ? ^ -
E + {'message': 'Hello World'}
E ? ^
test-myapp.py:42: AssertionError
============ short test summary info ==================
FAILED test-myapp.py::test_get_message - AssertionError:
assert {'message': 'Hello World'} == {'message': 'Hello
world!'}
============ 1 failed in 4.11s ========================
廣告
© . All rights reserved.