测试 Flask 应用

Flask 提供了用于测试应用的实用工具。本文档介绍了在测试中处理应用不同部分的技术。

我们将使用 pytest 框架来设置和运行我们的测试。

$ pip install pytest

教程 介绍了如何为示例 Flaskr 博客应用编写 100% 覆盖率的测试。有关应用特定测试的详细说明,请参阅关于测试的教程

识别测试

测试通常位于 tests 文件夹中。测试是函数,其名称以 test_ 开头,位于 Python 模块中,模块名称以 test_ 开头。测试也可以进一步分组到以 Test 开头的类中。

可能很难知道要测试什么。通常,尝试测试您编写的代码,而不是您使用的库的代码,因为它们已经过测试。尝试将复杂的行为提取为单独的函数进行单独测试。

Fixture

Pytest fixture 允许编写可在测试中重用的代码片段。一个简单的 fixture 返回一个值,但 fixture 也可以执行设置、产生一个值,然后执行拆卸。应用程序、测试客户端和 CLI 运行器的 fixture 如下所示,它们可以放在 tests/conftest.py 中。

如果您正在使用应用工厂,请定义一个 app fixture 来创建和配置应用实例。您可以在 yield 之前和之后添加代码来设置和拆卸其他资源,例如创建和清除数据库。

如果您不使用工厂,您已经有一个可以直接导入和配置的应用对象。您仍然可以使用 app fixture 来设置和拆卸资源。

import pytest
from my_project import create_app

@pytest.fixture()
def app():
    app = create_app()
    app.config.update({
        "TESTING": True,
    })

    # other setup can go here

    yield app

    # clean up / reset resources here


@pytest.fixture()
def client(app):
    return app.test_client()


@pytest.fixture()
def runner(app):
    return app.test_cli_runner()

使用测试客户端发送请求

测试客户端向应用程序发出请求,而无需运行实时服务器。Flask 的客户端扩展了 Werkzeug 的客户端,有关更多信息,请参阅这些文档。

client 具有与常见 HTTP 请求方法匹配的方法,例如 client.get()client.post()。它们接受许多参数来构建请求;您可以在 EnvironBuilder 中找到完整的文档。通常您会使用 pathquery_stringheadersdatajson

要发出请求,请使用请求应使用的方法和要测试的路由路径来调用。将返回一个 TestResponse 以检查响应数据。它具有响应对象的所有常用属性。您通常会查看 response.data,它是视图返回的字节。如果您想使用文本,Werkzeug 2.1 提供了 response.text,或者使用 response.get_data(as_text=True)

def test_request_example(client):
    response = client.get("/posts")
    assert b"<h2>Hello, World!</h2>" in response.data

传递一个字典 query_string={"key": "value", ...} 以在查询字符串中设置参数(在 URL 中的 ? 之后)。传递一个字典 headers={} 以设置请求头。

要在 POST 或 PUT 请求中发送请求正文,请将值传递给 data。如果传递原始字节,则使用该确切的正文。通常,您将传递一个字典以设置表单数据。

表单数据

要发送表单数据,请将字典传递给 dataContent-Type 标头将自动设置为 multipart/form-dataapplication/x-www-form-urlencoded

如果一个值是为读取字节 ("rb" 模式) 打开的文件对象,它将被视为上传的文件。要更改检测到的文件名和内容类型,请传递一个 (file, filename, content_type) 元组。文件对象将在发出请求后关闭,因此它们不需要使用常用的 with open() as f: 模式。

将文件存储在 tests/resources 文件夹中可能很有用,然后使用 pathlib.Path 获取相对于当前测试文件的文件。

from pathlib import Path

# get the resources folder in the tests folder
resources = Path(__file__).parent / "resources"

def test_edit_user(client):
    response = client.post("/user/2/edit", data={
        "name": "Flask",
        "theme": "dark",
        "picture": (resources / "picture.png").open("rb"),
    })
    assert response.status_code == 200

JSON 数据

要发送 JSON 数据,请将对象传递给 jsonContent-Type 标头将自动设置为 application/json

同样,如果响应包含 JSON 数据,则 response.json 属性将包含反序列化的对象。

def test_json_data(client):
    response = client.post("/graphql", json={
        "query": """
            query User($id: String!) {
                user(id: $id) {
                    name
                    theme
                    picture_url
                }
            }
        """,
        variables={"id": 2},
    })
    assert response.json["data"]["user"]["name"] == "Flask"

跟踪重定向

默认情况下,如果响应是重定向,客户端不会发出额外的请求。通过将 follow_redirects=True 传递给请求方法,客户端将继续发出请求,直到返回非重定向响应。

TestResponse.history 是导致最终响应的响应元组。每个响应都有一个 request 属性,该属性记录生成该响应的请求。

def test_logout_redirect(client):
    response = client.get("/logout", follow_redirects=True)
    # Check that there was one redirect response.
    assert len(response.history) == 1
    # Check that the second request was to the index page.
    assert response.request.path == "/index"

访问和修改会话

要访问 Flask 的上下文变量,主要是 session,请在 with 语句中使用客户端。应用和请求上下文将在发出请求保持活动状态,直到 with 代码块结束。

from flask import session

def test_access_session(client):
    with client:
        client.post("/auth/login", data={"username": "flask"})
        # session is still accessible
        assert session["user_id"] == 1

    # session is no longer accessible

如果您想在发出请求之前访问或设置会话中的值,请在 with 语句中使用客户端的 session_transaction() 方法。它返回一个会话对象,并在代码块结束后保存会话。

from flask import session

def test_modify_session(client):
    with client.session_transaction() as session:
        # set a user id without going through the login route
        session["user_id"] = 1

    # session is saved now

    response = client.get("/users/me")
    assert response.json["username"] == "flask"

使用 CLI 运行器运行命令

Flask 提供了 test_cli_runner() 来创建一个 FlaskCliRunner,它在隔离环境中运行 CLI 命令,并将输出捕获到 Result 对象中。Flask 的运行器扩展了 Click 的运行器,有关更多信息,请参阅这些文档。

使用运行器的 invoke() 方法以与从命令行使用 flask 命令相同的方式调用命令。

import click

@app.cli.command("hello")
@click.option("--name", default="World")
def hello_command(name):
    click.echo(f"Hello, {name}!")

def test_hello_command(runner):
    result = runner.invoke(args="hello")
    assert "World" in result.output

    result = runner.invoke(args=["hello", "--name", "Flask"])
    assert "Flask" in result.output

依赖于活动上下文的测试

您可能有从视图或命令调用的函数,这些函数期望有一个活动的应用上下文请求上下文,因为它们访问 requestsessioncurrent_app。与其通过发出请求或调用命令来测试它们,不如直接创建和激活上下文。

使用 with app.app_context() 来推送应用上下文。例如,数据库扩展通常需要一个活动的应用上下文来执行查询。

def test_db_post_model(app):
    with app.app_context():
        post = db.session.query(Post).get(1)

使用 with app.test_request_context() 来推送请求上下文。它接受与测试客户端的请求方法相同的参数。

def test_validate_user_edit(app):
    with app.test_request_context(
        "/user/2/edit", method="POST", data={"name": ""}
    ):
        # call a function that accesses `request`
        messages = validate_edit_user()

    assert messages["name"][0] == "Name cannot be empty."

创建测试请求上下文不会运行任何 Flask 调度代码,因此不会调用 before_request 函数。如果您需要调用这些函数,通常最好改为发出完整请求。但是,可以手动调用它们。

def test_auth_token(app):
    with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}):
        app.preprocess_request()
        assert g.user.name == "Flask"