Support CSRF tokens, for example with the Laravel framework.
A test which posts to a login page when it starts, then requests /hello and /world normally. However, it also specifically handles getting a CSRF token for logging in with (in this example) Laravel.
Laravel automatically checks for a CSRF token when you submit data (by default). CSRF is designed to stop cross-site scripting against your site, and involves having a temporary token on each page that is submitted with every post. You'll know you've hit this issue if you receive an HTTP 419 error.
The below example can also be used for many other frameworks, or altered to suit them.
from locust import HttpUser, task, between
from pyquery import PyQuery
class QuickstartUser(HttpUser):
# Wait between 5 and 9 seconds per request per user
wait_time = between(5, 9)
def on_start(self):
response = self.client.get("/login")
pq = PyQuery(response.content)
elements = pq("input[name=_token]")
for token in elements:
csrftoken = token.value
# debug example
#print("my token is:", csrftoken)
self.client.post("/login",
{"email": "user@domain.com", "password": "secr3t", "_token" : csrftoken})
@task(1)
def index_page(self):
# Request /dashboard on your Host
self.client.get("/dashboard")