def test_logger_positive(self): """Test logger property positive result""" obj = SkillContext("agent_context") with self.assertRaises(AssertionError): obj.logger obj._logger = mock.Mock() obj.logger
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 test_skill_id_positive(self): """Test skill_id property positive result""" obj = SkillContext("agent_context") obj._skill = mock.Mock() obj._skill.config = mock.Mock() obj._skill.config.public_id = "public_id" obj.skill_id
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 test_handlers_positive(self, *mocks): """Test handlers property positive result""" obj = SkillContext("agent_context") with self.assertRaises(ValueError): obj.handlers obj._skill = mock.Mock() obj._skill.handlers = {} obj.handlers
def test_behaviours_positive(self, *mocks): """Test behaviours property positive result""" obj = SkillContext("agent_context") with self.assertRaises(AssertionError): obj.behaviours obj._skill = mock.Mock() obj._skill.behaviours = {} obj.behaviours
def test_task_manager_positive(self): """Test task_manager property positive result""" agent_context = mock.Mock() agent_context.task_manager = "task_manager" obj = SkillContext(agent_context) with self.assertRaises(AssertionError): obj.task_manager obj._skill = mock.Mock() obj.task_manager
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): """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(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 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): """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_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 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())
def test_kwargs_not_empty(self): """Test the case when there are some kwargs not-empty""" kwargs = dict(foo="bar") component_name = "component_name" skill_context = SkillContext() with mock.patch.object(skill_context.logger, "warning") as mock_logger: self.TestComponent(component_name, skill_context, **kwargs) mock_logger.assert_any_call( f"The kwargs={kwargs} passed to {component_name} have not been set!" )
def _builder(self, agent_name="agent1", act_func=None) -> AEABuilder: """Build an aea instance.""" builder = AEABuilder() builder.set_name(agent_name) builder.add_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_PATH) skill_context = SkillContext() act_func = act_func or (lambda self: self) behaviour_cls = make_behaviour_cls_from_funcion(act_func) behaviour = behaviour_cls(name="behaviour", skill_context=skill_context) test_skill = Skill( SkillConfig(name="test_skill", author="fetchai"), skill_context=skill_context, behaviours={"behaviour": behaviour}, ) skill_context._skill = test_skill # weird hack builder.add_component_instance(test_skill) builder.set_runtime_mode("async") return builder
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(DEFAULT_LEDGER, 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) self.behaviour = behaviour_cls(name="behaviour1", skill_context=skill_context) 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": self.behaviour}, ) skill_context._skill = test_skill # weird hack builder.add_component_instance(test_skill) aea = builder.build() self.aea_tool = AeaTool(aea) self.envelope = AeaTool.dummy_envelope() self.aea_tool.aea.runtime.main_loop._setup()
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_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_print_warning_message_for_non_declared_skill_components(): """Test the helper function '_print_warning_message_for_non_declared_skill_components'.""" with unittest.mock.patch.object(aea.skills.base._default_logger, "warning") as mock_logger_warning: _print_warning_message_for_non_declared_skill_components( SkillContext(), {"unknown_class_1", "unknown_class_2"}, set(), "type", "path", ) mock_logger_warning.assert_any_call( "Class unknown_class_1 of type type found but not declared in the configuration file path." ) mock_logger_warning.assert_any_call( "Class unknown_class_2 of type type found but not declared in the configuration file path." )
def test_model_parse_module_missing_class(): """Test Model.parse_module when a class is missing.""" skill_context = SkillContext(skill=MagicMock( skill_id=PublicId.from_str("author/name:0.1.0"))) dummy_models_path = Path(ROOT_DIR, "tests", "data", "dummy_skill") with unittest.mock.patch.object(aea.skills.base._default_logger, "warning") as mock_logger_warning: models_by_id = Model.parse_module( dummy_models_path, { "dummy_model": SkillComponentConfiguration("DummyModel"), "unknown_model": SkillComponentConfiguration("UnknownModel"), }, skill_context, ) mock_logger_warning.assert_called_with( "Model 'UnknownModel' cannot be found.") assert "dummy_model" in models_by_id
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 setup_class(cls): """Set the tests up.""" skill_context = SkillContext() skill_config = SkillConfig(name="simple_skill", author="fetchai", version="0.1.0") class MyHandler(Handler): def setup(self): pass def handle(self, message: Message): pass def teardown(self): pass class MyBehaviour(Behaviour): def setup(self): pass def act(self): pass def teardown(self): pass cls.handler_name = "some_handler" cls.handler = MyHandler(skill_context=skill_context, name=cls.handler_name) cls.model_name = "some_model" cls.model = Model(skill_context=skill_context, name=cls.model_name) cls.behaviour_name = "some_behaviour" cls.behaviour = MyBehaviour(skill_context=skill_context, name=cls.behaviour_name) cls.skill = Skill( skill_config, skill_context, handlers={cls.handler.name: cls.handler}, models={cls.model.name: cls.model}, behaviours={cls.behaviour.name: cls.behaviour}, )
def test_handler_parse_module_missing_class(): """Test Handler.parse_module when a class is missing.""" skill_context = SkillContext(skill=MagicMock( skill_id=PublicId.from_str("author/name:0.1.0"))) dummy_handlers_path = Path(ROOT_DIR, "tests", "data", "dummy_skill", "handlers.py") with unittest.mock.patch.object(aea.skills.base._default_logger, "warning") as mock_logger_warning: behaviours_by_id = Handler.parse_module( dummy_handlers_path, { "dummy_handler": SkillComponentConfiguration("DummyHandler"), "unknown_handelr": SkillComponentConfiguration("UnknownHandler"), }, skill_context, ) mock_logger_warning.assert_called_with( "Handler 'UnknownHandler' cannot be found.") assert "dummy_handler" in behaviours_by_id
def setup_class(cls): """Test the initialisation of the AEA.""" cls.node = LocalNode() private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") cls.wallet = Wallet({'default': private_key_pem_path}) cls.ledger_apis = LedgerApis({}) cls.agent_name = "Agent0" cls.public_key = cls.wallet.public_keys['default'] cls.connection = DummyConnection() cls.connections = [cls.connection] cls.my_aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, timeout=2.0, resources=Resources( str(Path(CUR_PATH, "data/dummy_aea")))) cls.t = Thread(target=cls.my_aea.start) cls.t.start() time.sleep(0.5) cls.skill_context = SkillContext(cls.my_aea._context) cls.my_error_handler = ErrorHandler(skill_context=cls.skill_context)
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 run(): # Create a private key create_private_key(CosmosCrypto.identifier, private_key_file=COSMOS_PRIVATE_KEY_FILE_1) # Instantiate the builder and build the AEA # By default, the default protocol, error skill and stub connection are added builder = AEABuilder() builder.set_name("my_aea") builder.add_private_key(CosmosCrypto.identifier, COSMOS_PRIVATE_KEY_FILE_1) # Create our AEA my_aea = builder.build() # add a simple skill with handler skill_context = SkillContext(my_aea.context) skill_config = SkillConfig(name="simple_skill", author="fetchai", version="0.1.0") signing_handler = SigningHandler(skill_context=skill_context, name="signing_handler") signing_dialogues_model = SigningDialogues(skill_context=skill_context, name="signing_dialogues") simple_skill = Skill( skill_config, skill_context, handlers={signing_handler.name: signing_handler}, models={signing_dialogues_model.name: signing_dialogues_model}, ) my_aea.resources.add_skill(simple_skill) # create a second identity create_private_key(CosmosCrypto.identifier, private_key_file=COSMOS_PRIVATE_KEY_FILE_2) counterparty_wallet = Wallet( {CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE_2}) counterparty_identity = Identity( name="counterparty_aea", addresses=counterparty_wallet.addresses, default_address_key=CosmosCrypto.identifier, ) # create signing message for decision maker to sign terms = Terms( ledger_id=CosmosCrypto.identifier, sender_address=my_aea.identity.address, counterparty_address=counterparty_identity.address, amount_by_currency_id={"FET": -1}, quantities_by_good_id={"some_service": 1}, nonce="some_nonce", fee_by_currency_id={"FET": 0}, ) signing_dialogues = cast(SigningDialogues, skill_context.signing_dialogues) stub_transaction = LedgerApis.get_transfer_transaction( terms.ledger_id, terms.sender_address, terms.counterparty_address, terms.sender_payable_amount, terms.sender_fee, terms.nonce, ) signing_msg = SigningMessage( performative=SigningMessage.Performative.SIGN_TRANSACTION, dialogue_reference=signing_dialogues. new_self_initiated_dialogue_reference(), skill_callback_ids=(str(skill_context.skill_id), ), raw_transaction=RawTransaction(CosmosCrypto.identifier, stub_transaction), terms=terms, skill_callback_info={"some_info_key": "some_info_value"}, ) signing_msg.counterparty = "decision_maker" signing_dialogue = cast(Optional[SigningDialogue], signing_dialogues.update(signing_msg)) assert signing_dialogue is not None my_aea.context.decision_maker_message_queue.put_nowait(signing_msg) # 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 decision maker time.sleep(1) finally: # Shut down the AEA logger.info("STOPPING AEA NOW!") my_aea.stop() t.join()
def test_is_active_positive(self, skill_id_mock, debug_mock): """Test is_active setter positive result""" obj = SkillContext("agent_context") obj.is_active = "value" debug_mock.assert_called_once()
def test_shared_state_positive(self): """Test shared_state property positive result""" agent_context = mock.Mock() agent_context.shared_state = "shared_state" obj = SkillContext(agent_context) obj.shared_state