Esempio n. 1
0
    def _build_identity_from_wallet(self, wallet: Wallet) -> Identity:
        """
        Get the identity associated to a wallet.

        :param wallet: the wallet
        :return: the identity
        """
        assert self._name is not None, "You must set the name of the agent."

        if not wallet.addresses:
            raise ValueError("wallet has no addresses")

        if len(wallet.addresses) > 1:
            identity = Identity(
                self._name,
                addresses=wallet.addresses,
                default_address_key=self._default_ledger,
            )
        else:
            identity = Identity(
                self._name,
                address=wallet.addresses[self._default_ledger],
                default_address_key=self._default_ledger,
            )
        return identity
Esempio n. 2
0
    def setup(self):
        """Set up."""
        self.crypto = make_crypto(DEFAULT_LEDGER)
        self.crypto2 = make_crypto(DEFAULT_LEDGER)
        identity = Identity("", address=self.crypto.address)
        self.oef_search_dialogues = OefSearchDialogues(self.crypto.address)
        self.data_dir = tempfile.mkdtemp()

        # create the connection and multiplexer objects
        configuration = ConnectionConfig(
            api_key="TwiCIriSl0mLahw17pyqoA",
            soef_addr="s-oef.fetch.ai",
            soef_port=443,
            restricted_to_protocols={
                OefSearchMessage.protocol_specification_id
            },
            connection_id=SOEFConnection.connection_id,
        )
        self.connection = SOEFConnection(
            configuration=configuration,
            data_dir=self.data_dir,
            identity=identity,
        )
        self.connection2 = SOEFConnection(
            configuration=configuration,
            data_dir=self.data_dir,
            identity=Identity("", address=self.crypto2.address),
        )
        self.loop = asyncio.get_event_loop()
        self.loop.run_until_complete(self.connection.connect())
        self.loop.run_until_complete(self.connection2.connect())
        self.connection.channel.unique_page_address = "some_addr"
Esempio n. 3
0
    def setup(self):
        """Set up."""
        self.crypto = make_crypto(DEFAULT_LEDGER)
        self.crypto2 = make_crypto(DEFAULT_LEDGER)
        identity = Identity("", address=self.crypto.address)
        self.oef_search_dialogues = OefSearchDialogues(self.crypto.address)

        # create the connection and multiplexer objects
        configuration = ConnectionConfig(
            api_key="TwiCIriSl0mLahw17pyqoA",
            soef_addr="soef.fetch.ai",
            soef_port=9002,
            restricted_to_protocols={PublicId.from_str("fetchai/oef_search:0.3.0")},
            connection_id=SOEFConnection.connection_id,
        )
        self.connection = SOEFConnection(
            configuration=configuration, identity=identity,
        )
        self.connection.channel.unique_page_address = "some addr"
        self.connection2 = SOEFConnection(
            configuration=configuration,
            identity=Identity("", address=self.crypto2.address),
        )
        self.loop = asyncio.get_event_loop()
        self.loop.run_until_complete(self.connection.connect())
        self.loop.run_until_complete(self.connection2.connect())
Esempio n. 4
0
def test_init_identity_negative():
    """Test initialization of the identity object."""
    with pytest.raises(KeyError):
        Identity(
            "some_name",
            addresses={
                "cosmos": "some_address",
                "fetchai": "some_address"
            },
            default_address_key="ethereum",
        )
    with pytest.raises(AssertionError):
        Identity("some_name")
Esempio n. 5
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
Esempio n. 6
0
def test_init_identity_negative():
    """Test initialization of the identity object."""
    name = "some_name"
    address_1 = "some_address"
    with pytest.raises(KeyError):
        Identity(
            name,
            addresses={
                DEFAULT_LEDGER: address_1,
                FETCHAI: address_1
            },
            default_address_key="wrong_key",
        )
    with pytest.raises(ValueError):
        Identity(name)
Esempio n. 7
0
    def setup_class(cls):
        """Initialise the decision maker."""
        cls._patch_logger()
        cls.multiplexer = Multiplexer([_make_dummy_connection()])
        private_key_pem_path = os.path.join(CUR_PATH, "data",
                                            "fet_private_key.txt")
        eth_private_key_pem_path = os.path.join(CUR_PATH, "data",
                                                "fet_private_key.txt")
        cls.wallet = Wallet({
            FETCHAI: private_key_pem_path,
            ETHEREUM: eth_private_key_pem_path
        })
        cls.ledger_apis = LedgerApis({FETCHAI: DEFAULT_FETCHAI_CONFIG},
                                     FETCHAI)
        cls.agent_name = "test"
        cls.identity = Identity(cls.agent_name,
                                addresses=cls.wallet.addresses,
                                default_address_key=FETCHAI)
        cls.ownership_state = OwnershipState()
        cls.preferences = Preferences()
        cls.decision_maker = DecisionMaker(
            identity=cls.identity,
            wallet=cls.wallet,
            ledger_apis=cls.ledger_apis,
        )
        cls.multiplexer.connect()

        cls.tx_id = "transaction0"
        cls.tx_sender_addr = "agent_1"
        cls.tx_counterparty_addr = "pk"
        cls.info = {"some_info_key": "some_info_value"}
        cls.ledger_id = "fetchai"

        cls.decision_maker.start()
Esempio n. 8
0
    def setup(self):
        """Test the initialisation of the AEA."""
        private_key_path = os.path.join(CUR_PATH, "data",
                                        DEFAULT_PRIVATE_KEY_FILE)
        self.wallet = Wallet({DEFAULT_LEDGER: private_key_path})
        self.agent_name = "Agent0"

        self.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)
Esempio n. 9
0
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()
Esempio n. 10
0
    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()
Esempio n. 11
0
    def setup(cls):
        """Initialise the decision maker."""
        cls._patch_logger()
        cls.wallet = Wallet(
            {
                COSMOS: COSMOS_PRIVATE_KEY_PATH,
                ETHEREUM: ETHEREUM_PRIVATE_KEY_PATH,
                FETCHAI: FETCHAI_PRIVATE_KEY_PATH,
            }
        )
        cls.agent_name = "test"
        cls.identity = Identity(
            cls.agent_name, addresses=cls.wallet.addresses, default_address_key=COSMOS,
        )
        cls.decision_maker_handler = DecisionMakerHandler(
            identity=cls.identity, wallet=cls.wallet
        )
        cls.decision_maker = DecisionMaker(cls.decision_maker_handler)

        cls.tx_sender_addr = "agent_1"
        cls.tx_counterparty_addr = "pk"
        cls.info = {"some_info_key": "some_info_value"}
        cls.ledger_id = FETCHAI

        cls.decision_maker.start()
Esempio n. 12
0
 def setup_class(cls):
     """Test the initialisation of the AEA."""
     eth_private_key_path = os.path.join(CUR_PATH, "data",
                                         "eth_private_key.txt")
     fet_private_key_path = os.path.join(CUR_PATH, "data",
                                         "fet_private_key.txt")
     cls.wallet = Wallet({
         ETHEREUM: eth_private_key_path,
         FETCHAI: fet_private_key_path
     })
     cls.ledger_apis = LedgerApis({FETCHAI: {
         "network": "testnet"
     }}, FETCHAI)
     cls.connections = [
         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)
Esempio n. 13
0
    def setup(self):
        """Initialise the test case."""
        self.identity = Identity("name", address="my_key")
        self.agent_address = self.identity.address
        self.host = get_host()
        self.port = get_unused_tcp_port()
        self.api_spec_path = os.path.join(
            ROOT_DIR, "tests", "data", "petstore_sim.yaml"
        )
        self.connection_id = HTTPServerConnection.connection_id
        self.protocol_id = PublicId.from_str("fetchai/http:0.4.0")

        self.configuration = ConnectionConfig(
            host=self.host,
            port=self.port,
            api_spec_path=self.api_spec_path,
            connection_id=HTTPServerConnection.connection_id,
            restricted_to_protocols=set([self.protocol_id]),
        )
        self.http_connection = HTTPServerConnection(
            configuration=self.configuration, identity=self.identity,
        )
        self.loop = asyncio.get_event_loop()
        self.loop.run_until_complete(self.http_connection.connect())
        self.connection_address = str(HTTPServerConnection.connection_id)
        self._dialogues = HttpDialogues(self.connection_address)
        self.original_timeout = self.http_connection.channel.RESPONSE_TIMEOUT
Esempio n. 14
0
async def test_load_from_dir():
    """Test stub connection can be loaded from dir."""
    StubConnection.from_dir(
        ROOT_DIR + "/packages/fetchai/connections/stub",
        Identity("name", "address"),
        CryptoStore(),
    )
Esempio n. 15
0
    def setup_class(cls):
        """Initialise the decision maker."""
        cls._patch_logger()
        private_key_pem_path = os.path.join(CUR_PATH, "data",
                                            "fet_private_key.txt")
        eth_private_key_pem_path = os.path.join(CUR_PATH, "data",
                                                "fet_private_key.txt")
        cls.wallet = Wallet({
            FetchAICrypto.identifier:
            private_key_pem_path,
            EthereumCrypto.identifier:
            eth_private_key_pem_path,
        })
        cls.agent_name = "test"
        cls.identity = Identity(
            cls.agent_name,
            addresses=cls.wallet.addresses,
            default_address_key=FetchAICrypto.identifier,
        )
        cls.decision_maker_handler = DecisionMakerHandler(
            identity=cls.identity, wallet=cls.wallet)
        cls.decision_maker = DecisionMaker(cls.decision_maker_handler)

        cls.tx_sender_addr = "agent_1"
        cls.tx_counterparty_addr = "pk"
        cls.info = {"some_info_key": "some_info_value"}
        cls.ledger_id = "fetchai"

        cls.decision_maker.start()
Esempio n. 16
0
def run():
    # 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)

    # create the connection and multiplexer objects
    configuration = ConnectionConfig(
        input_file=INPUT_FILE,
        output_file=OUTPUT_FILE,
        connection_id=StubConnection.connection_id,
    )
    stub_connection = StubConnection(configuration=configuration,
                                     identity=Identity("some_agent",
                                                       "some_address"))
    multiplexer = Multiplexer([stub_connection])
    try:
        # Set the multiplexer running in a different thread
        t = Thread(target=multiplexer.connect)
        t.start()

        # Wait for everything to start up
        time.sleep(3)

        # Create a message inside an envelope and get the stub connection to pass it into the multiplexer
        message_text = (
            "multiplexer,some_agent,fetchai/default:0.4.0,\x08\x01*\x07\n\x05hello,"
        )
        with open(INPUT_FILE, "w") as f:
            write_with_lock(f, message_text)

        # Wait for the envelope to get processed
        time.sleep(2)

        # get the envelope
        envelope = multiplexer.get()  # type: Optional[Envelope]
        assert envelope is not None

        # Inspect its contents
        print(
            "Envelope received by Multiplexer: sender={}, to={}, protocol_id={}, message={}"
            .format(envelope.sender, envelope.to, envelope.protocol_id,
                    envelope.message))

        # Create a mirrored response envelope
        response_envelope = copy(envelope)
        response_envelope.to = envelope.sender
        response_envelope.sender = envelope.to

        # Send the envelope back
        multiplexer.put(response_envelope)

        # Read the output envelope generated by the multiplexer
        with open(OUTPUT_FILE, "r") as f:
            print("Envelope received from Multiplexer: " + f.readline())
    finally:
        # Shut down the multiplexer
        multiplexer.disconnect()
        t.join()
Esempio n. 17
0
def test_error_handler_is_not_set():
    """Test stop on no error handler presents."""
    agent_name = "my_agent"
    private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE)
    wallet = Wallet({DEFAULT_LEDGER: private_key_path})
    identity = Identity(agent_name, address=wallet.addresses[DEFAULT_LEDGER])
    resources = Resources()
    context_namespace = {"key1": 1, "key2": 2}
    agent = AEA(identity, wallet, resources, **context_namespace)

    msg = DefaultMessage(
        dialogue_reference=("", ""),
        message_id=1,
        target=0,
        performative=DefaultMessage.Performative.BYTES,
        content=b"hello",
    )
    msg.counterparty = agent.identity.address
    envelope = Envelope(
        to=agent.identity.address,
        sender=agent.identity.address,
        protocol_id=DefaultMessage.protocol_id,
        message=msg,
    )

    with patch.object(agent, "stop") as mocked_stop:
        agent._handle(envelope)

    mocked_stop.assert_called()
Esempio n. 18
0
    def setup_class(cls):
        """Set the test up"""
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        os.chdir(cls.t)
        crypto = make_crypto(DEFAULT_LEDGER)
        cls.node_host = "localhost"
        cls.node_port = "11234"
        cls.identity = Identity("", address=crypto.address)

        cls.key_file = os.path.join(cls.t, "keyfile")
        key_file_desc = open(cls.key_file, "ab")
        crypto.dump(key_file_desc)
        key_file_desc.close()

        cls.peer_crypto = make_crypto(DEFAULT_LEDGER)
        cls.cert_request = CertRequest(
            cls.peer_crypto.public_key,
            POR_DEFAULT_SERVICE_ID,
            DEFAULT_LEDGER,
            "2021-01-01",
            "2021-01-02",
            f"./{crypto.address}_cert.txt",
        )
        _process_cert(crypto, cls.cert_request, cls.t)
Esempio n. 19
0
def test_init_and_not_implemented():
    """Initialise the decision maker handler."""
    decision_maker_handler = DecisionMakerHandler(identity=Identity(
        "name", "address"),
                                                  wallet="wallet")
    with pytest.raises(NotImplementedError):
        decision_maker_handler.handle("message")
    def setup_class(cls):
        """Initialise the class."""
        cls.aca_admin_address = "127.0.0.1"
        cls.aca_admin_port = 8020

        cls.aea_address = "some string"
        cls.aea_identity = Identity("", address=cls.aea_address)

        cls.cwd = os.getcwd()

        # check Aries Cloud Agents (ACA) is installed
        res = shutil.which("aca-py")
        if res is None:
            pytest.skip(
                "Please install Aries Cloud Agents first! See the following link: https://github.com/hyperledger/aries-cloudagent-python"
            )

        # run an ACA
        # command: aca-py start --admin 127.0.0.1 8020 --admin-insecure-mode --inbound-transport http 0.0.0.0 8000 --outbound-transport http
        cls.process = subprocess.Popen(  # nosec
            [
                "aca-py",
                "start",
                "--admin",
                cls.aca_admin_address,
                str(cls.aca_admin_port),
                "--admin-insecure-mode",
                "--inbound-transport",
                "http",
                "0.0.0.0",
                "8000",
                "--outbound-transport",
                "http",
            ])
        time.sleep(4.0)
Esempio n. 21
0
    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()
Esempio n. 22
0
    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)
Esempio n. 23
0
    def setup_class(cls):
        """Set the tests up."""
        cls._patch_logger()

        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_directory = Path(cls.t, "dummy_skill")
        shutil.copytree(Path(CUR_PATH, "data", "dummy_skill"),
                        cls.skill_directory)
        os.chdir(cls.t)

        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        cls.wallet = Wallet({FETCHAI: private_key_path})
        ledger_apis = LedgerApis({}, FETCHAI)
        cls.connections = [
            DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID)
        ]
        cls.identity = Identity("name", address=cls.wallet.addresses[FETCHAI])
        cls.my_aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            ledger_apis,
            resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))),
            is_programmatic=False,
        )
        cls.agent_context = cls.my_aea.context
    def setup_client(self):
        """Set up client connection."""
        self.client_agent_address = "client_agent_address"
        self.client_agent_identity = Identity(
            "agent running client", address=self.client_agent_address)
        configuration = ConnectionConfig(
            host="localost",
            port="8888",  # TODO: remove host/port for client?
            connection_id=HTTPClientConnection.connection_id,
        )
        self.client = HTTPClientConnection(configuration=configuration,
                                           identity=self.client_agent_identity)
        self.loop.run_until_complete(self.client.connect())

        # skill side dialogues
        def role_from_first_message(  # pylint: disable=unused-argument
                message: Message,
                receiver_address: Address) -> BaseDialogue.Role:
            """Infer the role of the agent from an incoming/outgoing first message

            :param message: an incoming/outgoing first message
            :param receiver_address: the address of the receiving agent
            :return: The role of the agent
            """
            return HttpDialogue.Role.CLIENT

        self._client_dialogues = HttpDialogues(
            self.client_agent_address,
            role_from_first_message=role_from_first_message)
Esempio n. 25
0
def make_multiplexer_and_dialogues(
) -> Tuple[Multiplexer, OefSearchDialogues, Crypto, SOEFConnection]:
    """Return multplexer, dialogues and crypto instances."""
    crypto = make_crypto(DEFAULT_LEDGER)
    identity = Identity("", address=crypto.address)
    oef_search_dialogues = OefSearchDialogues(crypto.address)

    # create the connection and multiplexer objects
    configuration = ConnectionConfig(
        api_key="TwiCIriSl0mLahw17pyqoA",
        soef_addr="s-oef.fetch.ai",
        soef_port=443,
        restricted_to_protocols={
            OefSearchMessage.protocol_specification_id,
            OefSearchMessage.protocol_id,
        },
        connection_id=SOEFConnection.connection_id,
    )
    soef_connection = SOEFConnection(
        configuration=configuration,
        data_dir=MagicMock(),
        identity=identity,
    )
    multiplexer = Multiplexer([soef_connection])
    return multiplexer, oef_search_dialogues, crypto, soef_connection
Esempio n. 26
0
    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)
Esempio n. 27
0
def test_send_message_no_supported_protocol():
    """Test the case when we send an envelope with a specific connection that does not support the protocol."""
    with LocalNode() as node:
        identity_1 = Identity("", address="address_1")
        public_id = PublicId.from_str("fetchai/my_private_protocol:0.1.0")
        connection_1 = _make_local_connection(
            identity_1.address,
            node,
            restricted_to_protocols={public_id},
            excluded_protocols={public_id},
        )
        multiplexer = Multiplexer([connection_1])

        multiplexer.connect()

        with mock.patch.object(aea.mail.base.logger, "warning") as mock_logger_warning:
            protocol_id = UNKNOWN_PROTOCOL_PUBLIC_ID
            envelope = Envelope(
                to=identity_1.address,
                sender=identity_1.address,
                protocol_id=protocol_id,
                message=b"some bytes",
            )
            multiplexer.put(envelope)
            time.sleep(0.5)
            mock_logger_warning.assert_called_with(
                "Connection {} cannot handle protocol {}. Cannot send the envelope.".format(
                    connection_1.connection_id, protocol_id
                )
            )

        multiplexer.disconnect()
Esempio n. 28
0
def _run_interaction_channel():
    # load agent configuration file
    loader = ConfigLoader.from_configuration_type(PackageType.AGENT)
    agent_configuration = loader.load(Path(DEFAULT_AEA_CONFIG_FILE).open())
    agent_name = agent_configuration.name
    # load stub connection
    configuration = ConnectionConfig(
        input_file=DEFAULT_OUTPUT_FILE_NAME,
        output_file=DEFAULT_INPUT_FILE_NAME,
        connection_id=StubConnection.connection_id,
    )
    identity_stub = Identity(agent_name + "_interact", "interact")
    stub_connection = StubConnection(configuration=configuration,
                                     identity=identity_stub)
    multiplexer = Multiplexer([stub_connection])
    inbox = InBox(multiplexer)
    outbox = OutBox(multiplexer, default_address=identity_stub.address)
    dialogues = DefaultDialogues(identity_stub.name)

    try:
        multiplexer.connect()
        while True:  # pragma: no cover
            _process_envelopes(agent_name, identity_stub, inbox, outbox,
                               dialogues)

    except KeyboardInterrupt:
        click.echo("Interaction interrupted!")
    except BaseException as e:  # pylint: disable=broad-except # pragma: no cover
        click.echo(e)
    finally:
        multiplexer.disconnect()
Esempio n. 29
0
    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)
Esempio n. 30
0
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()