def post(self, id_user, id_estate): data = Room.parser_add.parse_args() try: estate = EstateModel.find_by_id(id_estate) # We handle the case of an owner can only modify the characteristics of his property # without having access to the edition of the other owners if id_user != estate.id_user: raise PermissionError room = RoomModel(id_estate, **data) room.save_to_db() return room.json(), 201 except NoResultFound: return { 'message': 'Please make sure the estate id is correct' }, 400 except PermissionError: return {'message': 'Access denied'}, 403 except: return { 'message': 'An error occurred while inserting the room' }, 500
def test_room_json(self): room = RoomModel( _id=1, company='Test Company', location='Test Location', name='Test Name', description='Some Test Description', rateofescape='10/10', image='test.jpg', duration='60 minutes', playedon='01/01/2018' ) expected = { 'id': 1, 'company': 'Test Company', 'location': 'Test Location', 'name': 'Test Name', 'description': 'Some Test Description', 'rateofescape': '10/10', 'image': 'test.jpg', 'duration': '60 minutes', 'playedon': '01/01/2018' } self.assertEqual(room.json(), expected)
def test_create_duplicate_room(self): room = RoomModel(_id=1, company='Test Company', location='Test Location', name='Test Name', description='Some Test Description', rateofescape='10/10', image='test.jpg', duration='60 minutes', playedon='01/01/2018') data = { 'id': 1, 'company': 'Test Company', 'location': 'Test Location', 'name': 'Test Name', 'description': 'Some Test Description', 'rateofescape': '10/10', 'image': 'test.jpg', 'duration': '60 minutes', 'playedon': '01/01/2018' } with self.app() as client: with self.app_context(): room.save_to_db() resp = client.post('/room/create', data=data) self.assertEqual(resp.status_code, 400) self.assertDictEqual( { 'message': "'Test Name' by 'Test Company' already exists" }, json.loads(resp.data))
def test_room_list(self): with self.app() as client: with self.app_context(): room = RoomModel(_id=1, company='Test Company', location='Test Location', name='Test Name', description='Some Test Description', rateofescape='10/10', image='test.jpg', duration='60 minutes', playedon='01/01/2018') data = { 'id': 1, 'company': 'Test Company', 'location': 'Test Location', 'name': 'Test Name', 'description': 'Some Test Description', 'rateofescape': '10/10', 'image': 'test.jpg', 'duration': '60 minutes', 'playedon': '01/01/2018' } room.save_to_db() resp = client.get('/rooms') self.assertDictEqual({'rooms': [data]}, json.loads(resp.data))
def post(self): data = AddHouse.parser.parse_args() house_type = TypeModel.find_by_name(data['house_type']) if not house_type: return {'message':"invalide house type"}, 400 city = CityModel.find_by_name(data['city']) if not city: return {'message':"invalide city name"}, 400 house = HouseModel(data['name'],data['description'],house_type.id,city.id) try: house.save_to_db() except: return {"message": "An error occurred creating the store."}, 500 # add the new house attached rooms if data['rooms'] is not None: rooms =[ast.literal_eval(rooms) for rooms in data['rooms']] for x in rooms: room = RoomModel(x['characteristics'],house.id) room.save_to_db() return house.json(), 201
def get(self, id): room = RoomModel.find_by_title(id) if room is None: try: room = RoomModel.find_by_id(int(id)) except ValueError: return {'message': 'The Room was not found.'}, 404 if room: return room.json() return {'message': 'The Room was not found.'}, 404
def post(self): data = RoomCreate.parser.parse_args() room = RoomModel.find_by_name_company(data['name'], data['company']) if room: return { 'message': "'{}' by '{}' already exists".format(data['name'], data['company']) }, 400 room = RoomModel(None, **data) room.save_to_db() return {'message': 'Room Created'}, 201
def path_to_unexplored(self, current_room): # id's of rooms passed in. all_rooms = RoomModel.find_all() rooms_dict = {} # make all rooms represent their JSON object, and insert into rooms dict. for i in range(len(all_rooms)): rooms_dict[str(all_rooms[i].json()['id'])] = all_rooms[i].json() visited_rooms = set() queue = [] path = [] room = current_room #id of room queue.append([room]) while len(queue) > 0: current_path = queue.pop(0) prev_room = current_path[-1] if prev_room is not None: if prev_room not in visited_rooms: visited_rooms.add(prev_room) for exit_dir in rooms_dict[str(prev_room)]['exits']: new_path = current_path[:] new_path.append( rooms_dict[str(prev_room)]['exits'][exit_dir]) if rooms_dict[str( prev_room)]['exits'][exit_dir] == '?': path = { "path": self.create_path(rooms_dict, current_path) } return path else: queue.append(new_path) path.append(exit_dir) # no path found. return None return None
def test_get_room(self): with self.app() as client: with self.app_context(): room = RoomModel(_id=1, company='Test Company', location='Test Location', name='Test Name', description='Some Test Description', rateofescape='10/10', image='test.jpg', duration='60 minutes', playedon='01/01/2018') room.save_to_db() resp = client.get('/room/1', headers={'Authorization': self.access_token}) self.assertEqual(resp.status_code, 200)
def put(self, id_user, id_estate, id_room): data = EditRoom.parser_edit.parse_args() try: room = RoomModel.find_by_id(id_room, id_estate) estate = EstateModel.find_by_id(id_estate) # We handle the case of an owner can only modify the characteristics of his property # without having access to the edition of the other owners if id_user != estate.id_user: raise PermissionError # Filling data room.name = room.name if data.name is None else data.name room.characteristic = room.characteristic if data.characteristic is None else data.characteristic room.save_to_db() return room.json(), 200 except NoResultFound: return {'message': 'Please make sure the id is correct'}, 400 except PermissionError: return {'message': 'Access denied'}, 403 except: return { 'message': 'An error occurred while inserting the room' }, 500
def put(self, id): room = RoomModel.find_by_id(id) if not room: return {'message': 'room not found'} data = Room.parser.parse_args() room.characteristics = data['characteristics'] room.save_to_db() return room.json()
def get(self): rooms = RoomModel.find_all() if rooms is None: return {'message': 'No rooms were found.'}, 404 for i in range(len(rooms)): rooms[i] = rooms[i].json() return rooms, 200
def test_delete_room(self): with self.app() as client: with self.app_context(): room = RoomModel(_id=1, company='Test Company', location='Test Location', name='Test Name', description='Some Test Description', rateofescape='10/10', image='test.jpg', duration='60 minutes', playedon='01/01/2018') room.save_to_db() resp = client.delete( '/room/1', data={ 'name': 'Test Name', 'company': 'Test Company' }, headers={'Authorization': self.access_token}) self.assertEqual(resp.status_code, 200) self.assertDictEqual({'message': 'Room was deleted'}, json.loads(resp.data))
def test_create_room(self): room = RoomModel( _id=1, company='Test Company', location='Test Location', name='Test Name', description='Some Test Description', rateofescape='10/10', image='test.jpg', duration='60 minutes', playedon='01/01/2018' ) self.assertEqual(room.name, 'Test Name', "The name of the room does not equal the constructors argument") self.assertEqual(room.location, 'Test Location', "The location of the room does not equal the constructors argument")
def delete(self, _id): claims = get_jwt_claims() if not claims['is_admin']: return {'message': 'Admin privilege required.'}, 401 parser = reqparse.RequestParser() parser.add_argument('company', type=str, required=True, help='You must enter company') parser.add_argument('name', type=str, required=True, help='You must enter a name') data = parser.parse_args() room = RoomModel.find_by_name_company(**data) if room: room.delete_from_db() return {'message': 'Room was deleted'} return { 'message': "No room found with id {}, name '{}' and company '{}'".format( _id, data['name'], data['company']) }, 400
def start_loop(self): with self.app.app_context(): directions = ['n', 'e', 's', 'w'] while True: time.sleep(1) # Get all players who are automatically traversing traversing_players = PlayerModel.find_all_by_single_path(False) if not traversing_players or len(traversing_players) < 1: continue # Make every record of traversing_players the JSON dict available. for player in traversing_players: player_data = player.json() # Only register next move if the player is passed cooldown. if int(time.time()) < player_data['nextAvailableMove'] + 2: continue player_path = json.loads(player_data["currentPath"])["path"] # Player has a path, travel based on it. if len(player_path) > 0: direction = player_path.pop(0) traverse_to_room = Traverse.TraverseOnce(player_data['password'], direction) traverse_to_room = traverse_to_room[0] if len(traverse_to_room['errors']) > 0: setattr(player, 'nextAvailableMove', (int(time.time()) + int(traverse_to_room['cooldown']))) player.save_to_db() continue setattr(player, 'nextAvailableMove', int(time.time()) + int(traverse_to_room['cooldown'])) setattr(player, 'currentRoomId', traverse_to_room['room_id']) setattr(player, 'currentPath', json.dumps({"path": player_path})) player.save_to_db() print(f"player traveled {direction} to {traverse_to_room['room_id']}") continue # return traverse_to_room current_room = RoomModel.find_by_id(player_data['currentRoomId']) current_room_data = None if current_room: current_room_data = current_room.json() else: # Get the room the player is currently in: player_status_response = requests.get('https://lambda-treasure-hunt.herokuapp.com/api/adv/init/', headers={'authorization': player_data['password']}).json() time.sleep(1) if len(player_status_response['errors']) > 0: setattr(player, 'nextAvailableMove', (int(time.time()) + int(player_status_response['cooldown']))) player.save_to_db() continue direction = player_status_response['exits'][0] traverse_to_room = Traverse.TraverseOnce(player_data['password'], direction) traverse_to_room = traverse_to_room[0] if len(traverse_to_room['errors']) > 0: setattr(player, 'nextAvailableMove', (int(time.time()) + int(traverse_to_room['cooldown']))) player.save_to_db() continue setattr(player, 'nextAvailableMove', (int(time.time()) + int(traverse_to_room['cooldown']))) setattr(player, 'currentRoomId', traverse_to_room['room_id']) player.save_to_db() continue # Check if any exits are unexplored by our database. for direction in directions: if current_room_data['exits'][direction] == '?': # move to that room. traverse_to_room = Traverse.TraverseOnce(player_data['password'], direction) traverse_to_room = traverse_to_room[0] if len(traverse_to_room['errors']) > 0: setattr(player, 'nextAvailableMove', (int(time.time()) + int(traverse_to_room['cooldown']))) player.save_to_db() continue setattr(player, 'nextAvailableMove', int(time.time()) + traverse_to_room['cooldown']) setattr(player, 'currentRoomId', traverse_to_room['room_id']) player.save_to_db() continue # No unexplored directions found - get shortest path to room that DOES have an unexplored exit/room player = PlayerModel.find_by_password(player_data['password']) player_data = player.json() travel_path = self.GraphTraversal.path_to_unexplored(player_data['currentRoomId']) setattr(player, 'currentPath', json.dumps(travel_path)) player.save_to_db()
def delete(self, id): room = RoomModel.find_by_id(id) if room: room.delete_from_db() return {'message': 'room has been deleted'}
def TraverseOnce(self, token, move): opposite_dirs = { "n": "s", "e": "w", "s": "n", "w": "e" } time.sleep(1) # Get the room the player is currently in: player_status_response = requests.get( 'https://lambda-treasure-hunt.herokuapp.com/api/adv/init/', headers={'authorization': token}).json() if len(player_status_response['errors']) > 0: return player_status_response, 400 time.sleep(1) # if the direction the player wants to move is in their current rooms direction list (if its a possible direction to move) if move in player_status_response["exits"]: # See if we have the players current room in our database. found_room = RoomModel.find_by_id( player_status_response['room_id']) # If we don't have the room in our database, we haven't seen it before. So we add it to our database. if not found_room: # room_coordinates turns "(32,45)" -> ["32", "45"] room_coordinates = re.findall( r"\d+", player_status_response['coordinates']) avail_exits = { "n": None if "n" not in player_status_response["exits"] else "?", "w": None if "w" not in player_status_response["exits"] else "?", "e": None if "e" not in player_status_response["exits"] else "?", "s": None if "s" not in player_status_response["exits"] else "?", } new_room_data = { "id": player_status_response['room_id'], "title": player_status_response['title'], "description": player_status_response['description'], "x": int(room_coordinates[0]), "y": int(room_coordinates[1]), "terrain": player_status_response['terrain'], "elevation": player_status_response['elevation'] } new_room_data.update(avail_exits) found_room = RoomModel(**new_room_data) # Now travel and save the next room result in the previous room player_travel_request = requests.post('https://lambda-treasure-hunt.herokuapp.com/api/adv/move/', json={ "direction": move}, headers={'authorization': token}).json() try: new_room_id = player_travel_request['room_id'] traveled_into_room = RoomModel.find_by_id(new_room_id) if not traveled_into_room: # Create room record for the room we just traveled into if not found new_room_coordinates = re.findall( r"\d+", player_travel_request['coordinates']) avail_exits = { "n": None if "n" not in player_travel_request["exits"] else "?", "w": None if "w" not in player_travel_request["exits"] else "?", "e": None if "e" not in player_travel_request["exits"] else "?", "s": None if "s" not in player_travel_request["exits"] else "?", } traveled_into_room_data = { "id": new_room_id, "title": player_travel_request['title'], "description": player_travel_request['description'], "x": int(new_room_coordinates[0]), "y": int(new_room_coordinates[1]), "terrain": player_travel_request['terrain'], "elevation": player_travel_request['elevation'] } traveled_into_room_data.update(avail_exits) traveled_into_room = RoomModel( **traveled_into_room_data) setattr(traveled_into_room, opposite_dirs[move], str( found_room.json()['id'])) setattr(found_room, move, new_room_id) found_room.save_to_db() return player_travel_request, 200 except KeyError: return player_travel_request, 400 # Room is found else: # Check if we have the next room's id that the player is traveling to. If we do, travel there and return response to user. if move in found_room.json()["exits"] and found_room.json()["exits"][move] is not None and found_room.json()["exits"][move] is not "?": next_room = found_room.json()["exits"][move] player_travel_request = requests.post('https://lambda-treasure-hunt.herokuapp.com/api/adv/move/', json={ "direction": move, "next_room_id": str(next_room)}, headers={'authorization': token}).json() return player_travel_request, 200 # If we don't, travel that direction without wise explorer bonus. Then save that direction result in our found_room for next time. else: player_travel_request = requests.post('https://lambda-treasure-hunt.herokuapp.com/api/adv/move/', json={ "direction": move}, headers={'authorization': token}).json() try: # Create new room we just traveled into, and save the direction to the previous room. new_found_room = RoomModel.find_by_id( player_travel_request["room_id"]) new_room_id = player_travel_request['room_id'] if not new_found_room: room_coordinates = re.findall( r"\d+", player_travel_request['coordinates']) avail_exits = { "n": None if "n" not in player_travel_request["exits"] else "?", "w": None if "w" not in player_travel_request["exits"] else "?", "e": None if "e" not in player_travel_request["exits"] else "?", "s": None if "s" not in player_travel_request["exits"] else "?", } new_room_data = { "id": new_room_id, "title": player_travel_request['title'], "description": player_travel_request['description'], "x": int(room_coordinates[0]), "y": int(room_coordinates[1]), "terrain": player_travel_request['terrain'], "elevation": player_travel_request['elevation'] } new_room_data.update(avail_exits) new_found_room = RoomModel(**new_room_data) setattr(new_found_room, opposite_dirs[move], str( player_status_response["room_id"])) setattr(found_room, move, new_room_id) new_found_room.save_to_db() found_room.save_to_db() return player_travel_request, 200 except KeyError: return player_travel_request, 400 else: return {'error': True, 'message': 'There is no exit in that direction.'}, 400
def test_crud(self): with self.app_context(): room = RoomModel(_id=1, company='Test Company', location='Test Location', name='Test Name', description='Some Test Description', rateofescape='10/10', image='test.jpg', duration='60 minutes', playedon='01/01/2018') self.assertIsNone(RoomModel.find_by_id(1)) room.save_to_db() self.assertIsNotNone( RoomModel.find_by_name_company('Test Name', 'Test Company')) self.assertIsNotNone(RoomModel.find_by_id(1)) self.assertIsNotNone(RoomModel.get_all_rooms()) room.delete_from_db() self.assertIsNone(RoomModel.find_by_id(1)) self.assertEqual(RoomModel.get_all_rooms(), {'rooms': []})
def get(self, _id): room = RoomModel.find_by_id(_id) if room: return room.json() return {'message': 'Room not Found'}, 404
def get(self): rooms = RoomModel.get_all_rooms() if rooms: return rooms return {'message': 'No rooms to display'}, 404
def get(self, name): room = RoomModel.find_by_name(name) if room: return room.json() return {'message': 'Item not found'}, 404