Search code examples
locust

Adjust wait_time in locust using custom arguments via CLI


I want to adjust wait_time parameter by passing it via CLI.

I have tried the following way:

custom_wait_time = None

# Add custom argument to locust
@events.init_command_line_parser.add_listener
def init_parser(parser):
    parser.add_argument("--locust-wait-time",
                      type=int,
                      include_in_web_ui=True,
                      default=None,
                      help="Wait time per each request of a user.")

@events.init.add_listener
def _(environment, **kwargs):
    global custom_wait_time
    custom_wait_time = int(environment.parsed_options.locust_wait_time)
    print(custom_wait_time) # First print

class MyUser(HttpUser):
    global custom_wait_time
    print(custom_wait_time) # Second print
    wait_time = constant(custom_wait_time)

Assume that custom_wait_time=10 when I pass it via CLI, the First print gives me custom_wait_time=10 while the Second print gives me custom_wait_time=None instead of 10, so the wait_time = constant(custom_wait_time) will break and give me the error below:

Traceback (most recent call last):
  File "src/gevent/greenlet.py", line 908, in gevent._gevent_cgreenlet.Greenlet.run
  File "/Users/opt/anaconda3/envs/ai/lib/python3.7/site-packages/locust/user/users.py", line 176, in run_user
    user.run()
  File "/Users/opt/anaconda3/envs/ai/lib/python3.7/site-packages/locust/user/users.py", line 144, in run
    self._taskset_instance.run()
  File "/Users/opt/anaconda3/envs/ai/lib/python3.7/site-packages/locust/user/task.py", line 367, in run
    self.wait()
  File "/Users/opt/anaconda3/envs/ai/lib/python3.7/site-packages/locust/user/task.py", line 445, in wait
    self._sleep(self.wait_time())
  File "/Users/opt/anaconda3/envs/ai/lib/python3.7/site-packages/locust/user/task.py", line 451, in _sleep
    gevent.sleep(seconds)
  File "/Users/opt/anaconda3/envs/ai/lib/python3.7/site-packages/gevent/hub.py", line 157, in sleep
    if seconds <= 0:
TypeError: '<=' not supported between instances of 'NoneType' and 'int'

Any help would be appreciated.


Solution

  • The problem is that the code will run in the wrong order - MyUser is defined before any of the init-methods are called.

    If you instead do MyUser.wait_time = constant(custom_wait_time) inside your init handler (and dont set it at all in the class) it should work.

    That way you dont need any globals either :)