102 lines
3.5 KiB
Python
102 lines
3.5 KiB
Python
import base64
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8080').rstrip('/')
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def call(method, path, body=None, token=None, raw=None, headers=None, timeout=10):
|
|
all_headers = {}
|
|
if token:
|
|
all_headers['Authorization'] = 'Bearer ' + token
|
|
if body is not None:
|
|
raw = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
|
if raw is not None:
|
|
all_headers['Content-Type'] = 'application/json'
|
|
all_headers.update(headers or {})
|
|
request = urllib.request.Request(BASE_URL + path, data=raw, headers=all_headers, method=method)
|
|
try:
|
|
response = urllib.request.urlopen(request, timeout=timeout)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
data = response.read()
|
|
return response.status, response.headers, json.loads(data) if data else None
|
|
|
|
|
|
def basic(username, password):
|
|
return {'Authorization': 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode()}
|
|
|
|
|
|
def register(label='user', password=None):
|
|
username = (label + '_' + uuid.uuid4().hex[:12])[:32]
|
|
password = password or 'Pw-' + uuid.uuid4().hex
|
|
status, _, user = call('POST', '/api/v1/users', {'username': username, 'display_name': label, 'password': password})
|
|
assert status == 201, status
|
|
return user, password
|
|
|
|
|
|
def login(username, password):
|
|
status, _, session = call('POST', '/api/v1/auth/sessions', headers=basic(username, password))
|
|
assert status == 201, status
|
|
return session
|
|
|
|
|
|
def new_user(label='user'):
|
|
user, password = register(label)
|
|
session = login(user['username'], password)
|
|
return dict(user, password=password, token=session['token'])
|
|
|
|
|
|
def new_chat(owner, *others, title='Тестовый чат'):
|
|
members = [owner['id']] + [u['id'] for u in others]
|
|
status, _, chat = call('POST', '/api/v1/chats', {'title': title, 'member_ids': members}, owner['token'])
|
|
assert status == 201, status
|
|
return chat
|
|
|
|
|
|
def read_all_messages(chat_id, token, limit):
|
|
items, cursor, pages = [], None, 0
|
|
while True:
|
|
query = '?limit=%d' % limit + ('&cursor=' + urllib.parse.quote(cursor, safe='') if cursor else '')
|
|
status, _, page = call('GET', '/api/v1/chats/%s/messages%s' % (chat_id, query), token=token)
|
|
assert status == 200, status
|
|
items += page['items']
|
|
pages += 1
|
|
cursor = page['next_cursor']
|
|
if cursor is None:
|
|
return items, pages
|
|
|
|
|
|
def compose(*args, env=None, check=True):
|
|
result = subprocess.run(['docker', 'compose', *args], cwd=ROOT, capture_output=True, text=True,
|
|
encoding='utf-8', env=env)
|
|
if check and result.returncode != 0:
|
|
raise RuntimeError('docker compose %s failed: %s' % (' '.join(args), result.stderr.strip()))
|
|
return result.stdout.strip()
|
|
|
|
|
|
def sql(query, db='messenger', service='postgres'):
|
|
return compose('exec', '-T', service, 'psql', '-U', 'messenger', '-d', db, '-X', '-tA', '-v', 'ON_ERROR_STOP=1',
|
|
'-c', query)
|
|
|
|
|
|
def wait_ready(seconds=90):
|
|
deadline = time.monotonic() + seconds
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if call('GET', '/health/ready', timeout=2)[0] == 200:
|
|
return time.monotonic()
|
|
except OSError:
|
|
pass
|
|
time.sleep(0.3)
|
|
raise AssertionError('API is not ready after %ds' % seconds)
|