python multithreading to test interface performance is so simple

Keywords: JSON Python

In addition to using performance testing tools for performance testing, we can also directly use python multithreading for performance testing.

Next, use these modules to test the performance of a query interface:

requests: send http request

json: the returned string is converted to json format

threading: multithreading

Time: Statistics time

See the code and notes for the specific implementation process.

import requests
import json
import threading
import time
# Define request base address
base_url = "http://127.0.0.1:8000"
success = 0
fail = 0
# Query thread
def get_guest_list_thread(start_user,end_user):
    for i in range(start_user,end_user):
        phone = 13800138000 + i 
        r = requests.get(base_url+'/api/get_guest_list/', params={'eid':1,'phone':phone})
        # print(r.status_code) # 200
        # print(r.content) # b'{"status": 200, "message": "success", "data": {"realname": "alen", "phone": "13800138000", "email": "alen@mail.com", "sign": false}}'
        # print(r.json()) # {'status': 200, 'message': 'success', 'data': {'realname': 'alen', 'phone': '13800138000', 'email': 'alen@mail.com', 'sign': False}}
        # print(type(r)) # < class' requests. Models. Response '> this type has json methods and does not need import json
        # print(r) # <Response [200]>
        # print(json.loads(r.content)) #You need to import json, {'status': 200,' message ':' success', 'data': {'realName': 'Alen', 'phone': '13800138000', 'email': 'Alen @ mail. Com', 'sign': false}}
        result = r.json()
        global success,fail
        try:
            if phone=='13800138000' or phone=='13800138001':
                assert result['status'] == 20
                success +=1
            else:
                assert result['status'] == 10022
                success +=1
        except AssertionError as e:
            print('get error:'+str(phone))
            fail +=1
 
# 5 threads, 25 data
# lists = {1:6, 6:11, 11:16, 16:21, 21:26} # You can write data like this, or you can generate it by
data = 25
n = 5
step = int(data/n)
lists = {}
for i in range(1,n+1):
    lists[(i-1)*step+1]=i*step + 1
print(lists)
 
 
# Create thread list
threads = []
# Create thread
for start_user,end_user in lists.items():
    t = threading.Thread(target=get_guest_list_thread,args=(start_user,end_user)) # args is a tuple
    threads.append(t)
if __name__ == '__main__':
    # start time
    start_time = time.time()
    # Startup thread
    for i in range(len(lists)):
        threads[i].start()
    for i in range(len(lists)):
        threads[i].join()
    # End time
    time.sleep(3) # In order to make it more obvious that the execution time of the use case is too long, sleep is added
    end_time = time.time()
    print("start time:"+str(start_time)+'>>>>>'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time)))
    print("End time:"+str(end_time)+'>>>>>'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end_time)))
    print('Total time consuming:' + str(end_time - start_time))
    print('Total time consuming:%.2f'%(end_time - start_time)) # Keep two decimal places
    print('Number of test cases passed:{}, Number of test failure cases:{}, The test pass rate is:{}'.format(success,fail,str(success*100/(success+fail))+'%'))

Result:

Published 333 original articles· Liked 138· 530000 visitors+
His message board follow

Posted by wikedawsum on Tue, 07 Apr 2020 09:36:13 -0700