经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python+Pytest实现压力测试详解
来源:jb51  时间:2023/3/14 8:45:57  对本文有异议

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

  • 阿里
  • 框架:FastAdmin.net

1.程序说明

1.1 设置测试参数

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

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

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

1.2 初始化测试结果

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

  1. # 初始化测试结果
  2. response_times = []
  3. errors = 0
  4. successes = 0

1.3 定义测试函数

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

  1. # 定义测试函数
  2. def test_func():
  3. nonlocal errors, successes
  4. for _ in range(num_requests):
  5. try:
  6. start_time = time.time()
  7. requests.get(url, timeout=timeout)
  8. end_time = time.time()
  9. response_time = end_time - start_time
  10. response_times.append(response_time)
  11. successes += 1
  12. except requests.exceptions.RequestException:
  13. errors += 1

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

  1. # 创建测试线程
  2. threads = []
  3. for _ in range(num_threads):
  4. t = threading.Thread(target=test_func)
  5. threads.append(t)
  6. # 启动测试线程
  7. for t in threads:
  8. t.start()
  9. # 等待测试线程结束
  10. for t in threads:
  11. t.join()

1.5 计算测试结果

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

1.6 将测试结果写入文件

  1. # 将测试结果写入文件
  2. with open('performance_test_result.txt', 'w') as f:
  3. f.write(f'总请求数:{total_requests}\n')
  4. f.write(f'总时间:{sum(response_times):.2f}s\n')
  5. f.write(f'吞吐量:{throughput:.2f} requests/s\n')
  6. f.write(f'并发数:{concurrency}\n')
  7. f.write(f'错误率:{error_rate:.2%}\n')
  8. f.write(f'CPU利用率:{cpu_usage:.2f}%\n')
  9. 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 声明压力测试

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

  1. # 定义测试用例
  2. @pytest.mark.performance
  3. def test_performance():
  4. # 设置测试参数
  5. url = 'http://www.a.biz/'
  6. 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。不过这东西配置起来又是另一个话题, 且听后话~哈哈(55555, 好像,又刨了一个坑)

4 完整源码

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. #-----------------------------------------------------------------------------
  5. # --- TDOUYA STUDIOS ---
  6. #-----------------------------------------------------------------------------
  7. #
  8. # @Project : pytest-training
  9. # @File : test_a.py
  10. # @Author : tianxin.xp@gmail.com
  11. # @Date : 2023/3/10 14:39
  12. #
  13. # 压力测试案例
  14. #
  15. #--------------------------------------------------------------------------"""
  16. import threading
  17. import time
  18. import psutil
  19. import pytest
  20. import requests
  21. # 定义测试用例
  22. @pytest.mark.performance
  23. def test_performance():
  24. # 设置测试参数
  25. url = 'http://www.tdouya.biz/'
  26. num_threads = 20
  27. num_requests = 200
  28. timeout = 5
  29. # 初始化测试结果
  30. response_times = []
  31. errors = 0
  32. successes = 0
  33. # 定义测试函数
  34. def test_func():
  35. nonlocal errors, successes
  36. for _ in range(num_requests):
  37. try:
  38. start_time = time.time()
  39. requests.get(url, timeout=timeout)
  40. end_time = time.time()
  41. response_time = end_time - start_time
  42. response_times.append(response_time)
  43. successes += 1
  44. except requests.exceptions.RequestException:
  45. errors += 1
  46. # 创建测试线程
  47. threads = []
  48. for _ in range(num_threads):
  49. t = threading.Thread(target=test_func)
  50. threads.append(t)
  51. # 启动测试线程
  52. for t in threads:
  53. t.start()
  54. # 等待测试线程结束
  55. for t in threads:
  56. t.join()
  57. # 计算测试结果
  58. total_requests = num_threads * num_requests
  59. throughput = successes / (sum(response_times) or 1)
  60. concurrency = num_threads
  61. error_rate = errors / (total_requests or 1)
  62. cpu_usage = psutil.cpu_percent()
  63. memory_usage = psutil.virtual_memory().percent
  64. # 输出测试结果
  65. print(f'总请求数:{total_requests}')
  66. print(f'总时间:{sum(response_times):.2f}s')
  67. print(f'吞吐量:{throughput:.2f} requests/s')
  68. print(f'并发数:{concurrency}')
  69. print(f'错误率:{error_rate:.2%}')
  70. print(f'CPU利用率:{cpu_usage:.2f}%')
  71. print(f'内存利用率:{memory_usage:.2f}%')
  72. # 将测试结果写入文件
  73. with open('performance_test_result.txt', 'w') as f:
  74. f.write(f'总请求数:{total_requests}\n')
  75. f.write(f'总时间:{sum(response_times):.2f}s\n')
  76. f.write(f'吞吐量:{throughput:.2f} requests/s\n')
  77. f.write(f'并发数:{concurrency}\n')
  78. f.write(f'错误率:{error_rate:.2%}\n')
  79. f.write(f'CPU利用率:{cpu_usage:.2f}%\n')
  80. f.write(f'内存利用率:{memory_usage:.2f}%\n')

到此这篇关于Python+Pytest实现压力测试详解的文章就介绍到这了,更多相关Python Pytest压力测试内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号