Load testing on an API using python
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
from locust import HttpLocust, TaskSet
def login(self):
params= {'name':'test','password':'test1','primary_email':'[email protected]','primary_mobile_number':'9999999999','country_abbrev':'US'}
self.client.post(URL, data=params)
#The data parameter or json can both be used here. If it's a dict then data would work but for json replace data with json. For more information you can check out requests package as Locust internally uses requests only.
class UserBehavior(TaskSet):
tasks = {index: 2, profile: 1}
def on_start(self):
login(self)
def on_stop(self):
pass
@task
def try(self):
pass
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 where host would be your IP. You can then go to 127.0.0.1:8089 to select the number of virtual users to simulate. On windows there's a limitation of 1024 users only. But you can use the amazing support of Master Slave Architecture provided by Locust.
PS: Anything put in the on_start method runs only once for each user. So since you want to test the limit of the API you should prefer adding that request under the @task decorator.
Hope this helps! :)