def test_initialise_aea(): """Tests the initialisation of the AEA.""" node = LocalNode() private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) identity = Identity("my_name", address=wallet.addresses[FETCHAI]) connections1 = [ OEFLocalConnection(identity.address, node, connection_id=OEFLocalConnection.connection_id) ] ledger_apis = LedgerApis({}, FETCHAI) my_AEA = AEA( identity, connections1, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "aea"))), ) assert my_AEA.context == my_AEA._context, "Cannot access the Agent's Context" assert (not my_AEA.context.connection_status.is_connected ), "AEA should not be connected." my_AEA.setup() assert my_AEA.resources is not None, "Resources must not be None after setup" my_AEA.resources = Resources(str(Path(CUR_PATH, "aea"))) assert my_AEA.resources is not None, "Resources must not be None after set" assert (my_AEA.context.shared_state is not None), "Shared state must not be None after set" assert my_AEA.context.task_manager is not None assert my_AEA.context.identity is not None, "Identity must not be None after set." my_AEA.stop()
def 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 test_act(): """Tests the act function of the AEA.""" with LocalNode() as node: agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) public_key = wallet.public_keys['default'] connections = [OEFLocalConnection(public_key, node)] agent = AEA( agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) behaviour = agent.resources.behaviour_registry.fetch("dummy") assert behaviour[0].nb_act_called > 0, "Act() wasn't called" finally: agent.stop() t.join()
def test_act(): """Tests the act function of the AEA.""" with LocalNode() as node: agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) ledger_apis = LedgerApis({}, FETCHAI) connections = [ OEFLocalConnection(identity.address, node, connection_id=LOCAL_CONNECTION_PUBLIC_ID) ] resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea"))) agent = AEA(identity, connections, wallet, ledger_apis, resources, is_programmatic=False) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) behaviour = agent.resources.behaviour_registry.fetch( (DUMMY_SKILL_PUBLIC_ID, "dummy")) assert behaviour.nb_act_called > 0, "Act() wasn't called" finally: agent.stop() t.join()
def 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 = [ DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID) ] private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) identity = Identity(cls.agent_name, address=wallet.addresses[FETCHAI]) cls.aea = AEA( identity, connections, wallet, ledger_apis, resources=Resources(cls.agent_folder), is_programmatic=False, ) cls.aea.setup()
def setup_class(cls): """Set the tests up.""" cls._patch_logger() # create temp agent folder cls.oldcwd = os.getcwd() cls.agent_name = "agent_test" + str(random.randint(0, 1000)) cls.t = tempfile.mkdtemp() cls.agent_folder = os.path.join(cls.t, cls.agent_name) shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"), cls.agent_folder) os.chdir(cls.agent_folder) # make fake skill cls.fake_skill_id = "fake" agent_config_path = Path(cls.agent_folder, DEFAULT_AEA_CONFIG_FILE) agent_config = yaml.safe_load(agent_config_path.read_text()) agent_config.get("skills").append(cls.fake_skill_id) yaml.safe_dump(agent_config, open(agent_config_path, "w")) Path(cls.agent_folder, "skills", cls.fake_skill_id).mkdir() connections = [DummyConnection()] private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) cls.resources = Resources(os.path.join(cls.agent_folder)) cls.aea = AEA(cls.agent_name, connections, wallet, ledger_apis, resources=cls.resources) cls.resources.load(cls.aea.context) cls.expected_skills = {"dummy", "error"}
def setup_class(cls): """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 = DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID) 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) 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 test_initialise_AEA(): """Tests the initialisation of the AEA.""" node = LocalNode() public_key_1 = "public_key" connections1 = [OEFLocalConnection(public_key_1, node)] private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) my_AEA = AEA("Agent0", connections1, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "aea")))) assert my_AEA.context == my_AEA._context, "Cannot access the Agent's Context" assert not my_AEA.context.connection_status.is_connected, "AEA should not be connected." my_AEA.setup() assert my_AEA.resources is not None,\ "Resources must not be None after setup" my_AEA.resources = Resources(str(Path(CUR_PATH, "aea"))) assert my_AEA.resources is not None,\ "Resources must not be None after set"
def setup(self) -> None: """ Set up the agent. :return: None """ self._resources = Resources.from_resource_dir(self._directory, self.context) assert self._resources is not None, "No resources initialized. Error in setup." self._resources.setup()
def test_react(): """Tests income messages.""" with LocalNode() as node: agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) ledger_apis = LedgerApis({}, FETCHAI) connection = OEFLocalConnection( identity.address, node, connection_id=LOCAL_CONNECTION_PUBLIC_ID) connections = [connection] resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea"))) msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.counterparty = identity.address message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=DefaultMessage.protocol_id, message=message_bytes, ) agent = AEA(identity, connections, wallet, ledger_apis, resources, is_programmatic=False) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) agent.outbox.put(envelope) time.sleep(2.0) default_protocol_public_id = DefaultMessage.protocol_id dummy_skill_public_id = DUMMY_SKILL_PUBLIC_ID handler = agent.resources.handler_registry.fetch_by_protocol_and_skill( default_protocol_public_id, dummy_skill_public_id) assert handler is not None, "Handler is not set." assert (msg in handler.handled_messages ), "The message is not inside the handled_messages." except Exception: raise finally: agent.stop() t.join()
def run(click_context, connection_names: List[str], env_file: str, install_deps: bool): """Run the agent.""" ctx = cast(Context, click_context.obj) _try_to_load_agent_config(ctx) _load_env_file(env_file) agent_name = cast(str, ctx.agent_config.agent_name) _verify_or_create_private_keys(ctx) _verify_ledger_apis_access() private_key_paths = dict([(identifier, config.path) for identifier, config in ctx.agent_config.private_key_paths.read_all()]) ledger_api_configs = dict([ (identifier, (config.addr, config.port)) for identifier, config in ctx.agent_config.ledger_apis.read_all() ]) wallet = Wallet(private_key_paths) ledger_apis = LedgerApis(ledger_api_configs) connection_names = [ctx.agent_config.default_connection ] if connection_names is None else connection_names connections = [] _try_to_load_protocols(ctx) try: for connection_name in connection_names: connection = _setup_connection(connection_name, wallet.public_keys[FETCHAI], ctx) connections.append(connection) except AEAConfigException as e: logger.error(str(e)) sys.exit(1) if install_deps: if Path("requirements.txt").exists(): click_context.invoke(install, requirement="requirements.txt") else: click_context.invoke(install) agent = AEA(agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(".")))) try: agent.start() except KeyboardInterrupt: logger.info("Interrupted.") # pragma: no cover except Exception as e: logger.exception(e) sys.exit(1) finally: agent.stop()
def setup_class(cls): """Set the tests up.""" cls._patch_logger() # create temp agent folder cls.oldcwd = os.getcwd() cls.agent_name = "agent_test" + str(random.randint(0, 1000)) # nosec cls.t = tempfile.mkdtemp() cls.agent_folder = os.path.join(cls.t, cls.agent_name) shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"), cls.agent_folder) os.chdir(cls.agent_folder) cls.error_skill_public_id = PublicId("fetchai", "error", "0.1.0") cls.dummy_skill_public_id = PublicId.from_str( "dummy_author/dummy:0.1.0") # # make fake skill cls.fake_skill_id = PublicId.from_str("fake_author/fake:0.1.0") agent_config_path = Path(cls.agent_folder, DEFAULT_AEA_CONFIG_FILE) agent_config = yaml.safe_load(agent_config_path.read_text()) agent_config.get("skills").append(str(cls.fake_skill_id)) yaml.safe_dump(agent_config, open(agent_config_path, "w")) Path(cls.agent_folder, "skills", cls.fake_skill_id.name).mkdir() connections = [ DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID) ] private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) cls.resources = Resources(os.path.join(cls.agent_folder)) identity = Identity(cls.agent_name, address=wallet.addresses[FETCHAI]) cls.aea = AEA( identity, connections, wallet, ledger_apis, resources=cls.resources, is_programmatic=False, ) cls.resources.load(cls.aea.context) cls.expected_skills = { PublicId("fetchai", "dummy", "0.1.0"), PublicId("fetchai", "error", "0.1.0"), } cls.expected_protocols = { PublicId("fetchai", "default", "0.1.0"), PublicId("fetchai", "oef", "0.1.0"), }
def _build_aea(ctx: Context, connection_ids: List[PublicId]) -> AEA: """ Build the aea. :param ctx: the context :param connection_ids: the list of connection ids """ agent_name = cast(str, ctx.agent_config.agent_name) wallet = Wallet(ctx.agent_config.private_key_paths_dict) if len(wallet.addresses) > 1: identity = Identity( agent_name, addresses=wallet.addresses, default_address_key=ctx.agent_config.default_ledger, ) else: # pragma: no cover identity = Identity( agent_name, address=wallet.addresses[ctx.agent_config.default_ledger], ) ledger_apis = LedgerApis(ctx.agent_config.ledger_apis_dict, ctx.agent_config.default_ledger) default_connection_id = PublicId.from_str( ctx.agent_config.default_connection) connection_ids = ([default_connection_id] if connection_ids is None else connection_ids) connections = [] try: for connection_id in connection_ids: connection = _setup_connection(connection_id, identity.address, ctx) connections.append(connection) except AEAConfigException as e: logger.error(str(e)) sys.exit(1) resources = Resources(AEA_DIR) aea = AEA( identity, connections, wallet, ledger_apis, resources, is_programmatic=False, ) return aea
def 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 = OEFLocalConnection( cls.agent_name, cls.node, connection_id=LOCAL_CONNECTION_PUBLIC_ID, ) cls.connections = [cls.connection] cls.resources = Resources(os.path.join(CUR_PATH, "data", "dummy_aea")) cls.aea = AEA( cls.identity, cls.connections, cls.wallet, cls.ledger_apis, cls.resources, is_programmatic=False, ) 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 envelope = Envelope( to=cls.agent_name, sender=cls.agent_name, protocol_id=DefaultMessage.protocol_id, message=DefaultSerializer().encode(cls.expected_message), ) cls.t = Thread(target=cls.aea.start) cls.t.start() time.sleep(0.5) cls.aea.outbox.put(envelope) time.sleep(0.5)
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)) 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 = [DummyConnection()] private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) cls.aea = AEA(cls.agent_name, connections, wallet, ledger_apis, resources=Resources(cls.agent_folder))
def setup(self) -> None: """ Set up the agent. :return: None """ self._resources = Resources.from_resource_dir(self._directory, None) assert self._resources is not None, "No resources initialized. Error in setup." self._resources.setup() self.w3 = Web3(Web3.HTTPProvider( "https://nile.dev-ocean.com")) #"http://localhost:7545")) with open( 'keystore/UTC--2019-10-19T15-13-02.082157851Z--719b682d53f15899376709fb372c98aa5a116799' ) as keyfile: encrypted_key = keyfile.read() self.private_key = self.w3.eth.account.decrypt( encrypted_key, 'submarine') master_contract_address = '0x7d5158372BC13D1bA316b44B9002821BE46652F5' master_contract_address = Web3.toChecksumAddress( master_contract_address) self.account = self.w3.eth.account.privateKeyToAccount( self.private_key) self.w3.eth.defaultAccount = self.account.address self.eventBehaviour = self.resources.behaviour_registry.fetch_all()[0] self.resultTask = self.resources.task_registry.fetch_all()[0] #my_address = '0x719b682d53f15899376709fb372c98aa5a116799' with open("abi.json") as f: abi = json.load(f) self.contract = self.w3.eth.contract(address=master_contract_address, abi=abi) self.address = master_contract_address print("master contract", self.contract)
def test_react(): """Tests income messages.""" with LocalNode() as node: agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) public_key = wallet.public_keys['default'] connection = OEFLocalConnection(public_key, node) connections = [connection] msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=public_key, sender=public_key, protocol_id="default", message=message_bytes) agent = AEA( agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) t = Thread(target=agent.start) try: t.start() time.sleep(0.1) agent.outbox.put(envelope) time.sleep(0.5) handler = agent.resources.handler_registry.fetch_by_skill('default', "dummy") assert msg in handler.handled_messages, "The message is not inside the handled_messages." except Exception: raise finally: agent.stop() t.join()
def 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(str(Path(CUR_PATH, "data", "dummy_aea"))) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) cls.input_file = tempfile.mkstemp()[1] cls.output_file = tempfile.mkstemp()[1] cls.agent = AEA( identity, [StubConnection(cls.input_file, cls.output_file)], wallet, ledger_apis, resources, is_programmatic=False, ) cls.t = Thread(target=cls.agent.start) cls.t.start() time.sleep(1.0)
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.resources = Resources(os.path.join(CUR_PATH, "data", "dummy_aea")) cls.aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, cls.resources) cls.expected_message = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") envelope = Envelope(to=cls.agent_name, sender=cls.agent_name, protocol_id="default", message=DefaultSerializer().encode(cls.expected_message)) cls.t = Thread(target=cls.aea.start) cls.t.start() time.sleep(0.5) cls.aea.outbox.put(envelope) time.sleep(0.5)
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 test_generated_protocol_end_to_end(self): """Test that a generated protocol could be used in exchanging messages between two agents.""" # AEA components ledger_apis = LedgerApis({}, FETCHAI) wallet_1 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE}) wallet_2 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE}) identity_1 = Identity( name="my_aea_1", address=wallet_1.addresses.get(FETCHAI), default_address_key=FETCHAI, ) identity_2 = Identity( name="my_aea_2", address=wallet_2.addresses.get(FETCHAI), default_address_key=FETCHAI, ) oef_connection_1 = OEFConnection( address=identity_1.address, oef_addr=HOST, oef_port=PORT ) oef_connection_2 = OEFConnection( address=identity_2.address, oef_addr=HOST, oef_port=PORT ) resources_1 = Resources() resources_2 = Resources() # add generated protocols to resources generated_protocol_configuration = ProtocolConfig.from_json( yaml.safe_load( open( os.path.join( self.cwd, "tests", "data", "generator", "two_party_negotiation", "protocol.yaml", ) ) ) ) generated_protocol = Protocol( TwoPartyNegotiationMessage.protocol_id, TwoPartyNegotiationSerializer(), generated_protocol_configuration, ) resources_1.protocol_registry.register( TwoPartyNegotiationMessage.protocol_id, generated_protocol ) resources_2.protocol_registry.register( TwoPartyNegotiationMessage.protocol_id, generated_protocol ) # create AEAs aea_1 = AEA(identity_1, [oef_connection_1], wallet_1, ledger_apis, resources_1) aea_2 = AEA(identity_2, [oef_connection_2], wallet_2, ledger_apis, resources_2) inform_number = tuple((1370, 1991, 1, 4, 17, 6)) # message 1 message = TwoPartyNegotiationMessage( message_id=1, dialogue_reference=(str(0), ""), target=0, performative=TwoPartyNegotiationMessage.Performative.INFORM, inform_number=inform_number, ) encoded_message_in_bytes = TwoPartyNegotiationSerializer().encode(message) envelope = Envelope( to=identity_2.address, sender=identity_1.address, protocol_id=TwoPartyNegotiationMessage.protocol_id, message=encoded_message_in_bytes, ) # message 2 reply_message = {1: "number one", 2: "number two", 7: "number seven"} message_2 = TwoPartyNegotiationMessage( message_id=2, dialogue_reference=(str(0), ""), target=1, performative=TwoPartyNegotiationMessage.Performative.INFORM_REPLY, reply_message=reply_message, ) encoded_message_2_in_bytes = TwoPartyNegotiationSerializer().encode(message_2) # add handlers to AEA resources agent_1_handler = Agent1Handler( skill_context=SkillContext(aea_1.context), name="fake_skill" ) resources_1.handler_registry.register( ( PublicId.from_str("fetchai/fake_skill:0.1.0"), TwoPartyNegotiationMessage.protocol_id, ), agent_1_handler, ) agent_2_handler = Agent2Handler( encoded_messsage=encoded_message_2_in_bytes, skill_context=SkillContext(aea_2.context), name="fake_skill", ) resources_2.handler_registry.register( ( PublicId.from_str("fetchai/fake_skill:0.1.0"), TwoPartyNegotiationMessage.protocol_id, ), agent_2_handler, ) # add error skill to AEAs error_skill_1 = Skill.from_dir( os.path.join(AEA_DIR, "skills", "error"), aea_1.context ) resources_1.add_skill(error_skill_1) error_skill_2 = Skill.from_dir( os.path.join(AEA_DIR, "skills", "error"), aea_2.context ) resources_2.add_skill(error_skill_2) # Start threads t_1 = Thread(target=aea_1.start) t_2 = Thread(target=aea_2.start) try: t_1.start() t_2.start() time.sleep(1.0) aea_1.outbox.put(envelope) time.sleep(5.0) assert ( agent_2_handler.handled_message.message_id == message.message_id ), "Message from Agent 1 to 2: message ids do not match" assert ( agent_2_handler.handled_message.dialogue_reference == message.dialogue_reference ), "Message from Agent 1 to 2: dialogue references do not match" assert ( agent_2_handler.handled_message.dialogue_reference[0] == message.dialogue_reference[0] ), "Message from Agent 1 to 2: dialogue reference[0]s do not match" assert ( agent_2_handler.handled_message.dialogue_reference[1] == message.dialogue_reference[1] ), "Message from Agent 1 to 2: dialogue reference[1]s do not match" assert ( agent_2_handler.handled_message.target == message.target ), "Message from Agent 1 to 2: targets do not match" assert ( agent_2_handler.handled_message.performative == message.performative ), "Message from Agent 1 to 2: performatives do not match" assert ( agent_2_handler.handled_message.inform_number == message.inform_number ), "Message from Agent 1 to 2: inform_numbers do not match" assert ( agent_1_handler.handled_message.message_id == message_2.message_id ), "Message from Agent 1 to 2: dialogue references do not match" assert ( agent_1_handler.handled_message.dialogue_reference == message_2.dialogue_reference ), "Message from Agent 2 to 1: dialogue references do not match" assert ( agent_1_handler.handled_message.dialogue_reference[0] == message_2.dialogue_reference[0] ), "Message from Agent 2 to 1: dialogue reference[0]s do not match" assert ( agent_1_handler.handled_message.dialogue_reference[1] == message_2.dialogue_reference[1] ), "Message from Agent 2 to 1: dialogue reference[1]s do not match" assert ( agent_1_handler.handled_message.target == message_2.target ), "Message from Agent 2 to 1: targets do not match" assert ( agent_1_handler.handled_message.performative == message_2.performative ), "Message from Agent 2 to 1: performatives do not match" assert ( agent_1_handler.handled_message.reply_message == message_2.reply_message ), "Message from Agent 1 to 2: reply_messages do not match" time.sleep(2.0) finally: aea_1.stop() aea_2.stop() t_1.join() t_2.join()
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_handle(): """Tests handle method of an agent.""" with LocalNode() as node: agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) connection = OEFLocalConnection(identity.address, node, connection_id=DUMMY_SKILL_PUBLIC_ID) connections = [connection] resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea"))) msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.counterparty = agent_name message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID, message=message_bytes, ) agent = AEA(identity, connections, wallet, ledger_apis, resources, is_programmatic=False) t = Thread(target=agent.start) try: t.start() time.sleep(2.0) dummy_skill = agent.resources.get_skill(DUMMY_SKILL_PUBLIC_ID) dummy_handler = dummy_skill.handlers["dummy"] expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 1 # DECODING ERROR msg = "hello".encode("utf-8") envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=DefaultMessage.protocol_id, message=msg, ) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 2 # UNSUPPORTED SKILL msg = FIPASerializer().encode( FIPAMessage( performative=FIPAMessage.Performative.ACCEPT, message_id=0, dialogue_reference=(str(0), ""), target=1, )) envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=FIPAMessage.protocol_id, message=msg, ) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 3 finally: agent.stop() t.join()
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 = OEFLocalConnection( cls.agent_name, cls.node, connection_id=LOCAL_CONNECTION_PUBLIC_ID) cls.connections = [cls.connection] cls.temp = tempfile.mkdtemp(prefix="test_aea_resources") cls.resources = Resources(cls.temp) cls.aea = AEA( cls.identity, cls.connections, cls.wallet, cls.ledger_apis, resources=cls.resources, ) default_protocol_id = DefaultMessage.protocol_id cls.default_protocol_configuration = ProtocolConfig.from_json( yaml.safe_load( open(Path(AEA_DIR, "protocols", "default", "protocol.yaml")))) cls.default_protocol = Protocol(default_protocol_id, DefaultSerializer(), cls.default_protocol_configuration) cls.resources.protocol_registry.register(default_protocol_id, 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( 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 run(): # Create a private keys _create_fetchai_private_key(private_key_file=FETCHAI_PRIVATE_KEY_FILE_1) _create_fetchai_private_key(private_key_file=FETCHAI_PRIVATE_KEY_FILE_2) # Set up the wallets wallet_1 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE_1}) wallet_2 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE_2}) # Generate some wealth _try_generate_testnet_wealth(FETCHAI, wallet_1.addresses[FETCHAI]) # Set up the LedgerApis ledger_apis = LedgerApis({FETCHAI: {"network": "testnet"}}, FETCHAI) tx_handler = TransactionHandler(skill_context="skill_context", name="fake_skill") resources = Resources() resources.handler_registry.register( ( PublicId.from_str("fetchai/fake_skill:0.1.0"), PublicId.from_str("fetchai/internal:0.1.0"), ), tx_handler, ) stub_connection = StubConnection(input_file_path=INPUT_FILE, output_file_path=OUTPUT_FILE) identity_1 = Identity( name="my_aea", address=wallet_1.addresses.get(FETCHAI), default_address_key=FETCHAI, ) identity_2 = Identity( name="my_aea_2", address=wallet_2.addresses.get(FETCHAI), default_address_key=FETCHAI, ) # create the AEA my_aea = AEA(identity_1, [stub_connection], wallet_1, ledger_apis, resources) ledger_api = ledger_apis.apis[FETCHAI] tx_nonce = ledger_api.generate_tx_nonce(identity_1.addresses.get(FETCHAI), identity_2.addresses.get(FETCHAI)) tx_msg = TransactionMessage( performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT, skill_callback_ids=[PublicId("fetchai", "fake_skill", "0.1.0")], tx_id="transaction0", tx_sender_addr=identity_1.addresses.get(FETCHAI), tx_counterparty_addr=identity_2.addresses.get(FETCHAI), tx_amount_by_currency_id={"FET": -1}, tx_sender_fee=1, tx_counterparty_fee=0, tx_quantities_by_good_id={}, ledger_id=FETCHAI, info={"some_info_key": "some_info_value"}, tx_nonce=tx_nonce, ) my_aea.context.decision_maker_message_queue.put_nowait(tx_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 weather station time.sleep(20) finally: # Shut down the AEA logger.info("STOPPING AEA NOW!") my_aea.stop() t.join()
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",) ) 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()
async def test_handle(): """Tests handle method of an agent.""" with LocalNode() as node: agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) public_key = wallet.public_keys['default'] connection = OEFLocalConnection(public_key, node) connections = [connection] msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=public_key, sender=public_key, protocol_id="unknown_protocol", message=message_bytes) agent = AEA( agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) dummy_skill = agent.resources.get_skill("dummy") dummy_handler = dummy_skill.handlers[0] expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(1.0) assert len(dummy_handler.handled_messages) == 1 # DECODING ERROR msg = "hello".encode("utf-8") envelope = Envelope( to=public_key, sender=public_key, protocol_id='default', message=msg) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(1.0) assert len(dummy_handler.handled_messages) == 2 # UNSUPPORTED SKILL msg = FIPASerializer().encode( FIPAMessage(performative=FIPAMessage.Performative.ACCEPT, message_id=0, dialogue_reference=(str(0), ''), target=1)) envelope = Envelope( to=public_key, sender=public_key, protocol_id="fipa", message=msg) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(1.0) assert len(dummy_handler.handled_messages) == 3 finally: agent.stop() t.join()