测试

Sanic端点可以使用 test_client object, which depends on an additional package: httpx 库,它实现了一个映射 requests 类库。

这个 test_client 暴露 getpostputdeletepatchheadoptions 方法来运行应用程序。一个简单的例子(使用pytest)如下:

# 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 方法,Sanic应用程序在 127.0.0.1:42101 然后对应用程序执行测试请求,使用 httpx .

这个 test_client 方法接受以下参数和关键字参数:

  • uri (default `'/'`) A string representing the URI to test.

  • gather_request (default `True`) A boolean which determines whether the original request will be returned by the function. If set to True, the return value is a tuple of (request, response), if False only the response is returned.

  • server_kwargs (default `{}`) a dict of additional arguments to pass into app.run before the test request is run.

  • debug (default `False`) A boolean which determines whether to run the server in debug mode.

该函数进一步采用 *request_args**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 POST请求提供数据:

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'

有关的可用参数的详细信息 httpx can be found [in the documentation for httpx .

注解

每当其中一个测试客户端运行时,您都可以测试应用程序实例以确定它是否处于测试模式: app.test_mode .

此外,Sanic还有一个异步测试客户端。不同之处在于,异步客户机将不支持应用程序的实例,而是使用ASGI访问它内部。所有的监听器和中间件仍然被执行。

@pytest.mark.asyncio
async def test_index_returns_200():
    request, response = await app.asgi_client.put('/')
    assert response.status == 200

注解

每当其中一个测试客户端运行时,您都可以测试应用程序实例以确定它是否处于测试模式: app.test_mode .

使用随机端口

如果需要使用内核选择的空闲未驱动端口而不是默认的 SanicTestClient ,可以通过指定 port=None . 在大多数系统上,端口将在1024到65535之间。

# Import the Sanic app, usually created with Sanic(__name__)
from external_server import app
from sanic.testing import SanicTestClient

def test_index_returns_200():
    request, response = SanicTestClient(app, port=None).get('/')
    assert response.status == 200

pytest-sanic

pytest-sanic 是一个pytest插件,它帮助您异步测试代码。只是写一些测试,比如,

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-sanic 还提供一些有用的fixture,如loop、unused_port、test_server、test_client。

@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))


#########
# Tests #
#########

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}