Beispiel #1
0
def test_list(capsys):
    with ArgvContext(CMD, 'list'), pytest.raises(SystemExit) as rc:
        alfaci.cli.main()
    captured = capsys.readouterr().out
    actual = len(captured.splitlines())
    assert actual == 2
    assert rc.value.code == 0
Beispiel #2
0
 def test_aws_cli_version_fail(self):
     when(cli).invoke(contains('aws --version')).thenReturn(
         (False, 'does-not-matter'))
     with ArgvContext(program, '-p', 'dev',
                      '-t'), self.assertRaises(SystemExit) as x:
         cli.main()
     self.assertEqual(x.exception.code, 1)
Beispiel #3
0
    def test_source_profile_region_mismatch(self):
        with ArgvContext(program, '-t', '-p', 'dev'):
            # clean up as going to mutate this
            self.config.close()
            # now start new test case
            self.config = tempfile.NamedTemporaryFile()
            conf_ini = b"""
            [default]
            sso_start_url = https://petshop.awsapps.com/start
            sso_region = us-east-1
            sso_account_id = 123456789
            sso_role_name = Engineering
            region = us-east-1
            output = json

            [profile dev]
            role_arn = arn:aws:iam::456789123:role/FullAdmin
            source_profile = default
            region = ap-southeast-2
            output = json
            """
            self.config.write(conf_ini)
            self.config.seek(0)
            self.config.read()
            cli.aws_config_file = self.config.name
            cli.main()
        cred = cli.read_config(self.credentials.name)
        tok_now = cred['dev']['aws_session_token']
        self.assertEqual(tok_now, 'tok')  # assert no update
        verify(cli, times=1).invoke(...)
Beispiel #4
0
    def test_source_profile_not_sso(self):
        with ArgvContext(program, '-t'):
            # clean up as going to mutate this
            self.config.close()
            # now start new test case
            self.config = tempfile.NamedTemporaryFile()
            conf_ini = b"""
            [default]
            region = ap-southeast-2
            output = json

            [profile dev]
            role_arn = arn:aws:iam::456789123:role/FullAdmin
            source_profile = default
            region = ap-southeast-2
            output = json
            """
            self.config.write(conf_ini)
            self.config.seek(0)
            self.config.read()
            cli.aws_config_file = self.config.name
            cli.main()
        cred = cli.read_config(self.credentials.name)
        tok_now = cred['dev']['aws_session_token']
        self.assertEqual(tok_now, 'tok')  # assert no update
        verify(cli, times=1).invoke(...)
Beispiel #5
0
    def test_main(self):
        with ArgvContext(program, '-p', 'dev', '--debug'):
            output = {
                'roleCredentials': {
                    'accessKeyId': 'AAAA4IGTCPYNIZGVJCVW',
                    'secretAccessKey':
                    '00GGc0cDG6WzbJIcDlw/gh0BaMOCKK0M/qDtDxR1',
                    'sessionToken': 'VeryLongBase664String==',
                    'expiration': datetime.utcnow().timestamp()
                }
            }
            success = True
            cli_v2 = 'aws-cli/2.0.9 Python/3.8.2 Darwin/19.4.0 botocore/2.0.0dev13 (MOCK)'
            when(cli).invoke(contains('aws --version')).thenReturn(
                (success, cli_v2))
            when(cli).invoke(
                contains('aws sts get-caller-identity')).thenReturn(
                    (success, 'does-not-matter'))
            when(cli).invoke(
                contains('aws sso get-role-credentials')).thenReturn(
                    (success, json.dumps(output)))

            cli.main()

            cred = cli.read_config(self.credentials.name)
            new_tok = cred['dev']['aws_session_token']
            self.assertNotEqual(new_tok, 'tok')
            self.assertEqual(new_tok, 'VeryLongBase664String==')
            verify(cli, times=3).invoke(...)
Beispiel #6
0
def test_filterversion_pypy(mock_namespaces):
    """
    Does filtering by Python version work when run with PyPy?
    """
    with ArgvContext('pyclean', '--legacy', '-V', '2.7', '-p', 'python-apt'):
        pyclean.cli.main()

    assert mock_namespaces.called
Beispiel #7
0
def test_default_modern(mock_modern_pyclean):
    """
    Does simply calling `pyclean` invoke the modern implementation?
    """
    with ArgvContext('pyclean', 'foo'):
        pyclean.cli.main()

    assert mock_modern_pyclean.called
Beispiel #8
0
def test_legacy_calls_compat(mock_get_implementation):
    """
    Does calling `pyclean --legacy` invoke the compat layer?
    """
    with ArgvContext('pyclean', '--legacy', 'foo'):
        pyclean.cli.main()

    assert mock_get_implementation.called
Beispiel #9
0
 def test_ca_bundle(self):
     with ArgvContext(program, '-p', 'ca_bundle', '-t'):
         cli.main()
         cred = cli.read_config(self.credentials.name)
         new_tok = cred['ca_bundle']['aws_session_token']
         self.assertNotEqual(new_tok, 'tok')
         self.assertEqual(new_tok, 'VeryLongBase664String==')
         verify(cli, times=2).invoke(...)
Beispiel #10
0
 def test_credential_not_found_2(self):
     when(pathlib.Path).mkdir(...).thenRaise(
         Exception("mock.credentials.file.exception"))
     with ArgvContext(program, '-d', '-p',
                      'dev'), self.assertRaises(SystemExit) as x:
         cli.aws_shared_credentials_file = "mock.credentials"
         cli.main()
     self.assertEqual(x.exception.code, 1)
def test_cli_command(mock_command):
    """
    Is the correct code called when invoked via the CLI?
    """
    with ArgvContext('foobar', 'baz'), pytest.raises(SystemExit):
        foobar.cli.main()

    assert mock_command.called
def test_fail_without_url():
    message_regex = "Error: Missing option '--rancher-url'."
    runner = CliRunner()
    with EnvironContext(RANCHER_URL=None), \
            ArgvContext('ranchertool'):
        result = runner.invoke(cli.main)
        assert result.exit_code == 2
        assert message_regex in result.output
Beispiel #13
0
 def test_print_export_vars_fail(self):
     when(cli).update_profile(...).thenReturn(None)
     with ArgvContext(program, '-e', '-t', '-p', 'dev'):
         cli.main()
     cred = cli.read_config(self.credentials.name)
     tok_now = cred['dev']['aws_session_token']
     self.assertEqual(tok_now, 'tok')  # assert no update
     verify(cli, times=1).invoke(...)
Beispiel #14
0
 def test_print_export_vars(self):
     with ArgvContext(program, '-e', '-p', 'dev'):
         cli.main()
     cred = cli.read_config(self.credentials.name)
     new_tok = cred['dev']['aws_session_token']
     self.assertNotEqual(new_tok, 'tok')
     self.assertEqual(new_tok, 'VeryLongBase664String==')
     verify(cli, times=3).invoke(...)
Beispiel #15
0
def test_clean_package_pypy(mock_namespaces):
    """
    Does collecting/traversing packages for cleaning work for PyPy?
    """
    with ArgvContext('pyclean', '--legacy', '-p', 'python-apt'):
        pyclean.cli.main()

    assert mock_namespaces.called
Beispiel #16
0
 def test_aws_cli_v1(self):
     with ArgvContext(program, '-p', 'dev',
                      '-t'), self.assertRaises(SystemExit) as x:
         mock_cli_v1 = 'aws-cli/1.18.61 Python/2.7.17 Linux/5.3.0-1020-azure botocore/1.16.11 (MOCK v1)'
         when(cli).invoke(contains('aws --version')).thenReturn(
             (True, mock_cli_v1))
         cli.main()
     self.assertEqual(x.exception.code, 1)
Beispiel #17
0
 def test_clipboard_export_vars_2(self):
     when(cli.importlib_util).find_spec("pyperclip").thenReturn(None)
     with ArgvContext(program, '-t', '-e', '-p', 'dev'):
         cli.main()
     cred = cli.read_config(self.credentials.name)
     new_tok = cred['dev']['aws_session_token']
     self.assertNotEqual(new_tok, 'tok')
     self.assertEqual(new_tok, 'VeryLongBase664String==')
     verify(cli, times=2).invoke(...)
Beispiel #18
0
def test_entrypoint_pypy_working(mock_import_module):
    """
    Is entrypoint overriding with PyPy implementation?
    """
    with ArgvContext('pypyclean', 'foo'):
        pyclean.cli.pypyclean()

    args, _ = mock_import_module.call_args
    assert args == ('pyclean.pypyclean',)
Beispiel #19
0
 def test_login_command_default(self):
     when(cli).poll(contains('aws sso login'), ...).thenReturn(True)
     with ArgvContext(program, '-t', 'login'):
         cli.main()
     cred = cli.read_config(self.credentials.name)
     new_tok = cred['default']['aws_session_token']
     self.assertNotEqual(new_tok, 'tok')
     self.assertEqual(new_tok, 'VeryLongBase664String==')
     verify(cli, times=1).poll(...)
Beispiel #20
0
 def test_profile_prefix(self):
     with ArgvContext(program, '-p', 'lab*', 'lab', 'zzz', '--trace'):
         cli.main()
         cred = cli.read_config(self.credentials.name)
         new_tok = cred['lab']['aws_session_token']
         self.assertNotEqual(new_tok, 'tok')
         self.assertEqual(new_tok, 'VeryLongBase664String==')
         self.assertEqual(4, len(cli.profiles))
         verify(cli, times=7).invoke(...)
Beispiel #21
0
 def test_credential_not_found(self):
     tmp_file = tempfile.NamedTemporaryFile()
     tmp_name = tmp_file.name
     tmp_file.close()
     with ArgvContext(program, '-d', '-p', 'dev'):
         cli.aws_shared_credentials_file = tmp_name
         cli.main()
     cred = cli.read_config(cli.aws_shared_credentials_file)
     tok_now = cred['dev']['aws_session_token']
     self.assertEqual(tok_now, 'VeryLongBase664String==')
Beispiel #22
0
 def test_login_command_fail(self):
     when(cli).poll(contains('aws sso login'), ...).thenReturn(False)
     with ArgvContext(program, '-t', 'login', '--profile', 'dev',
                      '--this'), self.assertRaises(SystemExit) as x:
         cli.main()
     self.assertEqual(x.exception.code, 1)
     cred = cli.read_config(self.credentials.name)
     tok_now = cred['dev']['aws_session_token']
     self.assertEqual(tok_now, 'tok')  # assert no update
     verify(cli, times=1).invoke(...)
Beispiel #23
0
def test_init(caplog, mock_cwd):
    """Check return value and log message"""
    caplog.set_level(logging.INFO, logger='alfaci.cli')
    with ArgvContext(CMD, 'init'), pytest.raises(SystemExit) as rc:
        alfaci.cli.main()
    assert len(caplog.records) == 1
    captured = caplog.records[0].message.strip()
    loc = mock_cwd / '.alfa-ci'
    expected = 'Initialized empty alfa-ci repository in %s' % loc
    assert captured == expected
    assert rc.value.code == 0
Beispiel #24
0
 def test_login_command_export_vars_2(self):
     when(cli).poll(contains('aws sso login'), ...).thenReturn(True)
     with ArgvContext(program, '-t', '-e',
                      'login'), self.assertRaises(SystemExit) as x:
         cli.main()
     self.assertEqual(x.exception.code, 0)
     cred = cli.read_config(self.credentials.name)
     new_tok = cred['default']['aws_session_token']
     self.assertNotEqual(new_tok, 'tok')
     self.assertEqual(new_tok, 'VeryLongBase664String==')
     verify(cli, times=1).poll(...)
Beispiel #25
0
def test_argv_context():
    """
    Test if ArgvContext sets the right argvs and resets to the old correctly
    """
    old = sys.argv
    new = ["Alice", "Bob", "Chris", "Daisy"]

    assert sys.argv == old

    with ArgvContext(*new):
        assert sys.argv == new, \
            "sys.argv wasn't correctly changed by the contextmanager"

    assert sys.argv == old, "sys.argv wasn't correctly reset"
Beispiel #26
0
 def test_sso_cache_not_json(self):
     with ArgvContext(program, '-p', 'dev',
                      '-t'), self.assertRaises(SystemExit) as x:
         # clean up as going to mutate this
         self.sso_cache_json.close()
         self.sso_cache_dir.cleanup()
         # start new test case
         self.sso_cache_dir = tempfile.TemporaryDirectory()
         self.sso_cache_json = tempfile.NamedTemporaryFile(
             dir=self.sso_cache_dir.name, suffix='.txt')
         self.sso_cache_json.seek(0)
         self.sso_cache_json.read()
         cli.aws_sso_cache_path = self.sso_cache_dir.name
         cli.main()
     self.assertEqual(x.exception.code, 1)
Beispiel #27
0
 def test_not_sso_profile(self):
     with ArgvContext(program, '-d'), self.assertRaises(SystemExit) as x:
         # clean up as going to mutate this
         self.config.close()
         # now start new test case
         self.config = tempfile.NamedTemporaryFile()
         conf_ini = b"""
         [default]
         region = ap-southeast-2
         output = json
         """
         self.config.write(conf_ini)
         self.config.seek(0)
         self.config.read()
         cli.AWS_CONFIG_PATH = self.config.name
         cli.main()
     self.assertEqual(x.exception.code, 1)
Beispiel #28
0
    def test_source_profile_eager_sync(self):
        with ArgvContext(program, '-t', '-p', 'dev'):
            self.credentials.close()
            self.credentials = tempfile.NamedTemporaryFile()
            cred_ini = b"""
            [default]
            region = ap-southeast-2
            aws_access_key_id = MOCK
            aws_secret_access_key  = MOCK
            aws_session_token = tok
            aws_session_expiration = 2020-05-27T18:21:43+0000
            """
            self.credentials.write(cred_ini)
            self.credentials.seek(0)
            self.credentials.read()
            cli.aws_shared_credentials_file = self.credentials.name

            self.config.close()
            # now start new test case
            self.config = tempfile.NamedTemporaryFile()
            conf_ini = b"""
            [default]
            sso_start_url = https://petshop.awsapps.com/start
            sso_region = ap-southeast-2
            sso_account_id = 123456789
            sso_role_name = Engineering
            region = ap-southeast-2
            output = json

            [profile dev]
            role_arn = arn:aws:iam::456789123:role/FullAdmin
            source_profile = default
            region = ap-southeast-2
            output = json
            """
            self.config.write(conf_ini)
            self.config.seek(0)
            self.config.read()
            cli.aws_config_file = self.config.name
            cli.main()
        cred = cli.read_config(self.credentials.name)
        new_tok = cred['dev']['aws_session_token']
        self.assertNotEqual(new_tok, 'tok')
        self.assertEqual(new_tok, 'VeryLongBase664String==')
        verify(cli, times=6).invoke(...)
Beispiel #29
0
 def test_print_export_vars_default_profile(self):
     with ArgvContext(program, '-e', '--default', '-t'):
         # clean up as going to mutate this
         self.config.close()
         # now start new test case
         self.config = tempfile.NamedTemporaryFile()
         conf_ini = b"""
         [default]
         sso_start_url = https://petshop.awsapps.com/start
         sso_region = ap-southeast-2
         sso_account_id = 123456789
         sso_role_name = Engineering
         region = ap-southeast-2
         output = json
         """
         self.config.write(conf_ini)
         self.config.seek(0)
         self.config.read()
         cli.aws_config_file = self.config.name
         cli.main()
     verify(cli, times=3).invoke(...)
Beispiel #30
0
 def test_sso_cache_expires(self):
     with ArgvContext(program, '-p', 'dev',
                      '-d'), self.assertRaises(SystemExit) as x:
         # clean up as going to mutate this
         self.sso_cache_json.close()
         self.sso_cache_dir.cleanup()
         # start new test case
         self.sso_cache_dir = tempfile.TemporaryDirectory()
         self.sso_cache_json = tempfile.NamedTemporaryFile(
             dir=self.sso_cache_dir.name, suffix='.json')
         cache_json = {
             "startUrl": "https://petshop.awsapps.com/start",
             "region": "ap-southeast-2",
             "accessToken": "longTextA.AverylOngText",
             "expiresAt": f"{str((datetime.utcnow()).isoformat())[:-7]}UTC"
         }
         self.sso_cache_json.write(json.dumps(cache_json).encode('utf-8'))
         self.sso_cache_json.seek(0)
         self.sso_cache_json.read()
         cli.AWS_SSO_CACHE_PATH = self.sso_cache_dir.name
         cli.main()
     self.assertEqual(x.exception.code, 1)