async def test_load_from_dir(): """Test stub connection can be loaded from dir.""" StubConnection.from_dir( ROOT_DIR + "/aea/connections/stub", Identity("name", "address"), CryptoStore(), )
def test_multiplexer_disconnect_one_raises_error_many_connections(): """Test the case when the multiplexer raises an exception while attempting the disconnection of one connection.""" with LocalNode() as node: tmpdir = Path(tempfile.mktemp()) 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_pbk", node) connection_2 = StubConnection(input_file_path, output_file_path) connection_3 = DummyConnection() 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 multiplexer.connect() assert connection_1.connection_status.is_connected assert connection_2.connection_status.is_connected assert connection_3.connection_status.is_connected with unittest.mock.patch.object(connection_3, "disconnect", side_effect=Exception): # with pytest.raises(AEAConnectionError, match="Failed to disconnect the multiplexer."): multiplexer.disconnect() # TODO is this what we want? assert not connection_1.connection_status.is_connected assert not connection_2.connection_status.is_connected assert connection_3.connection_status.is_connected shutil.rmtree(tmpdir)
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)
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()
def _make_stub_connection(input_file_path: str, output_file_path: str): connection = StubConnection( input_file_path=input_file_path, output_file_path=output_file_path, connection_id=DEFAULT_CONNECTION, ) return connection
def _make_stub_connection(input_file_path: str, output_file_path: str): connection = StubConnection( input_file_path=input_file_path, output_file_path=output_file_path, connection_id=PublicId("fetchai", "stub", "0.1.0"), ) return connection
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()
def _make_stub_connection(input_file_path: str, output_file_path: str): configuration = ConnectionConfig( input_file=input_file_path, output_file=output_file_path, connection_id=StubConnection.connection_id, ) connection = StubConnection(configuration=configuration) return connection
def setup_class(cls): """Set the test up.""" cls.tmpdir = Path(tempfile.mktemp()) d = cls.tmpdir / "test_stub" d.mkdir(parents=True) cls.input_file_path = d / "input_file.csv" cls.output_file_path = d / "input_file.csv" cls.connection = StubConnection(cls.input_file_path, cls.output_file_path) cls.multiplexer = Multiplexer([cls.connection]) cls.multiplexer.connect()
async def test_disconnection_when_already_disconnected(): """Test the case when disconnecting a connection already disconnected.""" tmpdir = Path(tempfile.mktemp()) d = tmpdir / "test_stub" d.mkdir(parents=True) input_file_path = d / "input_file.csv" output_file_path = d / "input_file.csv" stub_con = StubConnection(input_file_path, output_file_path) assert not stub_con.connection_status.is_connected await stub_con.disconnect() assert not stub_con.connection_status.is_connected
def test_connection_from_config(): """Test loading a connection from config file.""" tmpdir = Path(tempfile.mktemp()) d = tmpdir / "test_stub" d.mkdir(parents=True) input_file_path = d / "input_file.csv" output_file_path = d / "input_file.csv" stub_con = StubConnection.from_config( public_key="pk", connection_configuration=ConnectionConfig( input_file=input_file_path, output_file=output_file_path)) assert not stub_con.connection_status.is_connected shutil.rmtree(tmpdir, ignore_errors=True)
async def test_receiving_returns_none_when_error_occurs(): """Test that when we try to receive an envelope and an error occurs we return None.""" tmpdir = Path(tempfile.mktemp()) d = tmpdir / "test_stub" d.mkdir(parents=True) input_file_path = d / "input_file.csv" output_file_path = d / "input_file.csv" stub_con = StubConnection(input_file_path, output_file_path) await stub_con.connect() with unittest.mock.patch.object(stub_con.in_queue, "get", side_effect=Exception): ret = await stub_con.receive() assert ret is None
def setup_class(cls): """Set the test up.""" cls.cwd = os.getcwd() cls.tmpdir = Path(tempfile.mkdtemp()) d = cls.tmpdir / "test_stub" d.mkdir(parents=True) cls.input_file_path = d / "input_file.csv" cls.output_file_path = d / "input_file.csv" connection_id = PublicId("fetchai", "stub", "0.1.0") cls.connection = StubConnection(cls.input_file_path, cls.output_file_path, connection_id=connection_id) cls.multiplexer = Multiplexer([cls.connection]) cls.multiplexer.connect() os.chdir(cls.tmpdir)
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 an addresses identity: identity = Identity(name="my_agent", address="some_address") # Set up the stub connection configuration = ConnectionConfig( input_file_path=INPUT_FILE, output_file_path=OUTPUT_FILE, connection_id=StubConnection.connection_id, ) stub_connection = StubConnection(configuration=configuration, identity=identity) # Create our Agent my_agent = MyAgent(identity, [stub_connection]) # Set the agent running in a different thread try: t = Thread(target=my_agent.start) 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 agent message_text = ( b"my_agent,other_agent,fetchai/default:0.3.0,\x08\x01*\x07\n\x05hello," ) with open(INPUT_FILE, "wb") as f: f.write(message_text) # Wait for the envelope to get processed time.sleep(2) # Read the output envelope generated by the agent with open(OUTPUT_FILE, "rb") as f: print("output message: " + f.readline().decode("utf-8")) finally: # Shut down the agent my_agent.stop() t.join()
async def test_connection_when_already_connected(): """Test the case when connecting a connection already connected.""" 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" stub_con = StubConnection( input_file_path, output_file_path, connection_id=PublicId("fetchai", "stub", "0.1.0"), ) assert not stub_con.connection_status.is_connected await stub_con.connect() assert stub_con.connection_status.is_connected await stub_con.connect() assert stub_con.connection_status.is_connected
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 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
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 test_connection_from_config(self): """Test loading a connection from config file.""" stub_con = StubConnection.from_config( public_key="pk", connection_configuration=ConnectionConfig()) assert not stub_con.connection_status.is_connected
def test_init_no_connection_id(self, *mocks): """Test init no connection ID.""" StubConnection("input_file_path", "output_file_path")