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.""" 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(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.data_dir = MagicMock() self.connection = _make_dummy_connection() self.identity = Identity(self.agent_name, address=self.wallet.addresses[DEFAULT_LEDGER]) self.address = self.identity.address resources = Resources() resources.add_connection(self.connection) self.my_aea = AEA( self.identity, self.wallet, resources=resources, data_dir=self.data_dir, period=0.1, default_connection=self.connection.public_id, ) self.my_aea._inbox = InboxWithHistory(self.my_aea.runtime.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.runtime and self.my_aea.runtime.is_running, 10)
def setup_class(cls): """Set the tests up.""" # cls._patch_logger() # noqa: E800 # 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.resources = Resources() cls.resources.add_component( Protocol.from_dir( Path(ROOT_DIR, "packages", "fetchai", "protocols", "default"))) cls.resources.add_component( Skill.from_dir( Path(CUR_PATH, "data", "dummy_skill"), agent_context=MagicMock(agent_name="name"), )) cls.resources.add_component( Skill.from_dir( Path(ROOT_DIR, "packages", "fetchai", "skills", "error"), agent_context=MagicMock(agent_name="name"), )) cls.error_skill_public_id = ERROR_SKILL_PUBLIC_ID cls.dummy_skill_public_id = PublicId.from_str( "dummy_author/dummy:0.1.0") cls.contract_public_id = ERC1155_PUBLIC_ID
def setup(self): """Test the initialisation of the AEA.""" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") self.wallet = Wallet({FetchAICrypto.identifier: private_key_path}) self.agent_name = "Agent0" self.connection = _make_dummy_connection() self.identity = Identity( self.agent_name, address=self.wallet.addresses[FetchAICrypto.identifier]) 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 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() # 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.resources = Resources() cls.resources.add_component( Protocol.from_dir(Path(aea.AEA_DIR, "protocols", "default")) ) # cls.resources.add_component(Component.load_from_directory(ComponentType.PROTOCOL, Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"))) cls.resources.add_component( Skill.from_dir( Path(CUR_PATH, "data", "dummy_skill"), agent_context=MagicMock(), ) ) cls.resources.add_component( Skill.from_dir( Path(aea.AEA_DIR, "skills", "error"), agent_context=MagicMock(), ) ) cls.error_skill_public_id = DEFAULT_SKILL cls.dummy_skill_public_id = PublicId.from_str("dummy_author/dummy:0.1.0") cls.contract_public_id = PublicId.from_str("fetchai/erc1155:0.6.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 = [_make_dummy_connection()] 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 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 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): """Set the test up.""" agent_name = "my_agent" 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.context_namespace = {"key1": 1, "key2": 2} cls.agent = AEA( identity, [_make_local_connection(identity.address, LocalNode())], wallet, ledger_apis, resources, **cls.context_namespace) for skill in resources.get_all_skills(): skill.skill_context.set_agent_context(cls.agent.context)
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 __init__(self, with_default_packages: bool = True): """ Initialize the builder. :param with_default_packages: add the default packages. """ self._name = None # type: Optional[str] self._resources = Resources() self._private_key_paths = {} # type: Dict[str, str] self._ledger_apis_configs = {} # type: Dict[str, Dict[str, Union[str, int]]] self._default_key = None # set by the user, or instantiate a default one. self._default_ledger = ( "fetchai" # set by the user, or instantiate a default one. ) self._default_connection = PublicId("fetchai", "stub", "0.1.0") self._package_dependency_manager = _DependenciesManager() if with_default_packages: self._add_default_packages()
def test_load_abstract_component(): """Test abstract component loading.""" builder = AEABuilder() builder.set_name("aea_1") builder.add_private_key("fetchai") skill = Skill.from_dir(dummy_skill_path, Mock(agent_name="name")) skill.configuration.is_abstract = True builder.add_component_instance(skill) builder._load_and_add_components( ComponentType.SKILL, Resources(), "aea_1", agent_context=Mock(agent_name="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): """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 __init__(self, handlers=None, behaviours=None): """Init agent.""" self.handlers = handlers or [] self.behaviours = behaviours or [] self._runtime = MagicMock() self.runtime.decision_maker.message_out_queue = AsyncFriendlyQueue() self._inbox = AsyncFriendlyQueue() self._filter = Filter(Resources(), self.runtime.decision_maker.message_out_queue) self._logger = logging.getLogger("fake agent") self._period = 0.001 self.filter.handle_internal_message = MagicMock() self.filter.handle_new_handlers_and_behaviours = MagicMock()
def test_add_behaviour_dynamically(): """Test that we can add a behaviour dynamically.""" 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]) 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(agent.context) with run_in_thread(agent.start, timeout=5, on_exit=agent.stop): wait_for_condition( lambda: agent._main_loop and agent._main_loop.is_running, timeout=10) dummy_skill_id = PublicId("dummy_author", "dummy", "0.1.0") dummy_skill = agent.resources.get_skill(dummy_skill_id) wait_for_condition(lambda: dummy_skill is not None, timeout=10) new_behaviour = DummyBehaviour(name="dummy2", skill_context=dummy_skill.skill_context) dummy_skill.skill_context.new_behaviours.put(new_behaviour) wait_for_condition(lambda: new_behaviour.nb_act_called > 0, timeout=10) wait_for_condition( lambda: len(agent.resources.get_behaviours(dummy_skill_id)) == 2, timeout=10)
def _load_and_add_components( self, component_type: ComponentType, resources: Resources, agent_name: str, **kwargs, ) -> None: """ Load and add components added to the builder to a Resources instance. :param component_type: the component type for which :param resources: the resources object to populate. :param agent_name: the AEA name for logging purposes. :param kwargs: keyword argument to forward to the component loader. :return: None """ for configuration in self._package_dependency_manager.get_components_by_type( component_type ).values(): if configuration.is_abstract_component: load_aea_package(configuration) continue if configuration in self._component_instances[component_type].keys(): component = self._component_instances[component_type][configuration] if configuration.component_type != ComponentType.SKILL: component.logger = cast( logging.Logger, make_logger(configuration, agent_name) ) else: configuration = deepcopy(configuration) _logger = make_logger(configuration, agent_name) component = load_component_from_config( configuration, logger=_logger, **kwargs ) resources.add_component(component)
def setup_class(cls, decision_maker_handler_class=None): """Test the initialisation of the AEA.""" cls.wallet = Wallet({ FETCHAI: FETCHAI_PRIVATE_KEY_PATH, ETHEREUM: ETHEREUM_PRIVATE_KEY_PATH }) cls.connection = _make_dummy_connection() resources = Resources() resources.add_connection(cls.connection) cls.identity = Identity( "name", addresses=cls.wallet.addresses, default_address_key=FETCHAI, ) cls.my_aea = AEA( cls.identity, cls.wallet, data_dir=MagicMock(), resources=resources, decision_maker_handler_class=decision_maker_handler_class, ) cls.skill_context = SkillContext(cls.my_aea.context, skill=MagicMock(contracts={}))
def setup_class(cls): """Test the initialisation of the AEA.""" cls.wallet = Wallet({ COSMOS: COSMOS_PRIVATE_KEY_PATH, ETHEREUM: ETHEREUM_PRIVATE_KEY_PATH }) cls.connection = _make_dummy_connection() cls.identity = Identity( "name", addresses=cls.wallet.addresses, default_address_key=COSMOS, ) cls.my_aea = AEA(cls.identity, cls.wallet, resources=Resources()) cls.my_aea.resources.add_connection(cls.connection) cls.skill_context = SkillContext(cls.my_aea.context)
def test_agent_context_ledger_apis(): """Test that the ledger apis configurations are loaded correctly.""" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) connections = [_make_dummy_connection()] ledger_apis = LedgerApis({"fetchai": {"network": "testnet"}}, FETCHAI) identity = Identity("name", address=wallet.addresses[FETCHAI]) my_aea = AEA( identity, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))), is_programmatic=False, ) assert set(my_aea.context.ledger_apis.apis.keys()) == {"fetchai"}
def test_initialise_aea(): """Tests the initialisation of the AEA.""" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") builder = AEABuilder() builder.set_name("my_name").add_private_key(FETCHAI, private_key_path) my_AEA = builder.build() 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 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( { EthereumCrypto.identifier: eth_private_key_path, FetchAICrypto.identifier: fet_private_key_path, } ) cls.connection = _make_dummy_connection() cls.identity = Identity( "name", addresses=cls.wallet.addresses, default_address_key=FetchAICrypto.identifier, ) cls.my_aea = AEA(cls.identity, cls.wallet, resources=Resources(),) cls.my_aea.resources.add_connection(cls.connection) cls.skill_context = SkillContext(cls.my_aea.context)
def test_setup_aea(): """Tests the initialisation of the AEA.""" private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE) builder = AEABuilder() builder.set_name("my_name").add_private_key(DEFAULT_LEDGER, private_key_path) my_AEA = builder.build() 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() 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.teardown()
def setup_class(cls): """Set the test up.""" 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]) connection = _make_local_connection(identity.address, LocalNode()) resources = Resources() cls.context_namespace = {"key1": 1, "key2": 2} cls.agent = AEA(identity, wallet, resources, **cls.context_namespace) resources.add_connection(connection) resources.add_component( Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"), agent_context=cls.agent.context)) for skill in resources.get_all_skills(): skill.skill_context.set_agent_context(cls.agent.context)
def test_add_behaviour_dynamically(): """Test that we can add a behaviour dynamically.""" agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE) wallet = Wallet({DEFAULT_LEDGER: private_key_path}) resources = Resources() identity = Identity(agent_name, address=wallet.addresses[DEFAULT_LEDGER]) connection = _make_local_connection(identity.address, LocalNode()) agent = AEA( identity, wallet, resources, default_connection=connection.public_id, ) resources.add_connection(connection) resources.add_component( Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"), agent_context=agent.context)) for skill in resources.get_all_skills(): skill.skill_context.set_agent_context(agent.context) with run_in_thread(agent.start, timeout=5, on_exit=agent.stop): wait_for_condition( lambda: agent._main_loop and agent._main_loop.is_running, timeout=10) dummy_skill_id = PublicId("dummy_author", "dummy", "0.1.0") dummy_skill = agent.resources.get_skill(dummy_skill_id) wait_for_condition(lambda: dummy_skill is not None, timeout=10) new_behaviour = DummyBehaviour(name="dummy2", skill_context=dummy_skill.skill_context) dummy_skill.skill_context.new_behaviours.put(new_behaviour) wait_for_condition(lambda: new_behaviour.nb_act_called > 0, timeout=10) wait_for_condition( lambda: len(agent.resources.get_behaviours(dummy_skill_id)) == 2, timeout=10)
async def test_end_to_end_aea_aca(self): # AEA components ledger_apis = LedgerApis({}, FetchAICrypto.identifier) wallet = Wallet({FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE}) identity = Identity( name="my_aea_1", address=wallet.addresses.get(FetchAICrypto.identifier), default_address_key=FetchAICrypto.identifier, ) http_client_connection = HTTPClientConnection( address=self.aea_address, provider_address=self.aca_admin_address, provider_port=self.aca_admin_port, ) resources = Resources() # create AEA aea = AEA(identity, [http_client_connection], wallet, ledger_apis, resources) # Add http protocol to AEA resources http_protocol_configuration = ProtocolConfig.from_json( yaml.safe_load( open( os.path.join( self.cwd, "packages", "fetchai", "protocols", "http", "protocol.yaml", )))) http_protocol = Protocol(http_protocol_configuration, HttpSerializer()) resources.add_protocol(http_protocol) # Request message & envelope request_http_message = HttpMessage( dialogue_reference=("", ""), target=0, message_id=1, performative=HttpMessage.Performative.REQUEST, method="GET", url="http://{}:{}/status".format(self.aca_admin_address, self.aca_admin_port), headers="", version="", bodyy=b"", ) request_envelope = Envelope( to="ACA", sender="AEA", protocol_id=HTTP_PROTOCOL_PUBLIC_ID, message=HttpSerializer().encode(request_http_message), ) # add a simple skill with handler skill_context = SkillContext(aea.context) skill_config = SkillConfig(name="simple_skill", author="fetchai", version="0.1.0") aea_handler = AEAHandler(skill_context=skill_context, name="aea_handler") simple_skill = Skill(skill_config, skill_context, handlers={aea_handler.name: aea_handler}) resources.add_skill(simple_skill) # add error skill to AEA error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error")) resources.add_skill(error_skill) # start AEA thread t_aea = Thread(target=aea.start) try: t_aea.start() time.sleep(1.0) aea.outbox.put(request_envelope) time.sleep(5.0) assert (aea_handler.handled_message.performative == HttpMessage.Performative.RESPONSE) assert aea_handler.handled_message.version == "" assert aea_handler.handled_message.status_code == 200 assert aea_handler.handled_message.status_text == "OK" assert aea_handler.handled_message.headers is not None assert aea_handler.handled_message.version is not None finally: aea.stop() t_aea.join()
def test_initialize_aea_programmatically_build_resources(): """Test that we can initialize the agent by building the resource object.""" try: temp = tempfile.mkdtemp(prefix="test_aea_resources") with LocalNode() as node: agent_name = "MyAgent" 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]) connection = _make_local_connection(agent_name, node) resources = Resources() aea = AEA( identity, wallet, resources=resources, default_connection=connection.public_id, ) default_protocol = Protocol.from_dir( str(Path(AEA_DIR, "protocols", "default"))) resources.add_protocol(default_protocol) resources.add_connection(connection) error_skill = Skill.from_dir(str(Path(AEA_DIR, "skills", "error")), agent_context=aea.context) dummy_skill = Skill.from_dir(str( Path(CUR_PATH, "data", "dummy_skill")), agent_context=aea.context) resources.add_skill(dummy_skill) resources.add_skill(error_skill) default_protocol_id = DefaultMessage.protocol_id expected_message = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) expected_message.counterparty = agent_name expected_message.sender = agent_name with run_in_thread(aea.start, timeout=5, on_exit=aea.stop): wait_for_condition(lambda: aea.is_running, timeout=10) aea.outbox.put( Envelope( to=agent_name, sender=agent_name, protocol_id=default_protocol_id, message=expected_message, )) dummy_skill_id = DUMMY_SKILL_PUBLIC_ID dummy_behaviour_name = "dummy" dummy_behaviour = aea.resources.get_behaviour( dummy_skill_id, dummy_behaviour_name) wait_for_condition(lambda: dummy_behaviour is not None, timeout=10) wait_for_condition(lambda: dummy_behaviour.nb_act_called > 0, timeout=10) dummy_task = DummyTask() task_id = aea.task_manager.enqueue_task(dummy_task) async_result = aea.task_manager.get_task_result(task_id) expected_dummy_task = async_result.get(10.0) wait_for_condition( lambda: expected_dummy_task.nb_execute_called > 0, timeout=10) dummy_handler_name = "dummy" dummy_handler = aea.resources._handler_registry.fetch( (dummy_skill_id, dummy_handler_name)) dummy_handler_alt = aea.resources.get_handler( DefaultMessage.protocol_id, dummy_skill_id) wait_for_condition(lambda: dummy_handler == dummy_handler_alt, timeout=10) wait_for_condition(lambda: dummy_handler is not None, timeout=10) wait_for_condition( lambda: len(dummy_handler.handled_messages) == 1, timeout=10) wait_for_condition( lambda: dummy_handler.handled_messages[0] == expected_message, timeout=10, ) finally: Path(temp).rmdir()
def run(): # Create a private key _create_fetchai_private_key() # Set up the wallet, identity, oef connection, ledger and (empty) resources wallet = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE}) identity = Identity("my_aea", address=wallet.addresses.get(FETCHAI)) oef_connection = OEFConnection(address=identity.address, oef_addr=HOST, oef_port=PORT) ledger_apis = LedgerApis({}, FETCHAI) resources = Resources() # create the AEA my_aea = AEA( identity, [oef_connection], wallet, ledger_apis, resources, # stub_connection, ) # Add the default protocol (which is part of the AEA distribution) default_protocol = Protocol.from_dir( os.path.join(AEA_DIR, "protocols", "default")) resources.add_protocol(default_protocol) # Add the oef protocol (which is a package) oef_protocol = Protocol.from_dir( os.path.join( os.getcwd(), "packages", "fetchai", "protocols", "oef_search", )) resources.add_protocol(oef_protocol) # Add the fipa protocol (which is a package) fipa_protocol = Protocol.from_dir( os.path.join( os.getcwd(), "packages", "fetchai", "protocols", "fipa", )) resources.add_protocol(fipa_protocol) # Add the error and weather_station skills error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"), my_aea.context) weather_skill = Skill.from_dir( os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "weather_client"), my_aea.context, ) strategy = cast(Strategy, weather_skill.models.get("strategy")) strategy.is_ledger_tx = False strategy.max_buyer_tx_fee = 100 strategy.max_row_price = 40 for skill in [error_skill, weather_skill]: resources.add_skill(skill) # Set the AEA running in a different thread try: logger.info("STARTING AEA NOW!") t = Thread(target=my_aea.start) t.start() # Let it run long enough to interact with the weather station time.sleep(25) finally: # Shut down the AEA logger.info("STOPPING AEA NOW!") my_aea.stop() t.join()