Хранить отзывы сессий в PostgreSQL, сохранять U+0000, ограничить ожидание БД
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
"""Usage (стенд уже запущен через docker compose up -d):
|
||||
python student-tests/failure_check.py
|
||||
|
||||
Останавливает Valkey, затем PostgreSQL (docker compose stop, без удаления volumes),
|
||||
проверяет поведение API и восстановление после docker compose start.
|
||||
Останавливает и замораживает Valkey и PostgreSQL (docker compose stop/pause, без удаления volumes),
|
||||
проверяет поведение API и восстановление.
|
||||
"""
|
||||
import time
|
||||
import uuid
|
||||
@@ -65,6 +65,20 @@ def main():
|
||||
expect('через 6 с после unpause: /users/me', timed('GET', '/api/v1/users/me', revoked['token']), [401], 1)
|
||||
expect('через 6 с после unpause: сообщение', timed('POST', history, revoked['token'], {'text': 'после logout'}), [401], 1)
|
||||
|
||||
print('1в. Valkey на паузе: logout, рестарт API, unpause — отзыв переживает рестарт процесса')
|
||||
restarted = new_user('restart')
|
||||
call('GET', '/api/v1/users/me', token=restarted['token'])
|
||||
compose('pause', 'valkey')
|
||||
try:
|
||||
expect('logout при паузе Valkey', timed('DELETE', '/api/v1/auth/sessions/current', restarted['token']), [204], 1.5)
|
||||
compose('restart', 'api')
|
||||
wait_ready()
|
||||
finally:
|
||||
compose('unpause', 'valkey')
|
||||
time.sleep(6)
|
||||
expect('после рестарта API и unpause: /users/me', timed('GET', '/api/v1/users/me', restarted['token']), [401], 1)
|
||||
expect('после рестарта API и unpause: сообщение', timed('POST', history, restarted['token'], {'text': 'после рестарта'}), [401], 1)
|
||||
|
||||
print('2. PostgreSQL остановлен: ограниченная ошибка 503, анонимный запрос не проходит')
|
||||
compose('stop', 'postgres')
|
||||
stopped_at = time.monotonic()
|
||||
@@ -87,6 +101,24 @@ def main():
|
||||
if status != 200 or texts != ['до отказа', 'без кэша']:
|
||||
failures.append('восстановление')
|
||||
|
||||
print('4. PostgreSQL заморожен (pause): запросы получают 503 в пределах общего срока, а не зависают')
|
||||
compose('pause', 'postgres')
|
||||
try:
|
||||
expect('GET история', timed('GET', history, alice['token']), [503], 4.5)
|
||||
expect('POST сообщение', timed('POST', history, alice['token'], {'text': 'при заморозке'}), [503], 4.5)
|
||||
expect('неизвестный токен (не 200!)', timed('GET', '/api/v1/users/me', fake), [503], 4.5)
|
||||
expect('вход по Basic', timed('POST', '/api/v1/auth/sessions', headers=basic(alice['username'], alice['password'])), [503], 4.5)
|
||||
expect('/health/ready', timed('GET', '/health/ready'), [503], 2)
|
||||
expect('/health/live', timed('GET', '/health/live'), [200], 1)
|
||||
finally:
|
||||
compose('unpause', 'postgres')
|
||||
unpaused = time.monotonic()
|
||||
wait_ready()
|
||||
texts = [m['text'] for m in call('GET', history + '?limit=100', token=alice['token'])[2]['items']]
|
||||
print(' готовность через %.1f с после unpause; история: %s' % (time.monotonic() - unpaused, texts))
|
||||
if texts != ['до отказа', 'без кэша']:
|
||||
failures.append('после заморозки')
|
||||
|
||||
print('FAIL: ' + ', '.join(failures) if failures else 'PASS: отказы Valkey и PostgreSQL обработаны')
|
||||
raise SystemExit(1 if failures else 0)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from helpers import call, new_chat, new_user, read_all_messages
|
||||
from helpers import call, login, new_chat, new_user, read_all_messages
|
||||
|
||||
|
||||
class ErrorFormatMixin:
|
||||
@@ -130,12 +130,27 @@ class IdentityTest(ErrorFormatMixin, unittest.TestCase):
|
||||
forged = call('POST', '/api/v1/chats/%s/messages' % chat['id'], {'text': 'hi', 'sender_id': bob['id']}, alice['token'])
|
||||
self.assertError(forged, 400, 'invalid_request')
|
||||
|
||||
def test_nul_character_is_rejected(self):
|
||||
"""Символ NUL нельзя сохранить в PostgreSQL text -> 400, а не 500"""
|
||||
def test_nul_character_is_preserved(self):
|
||||
"""U+0000 — допустимый code point: сообщение, display_name и title сохраняются и читаются без изменений"""
|
||||
username, password = 'nul_' + uuid.uuid4().hex[:12], 'Nul-password-123'
|
||||
status, _, user = call('POST', '/api/v1/users', {'username': username, 'display_name': 'a\u0000lice', 'password': password})
|
||||
self.assertEqual((status, user['display_name']), (201, 'a\u0000lice'))
|
||||
alice = dict(user, token=login(username, password)['token'])
|
||||
self.assertEqual(call('GET', '/api/v1/users/me', token=alice['token'])[2]['display_name'], 'a\u0000lice')
|
||||
status, _, chat = call('POST', '/api/v1/chats', {'title': 't\u0000', 'member_ids': [alice['id']]}, alice['token'])
|
||||
self.assertEqual((status, chat['title']), (201, 't\u0000'))
|
||||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||||
status, _, message = call('POST', path, {'text': 'a\u0000b'}, alice['token'])
|
||||
self.assertEqual((status, message['text']), (201, 'a\u0000b'))
|
||||
self.assertEqual(call('GET', path, token=alice['token'])[2]['items'][0]['text'], 'a\u0000b')
|
||||
self.assertEqual(call('GET', '/api/v1/chats/' + chat['id'], token=alice['token'])[2]['title'], 't\u0000')
|
||||
|
||||
def test_lone_surrogate_is_rejected(self):
|
||||
"""Одиночный суррогат не кодируется в UTF-8 -> 400, а не 500"""
|
||||
alice = new_user('alice')
|
||||
chat = new_chat(alice)
|
||||
self.assertError(call('POST', '/api/v1/chats/%s/messages' % chat['id'], {'text': 'a\u0000b'}, alice['token']),
|
||||
400, 'invalid_request')
|
||||
self.assertError(call('POST', '/api/v1/chats/%s/messages' % chat['id'], raw=b'{"text": "a\\ud800b"}',
|
||||
token=alice['token']), 400, 'invalid_request')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Reference in New Issue
Block a user