diff --git a/locust/debug.py b/locust/debug.py index 3341549baa..1d765f3aba 100644 --- a/locust/debug.py +++ b/locust/debug.py @@ -22,7 +22,7 @@ class PrintListener: def __init__( self, - env: locust.env.Environment, + env: Environment, include_length=False, include_time=False, include_context=False, @@ -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, @@ -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) diff --git a/locust/test/test_debugging.py b/locust/test/test_debugging.py new file mode 100644 index 0000000000..3941df0a14 --- /dev/null +++ b/locust/test/test_debugging.py @@ -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)