(十二)关联

所谓关联,就是把一个任务中动态变化返回的数据获取到,把它保存为一个参数,提供给后续任务请求使用。

例如用户在任务1中请求获取任务列表,将返回的taskid获取到并保存为参数,然后在任务2中,用户查看任务详情,使用该taskid作为参数。

既然涉及参数的传递,就需要定义任务的执行顺序,否则locust从TaskSet中随机挑选一个任务执行,任务2可能先于任务1执行,此时任务2执行必然是fail的,参数taskid的值没有获取到。

我们用seq_task定义任务执行的先后顺序,同时使用python队列queue来实现参数的传递。

代码实例

# coding=utf-8
''' Created on 2019-11-08
    author: ali

    场景描述
    step1 用户登录(只登录一次)
    step2 用户查看任务列表,提取taskid
    step3 查看任务详情,以step2的taskid为参数
    step4 退出登录(任务停止时)
'''
import os
import json
import queue
import random
from random import choice
from locust import HttpLocust, task, TaskSequence, seq_task

class userTaskSet(TaskSequence):
    # 定义请求头
    webheaders = {
        "Accept-Encoding": "gzip, deflate",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Connection": "Keep-Alive",
    }

    # 用户登录
    def on_start(self):
        # 请求url
        test_url = "/zentao/user-login.json"
        # 用户名随机取值
        userdatas = ["ali001", "ali002", "ali003", "ali004", "ali005"]
        index = random.randint(0, len(userdatas)-1)
        username = userdatas[index]
        test_data = {
            "account": username,
            "password": "q1w2e3r4t5y6",
            "referer": "/zentao/",
            "passwordStrength": 1
        }
        with self.client.post(test_url, test_data, headers=self.webheaders, catch_response=True) as response:
            try:
                json_res = response.json()
                # 断言
                if json_res["status"] == 'success':
                    response.success()
                else:
                    response.failure('User login failed!')
                    print(json_res)
            except Exception as e:
                response.failure(e)
                print(e)

    # 用户查看任务列表,用户登录后执行该任务
    @seq_task(1)
    def taskList(self):
        test_url = "/zentao/project-task-1.json"

        with self.client.get(test_url, headers=self.webheaders, catch_response=True) as response:
            try:
                json_res = response.json()
                try:
                    taskidKeys = json.loads(json_res["data"])["tasks"].keys() # 字符串转换为json,key: tasks
                    taskid = choice(list(taskidKeys)) # 随机选取一个taskid
                except:
                    taskid = 484 # 获取不到时,设置默认taskid
                self.locust.taskid_queue.put_nowait(taskid)  # 将taskid放入队列
                if json_res["status"] == 'success':
                    response.success()
                else:
                    response.failure('User get task list failed!')
                    print(json_res)
            except Exception as e:
                response.failure(e)
                print(e)

    # 查看任务详情,用户执行查看任务列表后,执行该任务
    @seq_task(2)
    @task(1)
    def viewTask(self):
        taskid = self.locust.taskid_queue.get_nowait() # 从队列中取出taskid
        test_url = "/zentao/task-view-"+ str(taskid) +".json"
        print("taskid is %s " % str(taskid))
        with self.client.get(test_url, headers=self.webheaders, catch_response=True) as response:
            try:
                json_res = response.json()
                if json_res["status"] == 'success':
                    # print(json_res)
                    response.success()
                else:
                    response.failure('User view task failed!')
                    print(json_res)
            except Exception as e:
                response.failure(e)
                print(e)

    # 用户退出登录
    def on_stop(self):
        test_url = "/zentao/user-logout.json"
        with self.client.get(test_url, headers=self.webheaders, catch_response=True) as response:
            try:
                json_res = response.json()
                if json_res["status"] == 'success':
                    response.success()
                else:
                    response.failure('User logout failed!')
                    print(json_res)
            except Exception as e:
                response.failure(e)
                print(e)

class websiteUser(HttpLocust):
    task_set = userTaskSet
    host = 'http://127.0.0.1:8088'
    taskid_queue = queue.Queue()
    min_wait = 2000  # 单位为毫秒
    max_wait = 5000  # 单位为毫秒


if __name__ == "__main__":
    os.system("locust -f zentaoTest.py --host=http://127.0.0.1:8088")

运行结果

控制台打印taskid,可以看到每次取值都是不一样的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值