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.""" # 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 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 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 inject_contracts(self, skill: Skill) -> None: if skill.config.contracts is not None: # check all contracts are present contracts = {} # type: Dict[str, Contract] for contract_id in skill.config.contracts: contract = self._contract_registry.fetch(contract_id) if contract is None: raise ValueError( "Missing contract for contract id {}".format(contract_id) ) contracts[contract_id.name] = contract skill.inject_contracts(contracts)
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 test_handle_internal_message_new_handlers_with_error(self): """Test handle internal message when an error happens while registering a new handler.""" skill = Skill( SkillConfig("name", "author", "0.1.0"), handlers={}, behaviours={}, models={}, ) self.resources.add_skill(skill) new_handler = DummyHandler(name="dummy2", skill_context=skill.skill_context) with unittest.mock.patch.object(self.resources.handler_registry, "register", side_effect=ValueError): with unittest.mock.patch.object(aea.registries.filter.logger, "warning") as mock_logger_warning: skill.skill_context.new_handlers.put(new_handler) self.filter.handle_internal_messages() mock_logger_warning.assert_called_with( "Error when trying to add a new handler: ") assert self.decision_make_queue.empty() assert len(self.resources.handler_registry.fetch_all()) == 0 # restore previous state self.resources.component_registry.unregister(skill.component_id)
def test_storage_access_from_behaviour(): """Test storage access from behaviour component.""" builder = AEABuilder() builder.set_name("aea_1") builder.add_private_key(DEFAULT_LEDGER) skill_context = SkillContext() behaviour = TBehaviour(name="behaviour", skill_context=skill_context) test_skill = Skill( SkillConfig(name="test_skill", author="fetchai"), skill_context=skill_context, handlers={}, behaviours={"behaviour": behaviour}, ) builder.add_component_instance(test_skill) builder.set_storage_uri("sqlite://:memory:") aea = builder.build() skill_context.set_agent_context(aea.context) aea.runtime._threaded = True aea.runtime.start() try: wait_for_condition(lambda: aea.is_running, timeout=10) wait_for_condition(lambda: behaviour.counter > 0, timeout=10) col = skill_context.storage.get_sync_collection(behaviour.COL_NAME) assert col.get(behaviour.OBJ_ID) == behaviour.OBJ_BODY finally: aea.runtime.stop() aea.runtime.wait_completed(sync=True, timeout=10)
def make_skill( cls, config: SkillConfig = None, context: SkillContext = None, handlers: Optional[Dict[str, Type[Handler]]] = None, ) -> Skill: """ Make a skill from optional config, context, handlers dict. :param config: SkillConfig :param context: SkillContext :param handlers: dict of handler types to add to skill :return: Skill """ handlers = handlers or {} context = context or SkillContext() config = config or SkillConfig( name="skill_{}".format(uuid.uuid4().hex[0:5]), author="fetchai") handlers_instances = { name: handler_cls(name=name, skill_context=context) for name, handler_cls in handlers.items() } skill = Skill(configuration=config, skill_context=context, handlers=handlers_instances) return skill
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_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(self) -> None: """Set test cae instance.""" agent_name = "MyAgent" builder = AEABuilder() builder.set_name(agent_name) builder.add_private_key(DEFAULT_LEDGER, COSMOS_PRIVATE_KEY_PATH) self.handler_called = 0 def handler_func(*args, **kwargs): self.handler_called += 1 skill_context = SkillContext() handler_cls = make_handler_cls_from_funcion(handler_func) behaviour_cls = make_behaviour_cls_from_funcion(handler_func) self.handler = handler_cls(name="handler1", skill_context=skill_context) self.behaviour = behaviour_cls(name="behaviour1", skill_context=skill_context) test_skill = Skill( SkillConfig(name="test_skill", author="fetchai"), skill_context=skill_context, handlers={"handler": self.handler}, behaviours={"behaviour": self.behaviour}, ) skill_context._skill = test_skill # weird hack builder.add_component_instance(test_skill) self.aea = builder.build() self.aea_tool = AeaTool(self.aea)
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 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 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 inject_contracts(self, skill: Skill) -> None: """ Inject contracts into a skill context. :param skill: a skill :return: None """ if skill.config.contracts is not None: # check all contracts are present contracts = {} # type: Dict[str, Contract] for contract_id in skill.config.contracts: contract = self._component_registry.fetch( ComponentId(ComponentType.CONTRACT, contract_id)) if contract is None: raise ValueError( "Missing contract for contract id {}".format( contract_id)) contracts[contract_id.name] = cast(Contract, contract) skill.inject_contracts(contracts)
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 make_skill(agent, handlers=None, behaviours=None) -> Skill: """Construct skill instance for agent from behaviours.""" handlers = handlers or {} behaviours = behaviours or {} config = SkillConfig(name="test_skill", author="fetchai") skill_context = SkillContext(agent.context) skill = Skill(configuration=config, skill_context=skill_context) for name, handler_cls in handlers.items(): handler = handler_cls(name=name, skill_context=skill_context) skill.handlers.update({handler.name: handler}) for name, behaviour_cls in behaviours.items(): behaviour = behaviour_cls(name=name, skill_context=skill_context) skill.behaviours.update({behaviour.name: behaviour}) return skill
def setup(cls, **kwargs: Any) -> 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)) _shared_state = cast(Dict[str, Any], kwargs.pop("shared_state", dict())) _skill_config_overrides = cast( Dict[str, Any], kwargs.pop("config_overrides", dict()) ) 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", data_dir=os.getcwd(), ) # This enables pre-populating the 'shared_state' prior to loading the skill if _shared_state != dict(): for key, value in _shared_state.items(): agent_context.shared_state[key] = value skill_configuration_file_path: Path = Path(cls.path_to_skill, "skill.yaml") loader = ConfigLoaders.from_package_type(PackageType.SKILL) with open_file(skill_configuration_file_path) as fp: skill_config: SkillConfig = loader.load(fp) # This enables overriding the skill's config prior to loading if _skill_config_overrides != {}: skill_config.update(_skill_config_overrides) skill_config.directory = cls.path_to_skill cls._skill = Skill.from_config(skill_config, agent_context)
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 test_storage_access_from_handler(): """Test storage access from handler component.""" builder = AEABuilder() builder.set_name("aea_1") builder.add_private_key(DEFAULT_LEDGER) skill_context = SkillContext() handler = THandler(name="behaviour", skill_context=skill_context) test_skill = Skill( SkillConfig(name="test_skill", author="fetchai"), skill_context=skill_context, handlers={"handler": handler}, behaviours={}, ) builder.add_component_instance(test_skill) builder.set_storage_uri("sqlite://:memory:") aea = builder.build() skill_context.set_agent_context(aea.context) aea.runtime._threaded = True aea.runtime.start() msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.to = aea.identity.address msg.sender = aea.identity.address envelope = Envelope(to=msg.to, sender=msg.sender, message=msg,) try: wait_for_condition(lambda: aea.is_running, timeout=10) aea.runtime.multiplexer.in_queue.put(envelope) wait_for_condition(lambda: handler.counter > 0, timeout=10) col = skill_context.storage.get_sync_collection(handler.COL_NAME) assert col.get(handler.OBJ_ID) == handler.OBJ_BODY finally: aea.runtime.stop() aea.runtime.wait_completed(sync=True, timeout=10)
def _load_and_add_skills(self, context: AgentContext) -> None: for configuration in self._package_dependency_manager.skills.values(): logger_name = "aea.packages.{}.skills.{}".format( configuration.author, configuration.name ) skill_context = SkillContext() skill_context.set_agent_context(context) skill_context.logger = logging.getLogger(logger_name) configuration = cast(SkillConfig, configuration) try: skill = Skill.from_config(configuration, skill_context=skill_context) except Exception as e: raise Exception( "An error occurred while loading skill {}: {}".format( configuration.public_id, str(e) ) ) self._add_component_to_resources(skill)
def test_handle_internal_message_new_behaviours(self): """Test handle internal message when there are new behaviours to register.""" skill = Skill( SkillConfig("name", "author", "0.1.0"), handlers={}, behaviours={}, models={}, ) self.resources.add_skill(skill) new_behaviour = DummyBehaviour(name="dummy2", skill_context=skill.skill_context) skill.skill_context.new_behaviours.put(new_behaviour) self.filter.handle_internal_messages() assert self.decision_make_queue.empty() assert len(self.resources.behaviour_registry.fetch_all()) == 1 # restore previous state self.resources.remove_skill(skill.public_id) assert len(self.resources.behaviour_registry.fetch_all()) == 0
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 prepare(self, function: Callable) -> None: """Prepare aea_tool for testing. :param function: function be called on react handle or/and Behaviour.act :return: None """ agent_name = "MyAgent" builder = AEABuilder() builder.set_name(agent_name) builder.add_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_PATH) self.function_finished = False def handler_func(*args, **kwargs): function() self.function_finished = True skill_context = SkillContext() handler_cls = make_handler_cls_from_funcion(handler_func) behaviour_cls = make_behaviour_cls_from_funcion(handler_func) test_skill = Skill( SkillConfig(name="test_skill", author="fetchai"), skill_context=skill_context, handlers={ "handler1": handler_cls(name="handler1", skill_context=skill_context) }, behaviours={ "behaviour1": behaviour_cls(name="behaviour1", skill_context=skill_context) }, ) skill_context._skill = test_skill # weird hack builder._add_component_to_resources(test_skill) aea = builder.build() self.aea_tool = AeaTool(aea) self.aea_tool.put_inbox(AeaTool.dummy_envelope())