locust

The test_start event hook does not get parsed_options in the environment variable when running Locust as a library


I am trying to follow the below example in a distributed setting https://github.com/locustio/locust/blob/master/examples/add_command_line_argument.py

When I run Locust as a library, I do not see the parsed options getting populated.When I pass My argument from the UI, I do not see it in the test_start event hook. The environment.parsed_options is None

@events.init_command_line_parser.add_listener
def _(parser):
    parser.add_argument("--my-argument", type=str, env_var="LOCUST_MY_ARGUMENT", default="", help="It's working", include_in_web_ui=True)

@events.test_start.add_listener
def _(environment, **kw):
    print(f"Custom argument supplied: {environment.parsed_options.my_argument}")



class Master:

    env = Environment(
        user_classes=[Class1, Class2, Class3],
        events=events,
        available_user_classes={
            "Class1": Class1,
            "Class2": Class2,
            "Class3": Class3,
        },
    )

    def _run_master(self):
        self.env.step_load = True
        self.env.create_master_runner()
        self.env.create_web_ui("0.0.0.0", 8089, userclass_picker_is_active=True)
        gevent.spawn(stats_history, self.env.runner)
        self.env.runner.greenlet.join()
        self.env.web_ui.stop()

    def run(self):
        """
        Wrapper for running master locust node

        Parameters: None

        Returns: None
        """
        get_required_env("LOADTESTSERVICE_NAMESPACE")
        self._run_master()

Solution

  • Locust uses configargparse for getting and parsing options. A parser is usually created as part of main, but that doesn't get run when you run as a library. main also normally creates the Environment which is why you have to provide your own Environment when you run as a library. The parsed_options you're wanting are part of Environment but you're not creating your environment with parsed_options so that is expected to be None.

    There are myriad other ways to control custom parameters when running as a library (including environment variables), but if you really want to use Locust's custom args, you'll need to create and use your own configargparse parser (maybe call get_parser?) or since parsed_options is just a Namespace create your own namespace object and populate it with what you want and pass it into your Environment when it's being created.