Skip to content

API

User

Bases: ABC

Source code in src/aiolocust/__init__.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class User(ABC):
    host: str | None = None

    def __init__(self, runner: Runner | None = None) -> None:
        if runner and runner.host:
            self.host = runner.host
        self.runner: Runner = runner  # pyright: ignore[reportAttributeAccessIssue] # always set outside of unit testing
        self.running = True

    @abstractmethod
    def run(self) -> AbcCoroutine[Any, Any, None]: ...

    @asynccontextmanager
    async def cm(self) -> AsyncGenerator[None]:
        """Override this method if you need an async context manager around the run method"""
        yield

cm() async

Override this method if you need an async context manager around the run method

Source code in src/aiolocust/__init__.py
40
41
42
43
@asynccontextmanager
async def cm(self) -> AsyncGenerator[None]:
    """Override this method if you need an async context manager around the run method"""
    yield

datatypes

SafeCounter

A thread-safe counter.

Source code in src/aiolocust/datatypes.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class SafeCounter:
    """A thread-safe counter."""

    def __init__(self, limit: int | None = None) -> None:
        self.value = 0
        self.limit = limit if limit is not None else sys.maxsize
        self.lock = threading.Lock()

    def increment(self) -> bool:
        with self.lock:
            if self.value < self.limit:
                self.value += 1
                return False
            return True

mitmproxy_addon

dict_source(data)

We want nice double quotes

Source code in src/aiolocust/mitmproxy_addon.py
32
33
34
35
36
37
38
39
40
41
def dict_source(data: dict) -> str:
    """We want nice double quotes"""
    tokens = []
    for token in tokenize.generate_tokens(io.StringIO(repr(data)).readline):
        if token.type == tokenize.STRING:
            value = ast.literal_eval(token.string)
            if isinstance(value, str):
                token = token._replace(string=json.dumps(value, ensure_ascii=False))
        tokens.append(token)
    return tokenize.untokenize(tokens)

users

http

HttpUser

Bases: User

Base class for HTTP users.

Source code in src/aiolocust/users/http.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class HttpUser(User):
    """
    Base class for HTTP users.
    """

    session_kwargs: dict[str, Any] = {"timeout": aiohttp.ClientTimeout(60.0)}
    """
    Extra arguments to pass to aiohttp.ClientSession, e.g.
    ```python
    class TimeoutUser(HttpUser):
        session_kwargs = {
            "timeout": aiohttp.ClientTimeout(0.0001),
            "skip_auto_headers": {"User-Agent"},
        }
        ...
    ```
    """

    ssl_context: None | ssl.SSLContext = None
    """
    Used to create a custom TCPConnector for LocustClientSession,
    instead of having to pass `ssl=ssl_context` on each request.

    For example, to use OS-managed trust you could do something like this:
    ```python
    import truststore
    from aiolocust import HttpUser

    class MyUser(HttpUser):
        ssl_context = truststore.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)
        ...
    ```
    """

    client: LocustClientSession  # type: ignore[assignment] # always set in cm

    @asynccontextmanager
    async def cm(self) -> AsyncGenerator[None]:
        if aiolocust.config.connection_timings:
            trace_config = aiohttp.TraceConfig()
            trace_config.on_dns_resolvehost_start.append(dns_start)
            trace_config.on_dns_resolvehost_end.append(dns_end)
            trace_config.on_connection_create_start.append(connection_create_start)
            trace_config.on_connection_create_end.append(connection_create_end)
            trace_configs = [trace_config]
        else:
            trace_configs = None
        async with LocustClientSession(
            self.runner,
            self.host,
            connector=aiohttp.TCPConnector(ssl=self.ssl_context) if self.ssl_context else None,
            trace_configs=trace_configs,
            **self.session_kwargs,
        ) as self.client:
            yield
session_kwargs = {'timeout': aiohttp.ClientTimeout(60.0)} class-attribute instance-attribute

Extra arguments to pass to aiohttp.ClientSession, e.g.

class TimeoutUser(HttpUser):
    session_kwargs = {
        "timeout": aiohttp.ClientTimeout(0.0001),
        "skip_auto_headers": {"User-Agent"},
    }
    ...
ssl_context = None class-attribute instance-attribute

Used to create a custom TCPConnector for LocustClientSession, instead of having to pass ssl=ssl_context on each request.

For example, to use OS-managed trust you could do something like this:

import truststore
from aiolocust import HttpUser

class MyUser(HttpUser):
    ssl_context = truststore.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)
    ...

pw

LocustPage

A wrapper for the Playwright Page object to automatically generate OTel spans.

Source code in src/aiolocust/users/pw.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class LocustPage:
    """A wrapper for the Playwright Page object to automatically generate OTel spans."""

    def __init__(self, page: Page) -> None:
        self._page = page

    async def goto(self, url: str, **kwargs):
        with tracer.start_as_current_span("playwright.goto") as span:
            span.set_attribute("browser.url", url)
            try:
                result = await self._page.goto(url, **kwargs)
                # await events.request.fire(Request(url, 1, None))
            except Exception as e:
                span.record_exception(e)
                # await events.request.fire(Request(url, 1, e))
                raise
            return result

    async def click(self, selector: str, **kwargs):
        with tracer.start_as_current_span("playwright.click") as span:
            span.set_attribute("browser.selector", selector)
            try:
                result = await self._page.click(selector, **kwargs)
                # await events.request.fire(Request(selector, 1, None))
            except Exception as e:
                span.record_exception(e)
                # await events.request.fire(Request(selector, 1, e))
                raise
            return result

websocket

WebsocketUser

Bases: User

Websocket test cases are different: instead of providing the normal run() interface, subclasses typically implement these methods:

on_start() to establish the connection (if you need to do auth before connecting or some initial WS communication afterwards)

receive() to read messages received by the client

send() to send messages, or do anything else you like to do concurrently with the receive loop. It stops automatically (without logging a ConnectionClosed) if the connection is closed by the server.

The run() method ties these things together. Unlike other User classes you don't typically override it.

Source code in src/aiolocust/users/websocket.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
class WebsocketUser(User):
    """
    Websocket test cases are different: instead of providing the normal run() interface, subclasses typically implement these methods:

    on_start() to establish the connection (if you need to do auth before connecting or some initial WS communication afterwards)

    receive() to read messages received by the client

    send() to send messages, or do anything else you like to do concurrently with the receive loop.
    It stops automatically (without logging a ConnectionClosed) if the connection is closed by the server.

    The run() method ties these things together. Unlike other User classes you don't typically override it.
    """

    websocket: ClientConnection = None  # type: ignore # just ensure the attribute exists

    async def on_start(self) -> None:
        await self.connect()

    async def connect(
        self,
        url: str | None = None,
        ssl: SSLContext | None = None,
        additional_headers: dict | None = None,
        additional_attributes: Mapping[str, AnyValue] | None = None,
        **kwargs,
    ) -> None:
        url = url or self.host
        assert url, "No url specified"

        if self.websocket:
            self.websocket.transport.abort()
            await self.websocket.wait_closed()

        if not ssl and url.startswith("wss://"):
            ssl = truststore.SSLContext(PROTOCOL_TLS_CLIENT)
            ssl.check_hostname = False

        with tracer.start_as_current_span(
            "websocket.connect",
            kind=trace.SpanKind.CLIENT,
        ) as span:
            span.set_attribute("url.full", url)
            span.set_attribute("network.protocol.name", "websocket")
            if additional_attributes:
                span.set_attributes(additional_attributes)
            additional_headers = additional_headers or {}
            inject(additional_headers)
            self.websocket = await connect(
                url,
                additional_headers=additional_headers,
                ssl=ssl,
                **kwargs,
            )

    @abstractmethod
    async def receive(self) -> None: ...

    @abstractmethod
    async def send(self) -> None: ...

    # Wrappers made to ignore expected errors like assertions, response errors, etc. Like in Runner.user_loop()
    async def _receive(self) -> None:
        try:
            await self.receive()
        except EXPECTED_ERRORS:
            pass

    async def _send(self) -> None:
        try:
            await self.send()
        except EXPECTED_ERRORS:
            pass

    async def run(self) -> None:
        try:
            await self.on_start()
            assert self.websocket, "No websocket was created during on_start!"
            async with asyncio.TaskGroup() as group:
                tasks = [
                    group.create_task(self._receive()),
                    group.create_task(self._send()),
                ]
                if self.runner:
                    tasks.append(group.create_task(self.runner.wait_for_shutdown()))
                _, pending = await asyncio.wait(
                    tasks,
                    return_when=asyncio.FIRST_COMPLETED,
                )
                for task in pending:
                    task.cancel()
        finally:
            if self.websocket:
                await self.websocket.close()