Skip to content

Instantly share code, notes, and snippets.

@quangnguyenbh
Forked from kaka2507/Sample Locust
Created October 5, 2018 04:59
Show Gist options
  • Save quangnguyenbh/3faab0b6630793c9eb7332d2c136ee73 to your computer and use it in GitHub Desktop.
Save quangnguyenbh/3faab0b6630793c9eb7332d2c136ee73 to your computer and use it in GitHub Desktop.
from locust import HttpLocust, TaskSet, task
import random
import json
class EventAPITasks(TaskSet):
def on_start(self):
with self.client.post("/api/user/register", {
'username': self.locust.username,
'password': self.locust.password
}, catch_response=True) as response:
data = self.parse_response(response)
if 'code' in data:
response.failure(data['message'])
# login
with self.client.post("/api/user/login", {
'username': self.locust.username,
'password': self.locust.password
}, catch_response=True) as response:
data = self.parse_response(response)
if 'code' in data:
response.failure(data['message'])
else:
self.locust.session = data['session']
@task
def get_event_list(self):
with self.client.get("/api/event/", headers=self.get_headers(), catch_response=True) as response:
self.parse_response(response)
@task
def get_event_detail(self):
with self.client.get('/api/event/' + self.get_random_event_id() + '/', headers = self.get_headers(), catch_response=True) as response:
self.parse_response(response)
@task
def like_event(self):
with self.client.post('/api/event/' + self.get_random_event_id() + '/like', headers = self.get_headers(), catch_response=True) as response:
self.parse_response(response)
@task
def commnet_event(self):
with self.client.post('/api/event/' + self.get_random_event_id() + '/comment', {'comment': 'This is a comment from locust'}, headers=self.get_headers(), catch_response=True) as response:
self.parse_response(response)
@task
def participate_event(self):
with self.client.post('/api/event/' + self.get_random_event_id() + '/participate', headers=self.get_headers(), catch_response=True) as response:
self.parse_response(response)
def parse_response(self, response):
if response.status_code != 200:
response.failure('Wrong response')
data = json.loads(response.content)
return data
def get_random_event_id(self):
return str(random.randint(10, 20))
def get_headers(self):
return {
"AUTHENTICATION": self.locust.session
}
class EventAPIUser(HttpLocust):
task_set = EventAPITasks
min_wait = 300
max_wait = 1000
username = 'test_%s_%s' % (random.randint(20000, 30000), random.randint(10000, 20000))
password = '123456'
session = ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment