The target server of the course
Every plan in this course talks to one server: a small Python program on 127.0.0.1:8099 that answers JSON, waits when it is asked to wait, sets a cookie, wants a token and fails on purpose. It is a whole file of this lesson, it is started with one command, and it is the same file on every page of the course. Nothing about it is remote: a connection cannot drop and a site cannot change under the plan.
The server
It is the standard library's threaded HTTP server: one handler, thirteen paths, no framework and no dependency. The methods that matter are the four below it: the server answers on a port of its own, keeps the log quiet, and writes a Content-Length with every body so that a keep-alive client can read the next answer.
server.py
#!/usr/bin/env python3 """The target server of the JMeter course: a small JSON API on 127.0.0.1. python3 server.py 8099 Every endpoint is a few lines: the course tests them, it does not test the server. /slow sleeps, /fail answers 500, /login sets a cookie and returns a token, /secure wants that token in an Authorization header. """ import json import sys import time import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlparse USERS = [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}, {"id": 3, "name": "Linus"}] TOKEN = "secret-token" class Handler(BaseHTTPRequestHandler): """One request, one small JSON answer.""" protocol_version = "HTTP/1.1" def log_message(self, fmt, *args): """Keep the course\'s server log quiet: every request would be a line.""" def reply(self, status, body, ctype="application/json", headers=None): """Send a body with its length, so a keep-alive client can read it.""" data = body.encode("utf-8") self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) for name, value in (headers or {}).items(): self.send_header(name, value) self.end_headers() self.wfile.write(data) def reply_json(self, status, value, headers=None): self.reply(status, json.dumps(value), headers=headers) def do_GET(self): url = urlparse(self.path) query = parse_qs(url.query) if url.path == "/": self.reply(200, "<!doctype html><title>course</title><h1>JMeter course</h1>", "text/html") elif url.path == "/health": self.reply_json(200, {"status": "ok"}) elif url.path == "/api/users": self.reply_json(200, {"users": USERS, "count": len(USERS)}) elif url.path.startswith("/api/users/"): user = next((u for u in USERS if str(u["id"]) == url.path.rsplit("/", 1)[-1]), None) self.reply_json(200 if user else 404, user or {"error": "no such user"}) elif url.path == "/items": page = int(query.get("page", ["1"])[0]) self.reply_json(200, {"page": page, "items": [f"item-{page}-{n}" for n in range(1, 4)]}) elif url.path == "/slow": ms = int(query.get("ms", ["300"])[0]) time.sleep(ms / 1000.0) self.reply_json(200, {"slept_ms": ms}) elif url.path == "/fail": self.reply_json(500, {"error": "the server was told to fail"}) elif url.path == "/login": self.reply_json(200, {"token": TOKEN}, headers={"Set-Cookie": "session=abc123; Path=/"}) elif url.path == "/secure": if self.headers.get("Authorization") == "Bearer " + TOKEN: self.reply_json(200, {"message": "welcome"}) else: self.reply_json(401, {"error": "a token is required"}) elif url.path == "/token": self.reply_json(200, {"token": uuid.uuid4().hex}) elif url.path == "/redirect": self.reply(302, "", headers={"Location": "/health"}) elif url.path == "/xml": self.reply(200, "<user><id>1</id><name>Ada</name></user>", "application/xml") elif url.path == "/echo": body = json.dumps({"method": "GET", "path": self.path, "headers": dict(self.headers)}) self.reply(200, body) else: self.reply_json(404, {"error": "not found", "path": url.path}) def do_POST(self): length = int(self.headers.get("Content-Length", "0")) raw = self.rfile.read(length).decode("utf-8") if length else "" if self.path == "/api/orders": try: order = json.loads(raw) if raw else {} except json.JSONDecodeError: self.reply_json(400, {"error": "the body is not JSON"}) return self.reply_json(201, {"id": 1001, "received": order}) else: self.reply_json(404, {"error": "not found", "path": self.path}) if __name__ == "__main__": port = int(sys.argv[1]) if len(sys.argv) > 1 else 8099 server = ThreadingHTTPServer(("127.0.0.1", port), Handler) print(f"listening on 127.0.0.1:{port}", flush=True) server.serve_forever()
Start it
The port is the one argument. The ampersand puts the server in the background, which is what a reader wants in a terminal and what a page needs before its plan runs; a wget call right after it proves that the port answers.
python3 server.py 8099 &
wget -qO- http://127.0.0.1:8099/health
{"status": "ok"}
The endpoints
| Path | Answer | What a lesson uses it for |
|---|---|---|
| /health | a JSON object, 200 | a request that always works; the first plan |
| /api/users | three users, a count, 200 | a JSON body to extract from and assert on |
| /api/users/2 | one user, or a 404 | a path built from a variable |
| /items?page=2 | a page of items | a query parameter and its echo |
| /slow?ms=100 | the same JSON after 100 ms | elapsed time, timers and percentiles |
| /fail | a JSON error, 500 | an assertion that must fail |
| /login | a token and a cookie | correlation and the cookie manager |
| /secure | 200 with a token, 401 without | a header manager |
| /token | a new random token | a value that must be read before it is used |
| /redirect | a 302 to /health | follow-redirects on and off |
| /xml | a small XML document | a boundary or XPath extractor |
| POST /api/orders | a JSON echo, 201 | a request with a body |
| /echo | the request as it arrived | the headers a plan really sends |
The JSON endpoints
wget -qO- http://127.0.0.1:8099/api/users
{"users": [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}, {"id": 3, "name": "Linus"}], "count": 3}
wget -qO- http://127.0.0.1:8099/api/users/2
{"id": 2, "name": "Grace"}
wget -qO- 'http://127.0.0.1:8099/items?page=2'
{"page": 2, "items": ["item-2-1", "item-2-2", "item-2-3"]}
The ampersand of a query string is also the shell's "run this in the background", so the URL of a request with more than one parameter is quoted. The course quotes every URL that has a ? in it, whether it needs to or not.
wget -qO- 'http://127.0.0.1:8099/slow?ms=100'
{"slept_ms": 100}
A request that fails
A 500 is not an error for wget in the sense the shell means: the utility prints the server's answer and exits with status 8, and the message goes to stderr. It is the request a plan must learn to notice.
wget -qO- http://127.0.0.1:8099/fail
wget: server returned error: HTTP/1.1 500 Internal Server Error
A cookie and a token
The login answer carries both things a correlation has to handle: a token in the body and a cookie in a header. The cookie is invisible to a plain body read, so the -S flag of wget prints the response headers on stderr, and a pipe picks the one that matters.
wget -qO- http://127.0.0.1:8099/login
{"token": "secret-token"}
wget -SqO- http://127.0.0.1:8099/login 2>&1 | grep -i set-cookie
Set-Cookie: session=abc123; Path=/
/secure wants the token in an Authorization header. Without it the answer is a 401, and with it a 200 — the two answers the header lesson asserts on.
wget -SqO- http://127.0.0.1:8099/secure 2>&1 | head -1
HTTP/1.1 401 Unauthorized
wget -qO- --header='Authorization: Bearer secret-token' http://127.0.0.1:8099/secure
{"message": "welcome"}
A redirect
/redirect answers 302 with a Location header, and wget follows it without being asked. A plan has the same choice as a property of each request, and the request lesson shows both answers.
wget -qO- http://127.0.0.1:8099/redirect
{"status": "ok"}
A POST with a JSON body
The order endpoint echoes what it received, which is how a plan proves that its body arrived as JSON and not as a form field.
wget -qO- --post-data='{"item": "book", "qty": 2}' --header='Content-Type: application/json' http://127.0.0.1:8099/api/orders
{"id": 1001, "received": {"item": "book", "qty": 2}}
Related
- The first plan: the first plan that talks to this server.
- Correlation: the login, the token and the secured request in one plan.
- API testing: the same endpoints, checked by hand.
Article author: Arthur Isaev