Files
mtusi2026lab2-fork/scripts/check_grade3.py
2026-10-26 16:42:32 +03:00

93 lines
3.0 KiB
Python

#!/usr/bin/env python3
"""Grade-3 check that is not part of make test.
Creates a chat with one unknown member and expects 400. Then asks PostgreSQL
whether that title was stored. A rollback leaves zero rows.
"""
import json
import os
import subprocess
import sys
import urllib.error
import urllib.request
import uuid
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8080').rstrip('/')
def request(method, path, body=None, headers=None, expected=200):
data = None if body is None else json.dumps(body).encode('utf-8')
req = urllib.request.Request(BASE_URL + path, data=data, method=method)
req.add_header('Content-Type', 'application/json')
for key, value in (headers or {}).items():
req.add_header(key, value)
try:
with urllib.request.urlopen(req, timeout=10) as response:
status = response.status
payload = response.read()
except urllib.error.HTTPError as exc:
status = exc.code
payload = exc.read()
if status != expected:
sys.stderr.write('expected %s %s -> %s, got %s %s\n' % (method, path, expected, status, payload[:300]))
return None
if not payload:
return {}
return json.loads(payload)
def main():
username = 'u_orphan_' + uuid.uuid4().hex[:12]
password = 'T3st-' + uuid.uuid4().hex
user = request('POST', '/api/v1/users', {
'username': username,
'display_name': 'Orphan check',
'password': password,
}, expected=201)
if user is None:
return 1
import base64
basic = base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
session = request('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + basic}, expected=201)
if session is None:
return 1
title = 'orphan-' + uuid.uuid4().hex
missing = str(uuid.uuid4())
rejected = request(
'POST',
'/api/v1/chats',
{'title': title, 'member_ids': [user['id'], missing]},
headers={'Authorization': 'Bearer ' + session['token']},
expected=400,
)
if rejected is None:
return 1
sql = "SELECT count(*) FROM chats WHERE title = '%s'" % title.replace("'", '')
probe = subprocess.run(
[
'docker', 'compose', '--env-file', '.env', 'exec', '-T', 'postgres',
'psql', '-U', os.environ.get('POSTGRES_USER', 'messenger'),
'-d', os.environ.get('POSTGRES_DB', 'messenger'),
'-tAc', sql,
],
cwd=ROOT,
check=False,
capture_output=True,
text=True,
)
if probe.returncode != 0:
sys.stderr.write(probe.stderr)
return 1
count = probe.stdout.strip()
if count != '0':
sys.stderr.write('rolled-back chat is still stored: count=%s\n' % count)
return 1
print('PASS: unknown member returns 400 and leaves no chat row')
return 0
if __name__ == '__main__':
sys.exit(main())