def test_add_user_to_contact(self): self.login('*****@*****.**') with cas_mockup_server(), self.given( 'Add a user to contacts', '/apiv1/contacts', 'ADD', form=dict(userId=3), ): assert status == 200 session = self.create_session() user = session.query(Member).filter(Member.id == 1).one() assert len(user.contacts) == 2 when('The user id already added to contact', form=Update(userId=2)) assert status == '603 Already Added To Contacts' when('Try to add not existing user', form=Update(userId=6)) assert status == '611 Member Not Found' when('Try to request with invalid user id', form=Update(userId='invalid')) assert status == '705 Invalid Member Id' when('Request without issuing userId', form=Remove('userId')) assert status == '709 Member Id Is Required' when('Trying to pass the unauthorized request', authorization=None) assert status == 401
def test_login(self): call = dict( title='Login', description='Login to system as god', url='/apiv1/members', verb='LOGIN', form={ 'email': '*****@*****.**', 'password': '******', } ) with self.given(**call): then(response.status_code == 200) and_('token' in response.json) principal = JwtPrincipal.load(response.json['token']) and_('sessionId' in principal.payload) when( 'Trying to login with invalid email and_ password', form={ 'email': '*****@*****.**', 'password': '******', } ) then(response.status_code == 400) when( 'Trying to login with invalid password', form={ 'email': '*****@*****.**', 'password': '******', } ) then(response.status_code == 400)
def test_get_access_token(self): with oauth_mockup_server(): with self.given( 'Try to get an access token from CAS', '/apiv1/oauth2/tokens', 'OBTAIN', form=dict(authorizationCode='authorization code') ): assert status == 200 assert 'token' in response.json assert 'X-New-Jwt-Token' in response.headers when( 'Trying to pass without the authorization code parameter', form=Remove('authorizationCode') ) assert status == 403 when( 'Trying to pass with damage authorization code', form=Update(authorizationCode='token is damage') ) assert status == 401 with cas_server_status('503 Service Not Available'): when('CAS server is not available') assert status == '800 CAS Server Not Available' with cas_server_status('500 Internal Service Error'): when('CAS server faces with internal error') assert status == '801 CAS Server Internal Error' with cas_server_status('404 Not Found'): when('CAS server is not found') assert status == '617 CAS Server Not Found'
def test_register(self): form = dict( name='new name', family='new family', email='*****@*****.**', password='******', role='member', description='description', ) with self.given( 'Register a member', '/apiv1/members', 'REGISTER', form=form, ): assert response.status == 200 when('Invalid email format', form=Update(email='[email protected]')) assert status == '701 Invalid Email Format' when('Email address already is registered', form=Update(email='*****@*****.**')) assert status == '601 Email Address Is Already Registered' when('Request without email parameter', form=Remove('email')) assert status == '722 Email Not In Form' when('Request without name parameter', form=Remove('name')) assert status == '723 Name Not In Form' when('Request without family', form=Remove('family')) assert 'Family Not In form'
def test_mention(self): self.login('*****@*****.**') with cas_mockup_server(), self.given( 'Mention a target', f'/apiv1/targets/{self.room.id}/mentions', 'MENTION', json=dict(body='abc', originTargetId=self.room.id)): assert status == 200 assert response.json['body'] == 'abc' when('Origin target id is null', json=given | dict(originTargetId=None)) assert status == '718 Origin Target Id Is Null' when('Origin target id is not in form', json=given - 'originTargetId') assert status == '717 Origin Target Id Not In Form' when('Origin target id is not found', json=given | dict(originTargetId=0)) assert status == '622 Target Not Found' when('Body length is more than limit', json=given | dict(body=(65536 + 1) * 'a')) assert status == '702 Must be less than 65536 charecters' when('User is logged out', authorization=None) assert status == 401
def test_refresh_token(self): global token_expired, refresh_token_expired self.logout() with self.given('Loggin in to get a token', '/login', 'POST', form=dict(email='*****@*****.**', password='******')): refresh_token = response.headers['Set-Cookie'].split('; ')[0] assert 'token' in response.json assert refresh_token.startswith('refresh-token=') token = response.json['token'] # Login on client token_expired = True settings.jwt.refresh_token.secure = False # Request a protected resource after the token has been expired, # with broken cookies with self.given('Refresh token is broken', url='/me', verb='GET', authorization=token, headers={'Cookie': 'refresh-token=broken-data'}): assert response.status == 400 # Request a protected resource after the token has been expired, # with empty cookies when('Refresh token is empty', headers={'Cookie': 'refresh-token'}) assert response.status == 401 # Request a protected resource after the token has been expired, # without the cookies when('Without the cookies', headers=None) assert response.status == 401 # Request a protected resource after the token has been expired, # with appropriate cookies. when('With appropriate cookies', headers={'Cookie': refresh_token}) assert 'X-New-JWT-Token' in response.headers assert response.headers['X-New-JWT-Token'] is not None # Test with invalid refresh token when('With invalid refresh token', headers={'Cookie': 'refresh-token=InvalidToken'}) assert response.status == 400 # Waiting until expire refresh token refresh_token_expired = True # Request a protected resource after # the refresh-token has been expired. when('The refresh token has been expired.', headers={'Cookie': 'refresh-token'}) assert response.status == 401
def test_refresh_token(self): logintime = freeze_time("2000-01-01T01:01:00") latetime = freeze_time("2000-01-01T01:01:12") verylatetime = freeze_time("2000-01-01T01:02:00") self.logout() with logintime, self.given('Loggin in to get a token', '/login', 'POST', form=dict(email='*****@*****.**', password='******')): refresh_token = response.headers['Set-Cookie'].split('; ')[0] assert 'token' in response.json assert refresh_token.startswith('refresh-token=') token = response.json['token'] # Request a protected resource after the token has been expired, # with broken cookies with latetime, self.given( 'Refresh token is broken', '/me', authorization=token, headers={'Cookie': 'refresh-token=broken-data'}): assert status == 400 # Request a protected resource after the token has been expired, # with empty cookies when('Refresh token is empty', headers={'Cookie': 'refresh-token'}) assert status == 401 # Request a protected resource after the token has been expired, # without the cookies when('Without the cookies', headers=None) assert status == 401 # Request a protected resource after the token has been expired, # with appropriate cookies. when('With appropriate cookies', headers={'Cookie': refresh_token}) assert 'X-New-JWT-Token' in response.headers assert response.headers['X-New-JWT-Token'] is not None when('With invalid refresh token', headers={'Cookie': 'refresh-token=InvalidToken'}) assert status == 400 when('With empty refresh token', headers={'Cookie': 'refresh-token='}) assert status == 401 with verylatetime, self.given('When refresh token is expired', '/me', authorization=token, headers={'Cookie': refresh_token}): assert status == 401
def test_logout_a_user(self): self.login('*****@*****.**') with cas_mockup_server(), self.given( 'Log out a user', '/apiv1/tokens', 'INVALIDATE', ): assert status == 200 when('Try to access some authorize source', authorization=None) assert status == 401
def test_request_with_query_string(self): self.login('*****@*****.**') with cas_mockup_server(), self.given('Test request using query string', '/apiv1/members', 'SEARCH', query=dict(query='user')): assert status == 200 assert len(response.json) == 2 when('An unauthorized search', authorization=None) assert status == 401
def test_request_with_query_string(self): self.login(self.user1.email) with cas_mockup_server(), self.given( 'Test request using query string', f'/apiv1/targets/id: {self.room1.id}/messages', 'SEARCH', query=dict(query='Sec')): assert status == 200 assert len(response.json) == 1 when('An unauthorized search', authorization=None) assert status == 401
def test_get(self): self.login(self.member.email) with self.given( f'Get a member', f'/apiv1/members/id: {self.member.id}', f'GET', ): assert status == 200 assert response.json['id'] == self.member.id assert response.json['name'] == self.member.name assert response.json['family'] == self.member.family when('Intended member with string type not found', url_parameters=dict(id='Alphabetical')) assert status == 404 when('Intended member with string type not found', url_parameters=dict(id=0)) assert status == 404 when('Form parameter is sent with request', form=dict(parameter='Invalid form parameter')) assert status == '709 Form Not Allowed' when('Request is not authorized', authorization=None) assert status == 401
def test_register(self): form = dict( title='new business', address='new address', area='new area', phone='989352117155', memberId=1, ) with self.given( 'Register a business', f'/apiv1/businesses', 'REGISTER', form=form, ): assert response.status == 200 when('Title address already is registered', form=Update(title='Business title')) assert status == '602 Title Is Already Registered' when('Request without title parameter', form=Remove('title')) assert status == '724 Title Not In Form' when('The title format is invalid', form=Update(title='123abc ')) assert status == '708 Invalid Title Format' when('Request without phone parameter', form=Remove('phone')) assert status == '725 Phone Not In Form'
def test_get_user_by_id(self): self.login('*****@*****.**') with cas_mockup_server(), self.given( f'Get a message by id', f'/apiv1/messages/id:{self.message1.id}', f'GET', ): assert status == 200 assert response.json['body'] == 'This is message 1' when( 'Get The message sent by another user in the same room', url_parameters=Update(id=f'{self.message3.id}') ) assert status == 200 assert response.json['body'] == 'This is message 3' when('Invalid message id', url_parameters=Update(id='message1')) assert status == 404 when('Message not found', url_parameters=Update(id=0)) assert status == 404 when('Try to pass unauthorize request', authorization=None) assert status == 401
def test_redirect_to_cas(self): settings.merge(f''' oauth: application_id: 1 ''') with self.given( 'Trying to redirect to CAS server', '/apiv1/oauth2/tokens', 'REQUEST', ): assert status == 200 assert len(response.json) == 2 assert response.json['scopes'] == ['email', 'title', 'avatar'] when('Trying to pass with the form patameter', form=dict(a='a')) assert status == '711 Form Not Allowed'
def test_member_unregister(self): self.login(self.member.email) with self.given( 'Unregister a member', f'/apiv1/members/id: {self.member.id}', 'UNREGISTER', ): assert status == 200 assert response.json['id'] == self.member.id when('Member not found', url_parameters=given | dict(id=0)) status == 404 when('Member not found', url_parameters=given | dict(id='Alphabetical')) status == 404
def test_create_user(self): token = JwtPrincipal( dict(email='*****@*****.**', title='user1', referenceId=2)).dump().decode() with cas_mockup_server(), self.given( 'Create a member', '/apiv1/members', 'ENSURE', headers=dict(authorization=token, x_oauth2_access_token='access token1'), form=dict(title='example')): assert status == 200 assert response.json['title'] == 'user1' when('Access token is not in headers', headers=Remove('x_oauth2_access_token')) assert status == 400
def test_list_rooms_of_user(self): self.login('*****@*****.**') with cas_mockup_server(), self.given( 'List all the rooms a user owns', '/apiv1/rooms', 'LIST', ): assert status == 200 assert len(response.json) == 2 assert response.json[0]['title'] == 'room1' assert response.json[0]['ownerId'] == self.user1.id self.logout() self.login('*****@*****.**') when('List the rooms for another user', authorization=self._authentication_token) assert status == 200 assert len(response.json) == 1 assert response.json[0]['title'] == 'room3' assert response.json[0]['ownerId'] == self.user2.id
def test_login(self): with self.given('Loggin in to get a token', '/login', 'POST', form=dict(email='*****@*****.**', password='******')): assert response.status == '200 OK' assert response.headers['X-Identity'] == '1' assert 'token' in response.json token = response.json['token'] when('Password is incorrect', form=dict(email='*****@*****.**', password='******')) assert response.status == '400 Bad Request' with self.given('Trying to access a protected resource with the token', '/', 'GET', form=dict(a='a', b='b'), authorization=token): assert response.headers['X-Identity'] == '1' when('Token is broken', authorization='bad') assert response.status == 400 when('Token is empty', url='/me', authorization='') assert response.status == 401
def test_login(self): logintime = freeze_time("2000-01-01T01:01:00") latetime = freeze_time("2000-01-01T01:01:12") with logintime, self.given( 'Loggin in to get a token', '/login', 'POST', form=dict(email='*****@*****.**', password='******') ): assert status == '200 OK' assert response.headers['X-Identity'] == '1' assert 'token' in response.json token = response.json['token'] when( 'Password is incorrect', form=dict(email='*****@*****.**', password='******') ) assert status == '400 Bad Request' with logintime, self.given( 'Trying to access a protected resource with the token', '/me', authorization=token ): assert response.headers['X-Identity'] == '1' when('Token is broken', authorization='bad') assert status == 400 when('Token is empty', url='/me', authorization='') assert status == 401 when('Token is blank', url='/me', authorization=' ') assert status == 401 with latetime, self.given( 'Try to access a protected resource when session is expired', '/me', form=dict(a='a', b='b'), authorization=token ): assert status == 401
def test_create(self): email = '*****@*****.**' password = '******' with self.given('Create a login token', '/apiv1/tokens', 'CREATE', form=dict(email=email, password=password)): assert status == 200 assert 'token' in response.json when('Invalid password', form=Update(password='******')) assert status == '400 Incorrect Email Or Password' when('Not exist email', form=Update(email='*****@*****.**')) assert status == '400 Incorrect Email Or Password' when('Invalid email format', form=Update(email='user.com')) assert status == '400 Invalid Email Format' when('Trying to pass with empty form', form={}) assert status == '400 Empty Form'
def test_attach_file_to_message(self): self.login(self.user1.email) with cas_mockup_server(), open(IMAGE_PATH, 'rb') as f, self.given( f'Send a message to a target', f'/apiv1/targets/id:{self.room.id}/messages', f'SEND', multipart=dict(body='hello world!', mimetype='image/png', attachment=io.BytesIO(f.read()))): assert status == 200 assert response.json['body'] == 'hello world!' assert response.json['isMine'] is True assert 'attachment' in response.json with open(TEXT_PATH, 'rb') as f: when('Mime type does not match content type', multipart=Update(attachment=io.BytesIO(f.read()))) assert status == 200 with open(MAXIMUM_IMAGE_PATH, 'rb') as f: when('Image size is more than maximum length', multipart=Update(mimetype='image/jpeg', attachment=io.BytesIO(f.read()))) assert status == 413 settings.attachements.messages.files.max_length = 800 with open(EXECUTABLE_PATH, 'rb') as f: when('Image size is more than maximum length', multipart=Update(mimetype='image/jpeg', attachment=io.BytesIO(f.read()))) assert status == '415 Unsupported Media Type' with open(DLL_PATH, 'rb') as f: when('Image size is more than maximum length', multipart=Update(mimetype='image/jpeg', attachment=io.BytesIO(f.read()))) assert status == '415 Unsupported Media Type'
def test_claim_email(self): with cas_mockup_server(), self.given( 'claim a user', '/apiv1/emails', 'CLAIM', form=dict(email='*****@*****.**')): assert response.status == '200 OK' when('The email is repeted', form=Update(email='*****@*****.**')) assert response.status == '601 The requested email address is ' \ 'already registered.' when('The email format is invalid', form=Update(email='already.example.com')) assert response.status == '701 Invalid email format.' when('Request without email', form=Remove('email')) assert response.status == 400
def test_create_room(self): self.login('*****@*****.**') with cas_mockup_server(), self.given( 'Creating a room', '/apiv1/rooms', 'CREATE', form=dict(title='example'), ): assert status == 200 assert response.json['title'] == 'example' assert response.json['ownerId'] == 1 assert len(response.json['administratorIds']) == 1 assert len(response.json['memberIds']) == 1 when('The room title exceed maximum length', form=Update(title='a' * (50 + 1))) assert status == '702 Must Be Less Than 50 Charecters' when('Title is required', form=Remove('title')) assert status == '703 Room Title Is Required' when('The room already exist') assert status == '615 Room Already Exists'
def test_subscribe_rooms(self): self.login('*****@*****.**') rooms = (str(i) + ', ' for i in range(1, 102)) rooms_string = ''.join(rooms) with cas_mockup_server(), self.given( 'Subscribe multiple rooms', f'/apiv1/rooms?id=IN({self.room1.id}, {self.room2.id})', 'SUBSCRIBE', ): assert status == 200 assert len(response.json) == 2 assert response.json[0]['title'] == 'room1' assert response.json[0]['ownerId'] == self.user2.id when('There is form parameter', form=dict(parameter='abc')) assert status == '711 Form Not Allowed' when('The number of rooms to subscribe is more than limit', query=dict(id=f'IN({rooms_string})')) assert status == '716 Maximum 5 Rooms To Subscribe At A Time' when('Try to pass unauthorize request', authorization=None) assert status == 401
else: start_response( '200 OK', [('Content-Type', 'application/json;charset=utf-8')] ) result = json.dumps(dict( foo='bar' )) yield result.encode() with Given( wsgi_application, title='Quickstart!', url='/books/id: 1', as_='visitor') as story: assert status == 200 assert status == '200 OK' assert 'foo' in response.json assert response.json['foo'] == 'bar' when( 'Trying invalid book id', url_parameters={'id': None} ) assert response.status == 404
def test_creat_token(self): self.login('*****@*****.**') with cas_mockup_server(), self.given( 'Try to create a direct with a user', '/apiv1/directs', 'CREATE', form=dict(userId=3) ): assert status == 200 assert response.json['type'] == 'direct' when('The user not exists', form=Update(userId=5)) assert status == '611 Member Not Found' when( 'Try to pass invalid user id in the form', form=Update(userId='Invalid') ) assert status == '705 Invalid Member Id' when('Try to pass empty form', form=None) assert status == '710 Empty Form' when('Blocked user tries to create a direct', form=Update(userId=1)) assert status == '613 Not Allowed To Create Direct With This Member' self.logout() self.login('*****@*****.**') when( 'Try to create a direct with a blocked user', form=Update(userId=self.user1.id), authorization=self._authentication_token ) assert status == '613 Not Allowed To Create Direct With This Member' when('Try to pass an unauthorized request', authorization=None) assert status == 401
def test_mention(self): self.login(self.member1.email) with cas_mockup_server(), self.given( 'Mention a target', f'/apiv1/members/member_id: {self.member2.id}/mentions', 'MENTION', json=dict(body='abc', originTargetId=self.room.id)): assert status == 200 assert response.json['body'] == 'abc' when('Origin target id is null', json=given | dict(originTargetId=None)) assert status == '718 Origin Target Id Is Null' when('Origin target id is not in form', json=given - 'originTargetId') assert status == '717 Origin Target Id Not In Form' when('Origin target id is not found', json=given | dict(originTargetId=0)) assert status == '622 Target Not Found' when('Body length is more than limit', json=given | dict(body=(65536 + 1) * 'a')) assert status == '702 Must be less than 65536 charecters' when('There is no direct between mentioned and mentioner member', url_parameters=dict(member_id=self.member3.id)) assert response.json['body'] == 'abc' when('User is logged out', authorization=None) assert status == 401
def test_send_message_to_target(self): self.login(self.user1.email) with cas_mockup_server(), maestro_mockup_server(), self.given( f'Send a message to a target', f'/apiv1/targets/id:{self.room.id}/messages', f'SEND', form=dict(body='hello world!')): assert status == 200 assert response.json['body'] == 'hello world!' assert response.json['isMine'] is True assert response.json['mimetype'] == 'text/plain' assert response.json[ 'senderReferenceId'] == self.user1.reference_id when('Invalid target id', url_parameters=Update(id='Invalid')) assert status == '706 Invalid Target Id' when('Target does not exist', url_parameters=Update(id=0)) assert status == '404 Target Not Exists' when('Try to send unsopported media type', form=Update(mimetype='video/3gpp')) assert status == 415 when('Try to send long text', form=Update(body=(65536 + 1) * 'a')) assert status == '702 Must be less than 65536 charecters' when('Remove body from the form', form=Remove('body')) assert status == 400 when('Try to pass an unauthorized request', authorization=None) assert status == 401 settings.webhooks.sent.timeout = 0.1 when('Request to Dolphin is timeout') assert status == 200 settings.webhooks.sent.timeout = 30 settings.webhooks.sent.url = 'http://localhost:1' when('Connection is failed') assert status == 200
def test_create_token(self): email = self.member.email password = '******' with self.given('Create a login token', '/apiv1/tokens', 'CREATE', form=dict(email=email, password=password)): assert status == 200 assert 'token' in response.json when('Invalid password', form=Update(password='******')) assert status == '603 Incorrect Email Or Password' when('Not exist email', form=Update(email='*****@*****.**')) assert status == '603 Incorrect Email Or Password' when('Invalid email format', form=Update(email='user.com')) assert status == '701 Invalid Email Format' when('Trying to pass with empty form', form={}) assert status == '400 Empty Form' when('Email is empty', form=Remove('email')) assert status == '722 Email Not In Form' when('Passeord is empty', form=Remove('password')) assert status == '723 Password Is Not In Form' when('Password length is more than 50', form=Update(password=(50 + 1) * 'a')) assert status == '706 Title Length Is More Than 50'
def test_delete_the_message(self): self.login('*****@*****.**') with cas_mockup_server(), self.given('Try to delete a message', '/apiv1/messages/id:1', 'DELETE'): assert status == 200 assert response.json['body'] == 'This message is deleted' assert response.json['removedAt'] is not None when('Delete a message with attachment', url_parameters=Update(id=self.message3.id)) assert status == 200 assert response.json['attachment'] is None when('Delete the same message') assert status == '616 Message Already Deleted' when('Try to delete someone else messages', url_parameters=Update(id=self.message2.id)) assert status == 403 when('The message not exists', url_parameters=Update(id=0)) assert status == '614 Message Not Found' when('Trying to pass using invalid message id', url_parameters=Update(id='Invalid')) assert status == '707 Invalid MessageId' self.logout() self.login('*****@*****.**') when('Not allowed to delete the message', url_parameters=Update(id=self.message2.id), authorization=self._authentication_token) assert status == 403