def post(self, request): """ This method recives the request from the user and processes it Arguments: request {request object} -- The request sent by the user Returns: JSON -- returns json reponse with the needed crendentials """ if len(request.data["password"]) <= 5: raise serializers.ValidationError( {"error_type": "Password too small"}) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() token = get_token(user=user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "name": user.name, "is_admin": user.is_superuser, "is_commerce": user.is_commerce, "token": token, })
def test_success(self): self = set_up_user(self) login_mutation_query = login_mutation_with_token login_response = make_query(login_mutation_query) token = get_token(login_response) query_with_token = ''' { viewer { user { email } } } ''' viewer_query = {"query": query_with_token} response = make_query(viewer_query, token) expected = { "data": { "viewer": { "user": { "email": "*****@*****.**" } } } } self.assertEqual(response, expected)
def test_get_admin_users(): with app.test_client() as c: rv = c.get('/cms/admin/users', headers={'Authorization': 'Bearer ' + get_token()}) json_data = rv.get_json() print(len(json_data['collection'])) assert rv.status_code == 200
async def test_change_schedule_data(world, stream_room): token = get_token(world, ["moderator"]) async with world_communicator(token=token) as c1, world_communicator() as c2: await c1.send_json_to(["room.enter", 123, {"room": str(stream_room.pk)}]) response = await c1.receive_json_from() assert response[0] == "success" await c2.send_json_to(["room.enter", 123, {"room": str(stream_room.pk)}]) response = await c2.receive_json_from() assert response[0] == "success" await c1.send_json_to( [ "room.schedule", 123, {"room": str(stream_room.pk), "schedule_data": {"session": 1}}, ] ) response = await c1.receive_json_from() assert response[0] == "success" response = await c1.receive_json_from() assert response[0] == "room.schedule" assert response[1] == { "room": str(stream_room.pk), "schedule_data": {"session": 1}, } response = await c2.receive_json_from() assert response[0] == "room.schedule" assert response[1] == { "room": str(stream_room.pk), "schedule_data": {"session": 1}, }
def test_edit_page(popclient): """Test editing annotations.""" app, client = popclient with app.test_request_context(): u = User.query.filter_by(email=TESTUSER).first() login(u, client) # annotating annotation = Annotation.query.first() url = url_for('main.edit', annotation_id=annotation.id) rv = client.get(url, follow_redirects=True) assert rv.status_code == 200 data = { 'first_line': annotation.HEAD.first_line_num + 1, 'last_line': annotation.HEAD.first_line_num + 1, 'first_char_idx': 0, 'last_char_idx': -1, 'annotation': "This is a test!", 'reason': "Testing...", 'csrf_token': get_token(rv.data) } rv = client.post(url, data=data, follow_redirects=True) assert rv.status_code == 200 # testing that it went through url = url_for('main.annotation', annotation_id=annotation.id) rv = client.get(url) assert rv.status_code == 200 assert b"This is a test!" in rv.data
async def test_config_get(world): async with world_communicator(token=get_token(world, ["admin"])) as c1: await c1.send_json_to(["world.config.get", 123, {}]) response = await c1.receive_json_from() assert response[0] == "success" del response[2]["roles"] # let this test break less often del response[2]["available_permissions"] # let this test break less often assert response[2] == { "theme": {}, "trait_grants": { "admin": ["admin"], "viewer": ["global-viewer"], "apiuser": ["api"], "speaker": ["speaker"], "attendee": [], "moderator": ["moderator"], "room_owner": ["room-owner"], "participant": ["global-participant"], "room_creator": ["room-creator"], }, "bbb_defaults": {"record": False}, "pretalx": {"domain": "https://pretalx.com/", "event": "democon"}, "title": "Unsere tolle Online-Konferenz", "locale": "en", "dateLocale": "en-ie", "videoPlayer": None, "timezone": "Europe/Berlin", "connection_limit": 2, }
async def test_config_delete(world, stream_room): async with world_communicator(token=get_token(world, ["admin"])) as c1: await c1.send_json_to(["room.delete", 123, {"room": str(stream_room.pk)}]) response = await c1.receive_json_from() assert response[0] == "success" await database_sync_to_async(stream_room.refresh_from_db)() assert stream_room.deleted
async def test_config_patch(world): async with world_communicator(token=get_token(world, ["admin"])) as c1: await c1.send_json_to(["world.config.patch", 123, {"title": "Foo"}]) response = await c1.receive_json_from() assert response[0] == "success" await database_sync_to_async(world.refresh_from_db)() assert world.title == "Foo"
def post(self, request): """ [summary] Arguments: request {[type]} -- [description] Returns: [type] -- [description] """ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data token = get_token(user=user) try: shop_obj = Shop.objects.get(user=user) except shop_obj.DoesNotExist: shop_obj = "" return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "name": user.name, "is_admin": user.is_superuser, "is_commerce": user.is_commerce, "token": token, "shop_name": shop_obj.title if shop_obj else "", "shop_slug": shop_obj.slug, "shop_logo": shop_obj.logo.url if shop_obj.logo else "", })
def test_delete_user(): with app.test_client() as c: rv = c.delete('/cms/admin/6', headers={'Authorization': 'Bearer ' + get_token()}) json_data = rv.get_json() print(json_data) assert rv.status_code == 201
def test_delete(): with app.test_client() as c: rv = c.delete('/v1/book/7', headers={'Authorization': 'Bearer ' + get_token()}) json_data = rv.get_json() print(json_data) assert json_data['msg'] == '删除图书成功' assert rv.status_code == 201
def test_change_password(): with app.test_client() as c: rv = c.put('/cms/user/', headers={'Authorization': 'Bearer ' + get_token()}, json={'email': '*****@*****.**'}) json_data = rv.get_json() print(json_data) assert rv.status_code == 201
async def test_force_join_after_login(world, chat_room): token = get_token(world, []) channel_id = str(chat_room.channel.id) async with world_communicator(token=token, named=True): pass chat_room.force_join = True await database_sync_to_async(chat_room.save)() async with world_communicator(token=token, named=False) as c2: r = await c2.receive_json_from() # new channel list assert r[0] == "chat.channels" assert channel_id in [c["id"] for c in r[1]["channels"]]
def test_invalid_credentials_login(minclient): """Test login with invalid credentials.""" app, client = minclient with app.test_request_context(): url = url_for('main.login') rv = client.get(url) assert rv.status_code == 200 data = { 'email': TESTUSER, 'password': '******', 'csrf_token': get_token(rv.data) } rv = client.post(url, data=data, follow_redirects=True) assert rv.status_code == 200 assert b'Invalid email or password' in rv.data
def test_locked_login(minclient): """Test login of locked accounts.""" app, client = minclient with app.test_request_context(): url = url_for('main.login') rv = client.get(url) assert rv.status_code == 200 data = { 'email': COMMUNITY, 'password': PASSWORD, 'csrf_token': get_token(rv.data) } rv = client.post(url, data=data, follow_redirects=True) assert rv.status_code == 200 assert b'That account is locked' in rv.data
async def test_ban_user(world): async with world_communicator() as c_admin: token = get_token(world, ["admin"]) await c_admin.send_json_to(["authenticate", {"token": token}]) await c_admin.receive_json_from() async with world_communicator() as c_user: await c_user.send_json_to(["authenticate", {"client_id": "4"}]) response = await c_user.receive_json_from() user_id = response[1]["user.config"]["id"] await c_admin.send_json_to(["user.ban", 14, {"id": user_id}]) response = await c_admin.receive_json_from() assert response[0] == "success" await c_admin.send_json_to( ["user.ban", 14, { "id": str(uuid.uuid4()) }]) response = await c_admin.receive_json_from() assert response[0] == "error" assert ["connection.reload", {}] == await c_user.receive_json_from() assert { "type": "websocket.close" } == await c_user.receive_output(timeout=3) async with world_communicator() as c_user: await c_user.send_json_to(["authenticate", {"client_id": "4"}]) response = await c_user.receive_json_from() assert response[1] == {"code": "auth.denied"} await c_admin.send_json_to(["user.reactivate", 14, {"id": user_id}]) response = await c_admin.receive_json_from() assert response[0] == "success" await c_admin.send_json_to( ["user.reactivate", 14, { "id": str(uuid.uuid4()) }]) response = await c_admin.receive_json_from() assert response[0] == "error" async with world_communicator() as c_user: await c_user.send_json_to(["authenticate", {"client_id": "4"}]) response = await c_user.receive_json_from() assert response[0] == "authenticated"
async def test_create_rooms(world, can_create_rooms, with_channel): token = get_token(world, ["admin" if can_create_rooms else "nope"]) async with world_communicator() as c: await c.send_json_to(["authenticate", {"token": token}]) response = await c.receive_json_from() assert response[0] == "authenticated" await c.send_json_to( ["user.update", 123, {"profile": {"display_name": "Foo Fighter"}}] ) await c.receive_json_from() rooms = await get_rooms(world) assert len(rooms) == 8 modules = [] if with_channel: modules.append({"type": "chat.native"}) else: modules.append({"type": "weird.module"}) await c.send_json_to( [ "room.create", 123, { "name": "New Room!!", "description": "a description", "modules": modules, }, ] ) response = await c.receive_json_from() if with_channel and can_create_rooms: assert response[0] == "success" new_rooms = await get_rooms(world) assert len(new_rooms) == len(rooms) + 1 assert response[-1]["room"] assert bool(response[-1]["channel"]) is with_channel second_response = await c.receive_json_from() assert second_response[0] == "room.create" assert response[-1]["room"] == second_response[-1]["id"] else: assert response[0] == "error" new_rooms = await get_rooms(world) assert len(new_rooms) == len(rooms)
async def test_force_join_after_profile_update(world, chat_room): token = get_token(world, []) channel_id = str(chat_room.channel.id) chat_room.force_join = True await database_sync_to_async(chat_room.save)() async with world_communicator(token=token, named=False) as c: await c.send_json_to( ["user.update", 123, { "profile": { "display_name": "Foo Fighter" } }]) await c.receive_json_from() # success r = await c.receive_json_from() # new channel list assert r[0] == "chat.channels" assert channel_id in [c["id"] for c in r[1]["channels"]]
def test_edit_page(popclient): """Test editing annotations.""" app, client = popclient with app.test_request_context(): user = User.query.filter_by(email=TESTADMIN).first() login(user, client) line = Line.query.first() testline = line.line + 'This is a test.' url = url_for('admin.edit_line', line_id=line.id) rv = client.get(url, follow_redirects=True) assert rv.status_code == 200 data = {'line': testline, 'csrf_token': get_token(rv.data)} rv = client.post(url, data=data, follow_redirects=True) assert rv.status_code == 200 assert bytes(testline, 'utf-8') in rv.data
async def test_config_get(world, stream_room): async with world_communicator(token=get_token(world, ["admin"])) as c1: await c1.send_json_to( ["room.config.get", 123, { "room": str(stream_room.pk) }]) response = await c1.receive_json_from() assert response[0] == "success" assert response[2] == { "id": str(stream_room.pk), "trait_grants": { "viewer": [], "participant": [] }, "module_config": [ { "type": "livestream.native", "config": { "hls_url": "https://s1.live.pretix.eu/hls/sample.m3u8" }, }, { "type": "chat.native", "config": { "volatile": True } }, ], "picture": None, "name": "Plenum", "force_join": False, "description": "Hier findet die Eröffnungs- und End-Veranstaltung statt", "sorting_priority": 2, "pretalx_id": 130, }
async def test_block_user(world): async with world_communicator() as c_blocker: token = get_token(world, []) await c_blocker.send_json_to(["authenticate", {"token": token}]) await c_blocker.receive_json_from() async with world_communicator() as c_blockee: await c_blockee.send_json_to(["authenticate", {"client_id": "4"}]) response = await c_blockee.receive_json_from() user_id = response[1]["user.config"]["id"] await c_blocker.send_json_to(["user.block", 14, {"id": user_id}]) response = await c_blocker.receive_json_from() assert response[0] == "success" await c_blocker.send_json_to(["user.list.blocked", 14, {}]) response = await c_blocker.receive_json_from() assert response[0] == "success" assert response[2]["users"][0]["id"] == user_id await c_blocker.send_json_to( ["user.block", 14, { "id": str(uuid.uuid4()) }]) response = await c_blocker.receive_json_from() assert response[0] == "error" await c_blocker.send_json_to(["user.unblock", 14, {"id": user_id}]) response = await c_blocker.receive_json_from() assert response[0] == "success" await c_blocker.send_json_to(["user.list.blocked", 14, {}]) response = await c_blocker.receive_json_from() assert response[0] == "success" assert not response[2]["users"] await c_blocker.send_json_to( ["user.unblock", 14, { "id": str(uuid.uuid4()) }]) response = await c_blocker.receive_json_from() assert response[0] == "error"
def test_annotate_page(popclient): """Test annotating.""" app, client = popclient with app.test_request_context(): u = User.query.filter_by(email=TESTUSER).first() login(u, client) # getting the context text = Text.query.first() edition = text.primary line = Line.query.first() # annotating count = Annotation.query.count() url = url_for('main.annotate', text_url=text.url_name, edition_num=edition.num, first_line=line.num + 1, last_line=line.num + 2) rv = client.get(url) data = { 'first_line': line.num + 1, 'last_line': line.num + 2, 'first_char_idx': 0, 'last_char_idx': -1, 'annotation': "This is a test!", 'reason': "Testing...", 'csrf_token': get_token(rv.data) } rv = client.post(url, data=data, follow_redirects=True) assert rv.status_code == 200 # checking the count newcount = Annotation.query.count() assert newcount == count + 1 # testing that it posted url = url_for('main.index') rv = client.get(url) assert b"This is a test!" in rv.data
def test_register(minclient): """Test user registration""" app, client = minclient with app.test_request_context(): url = url_for('main.register') rv = client.get(url) assert rv.status_code == 200 data = { 'displayname': 'tester', 'email': '*****@*****.**', 'password': PASSWORD, 'password2': PASSWORD, 'csrf_token': get_token(rv.data) } rv = client.post(url, data=data, follow_redirects=True) assert rv.status_code == 200 with app.test_request_context(): url = url_for('user.index') rv = client.get(url) assert b'tester' in rv.data
def test_login_logout(minclient): """Test login and logout.""" app, client = minclient with app.test_request_context(): url = url_for('main.login') rv = client.get(url) assert rv.status_code == 200 data = { 'email': TESTUSER, 'password': PASSWORD, 'csrf_token': get_token(rv.data) } rv = client.post(url, data=data, follow_redirects=True) assert rv.status_code == 200 assert b'logout' in rv.data assert b'login' not in rv.data with app.test_request_context(): url = url_for('main.logout') rv = client.get(url, follow_redirects=True) assert b'login' in rv.data assert b'logout' not in rv.data
async def test_create_rooms_unique_names(world): token = get_token(world, ["admin"]) async with world_communicator() as c: await c.send_json_to(["authenticate", {"token": token}]) response = await c.receive_json_from() assert response[0] == "authenticated" await c.send_json_to( ["user.update", 123, {"profile": {"display_name": "Foo Fighter"}}] ) await c.receive_json_from() await c.send_json_to( [ "room.create", 123, { "name": "New Room!!", "description": "a description", "modules": [{"type": "chat.native"}], }, ] ) response = await c.receive_json_from() assert response[0] == "success" await c.receive_json_from() await c.send_json_to( [ "room.create", 123, { "name": "New Room!!", "description": "a description", "modules": [{"type": "chat.native"}], }, ] ) response = await c.receive_json_from() assert response[0] == "error"
def test_decrypt_token(): with app.test_client() as client: rv = client.post('/v1/token/verify', json={'token': get_token()}) json_data = rv.get_json() format_print(json_data)
async def test_broadcast_read_channels(world, chat_room): token = get_token(world, []) channel_id = str(chat_room.channel.id) async with world_communicator(token=token) as c1, world_communicator( token=token, named=False) as c2: await c1.send_json_to(["chat.join", 123, {"channel": channel_id}]) await c1.receive_json_from() # Success await c1.receive_json_from() # Join notification c1 await c2.receive_json_from() # c2 receives new channel list # c1 sends a message await c1.send_json_to([ "chat.send", 123, { "channel": channel_id, "event_type": "channel.message", "content": { "type": "text", "body": "Hello world" }, }, ]) await c1.receive_json_from() # success response = await c1.receive_json_from() # receives message event_id = response[1]["event_id"] # c1 gets a notification pointer (useless, but currently the case) response = await c1.receive_json_from( ) # receives notification pointer assert response[0] == "chat.notification_pointers" assert channel_id in response[1] # c2 gets a notification pointer response = await c2.receive_json_from( ) # receives notification pointer assert response[0] == "chat.notification_pointers" assert channel_id in response[1] # c2 confirms they read the message await c2.send_json_to([ "chat.mark_read", 123, { "channel": channel_id, "id": event_id, }, ]) await c2.receive_json_from() # success response = await c1.receive_json_from() assert response == ["chat.read_pointers", {channel_id: event_id}] with pytest.raises(asyncio.TimeoutError): await c1.receive_json_from() # no message to either client with pytest.raises(asyncio.TimeoutError): await c2.receive_json_from() # no message to either client async with world_communicator(token=token) as c3: assert c3.context["chat.channels"] == [{ "id": channel_id, "notification_pointer": event_id, }] assert c3.context["chat.read_pointers"] == {channel_id: event_id}
async def test_unread_channels(world, chat_room): sender_token = get_token(world, []) receiver_token = get_token(world, []) channel_id = str(chat_room.channel.id) async with world_communicator( token=sender_token) as c1, world_communicator( token=receiver_token) as c2: # Setup. Both clients join, then c2 unsubscribes again ("background tab") await c1.send_json_to(["chat.join", 123, {"channel": channel_id}]) await c1.receive_json_from() # Success await c1.receive_json_from() # Join notification c1 await c2.send_json_to(["chat.join", 123, {"channel": channel_id}]) await c2.receive_json_from() # Success await c1.receive_json_from() # Join notification c2 await c2.receive_json_from() # Join notification c2 await c2.send_json_to( ["chat.unsubscribe", 123, { "channel": channel_id }]) await c2.receive_json_from() # Success # c1 sends a message await c1.send_json_to([ "chat.send", 123, { "channel": channel_id, "event_type": "channel.message", "content": { "type": "text", "body": "Hello world" }, }, ]) await c1.receive_json_from() # success await c1.receive_json_from() # receives message # c1 gets a notification pointer (useless, but currently the case) response = await c1.receive_json_from( ) # receives notification pointer assert response[0] == "chat.notification_pointers" assert channel_id in response[1] # c2 gets a notification pointer response = await c2.receive_json_from( ) # receives notification pointer assert response[0] == "chat.notification_pointers" assert channel_id in response[1] # c1 sends a message await c1.send_json_to([ "chat.send", 123, { "channel": channel_id, "event_type": "channel.message", "content": { "type": "text", "body": "Hello world" }, }, ]) await c1.receive_json_from() # success response = await c1.receive_json_from() # receives message event_id = response[1]["event_id"] # nobody gets a notification pointer since both are in "unread" state # c2 confirms they read the message await c2.send_json_to([ "chat.mark_read", 123, { "channel": channel_id, "id": event_id, }, ]) await c2.receive_json_from() # success # c1 sends a message await c1.send_json_to([ "chat.send", 123, { "channel": channel_id, "event_type": "channel.message", "content": { "type": "text", "body": "Hello world" }, }, ]) await c1.receive_json_from() # success await c1.receive_json_from() # receives message # c2 gets a notification pointer response = await c2.receive_json_from( ) # receives notification pointer assert response[0] == "chat.notification_pointers" assert response[1] == {channel_id: event_id + 1} with pytest.raises(asyncio.TimeoutError): await c1.receive_json_from() # no message to either client with pytest.raises(asyncio.TimeoutError): await c2.receive_json_from() # no message to either client
async def test_edit_messages(world, chat_room, editor, editee, message_type, success): editor_token = get_token(world, [editor]) editee_token = get_token(world, [editee]) if editor != editee else None channel_id = str(chat_room.channel.id) async with world_communicator( token=editor_token) as c1, world_communicator( token=editee_token) as c2: # Setup await c1.send_json_to(["chat.join", 123, {"channel": channel_id}]) await c1.receive_json_from() # Success await c1.receive_json_from() # Join notification c1 await c2.send_json_to(["chat.join", 123, {"channel": channel_id}]) await c2.receive_json_from() # Success await c1.receive_json_from() # Join notification c2 await c2.receive_json_from() # Join notification c2 edit_self = editor == editee editor, not_editor = c1, c2 editee, not_editee = (c1, c2) if edit_self else (c2, c1) await editee.send_json_to([ "chat.send", 123, { "channel": channel_id, "event_type": "channel.message", "content": { "type": "text", "body": "Hello world" }, }, ]) response = await editee.receive_json_from() # success await editee.receive_json_from() # receives message await not_editee.receive_json_from() # receives message await editee.receive_json_from() # notification pointer await not_editee.receive_json_from() # notification pointer event_id = response[2]["event"]["event_id"] content = ({ "type": "text", "body": "Goodbye world" } if message_type == "text" else { "type": "deleted" }) await editor.send_json_to([ "chat.send", 123, { "channel": channel_id, "event_type": "channel.message", "replaces": event_id, "content": content, }, ]) response = await editor.receive_json_from() # success if success: assert response[0] == "success" assert response[2]["event"]["event_type"] == "channel.message" assert response[2]["event"]["content"] == content assert response[2]["event"]["replaces"] == event_id await editor.receive_json_from() # broadcast response = await not_editor.receive_json_from() # broadcast assert response[0] == "chat.event" assert response[1]["event_type"] == "channel.message" assert response[1]["content"] == content assert response[1]["replaces"] == event_id else: assert response[0] == "error" assert response[2]["code"] == "chat.denied" with pytest.raises(asyncio.TimeoutError): await editor.receive_json_from() # no message to either client with pytest.raises(asyncio.TimeoutError): await not_editor.receive_json_from( ) # no message to either client
"""