repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
locust | locust/test/test_tags.py | .py | from locust import TaskSet, User, tag, task
from locust.env import Environment
from locust.user.task import filter_tasks_by_tags
from .testcases import LocustTestCase
class TestTags(LocustTestCase):
def test_tagging(self):
@tag("tag1")
@task
def tagged():
pass
self.as... | 441 | 13,138 |
locust | locust/test/mock_logging.py | .py | from __future__ import annotations
import logging
from types import TracebackType
LogMessage = list[str | dict[str, TracebackType]]
class MockedLoggingHandler(logging.Handler):
debug: list[LogMessage] = []
warning: list[LogMessage] = []
info: list[LogMessage] = []
error: list[LogMessage] = []
cr... | 28 | 775 |
locust | locust/test/test_markov_taskset.py | .py | from locust import User, tag
from locust.exception import RescheduleTask
from locust.user.markov_taskset import (
InvalidTransitionError,
MarkovTaskSet,
MarkovTaskTagError,
NoMarkovTasksError,
NonMarkovTaskTransitionError,
transition,
transitions,
)
import random
from .testcases import Loc... | 229 | 7,046 |
locust | locust/test/subprocess_utils.py | .py | import os
import shlex
import signal
import subprocess
import time
from typing import IO
import gevent
import pytest
from .util import IS_WINDOWS
class TestProcess:
"""
Wraps a subprocess for testing purposes.
"""
__test__ = False
def __init__(
self,
command: str,
*,
... | 184 | 5,763 |
locust | locust/test/test_log.py | .py | from locust import log
from locust.log import greenlet_exception_logger
import re
import socket
import subprocess
import textwrap
from logging import getLogger
from unittest import mock
import gevent
from . import changed_rlimit
from .testcases import LocustTestCase
from .util import temporary_file
HOSTNAME = re.su... | 241 | 7,509 |
locust | locust/test/test_load_locustfile.py | .py | from locust import main
from locust.argument_parser import get_parser
from locust.main import create_environment
from locust.user import HttpUser, TaskSet, User
from locust.user.users import PytestUser
from locust.util.load_locustfile import is_user_class
import filecmp
import os
import textwrap
from .mock_locustfile... | 268 | 9,964 |
locust | locust/test/test_fasthttp.py | .py | from locust import FastHttpUser
from locust.contrib.fasthttp import FastHttpSession
from locust.exception import CatchResponseError, InterruptTaskSet, LocustError, ResponseError
from locust.user import TaskSet, task
from locust.util.load_locustfile import is_user_class
import socket
import time
from tempfile import Na... | 842 | 32,474 |
locust | locust/test/test_stats.py | .py | import locust
from locust import HttpUser, TaskSet, User, __version__, constant, task
from locust.env import Environment
from locust.rpc.protocol import Message
from locust.stats import (
PERCENTILES_TO_REPORT,
STATS_NAME_WIDTH,
STATS_TYPE_WIDTH,
CachedResponseTimes,
RequestStats,
StatsCSVFileWr... | 1,044 | 41,368 |
locust | locust/test/test_date.py | .py | from locust.util.date import format_duration, format_safe_timestamp, format_utc_timestamp
from datetime import datetime
import pytest
dates_checks = [
{
"datetime": datetime(2023, 10, 1, 12, 0, 0),
"utc_timestamp": "2023-10-01T10:00:00Z",
"safe_timestamp": "2023-10-01-12h00",
"dur... | 90 | 2,911 |
locust | locust/test/test_interruptable_task.py | .py | from locust import SequentialTaskSet, User, constant, task
from locust.env import Environment
from locust.exception import StopUser
from collections import defaultdict
from unittest import TestCase
class InterruptableTaskSet(SequentialTaskSet):
counter: defaultdict[str, int] = defaultdict(int)
def on_start(... | 49 | 1,377 |
locust | locust/test/test_html_filename.py | .py | from locust.html import process_html_filename
import unittest
from unittest.mock import MagicMock
class TestProcessHtmlFilename(unittest.TestCase):
def test_process_html_filename(self):
mock_options = MagicMock()
mock_options.num_users = 100
mock_options.spawn_rate = 10
mock_optio... | 55 | 1,845 |
locust | locust/test/testcases.py | .py | import locust
from locust import log
from locust.env import Environment
from locust.event import Events
from locust.test.mock_logging import MockedLoggingHandler
from locust.test.util import clear_all_functools_lru_cache
import base64
import logging
import random
import sys
import unittest
import warnings
from io impo... | 249 | 6,961 |
locust | locust/test/util.py | .py | from locust.argument_parser import get_locustfiles_locally, parse_locustfile_option
import datetime
import functools
import gc
import os
import socket
import time
import warnings
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
import requests
from cryptography import x509
from cryptograp... | 111 | 3,324 |
locust | locust/test/mock_locustfile.py | .py | import os
import random
import time
from contextlib import contextmanager
MOCK_LOCUSTFILE_CONTENT = '''
"""This is a mock locust file for unit testing"""
from locust import HttpUser, TaskSet, task, constant, LoadTestShape
def index(l):
l.client.get("/")
def stats(l):
l.client.get("/stats/requests")
class... | 57 | 1,270 |
locust | locust/test/__init__.py | .py | try:
import resource
# work around occasional "zmq.error.ZMQError: Too many open files"
# this is done in main.py when running locust proper so we need to do it here as well
resource.setrlimit(
resource.RLIMIT_NOFILE,
(
10000,
resource.RLIM_INFINITY,
),
... | 21 | 508 |
locust | locust/test/test_util.py | .py | from locust.util.rounding import proper_round
from locust.util.timespan import parse_timespan
from locust.util.url import is_url
import unittest
class TestParseTimespan(unittest.TestCase):
def test_parse_timespan_invalid_values(self):
self.assertRaises(ValueError, parse_timespan, None)
self.asser... | 57 | 2,434 |
locust | locust/test/test_web.py | .py | from __future__ import annotations
import locust
from locust import LoadTestShape, constant, stats
from locust.argument_parser import get_parser
from locust.env import Environment
from locust.log import LogReader
from locust.runners import Runner
from locust.stats import StatsCSVFileWriter
from locust.user import User... | 1,339 | 50,710 |
locust | locust/test/test_runners.py | .py | from __future__ import annotations
import locust
from locust import LoadTestShape, __version__, constant, runners
from locust.argument_parser import get_parser
from locust.dispatch import UsersDispatcher
from locust.env import Environment
from locust.exception import RPCError, RPCReceiveError, StopUser
from locust.log... | 4,508 | 170,979 |
locust | locust/test/test_parser.py | .py | import locust
from locust.argument_parser import (
get_parser,
parse_locustfile_paths,
ui_extra_args_dict,
)
import os
import unittest
from io import StringIO
from tempfile import NamedTemporaryFile, TemporaryDirectory
from unittest import mock
from .mock_locustfile import mock_locustfile
from .testcases ... | 454 | 18,213 |
locust | locust/test/test_users.py | .py | from locust import HttpUser, User
from locust.test.testcases import WebserverTestCase
import unittest
from urllib3 import PoolManager
class TestUserClass(unittest.TestCase):
class MyClassScopedUser(User):
pass
def test_fullname_module_scoped(self):
self.assertEqual(MyModuleScopedUser.fullna... | 70 | 2,135 |
locust | locust/test/test_sequential_taskset.py | .py | from locust import User, task
from locust.exception import RescheduleTask
from locust.user.sequential_taskset import SequentialTaskSet
from .testcases import LocustTestCase
class TestTaskSet(LocustTestCase):
def setUp(self):
super().setUp()
class MyUser(User):
host = "127.0.0.1"
... | 158 | 3,890 |
locust | locust/test/test_dispatch.py | .py | from __future__ import annotations
from locust import User
from locust.dispatch import UsersDispatcher
from locust.runners import WorkerNode
from locust.test.util import clear_all_functools_lru_cache
import math
import time
import unittest
from operator import attrgetter
_TOLERANCE = 0.025
class TestRampUpUsersFro... | 4,171 | 168,856 |
locust | locust/test/test_http.py | .py | from locust.clients import HttpSession
from locust.exception import LocustError
from locust.user.users import HttpUser
import time
import urllib3
from requests.exceptions import InvalidSchema, InvalidURL, MissingSchema, RequestException
from urllib3.exceptions import SSLError
from .testcases import WebserverTestCase... | 333 | 12,679 |
locust | locust/test/test_csv_request_logger.py | .py | """Tests for locust.contrib.csv_request_logger."""
from locust.contrib.csv_request_logger import CSV_COLUMNS, CsvRequestLogger, _status_code
from locust.env import Environment
import csv
import os
import tempfile
import unittest
from unittest.mock import MagicMock
def _make_environment() -> Environment:
return ... | 190 | 5,913 |
locust | locust/test/test_debugging.py | .py | from locust import debug, task
from locust.test.testcases import LocustTestCase
from locust.user.task import LOCUST_STATE_STOPPING
from locust.user.users import HttpUser
import os
from threading import Timer
from unittest import mock
class DebugTestCase(LocustTestCase):
def setUp(self):
super().setUp()
... | 40 | 1,053 |
locust | locust/test/test_socketio.py | .py | from locust.contrib.socketio import SocketIOUser
import time
from unittest.mock import patch
import socketio
from .testcases import LocustTestCase
class TestSocketIOUser(LocustTestCase):
def test_everything(self):
def connect(self, *args, **kwargs): ...
def emit(self, *args, **kwargs): ...
... | 35 | 1,552 |
locust | locust/test/test_pytest_locustfile.py | .py | # pytest style locustfiles, can be run from both pytest and locust!
#
# Example use:
#
# locust -H https://locust.io -f test_pytest.py -u 2 test_regular test_host
# pytest -H https://locust.io test_pytest.py
from locust.clients import HttpSession
from locust.contrib.fasthttp import FastHttpSession
from locust.exceptio... | 65 | 2,461 |
locust | locust/test/test_main.py | .py | from __future__ import annotations
import json
import os
import platform
import socket
import subprocess
import sys
import tempfile
import textwrap
import unittest
from tempfile import TemporaryDirectory
from unittest import TestCase
import gevent
import psutil
import requests
from pyquery import PyQuery as pq
from ... | 1,765 | 72,395 |
locust | locust/test/test_locust_class.py | .py | from locust import HttpUser, TaskSet, User, constant, task
from locust.env import Environment
from locust.exception import (
CatchResponseError,
InterruptTaskSet,
RescheduleTask,
RescheduleTaskImmediately,
ResponseError,
StopUser,
)
import gevent
from gevent import sleep
from gevent.pool import... | 834 | 25,526 |
locust | locust/test/test_env.py | .py | from locust import (
constant,
)
from locust.dispatch import UsersDispatcher
from locust.env import Environment, LoadTestShape
from locust.user import (
User,
task,
)
from locust.user.task import TaskSet
from .fake_module1_for_env_test import MyUserWithSameName as MyUserWithSameName1
from .fake_module2_for... | 284 | 8,919 |
locust | locust/test/test_zmqrpc.py | .py | from locust.exception import RPCError, RPCSendError
from locust.rpc import Message, zmqrpc
from locust.test.testcases import LocustTestCase
from time import sleep
import zmq
class ZMQRPC_tests(LocustTestCase):
def setUp(self):
super().setUp()
self.server = zmqrpc.Server("*", 0)
self.clie... | 59 | 2,156 |
locust | locust/test/test_taskratio.py | .py | from locust.user import TaskSet, User, task
from locust.user.inspectuser import _get_task_ratio, get_ratio
import unittest
class TestTaskRatio(unittest.TestCase):
def test_task_ratio_command(self):
class Tasks(TaskSet):
@task
def root_task1(self):
pass
... | 95 | 2,742 |
locust | locust/test/test_wait_time.py | .py | from locust import TaskSet, User, between, constant, constant_throughput
import random
import time
from .testcases import LocustTestCase
class TestWaitTime(LocustTestCase):
def test_between(self):
class MyUser(User):
wait_time = between(3, 9)
class TaskSet1(TaskSet):
pas... | 79 | 2,303 |
locust | locust/contrib/mqtt.py | .py | from __future__ import annotations
from locust import User
from locust.env import Environment
import random
import selectors
import time
import typing
from contextlib import suppress
import paho.mqtt.client as mqtt
from paho.mqtt.enums import MQTTErrorCode
if typing.TYPE_CHECKING:
from paho.mqtt.client import M... | 558 | 19,345 |
locust | locust/contrib/qdrant.py | .py | from locust import User, events
import time
from typing import Any
from qdrant_client import QdrantClient
from qdrant_client.models import VectorParams
class QdrantLocustClient:
"""Qdrant Client Wrapper"""
def __init__(self, url, collection_name, api_key=None, timeout=60, **kwargs):
self.url = url
... | 240 | 7,255 |
locust | locust/contrib/oai.py | .py | # Note: this User is experimental and may change without notice.
# The filename is oai.py so it doesnt clash with the openai package.
from locust.user import User
import os
import time
from collections.abc import Generator
from contextlib import contextmanager
import httpx
from openai import OpenAI # dont forget to ... | 70 | 2,431 |
locust | locust/contrib/postgres.py | .py | from locust import User, events
import time
import psycopg
class PostgresClient:
def __init__(self, conn_string):
self.connection = psycopg.connect(conn_string)
def execute_query(self, query):
start_time = time.time()
try:
self.connection.execute(query)
respo... | 46 | 1,230 |
locust | locust/contrib/socketio.py | .py | from locust import User
from locust.event import EventHook
from typing import Any
import gevent
import socketio
class SocketIOClient(socketio.Client):
def __init__(self, request_event: EventHook, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request_event = request_event
def conn... | 100 | 3,236 |
locust | locust/contrib/milvus.py | .py | import gevent.monkey
gevent.monkey.patch_all()
import grpc.experimental.gevent as grpc_gevent
grpc_gevent.init_gevent()
from locust import User, events
import time
from abc import ABC, abstractmethod
from typing import Any
from pymilvus import CollectionSchema, MilvusClient
from pymilvus.milvus_client import Index... | 409 | 13,015 |
locust | locust/contrib/fasthttp.py | .py | from __future__ import annotations
from locust.exception import CatchResponseError, LocustError, ResponseError, StopTest
from locust.user import User
from locust.util.deprecation import DeprecatedFastHttpLocustClass as FastHttpLocust # noqa: F401
import json
import json as unshadowed_json # some methods take a name... | 805 | 32,568 |
locust | locust/contrib/mongodb.py | .py | from locust import User, events
import time
from pymongo import MongoClient
from pymongo.errors import PyMongoError
class MongoDBClient(MongoClient):
def __init__(self, conn_string, db_name):
super().__init__(conn_string)
self.db = self.client[db_name]
def execute_query(self, collection_nam... | 42 | 1,246 |
locust | locust/contrib/dns.py | .py | from locust import User
from locust.exception import LocustError
import time
from collections.abc import Callable
import dns.query
from dns.exception import DNSException
from dns.message import Message
class DNSClient:
def __init__(self, request_event):
self.request_event = request_event
def __geta... | 63 | 2,070 |
locust | locust/contrib/csv_request_logger.py | .py | """
Per-request CSV logger for Locust.
Hooks into the ``request`` event and appends one row per completed request to a
CSV file. Useful for post-run analysis that requires individual data-points
rather than the aggregated statistics provided by the built-in
``--csv`` flag.
Usage::
from locust import HttpUser, t... | 188 | 5,990 |
locust | locust/util/rounding.py | .py | def proper_round(val: int | float, digits=0) -> int | float:
float_val = float(val)
return round(float_val + 10 ** (-len(str(float_val)) - 1), digits)
| 4 | 159 |
locust | locust/util/date.py | .py | from datetime import datetime, timezone
def format_utc_timestamp(unix_timestamp):
return datetime.fromtimestamp(int(unix_timestamp), timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def format_safe_timestamp(unix_timestamp):
return datetime.fromtimestamp(int(unix_timestamp)).strftime("%Y-%m-%d-%Hh%M")
def for... | 24 | 833 |
locust | locust/util/exception_handler.py | .py | import logging
import time
logger = logging.getLogger(__name__)
def retry(delays=(1, 3, 5), exception=Exception):
def decorator(function):
def wrapper(*args, **kwargs):
cnt = 0
for delay in delays + (None,):
try:
return function(*args, **kwargs)... | 27 | 797 |
locust | locust/util/directory.py | .py | import os
def get_abspaths_in(path, extension=None):
return [
os.path.abspath(os.path.join(root, f))
for root, _dirs, fs in os.walk(path)
for f in fs
if os.path.isfile(os.path.join(root, f))
and (f.endswith(extension) or extension is None)
and not f.startswith("_")
... | 13 | 326 |
locust | locust/util/load_locustfile.py | .py | from __future__ import annotations
import importlib
import importlib.util
import inspect
import os
import sys
from ..shape import LoadTestShape
from ..user import User
from ..user.users import PytestUser
def is_user_class(item) -> bool:
"""
Check if a variable is a runnable (non-abstract) User class
"""... | 137 | 5,187 |
locust | locust/util/timespan.py | .py | import re
from datetime import timedelta
def parse_timespan(time_str) -> int:
"""
Parse a string representing a time span and return the number of seconds.
Valid formats are: 20, 20s, 3m, 2h, 1h20m, 3h30m10s, etc.
"""
if not time_str:
raise ValueError("Invalid time span format")
if re... | 25 | 1,016 |
locust | locust/util/url.py | .py | from urllib.parse import urlparse
def is_url(url: str) -> bool:
"""
Check if path is an url
"""
try:
result = urlparse(url)
return result.scheme in ("https", "http") and bool(result.netloc)
except ValueError:
return False
| 13 | 268 |
locust | locust/util/cache.py | .py | import functools
from time import time
def memoize(timeout, dynamic_timeout=False):
"""
Memoization decorator with support for timeout.
If dynamic_timeout is set, the cache timeout is doubled if the cached function
takes longer time to run than the timeout time
"""
cache = {"timeout": timeout... | 36 | 1,062 |
locust | locust/util/deprecation.py | .py | import warnings
# Show deprecation warnings
warnings.filterwarnings("always", category=DeprecationWarning, module="locust")
def check_for_deprecated_task_set_attribute(class_dict):
from locust.user.task import TaskSet
if "task_set" in class_dict:
task_set = class_dict["task_set"]
if issubcla... | 57 | 2,026 |
locust | locust/user/markov_taskset.py | .py | from locust.exception import LocustError
from locust.user.task import TaskSetMeta
from locust.user.users import TaskSet
import logging
import random
from collections.abc import Callable
MarkovTaskT = Callable[..., None]
class NoMarkovTasksError(LocustError):
"""Raised when a MarkovTaskSet class doesn't define a... | 323 | 11,779 |
locust | locust/user/sequential_taskset.py | .py | from locust.exception import LocustError
from itertools import cycle
from .task import TaskSet, TaskSetMeta
class SequentialTaskSetMeta(TaskSetMeta):
"""
Meta class for SequentialTaskSet. It's used to allow SequentialTaskSet classes to specify
task execution in both a list as the tasks attribute or usin... | 67 | 2,687 |
locust | locust/user/__init__.py | .py | __all__ = (
"HttpUser",
"tag",
"task",
"TaskSet",
"User",
)
from .task import TaskSet, tag, task
from .users import HttpUser, User
| 10 | 151 |
locust | locust/user/users.py | .py | from __future__ import annotations
from locust.clients import HttpSession
from locust.exception import CatchResponseError, StopTest, StopUser
from locust.user.task import (
LOCUST_STATE_RUNNING,
LOCUST_STATE_STOPPING,
LOCUST_STATE_WAITING,
DefaultTaskSet,
TaskSet,
get_tasks_from_base_classes,
)... | 312 | 11,471 |
locust | locust/user/wait_time.py | .py | import random
from collections.abc import Callable
from time import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from locust import User
def between(min_wait: float, max_wait: float) -> Callable[["User"], float]:
"""
Returns a function that will return a random number between min_wait and max_... | 87 | 2,875 |
locust | locust/user/inspectuser.py | .py | from __future__ import annotations
import inspect
from collections import defaultdict
from json import dumps
from .task import TaskSet
from .users import User
def print_task_ratio(user_classes, num_users, total):
"""
This function calculates the task ratio of users based on the user total count.
"""
... | 82 | 2,601 |
locust | locust/user/task.py | .py | from __future__ import annotations
from locust.exception import (
InterruptTaskSet,
MissingWaitTimeError,
RescheduleTask,
RescheduleTaskImmediately,
StopTest,
StopUser,
)
import logging
import random
import traceback
from collections import deque
from collections.abc import Callable
from time ... | 514 | 17,388 |
locust | locust/rpc/zmqrpc.py | .py | from locust.exception import RPCError, RPCReceiveError, RPCSendError
from locust.util.exception_handler import retry
import socket as csocket
from socket import gaierror, has_dualstack_ipv6
import msgpack.exceptions as msgerr
import zmq.error as zmqerr
import zmq.green as zmq
from .protocol import Message
class Ba... | 95 | 3,214 |
locust | locust/rpc/__init__.py | .py | __all__ = (
"Message",
"rpc",
)
from . import zmqrpc as rpc
from .protocol import Message
| 8 | 99 |
locust | locust/rpc/protocol.py | .py | from __future__ import annotations
import datetime
import msgpack
try:
from bson import ObjectId
except ImportError:
class ObjectId: # type: ignore
def __init__(self, s):
raise Exception("You need to install pymongo or at least bson to be able to send/receive ObjectIds")
def decode(ob... | 48 | 1,282 |
locust | benchmarks/dispatch.py | .py | """
This file contains a benchmark to validate the performance of Locust itself.
More precisely, the performance of the `UsersDispatcher` class which is responsible
for calculating the distribution of users on each worker. This benchmark is to be used
by people working on Locust's development.
"""
from locust import U... | 231 | 8,319 |
locust | docs/conf.py | .py | #
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are comment... | 195 | 6,138 |
locust | docs/_ext/llms_txt.py | .py | """Sphinx extension that generates llms.txt and llms-full.txt for AI consumption.
Generates an index file (llms.txt) and a full concatenated markdown file (llms-full.txt)
from the existing RST documentation during the HTML build, following the llmstxt.org
standard.
This extension uses ``sphinx_markdown_builder.transl... | 247 | 9,077 |
locust | examples/stop_on_threshold.py | .py | # An example of how to stop locust if a threshold (in this case the fail ratio) is exceeded
from locust import HttpUser, events, task
from locust.runners import STATE_CLEANUP, STATE_STOPPED, STATE_STOPPING, WorkerRunner
import time
import gevent
class MyUser(HttpUser):
host = "http://www.google.com"
@task
... | 36 | 1,041 |
locust | examples/openai_ex.py | .py | # You need to install the openai package and set OPENAI_API_KEY env var to run this
# OpenAIUser tracks the number of output tokens in the response_length field,
# because it is more useful than the actual payload size. This field is available to event handlers.
from locust import run_single_user, task
from locust.co... | 30 | 1,124 |
locust | examples/markov_taskset.py | .py | from locust import MarkovTaskSet, User, constant, transition, transitions
"""
This example demonstrates the different ways to specify transitions in a MarkovTaskSet.
The MarkovTaskSet class supports several ways to define transitions between tasks:
1. Using @transition decorator for a single transition
2. Stacking mu... | 62 | 2,307 |
locust | examples/bottlenecked_server.py | .py | """
This example uses extensions in Locust's own WebUI to simulate a bottlenecked server and runs a test against itself.
The purpose of this is mainly to generate nice graphs in the UI to teach new users how to interpret load test results.
See https://docs.locust.io/en/stable/quickstart.html#locust-s-web-interface
""... | 39 | 1,112 |
locust | examples/custom_wait_function.py | .py | from locust import HttpUser, TaskSet, task
import random
def index(l):
l.client.get("/")
def stats(l):
l.client.get("/stats/requests")
class UserTasks(TaskSet):
# one can specify tasks like this
tasks = [index, stats]
# but it might be convenient to use the @task decorator
@task
def ... | 57 | 1,369 |
locust | examples/debugging_advanced.py | .py | from locust import HttpUser, run_single_user, task
from locust.exception import StopUser
class User1(HttpUser):
host = "http://localhost"
@task
def hello_world(self):
with self.client.get("/hello1", catch_response=True) as resp:
pass
raise StopUser()
class User2(HttpUser):
... | 31 | 655 |
locust | examples/add_command_line_argument.py | .py | from locust import HttpUser, events, task
@events.init_command_line_parser.add_listener
def _(parser):
parser.add_argument("--my-argument", type=str, env_var="LOCUST_MY_ARGUMENT", default="", help="It's working")
# Choices will validate command line input and show a dropdown in the web UI
parser.add_argum... | 31 | 1,668 |
locust | examples/fast_http_locust.py | .py | from locust import FastHttpUser, task
class WebsiteUser(FastHttpUser):
"""
User class that does requests to the locust web server running on localhost,
using the fast HTTP client
"""
host = "http://127.0.0.1:8089"
# some things you can configure on FastHttpUser
# connection_timeout = 60.0... | 27 | 610 |
locust | examples/extend_web_ui.py | .py | """
This is an example of a locustfile that uses Locust's built in event and web
UI extension hooks to track the sum of the content-length header in all
successful HTTP responses and display them in the web UI.
"""
from locust import HttpUser, TaskSet, between, events, task
import json
import os
from time import time... | 161 | 5,142 |
locust | examples/multiple_hosts.py | .py | from locust import HttpUser, TaskSet, between, task
from locust.clients import HttpSession
import os
class MultipleHostsUser(HttpUser):
abstract = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.api_client = HttpSession(
base_url=os.environ["API_H... | 36 | 862 |
locust | examples/csrf_form_authentication.py | .py | from locust import HttpUser, between, task
import re
class WebsiteUser(HttpUser):
host = "http://127.0.0.1:8089"
wait_time = between(2, 5)
@task
def authenticate(self):
with self.client.get("/sign-in", catch_response=True) as response:
match = re.search(
r'<form.*... | 30 | 818 |
locust | examples/worker_index.py | .py | # How to use worker_index to read from a pre-partitioned CSV file (mythings_0.csv, mythings_1.csv, ...)
# so that each worker uses their own file
from locust import User, events, runners, task
from locust_plugins import csvreader # install locust-plugins first
class DemoUser(User):
reader: csvreader.CSVDictRead... | 21 | 644 |
locust | examples/response_validations.py | .py | """
This shows some useful ways to validate responses and how to exit tasks early on failure.
"""
from locust import FastHttpUser, events, run_single_user, task
from locust.exception import RescheduleTask
class BadUser(FastHttpUser):
@task
def t(self):
self.client.request("POST", "/authenticate", jso... | 74 | 2,651 |
locust | examples/use_as_lib.py | .py | #!/usr/bin/env python3
from locust import HttpUser, events, task
from locust.env import Environment
from locust.log import setup_logging
from locust.stats import stats_history, stats_printer
import gevent
setup_logging("INFO")
class MyUser(HttpUser):
host = "https://docs.locust.io"
@task
def t(self):
... | 47 | 1,111 |
locust | examples/testdata_management.py | .py | # This example shows the various ways to run things before/outside of the normal task execution flow,
# which is very useful for fetching test data.
#
# 1. Locustfile parse time
# 2. Locust start (init)
# 3. Test start
# 4. User start
# 5. Inside a task
# M1. CPU & memory usage
# M2. master sent heartbeat to worker 1-N... | 145 | 5,210 |
locust | examples/rest.py | .py | from locust import FastHttpUser, run_single_user, task
from locust.contrib.fasthttp import RestResponseContextManager
from locust.user.wait_time import constant
from collections.abc import Generator
from contextlib import contextmanager
class MyUser(FastHttpUser):
host = "https://postman-echo.com"
wait_time ... | 100 | 4,260 |
locust | examples/manual_stats_reporting.py | .py | """
Example of a manual_report() function that can be used either as a context manager
(with statement), or a decorator, to manually add entries to Locust's statistics.
Usage as a context manager:
with manual_report("stats entry name"):
# Run time of this block will be reported under a stats entry called ... | 79 | 2,127 |
locust | examples/browse_docs_sequence_test.py | .py | # This locust test script example will simulate a user
# browsing the Locust documentation on https://docs.locust.io/
from locust import HttpUser, SequentialTaskSet, between, task
import random
from pyquery import PyQuery
class BrowseDocumentationSequence(SequentialTaskSet):
def on_start(self):
self.ur... | 48 | 1,523 |
locust | examples/debugging.py | .py | from locust import HttpUser, run_single_user, task
class QuickstartUser(HttpUser):
host = "http://localhost"
@task
def hello_world(self):
with self.client.get("/hello", catch_response=True) as resp:
pass # maybe set a breakpoint here to analyze the resp object?
# if launched direct... | 16 | 445 |
locust | examples/open_closed_workload.py | .py | from locust import HttpUser, constant, constant_pacing, task
class ClosedWorkload(HttpUser):
wait_time = constant(10) # sleep 10s after each task, regardless of execution time
@task
def t(self):
pass
class OpenWorkload(HttpUser):
wait_time = constant_pacing(10) # sleep just enough so that... | 23 | 626 |
locust | examples/semaphore_wait.py | .py | from locust import HttpUser, events, task
from gevent.lock import Semaphore
all_users_spawned = Semaphore()
all_users_spawned.acquire()
@events.spawning_complete.add_listener
def on_spawning_complete(**kw):
all_users_spawned.release()
class WebsiteUser(HttpUser):
host = "http://127.0.0.1:8089"
def on... | 23 | 428 |
locust | examples/browse_docs_test.py | .py | # This locust test script example will simulate a user
# browsing the Locust documentation on https://docs.locust.io/
from locust import HttpUser, TaskSet, between, task
import random
from pyquery import PyQuery
class BrowseDocumentation(TaskSet):
def on_start(self):
# assume all users arrive at the in... | 47 | 1,378 |
locust | examples/dynamic_user_credentials.py | .py | # locustfile.py
from locust import HttpUser, TaskSet, between, task
USER_CREDENTIALS = [
("user1", "password"),
("user2", "password"),
("user3", "password"),
]
class UserBehaviour(TaskSet):
def on_start(self):
if len(USER_CREDENTIALS) > 0:
user, passw = USER_CREDENTIALS.pop()
... | 27 | 639 |
locust | examples/testdata_from_csv.py | .py | """
This shows an easy way to get testdata from a csv file into locust and use it for requests
"""
from locust import FastHttpUser, events, run_single_user, task
import csv
import os
csvfile = open(os.path.join(os.path.dirname(__file__), "testdata_from_csv.csv"))
iter = csv.reader(csvfile)
class DemoUser(FastHttpU... | 56 | 1,768 |
locust | examples/basic.py | .py | from locust import HttpUser, TaskSet, between, task
def index(l):
l.client.get("/")
def stats(l):
l.client.get("/stats/requests")
class UserTasks(TaskSet):
# one can specify tasks like this
tasks = [index, stats]
# but it might be convenient to use the @task decorator
@task
def page40... | 30 | 589 |
locust | examples/dns_ex.py | .py | from locust import run_single_user, task
from locust.contrib.dns import DNSUser
import time
import dns.message
import dns.rdatatype
class MyDNSUser(DNSUser):
@task
def t(self):
message = dns.message.make_query("example.com", dns.rdatatype.A)
# self.client wraps all dns.query methods https://... | 28 | 769 |
locust | examples/web_ui_cache_stats.py | .py | """
This is an example of a locustfile that uses Locust's built in event and web
UI extension hooks to track the sum of Varnish cache hit/miss headers
and display them in the web UI.
"""
from locust import HttpUser, TaskSet, between, events, task
import json
import os
from time import time
from flask import Blueprin... | 207 | 6,845 |
locust | examples/locustfile.py | .py | from locust import HttpUser, between, task
import time
class QuickstartUser(HttpUser):
wait_time = between(1, 2)
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")
@task(3)
def view_item(self):
for item_id in range(10):
self.clie... | 22 | 495 |
locust | examples/x-forwarded-for.py | .py | from locust import HttpUser, run_single_user, task
import random
class ForwardedForUser(HttpUser):
subnet = "10.10."
def __init__(self, environment):
super().__init__(environment)
self.fake_ip = self.subnet + str(random.randint(0, 254)) + "." + str(random.randint(0, 254))
self.client... | 24 | 576 |
locust | examples/custom_messages.py | .py | from locust import HttpUser, between, events, task
from locust.runners import LocalRunner, MasterRunner, WorkerRunner
import gevent
usernames = []
def setup_test_users(environment, msg, **kwargs):
# Fired when the worker receives a message of type 'test_users'
usernames.extend(map(lambda u: u["name"], msg.d... | 73 | 2,609 |
locust | examples/events.py | .py | """
This is an example of a locustfile that uses Locust's built in event hooks to
track the sum of the content-length header in all successful HTTP responses
"""
from locust import HttpUser, TaskSet, between, events, task
class MyTaskSet(TaskSet):
@task(2)
def index(l):
l.client.get("/")
@task(1... | 74 | 2,307 |
locust | examples/nested_inline_tasksets.py | .py | from locust import HttpUser, TaskSet, between, task
class WebsiteUser(HttpUser):
"""
Example of the ability of inline nested TaskSet classes
"""
host = "http://127.0.0.1:8089"
wait_time = between(2, 5)
@task
class TopLevelTaskSet(TaskSet):
@task
class IndexTaskSet(TaskSet... | 27 | 581 |
locust | examples/test_pytest.py | .py | from locust.clients import HttpSession # this import is just for type hints
import time
# pytest/locust will discover any functions prefixed with "test_" as test cases.
# session and fastsession are pytest fixtures provided by Locust's pytest plugin.
def test_stuff(session):
resp = session.get("https://www.locu... | 41 | 1,564 |
locust | examples/socketio/socketio_ex.py | .py | from locust import HttpUser, task
from locust.contrib.socketio import SocketIOUser
from threading import Event
import gevent
from socketio import Client
class MySIOHttpUser(SocketIOUser, HttpUser):
options = {
# "logger": True,
# "engineio_logger": True,
}
event: Event
def on_start(... | 54 | 1,960 |
locust | examples/socketio/echo_server.py | .py | # Used by socketio_ex.py as a mock target. Requires installing gevent-websocket
import gevent.monkey
gevent.monkey.patch_all()
import time
import socketio
from flask import Flask
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
# Create a Socket.IO server
sio = socketio.Server(async_mod... | 67 | 1,510 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.