добавлены автоматические тесты аутентификации и отказов

This commit is contained in:
2026-10-08 01:46:43 +03:00
parent d33c50a087
commit 62cb785c63
4 changed files with 476 additions and 0 deletions
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
import base64
import json
import urllib.error
import urllib.request
import uuid
BASE_URL = "http://localhost:8080"
PASSWORD = "correct-password-123"
def call(
method: str,
path: str,
body: dict | None = None,
headers: dict[str, str] | None = None,
) -> tuple[int, dict | None, dict]:
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()
response_body = json.loads(raw) if raw else None
return response.status, response_body, dict(response.headers)
except urllib.error.HTTPError as error:
raw = error.read()
response_body = json.loads(raw) if raw else None
return error.code, response_body, dict(error.headers)
def basic_header(username: str, password: str) -> str:
credentials = f"{username}:{password}".encode("utf-8")
encoded = base64.b64encode(credentials).decode("ascii")
return f"Basic {encoded}"
def main() -> None:
username = "auth_" + uuid.uuid4().hex[:16]
# 1. Создаём отдельного пользователя для этого теста.
status, body, _ = call(
"POST",
"/api/v1/users",
{
"username": username,
"display_name": "Auth Test User",
"password": PASSWORD,
},
)
if status != 201:
raise AssertionError(
f"registration: expected 201, got {status}: {body}"
)
# 2. Неверный пароль не должен создавать сессию.
status, body, headers = call(
"POST",
"/api/v1/auth/sessions",
headers={
"Authorization": basic_header(
username,
"definitely-wrong-password",
)
},
)
if status != 401:
raise AssertionError(
f"wrong password: expected 401, got {status}: {body}"
)
if body is None or body.get("error", {}).get("code") != "unauthorized":
raise AssertionError(
f"wrong password: unexpected response body: {body}"
)
# 3. С правильным паролем получаем Bearer-сессию.
status, body, _ = call(
"POST",
"/api/v1/auth/sessions",
headers={
"Authorization": basic_header(username, PASSWORD)
},
)
if status != 201:
raise AssertionError(
f"login: expected 201, got {status}: {body}"
)
if body is None:
raise AssertionError("login: empty response body")
token = body.get("token")
if not token:
raise AssertionError("login: token is missing")
if body.get("token_type") != "Bearer":
raise AssertionError(
f"login: expected token_type Bearer, got {body.get('token_type')}"
)
bearer = {"Authorization": f"Bearer {token}"}
# 4. До logout токен обязан работать.
status, body, _ = call(
"GET",
"/api/v1/users/me",
headers=bearer,
)
if status != 200:
raise AssertionError(
f"token before logout: expected 200, got {status}: {body}"
)
# 5. Отзываем текущую сессию.
status, body, _ = call(
"DELETE",
"/api/v1/auth/sessions/current",
headers=bearer,
)
if status != 204:
raise AssertionError(
f"logout: expected 204, got {status}: {body}"
)
# 6. Тот же токен после logout больше не принимается.
status, body, _ = call(
"GET",
"/api/v1/users/me",
headers=bearer,
)
if status != 401:
raise AssertionError(
f"token after logout: expected 401, got {status}: {body}"
)
# 7. Повторный logout с уже отозванным токеном тоже не авторизован.
status, body, _ = call(
"DELETE",
"/api/v1/auth/sessions/current",
headers=bearer,
)
if status != 401:
raise AssertionError(
f"repeated logout: expected 401, got {status}: {body}"
)
print(
"PASS: wrong password returned 401; "
"valid session worked; logout revoked the token."
)
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
#!/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()