20. 测试模式
你的鼓励是我前进的动力,请为我点个赞吧!
Sanic可以的路由可以使用基于iohttp的库开发的test_client对象。test_client对象具有get、post、put、delete、patch、headhe和option方法,一个简单的例子如下所示:
# Import the Sanic app, usually created with Sanic(__name__)
from external_server import app
def test_index_returns_200():
request, response = app.test_client.get('/')
assert response.status == 200
def test_index_put_not_allowed():
request, response = app.test_client.put('/')
assert response.status == 405
开发者使用test-client时iohttp将会运行在127.0.0.1:42101的地址,可以使用开发者可以使用aihttp进行测试:
test_client可以接受如下参数:
参数 | 说明 |
---|---|
uri | 字符串类行的请求路由(默认值为“/”) |
gather_request | 是否返回request,如果为true设置为返回值为(request,response),如果为False将会设置返回response。 |
server_kwargs | 测试请求前,传递字典参数到app.run中 |
debug | 运行时是否开启调试模式(默认False) |
函数可以执行使用*request_arg或者**request_kwargs获取参数,可以直接将参数传递过去。
使用GET方式传递参数,具体示例如下所示:
def test_get_request_includes_data():
params = {'key1': 'value1', 'key2': 'value2'}
request, response = app.test_client.get('/', params=params)
assert request.args.get('key1') == 'value1'
json数据的测试:
def test_post_json_request_includes_data():
data = {'key1': 'value1', 'key2': 'value2'}
request, response = app.test_client.post('/', data=json.dumps(data))
assert request.json.get('key1') == 'value1'
(1)sanic的测试插件pytest-sanic
这是一个测试插件,能帮助大家测试异步,具体示例如下所示:
async def test_sanic_db_find_by_id(app):
"""
Let's assume that, in db we have,
{
"id": "123",
"name": "Kobe Bryant",
"team": "Lakers",
}
"""
doc = await app.db["players"].find_by_id("123")
assert doc.name == "Kobe Bryant"
assert doc.team == "Lakers"
@pytest.yield_fixture
def app():
app = Sanic("test_sanic_app")
@app.route("/test_get", methods=['GET'])
async def test_get(request):
return response.json({"GET": True})
@app.route("/test_post", methods=['POST'])
async def test_post(request):
return response.json({"POST": True})
yield app
@pytest.fixture
def test_cli(loop, app, test_client):
return loop.run_until_complete(test_client(app, protocol=WebSocketProtocol))
async def test_fixture_test_client_get(test_cli):
"""
GET request
"""
resp = await test_cli.get('/test_get')
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {"GET": True}
async def test_fixture_test_client_post(test_cli):
"""
POST request
"""
resp = await test_cli.post('/test_post')
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {"POST": True}