【Python】案例介绍Pytest进行压力测试

这篇具有很好参考价值的文章主要介绍了【Python】案例介绍Pytest进行压力测试。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在现代Web应用程序中,性能是至关重要的。为了确保应用程序能够在高负载下正常运行,我们需要进行性能测试。 今天,应小伙伴的提问, 田辛老师来写一个Pytest进行压力测试的简单案例。 这个案例的测试网站我们就隐藏了,不过网站的基本情况是:

  • 阿里云服务器:CentOS7, 宝塔面版, PHP7.4, MySQL5.7数据库
  • 开发框架:FastAdmin.net

1 程序说明

1.1 设置测试参数

首先,田辛老师做的第一件事情就是设置测试参数。代码如下

# 定义测试用例  
def test_performance():  
    # 设置测试参数  
    url = 'http://www.a.com/'  
    num_threads = 20  
    num_requests = 200  
    timeout = 5

这里面,田老师设置了网站的URL, 线程数, 每个线程的请求次数,以及超时时间。 可以看到, 这里面田老师一共会做4000次请求。

1.2 初始化测试结果

这段代码我想不需要田老师多讲, 这里做一个提示:注意缩进, 这段代码仍然在测试用例test_performance内。

    # 初始化测试结果  
    response_times = []  
    errors = 0  
    successes = 0

1.3 定义测试函数

接下来, 田老师定义了一个内部函数。这个函数就是在某一线程内完成设定次数的请求。

    # 定义测试函数  
    def test_func():  
        nonlocal errors, successes  
        for _ in range(num_requests):  
            try:  
                start_time = time.time()  
                requests.get(url, timeout=timeout)  
                end_time = time.time()  
                response_time = end_time - start_time  
                response_times.append(response_time)  
                successes += 1  
            except requests.exceptions.RequestException:  
                errors += 1

1.4 创建线程、执行线程、等待

    # 创建测试线程  
    threads = []  
    for _ in range(num_threads):  
        t = threading.Thread(target=test_func)  
        threads.append(t)  
      
    # 启动测试线程  
    for t in threads:  
        t.start()  
      
    # 等待测试线程结束  
    for t in threads:  
        t.join()

1.5 计算测试结果

    # 计算测试结果  
    total_requests = num_threads * num_requests  
    throughput = successes / (sum(response_times) or 1)  
    concurrency = num_threads  
    error_rate = errors / (total_requests or 1)  
    cpu_usage = psutil.cpu_percent()  
    memory_usage = psutil.virtual_memory().percent

1.6 将测试结果写入文件

    # 将测试结果写入文件  
    with open('performance_test_result.txt', 'w') as f:  
        f.write(f'总请求数:{total_requests}\n')  
        f.write(f'总时间:{sum(response_times):.2f}s\n')  
        f.write(f'吞吐量:{throughput:.2f} requests/s\n')  
        f.write(f'并发数:{concurrency}\n')  
        f.write(f'错误率:{error_rate:.2%}\n')  
        f.write(f'CPU利用率:{cpu_usage:.2f}%\n')  
        f.write(f'内存利用率:{memory_usage:.2f}%\n')

2 程序执行

2.1 直接执行

在PyCharm里面直接执行这段代码, 得出的结果是:

总请求数:4000  
总时间:1837.65s  
吞吐量:2.17 requests/s  
并发数:20  
错误率:0.12%  
CPU利用率:4.10%  
内存利用率:88.60%

2.2 加个装饰器然后出报告

如果在PyCharm里面直接执行上面的代码, 虽然我们把结果写在文件中,但是, 不好看呀。
所以呢,田老师再额外介绍一个方法,这个方法能够生成一个相对美观的测试报告出来。

2.2.1 声明压力测试

首先在定义用例的时候通过装饰器声明这是一个压力测试:

# 定义测试用例  
@pytest.mark.performance  
def test_performance():  
    # 设置测试参数  
    url = 'http://www.a.biz/'  
    num_threads = 20
2.2.2 在命令行中通过pytest命令执行测试

第二步, 在命令行中执行测试

  • -v 用于显示详细的测试结果
  • --html 用于指定输出报告的位置。 这个参数需要依赖包:pytest-html
$ pytest  -v --html=report.html  test_a.py   

输出执行结果是:

======================== test session starts =================================
platform win32 -- Python 3.10.9, pytest-7.2.1, pluggy-1.0.0 -- D:\python-grp\miniconda_env\py3.10_playwright\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.10.9', 'Platform': 'Windows-10-10.0.22624-SP0', 'Packages': {'pytest': '7.2.1', 'pluggy': '1.0.0'}, 'Plugins': {'allure-pytest': '2.12.0', 'base-url': '2.0.0', 'html': '3.2.0', 'metadata': '2.0.4', 'ordering': '0.6', 'playwright': '0.3.0'}, 'JAVA_HOME': 'D:\\java-grp\\jdk\\', 'Base URL': ''}
rootdir: E:\develop\python\pytest-training\test
plugins: allure-pytest-2.12.0, base-url-2.0.0, html-3.2.0, metadata-2.0.4, ordering-0.6, playwright-0.3.0
collected 1 item                                                                                                                                                                 

test_a.py::test_performance PASSED                                                                                                                                 [100%]

========================== warnings summary ================================= 
test_a.py:25
  E:\develop\python\pytest-training\test\test_a.py:25: PytestUnknownMarkWarning: Unknown pytest.mark.performance - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
    @pytest.mark.performance

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
-- generated html file: file:///E:/develop/python/pytest-training/test/report.html -- 
================= 1 passed, 1 warning in 99.09s (0:01:39) =================== 

(D:\python-grp\miniconda_env\py3.10_playwright) E:\develop\python\pytest-training\test>

最终生成的报告是:(有点长, 截取了关键部分)
python 服务器压力测试,Python,自动化测试,python,pytest,压力测试

3 案例缺陷

因为时间关系, 本案例今天没有时间在服务器端执行, 所以通过psutil库所取得CPU利用率和内存利用率时间并不对。 如果是在服务器端执行, 这两个数字才是对的。

如果要在本地获取服务器的CPU,内存,IO等情况,有一个监控神器:Prometheus。不过这东西配置起来又是另一个话题, 且听后话~哈哈(55555, 好像,又刨了一个坑)文章来源地址https://www.toymoban.com/news/detail-723881.html

4 完整源码

#!/usr/bin/env python  
# -*- coding:utf-8 -*-  
"""  
#-----------------------------------------------------------------------------  
#                     --- TDOUYA STUDIOS ---  
#-----------------------------------------------------------------------------  
#  
# @Project : pytest-training  
# @File    : test_a.py  
# @Author  : tianxin.xp@gmail.com  
# @Date    : 2023/3/10 14:39  
#  
# 压力测试案例  
#  
#--------------------------------------------------------------------------"""  
import threading  
import time  
  
import psutil  
import pytest  
import requests  
  
  
# 定义测试用例  
@pytest.mark.performance  
def test_performance():  
    # 设置测试参数  
    url = 'http://www.tdouya.biz/'  
    num_threads = 20  
    num_requests = 200  
    timeout = 5  
  
    # 初始化测试结果  
    response_times = []  
    errors = 0  
    successes = 0  
  
    # 定义测试函数  
    def test_func():  
        nonlocal errors, successes  
        for _ in range(num_requests):  
            try:  
                start_time = time.time()  
                requests.get(url, timeout=timeout)  
                end_time = time.time()  
                response_time = end_time - start_time  
                response_times.append(response_time)  
                successes += 1  
            except requests.exceptions.RequestException:  
                errors += 1  
  
    # 创建测试线程  
    threads = []  
    for _ in range(num_threads):  
        t = threading.Thread(target=test_func)  
        threads.append(t)  
  
    # 启动测试线程  
    for t in threads:  
        t.start()  
  
    # 等待测试线程结束  
    for t in threads:  
        t.join()  
  
    # 计算测试结果  
    total_requests = num_threads * num_requests  
    throughput = successes / (sum(response_times) or 1)  
    concurrency = num_threads  
    error_rate = errors / (total_requests or 1)  
    cpu_usage = psutil.cpu_percent()  
    memory_usage = psutil.virtual_memory().percent  
  
    # 输出测试结果  
    print(f'总请求数:{total_requests}')  
    print(f'总时间:{sum(response_times):.2f}s')  
    print(f'吞吐量:{throughput:.2f} requests/s')  
    print(f'并发数:{concurrency}')  
    print(f'错误率:{error_rate:.2%}')  
    print(f'CPU利用率:{cpu_usage:.2f}%')  
    print(f'内存利用率:{memory_usage:.2f}%')  
  
    # 将测试结果写入文件  
    with open('performance_test_result.txt', 'w') as f:  
        f.write(f'总请求数:{total_requests}\n')  
        f.write(f'总时间:{sum(response_times):.2f}s\n')  
        f.write(f'吞吐量:{throughput:.2f} requests/s\n')  
        f.write(f'并发数:{concurrency}\n')  
        f.write(f'错误率:{error_rate:.2%}\n')  
        f.write(f'CPU利用率:{cpu_usage:.2f}%\n')  
        f.write(f'内存利用率:{memory_usage:.2f}%\n')

到了这里,关于【Python】案例介绍Pytest进行压力测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【UI自动化测试技术】自动化测试研究:Python+Selenium+Pytest+Allure,详解UI自动化测试,学习模拟鼠标+模拟键盘进行相关操作(精)(四)

    1、了解元素交互的常用方法 2、学习如何对多选元素进行操作 3、 学习模拟鼠标进行相关操作 ( 本节目标 ) 4、 学习模拟键盘进行相关操作 ( 本节目标 ) 用于向 Web 浏览器提供虚拟化设备输入操作的低级接口.除了刚刚讲过的Web元素交互之外, Actions 接口 还提供了对指定输

    2024年03月24日
    浏览(41)
  • pytest-stress:好用的pytest压力测试插件

    简介 :pytest-stress允许在用户定义的时间内循环测试。特别适用于一些已知测试时间,但不知道运行次数的场景。 历史攻略: 压力测试工具:Stress详解 Python:超过设定的时长则退出 安装: 基础案例: 案例源码: 运行结果 :pytest --seconds 10 delay的场景:pytest --seconds 10 --del

    2024年04月28日
    浏览(21)
  • python fastapi 入门教程,每个案例都使用postman进行测试写的接口

    官方示例代码 运行命令:uvicorn test:app --reload 注意:运行命令app前面那个是文件位置,官方的文件名叫main,要以实际的文件名为准,不然找不到app 测试无r参数情况 测试有r参数情况 2.1、错误写法 报错了 2.2、正确写法 2.3、嵌套多个请求参数(不明白的话看下面的postman的请求

    2023年04月08日
    浏览(24)
  • Python测试之Pytest详解

    当涉及到 python 的测试框架时, pytest 是一个功能强大且广泛应用的第三方库。它提供简洁而灵活的方式来编写和执行测试用例,并具有广泛的应用场景。下面是 pytest 的介绍和详细使用说明: pytest 是一个用于 python 单元测试的框架,它建立在标准的 unittest 模块之上,并提供

    2024年02月05日
    浏览(24)
  • python实现接口压力测试

    直接上代码: 输出20次压测结果如下:

    2024年02月17日
    浏览(27)
  • Python测试框架 Pytest —— mock使用(pytest-mock)

    安装:pip install pytest-mock 这里的mock和unittest的mock基本上都是一样的,唯一的区别在于pytest.mock需要导入mock对象的详细路径。 先将需要模拟的天气接口,以及需要模拟的场景的代码写好,然后在进行遵循pytest的用例规范进行书写关于mock的测试用例 通过上述代码,提供pytest中

    2024年02月09日
    浏览(30)
  • Python实现短信循环压力测试教程

    一、安装依赖库 在使用短信循环压力测试之前,需要先安装需要的依赖库——selenium和webdriver。其中,selenium是Python的一个第三方库,能够模拟浏览器的行为,进行自动化测试等操作。webdriver是浏览器的驱动程序,可以实现Python与浏览器之间的交互。 pip install selenium 安装完成

    2024年02月08日
    浏览(71)
  • Python单元测试框架之pytest -- 断言

    对于测试来讲,不管是功能测试,自动化测试,还是单元测试。一般都会预设一个正确的预期结果,而在测试执行的过程中会得到一个实际的结果。测试的成功与否就是拿实际的结果与预期的结果进行比较。这个比的过程实际就是断言(assert)。 在unittest单元测试框架中提供

    2024年02月11日
    浏览(51)
  • Python测试工具-Pytest使用详解

    Pytest是一个全功能Python测试工具,支持第三方扩展插件,能够使用其开展单元测试和复杂功能测试。可以和selenium、requests、appium等模块结合使用实现WEB UI、API、APP自动化测试。 详见参考指南文档:https://docs.pytest.org/en/7.1.x/# PDF文档 : https://media.readthedocs.org/pdf/pytest/latest/pyt

    2024年02月02日
    浏览(28)
  • Python单元测试pytest捕获日志输出

    使用pytest进行单元测试时,遇到了需要测试日志输出的情况,查看了文档 https://docs.pytest.org/en/latest/how-to/capture-stdout-stderr.html https://docs.pytest.org/en/latest/how-to/logging.html 然后试了一下,捕捉logger.info可以用caplog,获取print输出可用capsys,Demo如下: - a.py - test_a.py - 验证:

    2024年04月10日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包