Files
mtusi2026lab4-fork/student-tests/test_api.py
T
nothingredmouth 9af7b15809 Добавить собственные интеграционные тесты API и проверки изображений
test_api.py — сквозные сценарии на живой БД (auth, сессии, чаты,
идемпотентность, миграции, доступ к чужим чатам). test_images.py —
валидация PNG/JPEG: MIME, лимиты bytes/pixels, повреждённые файлы,
доступ только для участников чата. Указано 3 применённые миграции.
2026-11-17 03:37:42 +00:00

142 lines
9.1 KiB
Python

"""Integration tests. DATABASE_URL[_FILE] must point to a disposable PostgreSQL DB."""
import base64
import time
import unittest
from dataclasses import replace
from uuid import uuid4
from messenger.api import create_app
from messenger.config import Settings
from messenger.database import Database
from messenger.migrate import migrate
class ApiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.settings = Settings.from_env()
cls.db = Database(cls.settings.database_url)
migrate(cls.db)
cls.app = create_app(settings=cls.settings)
def setUp(self):
self.c = self.app.test_client()
self.password = 'Учебный:пароль-12345'
self.name = 'u_' + uuid4().hex[:16]
self.registration = {'username': self.name, 'display_name': 'Имя 👋', 'password': self.password}
r = self.c.post('/api/v1/users', json=self.registration)
self.assertEqual(r.status_code, 201)
self.user = r.json
self.basic = {'Authorization': 'Basic ' + base64.b64encode((self.name + ':' + self.password).encode()).decode()}
r = self.c.post('/api/v1/auth/sessions', headers=self.basic)
self.assertEqual(r.status_code, 201)
self.session = r.json
self.headers = {'Authorization': 'Bearer ' + self.session['token'], 'Idempotency-Key': uuid4().hex}
self.chat = self.c.post('/api/v1/chats', headers=self.headers, json={
'title': 'Учебный чат', 'member_ids': [self.user['id']]}).json
self.path = '/api/v1/chats/' + self.chat['id'] + '/messages'
def error(self, response, status):
self.assertEqual(response.status_code, status)
self.assertEqual(response.json['error']['request_id'], response.headers['X-Request-Id'])
def test_authentication_and_logout(self):
for headers in [{}, self.basic, {'X-User-Id': self.user['id']}, {'Authorization': 'Bearer bad'}]:
r = self.c.get('/api/v1/users/me', headers=headers)
self.error(r, 401)
self.assertEqual(r.headers['WWW-Authenticate'], 'Bearer realm="messenger"')
for auth in ['Basic bad', 'Bearer bad', 'Basic ' + base64.b64encode((self.name + ':wrong-password').encode()).decode()]:
r = self.c.post('/api/v1/auth/sessions', headers={'Authorization': auth})
self.error(r, 401)
self.assertEqual(r.headers['WWW-Authenticate'], 'Basic realm="messenger", charset="UTF-8"')
r = self.c.get('/api/v1/users/me', headers=dict(self.headers, **{'X-User-Id': str(uuid4())}))
self.assertEqual(r.json, self.user)
self.error(self.c.post('/api/v1/auth/sessions', headers=self.basic, json={}), 400)
r = self.c.delete('/api/v1/auth/sessions/current', headers=self.headers)
self.assertEqual((r.status_code, r.data), (204, b''))
self.error(self.c.get('/api/v1/users/me', headers=self.headers), 401)
self.error(self.c.delete('/api/v1/auth/sessions/current', headers=self.headers), 401)
def test_expiry_and_restart_app(self):
short = create_app(settings=replace(self.settings, session_ttl=2)).test_client()
r = short.post('/api/v1/auth/sessions', headers=self.basic)
self.assertEqual(r.status_code, 201)
headers = {'Authorization': 'Bearer ' + r.json['token']}
self.assertEqual(short.get('/api/v1/users/me', headers=headers).status_code, 200)
# New app instance must respect the stored original expiry, not renew it.
restarted = create_app(settings=replace(self.settings, session_ttl=3600)).test_client()
self.assertEqual(restarted.get('/api/v1/users/me', headers=headers).status_code, 200)
time.sleep(2.1)
self.error(restarted.get('/api/v1/users/me', headers=headers), 401)
def test_strict_validation_and_private_chat(self):
self.error(self.c.post('/api/v1/users', data='{', content_type='application/json'), 400)
self.error(self.c.post('/api/v1/users', json=self.registration), 409)
for patch in [{'password': 'short'}, {'password': 42}, {'display_name': ' '}, {'extra': 1}]:
self.error(self.c.post('/api/v1/users', json=dict(self.registration, **patch)), 400)
self.error(self.c.post(self.path, headers=self.headers, json={'text': ' \n'}), 400)
self.error(self.c.post(self.path, headers=self.headers, json={'text': 'x', 'sender_id': self.user['id']}), 400)
self.error(self.c.get('/api/v1/chats/' + str(uuid4()), headers=self.headers), 404)
outsider = 'u_' + uuid4().hex[:16]
self.c.post('/api/v1/users', json=dict(self.registration, username=outsider))
basic = {'Authorization': 'Basic ' + base64.b64encode((outsider + ':' + self.password).encode()).decode()}
token = self.c.post('/api/v1/auth/sessions', headers=basic).json['token']
self.error(self.c.get(self.path, headers={'Authorization': 'Bearer ' + token}), 404)
def test_pagination_survives_new_app(self):
expected = [self.c.post(self.path, headers=dict(self.headers, **{'Idempotency-Key': uuid4().hex}), json={'text': str(i)}).json for i in range(5)]
first = self.c.get(self.path + '?limit=2', headers=self.headers).json
cursor = first['next_cursor']
new_client = create_app(settings=self.settings).test_client()
second = new_client.get(self.path, query_string={'limit': 1, 'cursor': cursor}, headers=self.headers).json
third = new_client.get(self.path, query_string={'limit': 100, 'cursor': second['next_cursor']}, headers=self.headers).json
self.assertEqual(first['items'] + second['items'] + third['items'], expected)
self.assertIsNone(third['next_cursor'])
self.error(self.c.get('/api/v1/chats', query_string={'cursor': cursor}, headers=self.headers), 400)
other = self.c.post('/api/v1/chats', headers=self.headers, json={'title': 'Other', 'member_ids': [self.user['id']]}).json
self.error(self.c.get('/api/v1/chats/' + other['id'] + '/messages', query_string={'cursor': cursor}, headers=self.headers), 400)
for limit in ['0', '101', '1.5', 'true']:
self.error(self.c.get(self.path, query_string={'limit': limit}, headers=self.headers), 400)
self.error(self.c.get(self.path, query_string={'cursor': 'invalid'}, headers=self.headers), 400)
page = self.c.get('/api/v1/chats?limit=1', headers=self.headers).json
last = self.c.get('/api/v1/chats', query_string={'cursor': page['next_cursor']}, headers=self.headers).json
self.assertEqual(len(page['items'] + last['items']), 2)
def test_atomic_chat_and_migration_repeat(self):
with self.db.transaction() as conn:
before = conn.execute('SELECT count(*) AS n FROM chats').fetchone()['n']
for members in [[self.user['id'], str(uuid4())], [self.user['id'], self.user['id']], []]:
self.error(self.c.post('/api/v1/chats', headers=self.headers,
json={'title': 'Invalid', 'member_ids': members}), 400)
migrate(self.db)
migrate(self.db)
with self.db.transaction() as conn:
self.assertEqual(conn.execute('SELECT count(*) AS n FROM chats').fetchone()['n'], before)
self.assertEqual(conn.execute('SELECT count(*) AS n FROM schema_migrations').fetchone()['n'], 3)
row = conn.execute('SELECT password_hash FROM users WHERE id=%s', (self.user['id'],)).fetchone()
self.assertTrue(row['password_hash'].startswith('$argon2id$'))
hashes = [r['token_hash'] for r in conn.execute('SELECT token_hash FROM sessions WHERE user_id=%s', (self.user['id'],))]
self.assertNotIn(self.session['token'], hashes)
self.assertEqual(self.c.get('/api/v1/users/me', headers=self.headers).json, self.user)
def test_idempotency_expiry_and_errors(self):
first = self.c.post(self.path, headers=self.headers, json={'text': 'Persist me'})
self.assertEqual(first.status_code, 201)
replay = self.c.post(self.path, headers=self.headers, json={'text': 'Persist me'})
self.assertEqual(replay.json, first.json)
self.error(self.c.post(self.path, headers=self.headers, json={'text': 'Different'}), 409)
for key in ['', 'bad key', 'x' * 129]:
self.error(self.c.post(self.path, headers=dict(self.headers, **{'Idempotency-Key': key}), json={'text': 'Text'}), 400)
# Expire only this test's synthetic record, without waiting 24 hours.
with self.db.transaction() as conn:
row = conn.execute("SELECT expires_at>clock_timestamp()+interval '23 hours' AS valid FROM message_requests WHERE user_id=%s", (self.user['id'],)).fetchone()
self.assertTrue(row['valid'])
conn.execute("UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=%s", (self.user['id'],))
new = self.c.post(self.path, headers=self.headers, json={'text': 'New after expiry'})
self.assertEqual(new.status_code, 201)
self.assertNotEqual(new.json['id'], first.json['id'])
self.assertEqual(len(self.c.get(self.path, headers=self.headers).json['items']), 2)
if __name__ == '__main__':
unittest.main()