async def test_receive_raises_exception(self):
        """Test the case when a receive raises a generic exception."""
        port = get_unused_tcp_port()
        tcp_server = TCPServerConnection(
            "address_server",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )
        tcp_client = TCPClientConnection(
            "address_client",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )

        await tcp_server.connect()
        await tcp_client.connect()

        with pytest.raises(Exception, match="generic exception"):
            with unittest.mock.patch.object(
                    tcp_client,
                    "_recv",
                    side_effect=Exception("generic exception")):
                task = asyncio.ensure_future(tcp_client.receive())
                await asyncio.sleep(0.1)
                assert task.result() is None

        await tcp_client.disconnect()
        await tcp_server.disconnect()
    async def test_receive_raises_exception(self):
        """Test the case when a receive raises a generic exception."""
        port = get_unused_tcp_port()
        tcp_server = TCPServerConnection(
            "address_server",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )
        tcp_client = TCPClientConnection(
            "address_client",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )

        await tcp_server.connect()
        await tcp_client.connect()
        await asyncio.sleep(0.1)
        with unittest.mock.patch.object(
                packages.fetchai.connections.tcp.tcp_server.logger,
                "error") as mock_logger_error:
            with unittest.mock.patch(
                    "asyncio.wait",
                    side_effect=Exception("generic exception")):
                result = await tcp_server.receive()
                assert result is None
                mock_logger_error.assert_called_with(
                    "Error in the receiving loop: generic exception")

        await tcp_client.disconnect()
        await tcp_server.disconnect()
    async def test_receive_raises_struct_error(self):
        """Test the case when a receive raises a struct error."""
        port = get_unused_tcp_port()
        tcp_server = TCPServerConnection(
            "address_server",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )
        tcp_client = TCPClientConnection(
            "address_client",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )

        await tcp_server.connect()
        await tcp_client.connect()

        with unittest.mock.patch.object(
                packages.fetchai.connections.tcp.tcp_client.logger,
                "debug") as mock_logger_debug:
            with unittest.mock.patch.object(tcp_client,
                                            "_recv",
                                            side_effect=struct.error):
                task = asyncio.ensure_future(tcp_client.receive())
                await asyncio.sleep(0.1)
                mock_logger_debug.assert_called_with("Struct error: ")
                assert task.result() is None

        await tcp_client.disconnect()
        await tcp_server.disconnect()
Example #4
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.address_1 = "address_1"
        cls.multiplexer1 = Multiplexer(
            [
                OEFLocalConnection(
                    cls.address_1,
                    cls.node,
                    connection_id=PublicId("fetchai", "local", "0.1.0"),
                )
            ]
        )
        cls.address_2 = "address_2"
        cls.multiplexer2 = Multiplexer(
            [
                OEFLocalConnection(
                    cls.address_2,
                    cls.node,
                    connection_id=PublicId("fetchai", "local", "0.1.0"),
                )
            ]
        )
        cls.multiplexer1.connect()
        cls.multiplexer2.connect()
Example #5
0
def test_multiplexer_connect_one_raises_error_many_connections():
    """Test the case when the multiplexer raises an exception while attempting the connection of one connection."""
    node = LocalNode()
    tmpdir = Path(tempfile.mkdtemp())
    d = tmpdir / "test_stub"
    d.mkdir(parents=True)
    input_file_path = d / "input_file.csv"
    output_file_path = d / "input_file.csv"

    connection_1 = OEFLocalConnection(
        "my_addr", node, connection_id=PublicId("fetchai", "local", "0.1.0")
    )
    connection_2 = StubConnection(
        input_file_path,
        output_file_path,
        connection_id=PublicId("fetchai", "stub", "0.1.0"),
    )
    connection_3 = DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID)
    multiplexer = Multiplexer([connection_1, connection_2, connection_3])

    assert not connection_1.connection_status.is_connected
    assert not connection_2.connection_status.is_connected
    assert not connection_3.connection_status.is_connected

    with unittest.mock.patch.object(connection_3, "connect", side_effect=Exception):
        with pytest.raises(
            AEAConnectionError, match="Failed to connect the multiplexer."
        ):
            multiplexer.connect()

    assert not connection_1.connection_status.is_connected
    assert not connection_2.connection_status.is_connected
    assert not connection_3.connection_status.is_connected

    shutil.rmtree(tmpdir)
Example #6
0
class TestRemovePackageWithLatestVersion(AEATestCaseEmpty):
    """Test case for remove package with latest version."""

    @pytest.mark.parametrize(
        ["type_", "public_id"],
        [
            ("protocol", PublicId.from_str(DEFAULT_PROTOCOL)),
            ("connection", PublicId("fetchai", "stub").to_latest()),
            ("contract", PublicId("fetchai", "erc1155").to_latest()),
        ],
    )
    def test_remove_pacakge_latest_version(self, type_, public_id):
        """Test remove protocol with latest version."""
        assert public_id.package_version.is_latest
        # we need this because there isn't a default contract/connection
        if type_ == "connection":
            self.add_item("connection", str(public_id))
        if type_ == "contract":
            self.add_item("contract", str(public_id))

        # first, check the package is present
        items_path = os.path.join(self.agent_name, "vendor", "fetchai", type_ + "s")
        items_folders = os.listdir(items_path)
        item_name = public_id.name
        assert item_name in items_folders

        # remove the package
        with patch("aea.cli.remove.RemoveItem.is_required_by", False):
            self.run_cli_command(
                *["remove", type_, str(public_id)], cwd=self._get_cwd()
            )

        # check that the 'aea remove' took effect.
        items_folders = os.listdir(items_path)
        assert item_name not in items_folders
    def setup_class(cls):
        """Set the tests up."""
        cls.patch = unittest.mock.patch.object(aea.registries.base.logger,
                                               "exception")
        cls.mocked_logger = cls.patch.__enter__()

        cls.oldcwd = os.getcwd()
        cls.agent_name = "agent_dir_test"
        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 protocol
        cls.fake_protocol_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("protocols").append(str(cls.fake_protocol_id))
        yaml.safe_dump(agent_config, open(agent_config_path, "w"))
        Path(cls.agent_folder, "protocols", cls.fake_protocol_id.name).mkdir()

        cls.registry = ProtocolRegistry()
        cls.registry.populate(cls.agent_folder)
        cls.expected_protocol_ids = {
            PublicId("fetchai", "default", "0.1.0"),
            PublicId("fetchai", "fipa", "0.1.0"),
        }
Example #8
0
    def setup_class(cls):
        """Set the tests up."""
        cls.patch = unittest.mock.patch.object(aea.registries.base.logger,
                                               "exception")
        cls.mocked_logger = cls.patch.__enter__()

        cls.oldcwd = os.getcwd()
        cls.agent_name = "agent_dir_test"
        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.registry = ProtocolRegistry()

        protocol_1 = Protocol.from_dir(
            Path(aea.AEA_DIR, "protocols", "default"))
        protocol_2 = Protocol.from_dir(
            Path(ROOT_DIR, "packages", "fetchai", "protocols", "fipa"), )
        cls.registry.register(protocol_1.public_id, protocol_1)
        cls.registry.register(protocol_2.public_id, protocol_2)

        cls.expected_protocol_ids = {
            PublicId("fetchai", "default", "0.1.0"),
            PublicId("fetchai", "fipa", "0.1.0"),
        }
Example #9
0
def test_component_id_same_prefix():
    """Test ComponentId.same_prefix"""
    component_id_1 = ComponentId(ComponentType.PROTOCOL,
                                 PublicId("author", "name", "0.1.0"))
    component_id_2 = ComponentId(ComponentType.PROTOCOL,
                                 PublicId("author", "name", "0.2.0"))
    assert component_id_1.same_prefix(component_id_2)
Example #10
0
    def setup_class(cls):
        """Initialise the class."""

        cls.address = "my_key"
        cls.host = get_host()
        cls.port = get_unused_tcp_port()
        cls.api_spec_path = os.path.join(ROOT_DIR, "tests", "data",
                                         "petstore_sim.yaml")
        cls.connection_id = PublicId("fetchai", "http_server", "0.1.0")
        cls.protocol_id = PublicId("fetchai", "http", "0.1.0")

        cls.http_connection = HTTPServerConnection(
            address=cls.address,
            host=cls.host,
            port=cls.port,
            api_spec_path=cls.api_spec_path,
            connection_id=cls.connection_id,
            restricted_to_protocols=set([cls.protocol_id]),
        )
        cls.loop = asyncio.new_event_loop()
        cls.http_connection.loop = cls.loop
        value = cls.loop.run_until_complete(cls.http_connection.connect())
        assert value is None
        assert cls.http_connection.connection_status.is_connected
        assert not cls.http_connection.channel.is_stopped

        cls.t = Thread(target=cls.loop.run_forever)
        cls.t.start()
    async def test_receive_cancelled(self):
        """Test that cancelling a receive task works correctly."""
        port = get_unused_tcp_port()
        tcp_server = TCPServerConnection(
            "address_server",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )
        tcp_client = TCPClientConnection(
            "address_client",
            "127.0.0.1",
            port,
            connection_id=PublicId("fetchai", "tcp", "0.1.0"),
        )

        await tcp_server.connect()
        await tcp_client.connect()

        with unittest.mock.patch.object(
                packages.fetchai.connections.tcp.tcp_client.logger,
                "debug") as mock_logger_debug:
            task = asyncio.ensure_future(tcp_client.receive())
            await asyncio.sleep(0.1)
            task.cancel()
            await asyncio.sleep(0.1)
            mock_logger_debug.assert_called_with(
                "[{}] Read cancelled.".format("address_client"))
            assert task.result() is None

        await tcp_client.disconnect()
        await tcp_server.disconnect()
Example #12
0
    def test_handle_internal_messages(self):
        """Test that the internal messages are handled."""
        t = TransactionMessage(
            performative=TransactionMessage.Performative.SUCCESSFUL_SETTLEMENT,
            tx_id="transaction0",
            skill_callback_ids=[PublicId("dummy_author", "dummy", "0.1.0")],
            tx_sender_addr="pk1",
            tx_counterparty_addr="pk2",
            tx_amount_by_currency_id={"FET": 2},
            tx_sender_fee=0,
            tx_counterparty_fee=0,
            tx_quantities_by_good_id={"Unknown": 10},
            ledger_id="fetchai",
            info={},
            tx_digest="some_tx_digest",
        )
        self.aea.decision_maker.message_out_queue.put(t)
        self.aea._filter.handle_internal_messages()

        internal_handlers_list = self.aea.resources.get_handlers(
            PublicId("fetchai", "internal", "0.1.0"))
        assert len(internal_handlers_list) == 1
        internal_handler = internal_handlers_list[0]
        assert len(internal_handler.handled_internal_messages) == 1
        self.aea.teardown()
Example #13
0
 def test__is_version_correct_negative(self):
     """Test for _is_version_correct method negative result."""
     public_id_a = PublicId("author", "package", "0.1.0")
     public_id_b = PublicId("author", "package", "0.1.1")
     ctx_mock = ContextMock(version=public_id_b.version)
     ctx_mock.agent_config.public_id = public_id_b
     result = _is_version_correct(ctx_mock, public_id_a)
     self.assertFalse(result)
Example #14
0
def test_package_id_lt():
    """Test PackageId.__lt__"""
    package_id_1 = PackageId(PackageType.PROTOCOL,
                             PublicId("author", "name", "0.1.0"))
    package_id_2 = PackageId(PackageType.PROTOCOL,
                             PublicId("author", "name", "0.2.0"))

    assert package_id_1 < package_id_2
Example #15
0
def test_public_id_comparator_when_name_is_different():
    """Test PublicId.__lt__ when author is different."""
    pid1 = PublicId("author", "name_1", "0.1.0")
    pid2 = PublicId("author", "name_2", "0.1.0")
    with pytest.raises(
        ValueError,
        match="The public IDs .* and .* cannot be compared. Their author or name attributes are different.",
    ):
        pid1 < pid2
Example #16
0
    def test_decision_maker_handle_tx_message_not_ready(self):
        """Test that the decision maker is not ready to pursuit the goals.Cannot handle the message."""
        tx_message = TransactionMessage(
            performative=TransactionMessage.Performative.
            PROPOSE_FOR_SETTLEMENT,
            skill_callback_ids=[PublicId(AUTHOR, "a_skill", "0.1.0")],
            tx_id=self.tx_id,
            tx_sender_addr=self.tx_sender_addr,
            tx_counterparty_addr=self.tx_counterparty_addr,
            tx_amount_by_currency_id={"FET": -2},
            tx_sender_fee=0,
            tx_counterparty_fee=0,
            tx_quantities_by_good_id={"good_id": 10},
            info=self.info,
            ledger_id=self.ledger_id,
            tx_nonce="Transaction nonce",
        )

        with mock.patch.object(
                self.decision_maker_handler.context.ledger_apis,
                "token_balance",
                return_value=1000000,
        ):
            with mock.patch.object(
                    self.decision_maker_handler.context.ledger_apis,
                    "transfer",
                    return_value="This is a test digest",
            ):
                with mock.patch(
                        "aea.decision_maker.default.GoalPursuitReadiness.Status"
                ) as mocked_status:
                    mocked_status.READY.value = False
                    self.decision_maker.handle(tx_message)
                    assert (not self.decision_maker_handler.context.
                            goal_pursuit_readiness.is_ready)
                    self.decision_maker.message_out_queue.get()

        tx_message = TransactionMessage(
            performative=TransactionMessage.Performative.
            PROPOSE_FOR_SETTLEMENT,
            skill_callback_ids=[PublicId(AUTHOR, "a_skill", "0.1.0")],
            tx_id=self.tx_id,
            tx_sender_addr=self.tx_sender_addr,
            tx_counterparty_addr=self.tx_counterparty_addr,
            tx_amount_by_currency_id={"FET": -2},
            tx_sender_fee=0,
            tx_counterparty_fee=0,
            tx_quantities_by_good_id={"good_id": 10},
            info=self.info,
            ledger_id=self.ledger_id,
            tx_nonce="transaction nonce",
        )
        self.decision_maker.handle(tx_message)
        assert not self.decision_maker.message_out_queue.empty()
        self.decision_maker.message_out_queue.get()
Example #17
0
def test_envelope_skill_id():
    """Test the property Envelope.skill_id."""
    envelope_context = EnvelopeContext(uri=URI("author/skill_name/0.1.0"))
    envelope = Envelope(
        to="to",
        sender="sender",
        protocol_id=PublicId("author", "name", "0.1.0"),
        message=b"message",
        context=envelope_context,
    )

    assert envelope.skill_id == PublicId("author", "skill_name", "0.1.0")
    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"),
        }
Example #19
0
 def test_register_when_component_id_mismatch(self):
     """Test AgentComponentRegistry.register when the component ids mismatch."""
     component_id_1 = ComponentId(ComponentType.PROTOCOL,
                                  PublicId("author", "name", "0.1.0"))
     component_id_2 = ComponentId(ComponentType.PROTOCOL,
                                  PublicId("author", "name", "0.2.0"))
     component_mock = MagicMock(component_id=component_id_1)
     with pytest.raises(
             ValueError,
             match="Component id '.*' is different to the id '.*' specified."
     ):
         self.registry.register(component_id_2, component_mock)
     self.registry._registered_keys = set()
Example #20
0
def test_pubic_id_same_prefix():
    """Test PublicId.same_prefix"""
    same_1 = PublicId("author", "name", "0.1.0")
    same_2 = PublicId("author", "name", "0.1.1")
    different = PublicId("author", "different_name", "0.1.0")

    assert same_1.same_prefix(same_2)
    assert same_2.same_prefix(same_1)

    assert not different.same_prefix(same_1)
    assert not same_1.same_prefix(different)

    assert not different.same_prefix(same_2)
    assert not same_2.same_prefix(different)
Example #21
0
def test_envelope_connection_id():
    """Test the property Envelope.connection_id."""
    envelope_context = EnvelopeContext(
        uri=URI("connection/author/connection_name/0.1.0"))
    envelope = Envelope(
        to="to",
        sender="sender",
        protocol_specification_id=PublicId("author", "name", "0.1.0"),
        message=b"message",
        context=envelope_context,
    )

    assert envelope.connection_id == PublicId("author", "connection_name",
                                              "0.1.0")
Example #22
0
class BaseTestReplaceComponentIds:
    """Base test class for 'replace_component_ids' utility function."""

    old_protocol_id = PublicId("author", "old_protocol", "0.1.0")
    old_contract_id = PublicId("author", "old_contract", "0.1.0")
    old_connection_id = PublicId("author", "old_connection", "0.1.0")
    old_skill_id = PublicId("author", "old_skill", "0.1.0")

    new_protocol_id = PublicId("author", "new_protocol", "0.1.0")
    new_contract_id = PublicId("author", "new_contract", "0.1.0")
    new_connection_id = PublicId("author", "new_connection", "0.1.0")
    new_skill_id = PublicId("author", "new_skill", "0.1.0")

    new_public_ids = {
        new_protocol_id,
        new_contract_id,
        new_connection_id,
        new_skill_id,
    }

    replacements = {
        ComponentType.PROTOCOL: {
            old_protocol_id: new_protocol_id
        },
        ComponentType.CONTRACT: {
            old_contract_id: new_contract_id
        },
        ComponentType.CONNECTION: {
            old_connection_id: new_connection_id
        },
        ComponentType.SKILL: {
            old_skill_id: new_skill_id
        },
    }
Example #23
0
def test_check_package_public_id():
    """Test check_package_public_id."""
    public_id = PublicId("test", "test", "10.0.1")

    with mock.patch("aea.cli.registry.push.load_component_public_id",
                    return_value=public_id):
        check_package_public_id(mock.Mock(), mock.Mock(), public_id)

    with mock.patch("aea.cli.registry.push.load_component_public_id",
                    return_value=public_id):
        with pytest.raises(ClickException,
                           match="Version, name or author does not match"):
            check_package_public_id(mock.Mock(), mock.Mock(),
                                    PublicId("test", "test", "10.0.2"))
Example #24
0
def test_envelope_context_raises_with_public_id_specified_twice():
    """Test the EnvelopeContext constructor, negative"""
    with pytest.raises(
            ValueError,
            match="Cannot define connection_id explicitly and in URI."):
        EnvelopeContext(
            uri=URI("connection/author/connection_name/0.1.0"),
            connection_id=PublicId("author", "connection_name", "0.1.0"),
        )
    with pytest.raises(ValueError,
                       match="Cannot define skill_id explicitly and in URI."):
        EnvelopeContext(
            uri=URI("skill/author/skill_name/0.1.0"),
            skill_id=PublicId("author", "skill_name", "0.1.0"),
        )
Example #25
0
 def test_handle_message_signing_unknown_and_two_dialogues(self):
     """Test message signing for unknown."""
     message = b"0x11f3f9487724404e3a1fb7252a322656b90ba0455a2ca5fcdcbe6eeee5f8126d"
     signing_dialogues = SigningDialogues("agent")
     signing_msg = SigningMessage(
         performative=SigningMessage.Performative.SIGN_MESSAGE,
         dialogue_reference=signing_dialogues.new_self_initiated_dialogue_reference(),
         skill_callback_ids=(str(PublicId("author", "a_skill", "0.1.0")),),
         skill_callback_info={},
         terms=Terms(
             ledger_id="unknown",
             sender_address="pk1",
             counterparty_address="pk2",
             amount_by_currency_id={"FET": -1},
             is_sender_payable_tx_fee=True,
             quantities_by_good_id={"good_id": 10},
             nonce="transaction nonce",
         ),
         raw_message=RawMessage("unknown", message),
     )
     signing_msg.counterparty = "decision_maker"
     signing_dialogue = signing_dialogues.update(signing_msg)
     assert signing_dialogue is not None
     self.decision_maker.message_in_queue.put_nowait(signing_msg)
     signing_msg_response = self.decision_maker.message_out_queue.get(timeout=2)
     signing_msg_response.counterparty = signing_msg.counterparty
     signing_msg_response.is_incoming = True
     recovered_dialogue = signing_dialogues.update(signing_msg_response)
     assert recovered_dialogue is not None and recovered_dialogue == signing_dialogue
     assert signing_msg_response.performative == SigningMessage.Performative.ERROR
     assert signing_msg_response.skill_callback_ids == signing_msg.skill_callback_ids
     assert (
         signing_msg_response.error_code
         == SigningMessage.ErrorCode.UNSUCCESSFUL_MESSAGE_SIGNING
     )
Example #26
0
 def test_handle_tx_signing_unknown(self):
     """Test tx signing for unknown."""
     tx = {}
     signing_dialogues = SigningDialogues("agent")
     signing_msg = SigningMessage(
         performative=SigningMessage.Performative.SIGN_TRANSACTION,
         dialogue_reference=signing_dialogues.new_self_initiated_dialogue_reference(),
         skill_callback_ids=(str(PublicId("author", "a_skill", "0.1.0")),),
         skill_callback_info={},
         terms=Terms(
             ledger_id="unknown",
             sender_address="pk1",
             counterparty_address="pk2",
             amount_by_currency_id={"FET": -1},
             is_sender_payable_tx_fee=True,
             quantities_by_good_id={"good_id": 10},
             nonce="transaction nonce",
         ),
         raw_transaction=RawTransaction("unknown", tx),
     )
     signing_msg.counterparty = "decision_maker"
     signing_dialogue = signing_dialogues.update(signing_msg)
     assert signing_dialogue is not None
     self.decision_maker.message_in_queue.put_nowait(signing_msg)
     signing_msg_response = self.decision_maker.message_out_queue.get(timeout=2)
     signing_msg_response.counterparty = signing_msg.counterparty
     signing_msg_response.is_incoming = True
     recovered_dialogue = signing_dialogues.update(signing_msg_response)
     assert recovered_dialogue is not None and recovered_dialogue == signing_dialogue
     assert signing_msg_response.performative == SigningMessage.Performative.ERROR
     assert signing_msg_response.skill_callback_ids == signing_msg.skill_callback_ids
     assert (
         signing_msg_response.error_code
         == SigningMessage.ErrorCode.UNSUCCESSFUL_TRANSACTION_SIGNING
     )
Example #27
0
def test_negative_check_is_item_in_remote_registry():
    """Test the utility function (negative) to check if an item is in the remote registry"""
    with pytest.raises(click.ClickException, match="Not found in Registry."):
        _check_is_item_in_remote_registry(
            PublicId("nonexisting_package_author", "nonexisting_package_name", "0.0.0"),
            "protocol",
        )
Example #28
0
 def test_handle_message_signing_ethereum_deprecated(self):
     """Test message signing for ethereum deprecated."""
     message = b"0x11f3f9487724404e3a1fb7252a3226"
     signing_dialogues = SigningDialogues(
         str(PublicId("author", "a_skill", "0.1.0")))
     signing_msg = SigningMessage(
         performative=SigningMessage.Performative.SIGN_MESSAGE,
         dialogue_reference=signing_dialogues.
         new_self_initiated_dialogue_reference(),
         terms=Terms(
             ledger_id=ETHEREUM,
             sender_address="pk1",
             counterparty_address="pk2",
             amount_by_currency_id={"FET": -1},
             is_sender_payable_tx_fee=True,
             quantities_by_good_id={"good_id": 10},
             nonce="transaction nonce",
         ),
         raw_message=RawMessage(ETHEREUM, message, is_deprecated_mode=True),
     )
     signing_dialogue = signing_dialogues.create_with_message(
         "decision_maker", signing_msg)
     assert signing_dialogue is not None
     self.decision_maker.message_in_queue.put_nowait(signing_msg)
     signing_msg_response = self.decision_maker.message_out_queue.get(
         timeout=2)
     recovered_dialogue = signing_dialogues.update(signing_msg_response)
     assert recovered_dialogue is not None and recovered_dialogue == signing_dialogue
     assert (signing_msg_response.performative ==
             SigningMessage.Performative.SIGNED_MESSAGE)
     assert type(signing_msg_response.signed_message) == SignedMessage
     assert signing_msg_response.signed_message.is_deprecated_mode
Example #29
0
    def __init__(
        self,
        address: Address,
        host: str,
        port: int,
        api_spec_path: Optional[str] = None,
        *args,
        **kwargs,
    ):
        """
        Initialize a connection to an RESTful API.

        :param address: the address of the agent.
        :param host: RESTful API hostname / IP address
        :param port: RESTful API port number
        :param api_spec_path: Directory API path and filename of the API spec YAML source file.
        """

        if kwargs.get("connection_id") is None:
            kwargs["connection_id"] = PublicId("fetchai", "http", "0.1.0")

        super().__init__(*args, **kwargs)
        self.address = address
        self.channel = HTTPChannel(
            address,
            host,
            port,
            api_spec_path,
            connection_id=self.connection_id,
            restricted_to_protocols=kwargs.get("restricted_to_protocols", {}),
        )
Example #30
0
 def test__is_version_correct_positive(self):
     """Test for _is_version_correct method positive result."""
     public_id = PublicId("author", "package", "0.1.0")
     ctx_mock = ContextMock(version=public_id.version)
     ctx_mock.agent_config.public_id = public_id
     result = _is_version_correct(ctx_mock, public_id)
     self.assertTrue(result)