测试记录-Python locust 性能测试

编写涉及到知识点:

Python,locust,ocr等

locust适合结合Python代码进行自定义性能测试,相比jmeter更加灵活

locust知识点请查看官方文档:Writing a locustfile — Locust 2.12.3 documentation

代码如下:

import uuid
from locust import HttpUser, TaskSet, task
import requests,re,time
from PIL import Image
import pytesseract,random
# from requests import session

# request = requests.session()


# def get_cert():
#
#     try:
#         file_name  = './images/test-{}.png'.format(uuid.uuid1())
#
#         with open(file_name, 'wb') as f:
#             response = requests.get('http://check.zdns.cn/domainDetect/Kaptcha.jpg')
#             image_content = response.content
#             time.sleep(1)
#             cookie = response.headers.get('Set-Cookie').split(';')[0]
#             f.write(image_content)
#         data = pytesseract.image_to_string(Image.open(file_name))
#     except Exception as e:
#         raise Exception(e)
#     data = ''.join(data.split(' ')).strip()
#
#
#     return data, cookie


class UserBehave(TaskSet):

    @task
    def send_req(self):
        # print('-----start-----')
        # cert_data = get_cert()
        try:
            file_name = './images/test-{}.png'.format(uuid.uuid1())

            with open(file_name, 'wb') as f:
                response = requests.get('验证码地址')
                image_content = response.content
                time.sleep(1)
                # if response.headers.get('Set-Cookie'):
                #     global cookie
                cookie = response.headers.get('Set-Cookie').split(';')[0]
                f.write(image_content)
            data = pytesseract.image_to_string(Image.open(file_name))
        except Exception as e:
            raise Exception(e)
        data = ''.join(data.split(' ')).strip()

        headers = {
            'Cookie': cookie,
            'accept':'text/javascript, application/javascript, */*; q=0.01',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
        }
        base_url = 'http://域名/report/validscan.shtml'
        # domain_name = ['baidu.com','qq.com','jd.com']
        domain_name = ['Mozilla.org', ]
        domain = random.choice(domain_name)
        params = {
            'jsonpcallback':'jQuery1507898510831248589_1661423048921',
            'domain':domain,
            'siteValid': data,
            '_':'1661405786028'
        }
        response = self.client.get(base_url, headers=headers, name="发送whois请求", params = params, catch_response=True)
        with response as r1:
            if '验证' in r1.text:
                r1.failure('验证码错误')
        data = response.text
        # print(data)
        if '错误' not in data:
            try:
                res = re.search(r'(^j.*?)\(', data)
                jquery_data = res.group(1)

                res = re.search(r"keysig\':\'(.*?)\'\}", data)
                keysig_data = res.group(1)
                # print(keysig_data)
                # print(jquery_data)
            except Exception as e:

                raise Exception(e)
            star_time = time.time()
            time_data = int(round(star_time * 1000))
            params={
                'jsonpcallback':jquery_data,
                'keysig':keysig_data.strip(),
                '_':time_data
            }

            self.client.get('域名查询url地址', name = "开启扫描任务",params = params, headers=headers)
            pay_time = 0

            while True:

                t = time.time()
                int(round(t * 1000))
                response = self.client.get('查询结果地址', name='结果获取', params = params,headers = headers)
                params['jsonpcallback'] = params['jsonpcallback'].split('_')[0] + '_' + str(int(round(t * 1000)))
                params.update({'_':int(round(t * 1000))})
                pay_time += response.elapsed.total_seconds()


                # print(response.text)
                if "'end':'true'" in response.text:
                    end_time = time.time()
                    break

                time.sleep(1)
            diff_time = round(end_time - star_time, 3)
            print('{} 域名获取结果时间:{}s'.format(domain, diff_time))
        # else:
        #     response.failure('验证码错误')
        time.sleep(1)


class WebsiteUser(HttpUser):

    tasks = [UserBehave]
    min_wait = 1000  # 最小等待时间
    max_wait = 3000  # 最大等待时间
    host = "http://test.cn(请修改)"  # 服务器地址,也可以在写命令时 指定host地址

if __name__ == '__main__':
    import os

    os.system('locust -f locust_whois_test.py')
    # for i in range(10):

        # data = get_cert()
        # print(data[0])




























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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值