【问题标题】:Locust - Accessing CLI args in LoadTestShape's __init__Locust - 在 LoadTestShape 的 __init__ 中访问 CLI 参数
【发布时间】:2021-11-25 04:30:50
【问题描述】:

我正在使用locust 执行负载测试,并使用来自LoadTestShape 的自定义类实现了基于RPS 的负载生成。 这个自定义类包含不同负载形状的方法,如_tick_step_increase_tick_rps_based 等:

class CustomLoadShape:
    # factory class that holds different shape methods #

    def __init__(self, step_interval=5, max_rps=500):
        self.step_interval = step_interval
        self.max_rps = max_rps

    def _tick_step_increase(self):
        # use self.interval here #
        pass

    def _tick_square_wave(self):
        # use self.max_rps here #
        pass

class MyCustomLoadShape(LoadTestShape, CustomLoadShape):
    # this class is present in locustfile #

    def __init__(self):
        CustomLoadShape.__init__()
        setattr(self, "tick", self._tick_rps_based)     # this is how i make sure the `tick` method is defined

我正在接受一些 cli 参数,例如 max-rps,并希望将它们传递给 MyCustomLoadShape(最终传递给 CustomLoadShape)。

我知道在任务函数中,我们可以通过self.environment.parsed_options.max_rps访问cli args。

直觉上,我尝试在__init__ 中做同样的事情,但它没有self.environment,而self.runnerNone(不知何故,它在tick 方法中显示为一个对象)。

虽然我们可以使用self.runner.environment.parsed_options.max_rpstick 方法中访问cli args,但我想知道在__init__ 中是否有一种方法可以做到这一点,以便我们可以以更OOP 的方式处理属性。

【问题讨论】:

    标签: python load-testing locust


    【解决方案1】:

    我最近回答了另一个类似的问题:

    How to create and use custom command line parameters in locust

    如果您无法访问 LoadShape 类中的环境,我建议您只使用在 init 上运行的另一个函数设置一个全局变量,如下所示:

    max_rps = None
    step_interval = None
    @events.init.add_listener
    def set_max_rps(environment, **kw):
        global max_rps
        max_rps = environment.parsed_options.max_rps
        global step_interval = None
        step_interval = None
    

    然后你可以从你的其他类中访问它:

    class CustomLoadShape:
        # factory class that holds different shape methods #
    
        def _tick_step_increase(self):
            # use interval here #
            step_interval
            pass
    
        def _tick_square_wave(self):
            # use max rps here #
            max_rps
            pass
    

    【讨论】:

    • 这是一种方法,虽然我通常倾向于避免使用全局变量.. 仍然试图弄清楚如何在 __init__ 中获取 self.runner 而不是 None ..
    • 我发现我们可以在__init__ 期间将MyCustomLoadShape 中的解析器加载为locust.argument_parser.parse_options(),然后访问cli args。唯一的缺点是解析 cli args 的函数将被调用两次 - 一次被 locust 调用,然后被这个调用调用
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多