From cc4e4c53a912813af4806ab996f2cbd84e7ed41f Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 12:30:52 -0300 Subject: [PATCH 1/8] copy elixire test user impl --- tests/common.py | 43 ++++++++++++++++++++++++++ tests/conftest.py | 73 ++++++++++++++++++++++++++++++++++++++++++++- tests/test_guild.py | 15 +++------- 3 files changed, 119 insertions(+), 12 deletions(-) diff --git a/tests/common.py b/tests/common.py index a7d5cbe..66d67c6 100644 --- a/tests/common.py +++ b/tests/common.py @@ -17,6 +17,7 @@ along with this program. If not, see . """ +import secrets from .credentials import CREDS async def login(acc_name: str, test_cli): @@ -44,3 +45,45 @@ async def get_uid(token, test_cli): rjson = await resp.json return rjson['id'] + + +def email() -> str: + return f'{secrets.token_hex(5)}@{secrets.token_hex(5)}.com' + + +class TestClient: + """Test client that wraps pytest-sanic's TestClient and a test + user and adds authorization headers to test requests.""" + def __init__(self, test_cli, test_user): + self.cli = test_cli + self.user = test_user + + def __getitem__(self, key): + return self.user[key] + + def _inject_auth(self, kwargs: dict) -> list: + """Inject the test user's API key into the test request before + passing the request on to the underlying TestClient.""" + headers = kwargs.get('headers', {}) + headers['authorization'] = self.user['token'] + return headers + + async def get(self, *args, **kwargs): + """Send a GET request.""" + kwargs['headers'] = self._inject_auth(kwargs) + return await self.cli.get(*args, **kwargs) + + async def post(self, *args, **kwargs): + """Send a POST request.""" + kwargs['headers'] = self._inject_auth(kwargs) + return await self.cli.post(*args, **kwargs) + + async def patch(self, *args, **kwargs): + """Send a PATCH request.""" + kwargs['headers'] = self._inject_auth(kwargs) + return await self.cli.patch(*args, **kwargs) + + async def delete(self, *args, **kwargs): + """Send a DELETE request.""" + kwargs['headers'] = self._inject_auth(kwargs) + return await self.cli.delete(*args, **kwargs) diff --git a/tests/conftest.py b/tests/conftest.py index 48c5726..f12f610 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,7 +17,7 @@ along with this program. If not, see . """ -import asyncio +import secrets import sys import os @@ -27,8 +27,14 @@ import pytest # this is very hacky. sys.path.append(os.getcwd()) +from tests.common import email, TestClient + from run import app as main_app, set_blueprints +from litecord.auth import create_user +from litecord.blueprints.auth import make_token +from litecord.blueprints.users import delete_user + @pytest.fixture(name='app') def _test_app(unused_tcp_port, event_loop): @@ -61,3 +67,68 @@ def _test_app(unused_tcp_port, event_loop): def _test_cli(app): """Give a test client.""" return app.test_client() + +# code shamelessly stolen from my elixire mr +# https://gitlab.com/elixire/elixire/merge_requests/52 +async def _user_fixture_setup(app): + username = secrets.token_hex(6) + password = secrets.token_hex(6) + user_email = email() + + # TODO context? + + user_id, pwd_hash = await create_user( + username, user_email, password, app.db, app.loop) + + # generate a token for api access + user_token = make_token(user_id, pwd_hash) + + return {'id': user_id, 'token': user_token, + 'email': user_email, 'username': username, + 'password': password} + + +async def _user_fixture_teardown(app, udata: dict): + await delete_user(udata['id'], db=app.db) + + +@pytest.fixture(name='test_user') +async def test_user_fixture(app): + """Yield a randomly generated test user.""" + udata = await _user_fixture_setup(app) + yield udata + await _user_fixture_teardown(app, udata) + + +@pytest.fixture +async def test_cli_user(test_cli, test_user): + """Yield a TestClient instance that contains a randomly generated + user.""" + yield TestClient(test_cli, test_user) + + +@pytest.fixture +async def test_cli_admin(test_cli): + """Yield a TestClient referencing an admin. + + This does not use the test_user because if a given test uses both + test_cli_user and test_cli_admin, test_cli_admin will just point to that + same test_cli_user, which isn't acceptable. + """ + test_user = await _user_fixture_setup(test_cli.app) + + await test_cli.app.db.execute(""" + UPDATE users SET admin = true WHERE user_id = $1 + """, test_user['id']) + + await test_cli.app.db.execute(""" + INSERT INTO domain_owners (domain_id, user_id) + VALUES (0, $1) + ON CONFLICT ON CONSTRAINT domain_owners_pkey + DO UPDATE + SET user_id = $1 + WHERE domain_owners.domain_id = 0 + """, test_user['id']) + + yield TestClient(test_cli, test_user) + await _user_fixture_teardown(test_cli.app, test_user) diff --git a/tests/test_guild.py b/tests/test_guild.py index f4aee70..dcb850e 100644 --- a/tests/test_guild.py +++ b/tests/test_guild.py @@ -23,19 +23,16 @@ import pytest from tests.common import login @pytest.mark.asyncio -async def test_guild_create(test_cli): +async def test_guild_create(test_cli_user): """Test the creation of a guild, in three stages: - creating it - checking the list - deleting it """ - token = await login('normal', test_cli) g_name = secrets.token_hex(5) # stage 1: create - resp = await test_cli.post('/api/v6/guilds', headers={ - 'Authorization': token - }, json={ + resp = await test_cli_user.post('/api/v6/guilds', json={ 'name': g_name, 'region': None, }) @@ -53,9 +50,7 @@ async def test_guild_create(test_cli): guild_id = created['id'] # stage 2: test - resp = await test_cli.get('/api/v6/users/@me/guilds', headers={ - 'Authorization': token - }) + resp = await test_cli_user.get('/api/v6/users/@me/guilds') assert resp.status_code == 200 rjson = await resp.json @@ -85,8 +80,6 @@ async def test_guild_create(test_cli): assert our_guild['name'] == created['name'] # stage 3: deletion - resp = await test_cli.delete(f'/api/v6/guilds/{guild_id}', headers={ - 'Authorization': token - }) + resp = await test_cli_user.delete(f'/api/v6/guilds/{guild_id}') assert resp.status_code == 204 From 7b07254741ab20061190173b6beab6697d377695 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 12:34:51 -0300 Subject: [PATCH 2/8] test_cli_admin -> test_cli_staff --- tests/conftest.py | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index f12f610..2614f3b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -32,6 +32,7 @@ from tests.common import email, TestClient from run import app as main_app, set_blueprints from litecord.auth import create_user +from litecord.enums import UserFlags from litecord.blueprints.auth import make_token from litecord.blueprints.users import delete_user @@ -75,8 +76,6 @@ async def _user_fixture_setup(app): password = secrets.token_hex(6) user_email = email() - # TODO context? - user_id, pwd_hash = await create_user( username, user_email, password, app.db, app.loop) @@ -108,27 +107,25 @@ async def test_cli_user(test_cli, test_user): @pytest.fixture -async def test_cli_admin(test_cli): - """Yield a TestClient referencing an admin. +async def test_cli_staff(test_cli): + """Yield a TestClient with a staff user.""" + # This does not use the test_user because if a given test uses both + # test_cli_user and test_cli_admin, test_cli_admin will just point to that + # same test_cli_user, which isn't acceptable. + app = test_cli.app + test_user = await _user_fixture_setup(app) + user_id = test_user['id'] - This does not use the test_user because if a given test uses both - test_cli_user and test_cli_admin, test_cli_admin will just point to that - same test_cli_user, which isn't acceptable. - """ - test_user = await _user_fixture_setup(test_cli.app) + # copied from manage.cmd.users.set_user_staff. + old_flags = await app.db.fetchval(""" + SELECT flags FROM users WHERE id = $1 + """, user_id) - await test_cli.app.db.execute(""" - UPDATE users SET admin = true WHERE user_id = $1 - """, test_user['id']) + new_flags = old_flags | UserFlags.staff - await test_cli.app.db.execute(""" - INSERT INTO domain_owners (domain_id, user_id) - VALUES (0, $1) - ON CONFLICT ON CONSTRAINT domain_owners_pkey - DO UPDATE - SET user_id = $1 - WHERE domain_owners.domain_id = 0 - """, test_user['id']) + await app.db.execute(""" + UPDATE users SET flags = $1 WHERE id = $2 + """, new_flags, user_id) yield TestClient(test_cli, test_user) await _user_fixture_teardown(test_cli.app, test_user) From 30902d6e8fe9f963c99305921feadb6237175cc4 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 12:51:40 -0300 Subject: [PATCH 3/8] update many tests to the new TestClient fixture --- tests/test_admin_api/test_guilds.py | 50 ++++++----------- tests/test_admin_api/test_instance_invites.py | 41 ++++---------- tests/test_admin_api/test_users.py | 54 +++++++------------ tests/test_gateway.py | 10 +--- tests/test_guild.py | 1 - tests/test_no_tracking.py | 11 +--- tests/test_user.py | 26 +++------ tests/test_websocket.py | 22 ++++---- 8 files changed, 68 insertions(+), 147 deletions(-) diff --git a/tests/test_admin_api/test_guilds.py b/tests/test_admin_api/test_guilds.py index e3183f5..e87309e 100644 --- a/tests/test_admin_api/test_guilds.py +++ b/tests/test_admin_api/test_guilds.py @@ -21,18 +21,13 @@ import secrets import pytest -from tests.common import login from litecord.blueprints.guilds import delete_guild from litecord.errors import GuildNotFound -async def _create_guild(test_cli, *, token=None): - token = token or await login('admin', test_cli) - +async def _create_guild(test_cli_staff): genned_name = secrets.token_hex(6) - resp = await test_cli.post('/api/v6/guilds', headers={ - 'Authorization': token - }, json={ + resp = await test_cli_staff.post('/api/v6/guilds', json={ 'name': genned_name, 'region': None }) @@ -45,12 +40,8 @@ async def _create_guild(test_cli, *, token=None): return rjson -async def _fetch_guild(test_cli, guild_id, *, token=None, ret_early=False): - token = token or await login('admin', test_cli) - - resp = await test_cli.get(f'/api/v6/admin/guilds/{guild_id}', headers={ - 'Authorization': token - }) +async def _fetch_guild(test_cli_staff, guild_id, *, ret_early=False): + resp = await test_cli_staff.get(f'/api/v6/admin/guilds/{guild_id}') if ret_early: return resp @@ -64,23 +55,21 @@ async def _fetch_guild(test_cli, guild_id, *, token=None, ret_early=False): @pytest.mark.asyncio -async def test_guild_fetch(test_cli): +async def test_guild_fetch(test_cli_staff): """Test the creation and fetching of a guild via the Admin API.""" - token = await login('admin', test_cli) - rjson = await _create_guild(test_cli, token=token) + rjson = await _create_guild(test_cli_staff) guild_id = rjson['id'] try: - await _fetch_guild(test_cli, guild_id) + await _fetch_guild(test_cli_staff, guild_id) finally: - await delete_guild(int(guild_id), app_=test_cli.app) + await delete_guild(int(guild_id), app_=test_cli_staff.test_cli.app) @pytest.mark.asyncio -async def test_guild_update(test_cli): +async def test_guild_update(test_cli_staff): """Test the update of a guild via the Admin API.""" - token = await login('admin', test_cli) - rjson = await _create_guild(test_cli, token=token) + rjson = await _create_guild(test_cli_staff, token=token) guild_id = rjson['id'] assert not rjson['unavailable'] @@ -103,30 +92,25 @@ async def test_guild_update(test_cli): assert rjson['id'] == guild_id assert rjson['unavailable'] - rjson = await _fetch_guild(test_cli, guild_id, token=token) + rjson = await _fetch_guild(test_cli_staff, guild_id) assert rjson['unavailable'] finally: - await delete_guild(int(guild_id), app_=test_cli.app) + await delete_guild(int(guild_id), app_=test_cli_staff.test_cli.app) @pytest.mark.asyncio -async def test_guild_delete(test_cli): +async def test_guild_delete(test_cli_staff): """Test the update of a guild via the Admin API.""" - token = await login('admin', test_cli) - rjson = await _create_guild(test_cli, token=token) + rjson = await _create_guild(test_cli_staff) guild_id = rjson['id'] try: - resp = await test_cli.delete( - f'/api/v6/admin/guilds/{guild_id}', - headers={ - 'Authorization': token - }) + resp = await test_cli_staff.delete(f'/api/v6/admin/guilds/{guild_id}') assert resp.status_code == 204 - resp = await _fetch_guild(test_cli, guild_id, token=token, - ret_early=True) + resp = await _fetch_guild( + test_cli_staff, guild_id, ret_early=True) assert resp.status_code == 404 rjson = await resp.json diff --git a/tests/test_admin_api/test_instance_invites.py b/tests/test_admin_api/test_instance_invites.py index aef9fb8..9bdeba5 100644 --- a/tests/test_admin_api/test_instance_invites.py +++ b/tests/test_admin_api/test_instance_invites.py @@ -19,15 +19,9 @@ along with this program. If not, see . import pytest -from tests.common import login -async def _get_invs(test_cli, token=None): - if token is None: - token = await login('admin', test_cli) - - resp = await test_cli.get('/api/v6/admin/instance/invites', headers={ - 'Authorization': token - }) +async def _get_invs(test_cli): + resp = await test_cli.get('/api/v6/admin/instance/invites') assert resp.status_code == 200 rjson = await resp.json @@ -36,34 +30,25 @@ async def _get_invs(test_cli, token=None): @pytest.mark.asyncio -async def test_get_invites(test_cli): +async def test_get_invites(test_cli_staff): """Test the listing of instance invites.""" - await _get_invs(test_cli) + await _get_invs(test_cli_staff) @pytest.mark.asyncio -async def test_inv_delete_invalid(test_cli): +async def test_inv_delete_invalid(test_cli_staff): """Test errors happen when trying to delete a non-existing instance invite.""" - token = await login('admin', test_cli) - resp = await test_cli.delete( - '/api/v6/admin/instance/invites/aaaaaaaaaa', - headers={ - 'Authorization': token - } - ) + resp = await test_cli_staff.delete('/api/v6/admin/instance/invites/aaaaaa') assert resp.status_code == 404 @pytest.mark.asyncio -async def test_create_invite(test_cli): +async def test_create_invite(test_cli_staff): """Test the creation of an instance invite, then listing it, then deleting it.""" - token = await login('admin', test_cli) - resp = await test_cli.put('/api/v6/admin/instance/invites', headers={ - 'Authorization': token - }, json={ + resp = await test_cli_staff.put('/api/v6/admin/instance/invites', json={ 'max_uses': 1 }) @@ -73,15 +58,11 @@ async def test_create_invite(test_cli): code = rjson['code'] # assert that the invite is in the list - invites = await _get_invs(test_cli, token) + invites = await _get_invs(test_cli_staff) assert any(inv['code'] == code for inv in invites) # delete it, and assert it worked - resp = await test_cli.delete( - f'/api/v6/admin/instance/invites/{code}', - headers={ - 'Authorization': token - } - ) + resp = await test_cli_staff.delete( + f'/api/v6/admin/instance/invites/{code}') assert resp.status_code == 204 diff --git a/tests/test_admin_api/test_users.py b/tests/test_admin_api/test_users.py index fc911cb..841711a 100644 --- a/tests/test_admin_api/test_users.py +++ b/tests/test_admin_api/test_users.py @@ -21,28 +21,24 @@ import secrets import pytest -from tests.common import login from tests.credentials import CREDS from litecord.enums import UserFlags -async def _search(test_cli, *, username='', discrim='', token=None): - token = token or await login('admin', test_cli) - +async def _search(test_cli, *, username='', discrim=''): query_string = { 'username': username, 'discriminator': discrim } - return await test_cli.get('/api/v6/admin/users', headers={ - 'Authorization': token - }, query_string=query_string) + return await test_cli.get('/api/v6/admin/users', query_string=query_string) @pytest.mark.asyncio -async def test_list_users(test_cli): +async def test_list_users(test_cli_staff): """Try to list as many users as possible.""" - resp = await _search(test_cli, username=CREDS['admin']['username']) + resp = await _search( + test_cli_staff, username=test_cli_staff.user['username']) assert resp.status_code == 200 rjson = await resp.json @@ -50,13 +46,10 @@ async def test_list_users(test_cli): assert rjson -async def _setup_user(test_cli, *, token=None) -> dict: - token = token or await login('admin', test_cli) +async def _setup_user(test_cli) -> dict: genned = secrets.token_hex(7) - resp = await test_cli.post('/api/v6/admin/users', headers={ - 'Authorization': token - }, json={ + resp = await test_cli.post('/api/v6/admin/users', json={ 'username': genned, 'email': f'{genned}@{genned}.com', 'password': genned, @@ -70,13 +63,9 @@ async def _setup_user(test_cli, *, token=None) -> dict: return rjson -async def _del_user(test_cli, user_id, *, token=None): +async def _del_user(test_cli, user_id): """Delete a user.""" - token = token or await login('admin', test_cli) - - resp = await test_cli.delete(f'/api/v6/admin/users/{user_id}', headers={ - 'Authorization': token - }) + resp = await test_cli.delete(f'/api/v6/admin/users/{user_id}') assert resp.status_code == 200 rjson = await resp.json @@ -93,32 +82,29 @@ async def _del_user(test_cli, user_id, *, token=None): @pytest.mark.asyncio -async def test_create_delete(test_cli): +async def test_create_delete(test_cli_staff): """Create a user. Then delete them.""" - token = await login('admin', test_cli) - - rjson = await _setup_user(test_cli, token=token) + rjson = await _setup_user(test_cli_staff) genned = rjson['username'] genned_uid = rjson['id'] try: # check if side-effects went through with a search - resp = await _search(test_cli, username=genned, token=token) + resp = await _search(test_cli_staff, username=genned) assert resp.status_code == 200 rjson = await resp.json assert isinstance(rjson, list) assert rjson[0]['id'] == genned_uid finally: - await _del_user(test_cli, genned_uid, token=token) + await _del_user(test_cli_staff, genned_uid, token=token) @pytest.mark.asyncio -async def test_user_update(test_cli): +async def test_user_update(test_cli_staff): """Test user update.""" - token = await login('admin', test_cli) - rjson = await _setup_user(test_cli, token=token) + rjson = await _setup_user(test_cli_staff) user_id = rjson['id'] @@ -126,11 +112,11 @@ async def test_user_update(test_cli): try: # set them as partner flag - resp = await test_cli.patch(f'/api/v6/admin/users/{user_id}', headers={ - 'Authorization': token - }, json={ - 'flags': UserFlags.partner, - }) + resp = await test_cli_staff.patch( + f'/api/v6/admin/users/{user_id}', + json={ + 'flags': UserFlags.partner, + }) assert resp.status_code == 200 rjson = await resp.json diff --git a/tests/test_gateway.py b/tests/test_gateway.py index e18d8e4..a160b88 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -23,8 +23,6 @@ sys.path.append(os.getcwd()) import pytest -from tests.common import login - @pytest.mark.asyncio async def test_gw(test_cli): @@ -38,13 +36,9 @@ async def test_gw(test_cli): @pytest.mark.asyncio -async def test_gw_bot(test_cli): +async def test_gw_bot(test_cli_user): """Test the Get Bot Gateway route""" - token = await login('normal', test_cli) - - resp = await test_cli.get('/api/v6/gateway/bot', headers={ - 'Authorization': token - }) + resp = await test_cli_user.get('/api/v6/gateway/bot') assert resp.status_code == 200 rjson = await resp.json diff --git a/tests/test_guild.py b/tests/test_guild.py index dcb850e..c91e676 100644 --- a/tests/test_guild.py +++ b/tests/test_guild.py @@ -20,7 +20,6 @@ import secrets import pytest -from tests.common import login @pytest.mark.asyncio async def test_guild_create(test_cli_user): diff --git a/tests/test_no_tracking.py b/tests/test_no_tracking.py index 8ac1af2..efdac93 100644 --- a/tests/test_no_tracking.py +++ b/tests/test_no_tracking.py @@ -19,8 +19,6 @@ along with this program. If not, see . import pytest -from tests.common import login - @pytest.mark.asyncio async def test_science_empty(test_cli): @@ -37,15 +35,10 @@ async def test_harvest_empty(test_cli): @pytest.mark.asyncio -async def test_consent_non_consenting(test_cli): +async def test_consent_non_consenting(test_cli_user): """Test the consent route to see if we're still on a non-consent status regarding data collection.""" - token = await login('normal', test_cli) - - resp = await test_cli.get('/api/v6/users/@me/consent', headers={ - 'Authorization': token - }) - + resp = await test_cli_user.get('/api/v6/users/@me/consent') assert resp.status_code == 200 rjson = await resp.json diff --git a/tests/test_user.py b/tests/test_user.py index 7a851a0..a83de77 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -20,15 +20,10 @@ along with this program. If not, see . import pytest import secrets -from tests.common import login, get_uid - @pytest.mark.asyncio -async def test_get_me(test_cli): - token = await login('normal', test_cli) - resp = await test_cli.get('/api/v6/users/@me', headers={ - 'Authorization': token - }) +async def test_get_me(test_cli_user): + resp = await test_cli_user.get('/api/v6/users/@me') assert resp.status_code == 200 rjson = await resp.json @@ -44,11 +39,8 @@ async def test_get_me(test_cli): @pytest.mark.asyncio -async def test_get_me_guilds(test_cli): - token = await login('normal', test_cli) - resp = await test_cli.get('/api/v6/users/@me/guilds', headers={ - 'Authorization': token - }) +async def test_get_me_guilds(test_cli_user): + resp = await test_cli_user.get('/api/v6/users/@me/guilds') assert resp.status_code == 200 rjson = await resp.json @@ -56,13 +48,9 @@ async def test_get_me_guilds(test_cli): @pytest.mark.asyncio -async def test_get_profile_self(test_cli): - token = await login('normal', test_cli) - user_id = await get_uid(token, test_cli) - - resp = await test_cli.get(f'/api/v6/users/{user_id}/profile', headers={ - 'Authorization': token - }) +async def test_get_profile_self(test_cli_user): + user_id = test_cli_user.user['id'] + resp = await test_cli_user.get(f'/api/v6/users/{user_id}/profile') assert resp.status_code == 200 rjson = await resp.json diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 826fe58..86dba0f 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -22,7 +22,6 @@ import json import pytest import websockets -from tests.common import login from litecord.gateway.opcodes import OP from litecord.gateway.websocket import decode_etf @@ -87,9 +86,8 @@ async def test_gw(test_cli): @pytest.mark.asyncio -async def test_ready(test_cli): - token = await login('normal', test_cli) - conn = await gw_start(test_cli) +async def test_ready(test_cli_user): + conn = await gw_start(test_cli_user.test_cli) # get the hello frame but ignore it await _json(conn) @@ -97,7 +95,7 @@ async def test_ready(test_cli): await _json_send(conn, { 'op': OP.IDENTIFY, 'd': { - 'token': token, + 'token': test_cli_user.user['token'], } }) @@ -112,9 +110,8 @@ async def test_ready(test_cli): @pytest.mark.asyncio -async def test_ready_fields(test_cli): - token = await login('normal', test_cli) - conn = await gw_start(test_cli) +async def test_ready_fields(test_cli_user): + conn = await gw_start(test_cli_user.test_cli) # get the hello frame but ignore it await _json(conn) @@ -122,7 +119,7 @@ async def test_ready_fields(test_cli): await _json_send(conn, { 'op': OP.IDENTIFY, 'd': { - 'token': token, + 'token': test_cli_user.user['token'], } }) @@ -153,9 +150,8 @@ async def test_ready_fields(test_cli): @pytest.mark.asyncio -async def test_heartbeat(test_cli): - token = await login('normal', test_cli) - conn = await gw_start(test_cli) +async def test_heartbeat(test_cli_user): + conn = await gw_start(test_cli_user.test_cli) # get the hello frame but ignore it await _json(conn) @@ -163,7 +159,7 @@ async def test_heartbeat(test_cli): await _json_send(conn, { 'op': OP.IDENTIFY, 'd': { - 'token': token, + 'token': test_cli_user.user['token'], } }) From 74c03f7dfaec13f7d50ce4b136a2825f11d426ef Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 12:58:51 -0300 Subject: [PATCH 4/8] fix tests --- tests/common.py | 6 ++++++ tests/test_admin_api/test_guilds.py | 14 ++++++-------- tests/test_admin_api/test_users.py | 5 ++--- tests/test_websocket.py | 6 +++--- 4 files changed, 17 insertions(+), 14 deletions(-) diff --git a/tests/common.py b/tests/common.py index 66d67c6..284b302 100644 --- a/tests/common.py +++ b/tests/common.py @@ -56,6 +56,7 @@ class TestClient: user and adds authorization headers to test requests.""" def __init__(self, test_cli, test_user): self.cli = test_cli + self.app = test_cli.app self.user = test_user def __getitem__(self, key): @@ -78,6 +79,11 @@ class TestClient: kwargs['headers'] = self._inject_auth(kwargs) return await self.cli.post(*args, **kwargs) + async def put(self, *args, **kwargs): + """Send a POST request.""" + kwargs['headers'] = self._inject_auth(kwargs) + return await self.cli.put(*args, **kwargs) + async def patch(self, *args, **kwargs): """Send a PATCH request.""" kwargs['headers'] = self._inject_auth(kwargs) diff --git a/tests/test_admin_api/test_guilds.py b/tests/test_admin_api/test_guilds.py index e87309e..d1156e0 100644 --- a/tests/test_admin_api/test_guilds.py +++ b/tests/test_admin_api/test_guilds.py @@ -63,13 +63,13 @@ async def test_guild_fetch(test_cli_staff): try: await _fetch_guild(test_cli_staff, guild_id) finally: - await delete_guild(int(guild_id), app_=test_cli_staff.test_cli.app) + await delete_guild(int(guild_id), app_=test_cli_staff.app) @pytest.mark.asyncio async def test_guild_update(test_cli_staff): """Test the update of a guild via the Admin API.""" - rjson = await _create_guild(test_cli_staff, token=token) + rjson = await _create_guild(test_cli_staff) guild_id = rjson['id'] assert not rjson['unavailable'] @@ -78,11 +78,9 @@ async def test_guild_update(test_cli_staff): # would be overkill to test the side-effects, so... I'm not # testing them. Yes, I know its a bad idea, but if someone has an easier # way to write that, do send an MR. - resp = await test_cli.patch( + resp = await test_cli_staff.patch( f'/api/v6/admin/guilds/{guild_id}', - headers={ - 'Authorization': token - }, json={ + json={ 'unavailable': True }) @@ -95,7 +93,7 @@ async def test_guild_update(test_cli_staff): rjson = await _fetch_guild(test_cli_staff, guild_id) assert rjson['unavailable'] finally: - await delete_guild(int(guild_id), app_=test_cli_staff.test_cli.app) + await delete_guild(int(guild_id), app_=test_cli_staff.app) @pytest.mark.asyncio @@ -118,4 +116,4 @@ async def test_guild_delete(test_cli_staff): assert rjson['error'] assert rjson['code'] == GuildNotFound.error_code finally: - await delete_guild(int(guild_id), app_=test_cli.app) + await delete_guild(int(guild_id), app_=test_cli_staff.app) diff --git a/tests/test_admin_api/test_users.py b/tests/test_admin_api/test_users.py index 841711a..a78acf7 100644 --- a/tests/test_admin_api/test_users.py +++ b/tests/test_admin_api/test_users.py @@ -21,7 +21,6 @@ import secrets import pytest -from tests.credentials import CREDS from litecord.enums import UserFlags @@ -98,7 +97,7 @@ async def test_create_delete(test_cli_staff): assert isinstance(rjson, list) assert rjson[0]['id'] == genned_uid finally: - await _del_user(test_cli_staff, genned_uid, token=token) + await _del_user(test_cli_staff, genned_uid) @pytest.mark.asyncio @@ -126,4 +125,4 @@ async def test_user_update(test_cli_staff): # TODO: maybe we can check for side effects by fetching the # user manually too... finally: - await _del_user(test_cli, user_id, token=token) + await _del_user(test_cli_staff, user_id) diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 86dba0f..dc31235 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -87,7 +87,7 @@ async def test_gw(test_cli): @pytest.mark.asyncio async def test_ready(test_cli_user): - conn = await gw_start(test_cli_user.test_cli) + conn = await gw_start(test_cli_user.cli) # get the hello frame but ignore it await _json(conn) @@ -111,7 +111,7 @@ async def test_ready(test_cli_user): @pytest.mark.asyncio async def test_ready_fields(test_cli_user): - conn = await gw_start(test_cli_user.test_cli) + conn = await gw_start(test_cli_user.cli) # get the hello frame but ignore it await _json(conn) @@ -151,7 +151,7 @@ async def test_ready_fields(test_cli_user): @pytest.mark.asyncio async def test_heartbeat(test_cli_user): - conn = await gw_start(test_cli_user.test_cli) + conn = await gw_start(test_cli_user.cli) # get the hello frame but ignore it await _json(conn) From cde6bc8ed8c555bf1fc967e0b6bcc7f0bdbb1f5d Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 12:59:24 -0300 Subject: [PATCH 5/8] update gitlab-ci.yml and README --- .gitlab-ci.yml | 1 - README.md | 6 ------ 2 files changed, 7 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 14cc31b..6dc2461 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -20,5 +20,4 @@ tests: - ls - cp config.ci.py config.py - pipenv run ./manage.py migrate - - pipenv run ./manage.py setup_tests - tox diff --git a/README.md b/README.md index a696c84..47eab60 100644 --- a/README.md +++ b/README.md @@ -145,13 +145,7 @@ $ pipenv run ./manage.py migrate ## Running tests -Running tests involves creating dummy users with known passwords. Because of -this, you should never setup a testing environment in production. - ```sh -# Setup any testing users: -$ pipenv run ./manage.py setup_tests - # Install tox: $ pip install tox From 103d88d8f8ab0508235330fb2c8e71107c74a20b Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 13:00:19 -0300 Subject: [PATCH 6/8] remove manage.cmd.tests --- manage/cmd/tests.py | 54 --------------------------------------------- manage/main.py | 3 +-- 2 files changed, 1 insertion(+), 56 deletions(-) delete mode 100644 manage/cmd/tests.py diff --git a/manage/cmd/tests.py b/manage/cmd/tests.py deleted file mode 100644 index 1c0900b..0000000 --- a/manage/cmd/tests.py +++ /dev/null @@ -1,54 +0,0 @@ -""" - -Litecord -Copyright (C) 2018-2019 Luna Mendes - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, version 3 of the License. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . - -""" - -from tests.credentials import CREDS -from litecord.blueprints.auth import create_user -from manage.cmd.users import set_user_staff - - -async def setup_tests(ctx, _args): - """Setup users for the testing environment.""" - for name, creds in CREDS.items(): - uid, _ = await create_user( - creds['username'], - creds['email'], - creds['password'], - ctx.db, - ctx.loop - ) - - discrim = await ctx.db.fetchval(""" - SELECT discriminator FROM users WHERE id = $1 - """, uid) - - print(f'created {name} {discrim} user: {uid}') - - if name == 'admin': - await set_user_staff(uid, ctx) - - print('OK') - - -def setup(subparser): - setup_test_parser = subparser.add_parser( - 'setup_tests', - help='Create test users', - ) - - setup_test_parser.set_defaults(func=setup_tests) diff --git a/manage/main.py b/manage/main.py index 9968eef..d475f15 100644 --- a/manage/main.py +++ b/manage/main.py @@ -26,7 +26,7 @@ from logbook import Logger from run import init_app_managers, init_app_db from manage.cmd.migration import migration -from manage.cmd import users, tests, invites +from manage.cmd import users, invites log = Logger(__name__) @@ -54,7 +54,6 @@ def init_parser(): migration(subparser) users.setup(subparser) - tests.setup(subparser) invites.setup(subparser) return parser From a26f665c8156266d4ffd24ec9c19f3a770c3c47c Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 13:00:42 -0300 Subject: [PATCH 7/8] rm tests/credentials.py --- tests/credentials.py | 37 ------------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 tests/credentials.py diff --git a/tests/credentials.py b/tests/credentials.py deleted file mode 100644 index 0d16f4c..0000000 --- a/tests/credentials.py +++ /dev/null @@ -1,37 +0,0 @@ -""" - -Litecord -Copyright (C) 2018-2019 Luna Mendes - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, version 3 of the License. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . - -""" - -""" -dummy credentials for litecord tests -""" - -CREDS = { - 'normal': { - 'username': 'testygirl', - 'email': 'girls@girls.com', - - # 10 char password should work - 'password': 'girls,,,,,' - }, - 'admin': { - 'username': 'big_girl', - 'email': 'big_girl@energy.com', - 'password': 'big_girl_dot_com', - } -} From f7de5c5596f7731bff6be1bd421929bd4b8e2beb Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 21 Jul 2019 13:02:19 -0300 Subject: [PATCH 8/8] tests.common: remove login() and get_uid() --- tests/common.py | 28 ---------------------------- tests/conftest.py | 1 - 2 files changed, 29 deletions(-) diff --git a/tests/common.py b/tests/common.py index 284b302..cc0a9b3 100644 --- a/tests/common.py +++ b/tests/common.py @@ -18,34 +18,6 @@ along with this program. If not, see . """ import secrets -from .credentials import CREDS - -async def login(acc_name: str, test_cli): - creds = CREDS[acc_name] - - resp = await test_cli.post('/api/v6/auth/login', json={ - 'email': creds['email'], - 'password': creds['password'] - }) - - if resp.status_code != 200: - raise RuntimeError(f'non-200 on login: {resp.status_code}') - - rjson = await resp.json - return rjson['token'] - - -async def get_uid(token, test_cli): - resp = await test_cli.get('/api/v6/users/@me', headers={ - 'Authorization': token - }) - - if resp.status_code != 200: - raise RuntimeError(f'non-200 on get uid: {resp.status_code}') - - rjson = await resp.json - return rjson['id'] - def email() -> str: return f'{secrets.token_hex(5)}@{secrets.token_hex(5)}.com' diff --git a/tests/conftest.py b/tests/conftest.py index 2614f3b..41e4558 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -21,7 +21,6 @@ import secrets import sys import os -import socket import pytest # this is very hacky.