def test_locked(self): '''Tests with a locked square.''' action_manager = ActionManager() database = MemcachedDatabase() database.get_square(TestEatAction.LOCATION, for_update=True) with self.assertRaises(LockAlreadyAquiredError): action_manager.do_action("123", "eat", [TestEatAction.ROBOT_ID]) database.rollback()
def test_locked(self): '''Tests with a locked square.''' action_manager = ActionManager() database = MemcachedDatabase() database.get_square(TestEatAction.LOCATION, for_update=True) with self.assertRaises(LockAlreadyAquiredError): action_manager.do_action("123", "eat", [TestEatAction.ROBOT_ID]) database.rollback()
def test_rollback(self): '''Tests if database rolls back the changes correctly.''' database = MemcachedDatabase() square = database.get_square((6, 2), for_update=True) square.set_robot_id("iuwuyehdmn990198283") database.rollback() database.commit() new_square = database.get_square((6, 2)) self.assertNotEqual(square.get_robot_id(), new_square.get_robot_id())
def test_locked_location(self): '''Tests adding a robot to a locked location.''' database = MemcachedDatabase() robot = Robot("test_locked_location_0023", "123") # Locking 8,1 database.get_square((8, 1), for_update=True) self._world.add_robot(robot, (8, 1)) database.commit() received_robot = database.get_robot(robot.get_id()) self.assertNotEqual(received_robot.get_location(), (8, 1))
def test_locked_square(self): '''Tests with a already-locked square.''' database = MemcachedDatabase() robot = Robot("oi981872yuweu.9887", "123") robot.set_location((5, 0)) robot.set_has_water(True) database.get_square((5, 0), for_update=True) action = WaterAction() with self.assertRaises(LockAlreadyAquiredError): action.do_action(robot, ["oi981872yuweu.9887"]) # Freeing lock. database.rollback()
def test_locked_square(self): '''Tests with a already-locked square.''' database = MemcachedDatabase() robot = Robot("oi981872yuweu.9887", "123") robot.set_location((5, 0)) robot.set_has_water(True) database.get_square((5, 0), for_update=True) action = WaterAction() with self.assertRaises(LockAlreadyAquiredError): action.do_action(robot, ["oi981872yuweu.9887"]) # Freeing lock. database.rollback()
def test_lock(self): '''Tests if location is locked.''' robot_id = "test_move_lock_76120" robot = Robot(robot_id, "123") world = World() action_manager = ActionManager() database = MemcachedDatabase() world.add_robot(robot, (13, 6)) database.commit() database.get_square((13, 7), for_update=True) with self.assertRaises(LockAlreadyAquiredError): action_manager.do_action("123", "move", [robot_id, "S"]) database.rollback()
def test_ok(self): '''Tests an OK scenario.''' database = MemcachedDatabase() row = [ MapSquare(MapSquareTypes.SOIL, (0, 999)), MapSquare(MapSquareTypes.WATER, (1, 999)), MapSquare(MapSquareTypes.ROCK, (2, 999)), MapSquare(MapSquareTypes.SAND, (3, 999)) ] database.add_square_row(row) self.assertEqual( database.get_square((0, 999)).get_type(), MapSquareTypes.SOIL) self.assertEqual( database.get_square((1, 999)).get_type(), MapSquareTypes.WATER) self.assertEqual( database.get_square((2, 999)).get_type(), MapSquareTypes.ROCK) self.assertEqual( database.get_square((3, 999)).get_type(), MapSquareTypes.SAND)
def test_for_update(self): '''Tests for_update flag of get_square method.''' database = MemcachedDatabase() square = database.get_square((6, 1), for_update=True) # Testing the lock. with self.assertRaises(LockAlreadyAquiredError): database.get_square((6, 1), for_update=True) # Testing commit. square.set_robot_id("ujhqi981762yhdg67") # It shouldn't be changed yet. new_square = database.get_square((6, 1)) self.assertNotEqual(square.get_robot_id(), new_square.get_robot_id()) # Committing changes. database.commit() new_square = database.get_square((6, 1)) self.assertEqual(square.get_robot_id(), new_square.get_robot_id()) # Lock should be freed. new_square = database.get_square((6, 1), for_update=True) database.rollback()
def test_getting_data(self): robot = Robot("13329.12900.12213", "123", name="HappyBot") robot.set_energy(124) robot.set_honor(7) robot.set_life(3) robot.set_has_water(True) plant = Plant() plant.set_age(64) plant.set_water_level(98) database = MemcachedDatabase() database.add_robot(robot, (6, 11)) square = database.get_square((5, 11), for_update=True) square.set_plant(plant) database.commit() expected_result = { "5,11": { "surface_type": MapSquareTypes.SOIL, "plant": { "water_level": 98, "matured": True, "age": 64 }, "robot": None }, "6,11": { "surface_type": MapSquareTypes.SOIL, "plant": None, "robot": { "name": "HappyBot", "has_water": True, "energy": 124, "life": 3, "honor": 7 } }, "6,2": { "surface_type": MapSquareTypes.ROCK, "robot": None, "plant": None } } communicator = Communicator() result = communicator.execute_command("NhdEr32Qcmp0Iue3", "map_data", expected_result.keys()) self.assertCountEqual(result, expected_result) for expected_key, expected_value in expected_result.items(): self.assertDictEqual(result[expected_key], expected_value)
class ObjectUpdater(DatabaseHook): '''This class checks objects in the world, and updates them if required. Responsibilities of this class: * Killing and removing a robot from the world, if its energy reached zero or it ran out of life. * Removing a plant from the world if its water level reached zero or it became too old. * Maturing a plant if it reached a certain age. * Updating a plant's water level during time. ''' def __init__(self): self._database = MemcachedDatabase() self._configs = Configs() def robot_got(self, robot_object, locked_for_update): '''Checks and updates the specified robot's object.''' if robot_object.get_energy() <= 0 or robot_object.get_life() <= 0: if not locked_for_update: # This would call this method again, and robot will be updated. return self._database.get_robot(robot_object.get_id(), for_update=True) robot_object.set_alive(False) # Removing the robot from its location. try: square = self._database.get_square(robot_object.get_location(), for_update=True) except LockAlreadyAquiredError: # Trying one more time. time.sleep(0.02) square = self._database.get_square(robot_object.get_location(), for_update=True) square.set_robot_id(None) # XXX: Though it's a very dirty thing to do, we have to commit these changes, because # later this robot will face an Authentication Exception, and our changes will be # lost. self._database.commit() # Immediately, locking the robot object. It's not atomic, so there's a little chance # that concurrency happens. But, it shouldn't be a problem, since the robot is already # dead, and can't do anything anyway. self._database.get_lock(robot_object.get_id()) return robot_object def square_got(self, location, square_object, locked_for_update): '''Checks and updates specified square object.''' plant = square_object.get_plant() if plant is None: return square_object # Time passed from the last time this plant updated. last_update = time.time() - plant.get_last_update() passed_cycles = math.floor(last_update / (self._configs.get_plant_cylce() / 1000)) if passed_cycles <= 0: # No cycle passed, no need to be updated. return square_object if not locked_for_update: # This will call this method again. try: return self._database.get_square(location, for_update=True) except LockAlreadyAquiredError: # Trying one more time. time.sleep(0.02) return self._database.get_square(location, for_update=True) plant.set_age(plant.get_age() + passed_cycles) plant.set_water_level(plant.get_water_level() - (passed_cycles * self._configs.get_plant_lose_water_in_cycle())) if plant.get_age() > self._configs.get_plant_max_age( ) or plant.get_water_level() <= 0: # Plant is dead! Removing it from the world. square_object.set_plant(None) plant.set_last_update(time.time()) return square_object
class ObjectUpdater(DatabaseHook): '''This class checks objects in the world, and updates them if required. Responsibilities of this class: * Killing and removing a robot from the world, if its energy reached zero or it ran out of life. * Removing a plant from the world if its water level reached zero or it became too old. * Maturing a plant if it reached a certain age. * Updating a plant's water level during time. ''' def __init__(self): self._database = MemcachedDatabase() self._configs = Configs() def robot_got(self, robot_object, locked_for_update): '''Checks and updates the specified robot's object.''' if robot_object.get_energy() <= 0 or robot_object.get_life() <= 0: if not locked_for_update: # This would call this method again, and robot will be updated. return self._database.get_robot(robot_object.get_id(), for_update=True) robot_object.set_alive(False) # Removing the robot from its location. try: square = self._database.get_square(robot_object.get_location(), for_update=True) except LockAlreadyAquiredError: # Trying one more time. time.sleep(0.02) square = self._database.get_square(robot_object.get_location(), for_update=True) square.set_robot_id(None) # XXX: Though it's a very dirty thing to do, we have to commit these changes, because # later this robot will face an Authentication Exception, and our changes will be # lost. self._database.commit() # Immediately, locking the robot object. It's not atomic, so there's a little chance # that concurrency happens. But, it shouldn't be a problem, since the robot is already # dead, and can't do anything anyway. self._database.get_lock(robot_object.get_id()) return robot_object def square_got(self, location, square_object, locked_for_update): '''Checks and updates specified square object.''' plant = square_object.get_plant() if plant is None: return square_object # Time passed from the last time this plant updated. last_update = time.time() - plant.get_last_update() passed_cycles = math.floor(last_update / (self._configs.get_plant_cylce() / 1000)) if passed_cycles <= 0: # No cycle passed, no need to be updated. return square_object if not locked_for_update: # This will call this method again. try: return self._database.get_square(location, for_update=True) except LockAlreadyAquiredError: # Trying one more time. time.sleep(0.02) return self._database.get_square(location, for_update=True) plant.set_age(plant.get_age() + passed_cycles) plant.set_water_level(plant.get_water_level() - (passed_cycles * self._configs.get_plant_lose_water_in_cycle())) if plant.get_age() > self._configs.get_plant_max_age() or plant.get_water_level() <= 0: # Plant is dead! Removing it from the world. square_object.set_plant(None) plant.set_last_update(time.time()) return square_object
class World(Singleton): def _initialize(self): self._size = (-1, -1) self._database = MemcachedDatabase() self._database.register_hook(ObjectUpdater()) def get_size(self): '''Returns size of the world.''' if self._size == (-1, -1): # Reading the size from database, and caching it. # Although `load_from_file' method sets this variable, # after forking this variable will be reset. So we need # to load the size from database again. self._size = self._database.get_world_size() return self._size def add_robot(self, robot, location): '''Adds a robot to the world. It tries to find the nearest empty point to the specified point. @param robot: Instance of objects.robot.Robot. @param location: Location to try to add the robot. (x, y) ''' for square_x, square_y in SquareInterator(location, self._size): try: square_object = self.get_square((square_x, square_y), for_update=True) # Checking if something blocked this square. if not square_object.is_blocking(): robot.set_location((square_x, square_y)) self._database.add_robot(robot, (square_x, square_y)) # Done. return except LockAlreadyAquiredError: # If this square was locked, go to the next one. continue raise exceptions.WorldIsFullError("No free location is remained in the world!") # pragma: no cover def move_robot(self, robot, destination): '''Moves a robot to the specified location. @param destination: A tuple of (x, y) ''' # Locking both origin and destination. origin = robot.get_location() origin_square = self.get_square(origin, for_update=True) destination_square = self.get_square(destination, for_update=True) if destination_square.is_blocking(): raise exceptions.LocationIsBlockedError("Destination location {0} is blocked.".format(destination)) origin_square.set_robot_id(None) destination_square.set_robot_id(robot.get_id()) robot.set_location(destination) def plant(self, plant, location): '''Plant a plant on the specified location.''' square = self.get_square(location, for_update=True) if square.get_type() != MapSquareTypes.SOIL: raise exceptions.CannotPlantHereError("Cannot plant on {0} square type.".format(square.get_type())) if square.get_plant() is not None: raise exceptions.AlreadyPlantError("There's already a plant on {0}".format(location)) square.set_plant(plant) def get_square(self, location, for_update=False): '''Gets the square object of the specified location. @param location: Location to get. @param for_update: If you want to update this square (store its changes back to the database) you should set this flag. Note that it automatically updates the changes if transaction commits. ''' return self._database.get_square(location, for_update=for_update) def load_from_file(self, file_path): '''Loads a world from the specified file.''' with open(file_path, 'r') as world_file: file_lines = world_file.readlines() row_length = None line_number = 0 for line in file_lines: line = line.replace('\r', '').replace('\n', '') if line.startswith("#") or line.isspace(): continue line_number += 1 # Keeping length of the first line, so we can validate that all # the lines have same length. if row_length is None: row_length = len(line) if len(line) != row_length: raise exceptions.InvalidWorldFileError("Length of line {0} is invalid.".format(line_number)) row = [] column_number = 0 for square_type in line: column_number += 1 square_type = int(square_type) if square_type not in (0, 1, 2, 3): raise exceptions.InvalidWorldFileError( "Found invalid square in line {0} column {1}.".format(line_number, column_number)) row.append(MapSquare(square_type, (column_number - 1, line_number - 1))) self._database.add_square_row(row) self._size = (row_length, line_number) self._database.set_world_size(self._size)
def test_not_exists_square(self): '''Tests getting a square that does not exists.''' database = MemcachedDatabase() with self.assertRaises(InvalidLocationError): database.get_square((19873, 1736))
class World(Singleton): def _initialize(self): self._size = (-1, -1) self._database = MemcachedDatabase() self._database.register_hook(ObjectUpdater()) def get_size(self): '''Returns size of the world.''' if self._size == (-1, -1): # Reading the size from database, and caching it. # Although `load_from_file' method sets this variable, # after forking this variable will be reset. So we need # to load the size from database again. self._size = self._database.get_world_size() return self._size def add_robot(self, robot, location): '''Adds a robot to the world. It tries to find the nearest empty point to the specified point. @param robot: Instance of objects.robot.Robot. @param location: Location to try to add the robot. (x, y) ''' for square_x, square_y in SquareInterator(location, self._size): try: square_object = self.get_square((square_x, square_y), for_update=True) # Checking if something blocked this square. if not square_object.is_blocking(): robot.set_location((square_x, square_y)) self._database.add_robot(robot, (square_x, square_y)) # Done. return except LockAlreadyAquiredError: # If this square was locked, go to the next one. continue raise exceptions.WorldIsFullError( "No free location is remained in the world!") # pragma: no cover def move_robot(self, robot, destination): '''Moves a robot to the specified location. @param destination: A tuple of (x, y) ''' # Locking both origin and destination. origin = robot.get_location() origin_square = self.get_square(origin, for_update=True) destination_square = self.get_square(destination, for_update=True) if destination_square.is_blocking(): raise exceptions.LocationIsBlockedError( "Destination location {0} is blocked.".format(destination)) origin_square.set_robot_id(None) destination_square.set_robot_id(robot.get_id()) robot.set_location(destination) def plant(self, plant, location): '''Plant a plant on the specified location.''' square = self.get_square(location, for_update=True) if square.get_type() != MapSquareTypes.SOIL: raise exceptions.CannotPlantHereError( "Cannot plant on {0} square type.".format(square.get_type())) if square.get_plant() is not None: raise exceptions.AlreadyPlantError( "There's already a plant on {0}".format(location)) square.set_plant(plant) def get_square(self, location, for_update=False): '''Gets the square object of the specified location. @param location: Location to get. @param for_update: If you want to update this square (store its changes back to the database) you should set this flag. Note that it automatically updates the changes if transaction commits. ''' return self._database.get_square(location, for_update=for_update) def load_from_file(self, file_path): '''Loads a world from the specified file.''' with open(file_path, 'r') as world_file: file_lines = world_file.readlines() row_length = None line_number = 0 for line in file_lines: line = line.replace('\r', '').replace('\n', '') if line.startswith("#") or line.isspace(): continue line_number += 1 # Keeping length of the first line, so we can validate that all # the lines have same length. if row_length is None: row_length = len(line) if len(line) != row_length: raise exceptions.InvalidWorldFileError( "Length of line {0} is invalid.".format(line_number)) row = [] column_number = 0 for square_type in line: column_number += 1 square_type = int(square_type) if square_type not in (0, 1, 2, 3): raise exceptions.InvalidWorldFileError( "Found invalid square in line {0} column {1}.".format( line_number, column_number)) row.append( MapSquare(square_type, (column_number - 1, line_number - 1))) self._database.add_square_row(row) self._size = (row_length, line_number) self._database.set_world_size(self._size)