Hello! 欢迎来到小浪云!


如何在 Flask 中执行单元测试


avatar
小浪云 2025-01-16 65

测试对于软件开发过程至关重要,可确保代码按预期运行且无缺陷。在Python中,pytest是一种流行的测试框架,与标准单元测试模块相比,它具有多种优势,标准单元测试模块是内置的Python测试框架,并且是标准库的一部分。 pytest 包括更简单的语法、更好的输出、强大的装置和丰富的插件生态系统。本教程将指导您设置 flask 应用程序、集成 pytest 固定装置以及使用 p

如何在 Flask 中执行单元测试

第 1 步 – 设置环境

Ubuntu 24.04 默认情况下附带 Python 3。打开终端并运行 使用以下命令来仔细检查 Python 3 安装:

root@Ubuntu:~# python3 --versionPython 3.12.3

如果 Python 3 已经安装在你的机器上,上面的命令将 返回 Python 3 安装的当前版本。如果不是 安装完毕后,您可以运行以下命令并获取Python 3 安装:

root@ubuntu:~# sudo apt install python3

接下来,您需要在系统上安装 pip 软件包安装程序:

root@ubuntu:~# sudo apt install python3-pip

安装 pip 后,让我们安装 Flask。

第 2 步 – 创建 Flask应用程序

让我们从创建一个简单的 Flask 应用程序开始。为您的项目创建一个新目录并导航到其中:

root@ubuntu:~# mkdir flask_testing_approot@ubuntu:~# cd flask_testing_app

现在,让我们创建并激活一个虚拟环境来管理依赖项:

root@ubuntu:~# python3 -m venv venvroot@ubuntu:~# source venv/bin/activate

使用以下命令安装 Flask pip:

root@ubuntu:~# pip install Flask

现在,让我们创建一个简单的 Flask 应用程序。创建一个名为 app.py 的新文件并添加以下代码:

app.py
from flask import Flask, jsonify  app = Flask(__name__)@app.route('/')def home():     return jsonify(message="Hello, Flask!")@app.route('/about')def about():     return jsonify(message="This is the About page")@app.route('/multiply/<int:x>/<int:y>')def multiply(x, y):     result = x * y    return jsonify(result=result)if __name__ == '__main__':     app.run(debug=True)

此应用程序有三个路由:

  • /:返回一个简单的“Hello, Flask!”
  • /about:返回一个简单的“这是关于页面”消息。
  • /multiply//:将两个整数相乘并返回result.

要运行应用程序,请执行以下命令命令:

root@ubuntu:~# flask run
output* Serving Flask app "app" (lazy loading)  * Environment: production    WARNING: This is a development server. Do not use it in a production deployment.    Use a production WSGI server instead.  * Debug mode: on  * Running on http://127.0.0.1:5000/ (Press CTRL C to quit)

从上面的输出中,您可以注意到服务器正在 http://127.0.0.1 上运行并侦听端口 5000。打开另一个Ubuntu控制台并一一执行以下cURL命令:

  • GET:curl http://127.0.0.1:5000/:5000/
  • GET:卷曲http://127.0.0.1:5000/about:5000/约
  • GET:卷曲http://127.0.0.1:5000/multiply/10/20:5000/乘/10/20

让我们了解一下这些 GET 请求是什么做:

  1. 卷曲http://127.0.0.1:5000/::5000/: 这将向 Flask 应用程序的根路由(‘/’)发送 GET 请求。服务器响应一个包含消息“Hello, Flask!”的 JSON 对象,演示了我们的主路由的基本功能。

  2. curl http://127.0.0.1:5000/about::5000/about: 这将向 /about 路由发送 GET 请求。服务器使用包含消息“这是关于页面”的 JSON 对象进行响应。这表明我们的路线运行正常。

  3. curl http://127.0.0.1:5000/multiply/10/20::5000/multiply/10/20: 这会向 /multiply 路由发送一个 GET 请求,其中包含两个参数:10 和 20。服务器将这些参数相乘 数字并以包含结果 (200) 的 JSON 对象进行响应。 这说明我们的multiply路由可以正确处理URL 参数并执行计算。

这些 GET 请求允许我们与 Flask 交互 应用程序的 API 端点,检索信息或触发 在服务器上执行操作而不修改任何数据。它们对于 获取数据、测试端点功能并验证我们的 路由按预期响应。

让我们看看其中的每个 GET 请求操作:

root@ubuntu:~# curl root@ubuntu:~# curl http://127.0.0.1:5000/:5000/
Output{"message":"Hello, Flask!"}
root@ubuntu: 〜#卷曲root@ubuntu:~# curl http://127.0.0.1:5000/about:500 0/关于
Output{"message":"This is the About page"}
root@ubuntu:~# curl root@ubuntu:~# curl http://127.0.0.1:5000/multiply/10/20:5000/multiply/10/20
Output{"result":200}

步骤3 – 安装 pytest 并编写您的第一个测试

现在您已经有了一个基本的 Flask 应用程序,让我们安装 pytest 并编写一些单元测试。

使用 pip 安装 pytest:

root@ubuntu:~# pip install pytest

创建一个测试目录来存储您的测试files:

root@ubuntu:~# mkdir tests

现在,让我们创建一个名为 test_app.py 的新文件并添加以下代码:

test_app.py
# Import sys module for modifying Python's runtime environmentimport sys# Import os module for interacting with the operating systemimport os# Add the parent directory to sys.pathsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# Import the Flask app instance from the main app filefrom app import app  # Import pytest for writing and running testsimport pytest@pytest.fixturedef client():     """A test client for the app."""     with app.test_client() as client:         yield clientdef test_home(client):     """Test the home route."""     response = client.get('/')     assert response.status_code == 200     assert response.json == {"message": "Hello, Flask!"}def test_about(client):     """Test the about route."""     response = client.get('/about')     assert response.status_code == 200     assert response.json == {"message": "This is the About page"}def test_multiply(client):     """Test the multiply route with valid input."""     response = client.get('/multiply/3/4')     assert response.status_code == 200     assert response.json == {"result": 12}def test_multiply_invalid_input(client):     """Test the multiply route with invalid input."""     response = client.get('/multiply/three/four')     assert response.status_code == 404def test_non_existent_route(client):     """Test for a non-existent route."""     response = client.get('/non-existent')     assert response.status_code == 404

我们来分解一下这个测试中的功能文件:

  1. @pytest.fixture def client(): 这是一个 pytest 夹具,为我们的 Flask 应用程序创建一个测试客户端。它使用 app.test_client() 方法创建一个客户端,该客户端可以向我们的应用程序发送请求,而无需运行实际的服务器。 Yield 语句允许客户端在测试中使用,然后在每次测试后正确关闭。

  2. def test_home(client): 此函数测试我们应用程序的主路由 (/)。它发送 使用测试客户端向路由发出 GET 请求,然后断言 响应状态代码为 200(正常)并且 JSON 响应与 预期消息。

  3. def test_about(client): 与test_home类似,该函数测试about路由(/about)。它检查 200 状态代码并验证 JSON 响应内容。

  4. def test_multiply(client): 此函数使用有效输入 (/multiply/3/4) 测试乘法路由。它检查状态代码是否为 200 并且 JSON 响应是否包含正确的乘法结果。

  5. def test_multiply_invalid_input(client): 此函数测试具有无效输入的乘法路径(乘法/三/四)。 它检查状态代码是否为 404(未找到),这是 当路由无法匹配字符串输入时的预期行为 必需的整数参数。

  6. def test_non_existent_route(client): 该函数测试当访问不存在的路由时应用程序的行为。它向 /non-existent 发送 GET 请求, 我们的 Flask 应用程序中没有定义它。测试断言 响应状态代码为 404(未找到),确保我们的应用程序正确 处理对未定义路由的请求。

这些测试涵盖了 Flask 应用程序的基本功能,确保 每条路线都能正确响应有效输入,并且乘法 路由适当地处理无效输入。通过使用 pytest,我们可以轻松运行这些测试来验证我们的应用程序是否按预期工作。

第 4 步 – 运行测试

要运行测试,请执行以下命令:

root@ubuntu:~# pytest

默认情况下,pytest发现过程将递归扫描当前文件夹及其子文件夹对于名称以“test_”开头或以“_test”结尾的文件。然后执行位于这些文件中的测试。您应该看到类似以下内容的输出:

Outputplatform Linux -- Python 3.12.3, pytest-8.3.2, pluggy-1.5.0 rootdir: /home/user/flask_testing_app collected 5 items                                                                                                                  tests/test_app.py ....                                                                                                     [100%]======================================================= 5 passed in 0.19s ========================================================

这表明所有测试均已成功通过。

第 5 步:在 pytest 中使用 Fixtures

夹具是用于提供数据或资源的函数 测试。它们可用于设置和拆除测试环境、加载 数据,或执行其他设置任务。在 pytest 中,装置是使用 @pytest.fixture 装饰器定义的。

以下是如何增强现有装置。更新客户端固定装置以使用安装和拆卸逻辑:

test_app.py
@pytest.fixturedef client():     """Set up a test client for the app with setup and teardown logic."""     print("nSetting up the test client")     with app.test_client() as client:         yield client  # This is where the testing happens     print("Tearing down the test client")def test_home(client):     """Test the home route."""     response = client.get('/')     assert response.status_code == 200     assert response.json == {"message": "Hello, Flask!"}def test_about(client):     """Test the about route."""     response = client.get('/about')     assert response.status_code == 200     assert response.json == {"message": "This is the About page"}def test_multiply(client):     """Test the multiply route with valid input."""     response = client.get('/multiply/3/4')     assert response.status_code == 200     assert response.json == {"result": 12}def test_multiply_invalid_input(client):     """Test the multiply route with invalid input."""     response = client.get('/multiply/three/four')     assert response.status_code == 404def test_non_existent_route(client):     """Test for a non-existent route."""     response = client.get('/non-existent')     assert response.status_code == 404

这个 setup 添加了打印语句来演示安装和拆卸 测试输出中的阶段。这些可以替换为实际资源 如果需要的话,管理代码。

让我们尝试再次运行测试:

root@ubuntu:~# pytest -vs

-v 标志增加了详细程度,而 -s 标志允许打印语句将显示在控制台输出中。

您应该看到以下内容输出:

Outputplatform linux -- Python 3.12.3, pytest-8.3.2, pluggy-1.5.0 rootdir: /home/user/flask_testing_app  cachedir: .pytest_cache        collected 5 items                                                                                            tests/test_app.py::test_home  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_about  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_multiply  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_multiply_invalid_input  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_non_existent_route  Setting up the test client PASSED Tearing down the test client============================================ 5 passed in 0.35s =============================================

第 6 步:添加失败测试用例

让我们向现有测试文件添加一个失败测试用例。修改 test_app.py 文件并在失败的测试用例末尾添加以下函数以获得不正确的结果:

test_app.py
def test_multiply_edge_cases(client):     """Test the multiply route with edge cases to demonstrate failing tests."""     # Test with zero     response = client.get('/multiply/0/5')     assert response.status_code == 200     assert response.json == {"result": 0}      # Test with large numbers (this might fail if not handled properly)     response = client.get('/multiply/1000000/1000000')     assert response.status_code == 200     assert response.json == {"result": 1000000000000}      # Intentional failing test: incorrect result     response = client.get('/multiply/2/3')     assert response.status_code == 200     assert response.json == {"result": 7}, "This test should fail to demonstrate a failing case"

让我们休息一下分析 test_multiply_edge_cases 函数并解释每个部分的含义执行:

  1. 使用零进行测试:此测试检查乘法函数是否正确处理 乘以零。我们期望相乘时结果为0 任意数为零。这是一个需要测试的重要边缘情况,因为一些 实现可能存在零乘法问题。

  2. 大数测试:此测试验证乘法函数是否可以处理大数 没有溢出或精度问题。我们乘以二百万 值,预计结果为一万亿。这项测试至关重要,因为 它检查函数能力的上限。请注意,这 如果服务器的实现不能处理大量数据,则可能会失败 正确地,这可能表明需要大量的库或 不同的数据类型

  3. 故意失败测试:此测试被故意设置为失败。它检查 2 * 3 是否等于 7, 这是不正确的。该测试旨在演示失败的测试如何 查看测试输出。这有助于理解如何识别 并调试失败的测试,这是测试驱动的一项基本技能 开发和调试过程。

通过包含这些边缘情况和故意失败,您可以 不仅测试多重路由的基本功能,还测试 极端条件下的行为及其错误报告 能力。这种测试方法有助于确保稳健性和 我们应用程序的可靠性。

让我们尝试再次运行测试:

root@ubuntu:~# pytest -vs

您应该看到以下输出:

Outputplatform linux -- Python 3.12.3, pytest-8.3.2, pluggy-1.5.0 rootdir: /home/user/flask_testing_app  cachedir: .pytest_cache          collected 6 items                                                                                                                             tests/test_app.py::test_home  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_about  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_multiply  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_multiply_invalid_input  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_non_existent_route  Setting up the test client PASSED Tearing down the test client  tests/test_app.py::test_multiply_edge_cases  Setting up the test client FAILED Tearing down the test client================================================================= FAILURES ==================================================================_________________________________________________________ test_multiply_edge_cases __________________________________________________________  client = <FlaskClient <Flask 'app'>>      def test_multiply_edge_cases(client):        """Test the multiply route with edge cases to demonstrate failing tests."""        # Test with zero         response = client.get('/multiply/0/5')         assert response.status_code == 200         assert response.json == {"result": 0}              # Test with large numbers (this might fail if not handled properly)         response = client.get('/multiply/1000000/1000000')         assert response.status_code == 200         assert response.json == {"result": 1000000000000}              # Intentional failing test: incorrect result         response = client.get('/multiply/2/3')         assert response.status_code == 200>       assert response.json == {"result": 7}, "This test should fail to demonstrate a failing case"E       AssertionError: This test should fail to demonstrate a failing caseE       assert {'result': 6} == {'result': 7}E          E         Differing items: E         {'result': 6} != {'result': 7}E          E         Full diff: E           {E         -     'result': 7,... E          E         ...Full output truncated (4 lines hidden), use '-vv' to show  tests/test_app.py:61: AssertionError========================================================== short test summary info ==========================================================FAILED tests/test_app.py::test_multiply_edge_cases - AssertionError: This test should fail to demonstrate a failing case======================================================== 1 failed, 5 passed in 0.32s ========================================================

上面的失败消息表明测试 test_multiply_edge_cases 中测试/test_app.py 文件失败。具体来说,此测试函数中的最后一个断言导致了失败。

这种故意失败对于演示如何测试非常有用 报告故障以及故障中提供了哪些信息 信息。它显示了发生故障的确切行, 预期值和实际值,以及两者之间的差异。

在现实场景中,您将修复代码以进行测试 如果预期结果不正确,则通过或调整测试。然而, 在这种情况下,失败是出于教育目的而故意发生的。

相关阅读