Saturday 19 February 2022

Locust - Running tests in a debugger in pycharm

Remember to checked the [Gevent compatible] in the debugger setting.


Running Locust in a debugger is extremely useful when developing your tests. Among other things, you can examine a particular response or check some User instance variable.

But debuggers sometimes have issues with complex gevent-applications like Locust, and there is a lot going on in the framework itself that you probably arent interested in. To simplify this, Locust provides a method called run_single_user:

Note that this is fairly new feature, and the api is subject to change.

from locust import HttpUser, task, run_single_user


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 directly, e.g. "python3 debugging.py", not "locust -f debugging.py"
if __name__ == "__main__":
    run_single_user(QuickstartUser)

It implicitly registeres an event handler for the request event to print some stats about every request made:

type    name                                           resp_ms exception
GET     /hello                                         38      ConnectionRefusedError(61, 'Connection refused')
GET     /hello                                         4       ConnectionRefusedError(61, 'Connection refused')

You can configure exactly what is printed by specifying parameters to run_single_user.

Make sure you have enabled gevent in your debugger settings. In VS Code’s launch.json it looks like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "gevent": true
        }
    ]
}

There is a similar setting in PyChar


from: https://docs.locust.io/en/latest/running-in-debugger.html

No comments:

Post a Comment