#!/usr/bin/env python3 import base64 import json import os import unittest import urllib.error import urllib.request import uuid from urllib.parse import quote BASE = os.environ.get('BASE_URL', 'http://localhost:8080').rstrip('/') def call(method, path, body=None, headers=None, raw=None): h = {'Accept': 'application/json'} data = None if body is not None: data = json.dumps(body, ensure_ascii=False).encode() h['Content-Type'] = 'application/json' if raw is not None: data = raw h.update(headers or {}) req = urllib.request.Request(BASE + path, data=data, headers=h, method=method) try: resp = urllib.request.urlopen(req, timeout=10) except urllib.error.HTTPError as e: resp = e raw_body = resp.read() payload = None if raw_body: try: payload = json.loads(raw_body) except Exception: payload = None hdrs = {k.lower(): v for k, v in resp.headers.items()} return resp.code, hdrs, payload def make_user(name=None): username = name or ('u_' + uuid.uuid4().hex[:10]) password = 'T3st-' + uuid.uuid4().hex code, _, user = call('POST', '/api/v1/users', { 'username': username, 'display_name': 'User ' + username, 'password': password, }) assert code == 201, code cred = base64.b64encode((username + ':' + password).encode()).decode() code, _, session = call('POST', '/api/v1/auth/sessions', headers={ 'Authorization': 'Basic ' + cred, }) assert code == 201, code return {'user': user, 'token': session['token'], 'password': password, 'username': username} def auth(actor): return {'Authorization': 'Bearer ' + actor['token']} class OwnTests(unittest.TestCase): def test_bad_json(self): code, hdrs, body = call( 'POST', '/api/v1/users', raw=b'{not json', headers={'Content-Type': 'application/json'}, ) self.assertEqual(code, 400) self.assertTrue(hdrs.get('x-request-id')) self.assertEqual(body['error']['code'], 'invalid_request') def test_duplicate_username(self): name = 'dup_' + uuid.uuid4().hex[:8] make_user(name) code, _, body = call('POST', '/api/v1/users', { 'username': name, 'display_name': 'Other', 'password': 'T3st-' + uuid.uuid4().hex, }) self.assertEqual(code, 409) self.assertEqual(body['error']['code'], 'conflict') def test_wrong_password(self): a = make_user() bad = base64.b64encode((a['username'] + ':wrong-password-xx').encode()).decode() code, hdrs, body = call('POST', '/api/v1/auth/sessions', headers={ 'Authorization': 'Basic ' + bad, }) self.assertEqual(code, 401) self.assertTrue((hdrs.get('www-authenticate') or '').lower().startswith('basic')) self.assertEqual(body['error']['code'], 'unauthorized') def test_basic_on_business(self): a = make_user() cred = base64.b64encode((a['username'] + ':' + a['password']).encode()).decode() code, hdrs, _ = call('GET', '/api/v1/users/me', headers={ 'Authorization': 'Basic ' + cred, }) self.assertEqual(code, 401) self.assertTrue((hdrs.get('www-authenticate') or '').lower().startswith('bearer')) def test_x_user_id_ignored(self): a = make_user() b = make_user() code, _, me = call('GET', '/api/v1/users/me', headers={ 'Authorization': 'Bearer ' + a['token'], 'X-User-Id': b['user']['id'], }) self.assertEqual(code, 200) self.assertEqual(me['id'], a['user']['id']) code, _, _ = call('GET', '/api/v1/users/me', headers={ 'X-User-Id': a['user']['id'], }) self.assertEqual(code, 401) def test_logout(self): a = make_user() code, _, _ = call('DELETE', '/api/v1/auth/sessions/current', headers=auth(a)) self.assertEqual(code, 204) code, _, _ = call('GET', '/api/v1/users/me', headers=auth(a)) self.assertEqual(code, 401) code, _, _ = call('DELETE', '/api/v1/auth/sessions/current', headers=auth(a)) self.assertEqual(code, 401) def test_empty_message(self): a = make_user() b = make_user() code, _, chat = call('POST', '/api/v1/chats', { 'title': 't', 'member_ids': [a['user']['id'], b['user']['id']], }, headers=auth(a)) self.assertEqual(code, 201) path = '/api/v1/chats/' + chat['id'] + '/messages' code, _, _ = call('POST', path, {'text': ''}, headers=auth(a)) self.assertEqual(code, 400) code, _, _ = call('POST', path, {'text': ' '}, headers=auth(a)) self.assertEqual(code, 400) def test_foreign_chat(self): a = make_user() b = make_user() eve = make_user() code, _, chat = call('POST', '/api/v1/chats', { 'title': 'private', 'member_ids': [a['user']['id'], b['user']['id']], }, headers=auth(a)) self.assertEqual(code, 201) path = '/api/v1/chats/' + chat['id'] code, _, _ = call('GET', path, headers=auth(eve)) self.assertEqual(code, 404) code, _, _ = call('POST', path + '/messages', {'text': 'hi'}, headers=auth(eve)) self.assertEqual(code, 404) def test_pagination_pages(self): a = make_user() code, _, chat = call('POST', '/api/v1/chats', { 'title': 'pages', 'member_ids': [a['user']['id']], }, headers=auth(a)) self.assertEqual(code, 201) path = '/api/v1/chats/' + chat['id'] + '/messages' ids = [] for i in range(7): code, _, msg = call('POST', path, {'text': 'm%d' % i}, headers=auth(a)) self.assertEqual(code, 201) ids.append(msg['id']) seen = [] cursor = None pages = 0 while True: url = path + '?limit=2' if cursor: url += '&cursor=' + quote(cursor, safe='') code, _, page = call('GET', url, headers=auth(a)) self.assertEqual(code, 200) pages += 1 for item in page['items']: seen.append(item['id']) cursor = page['next_cursor'] if cursor is None: break self.assertEqual(pages, 4) self.assertEqual(seen, ids) self.assertEqual(len(set(seen)), 7) def test_cursor_other_chat(self): a = make_user() _, _, c1 = call('POST', '/api/v1/chats', { 'title': 'c1', 'member_ids': [a['user']['id']], }, headers=auth(a)) _, _, c2 = call('POST', '/api/v1/chats', { 'title': 'c2', 'member_ids': [a['user']['id']], }, headers=auth(a)) p1 = '/api/v1/chats/' + c1['id'] + '/messages' p2 = '/api/v1/chats/' + c2['id'] + '/messages' call('POST', p1, {'text': 'one'}, headers=auth(a)) call('POST', p1, {'text': 'two'}, headers=auth(a)) code, _, page = call('GET', p1 + '?limit=1', headers=auth(a)) self.assertEqual(code, 200) cur = page['next_cursor'] self.assertTrue(cur) code, _, body = call( 'GET', p2 + '?limit=1&cursor=' + quote(cur, safe=''), headers=auth(a), ) self.assertEqual(code, 400) self.assertEqual(body['error']['code'], 'invalid_request') if __name__ == '__main__': unittest.main()