Search code examples
pythonapitestingloadlocust

How to provide test data to a locustfile in Python for load testing


I have built an API using flask and want to do load testing using locust. Can anyone help me how to create it and do a load testing


Solution

  • After getting the correct result I have come up with the way how you will pass your input to the flask API at the time of load testing.

    Load test for the text classification API

    from locust import HttpLocust, TaskSet, task
    import os
    import random
    TEST_DATA_PATH = 'load_test_data.txt' 
    
    def load_test_sentences():  
       sent = []  
       with open(TEST_DATA_PATH, 'rb') as fp:
         for row in fp:  
           row = row.strip()   
           sent.append(row)  
       return sent
    
    class UserBehavior(TaskSet):
        def on_start(self):
            self.sent=load_test_sentences()
    
        @task(1)
        def about(self):
            for ut in self.sent:
                self.client.get("/entity-extractor/location?q={}".format(ut.decode("utf-8")),name='Text Classification') 
    
    class MyLocust(HttpLocust):
        task_set = UserBehavior
        host = "http://0.0.0.0:8000"
        min_wait = 5000
        max_wait = 15000
        def __init__(self):
            print('loaded %s sentences' %len(load_test_sentences()))
            super(MyLocust, self).__init__()