Python+Pytest压力测试
在现代Web应用程序中,性能是至关重要的。为了确保应用程序能够在高负载下正常运行,我们需要进行性能测试。 今天,应小伙伴的提问, 老向老师来写一个Pytest进行压力测试的简单案例。 这个案例的测试网站我们就隐藏了,不过网站的基本情况是:
阿里框架: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>
3.案例缺陷
因为时间关系, 本案例今天没有时间在服务器端执行, 所以通过psutil库所取得CPU利用率和内存利用率时间并不对。 如果是在服务器端执行, 这两个数字才是对的。
如果要在本地获取服务器的CPU,内存,IO等情况,有一个监控神器:Prometheus。
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压力测试相关推荐
- go python php 压力测试_pyLot 基于python的压力测试工具
因为组内的产品是一个供上海甚至全球所有designer使用的网站,所以并发性很高,于是一直存在访问速度不佳的诟病.为了提高访问速度,就需要对该网站的性能进行测试.于是在网上查了并发性测试和自动化测试的 ...
- python pytest allure_python测试框架pytest和测试报告allure的联合使用-----测试套件
最近采用jenkins+python+pytest+allure写了一些自动化测试用例.碰到这样一种场景:如果我创建了2个测试任务,测试任务1包含2个测试用例test_a.py和test_b.py,测 ...
- 【Python】案例介绍Pytest进行压力测试
在现代Web应用程序中,性能是至关重要的.为了确保应用程序能够在高负载下正常运行,我们需要进行性能测试. 今天,应小伙伴的提问, 田辛老师来写一个Pytest进行压力测试的简单案例. 这个案例的测试网 ...
- python做数据库压力测试_Python 写的一个MongoDB压力测试
Python 写的一个MongoDB压力测试 $ pip install pymongo #!/usr/bin/env python #coding=utf-8 #Author: Ca0Gu0 fro ...
- python的web压力测试工具-pylot安装使用
pylot是python编写的一款web压力测试工具.使用比较简单.而且测试结果相对稳定. 这里不得不鄙视一下apache 的ab测试,那结果真是让人蛋疼,同样的url,测试结果飘忽不定,看得人心惊肉 ...
- python 压力测试小 demo
python 模拟前端进行连接,测试后端接口的压力测试. #coding=utf-8 import http.client,urllib.request,urllib.parse,urllib.err ...
- python+pytest接口自动化之测试函数、测试类/测试方法的封装
前言 今天呢,笔者想和大家聊聊python+pytest接口自动化中将代码进行封装,只有将测试代码进行封装,才能被测试框架识别执行. 例如单个接口的请求代码如下: import requestshea ...
- python实现自动拨打电话_python 实现手机自动拨打电话的方法(通话压力测试)
现在能用自动化实现的,尽量使用自动化程序去操作,代替人工去操作,更有效率. 今天说下用python结合adb命令去实现安卓手机端的通话压力测试. #操作前先在设置里打开power键可以结束通话按钮,否 ...
- python实现自动打电话-python 实现手机自动拨打电话的方法(通话压力测试)
现在能用自动化实现的,尽量使用自动化程序去操作,代替人工去操作,更有效率. 今天说下用python结合adb命令去实现安卓手机端的通话压力测试. #操作前先在设置里打开power键可以结束通话按钮,否 ...
最新文章
- Jquery实现form表单回填数据
- 视觉SLAM前端特征检测与跟踪的思考
- android 8.0的imei简书,Android 8.0通知栏渠道,渠道组的适配和使用
- Eclipse安装GoClipse
- vijos p1460——拉力赛
- 【GoWeb开发实战】Cookie
- 结合shiro 的图形验证码生成
- HDnoip2017题解
- 用PHP制作饼图调查表
- [转]【建议收藏】优秀实用的OpenCV开源项目汇总
- plsql tables 没有表_技术分享 | 在磁盘上查找 MySQL 表的大小
- 《MYSQL必知必会》—3~9.使用MySQL、检索数据列、排序检索数据列、过滤数据(WHERE子句、组合WHERE子句、通配符、正则表达式)
- sha1算法源码c版
- 【windows实用工具一】tftpd32+Xshell
- springboot uniapp小说阅读APP源码
- 利用List集合实现简单的斗地主
- 为什么对方的QQ邮箱收不到我QQ邮箱发的邮件?
- 牛客网赛码网 输入输出格式 pythonC++
- 为自己的snap应用添加变量
- C语言象棋马的遍历程序,[算法]图算法之骑士遍历问题(象棋中马的遍历问题)分析,C语言实现...