Python3接口性能测试实例代码

首先来看实例代码:

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

57

58

59

60

61

62

63

64

65

66

67

68

69

# -*- coding:utf-8 -*-

import requests

import datetime

import time

import threading

'''

allow_redirects = False禁止重定向,添加在request参数后

get请求用params传参

post请求,数据类型form,用data传参

post请求,数据类型form,用data传参

post请求,数据类型json,json传参

timeout:请求超时时间,添加在request参数后

nub = 10#设置并发线程数

ResponseTime=float(result.elapsed.microseconds)/1000 #获取响应时间,单位ms

ThinkTime = 0.5#设置思考时间

AverageTime = "{:.3f}".format(float(sum(myrequest.times))/float(len(myrequest.times)))#计算数组的平均值,保留3位小数

totaltime = float(hour)*60*60 + float(minute)*60 + float(second) #计算总的思考时间+请求时间

'''

class url_request:

    times = []

    error = []

    def weather_DC(self):

        myrequest=url_request()

        weatherinfo_search = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'

        params = {'key': 'cd1b11e80ffac05253196aa2a1233f25',

                  'city': 110101,

                  'extensions': 'base',

                  'output': 'JSON'}

        result = requests.get(url=weatherinfo_search, params=params)

        print("状态码:",result.status_code)

        print("返回报文:",result.text)

        ResponseTime=float(result.elapsed.microseconds)/1000

        myrequest.times.append(ResponseTime)

        if result.status_code !=200 :

            myrequest.error.append("0")

if __name__=='__main__':

    myrequest=url_request()

    threads = []

    starttime = datetime.datetime.now()

    print("请求开始时间:request start time %s" %starttime)

    nub = 10

    ThinkTime = 0.5

    for i in range(1, nub+1):

        t = threading.Thread(target=myrequest.weather_DC())

        threads.append(t)

    for t in threads:

        time.sleep(ThinkTime)

        print("线程数:thread %s" %t)

        t.setDaemon(True)

        t.start()

        t.join()

    endtime = datetime.datetime.now()

    print("请求结束时间:request end time %s" %endtime)

    time.sleep(3)

    AverageTime = "{:.3f}".format(float(sum(myrequest.times))/float(len(myrequest.times)))

    print("平均响应时间:Average Response Time %s ms" %AverageTime)

    usetime = str(endtime - starttime)

    hour = usetime.split(':').pop(0)

    minute = usetime.split(':').pop(1)

    second = usetime.split(':').pop(2)

    totaltime = float(hour)*60*60 + float(minute)*60 + float(second)

    print("并发数:Concurrent processing %s" %nub)

    print("#总共消耗的时间:use total time %s s" %(totaltime-float(nub*ThinkTime)))

    print("错误请求数:fail request %s s" %myrequest.error.count("0"))

实例扩展:

利用ruquest发送请求,利用多线程模拟并发

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

#!/user/bin/env python

#coding=utf-8

import requests

import datetime

import time

import threading

class url_request():

    times = []

    error = []

    def req(self,AppID,url):

        myreq=url_request()

        headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}

        payload = {'AppID':AppID,'CurrentURL':url}

        r = requests.post("http://xx.xxx.com/WeiXinJSAccessToken/json/WeChatJSTicket",headers=headers,data=payload)

        ResponseTime=float(r.elapsed.microseconds)/1000 #获取响应时间,单位ms

        myreq.times.append(ResponseTime) #将响应时间写入数组

        if r.status_code !=200 :

            myreq.error.append("0")

if __name__=='__main__':

    myreq=url_request()

    threads = []

    starttime = datetime.datetime.now()

    print "request start time %s" %starttime

    nub = 50#设置并发线程数

    ThinkTime = 0.5#设置思考时间

    for i in range(1, nub+1):

        t = threading.Thread(target=myreq.req, args=('12','http://m.ctrip.com/webapp/cpage/#mypoints'))

        threads.append(t)

    for t in threads:

        time.sleep(ThinkTime)

        #print "thread %s" %t #打印线程

        t.setDaemon(True)

        t.start()

    t.join()

    endtime = datetime.datetime.now()

    print "request end time %s" %endtime 

    time.sleep(3)

    AverageTime = "{:.3f}".format(float(sum(myreq.times))/float(len(myreq.times))) #计算数组的平均值,保留3位小数

    print "Average Response Time %s ms" %AverageTime #打印平均响应时间

    usetime = str(endtime - starttime)

    hour = usetime.split(':').pop(0)

    minute = usetime.split(':').pop(1)

    second = usetime.split(':').pop(2)

    totaltime = float(hour)*60*60 + float(minute)*60 + float(second) #计算总的思考时间+请求时间

    print "Concurrent processing %s" %nub #打印并发数

    print "use total time %s s" %(totaltime-float(nub*ThinkTime)) #打印总共消耗的时间

    print "fail request %s" %myreq.error.count("0") #打印错误请求数

1

2

3

4

5

6

request start time 2015-02-10 18:24:14.316000

request end time 2015-02-10 18:24:39.769000

Average Response Time 46.700 ms

Concurrent processing 50

use total time 25.453 s

fail request 1

​现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
qq群号:485187702【暗号:csdn11】
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值