Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix passing host to user class when debugging #2365

Merged
merged 2 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions locust/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class PrintListener:

def __init__(
self,
env: locust.env.Environment,
env: Environment,
include_length=False,
include_time=False,
include_context=False,
Expand Down Expand Up @@ -122,11 +122,15 @@ def run_single_user(
locust.log.setup_logging(loglevel)

if not _env:
_env = locust.env.Environment(events=locust.events)
options = argument_parser.parse_options()

# in case your test goes looking for the file name of your locustfile
_env.parsed_options = argument_parser.parse_options()
frame = inspect.stack()[1]
_env.parsed_options.locustfile = os.path.basename(frame[0].f_code.co_filename)
locustfile = os.path.basename(frame[0].f_code.co_filename)
options.locustfile = locustfile

_env = Environment(events=locust.events, locustfile=locustfile, host=options.host, parsed_options=options)

# log requests to stdout
PrintListener(
_env,
Expand All @@ -142,6 +146,8 @@ def run_single_user(
_env.user_classes = [user_class]
_env._filter_tasks_by_tags()
_env.events.test_start.fire(environment=_env)
if _env.host:
user_class.host = _env.host

# create a single user
user = user_class(_env)
Expand Down
37 changes: 37 additions & 0 deletions locust/test/test_debugging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import os
from threading import Timer
from unittest import mock

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


class DebugTestCase(LocustTestCase):
def setUp(self):
super().setUp()
debug._env = None


class TestDebugging(DebugTestCase):
@mock.patch.dict(os.environ, {"LOCUST_HOST": "http://localhost"})
def test_run_single_user_pass_host_to_user_classes(self):
"""
HttpUser should receive host from environment variable
"""

class MyUser1(HttpUser):
@task
def my_task():
pass

def _stop_user():
user = getattr(debug._env, "single_user_instance", None)
if user:
user._state = LOCUST_STATE_STOPPING

t = Timer(1, _stop_user)
t.start()

debug.run_single_user(MyUser1)