Search code examples
pythonpython-3.xtestingpytestlocust

Using locust with pytest


I am trying to run locust using pytest. I have created this python file but it is not showing any output. pytest doesnot collect the test. How can I use locust with pytest

from locust import HttpUser, TaskSet, task
class WebsiteTasks(TaskSet):
    def on_start(self):
        self.index()

    @task(2)
    def index(self):
        self.client.get("/")

    @task(1)
    def about(self):
        self.client.get("/page/about")


class WebsiteUser(HttpUser):
    task = WebsiteTasks
    host = "localhost:5000"
    min_wait = 1000
    max_wait = 5000

When I run pytest locust_test.py this is the output:

================================================================ test session starts ================================================================
platform linux -- Python 3.8.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /home/user/Desktop/testing
collected 0 items                                                                                                                                   


Solution

  • Pytest only sees and runs tests that are named a certain way (both class and function must start with "test").

    What you'll want to do is write a test that then uses Locust as a library to programmatically start your Locust test.

    import gevent
    from locustfile import WebsiteUser
    from locust.env import Environment
    from locust.stats import stats_printer, stats_history
    
    
    def test_locust():
        # setup Environment and Runner
        env = Environment(user_classes=[WebsiteUser])
        env.create_local_runner()
    
        # start a greenlet that periodically outputs the current stats
        gevent.spawn(stats_printer(env.stats))
    
        # start a greenlet that save current stats to history
        gevent.spawn(stats_history, env.runner)
    
        # start the test
        env.runner.start(1, spawn_rate=10)
    
        # in 60 seconds stop the runner
        gevent.spawn_later(60, lambda: env.runner.quit())
    
        # wait for the greenlets
        env.runner.greenlet.join()
    

    You can write test assertions based on your pass/fail criteria before you quit the runner. Perhaps write a different function for the lambda to call that checks env.stats for failures and response times first and then calls env.runner.quit() quit.