Files
mtusi2026lab2/tests_student/test_short_ttl.py
T

81 lines
2.0 KiB
Python

#!/usr/bin/env python3
import base64
import json
import time
import urllib.error
import urllib.request
import uuid
BASE_URL = "http://localhost:8080"
PASSWORD = "correct-password-123"
def call(method, path, body=None, headers=None):
request_headers = dict(headers or {})
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
request_headers["Content-Type"] = "application/json"
request = urllib.request.Request(
BASE_URL + path,
data=data,
headers=request_headers,
method=method,
)
try:
with urllib.request.urlopen(request, timeout=10) as response:
raw = response.read()
return response.status, json.loads(raw) if raw else None
except urllib.error.HTTPError as error:
raw = error.read()
return error.code, json.loads(raw) if raw else None
def main():
username = "ttl_" + uuid.uuid4().hex[:16]
status, body = call(
"POST",
"/api/v1/users",
{
"username": username,
"display_name": "TTL Test User",
"password": PASSWORD,
},
)
assert status == 201, f"registration: {status}, {body}"
credentials = base64.b64encode(
f"{username}:{PASSWORD}".encode("utf-8")
).decode("ascii")
status, body = call(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {credentials}"},
)
assert status == 201, f"login: {status}, {body}"
token = body["token"]
bearer = {"Authorization": f"Bearer {token}"}
status, body = call("GET", "/api/v1/users/me", headers=bearer)
assert status == 200, f"before expiry: {status}, {body}"
print("PASS: token works immediately after login.")
time.sleep(4)
status, body = call("GET", "/api/v1/users/me", headers=bearer)
assert status == 401, f"after expiry: {status}, {body}"
print("PASS: expired token returned 401.")
if __name__ == "__main__":
main()