Skip to content

Instantly share code, notes, and snippets.

@srmds
Last active March 8, 2019 18:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srmds/bdce081fabd0784769b14b27d161421d to your computer and use it in GitHub Desktop.
Save srmds/bdce081fabd0784769b14b27d161421d to your computer and use it in GitHub Desktop.
Load testing API with Locust
'''
Simple LocustIO testing script to call an API endpoint
********************************** Installation instructions **************************************
Prerequisites
- python 2.7 / 3
- pip, see: https://pip.pypa.io/en/stable/installing/
- locust, see: https://locust.io
1) Save this file as locustfile.py
2) Set ACCESSTOKEN, ENDPOINT, DOMAIN
3) Run:
$ locust -f /path/to/locustfile.py
4) Navigate to http://localhost:8089 or whatever locust uses as port
5) Set up number of users and hatch to create a swarm to simultaniously call the API
More info:
https://locust.io
https://docs.locust.io/en/stable/installation.html
***************************************************************************************************
'''
import random, gzip, StringIO, threading, urllib2, re, getpass
from locust import HttpLocust, TaskSet, task, web
from random import randint
from urlparse import urlparse
#resource.setrlimit(resource.RLIMIT_NOFILE, (999999, 999999))
# User agents to randomly select
USER_AGENTS = [
"Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19 (LocustIO)",
"Android 4.0.3;AppleWebKit/534.30;Build/IML74K;GT-I9220 Build/IML74K (LocustIO)",
"KWC-S4000/ UP.Browser/7.2.6.1.794 (GUI) MMP/2.0 (LocustIO)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) (LocustIO)",
"Googlebot-Image/1.0 (LocustIO)",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0 (LocustIO)",
"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52 (LocustIO)",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36",
]
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
""" 2 Additional headers """
self.headers = {
"User-Agent":USER_AGENTS[random.randint(0,len(USER_AGENTS)-1)],
"Authorization": "Bearer ACCESS_TOKEN"
}
self.client.headers = self.headers
# 100 Max
@task(100)
def action_landing_page(self):
""" 1 endpoint to call """
self.client.get("/api/v1/ENDPOINT>")
class WebsiteUser(HttpLocust):
""" 1 host to call """
host="https://DOMAIN.COM"
task_set = UserBehavior
min_wait=1000
max_wait=3000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment