def test_specific_point(self):
        '''Gets information of a specific point, and check its result.'''
        database = MemcachedDatabase()
        new_robot = Robot("oie982736hhjf", "lo098173635")
        new_robot.set_location((9, 4))

        database.add_robot(new_robot, (9, 4))
        database.commit()

        action_manager = ActionManager()
        info = action_manager.do_action(new_robot.get_password(), "sense", [new_robot.get_id()])

        self.assertEqual(len(info), 9)
        self.assertEqual(info["9,4"], {"surface_type": MapSquareTypes.SOIL,
                                       "robot": True,
                                       "plant": None})
        self.assertEqual(info["9,3"], {"surface_type": MapSquareTypes.WATER,
                                       "robot": False,
                                       "plant": None})
        self.assertEqual(info["10,5"], {"surface_type": MapSquareTypes.SOIL,
                                        "robot": False,
                                        "plant": None})
        self.assertEqual(info["8,4"], {"surface_type": MapSquareTypes.SOIL,
                                       "robot": False,
                                       "plant": None})
Ejemplo n.º 2
0
    def test_for_update(self):
        '''Tests of for_update flag works correctly.'''
        database = MemcachedDatabase()

        robot_id = "test_for_update_18762"
        robot = Robot(robot_id, "123")
        database.add_robot(robot, (10, 0))
        database.commit()

        new_robot = database.get_robot(robot_id, for_update=True)

        # Testing lock
        with self.assertRaises(LockAlreadyAquiredError):
            database.get_robot(robot_id, for_update=True)

        # Testing commit.
        new_robot.set_alive(False)

        # It shouldn't be changed yet.
        new_robot_2 = database.get_robot(robot_id)
        self.assertNotEqual(new_robot.get_alive(), new_robot_2.get_alive())

        # Actually committing changes.
        database.commit()
        new_robot_2 = database.get_robot(robot_id)
        self.assertEqual(new_robot.get_alive(), new_robot_2.get_alive())

        # Lock should be freed.
        database.get_robot(robot_id, for_update=True)
        database.rollback()
Ejemplo n.º 3
0
    def test_for_update(self):
        '''Tests of for_update flag works correctly.'''
        database = MemcachedDatabase()

        robot_id = "test_for_update_18762"
        robot = Robot(robot_id, "123")
        database.add_robot(robot, (10, 0))
        database.commit()

        new_robot = database.get_robot(robot_id, for_update=True)

        # Testing lock
        with self.assertRaises(LockAlreadyAquiredError):
            database.get_robot(robot_id, for_update=True)

        # Testing commit.
        new_robot.set_alive(False)

        # It shouldn't be changed yet.
        new_robot_2 = database.get_robot(robot_id)
        self.assertNotEqual(new_robot.get_alive(), new_robot_2.get_alive())

        # Actually committing changes.
        database.commit()
        new_robot_2 = database.get_robot(robot_id)
        self.assertEqual(new_robot.get_alive(), new_robot_2.get_alive())

        # Lock should be freed.
        database.get_robot(robot_id, for_update=True)
        database.rollback()
Ejemplo n.º 4
0
    def test_specific_point(self):
        '''Gets information of a specific point, and check its result.'''
        database = MemcachedDatabase()
        new_robot = Robot("oie982736hhjf", "lo098173635")
        new_robot.set_location((9, 4))

        database.add_robot(new_robot, (9, 4))
        database.commit()

        action_manager = ActionManager()
        info = action_manager.do_action(new_robot.get_password(), "sense",
                                        [new_robot.get_id()])

        self.assertEqual(len(info), 9)
        self.assertEqual(info["9,4"], {
            "surface_type": MapSquareTypes.SOIL,
            "robot": True,
            "plant": None
        })
        self.assertEqual(info["9,3"], {
            "surface_type": MapSquareTypes.WATER,
            "robot": False,
            "plant": None
        })
        self.assertEqual(info["10,5"], {
            "surface_type": MapSquareTypes.SOIL,
            "robot": False,
            "plant": None
        })
        self.assertEqual(info["8,4"], {
            "surface_type": MapSquareTypes.SOIL,
            "robot": False,
            "plant": None
        })
Ejemplo n.º 5
0
    def test_invalid_location(self):
        '''Tests if database checks for invalid locations.'''
        database = MemcachedDatabase()

        new_robot = Robot("test_invalid_location_19887", "123")

        with self.assertRaises(InvalidLocationError):
            database.add_robot(new_robot, (91872, 16652))
            database.commit()
Ejemplo n.º 6
0
    def test_rollback(self):
        '''Tests if calling rollback works correctly.'''
        database = MemcachedDatabase()

        new_robot = Robot("test_rollback_87162", "123")
        database.add_robot(new_robot, (1, 1))

        database.rollback()
        database.commit()

        with self.assertRaises(RobotNotFoundError):
            database.get_robot("test_rollback_87162")
Ejemplo n.º 7
0
    def test_duplicate_add(self):
        '''Adding two robots with same ID. Should be failed.'''
        database = MemcachedDatabase()

        new_robot = Robot("test_duplicate_add_", "123")
        database.add_robot(new_robot, (1, 1))
        database.commit()

        robot2 = Robot("test_duplicate_add_", "123")
        with self.assertRaises(CannotAddObjectError):
            database.add_robot(robot2, (1, 2))
            database.commit()
Ejemplo n.º 8
0
    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)
    def test_corner(self):
        '''Tests getting a corner of the map.'''
        database = MemcachedDatabase()
        new_robot = Robot("0981kdjieu871", "oie987163")
        new_robot.set_location((0, 1))

        database.add_robot(new_robot, (0, 1))
        database.commit()

        action_manager = ActionManager()
        info = action_manager.do_action(new_robot.get_password(), "sense", [new_robot.get_id()])

        self.assertEqual(len(info), 6)
    def test_blind_point(self):
        '''Gets information of a point, but don't care about the result.'''
        database = MemcachedDatabase()
        new_robot = Robot("1873yudhNCbueio", "ueijdnchiop")
        new_robot.set_location((9, 7))

        database.add_robot(new_robot, (9, 7))
        database.commit()

        action_manager = ActionManager()
        info = action_manager.do_action(new_robot.get_password(), "sense", [new_robot.get_id()])

        self.assertEqual(len(info), 9)
Ejemplo n.º 11
0
    def test_with_parent(self):
        '''Tests borning a robot with a parent.'''
        population_control = PopulationControl()
        database = MemcachedDatabase()

        database.add_password("oijdnnh76153WEd")
        robot = Robot("test_with_parent_18873", "123")
        database.add_robot(robot, (14, 1))
        database.commit()

        population_control.execute_command("oijdnnh76153WEd", "born", ["test_with_parent_18873", "My Child"])

        database.rollback()
Ejemplo n.º 12
0
    def test_corner(self):
        '''Tests getting a corner of the map.'''
        database = MemcachedDatabase()
        new_robot = Robot("0981kdjieu871", "oie987163")
        new_robot.set_location((0, 1))

        database.add_robot(new_robot, (0, 1))
        database.commit()

        action_manager = ActionManager()
        info = action_manager.do_action(new_robot.get_password(), "sense",
                                        [new_robot.get_id()])

        self.assertEqual(len(info), 6)
Ejemplo n.º 13
0
    def test_blind_point(self):
        '''Gets information of a point, but don't care about the result.'''
        database = MemcachedDatabase()
        new_robot = Robot("1873yudhNCbueio", "ueijdnchiop")
        new_robot.set_location((9, 7))

        database.add_robot(new_robot, (9, 7))
        database.commit()

        action_manager = ActionManager()
        info = action_manager.do_action(new_robot.get_password(), "sense",
                                        [new_robot.get_id()])

        self.assertEqual(len(info), 9)
Ejemplo n.º 14
0
    def test_with_parent(self):
        '''Tests borning a robot with a parent.'''
        population_control = PopulationControl()
        database = MemcachedDatabase()

        database.add_password("oijdnnh76153WEd")
        robot = Robot("test_with_parent_18873", "123")
        database.add_robot(robot, (14, 1))
        database.commit()

        population_control.execute_command(
            "oijdnnh76153WEd", "born", ["test_with_parent_18873", "My Child"])

        database.rollback()
Ejemplo n.º 15
0
    def test_simple_add(self):
        '''Test adding a single robot to database.'''
        database = MemcachedDatabase()

        new_robot = Robot("test_simple_add_", "123")

        # No exception should be raise.
        database.add_robot(new_robot, (0, 0))
        database.commit()

        gotted_robot = database.get_robot("test_simple_add_")

        self.assertEqual(gotted_robot.get_id(), new_robot.get_id())
        self.assertEqual(gotted_robot.get_alive(), new_robot.get_alive())
        self.assertEqual(gotted_robot.get_password(), new_robot.get_password())
Ejemplo n.º 16
0
    def test_rollback(self):
        '''Tests if changes rolls back correctly.'''
        database = MemcachedDatabase()

        robot_id = "test_rollback_18098"
        robot = Robot(robot_id, "123")
        database.add_robot(robot, (11, 0))
        database.commit()

        new_robot = database.get_robot(robot_id, for_update=True)
        new_robot.set_alive(False)

        database.rollback()
        database.commit()

        new_robot_2 = database.get_robot(robot_id)
        self.assertNotEqual(new_robot.get_alive(), new_robot_2.get_alive())
Ejemplo n.º 17
0
    def test_rollback(self):
        '''Tests if changes rolls back correctly.'''
        database = MemcachedDatabase()

        robot_id = "test_rollback_18098"
        robot = Robot(robot_id, "123")
        database.add_robot(robot, (11, 0))
        database.commit()

        new_robot = database.get_robot(robot_id, for_update=True)
        new_robot.set_alive(False)

        database.rollback()
        database.commit()

        new_robot_2 = database.get_robot(robot_id)
        self.assertNotEqual(new_robot.get_alive(), new_robot_2.get_alive())
Ejemplo n.º 18
0
    def test_concurrent_add_failure(self):
        '''Tests the behavior of Database class, when concurrent add fails.'''

        # Mocking `cas' method, making it always return False.
        def mocked_cas(*args):
            return False
        mc_connection = MemcachedConnection().get_connection()
        original_cas = mc_connection.cas
        mc_connection.cas = unittest.mock.Mock(side_effect=mocked_cas)

        try:
            new_robot = Robot("test_concurrent_add_failure_9865", "123")
            database = MemcachedDatabase()

            with self.assertRaises(CouldNotSetValueBecauseOfConcurrencyError):
                database.add_robot(new_robot, (1, 1))
                database.commit()

        finally:
            # Setting back the original cas method.
            mc_connection.cas = original_cas

        # Checking to see added robot is clearly rolled back.
        self.assertFalse(mc_connection.get(new_robot.get_id()))
class TestActionManager(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(TestActionManager, self).__init__(*args, **kwargs)

        self._action_manager = ActionManager()
        self._database = MemcachedDatabase()

    def tearDown(self):
        # Rolling back any remaining thing.
        self._database.rollback()

    def test_not_exist_robot(self):
        '''Test if ActionManager handles not-existed robot.'''
        with self.assertRaises(RobotNotFoundError):
            self._action_manager.do_action("123", "move",
                                           ["not_existed_robot_id"])

    def test_bad_robot_id(self):
        '''Test invalid robot IDs.'''
        # Note that listeners checks if `args' is a list, so action manager won't receive another type.

        with self.assertRaises(actions.exceptions.InvalidArgumentsError):
            self._action_manager.do_action("123", "move", [])

        with self.assertRaises(actions.exceptions.InvalidArgumentsError):
            self._action_manager.do_action("123", "move", [None])

    def test_invalid_password(self):
        '''Test if ActionManager authenticate passwords correctly.'''
        robot = Robot("test_invalid_password_95312", "andhue-ifue876-fkdnpw-1")
        self._database.add_robot(robot, (3, 1))
        self._database.commit()

        with self.assertRaises(AuthenticationFailedError):
            self._action_manager.do_action("ieukjdf-ioquiwe-751io", "status",
                                           ["test_invalid_password_95312"])

    def test_dead_robot(self):
        '''Test if ActionManager checks a dead robot.'''
        robot = Robot("test_dead_robot_98176", "1234")
        robot.set_alive(False)
        self._database.add_robot(robot, (3, 2))
        self._database.commit()

        with self.assertRaises(AuthenticationFailedError):
            self._action_manager.do_action("1234", "status",
                                           ["test_dead_robot_98176"])

    def test_bad_actions(self):
        '''Test wrong action IDs.'''
        robot = Robot("test_bad_actions_2376", "123")
        self._database.add_robot(robot, (4, 1))
        self._database.commit()

        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", "not-exist-action",
                                           ["test_bad_actions_2376"])

        self._database.rollback()
        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", 5432,
                                           ["test_bad_actions_2376"])

        self._database.rollback()
        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", None,
                                           ["test_bad_actions_2376"])

        self._database.rollback()
        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", "",
                                           ["test_bad_actions_2376"])

    def test_ok(self):
        '''Execute a fine action.'''
        robot = Robot("test_ok_action_3278", "4467yrt-ddfjh-1u872-oiie")
        self._database.add_robot(robot, (3, 3))
        self._database.commit()

        initial_energy = robot.get_energy()
        initial_age = robot.get_life()

        result = self._action_manager.do_action("4467yrt-ddfjh-1u872-oiie",
                                                "status",
                                                ["test_ok_action_3278"])

        self.assertEqual(result['alive'], True)

        # Robot should lost energy and age.
        self._database.commit()
        robot = self._database.get_robot("test_ok_action_3278")
        self.assertEqual(robot.get_energy(), initial_energy - 1)
        self.assertEqual(robot.get_life(), initial_age - 1)

    def test_losing_energy_on_error(self):
        '''Tests if ActionManager reduces energy and age after an exception.'''
        robot = Robot("test_losing_energy_on_error_981", "091oikjdmncj")
        self._database.add_robot(robot, (5, 3))
        self._database.commit()

        initial_energy = robot.get_energy()
        initial_age = robot.get_life()

        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("091oikjdmncj", "invalid_action",
                                           ["test_losing_energy_on_error_981"])

        self._database.commit()
        robot = self._database.get_robot("test_losing_energy_on_error_981")
        self.assertEqual(robot.get_energy(), initial_energy - 1)
        self.assertEqual(robot.get_life(), initial_age - 1)

        # Robot shouldn't lose energy on authentication error.
        with self.assertRaises(AuthenticationFailedError):
            self._action_manager.do_action("wrong pass", "invalid_action",
                                           ["test_losing_energy_on_error_981"])

        self._database.rollback()
        robot = self._database.get_robot("test_losing_energy_on_error_981")
        self.assertEqual(robot.get_energy(), initial_energy - 1)
        self.assertEqual(robot.get_life(), initial_age - 1)

    def test_delay(self):
        '''Tests delay between robot actions.'''
        robot = Robot("test_delay_1223", "09112345")
        self._database.add_robot(robot, (6, 3))
        self._database.commit()

        self._action_manager.do_action("09112345", "sense", [robot.get_id()])
        self._database.commit()

        start_time = time.time()
        self._action_manager.do_action("09112345", "sense", [robot.get_id()])
        elapsed_time = time.time() - start_time
        self._database.commit()

        # one millisecond reduced from delay to cover error.
        self.assertGreater(elapsed_time, 0.029)
Ejemplo n.º 20
0
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)
class TestActionManager(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestActionManager, self).__init__(*args, **kwargs)

        self._action_manager = ActionManager()
        self._database = MemcachedDatabase()

    def tearDown(self):
        # Rolling back any remaining thing.
        self._database.rollback()

    def test_not_exist_robot(self):
        '''Test if ActionManager handles not-existed robot.'''
        with self.assertRaises(RobotNotFoundError):
            self._action_manager.do_action("123", "move", ["not_existed_robot_id"])

    def test_bad_robot_id(self):
        '''Test invalid robot IDs.'''
        # Note that listeners checks if `args' is a list, so action manager won't receive another type.

        with self.assertRaises(actions.exceptions.InvalidArgumentsError):
            self._action_manager.do_action("123", "move", [])

        with self.assertRaises(actions.exceptions.InvalidArgumentsError):
            self._action_manager.do_action("123", "move", [None])

    def test_invalid_password(self):
        '''Test if ActionManager authenticate passwords correctly.'''
        robot = Robot("test_invalid_password_95312", "andhue-ifue876-fkdnpw-1")
        self._database.add_robot(robot, (3, 1))
        self._database.commit()

        with self.assertRaises(AuthenticationFailedError):
            self._action_manager.do_action("ieukjdf-ioquiwe-751io", "status", ["test_invalid_password_95312"])

    def test_dead_robot(self):
        '''Test if ActionManager checks a dead robot.'''
        robot = Robot("test_dead_robot_98176", "1234")
        robot.set_alive(False)
        self._database.add_robot(robot, (3, 2))
        self._database.commit()

        with self.assertRaises(AuthenticationFailedError):
            self._action_manager.do_action("1234", "status", ["test_dead_robot_98176"])

    def test_bad_actions(self):
        '''Test wrong action IDs.'''
        robot = Robot("test_bad_actions_2376", "123")
        self._database.add_robot(robot, (4, 1))
        self._database.commit()

        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", "not-exist-action", ["test_bad_actions_2376"])

        self._database.rollback()
        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", 5432, ["test_bad_actions_2376"])

        self._database.rollback()
        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", None, ["test_bad_actions_2376"])

        self._database.rollback()
        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("123", "", ["test_bad_actions_2376"])

    def test_ok(self):
        '''Execute a fine action.'''
        robot = Robot("test_ok_action_3278", "4467yrt-ddfjh-1u872-oiie")
        self._database.add_robot(robot, (3, 3))
        self._database.commit()

        initial_energy = robot.get_energy()
        initial_age = robot.get_life()

        result = self._action_manager.do_action("4467yrt-ddfjh-1u872-oiie", "status", ["test_ok_action_3278"])

        self.assertEqual(result['alive'], True)

        # Robot should lost energy and age.
        self._database.commit()
        robot = self._database.get_robot("test_ok_action_3278")
        self.assertEqual(robot.get_energy(), initial_energy - 1)
        self.assertEqual(robot.get_life(), initial_age - 1)

    def test_losing_energy_on_error(self):
        '''Tests if ActionManager reduces energy and age after an exception.'''
        robot = Robot("test_losing_energy_on_error_981", "091oikjdmncj")
        self._database.add_robot(robot, (5, 3))
        self._database.commit()

        initial_energy = robot.get_energy()
        initial_age = robot.get_life()

        with self.assertRaises(actions.exceptions.InvalidActionError):
            self._action_manager.do_action("091oikjdmncj", "invalid_action", ["test_losing_energy_on_error_981"])

        self._database.commit()
        robot = self._database.get_robot("test_losing_energy_on_error_981")
        self.assertEqual(robot.get_energy(), initial_energy - 1)
        self.assertEqual(robot.get_life(), initial_age - 1)

        # Robot shouldn't lose energy on authentication error.
        with self.assertRaises(AuthenticationFailedError):
            self._action_manager.do_action("wrong pass", "invalid_action", ["test_losing_energy_on_error_981"])

        self._database.rollback()
        robot = self._database.get_robot("test_losing_energy_on_error_981")
        self.assertEqual(robot.get_energy(), initial_energy - 1)
        self.assertEqual(robot.get_life(), initial_age - 1)

    def test_delay(self):
        '''Tests delay between robot actions.'''
        robot = Robot("test_delay_1223", "09112345")
        self._database.add_robot(robot, (6, 3))
        self._database.commit()

        self._action_manager.do_action("09112345", "sense", [robot.get_id()])
        self._database.commit()

        start_time = time.time()
        self._action_manager.do_action("09112345", "sense", [robot.get_id()])
        elapsed_time = time.time() - start_time
        self._database.commit()

        # one millisecond reduced from delay to cover error.
        self.assertGreater(elapsed_time, 0.029)
Ejemplo n.º 22
0
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)