This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
"""Additional black-box tests. Server must already be running; no secrets printed."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab2 student checks', lambda p: p.add_argument('--expiry', action='store_true'))
|
||||
c = Client(args.base_url)
|
||||
if args.expiry:
|
||||
actor = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
print('PASS: SESSION_TTL_SECONDS=2 expires existing token; no token printed.')
|
||||
return
|
||||
a, b, outsider, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
for raw in (b'{', b'null', b'[]', b'\xff'):
|
||||
c.call('POST', path, 400, actor=a, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
for data in ({'text': '\u0085'}, {'text': ' \t\n'}, {'text': 42}, {'text': 'x', 'sender_id': a['id']}):
|
||||
c.call('POST', path, 400, actor=a, body=data)
|
||||
for field in ('display_name', 'password'):
|
||||
bad = {**a['registration'], 'username': 'z_' + uuid.uuid4().hex[:12], field: '\u0085'}
|
||||
c.call('POST', '/api/v1/users', 400, body=bad)
|
||||
c.call('GET', path, 404, actor=outsider)
|
||||
c.call('POST', path, 404, actor=outsider, body={'text': 'hidden'})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': a['id']})
|
||||
c.call('GET', '/api/v1/users/me', actor=a, headers={'X-User-Id': outsider['id']}, schema='User')
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:10], 'display_name': 'Александра 😀', 'password': 'пароль:😀' * 10}
|
||||
c.call('POST', '/api/v1/users', 201, body=registration, schema='User')
|
||||
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
login = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
actor = {'id': login['user']['id'], 'token': login['token']}
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Basic ' + credential})
|
||||
c.call('POST', '/api/v1/auth/sessions', 400, headers={'Authorization': 'Basic ' + credential}, body={})
|
||||
wrong = base64.b64encode((registration['username'] + ':wrong-password-123').encode()).decode()
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + wrong})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor)
|
||||
before = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
|
||||
c.call('POST', '/api/v1/chats', 400, actor=a, body={'title': 'Invalid', 'member_ids': [a['id'], str(uuid.uuid4())]})
|
||||
after = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
|
||||
check(before == after, 'Invalid chat left partial state')
|
||||
registration = {**a['registration'], 'username': 'race_' + uuid.uuid4().hex[:12]}
|
||||
workers = threading.local()
|
||||
def initialize():
|
||||
workers.client = Client(args.base_url)
|
||||
def register(_):
|
||||
return workers.client.call('POST', '/api/v1/users', [201, 409], body=registration)['status']
|
||||
with ThreadPoolExecutor(max_workers=4, initializer=initialize) as pool:
|
||||
results = list(pool.map(register, range(4)))
|
||||
check(results.count(201) == 1 and results.count(409) == 3, 'Username uniqueness race')
|
||||
sent = list(pool.map(lambda i: workers.client.message(a, chat, 'Проверка ' + str(i))['json'], range(20)))
|
||||
c.message(b, chat, '😀' * 4000)
|
||||
seen, cursor, first_cursor = [], None, None
|
||||
while True:
|
||||
query = '?limit=3' + ('&cursor=' + quote(cursor, safe='') if cursor else '')
|
||||
response = c.call('GET', path + query, actor=b, schema='MessagePage')['json']
|
||||
seen.extend(response['items'])
|
||||
cursor = response['next_cursor']
|
||||
first_cursor = first_cursor or cursor
|
||||
if cursor is None:
|
||||
break
|
||||
check(len(seen) == 21 and len({m['id'] for m in seen}) == 21, 'Pagination lost/duplicated records')
|
||||
check(all(m in seen for m in sent), 'Confirmed message missing')
|
||||
for query in ('?limit=0', '?limit=101', '?cursor=', '?cursor=bad'):
|
||||
c.call('GET', path + query, 400, actor=a)
|
||||
second = c.call('POST', '/api/v1/chats', 201, actor=a, body={'title': 'Second', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + second['id'] + '/messages?cursor=' + quote(first_cursor), 400, actor=a)
|
||||
p1 = c.call('GET', '/api/v1/chats?limit=1', actor=a, schema='ChatPage')['json']
|
||||
p2 = c.call('GET', '/api/v1/chats?limit=100&cursor=' + quote(p1['next_cursor']), actor=a, schema='ChatPage')['json']
|
||||
check(len(p1['items'] + p2['items']) == 2 and p2['next_cursor'] is None, 'Chat pagination')
|
||||
print('PASS: Basic/Bearer/logout, Unicode passwords with colon, validation, membership, atomic invalid chat, username race and pagination of 21 messages.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
// Run inside the API container with: node < student-tests/storage.js
|
||||
const assert = require('node:assert/strict');
|
||||
const { pool, transaction } = require('./src/db');
|
||||
const { migrate } = require('./src/migrate');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
async function counts() {
|
||||
const result = {};
|
||||
for (const table of ['users', 'chats', 'chat_members', 'messages', 'sessions'])
|
||||
result[table] = (await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n;
|
||||
return result;
|
||||
}
|
||||
async function main() {
|
||||
const before = await counts();
|
||||
await migrate(); await migrate();
|
||||
assert.deepEqual(await counts(), before);
|
||||
assert.equal((await pool.query('SELECT count(*)::int AS n FROM schema_migrations')).rows[0].n, 1);
|
||||
const id = randomUUID();
|
||||
await assert.rejects(transaction(async client => {
|
||||
await client.query('INSERT INTO chats(id,title) VALUES($1,$2)', [id, 'Rollback test']);
|
||||
await client.query('INSERT INTO chat_members VALUES($1,$2)', [id, randomUUID()]);
|
||||
}), e => e.code === '23503');
|
||||
assert.equal((await pool.query('SELECT id FROM chats WHERE id=$1', [id])).rowCount, 0);
|
||||
const constraints = (await pool.query(`SELECT contype,count(*)::int AS n FROM pg_constraint
|
||||
WHERE connamespace='public'::regnamespace GROUP BY contype`)).rows;
|
||||
assert.ok(constraints.some(c => c.contype === 'f' && c.n >= 4));
|
||||
console.log('PASS: two repeated migrations preserve all row counts; FK failure rolls back chat insert; foreign keys present.');
|
||||
console.log(JSON.stringify({ counts: before, constraints }));
|
||||
}
|
||||
main().catch(error => { console.error('FAIL: storage checks (' + (error.code || error.name) + ')'); process.exitCode = 1; }).finally(() => pool.end());
|
||||
Reference in New Issue
Block a user