Python+Pytest實現(xiàn)壓力測試詳解
在現(xiàn)代Web應(yīng)用程序中,性能是至關(guān)重要的。為了確保應(yīng)用程序能夠在高負(fù)載下正常運(yùn)行,我們需要進(jìn)行性能測試。 今天,應(yīng)小伙伴的提問, 田辛老師來寫一個Pytest進(jìn)行壓力測試的簡單案例。 這個案例的測試網(wǎng)站我們就隱藏了,不過網(wǎng)站的基本情況是:
- 阿里
- 框架:FastAdmin.net
1.程序說明
1.1 設(shè)置測試參數(shù)
首先,田辛老師做的第一件事情就是設(shè)置測試參數(shù)。代碼如下
# 定義測試用例
def test_performance():
# 設(shè)置測試參數(shù)
url = 'http://www.a.com/'
num_threads = 20
num_requests = 200
timeout = 5
這里面,田老師設(shè)置了網(wǎng)站的URL, 線程數(shù), 每個線程的請求次數(shù),以及超時時間。 可以看到, 這里面田老師一共會做4000次請求。
1.2 初始化測試結(jié)果
這段代碼我想不需要田老師多講, 這里做一個提示:注意縮進(jìn), 這段代碼仍然在測試用例test_performance內(nèi)。
# 初始化測試結(jié)果
response_times = []
errors = 0
successes = 0
1.3 定義測試函數(shù)
接下來, 田老師定義了一個內(nèi)部函數(shù)。這個函數(shù)就是在某一線程內(nèi)完成設(shè)定次數(shù)的請求。
# 定義測試函數(shù)
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 創(chuàng)建線程、執(zhí)行線程、等待
# 創(chuàng)建測試線程
threads = []
for _ in range(num_threads):
t = threading.Thread(target=test_func)
threads.append(t)
# 啟動測試線程
for t in threads:
t.start()
# 等待測試線程結(jié)束
for t in threads:
t.join()
1.5 計算測試結(jié)果
# 計算測試結(jié)果
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 將測試結(jié)果寫入文件
# 將測試結(jié)果寫入文件
with open('performance_test_result.txt', 'w') as f:
f.write(f'總請求數(shù):{total_requests}\n')
f.write(f'總時間:{sum(response_times):.2f}s\n')
f.write(f'吞吐量:{throughput:.2f} requests/s\n')
f.write(f'并發(fā)數(shù):{concurrency}\n')
f.write(f'錯誤率:{error_rate:.2%}\n')
f.write(f'CPU利用率:{cpu_usage:.2f}%\n')
f.write(f'內(nèi)存利用率:{memory_usage:.2f}%\n')
2.程序執(zhí)行
2.1 直接執(zhí)行
在PyCharm里面直接執(zhí)行這段代碼, 得出的結(jié)果是:
總請求數(shù):4000
總時間:1837.65s
吞吐量:2.17 requests/s
并發(fā)數(shù):20
錯誤率:0.12%
CPU利用率:4.10%
內(nèi)存利用率:88.60%
2.2 加個裝飾器然后出報告
如果在PyCharm里面直接執(zhí)行上面的代碼, 雖然我們把結(jié)果寫在文件中,但是, 不好看呀。
所以呢,田老師再額外介紹一個方法,這個方法能夠生成一個相對美觀的測試報告出來。
2.2.1 聲明壓力測試
首先在定義用例的時候通過裝飾器聲明這是一個壓力測試:
# 定義測試用例
@pytest.mark.performance
def test_performance():
# 設(shè)置測試參數(shù)
url = 'http://www.a.biz/'
num_threads = 20
2.2.2 在命令行中通過pytest命令執(zhí)行測試
第二步, 在命令行中執(zhí)行測試
- -v 用于顯示詳細(xì)的測試結(jié)果
- --html 用于指定輸出報告的位置。 這個參數(shù)需要依賴包:pytest-html
$ pytest -v --html=report.html test_a.py
輸出執(zhí)行結(jié)果是:
======================== 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>
最終生成的報告是:(有點(diǎn)長, 截取了關(guān)鍵部分)

3.案例缺陷
因為時間關(guān)系, 本案例今天沒有時間在服務(wù)器端執(zhí)行, 所以通過psutil庫所取得CPU利用率和內(nèi)存利用率時間并不對。 如果是在服務(wù)器端執(zhí)行, 這兩個數(shù)字才是對的。
如果要在本地獲取服務(wù)器的CPU,內(nèi)存,IO等情況,有一個監(jiān)控神器:Prometheus。不過這東西配置起來又是另一個話題, 且聽后話~哈哈(55555, 好像,又刨了一個坑)
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():
# 設(shè)置測試參數(shù)
url = 'http://www.tdouya.biz/'
num_threads = 20
num_requests = 200
timeout = 5
# 初始化測試結(jié)果
response_times = []
errors = 0
successes = 0
# 定義測試函數(shù)
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
# 創(chuàng)建測試線程
threads = []
for _ in range(num_threads):
t = threading.Thread(target=test_func)
threads.append(t)
# 啟動測試線程
for t in threads:
t.start()
# 等待測試線程結(jié)束
for t in threads:
t.join()
# 計算測試結(jié)果
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
# 輸出測試結(jié)果
print(f'總請求數(shù):{total_requests}')
print(f'總時間:{sum(response_times):.2f}s')
print(f'吞吐量:{throughput:.2f} requests/s')
print(f'并發(fā)數(shù):{concurrency}')
print(f'錯誤率:{error_rate:.2%}')
print(f'CPU利用率:{cpu_usage:.2f}%')
print(f'內(nèi)存利用率:{memory_usage:.2f}%')
# 將測試結(jié)果寫入文件
with open('performance_test_result.txt', 'w') as f:
f.write(f'總請求數(shù):{total_requests}\n')
f.write(f'總時間:{sum(response_times):.2f}s\n')
f.write(f'吞吐量:{throughput:.2f} requests/s\n')
f.write(f'并發(fā)數(shù):{concurrency}\n')
f.write(f'錯誤率:{error_rate:.2%}\n')
f.write(f'CPU利用率:{cpu_usage:.2f}%\n')
f.write(f'內(nèi)存利用率:{memory_usage:.2f}%\n')
到此這篇關(guān)于Python+Pytest實現(xiàn)壓力測試詳解的文章就介紹到這了,更多相關(guān)Python Pytest壓力測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python虛擬環(huán)境venv實戰(zhàn)過程詳解
Python的虛擬環(huán)境可以幫助我們在同一臺機(jī)器上,同時使用不同的Python版本和庫,方便管理和開發(fā),下面這篇文章主要給大家介紹了關(guān)于Python虛擬環(huán)境venv的相關(guān)資料,需要的朋友可以參考下2023-06-06
python函數(shù)參數(shù),名稱空間,以及函數(shù)嵌套
這篇文章主要給大家介紹python函數(shù)參數(shù)、名稱空間、以及函數(shù)嵌套的相關(guān)資料,想具體了解的小伙伴請和小編一起進(jìn)入下面文章內(nèi)容吧2021-10-10
Python實現(xiàn)PPT幻燈片的添加、刪除或隱藏操作
PowerPoint文檔是商務(wù)、教育、創(chuàng)意等各領(lǐng)域常見的用于展示、教育和傳達(dá)信息的格式,在制作PPT演示文稿時,靈活地操作幻燈片是提高演示效果、優(yōu)化內(nèi)容組織的關(guān)鍵步驟,本文給大家介紹了Python 操作PPT幻燈片- 添加、刪除、或隱藏幻燈片,需要的朋友可以參考下2024-08-08
用scikit-learn和pandas學(xué)習(xí)線性回歸的方法
這篇文章主要介紹了用scikit-learn和pandas學(xué)習(xí)線性回歸的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
opencv+mediapipe實現(xiàn)人臉檢測及攝像頭實時示例
本文主要介紹了opencv+mediapipe實現(xiàn)人臉檢測及攝像頭實時,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12
Tensorflow中的placeholder和feed_dict的使用
這篇文章主要介紹了Tensorflow中的placeholder和feed_dict的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07

