def test_encode_auth_token(self): user = User( username='******', password='******' ) db.session.add(user) db.session.commit() auth_token = user.encode_auth_token(user.id) self.assertTrue(isinstance(auth_token, bytes))
def test_insert_in_event(self): # Add 2 users so user id is a different value to event id for username in ('test_username1', 'test_username2'): user = User( username=username, password='******' ) db.session.add(user) db.session.commit() self.assertEqual(user.id, 2) before_insert = datetime.utcnow() time.sleep(1) event = Event( name='test', date=datetime.now().date(), author_id=user.id, initial_number_of_tickets=10 ) db.session.add(event) db.session.commit() time.sleep(1) after_insert = datetime.utcnow() self.assertEqual(event.id, 1) self.assertEqual(event.name, 'test') self.assertTrue(uuid.UUID(bytes=event.guid)) self.assertEqual(event.author_id, user.id) self.assertEqual(event.initial_number_of_tickets, 10) self.assertTrue(before_insert < event.date_created_utc < after_insert)
def post(self): # get auth token auth_header = token_parser.parse_args() auth_token = auth_header['Authorization'] try: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): # mark the token as blacklisted blacklist_token = BlacklistToken(token=auth_token) # insert the token db.session.add(blacklist_token) db.session.commit() response_object = { 'status': 'success', 'message': 'Successfully logged out.' } return response_object, 200 else: response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred logging in a user', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.' } return response_object, 500
def get(self): # get the auth token auth_header = token_parser.parse_args() auth_token = auth_header['Authorization'] try: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): user = User.query.filter_by(id=resp).first() response_object = { 'status': 'success', 'data': { 'username': user.username, 'registered_on_utc': user.registered_on_utc } } return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred checking status of a user', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.' } return response_object, 500
def test_insert_in_ticket(self): for username in ('test_username1', 'test_username2'): user = User( username=username, password='******' ) db.session.add(user) db.session.commit() self.assertEqual(user.id, 2) before_insert = datetime.utcnow() time.sleep(1) event = Event( name='test', date=datetime.now().date(), author_id=user.id, initial_number_of_tickets=10 ) db.session.add(event) db.session.commit() time.sleep(1) after_insert = datetime.utcnow() self.assertEqual(event.id, 1) self.assertEqual(event.name, 'test') self.assertTrue(uuid.UUID(bytes=event.guid)) self.assertEqual(event.author_id, user.id) self.assertEqual(event.initial_number_of_tickets, 10) self.assertTrue(before_insert < event.date_created_utc < after_insert) before_insert = datetime.utcnow() time.sleep(1) ticket = Ticket( author_id=user.id, event_id=event.id ) db.session.add(ticket) db.session.commit() time.sleep(1) after_insert = datetime.utcnow() self.assertNotEqual(uuid.UUID(bytes=ticket.guid), uuid.UUID(bytes=event.guid)) self.assertEqual(ticket.id, 1) self.assertTrue(uuid.UUID(bytes=ticket.guid)) self.assertEqual(ticket.author_id, user.id) self.assertEqual(ticket.event_id, event.id) self.assertFalse(ticket.is_redeemed) self.assertTrue(before_insert < ticket.date_created_utc < after_insert)
def get(self): """Get status of an event""" params = event_all_parser.parse_args() try: resp = User.decode_auth_token(params['Authorization']) if not isinstance(resp, str): result = db.session.query( Event.guid.label('guid'), Event.name.label('name'), Event.date.label('date'), db.func.count(Ticket.id).label('total'), db.func.sum(Ticket.is_redeemed).label('redeemed') )\ .join(Event)\ .group_by( Event.guid, Event.name, Event.date )\ .order_by( Event.date.desc(), Event.name.asc(), Event.guid.asc() )\ .all() data = [{ 'guid': str(uuid.UUID(bytes=row.guid)), 'name': row.name, 'date': row.date, 'number_of_tickets': row.total, 'number_of_redeemed_tickets': int(row.redeemed) } for row in result] response_object = { 'status': 'success', 'message': 'Successfully retrieved event status.', 'data': data } return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred creating an event.', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.', } return response_object, 500
def get(self, eventIdentifier): """Get download of an events unreemed tickets""" params = event_download_parser.parse_args() try: resp = User.decode_auth_token(params['Authorization']) if not isinstance(resp, str): event = Event.query.filter_by( guid=eventIdentifier.bytes).first() if not event: response_object = { 'status': 'fail', 'message': 'Invalid eventIdentifier.' } return response_object, 402 result = db.session.query( Ticket.guid.label('guid') )\ .filter(db.and_( Ticket.event_id == event.id, Ticket.is_redeemed == False # Doesn't select if "is" is used instead of "==" ))\ .all() ticket_identifiers = [ str(uuid.UUID(bytes=row.guid)) for row in result ] response_object = { 'status': 'success', 'message': 'Successfully downloaded unredeemed event tickets.', 'data': { 'ticketIdentifiers': ticket_identifiers } } return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred creating an event.', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.', } return response_object, 500
def post(self): post_data = usr_pwd_parser.parse_args() try: # check if user already exists user = User.query.filter_by(username=post_data['username']).first() if not user: user = User(username=post_data['username'], password=post_data['password']) # insert the user db.session.add(user) db.session.commit() # generate the auth token auth_token = user.encode_auth_token(user.id) response_object = { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() } return response_object, 200 else: response_object = { 'status': 'fail', 'message': 'User already exists. Please Log in.', } return response_object, 201 except Exception: logger.error('An error occurred registering a user', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.', } return response_object, 500
def get(self, eventIdentifier): """Get status of an event""" params = event_status_parser.parse_args() try: resp = User.decode_auth_token(params['Authorization']) if not isinstance(resp, str): event = Event.query.filter_by( guid=eventIdentifier.bytes).first() if not event: response_object = { 'status': 'fail', 'message': 'Invalid eventIdentifier.' } return response_object, 402 result = db.session.query( Event.name.label('name'), Event.date.label('date'), db.func.count(Ticket.id).label('total'), db.func.sum(Ticket.is_redeemed).label('redeemed') )\ .join(Event)\ .filter(Event.guid == eventIdentifier.bytes)\ .group_by(Event.name, Event.date)\ .first() response_object = { 'status': 'success', 'message': 'Successfully retrieved event status.', 'data': { 'name': result.name, 'date': result.date, 'number_of_tickets': result.total, 'number_of_redeemed_tickets': int(result.redeemed) } } return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred creating an event.', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.', } return response_object, 500
def test_registered_with_already_registered_user(self): """ Test registration with already registered username """ user = User(username='******', password='******') db.session.add(user) db.session.commit() with self.client: response = self.register_user('dummy_username', '12345678') data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 'fail') self.assertTrue( data['message'] == 'User already exists. Please Log in.') self.assertTrue(response.content_type == 'application/json') self.assertEqual(response.status_code, 201)
def put(self, eventIdentifier): """Add more tickets to an existing event""" params = event_add_parser.parse_args() try: resp = User.decode_auth_token(params['Authorization']) if not isinstance(resp, str): event = Event.query.filter_by( guid=eventIdentifier.bytes).first() if not event: response_object = { 'status': 'fail', 'message': 'Invalid eventIdentifier.' } return response_object, 402 if event.additional_number_of_tickets: event.additional_number_of_tickets += params[ 'additionalNumberOfTickets'] else: event.additional_number_of_tickets = params[ 'additionalNumberOfTickets'] tickets = (Ticket(author_id=resp, event_id=event.id) for _ in range(params['additionalNumberOfTickets'])) db.session.add_all(tickets) db.session.commit() response_object = { 'status': 'success', 'message': f'Successfully added {params["additionalNumberOfTickets"]} event tickets.', } return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred creating an event.', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.', } return response_object, 500
def test_creating_event(self): """ Test creating an event """ with self.client: start_time = datetime.utcnow() reg_response = self.register_user('dummy_username', '12345678') auth_token = json.loads( reg_response.data.decode("utf-8"))['auth_token'] event_response = self.create_event(name='test', date=datetime.now().date(), initial_number_of_tickets=5, auth_token=auth_token) event_data = json.loads(event_response.data.decode()) self.assertEqual(event_response.status_code, 200) self.assertEqual(event_data['status'], 'success') self.assertEqual(event_data['message'], 'Successfully created event "test".') self.assertTrue(event_data['eventIdentifier']) self.assertEqual(event_response.content_type, 'application/json') eventIdentifier = event_data['eventIdentifier'] eventIdentifier = uuid.UUID(eventIdentifier) event = Event.query.filter_by(guid=eventIdentifier.bytes).first() author_id = User.decode_auth_token(auth_token) self.assertEqual(event.name, 'test') self.assertEqual(event.author_id, author_id) self.assertEqual(event.initial_number_of_tickets, 5) self.assertTrue(uuid.UUID(bytes=event.guid)) self.assertTrue( start_time < event.date_created_utc < datetime.utcnow()) tickets = Ticket.query.filter( db.and_(Ticket.author_id == event.author_id, Ticket.event_id == event.id)).all() self.assertEqual(len(tickets), 5)
def post(self): """Create an event""" post_data = create_event_parser.parse_args() try: resp = User.decode_auth_token(post_data['Authorization']) if not isinstance(resp, str): event = Event(name=post_data['name'], date=post_data['date'], initial_number_of_tickets=post_data[ 'initial_number_of_tickets'], author_id=resp) db.session.add(event) db.session.flush() tickets = ( Ticket(author_id=resp, event_id=event.id) for _ in range(post_data['initial_number_of_tickets'])) db.session.add_all(tickets) db.session.commit() response_object = { 'status': 'success', 'message': f'Successfully created event "{event.name}".', 'eventIdentifier': str(uuid.UUID(bytes=event.guid)) } return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred creating an event.', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.', } return response_object, 500
def get(self, ticketIdentifier): """Check status of ticket""" params = token_parser.parse_args() try: resp = User.decode_auth_token(params['Authorization']) if not isinstance(resp, str): ticket = Ticket.query.filter_by( guid=ticketIdentifier.bytes).first() if not ticket: response_object = { 'status': 'fail', 'message': 'Invalid ticketIdentifier.' } return response_object, 402 if ticket.is_redeemed: response_object = { 'status': 'success', 'message': 'GONE: ticket redeemed.' } return response_object, 410 response_object = {'status': 'success', 'message': 'OK.'} return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 except Exception: logger.error('An error occurred creating an event.', exc_info=True) response_object = { 'status': 'fail', 'message': 'An Internal Server Error Occurred.', } return response_object, 500