API

User class

class User(environment)[source]

Represents a “user” which is to be spawned and attack the system that is to be load tested.

The behaviour of this user is defined by its tasks. Tasks can be declared either directly on the class by using the @task decorator on methods, or by setting the tasks attribute.

This class should usually be subclassed by a class that defines some kind of client. For example when load testing an HTTP system, you probably want to use the HttpUser class.

abstract = True

If abstract is True, the class is meant to be subclassed, and locust will not spawn users of this class during a test.

context()[source]

Adds the returned value (a dict) to the context for request event. Override this in your User class to customize the context.

environment

A reference to the Environment in which this user is running

fixed_count = 0

If the value > 0, the weight property will be ignored and the ‘fixed_count’-instances will be spawned. These Users are spawned first. If the total target count (specified by the –users arg) is not enough to spawn all instances of each User class with the defined property, the final count of each User is undefined.

on_start()[source]

Called when a User starts running.

on_stop()[source]

Called when a User stops running (is killed)

tasks = []

Collection of python callables and/or TaskSet classes that the Locust user(s) will run.

If tasks is a list, the task to be performed will be picked randomly.

If tasks is a (callable,int) list of two-tuples, or a {callable:int} dict, the task to be performed will be picked randomly, but each task will be weighted according to its corresponding int value. So in the following case, ThreadPage will be fifteen times more likely to be picked than write_post:

class ForumPage(TaskSet):
    tasks = {ThreadPage:15, write_post:1}
wait()[source]

Make the running user sleep for a duration defined by the User.wait_time function.

The user can also be killed gracefully while it’s sleeping, so calling this method within a task makes it possible for a user to be killed mid-task even if you’ve set a stop_timeout. If this behaviour is not desired, you should make the user wait using gevent.sleep() instead.

wait_time()

Method that returns the time (in seconds) between the execution of locust tasks. Can be overridden for individual TaskSets.

Example:

from locust import User, between
class MyUser(User):
    wait_time = between(3, 25)
weight = 1

Probability of user class being chosen. The higher the weight, the greater the chance of it being chosen.

HttpUser class

class HttpUser(*args, **kwargs)[source]

Represents an HTTP “user” which is to be spawned and attack the system that is to be load tested.

The behaviour of this user is defined by its tasks. Tasks can be declared either directly on the class by using the @task decorator on methods, or by setting the tasks attribute.

This class creates a client attribute on instantiation which is an HTTP client with support for keeping a user session between requests.

abstract = True

If abstract is True, the class is meant to be subclassed, and users will not choose this locust during a test

client

Instance of HttpSession that is created upon instantiation of Locust. The client supports cookies, and therefore keeps the session between HTTP requests.

FastHttpUser class

class FastHttpUser(environment)[source]

FastHttpUser provides the same API as HttpUser, but uses geventhttpclient instead of python-requests as its underlying client. It uses considerably less CPU on the load generator, and should work as a simple drop-in-replacement in most cases.

abstract = True

Dont register this as a User class that can be run by itself

client

Instance of HttpSession that is created upon instantiation of User. The client support cookies, and therefore keeps the session between HTTP requests.

rest(method, url, headers=None, **kwargs)[source]

A wrapper for self.client.request that:

  • Parses the JSON response to a dict called js in the response object. Marks the request as failed if the response was not valid JSON.

  • Defaults Content-Type and Accept headers to application/json

  • Sets catch_response=True (so always use a with-block)

  • Catches any unhandled exceptions thrown inside your with-block, marking the sample as failed (instead of exiting the task immediately without even firing the request event)

TaskSet class

class TaskSet(parent)[source]

Class defining a set of tasks that a User will execute.

When a TaskSet starts running, it will pick a task from the tasks attribute, execute it, and then sleep for the number of seconds returned by its wait_time function. If no wait_time method has been declared on the TaskSet, it’ll call the wait_time function on the User by default. It will then schedule another task for execution and so on.

TaskSets can be nested, which means that a TaskSet’s tasks attribute can contain another TaskSet. If the nested TaskSet is scheduled to be executed, it will be instantiated and called from the currently executing TaskSet. Execution in the currently running TaskSet will then be handed over to the nested TaskSet which will continue to run until it throws an InterruptTaskSet exception, which is done when TaskSet.interrupt() is called. (execution will then continue in the first TaskSet).

property client

Shortcut to the client client attribute of this TaskSet’s User

interrupt(reschedule=True)[source]

Interrupt the TaskSet and hand over execution control back to the parent TaskSet.

If reschedule is True (default), the parent User will immediately re-schedule, and execute, a new task.

on_start()[source]

Called when a User starts executing this TaskSet

on_stop()[source]

Called when a User stops executing this TaskSet. E.g. when TaskSet.interrupt() is called or when the User is killed

property parent

Parent TaskSet instance of this TaskSet (or User if this is not a nested TaskSet)

schedule_task(task_callable, first=False)[source]

Add a task to the User’s task execution queue.

Parameters
  • task_callable – User task to schedule.

  • first – Optional keyword argument. If True, the task will be put first in the queue.

tasks = []

Collection of python callables and/or TaskSet classes that the User(s) will run.

If tasks is a list, the task to be performed will be picked randomly.

If tasks is a (callable,int) list of two-tuples, or a {callable:int} dict, the task to be performed will be picked randomly, but each task will be weighted according to its corresponding int value. So in the following case, ThreadPage will be fifteen times more likely to be picked than write_post:

class ForumPage(TaskSet):
    tasks = {ThreadPage:15, write_post:1}
property user

User instance that this TaskSet was created by

wait()[source]

Make the running user sleep for a duration defined by the Locust.wait_time function (or TaskSet.wait_time function if it’s been defined).

The user can also be killed gracefully while it’s sleeping, so calling this method within a task makes it possible for a user to be killed mid-task, even if you’ve set a stop_timeout. If this behaviour is not desired you should make the user wait using gevent.sleep() instead.

wait_time()[source]

Method that returns the time (in seconds) between the execution of tasks.

Example:

from locust import TaskSet, between
class Tasks(TaskSet):
    wait_time = between(3, 25)

task decorator

task(weight=1)[source]

Used as a convenience decorator to be able to declare tasks for a User or a TaskSet inline in the class. Example:

class ForumPage(TaskSet):
    @task(100)
    def read_thread(self):
        pass

    @task(7)
    def create_thread(self):
        pass

    @task(25)
    class ForumThread(TaskSet):
        @task
        def get_author(self):
            pass

        @task
        def get_created(self):
            pass

tag decorator

tag(*tags)[source]

Decorator for tagging tasks and TaskSets with the given tag name. You can then limit the test to only execute tasks that are tagged with any of the tags provided by the --tags command-line argument. Example:

class ForumPage(TaskSet):
    @tag('thread')
    @task(100)
    def read_thread(self):
        pass

    @tag('thread')
    @tag('post')
    @task(7)
    def create_thread(self):
        pass

    @tag('post')
    @task(11)
    def comment(self):
        pass

SequentialTaskSet class

class SequentialTaskSet(*args, **kwargs)[source]

Class defining a sequence of tasks that a User will execute.

Works like TaskSet, but task weight is ignored, and all tasks are executed in order. Tasks can either be specified by setting the tasks attribute to a list of tasks, or by declaring tasks as methods using the @task decorator. The order of declaration decides the order of execution.

It’s possible to combine a task list in the tasks attribute, with some tasks declared using the @task decorator. The order of declaration is respected also in that case.

property client

Shortcut to the client client attribute of this TaskSet’s User

interrupt(reschedule=True)

Interrupt the TaskSet and hand over execution control back to the parent TaskSet.

If reschedule is True (default), the parent User will immediately re-schedule, and execute, a new task.

on_start()

Called when a User starts executing this TaskSet

on_stop()

Called when a User stops executing this TaskSet. E.g. when TaskSet.interrupt() is called or when the User is killed

property parent

Parent TaskSet instance of this TaskSet (or User if this is not a nested TaskSet)

schedule_task(task_callable, first=False)

Add a task to the User’s task execution queue.

Parameters
  • task_callable – User task to schedule.

  • first – Optional keyword argument. If True, the task will be put first in the queue.

property user

User instance that this TaskSet was created by

wait_time()

Method that returns the time (in seconds) between the execution of tasks.

Example:

from locust import TaskSet, between
class Tasks(TaskSet):
    wait_time = between(3, 25)

Built in wait_time functions

between(min_wait, max_wait)

Returns a function that will return a random number between min_wait and max_wait.

Example:

class MyUser(User):
    # wait between 3.0 and 10.5 seconds after each task
    wait_time = between(3.0, 10.5)
constant(wait_time)

Returns a function that just returns the number specified by the wait_time argument

Example:

class MyUser(User):
    wait_time = constant(3)
constant_pacing(wait_time)

Returns a function that will track the run time of the tasks, and for each time it’s called it will return a wait time that will try to make the total time between task execution equal to the time specified by the wait_time argument.

In the following example the task will always be executed once every 10 seconds, no matter the task execution time:

class MyUser(User):
    wait_time = constant_pacing(10)
    @task
    def my_task(self):
        time.sleep(random.random())

If a task execution exceeds the specified wait_time, the wait will be 0 before starting the next task.

constant_throughput(task_runs_per_second)

Returns a function that will track the run time of the tasks, and for each time it’s called it will return a wait time that will try to make the number of task runs per second execution equal to the time specified by the task_runs_per_second argument.

If you have multiple requests in a task your RPS will of course be higher than the specified throughput.

This is the mathematical inverse of constant_pacing.

In the following example the task will always be executed once every 10 seconds, no matter the task execution time:

class MyUser(User):
    wait_time = constant_throughput(0.1)
    @task
    def my_task(self):
        time.sleep(random.random())

If a task execution exceeds the specified wait_time, the wait will be 0 before starting the next task.

HttpSession class

class HttpSession(base_url, request_event, user, *args, pool_manager=None, **kwargs)[source]

Class for performing web requests and holding (session-) cookies between requests (in order to be able to log in and out of websites). Each request is logged so that locust can display statistics.

This is a slightly extended version of python-request’s requests.Session class and mostly this class works exactly the same. However the methods for making requests (get, post, delete, put, head, options, patch, request) can now take a url argument that’s only the path part of the URL, in which case the host part of the URL will be prepended with the HttpSession.base_url which is normally inherited from a User class’ host attribute.

Each of the methods for making requests also takes two additional optional arguments which are Locust specific and doesn’t exist in python-requests. These are:

Parameters
  • name – (optional) An argument that can be specified to use as label in Locust’s statistics instead of the URL path. This can be used to group different URL’s that are requested into a single entry in Locust’s statistics.

  • catch_response – (optional) Boolean argument that, if set, can be used to make a request return a context manager to work as argument to a with statement. This will allow the request to be marked as a fail based on the content of the response, even if the response code is ok (2xx). The opposite also works, one can use catch_response to catch a request and then mark it as successful even if the response code was not (i.e 500 or 404).

__init__(base_url, request_event, user, *args, pool_manager=None, **kwargs)[source]
delete(url, **kwargs)

Sends a DELETE request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

get(url, **kwargs)

Sends a GET request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

head(url, **kwargs)

Sends a HEAD request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

options(url, **kwargs)

Sends a OPTIONS request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

patch(url, data=None, **kwargs)

Sends a PATCH request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

post(url, data=None, json=None, **kwargs)

Sends a POST request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

put(url, data=None, **kwargs)

Sends a PUT request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

request(method, url, name=None, catch_response=False, context={}, **kwargs)[source]

Constructs and sends a requests.Request. Returns requests.Response object.

Parameters
  • method – method for the new Request object.

  • url – URL for the new Request object.

  • name – (optional) An argument that can be specified to use as label in Locust’s statistics instead of the URL path. This can be used to group different URL’s that are requested into a single entry in Locust’s statistics.

  • catch_response – (optional) Boolean argument that, if set, can be used to make a request return a context manager to work as argument to a with statement. This will allow the request to be marked as a fail based on the content of the response, even if the response code is ok (2xx). The opposite also works, one can use catch_response to catch a request and then mark it as successful even if the response code was not (i.e 500 or 404).

  • params – (optional) Dictionary or bytes to be sent in the query string for the Request.

  • data – (optional) Dictionary or bytes to send in the body of the Request.

  • headers – (optional) Dictionary of HTTP Headers to send with the Request.

  • cookies – (optional) Dict or CookieJar object to send with the Request.

  • files – (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.

  • auth – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.

  • timeout (float or tuple) – (optional) How long in seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.

  • allow_redirects (bool) – (optional) Set to True by default.

  • proxies – (optional) Dictionary mapping protocol to the URL of the proxy.

  • stream – (optional) whether to immediately download the response content. Defaults to False.

  • verify – (optional) if True, the SSL cert will be verified. A CA_BUNDLE path can also be provided.

  • cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Response class

This class actually resides in the requests library, since that’s what Locust is using to make HTTP requests, but it’s included in the API docs for locust since it’s so central when writing locust load tests. You can also look at the Response class at the requests documentation.

class Response[source]

The Response object, which contains a server’s response to an HTTP request.

property apparent_encoding

The apparent encoding, provided by the charset_normalizer or chardet libraries.

close()[source]

Releases the connection back to the pool. Once this method has been called the underlying raw object must not be accessed again.

Note: Should not normally need to be called explicitly.

property content

Content of the response, in bytes.

cookies

A CookieJar of Cookies the server sent back.

elapsed

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.

encoding

Encoding to decode with when accessing r.text.

headers

Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.

history

A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.

property is_permanent_redirect

True if this Response one of the permanent versions of redirect.

property is_redirect

True if this Response is a well-formed HTTP redirect that could have been processed automatically (by Session.resolve_redirects()).

iter_content(chunk_size=1, decode_unicode=False)[source]

Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.

chunk_size must be of type int or None. A value of None will function differently depending on the value of stream. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk.

If decode_unicode is True, content will be decoded using the best available encoding based on the response.

iter_lines(chunk_size=512, decode_unicode=False, delimiter=None)[source]

Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.

Note

This method is not reentrant safe.

json(**kwargs)[source]

Returns the json-encoded content of a response, if any.

Parameters

**kwargs – Optional arguments that json.loads takes.

Raises

requests.exceptions.JSONDecodeError – If the response body does not contain valid json.

property links

Returns the parsed header links of the response, if any.

property next

Returns a PreparedRequest for the next request in a redirect chain, if there is one.

property ok

Returns True if status_code is less than 400, False if not.

This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK.

raise_for_status()[source]

Raises HTTPError, if one occurred.

raw

File-like object representation of response (for advanced usage). Use of raw requires that stream=True be set on the request. This requirement does not apply for use internally to Requests.

reason

Textual reason of responded HTTP Status, e.g. “Not Found” or “OK”.

request

The PreparedRequest object to which this is a response.

status_code

Integer Code of responded HTTP Status, e.g. 404 or 200.

property text

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using charset_normalizer or chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

url

Final URL location of Response.

ResponseContextManager class

class ResponseContextManager(response, request_event, request_meta)[source]

A Response class that also acts as a context manager that provides the ability to manually control if an HTTP request should be marked as successful or a failure in Locust’s statistics

This class is a subclass of Response with two additional methods: success and failure.

failure(exc)[source]

Report the response as a failure.

if exc is anything other than a python exception (like a string) it will be wrapped inside a CatchResponseError.

Example:

with self.client.get("/", catch_response=True) as response:
    if response.content == b"":
        response.failure("No data")
success()[source]

Report the response as successful

Example:

with self.client.get("/does/not/exist", catch_response=True) as response:
    if response.status_code == 404:
        response.success()

Exceptions

exception InterruptTaskSet(reschedule=True)[source]

Exception that will interrupt a User when thrown inside a task

exception RescheduleTask[source]

When raised in a task it’s equivalent of a return statement.

Also used internally by TaskSet. When raised within the task control flow of a TaskSet, but not inside a task, the execution should be handed over to the parent TaskSet.

exception RescheduleTaskImmediately[source]

When raised in a User task, another User task will be rescheduled immediately (without calling wait_time first)

Environment class

class Environment(*, user_classes=None, shape_class=None, tags=None, locustfile=None, exclude_tags=None, events=None, host=None, reset_stats=False, stop_timeout=None, catch_exceptions=True, parsed_options=None, available_user_classes=None, available_shape_classes=None, available_user_tasks=None, dispatcher_class=<class 'locust.dispatch.UsersDispatcher'>)[source]
assign_equal_weights()[source]

Update the user classes such that each user runs their specified tasks with equal probability.

available_shape_classes

List of the available Shape Classes to pick from in the ShapeClass Picker

available_user_classes

List of the available User Classes to pick from in the UserClass Picker

available_user_tasks

List of the available Tasks per User Classes to pick from in the Task Picker

catch_exceptions

If True exceptions that happen within running users will be caught (and reported in UI/console). If False, exceptions will be raised.

create_local_runner()[source]

Create a LocalRunner instance for this Environment

create_master_runner(master_bind_host='*', master_bind_port=5557)[source]

Create a MasterRunner instance for this Environment

Parameters
  • master_bind_host – Interface/host that the master should use for incoming worker connections. Defaults to “*” which means all interfaces.

  • master_bind_port – Port that the master should listen for incoming worker connections on

create_web_ui(host='', port=8089, web_login=False, tls_cert=None, tls_key=None, stats_csv_writer=None, delayed_start=False, userclass_picker_is_active=False, modern_ui=False)[source]

Creates a WebUI instance for this Environment and start running the web server

Parameters
  • host – Host/interface that the web server should accept connections to. Defaults to “” which means all interfaces

  • port – Port that the web server should listen to

  • web_login – If provided, an authentication page will protect the app

  • tls_cert – An optional path (str) to a TLS cert. If this is provided the web UI will be served over HTTPS

  • tls_key – An optional path (str) to a TLS private key. If this is provided the web UI will be served over HTTPS

  • stats_csv_writerStatsCSV <stats_csv.StatsCSV> instance.

  • delayed_start – Whether or not to delay starting web UI until start() is called. Delaying web UI start allows for adding Flask routes or Blueprints before accepting requests, avoiding errors.

create_worker_runner(master_host, master_port)[source]

Create a WorkerRunner instance for this Environment

Parameters
  • master_host – Host/IP of a running master node

  • master_port – Port on master node to connect to

dispatcher_class

A user dispatcher class that decides how users are spawned, default UsersDispatcher

events

Event hooks used by Locust internally, as well as to extend Locust’s functionality See Event hooks for available events.

exclude_tags

If set, only tasks that aren’t tagged by tags in this list will be executed. Leave this as None to use the one from parsed_options

host

Base URL of the target system

locustfile

Filename (not path) of locustfile

parsed_options

Reference to the parsed command line options (used to pre-populate fields in Web UI). When using Locust as a library, this should either be None or an object created by argument_parser.parse_args()

process_exit_code

If set it’ll be the exit code of the Locust process

reset_stats

Determines if stats should be reset once all simulated users have been spawned

runner

Reference to the Runner instance

shape_class

A shape class to control the shape of the load test

stats

Reference to RequestStats instance

tags

If set, only tasks that are tagged by tags in this list will be executed. Leave this as None to use the one from parsed_options

user_classes

User classes that the runner will run

web_ui

Reference to the WebUI instance

Event hooks

Locust provides event hooks that can be used to extend Locust in various ways.

The following event hooks are available under Environment.events, and there’s also a reference to these events under locust.events that can be used at the module level of locust scripts (since the Environment instance hasn’t been created when the locustfile is imported).

class Events[source]
cpu_warning

Fired when the CPU usage exceeds runners.CPU_WARNING_THRESHOLD (90% by default)

init

Fired when Locust is started, once the Environment instance and locust runner instance have been created. This hook can be used by end-users’ code to run code that requires access to the Environment. For example to register listeners to other events.

Event arguments:

Parameters

environment – Environment instance

init_command_line_parser

Event that can be used to add command line options to Locust

Event arguments:

Parameters

parser – ArgumentParser instance

quit

Fired after quitting events, just before process is exited.

Event arguments:

Parameters

exit_code – Exit code for process

quitting

Fired when the locust process is exiting.

Event arguments:

Parameters

environment – Environment instance

report_to_master

Used when Locust is running in –worker mode. It can be used to attach data to the dicts that are regularly sent to the master. It’s fired regularly when a report is to be sent to the master server.

Note that the keys “stats” and “errors” are used by Locust and shouldn’t be overridden.

Event arguments:

Parameters
  • client_id – The client id of the running locust process.

  • data – Data dict that can be modified in order to attach data that should be sent to the master.

request

Fired when a request in completed.

Event arguments:

Parameters
  • request_type – Request type method used

  • name – Path to the URL that was called (or override name if it was used in the call to the client)

  • response_time – Time in milliseconds until exception was thrown

  • response_length – Content-length of the response

  • response – Response object (e.g. a requests.Response)

  • contextUser/request context

  • exception – Exception instance that was thrown. None if request was successful.

If you want to simplify a custom client, you can have Locust measure the time for you by using measure()

reset_stats

Fired when the Reset Stats button is clicked in the web UI.

spawning_complete

Fired when all simulated users has been spawned.

Event arguments:

Parameters

user_count – Number of users that were spawned

test_start

Fired on each node when a new load test is started. It’s not fired again if the number of users change during a test.

test_stop

Fired on each node when a load test is stopped.

test_stopping

Fired on each node when a load test is about to stop - before stopping users.

user_error

Fired when an exception occurs inside the execution of a User class.

Event arguments:

Parameters
  • user_instance – User class instance where the exception occurred

  • exception – Exception that was thrown

  • tb – Traceback object (from e.__traceback__)

worker_connect

Fired on master when a new worker connects. Note that is fired immediately after the connection is established, so init event may not yet have finished on worker.

Parameters

client_id – Client id of the connected worker

worker_report

Used when Locust is running in –master mode and is fired when the master server receives a report from a Locust worker server.

This event can be used to aggregate data from the locust worker servers.

Event arguments:

Parameters
  • client_id – Client id of the reporting worker

  • data – Data dict with the data from the worker node

EventHook class

The event hooks are instances of the locust.events.EventHook class:

class EventHook[source]

Simple event class used to provide hooks for different types of events in Locust.

Here’s how to use the EventHook class:

my_event = EventHook()
def on_my_event(a, b, **kw):
    print("Event was fired with arguments: %s, %s" % (a, b))
my_event.add_listener(on_my_event)
my_event.fire(a="foo", b="bar")

If reverse is True, then the handlers will run in the reverse order that they were inserted

measure(request_type, name, response_length=0, context=None)[source]

Convenience method for firing the event with automatically calculated response time and automatically marking the request as failed if an exception is raised (this is really only useful for the request event)

Example usage (in a task):

with self.environment.events.request.measure(“myrequestType”, “myRequestName”) as request_meta:

# do the stuff you want to measure

You can optionally add/overwrite entries in the request_meta dict and they will be passed to the request event.

Experimental.

Note

It’s highly recommended that you add a wildcard keyword argument in your event listeners to prevent your code from breaking if new arguments are added in a future version.

Runner classes

class Runner(environment)[source]

Orchestrates the load test by starting and stopping the users.

Use one of the create_local_runner, create_master_runner or create_worker_runner methods on the Environment instance to create a runner of the desired type.

quit()[source]

Stop any running load test and kill all greenlets for the runner

stop()[source]

Stop a running load test by stopping all running users

property user_count
Returns

Number of currently running users

class LocalRunner(environment)[source]

Runner for running single process load test

class MasterRunner(environment, master_bind_host, master_bind_port)[source]

Runner used to run distributed load tests across multiple processes and/or machines.

MasterRunner doesn’t spawn any user greenlets itself. Instead it expects WorkerRunners to connect to it, which it will then direct to start and stop user greenlets. Stats sent back from the WorkerRunners will aggregated.

register_message(msg_type, listener)

Register a listener for a custom message from another node

Parameters
  • msg_type – The type of the message to listen for

  • listener – The function to execute when the message is received

send_message(msg_type, data=None, client_id=None)[source]

Sends a message to attached worker node(s)

Parameters
  • msg_type – The type of the message to send

  • data – Optional data to send

  • client_id – Optional id of the target worker node. If None, will send to all attached workers

class WorkerRunner(environment, master_host, master_port)[source]

Runner used to run distributed load tests across multiple processes and/or machines.

WorkerRunner connects to a MasterRunner from which it’ll receive instructions to start and stop user greenlets. The WorkerRunner will periodically take the stats generated by the running users and send back to the MasterRunner.

register_message(msg_type, listener)

Register a listener for a custom message from another node

Parameters
  • msg_type – The type of the message to listen for

  • listener – The function to execute when the message is received

send_message(msg_type, data=None, client_id=None)[source]

Sends a message to master node

Parameters
  • msg_type – The type of the message to send

  • data – Optional data to send

  • client_id – (unused)

Web UI class

class WebUI(environment, host, port, web_login=False, tls_cert=None, tls_key=None, stats_csv_writer=None, delayed_start=False, userclass_picker_is_active=False, modern_ui=False)[source]

Sets up and runs a Flask web app that can start and stop load tests using the environment.runner as well as show the load test statistics in environment.stats

app = None

Reference to the flask.Flask app. Can be used to add additional web routes and customize the Flask app in other various ways. Example:

from flask import request

@web_ui.app.route("/my_custom_route")
def my_custom_route():
    return "your IP is: %s" % request.remote_addr
auth_args

Arguments used to render auth.html for the web UI auth page. Must be used when configuring auth

auth_required_if_enabled(view_func)[source]

Decorator that can be used on custom route methods that will turn on Flask Login authentication if the --web-login flag is used. Example:

@web_ui.app.route("/my_custom_route")
@web_ui.auth_required_if_enabled
def my_custom_route():
    return "custom response"
greenlet = None

Greenlet of the running web server

server = None

Reference to the pyqsgi.WSGIServer instance

stop()[source]

Stop the running web server

template_args

Arguments used to render index.html for the web UI. Must be used with custom templates extending index.html.

Other

class LoadTestShape[source]

Base class for custom load shapes.

get_current_user_count()[source]

Returns current actual number of users from the runner

get_run_time()[source]

Calculates run time in seconds of the load test

reset_time()[source]

Resets start time back to 0

runner = None

Reference to the Runner instance

abstract tick()[source]

Returns a tuple with 2 elements to control the running load test:

user_count – Total user count spawn_rate – Number of users to start/stop per second when changing number of users user_classes – None or a List of userclasses to be spawned in it tick

If None is returned then the running load test will be stopped.

class RequestStats(use_response_times_cache=True)[source]

Class that holds the request statistics. Accessible in a User from self.environment.stats

get(name, method)[source]

Retrieve a StatsEntry instance by name and method

class StatsEntry(stats, name, method, use_response_times_cache=False)[source]

Represents a single stats entry (name and method)

run_single_user(user_class, include_length=False, include_time=False, include_context=False, include_payload=False, loglevel='WARNING')[source]

Runs a single User. Useful when you want to run a debugger.

It creates in a new locust Environment and triggers any init or test_start events as normal.

It does not trigger test_stop or quit when you quit the debugger.

It prints some info about every request to stdout, and you can get additional info using the include_* flags

It also initiates logging on WARNING level (not INFO, because it could interfere with the printing of requests), but you can change that by passing a log level (or disabling logging entirely by passing None)