用python做簡單的接口壓力測試

一個多月沒有更博了,最近研究了一下接口的壓力測試,主要來說就是連續頻繁的對接口的調用,來測試接口的響應速度、返回結果,找到接口的性能瓶頸,最大承受極限等。

做接口壓力測試的方法和工具很多,比較常用的工具有postman、jmeter,這兩種都是界面形式的操作,具體可以參考這篇文章
強大的接口測試與壓力測試工具——postman&jmeter

當然也可以使用代碼來跑~~我懷疑你在裝逼,但是沒有證據!

那接下來就是如何用python腳本進行接口測試了,這裏使用的是python3,相關的下載安裝和環境配置這裏不做多說,很多文章都有介紹。

首先我們先要了解要用到http.client.HTTPConnection網絡請求,可以去這篇文章看具體使用方法

https://www.cnblogs.com/cocoajin/p/3679384.html

然後就是需要到線程的支持,最後是對執行結果的輸出分析。

注:下文分段解釋,但是執行時請放在一個.py文件下(代碼有參考借鑑一些別的文章)

一、引入所需庫和設置需要到的參數

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

這裏請根據真實的接口地址進行配置,有需要到token的請自行拿到token值,不需要頭部的的可以在下面中寫headers = {}

二、創建一個 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

res.read().decode('utf-8')這個方法會返回接口響應的所有內容

三、使用派生類方法寫執行

# 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))

四、上面就是所有的代碼,然後我們打開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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章