Skip to content

Commit

Permalink
Merge pull request #2713 from locustio/Give-better-error-message-if-U…
Browse files Browse the repository at this point in the history
…ser-subclass-doesnt-call-base-constructor

Give better error message if User subclass doesnt call base constructor
  • Loading branch information
cyberw authored May 15, 2024
2 parents ceb07c9 + 2ab11c3 commit 7690caf
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
3 changes: 3 additions & 0 deletions locust/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ def spawn(user_class: str, spawn_count: int) -> list[User]:
new_users: list[User] = []
while n < spawn_count:
new_user = self.user_classes_by_name[user_class](self.environment)
assert hasattr(
new_user, "environment"
), f"Attribute 'environment' is missing on user {user_class}. Perhaps you defined your own __init__ and forgot to call the base constructor? (super().__init__(*args, **kwargs))"
new_user.start(self.user_greenlets)
new_users.append(new_user)
n += 1
Expand Down
18 changes: 18 additions & 0 deletions locust/test/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,24 @@ def reset_state(self):


class TestLocustRunner(LocustRunnerTestCase):
def test_missing_constructor_call_in_user(self):
class BadUser(User):
def __init__(self, *args, **kwargs):
pass # not calling base class constructor!!!

@task
def t(self):
pass

environment = Environment(user_classes=[BadUser])
runner = LocalRunner(environment)
with self.assertRaises(AssertionError) as assert_raises_context:
runner.spawn_users({BadUser.__name__: 1})
self.assertIn(
"Attribute 'environment' is missing on user BadUser. Perhaps you defined your own __init__ and forgot to call the base constructor",
str(assert_raises_context.exception),
)

def test_cpu_warning(self):
_monitor_interval = runners.CPU_MONITOR_INTERVAL
runners.CPU_MONITOR_INTERVAL = 2.0
Expand Down

0 comments on commit 7690caf

Please sign in to comment.