Search code examples
pythonload-testinglocust

Load testing on an API using python


I am currently writing python script for load testing an API.I want to check how many requests can an API take at a time.The API is for registration so I have to send unique parameters everytime.

Is there anyway I could achieve it through locust or any other way?

Any help would be appreciated.

This is my code for registration of single user.

def registration:
    URL = "ip"
    PARAMS = {'name':'test','password':'test1','primary_email':'[email protected]','primary_mobile_number':'9999999999','country_abbrev':'US'} 
    r = requests.post(url = URL,params = PARAMS,auth=HTTPDigestAuth('user', 'pass')) 
    response = r.text 
    print response

Solution

  • Take a look at Faker Python Package. This generates fake data for you whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.

    from locust import HttpLocust, TaskSet, task
    class UserBehavior(TaskSet):
        def on_start(self):
            pass  # add code that you want to run during ramp up
    
        def on_stop(self):
            pass  # add code that you want to run during ramp down
    
        def registration(self):
            name = fake.first_name()
            last_name = fake.last_name()
            password = ''
            email = name + last_name + '@gmail.com'
            phone = fake.phone_number()
            URL = "ip"
            PARAMS = {'name':name,'password': password,'primary_email': email,'primary_mobile_number':phone,'country_abbrev':'US'} 
            self.client.post(URL, PARAMS)
    
    class WebsiteUser(HttpLocust):
        task_set = UserBehavior
        min_wait = 5000
        max_wait = 9000
    

    To start the load test, run locust -f locust_files/my_locust_file.py --host=http://example.com For more info, visit Locust Quickstart