动态创建蝗虫任务? [英] Create locust tasks dynamically?

查看:17
本文介绍了动态创建蝗虫任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要产生30个用户,并为他们提供50个不同的任务,我需要他们并行运行。因此,我尝试生成50个任务,如下所示:

class UserSimulation(HttpUser):
    host = os.environ['BASE_URL']

    # time in seconds the simulated user will wait before proceeding to the next task
    wait_time = between(1, 2)

    for item_id in range(1, 51):

        @task(1)
        def view_items_with_different_item_ids(self, item_id=item_id):
            self.client.get(
                url=f"/my-url/item24_00{item_id}",
                verify=False,
                auth=(os.environ['USERNAME'], os.environ['PASSWORD'])

由于显而易见的原因,这种方法不允许我动态创建50个任务,因为只保存最后一个任务。有什么解决办法吗?

推荐答案

若要按您尝试的方式操作,请尝试creating different functions programmatically。我不知道如何使用这些修饰符,但如果没有其他问题,您可以在创建函数时将它们添加到Locust任务列表中。只需在创建函数时创建任务列表tasks = []然后tasks.append(view_items_with_different_item_ids_1)

然而,根据您对所需内容的描述,我不确定这是否有必要。如果您只需要30个用户去进行50次调用,那么您只需要一个任务,您就可以在其中循环调用。

class UserSimulation(HttpUser):
    host = os.environ['BASE_URL']

    # time in seconds the simulated user will wait before proceeding to the next task
    wait_time = between(1, 2)

    @task(1)
    def view_items_with_different_item_ids(self):
        for item_id in range(1, 51):
            self.client.get(
                url=f"/my-url/item24_00{item_id}",
                verify=False,
                auth=(os.environ['USERNAME'], os.environ['PASSWORD'])

如果您需要一个随机数而不是连续数,但需要确保每个数都被调用一次:

    import random

    item_ids = list(range(1,51))
    random.shuffle(item_ids)
    @task(1)
    def view_items_with_different_item_ids(self):
        for item_id in item_ids:
            self.client.get(
                url=f"/my-url/item24_00{item_id}",
                verify=False,
                auth=(os.environ['USERNAME'], os.environ['PASSWORD'])

如果您只想一直拉一个随机数,而不关心重复:

    import random

    item_ids = list(range(1,51))
    @task(1)
    def view_items_with_different_item_ids(self):
        random_id = random.choice(item_ids)
        self.client.get(
            url=f"/my-url/item24_00{random_id}",
            verify=False,
            auth=(os.environ['USERNAME'], os.environ['PASSWORD'])

这篇关于动态创建蝗虫任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆