entry_point.py

from other_file import UserBehaviour

class ApiUser(HttpUser):

  tasks = [UserBehaviour]

  def on_start(self):
    # log in and return session id and cookie
    # example: self.foo = "foo"

other_file.py

from entry_point import ApiUser

class UserBehaviour(TaskSet):

  @task
  def do_something(self, session_id, session_cookie)
    # use session id and session cookie from user instance running the taskset
    # example: print(self.ApiUser.foo)

NOTE: Going through the documentation, I did find that "the User instance can be accessed from within a TaskSet instance through the TaskSet.user", however all my attempts to import the user into the taskset file led to a "cannot import name 'ApiUser' from 'entry_point'" error. If instead of from entry_point import ApiUser I do from entry_point import *, then I get a name 'ApiUser' is not defined error.

1

There are 1 best solutions below

4
Xen0byte On BEST ANSWER

Thank you very much @Cyberwiz for putting me on the right track. I've finally managed to figure out what I was doing wrong... which, as it turns out, was a couple of things.

Firstly, importing ApiUser in other_file.py was incorrect for two reasons: 1) it creates a cyclical dependency, and 2) even if it would eventually work it would import the ApiUser class, not the instance of the ApiUser class.

Secondly, I was previously getting a module locust.user has no attribute {name} error, and that was because my code looked like this:

class UserBehaviour(TaskSet):
  # do something with user.foo

Having figured this out, I honestly have no idea why I thought the above would work. I've changed my code to reflect the example below and everything now works like a charm:

class UserBehaviour(TaskSet):

  @task
  def do_something(self):
    # do something with self.user.foo