 
- Python Falcon教程
- Python Falcon - 主页
- Python Falcon - 简介
- Python Falcon - 环境设置
- Python Falcon - WSGI 与 ASGI
- Python Falcon - Hello World(WSGI)
- Python Falcon - 女服务员
- Python Falcon - ASGI
- 蟒蛇Falcon - Uvicorn
- Python Falcon - API 测试工具
- 请求与响应
- Python Falcon - 资源类
- Python Falcon - 应用程序类
- Python Falcon - 路由
- Falcon - 后缀响应者
- Python Falcon - 检查模块
- Python Falcon - Jinja2 模板
- Python Falcon - cookie
- Python Falcon - 状态代码
- Python Falcon - 错误处理
- Python Falcon - 钩子
- Python Falcon - 中间件
- Python Falcon - CORS
- Python Falcon - Websocket
- Python Falcon - Sqlalchemy 模型
- Python Falcon - 测试
- Python Falcon - 部署
- Python Falcon 有用资源
- Python Falcon - 快速指南
- Python Falcon - 有用的资源
- Python Falcon - 讨论
Python Falcon - 测试
Falcon 的测试模块是 Falcon 应用程序的功能测试框架。它包含各种测试类和实用函数来支持功能测试。测试框架支持unittest和pytest。
我们将使用以下脚本(myapp.py)来演示测试功能。它包含一个HelloResource类,该类带有一个on_get()响应程序,该响应程序呈现 Hello World 的 JSON 响应。create ()函数返回 Falcon 的 Application 对象,该对象添加了通过“/” URL注册的路由。
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)
使用单元测试
test.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
要运行测试函数,我们需要一个testing.TestClient类的对象。它模拟 WSGI 和 ASGI 应用程序的请求。该对象首先通过将 Falcon 应用程序对象作为参数来获得。
我们运行simulate_*()函数并用预期输出断言其结果来决定测试是失败还是通过。在这两个示例中,测试都失败,因为 Hello World 消息中“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 ========================