コード例 #1
0
def test_add_key_fails_bad_ledger_id():
    """Test that 'aea add-key' fails because the ledger id is not valid."""
    oldcwd = os.getcwd()
    runner = CliRunner()
    agent_name = "myagent"
    tmpdir = tempfile.mkdtemp()
    os.chdir(tmpdir)
    try:
        result = runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])

        result = runner.invoke(
            cli, [*CLI_LOG_OPTION, "create", "--local", agent_name])
        assert result.exit_code == 0
        os.chdir(Path(tmpdir, agent_name))

        # generate a private key file
        result = runner.invoke(
            cli, [*CLI_LOG_OPTION, "generate-key", FetchAICrypto.identifier])
        assert result.exit_code == 0
        assert Path(FETCHAI_PRIVATE_KEY_FILE).exists()
        bad_ledger_id = "this_is_a_bad_ledger_id"

        result = runner.invoke(cli, [
            *CLI_LOG_OPTION, "add-key", bad_ledger_id, FETCHAI_PRIVATE_KEY_FILE
        ])
        assert result.exit_code == 2

        # check that no key has been added.
        f = open(Path(DEFAULT_AEA_CONFIG_FILE))
        expected_json = yaml.safe_load(f)
        config = AgentConfig.from_json(expected_json)
        assert len(config.private_key_paths.read_all()) == 0
    finally:
        os.chdir(oldcwd)
コード例 #2
0
class CreateCommandTestCase(TestCase):
    """Test case for CLI create command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_create_no_init(self):
        """Test for CLI create no init result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "agent_name", "--author=some"],
            standalone_mode=False,
        )
        self.assertEqual(
            result.exception.message,
            "Author is not set up. Please use 'aea init' to initialize.",
        )

    @patch("aea.cli.create.get_or_create_cli_config", return_value={})
    def test_create_no_author_local(self, *mocks):
        """Test for CLI create no author local result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "--local", "agent_name"],
            standalone_mode=False,
        )
        expected_message = (
            "The AEA configurations are not initialized. "
            "Uses `aea init` before continuing or provide optional argument `--author`."
        )
        self.assertEqual(result.exception.message, expected_message)
コード例 #3
0
def test_local_registry_update():
    """Test local-registry-sync cli command."""
    PACKAGES = [
        PackageId(PackageType.CONNECTION, PublicId("fetchai", "local", "0.11.0")),
        PackageId(PackageType.AGENT, PublicId("fetchai", "my_first_aea", "0.10.0")),
    ]
    with TemporaryDirectory() as tmp_dir:
        for package_id in PACKAGES:
            package_dir = os.path.join(
                tmp_dir,
                package_id.public_id.author,
                str(package_id.package_type.to_plural()),
                package_id.public_id.name,
            )
            os.makedirs(package_dir)
            fetch_package(
                str(package_id.package_type),
                public_id=package_id.public_id,
                cwd=tmp_dir,
                dest=package_dir,
            )

        assert set(PACKAGES) == set([i[0] for i in enlist_packages(tmp_dir)])

        runner = CliRunner()
        with cd(tmp_dir):
            # check intention to upgrade
            with patch(
                "aea.cli.local_registry_sync.replace_package"
            ) as replace_package_mock:
                result = runner.invoke(
                    cli, ["-s", "local-registry-sync"], catch_exceptions=False
                )
                assert result.exit_code == 0, result.stdout
            assert replace_package_mock.call_count == len(PACKAGES)

            # do actual upgrade
            result = runner.invoke(
                cli, ["-s", "local-registry-sync"], catch_exceptions=False
            )
            assert result.exit_code == 0, result.stdout

            # check next update will do nothing
            with patch(
                "aea.cli.local_registry_sync.replace_package"
            ) as replace_package_mock:
                result = runner.invoke(
                    cli, ["-s", "local-registry-sync"], catch_exceptions=False
                )
                assert result.exit_code == 0, result.stdout
            assert replace_package_mock.call_count == 0

        def sort_(packages):
            return sorted(packages, key=lambda x: str(x))

        new_packages = [i[0] for i in enlist_packages(tmp_dir)]

        for new_package, old_package in zip(sort_(new_packages), sort_(PACKAGES)):
            assert new_package.public_id > old_package.public_id
コード例 #4
0
ファイル: test_run.py プロジェクト: yangjue-han/agents-aea
def test_run_multiple_connections(connection_ids):
    """Test that the command 'aea run' works as expected when specifying multiple connections."""
    runner = CliRunner()
    agent_name = "myagent"
    cwd = os.getcwd()
    t = tempfile.mkdtemp()
    # copy the 'packages' directory in the parent of the agent folder.
    shutil.copytree(Path(ROOT_DIR, "packages"), Path(t, "packages"))

    os.chdir(t)
    result = runner.invoke(
        cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
    assert result.exit_code == 0

    result = runner.invoke(cli,
                           [*CLI_LOG_OPTION, "create", "--local", agent_name])
    assert result.exit_code == 0

    os.chdir(Path(t, agent_name))

    result = runner.invoke(cli, [
        *CLI_LOG_OPTION, "add", "--local", "connection", "fetchai/local:0.1.0"
    ])
    assert result.exit_code == 0

    # stub is the default connection, so it should fail
    result = runner.invoke(cli, [
        *CLI_LOG_OPTION, "add", "--local", "connection",
        str(DEFAULT_CONNECTION)
    ])
    assert result.exit_code == 1

    try:
        process = subprocess.Popen(  # nosec
            [
                sys.executable, "-m", "aea.cli", "run", "--connections",
                connection_ids
            ],
            stdout=subprocess.PIPE,
            env=os.environ.copy(),
        )

        time.sleep(5.0)
        sigint_crossplatform(process)
        process.wait(timeout=5)

        assert process.returncode == 0

    finally:
        poll = process.poll()
        if poll is None:
            process.terminate()
            process.wait(2)

        os.chdir(cwd)
        try:
            shutil.rmtree(t)
        except (OSError, IOError):
            pass
コード例 #5
0
ファイル: test_run.py プロジェクト: yangjue-han/agents-aea
def test_run_ethereum_private_key_config():
    """Test that the command 'aea run' works as expected."""
    runner = CliRunner()
    agent_name = "myagent"
    cwd = os.getcwd()
    t = tempfile.mkdtemp()
    # copy the 'packages' directory in the parent of the agent folder.
    shutil.copytree(Path(ROOT_DIR, "packages"), Path(t, "packages"))

    os.chdir(t)
    result = runner.invoke(
        cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
    assert result.exit_code == 0

    result = runner.invoke(cli,
                           [*CLI_LOG_OPTION, "create", "--local", agent_name])
    assert result.exit_code == 0

    os.chdir(Path(t, agent_name))

    result = runner.invoke(cli, [
        *CLI_LOG_OPTION, "add", "--local", "connection", "fetchai/local:0.1.0"
    ])
    assert result.exit_code == 0

    # Load the agent yaml file and manually insert the things we need
    file = open("aea-config.yaml", mode="r")

    # read all lines at once
    whole_file = file.read()

    find_text = "private_key_paths: {}"
    replace_text = """private_key_paths:
    ethereum: default_private_key_not.txt"""

    whole_file = whole_file.replace(find_text, replace_text)

    # close the file
    file.close()

    with open("aea-config.yaml", "w") as f:
        f.write(whole_file)

    error_msg = ""
    try:
        cli.main(
            [*CLI_LOG_OPTION, "run", "--connections", "fetchai/local:0.1.0"])
    except SystemExit as e:
        error_msg = str(e)

    assert error_msg == "1"

    os.chdir(cwd)
    try:
        shutil.rmtree(t)
    except (OSError, IOError):
        pass
コード例 #6
0
def test_invoke_error():
    """Test runner invoke method raises an error."""
    cli_runner = CliRunner()

    with patch.object(cli, "main", side_effect=SystemExit(1)):
        result = cli_runner.invoke(cli, ["--help"])
        assert result.exit_code == 1

    with patch.object(cli, "main", side_effect=SystemExit(object())):
        result = cli_runner.invoke(cli, ["--help"])
        assert result.exit_code == 1
コード例 #7
0
def test_invoke():
    """Test runner invoke method."""
    cli_runner = CliRunner()

    result = cli_runner.invoke(cli, ["--help"])
    assert ("Command-line tool for setting up an Autonomous Economic Agent"
            in result.output)

    result = cli_runner.invoke(cli, "--help")
    assert ("Command-line tool for setting up an Autonomous Economic Agent"
            in result.output)
コード例 #8
0
def test_catch_exception():
    """Test runner invoke method raises an exception and its propogated."""
    cli_runner = CliRunner()

    # True
    with patch.object(cli, "main", side_effect=ValueError("expected")):
        result = cli_runner.invoke(cli, ["--help"])
        assert result.exit_code == 1

    # False

    with pytest.raises(ValueError, match="expected"):
        with patch.object(cli, "main", side_effect=ValueError("expected")):
            result = cli_runner.invoke(cli, ["--help"], catch_exceptions=False)
コード例 #9
0
ファイル: test_list.py プロジェクト: yangjue-han/agents-aea
class ListContractsCommandTestCase(TestCase):
    """Test that the command 'aea list contracts' works as expected."""
    def setUp(self):
        """Set the test up."""
        self.runner = CliRunner()
        self.schema = json.load(open(AGENT_CONFIGURATION_SCHEMA))
        self.resolver = jsonschema.RefResolver(
            "file://{}/".format(Path(CONFIGURATION_SCHEMA_DIR).absolute()),
            self.schema)
        self.validator = Draft4Validator(self.schema, resolver=self.resolver)
        self.cwd = os.getcwd()
        self.t = tempfile.mkdtemp()
        # copy the 'dummy_aea' directory in the parent of the agent folder.
        shutil.copytree(Path(CUR_PATH, "data", "dummy_aea"),
                        Path(self.t, "dummy_aea"))
        os.chdir(Path(self.t, "dummy_aea"))

    @mock.patch("aea.cli.list._get_item_details")
    @mock.patch("aea.cli.utils.formatting.format_items")
    def test_list_contracts_positive(self, *mocks):
        """Test list contracts command positive result."""
        result = self.runner.invoke(cli,
                                    [*CLI_LOG_OPTION, "list", "contracts"],
                                    standalone_mode=False)
        self.assertEqual(result.exit_code, 0)

    def tearDown(self):
        """Tear the test down."""
        os.chdir(self.cwd)
        try:
            shutil.rmtree(self.t)
        except (OSError, IOError):
            pass
コード例 #10
0
class RegisterTestCase(TestCase):
    """Test case for CLI register command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_register_positive(self, do_register_mock):
        """Test for CLI register positive result."""
        username = "******"
        email = "*****@*****.**"
        fake_pwd = "fake_pwd"  # nosec

        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "register",
                "--username={}".format(username),
                "--email={}".format(email),
                "--password={}".format(fake_pwd),
                "--confirm_password={}".format(fake_pwd),
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
        do_register_mock.assert_called_once_with(username, email, fake_pwd,
                                                 fake_pwd)
コード例 #11
0
def test_mix_std_err_False():
    """Test stderr and stdout not mixed."""
    cli_runner = CliRunner(mix_stderr=False)

    result = cli_runner.invoke(cli, "-v DEBUG run")
    assert result.exit_code == 1
    # check for access, no exception should be raised
    result.stderr
コード例 #12
0
def test_mix_std_err_True():
    """Test stderr and stdout are mixed."""
    cli_runner = CliRunner(mix_stderr=True)

    result = cli_runner.invoke(cli, "-v DEBUG run")
    assert result.exit_code == 1

    with pytest.raises(ValueError):
        result.stderr
コード例 #13
0
ファイル: test_run.py プロジェクト: yangjue-han/agents-aea
def test_run_with_default_connection():
    """Test that the command 'aea run' works as expected."""
    runner = CliRunner()
    agent_name = "myagent"
    cwd = os.getcwd()
    t = tempfile.mkdtemp()
    # copy the 'packages' directory in the parent of the agent folder.
    shutil.copytree(Path(ROOT_DIR, "packages"), Path(t, "packages"))

    os.chdir(t)
    result = runner.invoke(
        cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
    assert result.exit_code == 0

    result = runner.invoke(cli,
                           [*CLI_LOG_OPTION, "create", "--local", agent_name])
    assert result.exit_code == 0

    os.chdir(Path(t, agent_name))

    try:
        process = subprocess.Popen(  # nosec
            [sys.executable, "-m", "aea.cli", "run"],
            stdout=subprocess.PIPE,
            env=os.environ.copy(),
        )

        time.sleep(10.0)
        sigint_crossplatform(process)
        process.wait(timeout=20)

        assert process.returncode == 0

    finally:
        poll = process.poll()
        if poll is None:
            process.terminate()
            process.wait(2)

        os.chdir(cwd)
        try:
            shutil.rmtree(t)
        except (OSError, IOError):
            pass
コード例 #14
0
class AddContractCommandTestCase(TestCase):
    """Test that the command 'aea add contract' works as expected."""

    def setUp(self):
        """Set the test up."""
        self.runner = CliRunner()

    @mock.patch("aea.cli.add._add_item")
    def test_add_contract_positive(self, *mocks):
        """Test add contract command positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "contract", "author/name:0.1.0"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "--local", "contract", "author/name:0.1.0"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
コード例 #15
0
def test_add_key_fails_bad_key():
    """Test that 'aea add-key' fails because the key is not valid."""
    oldcwd = os.getcwd()
    runner = CliRunner()
    agent_name = "myagent"
    tmpdir = tempfile.mkdtemp()
    os.chdir(tmpdir)
    try:
        with mock.patch.object(aea.crypto.helpers.logger,
                               "error") as mock_logger_error:

            result = runner.invoke(
                cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])

            result = runner.invoke(
                cli, [*CLI_LOG_OPTION, "create", "--local", agent_name])
            assert result.exit_code == 0
            os.chdir(Path(tmpdir, agent_name))

            # create an empty file - surely not a private key
            pvk_file = "this_is_not_a_key.txt"
            Path(pvk_file).touch()

            result = runner.invoke(cli, [
                *CLI_LOG_OPTION, "add-key", FetchAICrypto.identifier, pvk_file
            ])
            assert result.exit_code == 1
            error_message = "Invalid length of private key, received 0, expected 32"
            mock_logger_error.assert_called_with(
                "This is not a valid private key file: '{}'\n Exception: '{}'".
                format(pvk_file, error_message))

            # check that no key has been added.
            f = open(Path(DEFAULT_AEA_CONFIG_FILE))
            expected_json = yaml.safe_load(f)
            config = AgentConfig.from_json(expected_json)
            assert len(config.private_key_paths.read_all()) == 0
    finally:
        os.chdir(oldcwd)
コード例 #16
0
ファイル: test_logout.py プロジェクト: yangjue-han/agents-aea
class LogoutTestCase(TestCase):
    """Test case for CLI logout command."""

    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_logout_positive(self, update_cli_config_mock, registry_logout_mock):
        """Test for CLI logout positive result."""
        result = self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "logout"], standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
        registry_logout_mock.assert_called_once()
        update_cli_config_mock.assert_called_once()
コード例 #17
0
class FingerprintCommandTestCase(TestCase):
    """Test case for CLI fingerprint command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_fingerprint_positive(self, *mocks):
        """Test for CLI fingerprint positive result."""
        public_id = "author/name:0.1.0"
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "fingerprint", "connection", public_id],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)

        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "fingerprint", "contract", public_id],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)

        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "fingerprint", "protocol", public_id],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)

        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "fingerprint", "skill", public_id],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
コード例 #18
0
ファイル: test_misc.py プロジェクト: yangjue-han/agents-aea
def test_flag_help():
    """Test that the flag '--help' works correctly."""
    runner = CliRunner()
    result = runner.invoke(cli, ["--help"])
    assert (result.stdout == """Usage: aea [OPTIONS] COMMAND [ARGS]...

  Command-line tool for setting up an Autonomous Economic Agent.

Options:
  --version                 Show the version and exit.
  -v, --verbosity LVL       One of NOTSET, DEBUG, INFO, WARNING, ERROR,
                            CRITICAL, OFF

  --skip-consistency-check  Skip consistency check.
  --help                    Show this message and exit.

Commands:
  add              Add a resource to the agent.
  add-key          Add a private key to the wallet.
  config           Read or modify a configuration.
  create           Create an agent.
  delete           Delete an agent.
  fetch            Fetch Agent from Registry.
  fingerprint      Fingerprint a resource.
  freeze           Get the dependencies.
  generate         Generate a resource for the agent.
  generate-key     Generate private keys.
  generate-wealth  Generate wealth for address on test network.
  get-address      Get the address associated with the private key.
  get-wealth       Get the wealth associated with the private key.
  gui              Run the CLI GUI.
  init             Initialize your AEA configurations.
  install          Install the dependencies.
  interact         Interact with a running AEA via the stub connection.
  launch           Launch many agents at the same time.
  list             List the installed resources.
  login            Login to Registry account.
  logout           Logout from Registry account.
  publish          Publish Agent to Registry.
  push             Push item to Registry or save it in local packages.
  register         Register a new Registry account.
  remove           Remove a resource from the agent.
  run              Run the agent.
  scaffold         Scaffold a resource for the agent.
  search           Search for components in the registry.
""")
コード例 #19
0
class TestGui:
    """Test that the command 'aea gui' works as expected."""
    def setup(self):
        """Set the test up."""
        self.runner = CliRunner()
        self.schema = json.load(open(AGENT_CONFIGURATION_SCHEMA))
        self.resolver = jsonschema.RefResolver(
            make_jsonschema_base_uri(
                Path(CONFIGURATION_SCHEMA_DIR).absolute()),
            self.schema,
        )
        self.validator = Draft4Validator(self.schema, resolver=self.resolver)

        self.agent_name = "myagent"
        self.cwd = os.getcwd()
        self.t = tempfile.mkdtemp()
        os.chdir(self.t)
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "init", "--local", "--author", "test_author"],
        )

        assert result.exit_code == 0

    @pytest.mark.flaky(reruns=MAX_FLAKY_RERUNS)
    def test_gui(self):
        """Test that the gui process has been spawned correctly."""
        self.proc = PexpectWrapper(  # nosec
            [sys.executable, "-m", "aea.cli", "-v", "DEBUG", "gui"],
            encoding="utf-8",
            logfile=sys.stdout,
        )
        self.proc.expect_exact(["Running on http://"], timeout=20)

        assert tcpping("127.0.0.1", 8080)

    def teardown(self):
        """Tear the test down."""
        self.proc.terminate()
        self.proc.wait_to_complete(10)
        os.chdir(self.cwd)
        try:
            shutil.rmtree(self.t)
        except OSError:
            pass
コード例 #20
0
ファイル: test_core.py プロジェクト: yangjue-han/agents-aea
class GetAddressCommandTestCase(TestCase):
    """Test case for CLI get_address command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_run_positive(self, *mocks):
        """Test for CLI get_address positive result."""
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "--skip-consistency-check",
                "get-address",
                FetchAICrypto.identifier,
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
コード例 #21
0
class RemoveContractCommandTestCase(TestCase):
    """Test that the command 'aea remove contract' works as expected."""
    def setUp(self):
        """Set the test up."""
        self.runner = CliRunner()

    @mock.patch("aea.cli.remove._remove_item")
    def test_remove_contract_positive(self, *mocks):
        """Test remove contract command positive result."""
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "--skip-consistency-check",
                "remove",
                "contract",
                "author/name:0.1.0",
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
コード例 #22
0
class LoginTestCase(TestCase):
    """Test case for CLI login command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_login_positive(self, update_cli_config_mock, registry_login_mock):
        """Test for CLI login positive result."""
        username, password = ("Username", "Password")
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION, "login", username,
                "--password={}".format(password)
            ],
            standalone_mode=False,
        )
        expected_output = ("Signing in as Username...\n"
                           "Successfully signed in: Username.\n")
        self.assertEqual(result.output, expected_output)
        registry_login_mock.assert_called_once_with(username, password)
        update_cli_config_mock.assert_called_once_with({"auth_token": "token"})
コード例 #23
0
ファイル: test_core.py プロジェクト: yangjue-han/agents-aea
class AddKeyCommandTestCase(TestCase):
    """Test case for CLI add_key command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_run_positive(self, *mocks):
        """Test for CLI add_key positive result."""
        filepath = str(Path(
            ROOT_DIR,
            "setup.py"))  # some existing filepath to pass CLI argument check
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "--skip-consistency-check",
                "add-key",
                FetchAICrypto.identifier,
                filepath,
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
コード例 #24
0
ファイル: test_run.py プロジェクト: yangjue-han/agents-aea
def test_run_unknown_private_key():
    """Test that the command 'aea run' works as expected."""
    runner = CliRunner()
    agent_name = "myagent"
    cwd = os.getcwd()
    t = tempfile.mkdtemp()
    # copy the 'packages' directory in the parent of the agent folder.
    shutil.copytree(Path(ROOT_DIR, "packages"), Path(t, "packages"))

    os.chdir(t)
    result = runner.invoke(
        cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
    assert result.exit_code == 0

    result = runner.invoke(cli,
                           [*CLI_LOG_OPTION, "create", "--local", agent_name])
    assert result.exit_code == 0

    os.chdir(Path(t, agent_name))

    result = runner.invoke(cli, [
        *CLI_LOG_OPTION, "add", "--local", "connection", "fetchai/local:0.1.0"
    ])
    assert result.exit_code == 0
    result = runner.invoke(
        cli,
        [
            *CLI_LOG_OPTION,
            "config",
            "set",
            "agent.default_connection",
            "fetchai/local:0.1.0",
        ],
    )
    assert result.exit_code == 0

    # Load the agent yaml file and manually insert the things we need
    file = open("aea-config.yaml", mode="r")

    # read all lines at once
    whole_file = file.read()

    find_text = "private_key_paths: {}"
    replace_text = """private_key_paths:
        fetchai_not: fet_private_key.txt"""

    whole_file = whole_file.replace(find_text, replace_text)

    # close the file
    file.close()

    with open("aea-config.yaml", "w") as f:
        f.write(whole_file)

    # Private key needs to exist otherwise doesn't get to code path we are interested in testing
    with open("fet_private_key.txt", "w") as f:
        f.write(
            "3801d3703a1fcef18f6bf393fba89245f36b175f4989d8d6e026300dad21e05d")

    result = runner.invoke(
        cli,
        [*CLI_LOG_OPTION, "run", "--connections", "fetchai/local:0.1.0"],
        standalone_mode=False,
    )

    s = "Crypto not registered with id 'fetchai_not'."
    assert result.exception.message == s

    os.chdir(cwd)
    try:
        shutil.rmtree(t)
    except (OSError, IOError):
        pass
コード例 #25
0
ファイル: test_run.py プロジェクト: yangjue-han/agents-aea
def test_run_unknown_ledger():
    """Test that the command 'aea run' works as expected."""
    runner = CliRunner()
    agent_name = "myagent"
    cwd = os.getcwd()
    t = tempfile.mkdtemp()
    # copy the 'packages' directory in the parent of the agent folder.
    shutil.copytree(Path(ROOT_DIR, "packages"), Path(t, "packages"))

    os.chdir(t)
    result = runner.invoke(
        cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
    assert result.exit_code == 0

    result = runner.invoke(cli,
                           [*CLI_LOG_OPTION, "create", "--local", agent_name])
    assert result.exit_code == 0

    os.chdir(Path(t, agent_name))

    result = runner.invoke(cli, [
        *CLI_LOG_OPTION, "add", "--local", "connection", "fetchai/local:0.1.0"
    ])
    assert result.exit_code == 0
    result = runner.invoke(
        cli,
        [
            *CLI_LOG_OPTION,
            "config",
            "set",
            "agent.default_connection",
            "fetchai/local:0.1.0",
        ],
    )
    assert result.exit_code == 0

    # Load the agent yaml file and manually insert the things we need
    file = open("aea-config.yaml", mode="r")

    # read all lines at once
    whole_file = file.read()

    # add in the ledger address
    find_text = "ledger_apis: {}"
    replace_text = """ledger_apis:
    unknown:
        address: https://ropsten.infura.io/v3/f00f7b3ba0e848ddbdc8941c527447fe
        chain_id: 3
        gas_price: 20"""

    whole_file = whole_file.replace(find_text, replace_text)

    # close the file
    file.close()

    with open("aea-config.yaml", "w") as f:
        f.write(whole_file)

    result = runner.invoke(
        cli,
        [*CLI_LOG_OPTION, "run", "--connections", "fetchai/local:0.1.0"],
        standalone_mode=False,
    )

    s = "Unsupported identifier unknown in ledger apis."
    assert result.exception.message == s

    os.chdir(cwd)
    try:
        shutil.rmtree(t)
    except (OSError, IOError):
        pass
コード例 #26
0
ファイル: test_run.py プロジェクト: yangjue-han/agents-aea
def test_run_fet_ledger_apis():
    """Test that the command 'aea run' works as expected."""
    runner = CliRunner()
    agent_name = "myagent"
    cwd = os.getcwd()
    t = tempfile.mkdtemp()
    # copy the 'packages' directory in the parent of the agent folder.
    shutil.copytree(Path(ROOT_DIR, "packages"), Path(t, "packages"))

    os.chdir(t)
    result = runner.invoke(
        cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
    assert result.exit_code == 0

    result = runner.invoke(cli,
                           [*CLI_LOG_OPTION, "create", "--local", agent_name])
    assert result.exit_code == 0

    os.chdir(Path(t, agent_name))

    result = runner.invoke(cli, [
        *CLI_LOG_OPTION, "add", "--local", "connection", "fetchai/local:0.1.0"
    ])
    assert result.exit_code == 0
    result = runner.invoke(
        cli,
        [
            *CLI_LOG_OPTION,
            "config",
            "set",
            "agent.default_connection",
            "fetchai/local:0.1.0",
        ],
    )
    assert result.exit_code == 0

    # Load the agent yaml file and manually insert the things we need
    file = open("aea-config.yaml", mode="r")

    # read all lines at once
    whole_file = file.read()

    # add in the ledger address

    find_text = "ledger_apis: {}"
    replace_text = """ledger_apis:
    fetchai:
        network: testnet"""

    whole_file = whole_file.replace(find_text, replace_text)

    # close the file
    file.close()

    with open("aea-config.yaml", "w") as f:
        f.write(whole_file)

    try:
        process = subprocess.Popen(  # nosec
            [
                sys.executable,
                "-m",
                "aea.cli",
                "run",
                "--connections",
                "fetchai/local:0.1.0",
            ],
            stdout=subprocess.PIPE,
            env=os.environ.copy(),
        )

        time.sleep(10.0)
        sigint_crossplatform(process)
        process.wait(timeout=20)

        assert process.returncode == 0

    finally:
        poll = process.poll()
        if poll is None:
            process.terminate()
            process.wait(2)

        os.chdir(cwd)
        try:
            shutil.rmtree(t)
        except (OSError, IOError):
            pass
コード例 #27
0
ファイル: test_run.py プロジェクト: yangjue-han/agents-aea
def test_run_with_install_deps_and_requirement_file():
    """Test that the command 'aea run --install-deps' with requirement file does not crash."""
    runner = CliRunner()
    agent_name = "myagent"
    cwd = os.getcwd()
    t = tempfile.mkdtemp()
    # copy the 'packages' directory in the parent of the agent folder.
    shutil.copytree(Path(ROOT_DIR, "packages"), Path(t, "packages"))

    os.chdir(t)
    result = runner.invoke(
        cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
    assert result.exit_code == 0

    result = runner.invoke(cli,
                           [*CLI_LOG_OPTION, "create", "--local", agent_name])
    assert result.exit_code == 0

    os.chdir(Path(t, agent_name))

    result = runner.invoke(cli, [
        *CLI_LOG_OPTION, "add", "--local", "connection", "fetchai/local:0.1.0"
    ])
    assert result.exit_code == 0
    result = runner.invoke(
        cli,
        [
            *CLI_LOG_OPTION,
            "config",
            "set",
            "agent.default_connection",
            "fetchai/local:0.1.0",
        ],
    )
    assert result.exit_code == 0

    result = runner.invoke(cli, [*CLI_LOG_OPTION, "freeze"])
    assert result.exit_code == 0
    Path(t, agent_name, "requirements.txt").write_text(result.output)

    try:
        process = PexpectWrapper(
            [
                sys.executable,
                "-m",
                "aea.cli",
                "run",
                "--install-deps",
                "--connections",
                "fetchai/local:0.1.0",
            ],
            env=os.environ,
            maxread=10000,
            encoding="utf-8",
            logfile=sys.stdout,
        )
        process.expect_all(["Start processing messages..."])
        time.sleep(1.0)
        process.control_c()
        process.wait_to_complete(10)
        assert process.returncode == 0

    finally:
        process.terminate()
        process.wait_to_complete(10)
        os.chdir(cwd)
        try:
            shutil.rmtree(t)
        except (OSError, IOError):
            pass
コード例 #28
0
class TestDoInit:
    """Test that the command 'aea init'."""
    @staticmethod
    def random_string(length: int = 8) -> str:
        """Generate random string.

        :param length: how long random string should be

        :return: random chars str
        """
        return "".join(
            random.choice(string.ascii_lowercase)
            for i in range(length)  # nosec
        )

    def setup(self):
        """Set the test up."""
        self.runner = CliRunner()
        self.agent_name = "myagent"
        self.cwd = os.getcwd()
        self.t = tempfile.mkdtemp()
        self.agent_folder = Path(self.t, self.agent_name)
        os.chdir(self.t)
        self.cli_config_file = f"{self.t}/cli_config.yaml"
        self.cli_config_patch = patch("aea.cli.utils.config.CLI_CONFIG_PATH",
                                      self.cli_config_file)
        self.cli_config_patch.start()

    def test_author_local(self):
        """Test author set localy."""
        author = "test_author"
        assert not os.path.exists(self.cli_config_file)

        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "init", "--local", "--author", author],
        )

        assert result.exit_code == 0
        assert "AEA configurations successfully initialized" in result.output
        assert self._read_config()["author"] == "test_author"

    def _read_config(self) -> dict:
        """Read cli config file.

        :return: dict
        """
        with open(self.cli_config_file, "r") as f:
            data = yaml.safe_load(f)
        return data

    def test_already_registered(self):
        """Test author already registered."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "init", "--local", "--author", "author"],
        )
        assert result.exit_code == 0
        result = self.runner.invoke(cli, [*CLI_LOG_OPTION, "init", "--local"])
        assert "AEA configurations already initialized" in result.output

    @patch("aea.cli.register.register_new_account", return_value="TOKEN")
    def test_non_local(self, mock):
        """Test registration online."""
        email = f"{self.random_string()}@{self.random_string()}.com"
        pwd = self.random_string()
        author = "test_author" + self.random_string()
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "init", "--author", author],
            input=f"n\n{email}\n{pwd}\n{pwd}\n\n",
            mix_stderr=True,
        )
        assert result.exit_code == 0, result.output
        assert "Successfully registered" in result.output

        config = self._read_config()
        assert config["author"] == author
        assert config["auth_token"] == "TOKEN"

    @patch("aea.cli.init.do_login", return_value=None)
    def test_registered(self, *mocks):
        """Test author already registered."""
        author = "test_author" + self.random_string()
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "init", "--author", author],
            input="y\nsome fake password\n",
        )

        assert result.exit_code == 0

    @patch("aea.cli.init.is_auth_token_present", return_value=True)
    @patch("aea.cli.init.check_is_author_logged_in", return_value=True)
    def test_already_logged_in(self, *mocks):
        """Registered and logged in (has token)."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "init", "--author", "test_author"],
            mix_stderr=True,
        )
        assert result.exit_code == 0

    def teardown(self):
        """Tear the test down."""
        self.cli_config_patch.stop()
        os.chdir(self.cwd)
        shutil.rmtree(self.t)
コード例 #29
0
class TestMultiplexerDisconnectsOnTermination:  # pylint: disable=attribute-defined-outside-init
    """Test multiplexer disconnects on  agent process keyboard interrupted."""
    def setup(self):
        """Set the test up."""
        self.proc = None
        self.runner = CliRunner()
        self.agent_name = "myagent"
        self.cwd = os.getcwd()
        self.t = tempfile.mkdtemp()
        shutil.copytree(Path(ROOT_DIR, "packages"), Path(self.t, "packages"))
        os.chdir(self.t)
        self.key_path = os.path.join(self.t, "fetchai_private_key.txt")
        self.conn_key_path = os.path.join(self.t, "conn_private_key.txt")

        result = self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
        assert result.exit_code == 0

        result = self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "create", "--local", self.agent_name])
        assert result.exit_code == 0

        os.chdir(Path(self.t, self.agent_name))

    def test_multiplexer_disconnected_on_early_interruption(self):
        """Test multiplexer disconnected properly on termination before connected."""
        result = self.runner.invoke(cli, [
            *CLI_LOG_OPTION, "add", "--local", "connection",
            str(P2P_PUBLIC_ID)
        ])
        assert result.exit_code == 0, result.stdout_bytes

        result = self.runner.invoke(cli, [*CLI_LOG_OPTION, "build"])
        assert result.exit_code == 0, result.stdout_bytes

        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "generate-key", DEFAULT_LEDGER, self.key_path])
        assert result.exit_code == 0, result.stdout_bytes

        result = self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "add-key", DEFAULT_LEDGER, self.key_path])
        assert result.exit_code == 0, result.stdout_bytes

        result = self.runner.invoke(cli, [
            *CLI_LOG_OPTION, "generate-key", DEFAULT_LEDGER, self.conn_key_path
        ])
        assert result.exit_code == 0, result.stdout_bytes

        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "add-key",
                DEFAULT_LEDGER,
                self.conn_key_path,
                "--connection",
            ],
        )
        assert result.exit_code == 0, result.stdout_bytes

        result = self.runner.invoke(cli,
                                    [*CLI_LOG_OPTION, "issue-certificates"])
        assert result.exit_code == 0, result.stdout_bytes

        self.proc = PexpectWrapper(  # nosec
            [sys.executable, "-m", "aea.cli", "-v", "DEBUG", "run"],
            env=os.environ,
            maxread=10000,
            encoding="utf-8",
            logfile=sys.stdout,
        )

        self.proc.expect_all(
            ["Starting libp2p node..."],
            timeout=50,
        )
        self.proc.control_c()
        self.proc.expect_all(
            ["Multiplexer .*disconnected."],
            timeout=20,
            strict=False,
        )

        self.proc.expect_all(
            [EOF],
            timeout=20,
        )

    def test_multiplexer_disconnected_on_termination_after_connected_no_connection(
        self, ):
        """Test multiplexer disconnected properly on termination after connected."""
        self.proc = PexpectWrapper(  # nosec
            [sys.executable, "-m", "aea.cli", "-v", "DEBUG", "run"],
            env=os.environ,
            maxread=10000,
            encoding="utf-8",
            logfile=sys.stdout,
        )

        self.proc.expect_all(
            ["Start processing messages..."],
            timeout=20,
        )
        self.proc.control_c()
        self.proc.expect_all(
            ["Multiplexer disconnecting...", "Multiplexer disconnected.", EOF],
            timeout=20,
        )

    def test_multiplexer_disconnected_on_termination_after_connected_one_connection(
        self, ):
        """Test multiplexer disconnected properly on termination after connected."""

        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION, "add", "--local", "connection",
                str(STUB_CONNECTION_ID)
            ],
        )
        assert result.exit_code == 0, result.stdout_bytes

        self.proc = PexpectWrapper(  # nosec
            [sys.executable, "-m", "aea.cli", "-v", "DEBUG", "run"],
            env=os.environ,
            maxread=10000,
            encoding="utf-8",
            logfile=sys.stdout,
        )

        self.proc.expect_all(
            ["Start processing messages..."],
            timeout=20,
        )
        self.proc.control_c()
        self.proc.expect_all(
            ["Multiplexer disconnecting...", "Multiplexer disconnected.", EOF],
            timeout=20,
        )

    def teardown(self):
        """Tear the test down."""
        if self.proc:
            self.proc.wait_to_complete(10)
        os.chdir(self.cwd)
        try:
            shutil.rmtree(self.t)
        except (OSError, IOError):
            pass
コード例 #30
0
class TestProjectAndAgentAlias:
    """Check project and agent alias."""

    def setup(self):
        """Set the test up."""
        self.cwd = os.getcwd()
        self.t = tempfile.mkdtemp()
        os.chdir(self.t)
        self.runner = CliRunner()
        self.project_public_id = MY_FIRST_AEA_PUBLIC_ID
        self.project_path = os.path.join(
            self.t, self.project_public_id.author, self.project_public_id.name
        )

    def _test_project(self, is_local: bool, skip_consistency_check: bool):
        """Test method to handle both local and remote registry."""
        registry_path = os.path.join(ROOT_DIR, "packages")
        project = Project.load(
            self.t,
            self.project_public_id,
            is_local=is_local,
            registry_path=registry_path,
            skip_consistency_check=skip_consistency_check,
        )
        assert os.path.exists(self.project_path)

        with cd(self.project_path):
            result = self.runner.invoke(
                cli,
                ["--skip-consistency-check", "config", "get", "agent.agent_name"],
                catch_exceptions=False,
                standalone_mode=False,
            )
        assert self.project_public_id.name in result.output
        project.remove()
        assert not os.path.exists(self.project_path)

    def test_project_local(self):
        """Test project loaded and removed, from local registry."""
        self._test_project(True, False)

    @pytest.mark.integration
    @pytest.mark.flaky(reruns=MAX_FLAKY_RERUNS)
    def test_project_remote(self):
        """Test project loaded and removed, from remove registry."""
        self.project_public_id = MY_FIRST_AEA_PUBLIC_ID.to_latest()
        self._test_project(False, True)

    def test_agents(self):
        """Test agent added to project and rmeoved."""
        project = Project(self.project_public_id, self.project_path)
        alias = AgentAlias(project, "test", [], Mock(), Mock())
        assert project.agents
        alias.remove_from_project()
        assert not project.agents

    def teardown(self):
        """Tear dowm the test."""
        os.chdir(self.cwd)
        try:
            shutil.rmtree(self.t)
        except (OSError, IOError):
            pass