Falcon 框架的 Pytest `client` 夹具
项目描述
Pytest Falcon 客户端
猎鹰框架的Pytestclient夹具。
安装
pip install pytest-falcon-client
设置
插件提供了make_client固定装置,您可以通过将falcon.API实例作为参数传递来按原样使用:
import pytest
from yout_application import create_api
@pytest.fixture
def api():
return create_api()
def test_something(make_client, api):
client = make_client(api)
got = client.get('/your_url/42/')
assert got == {'awesome': 'response'}
为了更简单的使用,您可以定义自己的client夹具:
import pytest
from yout_application import create_api
@pytest.fixture
def client(make_client):
api = create_api()
return make_client(api)
def test_something(client):
got = client.get('/your_url/42/')
assert got == {'awesome': 'response'}
断言示例
获取响应正文为 json 并对状态码进行自动断言
def test_something(client):
got = client.get('/your_url/42/')
assert got == {'some': 'staff'}
以 json 格式获取响应正文并为您自己的状态代码执行自动断言
def test_something(client):
got = client.get('/your_url/42/', expected_statuses=[400, 401])
assert got == {'some': 'stuff'}
按原样获取响应对象并跳过任何自动断言
def test_something(client):
response = client.get('/your_url/42/', as_response=True)
assert response.status_code == 400
assert response.json == {'some': 'stuff'}
每个请求的自定义自动断言
例如,您想断言每个响应都有
Access-Control-Allow-Origin带有 value 的标头falconframework.org。你可以用这样的自定义来做到这ApiTestClient一点:
导入 pytest
从 pytest_falcon_client 导入 ApiTestClient
从 yout_application 导入 create_api
class CustomApiTestClient ( ApiTestClient ):
def response_assertions ( self , response ):
# 你可以在这里为每个请求做任何自动断言
assert response 。标头[
'Access-Control-Allow-Origin' ] == 'falconframework.org'
@pytest 。fixture
def client ():
api = create_api ()
return CustomApiTestClient ( api )
def test_something(client):
response = client.get('/your_url/42/', as_response=True)
assert response.status_code == 400
assert response.json == {'some': 'stuff'}
模拟一些默认客户端行为
如果您的服务依赖于一些默认的客户端行为,例如标头、cookie 或其他东西,该怎么办?您可以使用 custom 为每个请求设置此行为ApiTestClient:
import pytest
from pytest_falcon_client import ApiTestClient
from yout_application import create_api
class CustomApiTestClient(ApiTestClient):
def prepare_request(self, method, expected_statuses, *args, **kwargs):
kwargs['headers'] = {'Origin': 'falconframework.org'} # add `ORIGIN` header to every request
return args, kwargs, expected_statuses # should returns all of this
@pytest.fixture
def client():
api = create_api()
return CustomApiTestClient(api)
def test_something(client):
got = client.get('/your_url/42/', as_response=True)
assert got == {'some': 'stuff'}
在 中查看更多示例tests。