如何在 Flask 中执行单元测试

测试对于软件开发过程至关重要,可确保代码按预期运行且无缺陷。在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, jsonifyapp = 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//')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 请求是什么做:

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

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

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 的新文件并添加以下代码:

腾讯混元 腾讯混元

腾讯混元大由腾讯研发的大语言模型,具备强大的中文创作能力、逻辑推理能力,以及可靠的任务执行能力。

腾讯混元 65 查看详情 腾讯混元 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

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

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

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

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

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

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

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.0rootdir: /home/user/flask_testing_appcollected 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.0rootdir: /home/user/flask_testing_app cachedir: .pytest_cache      collected 5 items                                                                                          tests/test_app.py::test_home Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_about Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_multiply Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_multiply_invalid_input Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_non_existent_route Setting up the test clientPASSEDTearing 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 函数并解释每个部分的含义执行:

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

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

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

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

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

root@ubuntu:~# pytest -vs

您应该看到以下输出:

Outputplatform linux -- Python 3.12.3, pytest-8.3.2, pluggy-1.5.0rootdir: /home/user/flask_testing_app cachedir: .pytest_cache        collected 6 items                                                                                                                           tests/test_app.py::test_home Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_about Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_multiply Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_multiply_invalid_input Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_non_existent_route Setting up the test clientPASSEDTearing down the test clienttests/test_app.py::test_multiply_edge_cases Setting up the test clientFAILEDTearing down the test client================================================================= FAILURES ==================================================================_________________________________________________________ test_multiply_edge_cases __________________________________________________________client = <FlaskClient >    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 showtests/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 文件失败。具体来说,此测试函数中的最后一个断言导致了失败。

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

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

以上就是如何在 Flask 中执行单元测试的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/517088.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月9日 03:43:05
下一篇 2025年11月9日 03:43:42

相关推荐

  • Uniapp 中如何不拉伸不裁剪地展示图片?

    灵活展示图片:如何不拉伸不裁剪 在界面设计中,常常需要以原尺寸展示用户上传的图片。本文将介绍一种在 uniapp 框架中实现该功能的简单方法。 对于不同尺寸的图片,可以采用以下处理方式: 极端宽高比:撑满屏幕宽度或高度,再等比缩放居中。非极端宽高比:居中显示,若能撑满则撑满。 然而,如果需要不拉伸不…

    2025年12月24日
    400
  • 如何让小说网站控制台显示乱码,同时网页内容正常显示?

    如何在不影响用户界面的情况下实现控制台乱码? 当在小说网站上下载小说时,大家可能会遇到一个问题:网站上的文本在网页内正常显示,但是在控制台中却是乱码。如何实现此类操作,从而在不影响用户界面(UI)的情况下保持控制台乱码呢? 答案在于使用自定义字体。网站可以通过在服务器端配置自定义字体,并通过在客户端…

    2025年12月24日
    800
  • 如何在地图上轻松创建气泡信息框?

    地图上气泡信息框的巧妙生成 地图上气泡信息框是一种常用的交互功能,它简便易用,能够为用户提供额外信息。本文将探讨如何借助地图库的功能轻松创建这一功能。 利用地图库的原生功能 大多数地图库,如高德地图,都提供了现成的信息窗体和右键菜单功能。这些功能可以通过以下途径实现: 高德地图 JS API 参考文…

    2025年12月24日
    400
  • 如何使用 scroll-behavior 属性实现元素scrollLeft变化时的平滑动画?

    如何实现元素scrollleft变化时的平滑动画效果? 在许多网页应用中,滚动容器的水平滚动条(scrollleft)需要频繁使用。为了让滚动动作更加自然,你希望给scrollleft的变化添加动画效果。 解决方案:scroll-behavior 属性 要实现scrollleft变化时的平滑动画效果…

    2025年12月24日
    000
  • 如何为滚动元素添加平滑过渡,使滚动条滑动时更自然流畅?

    给滚动元素平滑过渡 如何在滚动条属性(scrollleft)发生改变时为元素添加平滑的过渡效果? 解决方案:scroll-behavior 属性 为滚动容器设置 scroll-behavior 属性可以实现平滑滚动。 html 代码: click the button to slide right!…

    2025年12月24日
    500
  • 如何选择元素个数不固定的指定类名子元素?

    灵活选择元素个数不固定的指定类名子元素 在网页布局中,有时需要选择特定类名的子元素,但这些元素的数量并不固定。例如,下面这段 html 代码中,activebar 和 item 元素的数量均不固定: *n *n 如果需要选择第一个 item元素,可以使用 css 选择器 :nth-child()。该…

    2025年12月24日
    200
  • 使用 SVG 如何实现自定义宽度、间距和半径的虚线边框?

    使用 svg 实现自定义虚线边框 如何实现一个具有自定义宽度、间距和半径的虚线边框是一个常见的前端开发问题。传统的解决方案通常涉及使用 border-image 引入切片图片,但是这种方法存在引入外部资源、性能低下的缺点。 为了避免上述问题,可以使用 svg(可缩放矢量图形)来创建纯代码实现。一种方…

    2025年12月24日
    100
  • 如何解决本地图片在使用 mask JS 库时出现的跨域错误?

    如何跨越localhost使用本地图片? 问题: 在本地使用mask js库时,引入本地图片会报跨域错误。 解决方案: 要解决此问题,需要使用本地服务器启动文件,以http或https协议访问图片,而不是使用file://协议。例如: python -m http.server 8000 然后,可以…

    2025年12月24日
    200
  • 如何让“元素跟随文本高度,而不是撑高父容器?

    如何让 元素跟随文本高度,而不是撑高父容器 在页面布局中,经常遇到父容器高度被子元素撑开的问题。在图例所示的案例中,父容器被较高的图片撑开,而文本的高度没有被考虑。本问答将提供纯css解决方案,让图片跟随文本高度,确保父容器的高度不会被图片影响。 解决方法 为了解决这个问题,需要将图片从文档流中脱离…

    2025年12月24日
    000
  • 为什么 CSS mask 属性未请求指定图片?

    解决 css mask 属性未请求图片的问题 在使用 css mask 属性时,指定了图片地址,但网络面板显示未请求获取该图片,这可能是由于浏览器兼容性问题造成的。 问题 如下代码所示: 立即学习“前端免费学习笔记(深入)”; icon [data-icon=”cloud”] { –icon-cl…

    2025年12月24日
    200
  • 如何利用 CSS 选中激活标签并影响相邻元素的样式?

    如何利用 css 选中激活标签并影响相邻元素? 为了实现激活标签影响相邻元素的样式需求,可以通过 :has 选择器来实现。以下是如何具体操作: 对于激活标签相邻后的元素,可以在 css 中使用以下代码进行设置: li:has(+li.active) { border-radius: 0 0 10px…

    2025年12月24日
    100
  • 如何模拟Windows 10 设置界面中的鼠标悬浮放大效果?

    win10设置界面的鼠标移动显示周边的样式(探照灯效果)的实现方式 在windows设置界面的鼠标悬浮效果中,光标周围会显示一个放大区域。在前端开发中,可以通过多种方式实现类似的效果。 使用css 使用css的transform和box-shadow属性。通过将transform: scale(1.…

    2025年12月24日
    200
  • 为什么我的 Safari 自定义样式表在百度页面上失效了?

    为什么在 Safari 中自定义样式表未能正常工作? 在 Safari 的偏好设置中设置自定义样式表后,您对其进行测试却发现效果不同。在您自己的网页中,样式有效,而在百度页面中却失效。 造成这种情况的原因是,第一个访问的项目使用了文件协议,可以访问本地目录中的图片文件。而第二个访问的百度使用了 ht…

    2025年12月24日
    000
  • 如何用前端实现 Windows 10 设置界面的鼠标移动探照灯效果?

    如何在前端实现 Windows 10 设置界面中的鼠标移动探照灯效果 想要在前端开发中实现 Windows 10 设置界面中类似的鼠标移动探照灯效果,可以通过以下途径: CSS 解决方案 DEMO 1: Windows 10 网格悬停效果:https://codepen.io/tr4553r7/pe…

    2025年12月24日
    000
  • 使用CSS mask属性指定图片URL时,为什么浏览器无法加载图片?

    css mask属性未能加载图片的解决方法 使用css mask属性指定图片url时,如示例中所示: mask: url(“https://api.iconify.design/mdi:apple-icloud.svg”) center / contain no-repeat; 但是,在网络面板中却…

    2025年12月24日
    000
  • 如何用CSS Paint API为网页元素添加时尚的斑马线边框?

    为元素添加时尚的斑马线边框 在网页设计中,有时我们需要添加时尚的边框来提升元素的视觉效果。其中,斑马线边框是一种既醒目又别致的设计元素。 实现斜向斑马线边框 要实现斜向斑马线间隔圆环,我们可以使用css paint api。该api提供了强大的功能,可以让我们在元素上绘制复杂的图形。 立即学习“前端…

    2025年12月24日
    000
  • 图片如何不撑高父容器?

    如何让图片不撑高父容器? 当父容器包含不同高度的子元素时,父容器的高度通常会被最高元素撑开。如果你希望父容器的高度由文本内容撑开,避免图片对其产生影响,可以通过以下 css 解决方法: 绝对定位元素: .child-image { position: absolute; top: 0; left: …

    2025年12月24日
    000
  • 使用 Mask 导入本地图片时,如何解决跨域问题?

    跨域疑难:如何解决 mask 引入本地图片产生的跨域问题? 在使用 mask 导入本地图片时,你可能会遇到令人沮丧的跨域错误。为什么会出现跨域问题呢?让我们深入了解一下: mask 框架假设你以 http(s) 协议加载你的 html 文件,而当使用 file:// 协议打开本地文件时,就会产生跨域…

    2025年12月24日
    200
  • CSS 帮助

    我正在尝试将文本附加到棕色框的左侧。我不能。我不知道代码有什么问题。请帮助我。 css .hero { position: relative; bottom: 80px; display: flex; justify-content: left; align-items: start; color:…

    2025年12月24日 好文分享
    200
  • 前端代码辅助工具:如何选择最可靠的AI工具?

    前端代码辅助工具:可靠性探讨 对于前端工程师来说,在HTML、CSS和JavaScript开发中借助AI工具是司空见惯的事情。然而,并非所有工具都能提供同等的可靠性。 个性化需求 关于哪个AI工具最可靠,这个问题没有一刀切的答案。每个人的使用习惯和项目需求各不相同。以下是一些影响选择的重要因素: 立…

    2025年12月24日
    300

发表回复

登录后才能评论
关注微信