• 如何用python做简单的接口压力测试


    这篇文章主要介绍了如何用python做简单的接口压力测试问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教−

    最近研究了一下接口的压力测试,主要来说就是连续频繁的对接口的调用,来测试接口的响应速度、返回结果,找到接口的性能瓶颈,最大承受极限等。

    做接口压力测试的方法和工具很多,比较常用的工具有postman、jmeter,这两种都是界面形式的操作

    那接下来就是如何用python脚本进行接口测试了,这里使用的是python3,相关的下载安装和环境配置这里不做多说,很多文章都有介绍。

    首先我们先要了解要用到http.client.HTTPConnection网络请求。

    然后就是需要到线程的支持,最后是对执行结果的输出分析。

    注:下文分段解释,但是执行时请放在一个.py文件下(代码有参考借鉴一些别的文章)

    一、引入所需库和设置需要到的参数

    这里请根据真实的接口地址进行配置,有需要到token的请自行拿到token值,不需要头部的的可以在下面中写headers = {}

    import threading
    import time
    import http.client
    import urllib
    import requests
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    pararms = urllib.parse.urlencode({'token':'xxx'})
    rqheaders={ #'DeviceToken':'xxxxxxxxx','OSVersion':'1.0.3','AppVersion':'14',
    'Accept':'application/json, text/plain, */*',
    'Accept-Encoding':'gzip, deflate, br',
    'Accept-Language':'zh-CN,zh;q=0.9',
    'Host':'deve.xxx.com',
    'Origin':'https://www.xxx.com',
    'Referer':'https://www.xxx.com/xxx_test/',
    'token':'xxx',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'}
    HOST1 = "www.baidu.com"; #主机地址 例如192.168.1.101   nanning.anjuke.com,
    HOST_L = "deve.xxx.com"
    HOST_IP = "xxx.xx.xxx.xx"  #ip地址
    PORT = 9999 #端口
    METHOD = {1:"GET",2:"POST",3:"OPTIONS"}
    URI = "/api/web/XXX" #相对地址
    TOTAL = 0 #总数
    SUCC = 0 #响应成功数
    FAIL = 0 #响应失败数
    EXCEPT = 0 #响应异常数
    MAXTIME=0 #最大响应时间
    MINTIME=100 #最小响应时间,初始值为100秒
    GT3=0 #统计3秒内响应的
    LT3=0 #统计大于3秒响应的
    # 并发的线程数
    thread_count = 5
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    二、创建一个 threading.Thread 的派生类

    class RequestThread(threading.Thread):
        # 构造函数
        def __init__(self, thread_name):
            threading.Thread.__init__(self)
            self.test_count = 0
            print ("===========task init===========METHOD=",METHOD[3])
        # 线程运行的入口函数
        def run(self):
            self.test_performace()
        def test_performace(self):
                global TOTAL
                global SUCC
                global FAIL
                global EXCEPT
                global GT3
                global LT3
                try:
                    st = time.time()
                    conn = http.client.HTTPConnection(HOST1,PORT)  #若没有PORT请删掉这个参数
                    req = conn.request(METHOD[1], URI, body = {}, headers = rqheaders)  # or POST  headers=rqheaders
                    res = conn.getresponse()
                    #print ('msg:', res.msg)
                    #print ('headers:', res.getheaders())
                    print("res.status =",res.status)
                    print('res.read =',res.read().decode('utf-8'))
                    start_time
                    if res.status == 200:
                        TOTAL = TOTAL+1
                        SUCC = SUCC+1
                        print("TOTAL = ",TOTAL)
                    else:
                        TOTAL = TOTAL+1
                        FAIL = FAIL+1
                        print("TOTAL = ",TOTAL)
                    time_span = time.time()-st
                    print ("%s:%f\n"%(self.name,time_span))
                    self.maxtime(time_span)
                    self.mintime(time_span)
                    if time_span>3:
                        GT3 = GT3+1
                    else:
                        LT3 = LT3+1
                except Exception as e:
                    print("e =",e)
                    TOTAL = TOTAL+1
                    EXCEPT = EXCEPT+1
                conn.close()
        def maxtime(self,ts):
                global MAXTIME
                print(ts)
                if ts>MAXTIME:
                    MAXTIME=ts
        def mintime(self,ts):
                global MINTIME
                if ts<MINTIME:
                    MINTIME=ts
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    三、使用派生类方法写执行

    # main 代码开始
    print ("===========task start===========")
    # 开始的时间
    start_time = time.time()
    i = 1
    while i <= thread_count:
        t = RequestThread("thread" + str(i))
        t.start()
        i = i + 1
    t=0
    #并发数所有都完成或大于60秒就结束
    while TOTAL<thread_count|t>60:
            print ("total:%d,succ:%d,fail:%d,except:%d\n"%(TOTAL,SUCC,FAIL,EXCEPT))
            print (HOST,URI)
            t = t+1
            time.sleep(2)
    time.sleep(2)
    print ("===========task end===========")
    print ("total:%d,succ:%d,fail:%d,except:%d"%(TOTAL,SUCC,FAIL,EXCEPT))
    print ("response maxtime:",MAXTIME)
    print ("response mintime:",MINTIME)
    print ("great than 3 seconds:%d,percent:%0.2f"%(GT3,float(GT3)/TOTAL))
    print ("less than 3 seconds:%d,percent:%0.2f"%(LT3,float(LT3)/TOTAL))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    四、上面就是所有的代码

    然后我们打开cmd来运行这个脚本,这里设置thread_count = 1,即执行一次请求

    cmd进入到相应的py文件夹下,运行脚本结果如下所示:

    F:\pythonTest>python testInterfacePressure.py
    ===========task start===========
    ===========task init===========METHOD= OPTIONS
    res.status = 200
    res.read = {.........."code":1,"message":"数据读取成功","status":200}
    
    TOTAL =  1
    Thread-1:0.149927
    
    0.14992666244506836
    ===========task end===========
    total:1,succ:1,fail:0,except:0
    response maxtime: 0.14992666244506836
    response mintime: 0.14992666244506836
    great than 3 seconds:0,percent:0.00
    less than 3 seconds:1,percent:1.00
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。


    最后

    如果你想学习自动化测试,那么下面这套视频应该会帮到你很多

    如何逼自己1个月学完自动化测试,学完即就业,小白也能信手拈来,拿走不谢,允许白嫖....

    最后我这里给你们分享一下我所积累和整理的一些文档和学习资料,有需要直接领取就可以了!


    以上内容,对于软件测试的朋友来说应该是最全面最完整的备战仓库了,为了更好地整理每个模块,我也参考了很多网上的优质博文和项目,力求不漏掉每一个知识点,很多朋友靠着这些内容进行复习,拿到了BATJ等大厂的offer,这个仓库也已经帮助了很多的软件测试的学习者,希望也能帮助到你。

    ​​

    ​​​​

  • 相关阅读:
    leetcode-495-提莫攻击
    牛客: BM5 合并k个已排序的链表
    【数据结构】【程序填空】赫夫曼解码
    UWA Pipeline 新功能|构建分析、自动化测试支持iOS平台
    粘包和半包问题及解决办法
    C# 电脑程序控制电路开关
    键盘按键Home & End的妙用
    chrome插件:content.js、background.js, options.js, popup.js之间的通信
    基于TI DRV10970驱动直流无刷电机
    lambda表达式的使用
  • 原文地址:https://blog.csdn.net/qq_56271699/article/details/133961534