Skip to content

API

HttpUser

Bases: User

Source code in src/aiolocust/users/http.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class HttpUser(User):
    session_kwargs: dict[str, Any] = {}
    """
    Extra arguments to pass to aiohttp.ClientSession, e.g.
    ```
    class TimeoutUser(HttpUser):
        session_kwargs = {
            "timeout": aiohttp.ClientTimeout(0.0001),
            "skip_auto_headers": {"User-Agent"},
        }
        ...
    ```
    """

    def __init__(self, runner: Runner | None = None, base_url=None):
        super().__init__(runner)
        self.base_url = base_url
        self.client: LocustClientSession  # type: ignore[assignment] # always set in cm

    @asynccontextmanager
    async def cm(self):
        async with LocustClientSession(self.runner, self.base_url, **self.session_kwargs) as self.client:
            yield

session_kwargs = {} 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"},
    }
    ...

User

Bases: ABC

Source code in src/aiolocust/__init__.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class User(ABC):
    def __init__(self, runner: Runner | None = None, **kwargs):
        self.runner: Runner = runner  # pyright: ignore[reportAttributeAccessIssue] # always set outside of unit testing
        self.running = True

    @abstractmethod
    async def run(self): ...

    @asynccontextmanager
    async def cm(self):
        """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
13
14
15
16
@asynccontextmanager
async def cm(self):
    """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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class SafeCounter:
    """A thread-safe counter."""

    def __init__(self, limit: int | 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

main

is_user_class(item)

Check if a variable is a runnable (non-abstract) User class

Source code in src/aiolocust/main.py
34
35
36
37
38
def is_user_class(item) -> bool:
    """
    Check if a variable is a runnable (non-abstract) User class
    """
    return bool(inspect.isclass(item)) and issubclass(item, User) and not inspect.isabstract(item)

users

http

HttpUser

Bases: User

Source code in src/aiolocust/users/http.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class HttpUser(User):
    session_kwargs: dict[str, Any] = {}
    """
    Extra arguments to pass to aiohttp.ClientSession, e.g.
    ```
    class TimeoutUser(HttpUser):
        session_kwargs = {
            "timeout": aiohttp.ClientTimeout(0.0001),
            "skip_auto_headers": {"User-Agent"},
        }
        ...
    ```
    """

    def __init__(self, runner: Runner | None = None, base_url=None):
        super().__init__(runner)
        self.base_url = base_url
        self.client: LocustClientSession  # type: ignore[assignment] # always set in cm

    @asynccontextmanager
    async def cm(self):
        async with LocustClientSession(self.runner, self.base_url, **self.session_kwargs) as self.client:
            yield
session_kwargs = {} 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"},
    }
    ...

request_hook(span, params)

Request hook for renaming spans based on name parameter (passed via context vars)

Typical usage:

AioHttpClientInstrumentor().instrument(request_hook=aiolocust.users.http.request_hook)
Source code in src/aiolocust/users/http.py
114
115
116
117
118
119
120
121
122
123
124
125
def request_hook(span: Span, params: aiohttp.TraceRequestStartParams):  # noqa: ARG001
    """
    Request hook for renaming spans based on name parameter (passed via context vars)

    Typical usage:

    ```
    AioHttpClientInstrumentor().instrument(request_hook=aiolocust.users.http.request_hook)
    ```
    """
    if custom_name := context.get_value(SPAN_NAME_KEY):
        span.update_name(str(custom_name))

pw

LocustPage

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

Source code in src/aiolocust/users/pw.py
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
class LocustPage:
    """A wrapper for the Playwright Page object to automatically generate OTel spans."""

    def __init__(self, page: Page):
        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)
                stats.request(Request(url, 1, 1, None))
            except Exception as e:
                span.record_exception(e)
                stats.request(Request(url, 1, 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)
                stats.request(Request(selector, 1, 1, None))
            except Exception as e:
                span.record_exception(e)
                stats.request(Request(selector, 1, 1, e))
                raise
            return result