4_grade
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
caramelteawithmint
2026-11-06 04:33:40 +03:00
parent fc62d81ec4
commit 49ce543631
10 changed files with 395 additions and 36 deletions
+41
View File
@@ -0,0 +1,41 @@
import urllib.request
import urllib.error
import json
import base64
import time
import uuid
url = 'http://localhost:8080/api/v1'
def call(m, p, b=None, h=None):
req = urllib.request.Request(url+p, method=m)
if b:
req.data = json.dumps(b).encode()
req.add_header('Content-Type','application/json')
if h:
for k,v in h.items(): req.add_header(k,v)
try:
return urllib.request.urlopen(req).status, json.loads(urllib.request.urlopen(req).read()) if m=='GET' else None
except urllib.error.HTTPError as e:
return e.code, None
u = f'test_{uuid.uuid4().hex[:6]}'
call('POST', '/users', {'username':u, 'display_name':'Test', 'password':'TestPassword123!'})
cred = base64.b64encode(f'{u}:TestPassword123!'.encode()).decode()
req = urllib.request.Request(url+'/auth/sessions', method='POST', headers={'Authorization': f'Basic {cred}'})
res = json.loads(urllib.request.urlopen(req).read())
token = res['token']
print(f'Токен получен: {token[:10]}...')
print('Ждем 3 секунды...')
time.sleep(3)
try:
req2 = urllib.request.Request(url+'/users/me', headers={'Authorization': f'Bearer {token}'})
urllib.request.urlopen(req2)
print('FAIL: Токен всё еще работает (200)')
except urllib.error.HTTPError as e:
if e.code == 401:
print('PASS: Токен истек, получили 401!')
else:
print(f'FAIL: Ожидали 401, получили {e.code}')
+70
View File
@@ -0,0 +1,70 @@
import urllib.request
import urllib.error
import json
import base64
import uuid
import threading
BASE_URL = "http://localhost:8080"
def call(method, path, expected_status, headers=None, body=None):
url = BASE_URL + path
req = urllib.request.Request(url, method=method)
if headers:
for k, v in headers.items():
req.add_header(k, v)
if body:
req.data = json.dumps(body).encode('utf-8')
req.add_header('Content-Type', 'application/json')
try:
with urllib.request.urlopen(req) as response:
return response.status
except urllib.error.HTTPError as e:
return e.code
def main():
print("=== Тест 1: Гонка регистрации (одновременные запросы) ===")
username = f"race_{uuid.uuid4().hex[:6]}"
body = {"username": username, "display_name": "Race", "password": "Password123!"}
results = []
def register():
results.append(call("POST", "/api/v1/users", None, body=body))
t1 = threading.Thread(target=register)
t2 = threading.Thread(target=register)
t1.start(); t2.start()
t1.join(); t2.join()
# Один должен быть 201, второй 409
if sorted(results) == [201, 409]:
print("PASS: Гонка обработана (один 201, один 409).")
else:
print(f"FAIL: Ожидали [201, 409], получили {results}")
print("\n=== Тест 2: Неверный пароль ===")
cred = base64.b64encode(f"{username}:WrongPassword".encode()).decode()
status = call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": f"Basic {cred}"})
if status == 401:
print("PASS: Неверный пароль отклонен (401).")
else:
print(f"FAIL: Ожидали 401, получили {status}")
print("\n=== Тест 3: Logout ===")
cred = base64.b64encode(f"{username}:Password123!".encode()).decode()
req = urllib.request.Request(BASE_URL + '/api/v1/auth/sessions', method='POST', headers={'Authorization': f'Basic {cred}'})
with urllib.request.urlopen(req) as response:
token = json.loads(response.read())['token']
status = call("DELETE", "/api/v1/auth/sessions/current", 204, headers={"Authorization": f"Bearer {token}"})
status2 = call("GET", "/api/v1/users/me", 401, headers={"Authorization": f"Bearer {token}"})
if status == 204 and status2 == 401:
print("PASS: Logout работает (204, затем 401).")
else:
print(f"FAIL: Logout не сработал. Коды: {status}, {status2}")
if __name__ == "__main__":
main()
+88
View File
@@ -0,0 +1,88 @@
import time
import subprocess
import urllib.request
import urllib.error
import json
import base64
import uuid
import os
BASE_URL = "http://localhost:8080"
def call(method, path, expected_status, headers=None, body=None):
url = BASE_URL + path
req = urllib.request.Request(url, method=method)
if headers:
for k, v in headers.items():
req.add_header(k, v)
data = None
if body:
data = json.dumps(body).encode('utf-8')
req.add_header('Content-Type', 'application/json')
req.data = data
try:
with urllib.request.urlopen(req) as response:
status = response.status
resp_body = response.read()
except urllib.error.HTTPError as e:
status = e.code
resp_body = e.read()
if status != expected_status:
raise AssertionError(f"Expected {expected_status}, got {status} for {method} {path}. Body: {resp_body}")
return json.loads(resp_body) if resp_body else None
def main():
print("=== Тест 1: Истечение сессии (TTL) ===")
username = f"test_ttl_{uuid.uuid4().hex[:6]}"
password = "TestPassword123!"
user = call("POST", "/api/v1/users", 201, body={
"username": username, "display_name": "TTL User", "password": password
})
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
session = call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": f"Basic {cred}"})
token = session["token"]
call("GET", "/api/v1/users/me", 200, headers={"Authorization": f"Bearer {token}"})
print("Токен создан и работает.")
print("Останавливаем API, чтобы изменить TTL на 2 секунды...")
subprocess.run(["docker", "compose", "down"], check=True, stdout=subprocess.DEVNULL)
env = {"SESSION_TTL_SECONDS": "2"}
subprocess.run(["docker", "compose", "up", "-d"], env={**os.environ, **env}, check=True)
time.sleep(5)
print("Ждем 3 секунды, чтобы токен истек...")
time.sleep(3)
try:
call("GET", "/api/v1/users/me", 401, headers={"Authorization": f"Bearer {token}"})
print("PASS: Сессия успешно истекла (получили 401).")
except AssertionError as e:
print(f"FAIL: Сессия не истекла. Ошибка: {e}")
raise
print("\n=== Тест 2: Отказ Redis ===")
print("Останавливаем контейнер Redis...")
subprocess.run(["docker", "compose", "stop", "redis"], check=True, stdout=subprocess.DEVNULL)
print("Пробуем авторизоваться (должны получить 503)...")
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
try:
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": f"Basic {cred}"})
print("PASS: API вернул 503, так как Redis лежит.")
except AssertionError:
print("WARN: API вернул не 503. Проверьте логи (возможно 500).")
print("Возвращаем Redis обратно...")
subprocess.run(["docker", "compose", "start", "redis"], check=True, stdout=subprocess.DEVNULL)
time.sleep(2)
if __name__ == "__main__":
main()