API

Locust class

class Locust

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

The behaviour of this user is defined by the task_set attribute, which should point to a TaskSet class.

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 HttpLocust class.

task_set = None

TaskSet class that defines the execution behaviour of this locust

wait_time = None

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

Example:

from locust import Locust, between
class User(Locust):
    wait_time = between(3, 25)
weight = 10

Probability of locust being chosen. The higher the weight, the greater is the chance of it being chosen.

HttpLocust class

class HttpLocust

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

The behaviour of this user is defined by the task_set attribute, which should point to a TaskSet class.

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

client = None

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

TaskSet class

class TaskSet(parent)

Class defining a set of tasks that a Locust 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 it’s wait_time function. If no wait_time method has been declared on the TaskSet, it’ll call the wait_time function on the Locust 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 it scheduled to be executed, it will be instantiated and called from the current 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).

client

Reference to the client attribute of the root Locust instance.

interrupt(reschedule=True)

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

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

This method should not be called by the root TaskSet (the one that is immediately, attached to the Locust class’ task_set attribute), but rather in nested TaskSet classes further down the hierarchy.

locust = None

Will refer to the root Locust class instance when the TaskSet has been instantiated

parent = None

Will refer to the parent TaskSet, or Locust, class instance when the TaskSet has been instantiated. Useful for nested TaskSet classes.

schedule_task(task_callable, args=None, kwargs=None, first=False)

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

Arguments:

  • task_callable: Locust task to schedule
  • args: Arguments that will be passed to the task callable
  • kwargs: Dict of keyword arguments that will be passed to the task callable.
  • first: Optional keyword argument. If True, the task will be put first in the queue.
tasks = []

List with python callables that represents a locust user task.

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 it’s 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_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)

task decorator

task(weight=1)

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

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

TaskSequence class

class TaskSequence(parent)

Class defining a sequence of tasks that a Locust user will execute.

When a TaskSequence starts running, it will pick the task in index from the tasks attribute, execute it, and call its wait_function which will define a time to sleep for. This defaults to a uniformly distributed random number between min_wait and max_wait milliseconds. It will then schedule the index + 1 % len(tasks) task for execution and so on.

TaskSequence can be nested with TaskSet, which means that a TaskSequence’s tasks attribute can contain TaskSet instances as well as other TaskSequence instances. If the nested TaskSet is scheduled to be executed, it will be instantiated and called from the current 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).

In this class, tasks should be defined as a list, or simply define the tasks with the @seq_task decorator

client

Reference to the client attribute of the root Locust instance.

interrupt(reschedule=True)

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

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

This method should not be called by the root TaskSet (the one that is immediately, attached to the Locust class’ task_set attribute), but rather in nested TaskSet classes further down the hierarchy.

schedule_task(task_callable, args=None, kwargs=None, first=False)

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

Arguments:

  • task_callable: Locust task to schedule
  • args: Arguments that will be passed to the task callable
  • kwargs: Dict of keyword arguments that will be passed to the task callable.
  • first: Optional keyword argument. If True, the task will be put first in the queue.
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)

seq_task decorator

seq_task(order)

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

class NormalUser(TaskSequence):
    @seq_task(1)
    def login_first(self):
        pass

    @seq_task(2)
    @task(25) # You can also set the weight in order to execute the task for `weight` times one after another.
    def then_read_thread(self):
        pass

    @seq_task(3)
    def then_logout(self):
        pass

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 User(Locust):
    # 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 User(Locust):
    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 second, no matter the task execution time:

class User(Locust):
    wait_time = constant_pacing(1)
    class task_set(TaskSet):
        @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, *args, **kwargs)

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 Locust class’ host property.

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, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

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, **kwargs)

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 python-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

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

apparent_encoding

The apparent encoding, provided by the chardet library.

close()

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.

content

Content of the response, in bytes.

cookies = None

A CookieJar of Cookies the server sent back.

elapsed = None

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 = None

Encoding to decode with when accessing r.text.

headers = None

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

history = None

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.

is_permanent_redirect

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

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)

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)

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)

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

Parameters:**kwargs – Optional arguments that json.loads takes.
Raises:ValueError – If the response body does not contain valid json.
links

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

next

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

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()

Raises stored HTTPError, if one occurred.

raw = None

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 = None

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

request = None

The PreparedRequest object to which this is a response.

status_code = None

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

text

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using 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 = None

Final URL location of Response.

ResponseContextManager class

class ResponseContextManager(response)

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)

Report the response as a failure.

exc can be either a python exception, or a string in which case 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()

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()

InterruptTaskSet Exception

exception InterruptTaskSet(reschedule=True)

Exception that will interrupt a Locust when thrown inside a task

Event hooks

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

class EventHook

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 += 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

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.

Available hooks

The following event hooks are available under the locust.events module:

request_success = <locust.events.EventHook object>

request_success is fired when a request is completed successfully.

Listeners should take the following arguments:

  • 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: Response time in milliseconds
  • response_length: Content-length of the response
request_failure = <locust.events.EventHook object>

request_failure is fired when a request fails

Event is fired with the following arguments:

  • 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
  • exception: Exception instance that was thrown
locust_error = <locust.events.EventHook object>

locust_error is fired when an exception occurs inside the execution of a Locust class.

Event is fired with the following arguments:

  • locust_instance: Locust class instance where the exception occurred
  • exception: Exception that was thrown
  • tb: Traceback object (from sys.exc_info()[2])
report_to_master = <locust.events.EventHook object>

report_to_master is used when Locust is running in –slave 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 is fired with the following arguments:

  • 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.
slave_report = <locust.events.EventHook object>

slave_report is used when Locust is running in –master mode and is fired when the master server receives a report from a Locust slave server.

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

Event is fired with following arguments:

  • client_id: Client id of the reporting locust slave
  • data: Data dict with the data from the slave node
hatch_complete = <locust.events.EventHook object>

hatch_complete is fired when all locust users has been spawned.

Event is fire with the following arguments:

  • user_count: Number of users that was hatched
quitting = <locust.events.EventHook object>

quitting is fired when the locust process is exiting