Samolevar
Samolevar

Reputation: 53

Locust, how to access custom command line argument from LoadTestShape

I create a listener for new command line argument:

@events.init_command_line_parser.add_listener
def init_parser(parser):
    parser.add_argument("--stages", type=str, env_var="LOCUST_STAGES", help="It's working")

but I don't have a clue how to get access to this value. Trying something like:

@events.init.add_listener
def _(environment, **kw):
    os.environ['stages'] = environment.parsed_options.stages

But there is no effect, because command : os.environ.get('stages') returns None

How should I get this value? Especially if I only use it with others like:

locust -f locustfiles/file.py --tag some_tag --stages stages.json

Upvotes: 3

Views: 2615

Answers (3)

ervand7
ervand7

Reputation: 21

You can get access to your custom argument value by the next way. First - create parser variable:

import argparse
locust_parser_settings = argparse.ArgumentParser(
  prog='locust',
  usage='==SUPPRESS==',
  description='\nUsage: locust [OPTIONS] [UserClass ...]\n\n',
  formatter_class=argparse.RawDescriptionHelpFormatter,
  conflict_handler='error',
  add_help=True
)

Then write your hook function with returning of argument value:

@events.init_command_line_parser.add_listener
    def locust_add_option_and_get_option_value(parser):
      parser.add_argument("--my-argument", type=str, env_var="LOCUST_MY_ARGUMENT", default="", help="It's working")
      my_argument = parser.parse_known_args()[0].my_argument
      return my_argument

And at the end you should forcibly call your hook:

my_custom_arg = locust_add_option_and_get_option_value(parser=locust_parser_settings)

Upvotes: 0

Vova
Vova

Reputation: 3537

to add custom arguments, via CLI check github:

    @events.init_command_line_parser.add_listener
def init_parser(parser):
    parser.add_argument("--customarg", type=str, env_var="LOCUST_MY_ARGUMENT", default="1234", help="It's working")

@events.init.add_listener
def _(environment, **kw):
    print("Custom argument supplied: %s" % environment.parsed_options.customarg)

to get it inside your class User init, use:

print(self.environment.parsed_options.customarg)

and run like:

locust -f locustfile.py --customarg CUSTOM_VALUE --headless -u 10 -r 10 --run-time 5s

Upvotes: 1

Cyberwiz
Cyberwiz

Reputation: 11426

You can access the locust environment inside your LoadTestShape class using self.runner.environment (same as in a User/@task)

So you can do something like

def tick(self):
    print(self.runner.environment.parsed_options.stages)
    ...

(note: you need 1.4.4 for this to work)

Upvotes: 2

Related Questions