Exemplo n.º 1
0
def test_use_container():
    container = Container()
    container.reset()

    agent = make_connected_agent()

    assert agent.container == Container()

    assert container.has_agent(str(agent.jid))
    assert container.get_agent(str(agent.jid)) == agent

    agent.stop()
Exemplo n.º 2
0
def test_use_container():
    container = Container()
    container.reset()

    agent = MockedAgentFactory()

    assert agent.container == Container()

    assert container.has_agent(str(agent.jid))
    assert container.get_agent(str(agent.jid)) == agent

    agent.stop()
Exemplo n.º 3
0
    def __init__(self, jid, password, verify_security=False):
        """
        Creates an agent

        Args:
          jid (str): The identifier of the agent in the form username@server
          password (str): The password to connect to the server
          verify_security (bool): Wether to verify or not the SSL certificates
        """
        self.jid = aioxmpp.JID.fromstr(jid)
        self.password = password
        self.verify_security = verify_security

        self.behaviours = []
        self._values = {}

        self.conn_coro = None
        self.stream = None
        self.client = None
        self.message_dispatcher = None
        self.presence = None
        self.loop = None

        self.container = Container()
        self.container.register(self)

        self.loop = self.container.loop

        # Web service
        self.web = WebApp(agent=self)

        self.traces = TraceStore(size=1000)

        self._alive = Event()
Exemplo n.º 4
0
    def __init__(self, colour, jid, password, verify_security=False):
        self.jid = aioxmpp.JID.fromstr(jid)
        self.password = password
        self.verify_security = verify_security

        self.behaviours = []
        self._values = {}

        self.conn_coro = None
        self.stream = None
        self.client = None
        self.message_dispatcher = None
        self.presence = None
        self.loop = None

        self.container = Container()
        self.container.register(self)

        self.loop = self.container.loop

        # Web service
        self.web = WebApp(agent=self)
        self.traces = TraceStore(size=1000)
        self._alive = Event()

        self.colour = colour
        self.finished = False
        # initialize four pawns with
        # id (first leter from colour and index (from 1 to 4))
        self.pawns = [Pawn(i, self.colour, self.__getitem__() + str(i))
                      for i in range(1, 5)]
Exemplo n.º 5
0
def test_send_message_to_outer_with_container():
    class SendBehaviour(OneShotBehaviour):
        async def run(self):
            message = Message(to="to@outerhost")
            await self.send(message)
            self.kill()

    container = Container()
    container.reset()

    agent = MockedAgentFactory()
    agent.start(auto_register=False)

    behaviour = SendBehaviour()
    behaviour._xmpp_send = CoroutineMock()
    agent.add_behaviour(behaviour)

    behaviour.join()

    assert container.has_agent(str(agent.jid))
    assert not container.has_agent("to@outerhost")

    assert behaviour._xmpp_send.await_count == 1
    msg_arg = behaviour._xmpp_send.await_args[0][0]
    assert msg_arg.to == aioxmpp.JID.fromstr("to@outerhost")

    agent.stop()
Exemplo n.º 6
0
def run_around_tests():
    # Code that will run before your test, for example:
    # A test function will be run at this point
    container = Container()
    if not container.is_running:
        container.__init__()
    yield
    # Code that will run after your test, for example:
    quit_spade()
Exemplo n.º 7
0
    def __init__(self, map_name, port=8001):
        self.clients = {}
        self.map_name = map_name
        self.port = port
        self.server = None

        self.container = Container()

        self.loop = self.container.loop

        self.coro = asyncio.start_server(self.accept_client, "", self.port, loop=self.loop)
Exemplo n.º 8
0
def test_unregister():
    container = Container()
    container.reset()

    agent = MockedAgentFactory()
    agent2 = MockedAgentFactory(jid="agent2@server")

    assert container.has_agent(str(agent.jid))
    assert container.has_agent(str(agent2.jid))

    container.unregister(agent.jid)

    assert not container.has_agent(str(agent.jid))
    assert container.has_agent(str(agent2.jid))
Exemplo n.º 9
0
def test_unregister():
    container = Container()
    container.reset()

    agent = make_connected_agent()
    agent2 = make_connected_agent(jid="agent2@server")

    assert container.has_agent(str(agent.jid))
    assert container.has_agent(str(agent2.jid))

    container.unregister(agent.jid)

    assert not container.has_agent(str(agent.jid))
    assert container.has_agent(str(agent2.jid))
Exemplo n.º 10
0
def test_use_container_false():
    container = Container()
    container.reset()

    agent = make_connected_agent(use_container=False)

    assert agent.container is None

    assert not container.has_agent(str(agent.jid))

    with pytest.raises(KeyError):
        container.get_agent(str(agent.jid))

    agent.stop()
Exemplo n.º 11
0
    def __init__(self,
                 jid,
                 password,
                 verify_security=False,
                 use_container=True,
                 loop=None):
        """
        Creates an agent

        Args:
          jid (str): The identifier of the agent in the form username@server
          password (str): The password to connect to the server
          verify_security (bool): Wether to verify or not the SSL certificates
          loop (an asyncio event loop): the event loop if it was already created (optional)
        """
        self.jid = aioxmpp.JID.fromstr(jid)
        self.password = password
        self.verify_security = verify_security

        self.behaviours = []
        self._values = {}

        if use_container:
            self.container = Container()
            self.container.register(self)
        else:
            self.container = None

        self.traces = TraceStore(size=1000)

        if loop:
            self.loop = loop
            self.external_loop = True
        else:
            self.loop = asyncio.new_event_loop()
            self.external_loop = False
        asyncio.set_event_loop(self.loop)

        self.aiothread = AioThread(self, self.loop)
        self._alive = Event()

        # obtain an instance of the service
        self.message_dispatcher = self.client.summon(SimpleMessageDispatcher)

        # Presence service
        self.presence = PresenceManager(self)

        # Web service
        self.web = WebApp(agent=self)
Exemplo n.º 12
0
    def __init__(self, jid, password, verify_security=False):

        self.jid = aioxmpp.JID.fromstr(jid)
        self.password = password
        self.verify_security = verify_security

        self.behaviours = []
        self._values = {}

        self.conn_coro = None
        self.stream = None
        self.client = None
        self.message_dispatcher = None
        self.presence = None
        self.loop = None

        self.container = Container()
        self.container.register(self)

        self.loop = self.container.loop

        # Web service
        self.web = WebApp(agent=self)

        self.traces = TraceStore(size=1000)

        self._alive = Event()

        self.players = deque()
        self.standing = []
        self.board = Board()
        # is game finished
        self.finished = False
        # last rolled value from die (dice)
        self.rolled_value = None
        # player who last rolled die
        self.curr_player = None
        # curr_player's possible pawn to move
        self.allowed_pawns = []
        # curr_player's chosen pawn to move
        self.picked_pawn = None
        # used for nicer print
        self.prompted_for_pawn = False
        # chosen index from allowed pawn
        self.index = None
        # jog pawn if any
        self.jog_pawns = []
        # agents that represent players
        self.playerAgents = []
Exemplo n.º 13
0
def test_send_message_with_container():
    class FakeReceiverAgent:
        def __init__(self):
            self.jid = "fake_receiver_agent@server"

        def set_container(self, c):
            pass

        def set_loop(self, loop):
            pass

        def stop(self):
            pass

        def is_alive(self):
            return False

    class SendBehaviour(OneShotBehaviour):
        async def run(self):
            message = Message(to="fake_receiver_agent@server")
            await self.send(message)
            self.kill()

    container = Container()
    container.reset()
    fake_receiver_agent = FakeReceiverAgent()
    container.register(fake_receiver_agent)

    fake_receiver_agent.dispatch = MagicMock()

    agent = MockedAgentFactory()
    future = agent.start(auto_register=False)
    future.result()

    agent.client = MagicMock()
    agent.client.send = CoroutineMock()
    behaviour = SendBehaviour()
    agent.add_behaviour(behaviour)

    behaviour.join()

    assert agent.client.send.await_count == 0

    assert fake_receiver_agent.dispatch.call_count == 1
    assert (str(fake_receiver_agent.dispatch.call_args[0][0].to) ==
            "fake_receiver_agent@server")

    agent.stop()
Exemplo n.º 14
0
def test_cancel_tasks():
    agent = MockedAgentFactory()

    class Behav(CyclicBehaviour):
        async def run(self):
            await asyncio.sleep(100)
            self.has_finished = True

    behav = Behav()
    behav.has_finished = False
    agent.add_behaviour(behaviour=behav)
    future = agent.start()
    future.result()

    assert not behav.has_finished

    container = Container()
    container.stop()

    assert not behav.has_finished
Exemplo n.º 15
0
def test_send_message_with_container():
    class FakeReceiverAgent:
        def __init__(self):
            self.jid = "fake_receiver_agent@server"

        def set_container(self, c):
            pass

    class SendBehaviour(OneShotBehaviour):
        async def run(self):
            message = Message(to="fake_receiver_agent@server")
            await self.send(message)
            self.kill()

    container = Container()
    container.reset()
    fake_receiver_agent = FakeReceiverAgent()
    container.register(fake_receiver_agent)

    fake_receiver_agent.dispatch = MagicMock()

    agent = make_connected_agent(use_container=True)
    agent.start(auto_register=False)

    agent.aiothread.client = MagicMock()
    agent.client.send = CoroutineMock()
    behaviour = SendBehaviour()
    agent.add_behaviour(behaviour)

    wait_for_behaviour_is_killed(behaviour)

    assert agent.client.send.await_count == 0

    assert fake_receiver_agent.dispatch.call_count == 1
    assert str(fake_receiver_agent.dispatch.call_args[0]
               [0].to) == "fake_receiver_agent@server"

    agent.stop()
Exemplo n.º 16
0
    def __init__(self,
                 jid,
                 password,
                 pubsub_server=None,
                 verify_security=False):
        """
        Creates an artifact

        Args:
          jid (str): The identifier of the artifact in the form username@server
          password (str): The password to connect to the server
          verify_security (bool): Wether to verify or not the SSL certificates
        """
        self.jid = aioxmpp.JID.fromstr(jid)
        self.password = password
        self.verify_security = verify_security

        self.pubsub_server = (pubsub_server if pubsub_server else
                              f"pubsub.{self.jid.domain}")

        self._values = {}

        self.conn_coro = None
        self.stream = None
        self.client = None
        self.message_dispatcher = None
        self.presence = None

        self.container = Container()
        self.container.register(self)
        self.loop = self.container.loop

        # self.loop = None #asyncio.new_event_loop()

        self.queue = asyncio.Queue(loop=self.loop)
        self._alive = Event()
Exemplo n.º 17
0
 async def run(self):
     container = Container()
     container.stop()
Exemplo n.º 18
0
def pytest_unconfigure(config):
    container = Container()
    container.stop()
Exemplo n.º 19
0
def run(game, map_path, verbose):
    """Run a JSON game file with the players definition."""

    set_verbosity(verbose)

    try:
        with open(game) as f:
            config = json.load(f)
    except json.decoder.JSONDecodeError:
        click.echo(
            "{} must be a valid JSON file. Run pygomas help run to see an example."
            .format(game))
        return -1

    default = {
        "host": "127.0.0.1",
        "manager": "cmanager",
        "service": "cservice",
        "axis": [],
        "allied": [],
    }
    for key in default.keys():
        if key not in config:
            config[key] = default[key]

    host = config["host"]
    manager_jid = "{}@{}".format(config["manager"], host)
    service_jid = "{}@{}".format(config["service"], host)

    troops = list()

    for troop in config["axis"]:
        new_troops = create_troops(troop,
                                   host,
                                   manager_jid,
                                   service_jid,
                                   map_path,
                                   team=TEAM_AXIS)
        troops += new_troops

    for troop in config["allied"]:
        new_troops = create_troops(troop,
                                   host,
                                   manager_jid,
                                   service_jid,
                                   map_path,
                                   team=TEAM_ALLIED)
        troops += new_troops

    container = Container()
    while not container.loop.is_running():
        time.sleep(0.1)

    futures = asyncio.run_coroutine_threadsafe(run_agents(troops),
                                               container.loop)
    futures.result()

    while any([agent.is_alive() for agent in troops]):
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            break
    click.echo("Stopping troops . . .")

    quit_spade()

    return 0