예제 #1
0
class CheckFileNotExistsTestCase(TestCase):
    """Test case for CLI add_key command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_file_specified_does_not_exist(self, *mocks):
        """Test for CLI add_key fails on file not exists."""
        with pytest.raises(BadParameter, match=r"File '.*' does not exist."):
            self.runner.invoke(
                cli,
                [
                    *CLI_LOG_OPTION,
                    "--skip-consistency-check",
                    "add-key",
                    FETCHAI,
                    "somefile",
                ],
                standalone_mode=False,
                catch_exceptions=False,
            )

    def test_file_not_specified_does_not_exist(self, *mocks):
        """Test for CLI add_key fails on file not exists."""
        with pytest.raises(BadParameter, match=r"File '.*' does not exist."):
            self.runner.invoke(
                cli,
                [
                    *CLI_LOG_OPTION, "--skip-consistency-check", "add-key",
                    FETCHAI
                ],
                standalone_mode=False,
                catch_exceptions=False,
            )
예제 #2
0
def test_fetch_twice_remote():
    """Test fails on fetch if dir exists."""
    with TemporaryDirectory() as tmp_dir:
        with cd(tmp_dir):
            name = "my_first_aea"
            runner = CliRunner()
            result = runner.invoke(
                cli,
                [
                    "--registry-path",
                    PACKAGES_DIR,
                    "fetch",
                    "--local",
                    "fetchai/my_first_aea",
                ],
                catch_exceptions=False,
            )
            assert result.exit_code == 0, result.stdout
            assert os.path.exists(name)

            with pytest.raises(
                ClickException,
                match='Item "my_first_aea" already exists in target folder.',
            ):
                result = runner.invoke(
                    cli,
                    ["fetch", "--remote", "fetchai/my_first_aea"],
                    standalone_mode=False,
                    catch_exceptions=False,
                )
예제 #3
0
class TestSearchContractsLocal(TestCase):
    """Test that the command 'aea search contracts' works as expected."""
    def setUp(self):
        """Set the test up."""
        self.runner = CliRunner()

    @mock.patch("aea.cli.search.format_items",
                return_value=FORMAT_ITEMS_SAMPLE_OUTPUT)
    @mock.patch("aea.cli.search._search_items_locally", return_value=["item1"])
    def test_search_contracts_positive(self, *mocks):
        """Test search contracts command positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "search", "--local", "contracts"],
            standalone_mode=False,
        )
        assert result.output == ('Searching for ""...\n'
                                 "Contracts found:\n\n"
                                 "{}\n".format(FORMAT_ITEMS_SAMPLE_OUTPUT))

    @mock.patch("aea.cli.search.format_items",
                return_value=FORMAT_ITEMS_SAMPLE_OUTPUT)
    @mock.patch("aea.cli.search.request_api", return_value=["item1"])
    def test_search_contracts_registry_positive(self, *mocks):
        """Test search contracts in registry command positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "search", "contracts"],
            standalone_mode=False,
        )
        assert result.output == ('Searching for ""...\n'
                                 "Contracts found:\n\n"
                                 "{}\n".format(FORMAT_ITEMS_SAMPLE_OUTPUT))
예제 #4
0
class ListAllCommandTestCase(TestCase):
    """Test case for aea list all command."""

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

    @mock.patch("aea.cli.list.list_agent_items", return_value=[])
    @mock.patch("aea.cli.list.format_items")
    @mock.patch("aea.cli.utils.decorators._check_aea_project")
    def test_list_all_no_details_positive(self, *mocks):
        """Test list all command no details positive result."""
        result = self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "list", "all"], standalone_mode=False
        )
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output, "")

    @mock.patch("aea.cli.list.list_agent_items", return_value=[{"name": "some"}])
    @mock.patch("aea.cli.list.format_items", return_value="correct")
    @mock.patch("aea.cli.utils.decorators._check_aea_project")
    def test_list_all_positive(self, *mocks):
        """Test list all command positive result."""
        result = self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "list", "all"], standalone_mode=False
        )
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(
            result.output,
            "Connections:\ncorrect\nContracts:\ncorrect\n"
            "Protocols:\ncorrect\nSkills:\ncorrect\n",
        )
예제 #5
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", FETCHAI])
        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)
예제 #6
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)
예제 #7
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)
예제 #8
0
class TestFreeze:
    """Test that the command 'aea freeze' works as expected."""
    def setup(self):
        """Set the test up."""
        self.schema = json.load(open(AGENT_CONFIGURATION_SCHEMA))
        self.resolver = jsonschema.RefResolver(
            make_jsonschema_base_uri(Path(CONFIGURATION_SCHEMA_DIR)),
            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"))
        self.runner = CliRunner()
        os.chdir(Path(self.t, "dummy_aea"))
        self.result = self.runner.invoke(cli, [*CLI_LOG_OPTION, "freeze"],
                                         standalone_mode=False)

    @pytest.mark.flaky(reruns=MAX_FLAKY_RERUNS)
    def test_exit_code_equal_to_zero_and_correct_output(self):
        """Assert that the exit code is equal to zero (i.e. success)."""
        assert self.result.exit_code == 0
        """Test that the command has printed the correct output."""
        assert self.result.output == """protobuf\nvyper==0.1.0b12\n"""

    def teardown(self):
        """Tear the test down."""
        os.chdir(self.cwd)
        try:
            shutil.rmtree(self.t)
        except (OSError, IOError):
            pass
예제 #9
0
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.list_agent_items")
    @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
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()
    dir_path = Path("packages")
    tmp_dir = tmpdir / dir_path
    src_dir = oldcwd / Path(ROOT_DIR, dir_path)
    shutil.copytree(str(src_dir), str(tmp_dir))
    os.chdir(tmpdir)
    try:
        with mock.patch.object(
            aea.crypto.helpers._default_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", FETCHAI, 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
                ),
                exc_info=True,
            )

            # 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)
예제 #11
0
class FetchCommandTestCase(TestCase):
    """Test case for CLI fetch command."""

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

    def test_fetch_positive(self, *mocks):
        """Test for CLI push connection positive result."""
        self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "fetch", "author/name:0.1.0"], standalone_mode=False,
        )
        self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "fetch", "--local", "author/name:0.1.0"],
            standalone_mode=False,
        )
예제 #12
0
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 (AEA).

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

  -s, --skip-consistency-check  Skip consistency checks of agent during command
                                execution.

  --registry-path DIRECTORY     Provide a local registry directory full path.
  --help                        Show this message and exit.

Commands:
  add                  Add a package to the agent.
  add-key              Add a private key to the wallet of the agent.
  build                Build the agent and its components.
  config               Read or modify a configuration of the agent.
  create               Create a new agent.
  delete               Delete an agent.
  eject                Eject a vendor package of the agent.
  fetch                Fetch an agent from the registry.
  fingerprint          Fingerprint a non-vendor package of the agent.
  freeze               Get the dependencies of the agent.
  generate             Generate a package for the agent.
  generate-key         Generate a private key and place it in a file.
  generate-wealth      Generate wealth for the agent on a test network.
  get-address          Get the address associated with a private key of the...
  get-multiaddress     Get the multiaddress associated with a private key or...
  get-wealth           Get the wealth associated with the private key of the...
  gui                  Run the CLI GUI.
  init                 Initialize your AEA configurations.
  install              Install the dependencies of the agent.
  interact             Interact with the running agent via the stub...
  issue-certificates   Issue certificates for connections that require them.
  launch               Launch many agents at the same time.
  list                 List the installed packages of the agent.
  local-registry-sync  Upgrade the local package registry.
  login                Login to the registry account.
  logout               Logout from the registry account.
  publish              Publish the agent to the registry.
  push                 Push a non-vendor package of the agent to the registry.
  register             Create a new registry account.
  remove               Remove a package from the agent.
  remove-key           Remove a private key from the wallet of the agent.
  reset_password       Reset the password of the registry account.
  run                  Run the agent.
  scaffold             Scaffold a package for the agent.
  search               Search for packages in the registry.
  transfer             Transfer wealth associated with a private key of the...
  upgrade              Upgrade the packages of the agent.
""")
예제 #13
0
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
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 = PexpectWrapper(  # nosec
            [sys.executable, "-m", "aea.cli", "run"],
            env=os.environ.copy(),
            maxread=10000,
            encoding="utf-8",
            logfile=sys.stdout,
        )

        process.expect("Start processing messages", timeout=10)
        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
예제 #15
0
class TestPushVersionsMismatch(TestCase):
    """Test that the command 'aea push contract' works as expected."""

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

    def test_push_local_version_check_failed(self, *mocks):
        """Test push contract command positive result."""
        with mock.patch(
            "aea.cli.registry.push.load_component_public_id",
            return_value=PublicId("author", "name", "1000.0.0"),
        ):
            with pytest.raises(
                ClickException, match="Version, name or author does not match."
            ):
                self.runner.invoke(
                    cli,
                    [
                        *CLI_LOG_OPTION,
                        "push",
                        "--local",
                        "contract",
                        "author/name:0.1.0",
                    ],
                    standalone_mode=False,
                    catch_exceptions=False,
                )

    def test_push_remote_version_check_failed(self, *mocks):
        """Test push contract command positive result."""
        with mock.patch(
            "aea.cli.registry.push.load_component_public_id",
            return_value=PublicId("author", "name", "1000.0.0"),
        ):
            with pytest.raises(
                ClickException, match="Version, name or author does not match."
            ):
                self.runner.invoke(
                    cli,
                    [*CLI_LOG_OPTION, "push", "contract", "author/name:0.1.0"],
                    standalone_mode=False,
                    catch_exceptions=False,
                )
예제 #16
0
class PublishCommandTestCase(TestCase):
    """Test case for CLI publish command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_publish_positive(self, *mocks):
        """Test for CLI publish positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "publish"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "publish", "--local"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
예제 #17
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)
예제 #18
0
class PushContractCommandTestCase(TestCase):
    """Test that the command 'aea push contract' works as expected."""

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

    @mock.patch("aea.cli.push._save_item_locally")
    def test_push_contract_positive(self, *mocks):
        """Test push contract command positive result."""
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "--skip-consistency-check",
                "push",
                "--local",
                "contract",
                "author/name:0.1.0",
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)

    @mock.patch("aea.cli.push.push_item")
    def test_push_contract_registry_positive(self, *mocks):
        """Test push contract to registry command positive result."""
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "--skip-consistency-check",
                "push",
                "contract",
                "author/name:0.1.0",
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
예제 #19
0
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

  -s, --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.
  eject             Eject an installed item.
  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-multiaddress  Get the multiaddress associated with a private key or...
  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.
  reset_password    Reset password of Registry account.
  run               Run the agent.
  scaffold          Scaffold a resource for the agent.
  search            Search for components in the registry.
  transfer          Get the wealth associated with the private key.
  upgrade           Upgrade agent's component.
""")
예제 #20
0
class ScaffoldContractCommandTestCase(TestCase):
    """Test case for CLI scaffold contract command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_scaffold_contract_command_positive(self, *mocks):
        """Test for CLI scaffold contract command for positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "scaffold", "contract", "contract_name"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
예제 #21
0
class ScaffoldDecisionMakerHandlerTestCase(TestCase):
    """Test case for CLI scaffold decision maker handler command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_scaffold_decision_maker_handler_command_positive(self, *mocks):
        """Test for CLI scaffold decision maker handler command for positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "scaffold", "decision-maker-handler"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
예제 #22
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)
예제 #23
0
class ResetPasswordTestCase(TestCase):
    """Test case for CLI reset_password command."""

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

    def test_reset_password_positive(self, registry_reset_password_mock):
        """Test for CLI reset_password positive result."""
        email = "*****@*****.**"
        result = self.runner.invoke(
            cli, [*CLI_LOG_OPTION, "reset_password", email], standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
        registry_reset_password_mock.assert_called_once_with(email)
예제 #24
0
class PushCommandTestCase(TestCase):
    """Test case for CLI push command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

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

    def test_push_protocol_positive(self, *mocks):
        """Test for CLI push protocol positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "push", "protocol", "author/name:0.1.0"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION, "push", "--local", "protocol",
                "author/name:0.1.0"
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)

    def test_push_skill_positive(self, *mocks):
        """Test for CLI push skill positive result."""
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "push", "skill", "author/name:0.1.0"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
        result = self.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "push", "--local", "skill", "author/name:0.1.0"],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
예제 #25
0
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()
예제 #26
0
class GetWealthCommandTestCase(TestCase):
    """Test case for CLI get_wealth command."""
    def setUp(self):
        """Set it up."""
        self.runner = CliRunner()

    def test_run_positive(self, *mocks):
        """Test for CLI get_wealth positive result."""
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION, "--skip-consistency-check", "get-wealth",
                FETCHAI
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
예제 #27
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)
예제 #28
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"})
예제 #29
0
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",
                FETCHAI,
                filepath,
            ],
            standalone_mode=False,
        )
        self.assertEqual(result.exit_code, 0)
예제 #30
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",
        )
        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"],
        )
        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)