#!/usr/bin/env python3 import sys import uuid import requests BASE = "http://localhost:8080" LOGIN = "test" PASSWORD = "test123" TIMEOUT = 5 failures = [] def check(condition, message): if condition: print("PASS:", message) return True failures.append(message) print("FAIL:", message) return False def login(): response = requests.post( BASE + "/api/auth/login", json={"login": LOGIN, "password": PASSWORD}, timeout=TIMEOUT, ) if not check(response.status_code == 200, "login returns 200 (got %d)" % response.status_code): print(response.text) return None token = response.json().get("token") check(bool(token), "login returns a token") return token def main(): token = login() if token is None: return 1 auth = {"Authorization": "Bearer " + token} response = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT) check(response.status_code == 200, "GET /api/messages returns 200") instance = response.headers.get("X-Instance-Id") check(bool(instance), "response carries X-Instance-Id (%s)" % instance) check(isinstance(response.json(), list), "GET /api/messages returns a JSON array") key = "key-" + uuid.uuid4().hex[:12] body = {"recipient": LOGIN, "body": "hello " + uuid.uuid4().hex[:8]} first = requests.post( BASE + "/api/messages", headers=dict(auth, **{"Idempotency-Key": key}), json=body, timeout=TIMEOUT, ) check(first.status_code == 201, "first POST returns 201 (got %d)" % first.status_code) second = requests.post( BASE + "/api/messages", headers=dict(auth, **{"Idempotency-Key": key}), json=body, timeout=TIMEOUT, ) check(second.status_code in (200, 201), "replayed POST returns 2xx (got %d)" % second.status_code) first_id = first.json().get("id") second_id = second.json().get("id") check(first_id is not None, "first POST returns message id") check(first_id == second_id, "replay returns the same id (%s vs %s)" % (first_id, second_id)) missing_key = requests.post(BASE + "/api/messages", headers=auth, json=body, timeout=TIMEOUT) check(missing_key.status_code == 400, "POST without Idempotency-Key returns 400 (got %d)" % missing_key.status_code) unauthorized = requests.get(BASE + "/api/messages", timeout=TIMEOUT) check(unauthorized.status_code == 401, "GET without token returns 401 (got %d)" % unauthorized.status_code) messages = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT).json() matching = [m for m in messages if m.get("body") == body["body"]] check(len(matching) == 1, "history contains exactly one copy of the message (got %d)" % len(matching)) if failures: print("\n%d check(s) failed" % len(failures)) return 1 print("\nAll API checks passed") return 0 if __name__ == "__main__": try: sys.exit(main()) except requests.RequestException as exc: print("request failed:", exc) sys.exit(1)