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): """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_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 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 test_missing_components(self): """Test log message for missing components.""" Path(self.skill_directory, "handlers.py").write_text("") Path(self.skill_directory, "behaviours.py").write_text("") Path(self.skill_directory, "dummy.py").write_text("") Skill.from_dir(self.skill_directory, self.agent_context) self.mocked_logger_warning.assert_any_call( "Handler 'DummyInternalHandler' cannot be found.") self.mocked_logger_warning.assert_any_call( "Behaviour 'DummyBehaviour' cannot be found.") self.mocked_logger_warning.assert_any_call( "Model 'DummyModel' cannot be found.")
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 setup(cls) -> None: """Set up the skill test case.""" identity = Identity("test_agent_name", "test_agent_address") cls._multiplexer = AsyncMultiplexer() cls._multiplexer._out_queue = ( # pylint: disable=protected-access asyncio.Queue() ) cls._outbox = OutBox(cast(Multiplexer, cls._multiplexer)) agent_context = AgentContext( identity=identity, connection_status=cls._multiplexer.connection_status, outbox=cls._outbox, decision_maker_message_queue=Queue(), decision_maker_handler_context=SimpleNamespace(), task_manager=TaskManager(), default_ledger_id=identity.default_address_key, currency_denominations=DEFAULT_CURRENCY_DENOMINATIONS, default_connection=None, default_routing={}, search_service_address="dummy_search_service_address", decision_maker_address="dummy_decision_maker_address", ) cls._skill = Skill.from_dir(str(cls.path_to_skill), agent_context)
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 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 populate_skills(self, directory: str, agent_context: AgentContext) -> None: """ Populate skills. :param directory: the agent's resources directory. :param agent_context: the agent's context object :return: None """ root_skill_directory = os.path.join(directory, "skills") if not os.path.exists(root_skill_directory): logger.warning("No skill found.") return skill_directories = [ str(x) for x in Path(root_skill_directory).iterdir() if x.is_dir() and re.match(PACKAGE_NAME_REGEX, x.name) ] logger.debug("Processing the following skill directories: {}".format( pprint.pformat(skill_directories))) for skill_directory in skill_directories: try: skill = Skill.from_dir(skill_directory, agent_context) assert skill is not None self.add_skill(skill) except Exception as e: logger.warning( "A problem occurred while parsing the skill directory {}. Exception: {}" .format(skill_directory, str(e)))
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 populate_skills( self, directory: str, agent_context: AgentContext, allowed_skills: Optional[Set[PublicId]] = None, ) -> None: """ Populate skills. :param directory: the agent's resources directory. :param agent_context: the agent's context object :param allowed_skills: an optional set of allowed skills (public ids). If None, every skill is allowed. :return: None """ skill_directory_paths = set() # type: ignore # find all skill directories from vendor/*/skills skill_directory_paths.update( Path(directory, "vendor").glob("./*/skills/*/")) # find all skill directories from skills/ skill_directory_paths.update(Path(directory, "skills").glob("./*/")) skills_packages_paths = list( filter( lambda x: PACKAGE_NAME_REGEX.match(str(x.name)) and x.is_dir(), skill_directory_paths, )) # type: ignore logger.debug("Found the following skill packages: {}".format( pprint.pformat(map(str, skills_packages_paths)))) for skill_directory in skills_packages_paths: logger.debug( "Processing the following skill directory: '{}".format( skill_directory)) try: skill_loader = ConfigLoader.from_configuration_type( ConfigurationType.SKILL) skill_config = skill_loader.load( open(skill_directory / DEFAULT_SKILL_CONFIG_FILE)) if (allowed_skills is not None and skill_config.public_id not in allowed_skills): logger.debug( "Ignoring skill {}, not declared in the configuration file." .format(skill_config.public_id)) continue else: skill = Skill.from_dir(str(skill_directory), agent_context) assert skill is not None self.add_skill(skill) except Exception as e: logger.warning( "A problem occurred while parsing the skill directory {}. Exception: {}" .format(skill_directory, str(e)))
def test_loading(): """Test that we correctly load AEA package modules.""" agent_context_mock = Mock() skill_directory = os.path.join(CUR_PATH, "data", "dummy_skill") prefixes = [ "packages", "packages.dummy_author", "packages.dummy_author.skills", "packages.dummy_author.skills.dummy", "packages.dummy_author.skills.dummy.dummy_subpackage", ] Skill.from_dir(skill_directory, agent_context_mock) assert all( prefix in sys.modules for prefix in prefixes), "Not all the subpackages are importable." # try to import a function from a skill submodule. from packages.dummy_author.skills.dummy.dummy_subpackage.foo import bar # type: ignore assert bar() == 42
def test_remove_skill(): """Test add/remove skill.""" builder = AEABuilder() builder.set_name("aea_1") builder.add_private_key("fetchai") skill = Skill.from_dir(dummy_skill_path, Mock(agent_name="name")) num_deps = len(builder._package_dependency_manager.all_dependencies) builder.add_component_instance(skill) assert len(builder._package_dependency_manager.all_dependencies) == num_deps + 1 builder.remove_skill(skill.public_id) assert len(builder._package_dependency_manager.all_dependencies) == num_deps
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 test_ids_non_empty(self): """Test ids, non-empty case.""" dummy_skill = Skill.from_dir( Path(CUR_PATH, "data", "dummy_skill"), agent_context=MagicMock(agent_name="name"), ) behaviour = next(iter(dummy_skill.behaviours.values())) skill_component_id = (dummy_skill.public_id, behaviour.name) self.registry.register(skill_component_id, behaviour) assert self.registry.ids() == {skill_component_id} self.registry.unregister(skill_component_id)
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 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", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) resources = Resources() identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) 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)
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.is_running, timeout=10) dummy_skill_id = DUMMY_SKILL_PUBLIC_ID 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 run(): # Create a private key create_private_key(CosmosCrypto.identifier) # Set up the wallet, identity and (empty) resources wallet = Wallet( private_key_paths={CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE}, connection_private_key_paths={CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE}, ) identity = Identity("my_aea", address=wallet.addresses.get(CosmosCrypto.identifier)) resources = Resources() # specify the default routing for some protocols default_routing = { PublicId.from_str("fetchai/ledger_api:0.1.0"): LedgerConnection.connection_id, PublicId.from_str("fetchai/oef_search:0.3.0"): SOEFConnection.connection_id, } default_connection = SOEFConnection.connection_id # create the AEA my_aea = AEA( identity, wallet, resources, default_connection=default_connection, default_routing=default_routing, ) # 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 signing protocol (which is part of the AEA distribution) signing_protocol = Protocol.from_dir(os.path.join(AEA_DIR, "protocols", "signing")) resources.add_protocol(signing_protocol) # Add the ledger_api protocol ledger_api_protocol = Protocol.from_dir( os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "ledger_api",) ) resources.add_protocol(ledger_api_protocol) # Add the oef_search protocol oef_protocol = Protocol.from_dir( os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "oef_search",) ) resources.add_protocol(oef_protocol) # Add the fipa protocol fipa_protocol = Protocol.from_dir( os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "fipa",) ) resources.add_protocol(fipa_protocol) # Add the LedgerAPI connection configuration = ConnectionConfig(connection_id=LedgerConnection.connection_id) ledger_api_connection = LedgerConnection( configuration=configuration, identity=identity ) resources.add_connection(ledger_api_connection) # Add the P2P connection configuration = ConnectionConfig( connection_id=P2PLibp2pConnection.connection_id, delegate_uri="127.0.0.1:11001", entry_peers=[ENTRY_PEER_ADDRESS], local_uri="127.0.0.1:9001", log_file="libp2p_node.log", public_uri="127.0.0.1:9001", ) p2p_connection = P2PLibp2pConnection( configuration=configuration, identity=identity, crypto_store=wallet.connection_cryptos, ) resources.add_connection(p2p_connection) # Add the SOEF connection configuration = ConnectionConfig( api_key=API_KEY, soef_addr=SOEF_ADDR, soef_port=SOEF_PORT, restricted_to_protocols={PublicId.from_str("fetchai/oef_search:0.3.0")}, connection_id=SOEFConnection.connection_id, delegate_uri="127.0.0.1:11001", entry_peers=[ENTRY_PEER_ADDRESS], local_uri="127.0.0.1:9001", log_file="libp2p_node.log", public_uri="127.0.0.1:9001", ) soef_connection = SOEFConnection(configuration=configuration, identity=identity) resources.add_connection(soef_connection) # Add the error and weather_client skills error_skill = Skill.from_dir( os.path.join(AEA_DIR, "skills", "error"), agent_context=my_aea.context ) weather_skill = Skill.from_dir( os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "weather_client"), agent_context=my_aea.context, ) strategy = cast(Strategy, weather_skill.models.get("strategy")) strategy._is_ledger_tx = False for skill in [error_skill, weather_skill]: resources.add_skill(skill) # Run the AEA try: logger.info("STARTING AEA NOW!") my_aea.start() except KeyboardInterrupt: logger.info("STOPPING AEA NOW!") my_aea.stop()
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_missing_task(self): """Test that when parsing a skill and a task is missing, we behave correctly.""" Path(self.t, "tasks.py").write_text("") Skill.from_dir(self.t, self.agent_context) self.mocked_logger_warning.assert_called_with("Task 'DummyTask' cannot be found.")
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()
def test_missing_shared_class(self): """Test that when parsing a skill and a shared_class is missing, we behave correctly.""" Path(self.t, "dummy.py").write_text("") Skill.from_dir(self.t, self.agent_context) self.mocked_logger_warning.assert_called_with("Shared class 'DummySharedClass' cannot be found.")
def run(): # Create a private key _create_fetchai_private_key() # Ensure the input and output files do not exist initially if os.path.isfile(INPUT_FILE): os.remove(INPUT_FILE) if os.path.isfile(OUTPUT_FILE): os.remove(OUTPUT_FILE) # Set up the Wallet, stub connection, ledger and (empty) resources wallet = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE}) stub_connection = StubConnection( input_file_path=INPUT_FILE, output_file_path=OUTPUT_FILE ) ledger_apis = LedgerApis({"fetchai": {"network": "testnet"}}, "fetchai") resources = Resources() # Create an identity identity = Identity( name="my_aea", address=wallet.addresses.get(FETCHAI), default_address_key=FETCHAI, ) # Create our AEA my_aea = AEA(identity, [stub_connection], wallet, ledger_apis, resources) # 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 error skill (from the local packages dir) and the echo skill (which is part of the AEA distribution) echo_skill = Skill.from_dir( os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "echo"), my_aea.context, ) resources.add_skill(echo_skill) error_skill = Skill.from_dir( os.path.join(AEA_DIR, "skills", "error"), my_aea.context ) resources.add_skill(error_skill) # Set the AEA running in a different thread try: t = Thread(target=my_aea.start) t.start() # Wait for everything to start up time.sleep(4) # Create a message inside an envelope and get the stub connection to pass it on to the echo skill message_text = ( "my_aea,other_agent,fetchai/default:0.1.0,\x08\x01*\x07\n\x05hello" ) with open(INPUT_FILE, "w") as f: f.write(message_text) print("input message: " + message_text) # Wait for the envelope to get processed time.sleep(4) # Read the output envelope generated by the echo skill with open(OUTPUT_FILE, "r") as f: print("output message: " + f.readline()) finally: # Shut down the AEA my_aea.stop() t.join() t = None
async def test_end_to_end_aea_aca(self): """Test the end to end aea aca interaction.""" # AEA components wallet = Wallet({DEFAULT_LEDGER: DEFAULT_PRIVATE_KEY_FILE}) identity = Identity( name="my_aea_1", address=wallet.addresses.get(DEFAULT_LEDGER), default_address_key=DEFAULT_LEDGER, ) configuration = ConnectionConfig( host=self.aca_admin_address, port=self.aca_admin_port, connection_id=HTTPClientConnection.connection_id, ) http_client_connection = HTTPClientConnection( configuration=configuration, identity=identity, ) resources = Resources() resources.add_connection(http_client_connection) # create AEA aea = AEA(identity, wallet, 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, HttpMessage.serializer()) 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="", body=b"", ) request_http_message.to = "ACA" request_envelope = Envelope( to="ACA", sender="AEA", protocol_id=HttpMessage.protocol_id, message=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"), agent_context=aea.context) 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 setup_class(cls): """Set the tests up.""" cls.skill = Skill.from_dir( Path(ROOT_DIR, "tests", "data", "dummy_skill"), MagicMock(agent_name="agent_name"), )
def test_load_skill(): """Test the loading of a skill.""" agent_context = MagicMock(agent_name="name") skill = Skill.from_dir(Path(ROOT_DIR, "tests", "data", "dummy_skill"), agent_context=agent_context) assert isinstance(skill, Skill)
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()