def test_act(): """Tests the act function of the AEA.""" with LocalNode() as node: agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) public_key = wallet.public_keys['default'] connections = [OEFLocalConnection(public_key, node)] agent = AEA( agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) behaviour = agent.resources.behaviour_registry.fetch("dummy") assert behaviour[0].nb_act_called > 0, "Act() wasn't called" finally: agent.stop() t.join()
def test_error_handler_is_not_set(): """Test stop on no error handler presents.""" agent_name = "my_agent" private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE) wallet = Wallet({DEFAULT_LEDGER: private_key_path}) identity = Identity(agent_name, address=wallet.addresses[DEFAULT_LEDGER]) resources = Resources() context_namespace = {"key1": 1, "key2": 2} agent = AEA(identity, wallet, resources, **context_namespace) msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.counterparty = agent.identity.address envelope = Envelope( to=agent.identity.address, sender=agent.identity.address, protocol_id=DefaultMessage.protocol_id, message=msg, ) with patch.object(agent, "stop") as mocked_stop: agent._handle(envelope) mocked_stop.assert_called()
def test_react(): """Tests income messages.""" node = LocalNode() agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") crypto = Crypto(private_key_pem_path=private_key_pem_path) public_key = crypto.public_key mailbox = MailBox(OEFLocalConnection(public_key, node)) msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") message_bytes = DefaultSerializer().encode(msg) envelope = Envelope(to="Agent1", sender=public_key, protocol_id="default", message=message_bytes) agent = AEA(agent_name, mailbox, private_key_pem_path=private_key_pem_path, directory=str(Path(CUR_PATH, "data", "dummy_aea"))) t = Thread(target=agent.start) try: t.start() agent.mailbox.inbox._queue.put(envelope) time.sleep(1) handler = agent.resources \ .handler_registry.fetch_by_skill('default', "dummy") assert envelope in handler.handled_envelopes, \ "The envelope is not inside the handled_envelopes." finally: agent.stop() t.join()
def setup(self): """Test the initialisation of the AEA.""" private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE) self.wallet = Wallet({DEFAULT_LEDGER: private_key_path}) self.agent_name = "Agent0" self.connection = _make_dummy_connection() self.identity = Identity(self.agent_name, address=self.wallet.addresses[DEFAULT_LEDGER]) self.address = self.identity.address self.my_aea = AEA( self.identity, self.wallet, timeout=0.1, resources=Resources(), default_connection=self.connection.public_id, ) self.my_aea.resources.add_connection(self.connection) self.my_aea._inbox = InboxWithHistory(self.my_aea.multiplexer) self.skill_context = SkillContext(self.my_aea._context) logger_name = "aea.{}.skills.{}.{}".format( self.my_aea._context.agent_name, "fetchai", "error") self.skill_context._logger = logging.getLogger(logger_name) self.my_error_handler = ErrorHandler(name="error", skill_context=self.skill_context) self.t = Thread(target=self.my_aea.start) self.t.start() wait_for_condition( lambda: self.my_aea._main_loop and self.my_aea._main_loop. is_running, 10)
def test_act(): """Tests the act function of the AEA.""" with LocalNode() as node: agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) ledger_apis = LedgerApis({}, FETCHAI) connections = [ OEFLocalConnection(identity.address, node, connection_id=LOCAL_CONNECTION_PUBLIC_ID) ] resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea"))) agent = AEA(identity, connections, wallet, ledger_apis, resources, is_programmatic=False) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) behaviour = agent.resources.behaviour_registry.fetch( (DUMMY_SKILL_PUBLIC_ID, "dummy")) assert behaviour.nb_act_called > 0, "Act() wasn't called" finally: agent.stop() t.join()
def test_react(): """Tests income messages.""" with LocalNode() as node: agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) ledger_apis = LedgerApis({}, FETCHAI) connection = OEFLocalConnection( identity.address, node, connection_id=LOCAL_CONNECTION_PUBLIC_ID) connections = [connection] resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea"))) msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.counterparty = identity.address message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=DefaultMessage.protocol_id, message=message_bytes, ) agent = AEA(identity, connections, wallet, ledger_apis, resources, is_programmatic=False) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) agent.outbox.put(envelope) time.sleep(2.0) default_protocol_public_id = DefaultMessage.protocol_id dummy_skill_public_id = DUMMY_SKILL_PUBLIC_ID handler = agent.resources.handler_registry.fetch_by_protocol_and_skill( default_protocol_public_id, dummy_skill_public_id) assert handler is not None, "Handler is not set." assert (msg in handler.handled_messages ), "The message is not inside the handled_messages." except Exception: raise finally: agent.stop() t.join()
def test_initialiseAeA(): """Tests the initialisation of the AeA.""" node = LocalNode() public_key_1 = "mailbox1" mailbox1 = MailBox(OEFLocalConnection(public_key_1, node)) myAea = AEA("Agent0", mailbox1, directory=str(Path(CUR_PATH, "aea"))) assert AEA("Agent0", mailbox1), "Agent is not inisialised" print(myAea.context) assert myAea.context == myAea._context, "Cannot access the Agent's Context" myAea.setup() assert myAea.resources is not None,\ "Resources must not be None after setup"
def _run_aea(aea: AEA) -> None: click.echo(AEA_LOGO + "v" + __version__ + "\n") click.echo("{} starting ...".format(aea.name)) try: aea.start() except KeyboardInterrupt: click.echo(" {} interrupted!".format(aea.name)) # pragma: no cover except Exception as e: logger.exception(e) sys.exit(1) finally: click.echo("{} stopping ...".format(aea.name)) aea.stop()
def test_handle(): """Tests handle method of an agent.""" node = LocalNode() agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") crypto = Crypto(private_key_pem_path=private_key_pem_path) public_key = crypto.public_key mailbox = MailBox(OEFLocalConnection(public_key, node)) msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") message_bytes = DefaultSerializer().encode(msg) envelope = Envelope(to="Agent1", sender=public_key, protocol_id="unknown_protocol", message=message_bytes) agent = AEA(agent_name, mailbox, private_key_pem_path=private_key_pem_path, directory=str(Path(CUR_PATH, "data", "dummy_aea"))) t = Thread(target=agent.start) try: t.start() agent.mailbox.inbox._queue.put(envelope) env = agent.mailbox.outbox._queue.get(block=True, timeout=5.0) assert env.protocol_id == "default", \ "The envelope is not the expected protocol (Unsupported protocol)" # DECODING ERROR msg = "hello".encode("utf-8") envelope = Envelope(to=public_key, sender=public_key, protocol_id='default', message=msg) agent.mailbox.inbox._queue.put(envelope) # UNSUPPORTED SKILL msg = FIPASerializer().encode( FIPAMessage(performative=FIPAMessage.Performative.ACCEPT, message_id=0, dialogue_id=0, destination=public_key, target=1)) envelope = Envelope(to=public_key, sender=public_key, protocol_id="fipa", message=msg) agent.mailbox.inbox._queue.put(envelope) finally: agent.stop() t.join()
def _run_aea(aea: AEA) -> None: click.echo(AEA_LOGO + "v" + __version__ + "\n") click.echo("Starting AEA '{}' in '{}' mode...".format( aea.name, aea.DEFAULT_RUN_LOOP)) try: aea.start() except KeyboardInterrupt: click.echo(" AEA '{}' interrupted!".format( aea.name)) # pragma: no cover except Exception as e: raise click.ClickException(str(e)) finally: click.echo("Stopping AEA '{}' ...".format(aea.name)) aea.stop() click.echo("AEA '{}' stopped.".format(aea.name))
def make_agent(agent_name="my_agent", runtime_mode="threaded") -> AEA: """Make AEA instance.""" wallet = Wallet({DEFAULT_LEDGER: None}) identity = Identity(agent_name, address=agent_name) resources = Resources() agent_context = MagicMock() agent_context.agent_name = agent_name agent_context.agent_address = agent_name resources.add_skill( Skill.from_dir( str( PACKAGES_DIR / FETCHAI / SKILLS / PublicId.from_str(DEFAULT_SKILL).name ), agent_context=agent_context, ) ) resources.add_protocol( Protocol.from_dir( str( PACKAGES_DIR / FETCHAI / PROTOCOLS / PublicId.from_str(DEFAULT_PROTOCOL).name ) ) ) return AEA(identity, wallet, resources, runtime_mode=runtime_mode)
def setup_class(cls): """Test the initialisation of the AEA.""" cls.node = LocalNode() private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") cls.wallet = Wallet({FETCHAI: private_key_path}) cls.ledger_apis = LedgerApis({}, FETCHAI) cls.agent_name = "Agent0" cls.connection = _make_dummy_connection() cls.connections = [cls.connection] cls.identity = Identity(cls.agent_name, address=cls.wallet.addresses[FETCHAI]) cls.address = cls.identity.address cls.my_aea = AEA( cls.identity, cls.connections, cls.wallet, cls.ledger_apis, timeout=2.0, resources=Resources(str(Path(CUR_PATH, "data/dummy_aea"))), is_programmatic=False, ) cls.skill_context = SkillContext(cls.my_aea._context) logger_name = "aea.{}.skills.{}.{}".format( cls.my_aea._context.agent_name, "fetchai", "error" ) cls.skill_context._logger = logging.getLogger(logger_name) cls.my_error_handler = ErrorHandler( name="error", skill_context=cls.skill_context ) cls.t = Thread(target=cls.my_aea.start) cls.t.start() time.sleep(0.5)
def setup_class(cls): """Set the tests up.""" cls._patch_logger() cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() cls.skill_directory = Path(cls.t, "dummy_skill") shutil.copytree(Path(CUR_PATH, "data", "dummy_skill"), cls.skill_directory) os.chdir(cls.t) private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") cls.wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) cls.connections = [ DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID) ] cls.identity = Identity("name", address=cls.wallet.addresses[FETCHAI]) cls.my_aea = AEA( cls.identity, cls.connections, cls.wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))), is_programmatic=False, ) cls.agent_context = cls.my_aea.context
def setup_class(cls): """Set the tests up.""" cls._patch_logger() # create temp agent folder cls.oldcwd = os.getcwd() cls.agent_name = "agent_test" + str(random.randint(0, 1000)) cls.t = tempfile.mkdtemp() cls.agent_folder = os.path.join(cls.t, cls.agent_name) shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"), cls.agent_folder) os.chdir(cls.agent_folder) # make fake skill cls.fake_skill_id = "fake" agent_config_path = Path(cls.agent_folder, DEFAULT_AEA_CONFIG_FILE) agent_config = yaml.safe_load(agent_config_path.read_text()) agent_config.get("skills").append(cls.fake_skill_id) yaml.safe_dump(agent_config, open(agent_config_path, "w")) Path(cls.agent_folder, "skills", cls.fake_skill_id).mkdir() connections = [DummyConnection()] private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) cls.resources = Resources(os.path.join(cls.agent_folder)) cls.aea = AEA(cls.agent_name, connections, wallet, ledger_apis, resources=cls.resources) cls.resources.load(cls.aea.context) cls.expected_skills = {"dummy", "error"}
def setup_class(cls): """Set the test up.""" agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) resources = Resources() resources.add_component( Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"))) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) cls.input_file = tempfile.mkstemp()[1] cls.output_file = tempfile.mkstemp()[1] cls.agent = AEA( identity, [_make_local_connection(identity.address, LocalNode())], wallet, ledger_apis, resources, ) for skill in resources.get_all_skills(): skill.skill_context.set_agent_context(cls.agent.context) cls.t = Thread(target=cls.agent.start) cls.t.start() time.sleep(1.0)
def setup_class(cls): """Test the initialisation of the AEA.""" eth_private_key_path = os.path.join(CUR_PATH, "data", "eth_private_key.txt") fet_private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") cls.wallet = Wallet({ ETHEREUM: eth_private_key_path, FETCHAI: fet_private_key_path }) cls.ledger_apis = LedgerApis({FETCHAI: { "network": "testnet" }}, FETCHAI) cls.connections = [ DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID) ] cls.identity = Identity("name", addresses=cls.wallet.addresses, default_address_key=FETCHAI) cls.my_aea = AEA( cls.identity, cls.connections, cls.wallet, cls.ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))), is_programmatic=False, ) cls.skill_context = SkillContext(cls.my_aea.context)
def setup_class(cls): """Set the tests up.""" # create temp agent folder cls.oldcwd = os.getcwd() cls.agent_name = "agent_test" + str(random.randint(0, 1000)) # nosec cls.t = tempfile.mkdtemp() cls.agent_folder = os.path.join(cls.t, cls.agent_name) shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"), cls.agent_folder) os.chdir(cls.agent_folder) connection = _make_dummy_connection() private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE) wallet = Wallet({DEFAULT_LEDGER: private_key_path}) identity = Identity(cls.agent_name, address=wallet.addresses[DEFAULT_LEDGER]) resources = Resources() resources.add_component( Skill.from_dir( Path(CUR_PATH, "data", "dummy_skill"), agent_context=MagicMock(), ) ) resources.add_connection(connection) cls.aea = AEA(identity, wallet, resources=resources,) cls.aea.setup()
def build(self, connection_ids: Optional[Collection[PublicId]] = None) -> AEA: """ Build the AEA. :param connection_ids: select only these connections to run the AEA. :return: the AEA object. """ wallet = Wallet(self.private_key_paths) identity = self._build_identity_from_wallet(wallet) self._load_and_add_protocols() self._load_and_add_contracts() connections = self._load_connections(identity.address, connection_ids) aea = AEA( identity, connections, wallet, LedgerApis(self.ledger_apis_config, self._default_ledger), self._resources, loop=None, timeout=0.0, is_debug=False, is_programmatic=True, max_reactions=20, ) self._load_and_add_skills(aea.context) return aea
def setup_class(cls): """Set the test up.""" cls.node = LocalNode() cls.node.start() cls.agent_name = "MyAgent" cls.private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") cls.wallet = Wallet({'default': cls.private_key_pem_path}) cls.ledger_apis = LedgerApis({}) cls.connection = OEFLocalConnection(cls.agent_name, cls.node) cls.connections = [cls.connection] cls.temp = tempfile.mkdtemp(prefix="test_aea_resources") cls.resources = Resources(cls.temp) cls.aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, resources=cls.resources) cls.default_protocol_configuration = ProtocolConfig.from_json( yaml.safe_load(open(Path(AEA_DIR, "protocols", "default", "protocol.yaml")))) cls.default_protocol = Protocol("default", DefaultSerializer(), cls.default_protocol_configuration) cls.resources.protocol_registry.register(("default", None), cls.default_protocol) cls.error_skill = Skill.from_dir(Path(AEA_DIR, "skills", "error"), cls.aea.context) cls.dummy_skill = Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"), cls.aea.context) cls.resources.add_skill(cls.dummy_skill) cls.resources.add_skill(cls.error_skill) cls.expected_message = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") cls.t = Thread(target=cls.aea.start) cls.t.start() time.sleep(0.5) cls.aea.outbox.put(Envelope(to=cls.agent_name, sender=cls.agent_name, protocol_id="default", message=DefaultSerializer().encode(cls.expected_message)))
def setup_class(cls): """Set the tests up.""" # create temp agent folder cls.oldcwd = os.getcwd() cls.agent_name = "agent_test" + str(random.randint(0, 1000)) # nosec cls.t = tempfile.mkdtemp() cls.agent_folder = os.path.join(cls.t, cls.agent_name) shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"), cls.agent_folder) os.chdir(cls.agent_folder) connections = [_make_dummy_connection()] private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) identity = Identity(cls.agent_name, address=wallet.addresses[FETCHAI]) resources = Resources(cls.agent_folder) resources.add_component( Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"))) cls.aea = AEA( identity, connections, wallet, ledger_apis, resources=resources, is_programmatic=False, ) cls.aea.setup()
def setup_class(cls): """Set the test up.""" cls.node = LocalNode() cls.node.start() cls.agent_name = "MyAgent" cls.private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") cls.wallet = Wallet({FETCHAI: cls.private_key_path}) cls.ledger_apis = LedgerApis({}, FETCHAI) cls.identity = Identity(cls.agent_name, address=cls.wallet.addresses[FETCHAI]) cls.connection = _make_local_connection(cls.agent_name, cls.node) cls.connections = [cls.connection] cls.temp = tempfile.mkdtemp(prefix="test_aea_resources") cls.resources = Resources(cls.temp) cls.default_protocol = Protocol.from_dir( str(Path(AEA_DIR, "protocols", "default"))) cls.resources.add_protocol(cls.default_protocol) cls.error_skill = Skill.from_dir(str(Path(AEA_DIR, "skills", "error"))) cls.dummy_skill = Skill.from_dir( str(Path(CUR_PATH, "data", "dummy_skill"))) cls.resources.add_skill(cls.dummy_skill) cls.resources.add_skill(cls.error_skill) cls.aea = AEA( cls.identity, cls.connections, cls.wallet, cls.ledger_apis, resources=cls.resources, ) cls.error_skill.skill_context.set_agent_context(cls.aea.context) cls.dummy_skill.skill_context.set_agent_context(cls.aea.context) default_protocol_id = DefaultMessage.protocol_id cls.expected_message = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) cls.expected_message.counterparty = cls.agent_name cls.t = Thread(target=cls.aea.start) cls.t.start() time.sleep(0.5) cls.aea.outbox.put( Envelope( to=cls.agent_name, sender=cls.agent_name, protocol_id=default_protocol_id, message=DefaultSerializer().encode(cls.expected_message), ))
def setup_class(cls): """Test the initialisation of the AEA.""" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") cls.wallet = Wallet({'default': private_key_pem_path}) cls.ledger_apis = LedgerApis({"fetchai": ("alpha.fetch-ai.com", 80)}) cls.connections = [DummyConnection()] cls.my_aea = AEA("Agent0", cls.connections, cls.wallet, cls.ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) cls.skill_context = SkillContext(cls.my_aea.context)
def test_initialise_AEA(): """Tests the initialisation of the AEA.""" node = LocalNode() public_key_1 = "public_key" connections1 = [OEFLocalConnection(public_key_1, node)] private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) my_AEA = AEA("Agent0", connections1, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "aea")))) assert my_AEA.context == my_AEA._context, "Cannot access the Agent's Context" assert not my_AEA.context.connection_status.is_connected, "AEA should not be connected." my_AEA.setup() assert my_AEA.resources is not None,\ "Resources must not be None after setup" my_AEA.resources = Resources(str(Path(CUR_PATH, "aea"))) assert my_AEA.resources is not None,\ "Resources must not be None after set"
def test_initialise_aea(): """Tests the initialisation of the AEA.""" node = LocalNode() private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) identity = Identity("my_name", address=wallet.addresses[FETCHAI]) connections1 = [ OEFLocalConnection(identity.address, node, connection_id=OEFLocalConnection.connection_id) ] ledger_apis = LedgerApis({}, FETCHAI) my_AEA = AEA( identity, connections1, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "aea"))), ) assert my_AEA.context == my_AEA._context, "Cannot access the Agent's Context" assert (not my_AEA.context.connection_status.is_connected ), "AEA should not be connected." my_AEA.setup() assert my_AEA.resources is not None, "Resources must not be None after setup" my_AEA.resources = Resources(str(Path(CUR_PATH, "aea"))) assert my_AEA.resources is not None, "Resources must not be None after set" assert (my_AEA.context.shared_state is not None), "Shared state must not be None after set" assert my_AEA.context.task_manager is not None assert my_AEA.context.identity is not None, "Identity must not be None after set." my_AEA.stop()
def build(self, connection_ids: Optional[Collection[PublicId]] = None,) -> AEA: """ Build the AEA. This method is re-entrant only if the components have been added through the method 'add_component'. If some of them have been loaded with 'add_component_instance', it can be called only once, and further calls are only possible after a call to 'reset' and re-loading of the components added via 'add_component_instance' and the private keys. :param connection_ids: select only these connections to run the AEA. :return: the AEA object. :raises ValueError: if we cannot """ self._check_we_can_build() resources = Resources() wallet = Wallet( copy(self.private_key_paths), copy(self.connection_private_key_paths) ) identity = self._build_identity_from_wallet(wallet) self._load_and_add_components(ComponentType.PROTOCOL, resources, identity.name) self._load_and_add_components(ComponentType.CONTRACT, resources, identity.name) self._load_and_add_components( ComponentType.CONNECTION, resources, identity.name, identity=identity, crypto_store=wallet.connection_cryptos, ) connection_ids = self._process_connection_ids(connection_ids) aea = AEA( identity, wallet, resources, loop=None, timeout=self._get_agent_loop_timeout(), execution_timeout=self._get_execution_timeout(), is_debug=False, max_reactions=self._get_max_reactions(), decision_maker_handler_class=self._get_decision_maker_handler_class(), skill_exception_policy=self._get_skill_exception_policy(), default_routing=self._get_default_routing(), default_connection=self._get_default_connection(), loop_mode=self._get_loop_mode(), runtime_mode=self._get_runtime_mode(), connection_ids=connection_ids, search_service_address=self._get_search_service_address(), **deepcopy(self._context_namespace), ) self._load_and_add_components( ComponentType.SKILL, resources, identity.name, agent_context=aea.context ) self._build_called = True self._populate_contract_registry() return aea
def setup_class(cls): """Set the tests up.""" cls._patch_logger() # create temp agent folder cls.oldcwd = os.getcwd() cls.agent_name = "agent_test" + str(random.randint(0, 1000)) # nosec cls.t = tempfile.mkdtemp() cls.agent_folder = os.path.join(cls.t, cls.agent_name) shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"), cls.agent_folder) os.chdir(cls.agent_folder) cls.error_skill_public_id = PublicId("fetchai", "error", "0.1.0") cls.dummy_skill_public_id = PublicId.from_str( "dummy_author/dummy:0.1.0") # # make fake skill cls.fake_skill_id = PublicId.from_str("fake_author/fake:0.1.0") agent_config_path = Path(cls.agent_folder, DEFAULT_AEA_CONFIG_FILE) agent_config = yaml.safe_load(agent_config_path.read_text()) agent_config.get("skills").append(str(cls.fake_skill_id)) yaml.safe_dump(agent_config, open(agent_config_path, "w")) Path(cls.agent_folder, "skills", cls.fake_skill_id.name).mkdir() connections = [ DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID) ] private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) cls.resources = Resources(os.path.join(cls.agent_folder)) identity = Identity(cls.agent_name, address=wallet.addresses[FETCHAI]) cls.aea = AEA( identity, connections, wallet, ledger_apis, resources=cls.resources, is_programmatic=False, ) cls.resources.load(cls.aea.context) cls.expected_skills = { PublicId("fetchai", "dummy", "0.1.0"), PublicId("fetchai", "error", "0.1.0"), } cls.expected_protocols = { PublicId("fetchai", "default", "0.1.0"), PublicId("fetchai", "oef", "0.1.0"), }
def test_agent_context_ledger_apis(): """Test that the ledger apis configurations are loaded correctly.""" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) connections = [DummyConnection()] ledger_apis = LedgerApis({"fetchai": ('alpha.fetch-ai.com', 80)}) my_aea = AEA("Agent0", connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) assert set(my_aea.context.ledger_apis.apis.keys()) == {"fetchai"} fetchai_ledger_api_obj = my_aea.context.ledger_apis.apis["fetchai"] assert fetchai_ledger_api_obj.tokens.host == 'alpha.fetch-ai.com' assert fetchai_ledger_api_obj.tokens.port == 80
def test_react(): """Tests income messages.""" with LocalNode() as node: agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) public_key = wallet.public_keys['default'] connection = OEFLocalConnection(public_key, node) connections = [connection] msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=public_key, sender=public_key, protocol_id="default", message=message_bytes) agent = AEA( agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) t = Thread(target=agent.start) try: t.start() time.sleep(0.1) agent.outbox.put(envelope) time.sleep(0.5) handler = agent.resources.handler_registry.fetch_by_skill('default', "dummy") assert msg in handler.handled_messages, "The message is not inside the handled_messages." except Exception: raise finally: agent.stop() t.join()
def _build_aea(ctx: Context, connection_ids: List[PublicId]) -> AEA: """ Build the aea. :param ctx: the context :param connection_ids: the list of connection ids """ agent_name = cast(str, ctx.agent_config.agent_name) wallet = Wallet(ctx.agent_config.private_key_paths_dict) if len(wallet.addresses) > 1: identity = Identity( agent_name, addresses=wallet.addresses, default_address_key=ctx.agent_config.default_ledger, ) else: # pragma: no cover identity = Identity( agent_name, address=wallet.addresses[ctx.agent_config.default_ledger], ) ledger_apis = LedgerApis(ctx.agent_config.ledger_apis_dict, ctx.agent_config.default_ledger) default_connection_id = PublicId.from_str( ctx.agent_config.default_connection) connection_ids = ([default_connection_id] if connection_ids is None else connection_ids) connections = [] try: for connection_id in connection_ids: connection = _setup_connection(connection_id, identity.address, ctx) connections.append(connection) except AEAConfigException as e: logger.error(str(e)) sys.exit(1) resources = Resources(AEA_DIR) aea = AEA( identity, connections, wallet, ledger_apis, resources, is_programmatic=False, ) return aea
def test_act(): """Tests the act function of the AeA.""" node = LocalNode() agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") crypto = Crypto(private_key_pem_path=private_key_pem_path) public_key = crypto.public_key mailbox = MailBox(OEFLocalConnection(public_key, node)) agent = AEA(agent_name, mailbox, private_key_pem_path=private_key_pem_path, directory=str(Path(CUR_PATH, "data", "dummy_aea"))) t = Thread(target=agent.start) try: t.start() time.sleep(1) behaviour = agent.resources.behaviour_registry.fetch("dummy") assert behaviour[0].nb_act_called > 0, "Act() wasn't called" finally: agent.stop() t.join()