0

0

如何在 Flask 中执行单元测试

冷漠man

冷漠man

发布时间:2025-01-15 11:26:29

|

715人浏览过

|

来源于digitalocean.com

转载

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

截屏2025-01-15 11.16.44.png

第 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:

Descript
Descript

一个多功能的音频和视频编辑引擎

下载
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 文件失败。具体来说,此测试函数中的最后一个断言导致了失败。

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

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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
Python Flask框架
Python Flask框架

本专题专注于 Python 轻量级 Web 框架 Flask 的学习与实战,内容涵盖路由与视图、模板渲染、表单处理、数据库集成、用户认证以及RESTful API 开发。通过博客系统、任务管理工具与微服务接口等项目实战,帮助学员掌握 Flask 在快速构建小型到中型 Web 应用中的核心技能。

103

2025.08.25

Python Flask Web框架与API开发
Python Flask Web框架与API开发

本专题系统介绍 Python Flask Web框架的基础与进阶应用,包括Flask路由、请求与响应、模板渲染、表单处理、安全性加固、数据库集成(SQLAlchemy)、以及使用Flask构建 RESTful API 服务。通过多个实战项目,帮助学习者掌握使用 Flask 开发高效、可扩展的 Web 应用与 API。

81

2025.12.15

json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

454

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

546

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

333

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

82

2025.09.10

pip安装使用方法
pip安装使用方法

安装步骤:1、确保Python已经正确安装在您的计算机上;2、下载“get-pip.py”脚本;3、按下Win + R键,然后输入cmd并按下Enter键来打开命令行窗口;4、在命令行窗口中,使用cd命令切换到“get-pip.py”所在的目录;5、执行安装命令;6、验证安装结果即可。大家可以访问本专题下的文章,了解pip安装使用方法的更多内容。

373

2023.10.09

更新pip版本
更新pip版本

更新pip版本方法有使用pip自身更新、使用操作系统自带的包管理工具、使用python包管理工具、手动安装最新版本。想了解更多相关的内容,请阅读专题下面的文章。

434

2024.12.20

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

59

2026.03.06

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PostgreSQL 教程
PostgreSQL 教程

共48课时 | 10.4万人学习

Git 教程
Git 教程

共21课时 | 4.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号