接口测试python脚本,接口并发python脚本

一、接口测试python脚本
写了很久了,一直没发博客,今儿多发几篇,先上代码。

#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
import requests
from datetime import datetime
class Httpreq():
    def __init__(self,url,data,heards):
        self.url=url
        self.data=data
        self.heards=heards
    def req_1(self):
        requests_statuscode=requests.post(url=self.url,json=self.data).status_code
        try:
            if requests_statuscode == 200:
                print(1)
                #return "请求成功,开始判断响应状态"
            else:
                #return requests_statuscode
                print("请求失败if内")
        except Exception as e:
            print("请求失败try内")
        x = requests.post(url=self.url,json=self.data)
        try :
            a = x.text
            with open(datetime.now().strftime('%Y%m%d%H%M%S') + '.txt','w',encoding="utf-8") as f:
                f.write(a)
        except Exception as e:
            print("写入文件有问题")
        a = x.json()["code"]
        if a == 1000:
            print("正常返回")
        elif a == -1:
            print("系统繁忙")
        elif a == 1001:
            print("partnerId无效")
        elif a == 1002:
            print("IP白名单错误,禁止服务")
        elif a == 1003 :
            print("签名错误")
        elif a == 1004 :
            print("缺少必要的参数")
        else:
            print("返回未知的错误")
if __name__ == '__main__':
    the_url='http://test.pipifit.com/analysisShopCartOverCate'
    #接口url
    the_data= {'day': 1, 'period': 1, 'goodsInfo': [{"goodsId": 1213,"goodsNumber":1}], 'sex': 0, 'symptoms': 1001}
    #请求body
    Httpreq(the_url,the_data,'').req_1()

下面 为接口并发测试脚本,使用的是多线程,而非协程(也就是说,比较鸡肋)。
二、接口并发
脚本1,名为kepler.py。该脚本功能为:向京东开普勒发送post请求

#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
import requests
class Http_request():
    def __init__(self,url,**kwargs):
        self.url = url
        self.kwargs=kwargs
    def update_port_datas(self):
        datas = {
        "method":"biz.product.sku.query",
        "app_key":r'appkey',#需要从京东获得
        'access_token':r'token',#需要从京东获得
        'timestamp':'2019-02-1416:13:10',
        'v':'1.0',
        'format':'json',
        'param_json':'{"name":"测试商品池","pageNum":"1"}'
        }
        try:
            for k in self.kwargs:
                datas[k]=self.kwargs[k]
        except Exception as e:
            print(e)
        return datas

    def post_request(self):
        datas =self.update_port_datas()
        try:
            post_response =requests.post(url=self.url,data=datas)
            return post_response.text
        except Exception as e:
            print (e)
if __name__=="__main__":
    url = "https://router.jd.com/api"
    a = Http_request(url,method="biz.product.PageNum.query",param_json='{}').post_request()
    print(a)

脚本2,名为test.py。该脚本主要功能:建立线程。

#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
import threading
import time

#定义一个方法
def tr(a,b):
    print([x for x in range(a+b)])
    pass

class Mythread(threading.Thread):
    #使用继承实现多线程
    def __init__(self,func):
        threading.Thread.__init__(self)
        self.func=func  #功能名
        #self.args=args  #功能所需参数
    #初始化父类  threading.Thread
    def run(self):
        lock = threading.Lock()
        if lock.acquire():
            self.func  #调用run方法,实现功能的多线程
            print(self.name,time.ctime())
            lock.release()
    #给需要实现多线程的功能 加锁。注意:run方法为重写父类threading.Thread的run方法,函数名不得改变,且此方法必须有。
if __name__=="__main__":
    thread_list=[]
    for i in range(5):  #需要开启多少线程,range中的数字填多少,此处需要5个
        t = thread_list.append(Mythread(tr(3,4)))
    for t in thread_list:
        t.start()
    for t in thread_list:
        t.join()

脚本3,名为port.py。该脚本功能为:设定线程数,开始并发post请求。

#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
from kepler import Http_request
from test import Mythread
import gevent
import requests
def tr():
    url = "https://router.jd.com/api"
    a = Http_request(url,method="biz.product.PageNum.query",param_json='{}').post_request()
    print(a)
def calc():
    url = 'http://te.pipifit.com/goods/list'
    res = requests.get(url,params={'foodId':1},headers={"token":"a93c0fea8150ef04b96ac90ccb8a"})
    print(res.text)
def bing_fa(x):
    c =0
    while 1:
        calc()
        c+=1
        if c>=x:
            break
def thread_func(x,tr):
    thread_list=[]
    for i in range(x):  #需要开启多少线程,range中的数字填多少,此处需要5个
        t = thread_list.append(Mythread(tr))
    for t in thread_list:
        t.start()
    for t in thread_list:
        t.join()
#
gevent.spawn(thread_func(2,bing_fa(500000)))

执行结果示例
在这里插入图片描述
三、总结
总体来说,接口测试并不是很复杂(不考虑pytest或者unittest框架),接口并发也很好构造。但是多线程并不能将单台机器的性能发挥到极致(满载),这是由python解释器是单线程而引起的,所以,以上接口并发脚本并不能满足工作要求。
当然,python的库多且牛,推荐给大家一个专门做性能方面的工具,由python编写的,可以自由构造脚本实现性能测试。他就是:locust。官网:http://locust.io/
另外,给大家一个虫师讲解的安装使用教程的连接。https://www.cnblogs.com/fnng/p/6081798.html
我是胖超人。chubby superman salutes you

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