def test_write_global_setting(self):
        """Establish that if we attempt to write a valid setting, that
        the parser's write method is run.
        """
        # Invoke the command, but trap the file-write at the end
        # so we don't plow over real things.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.commands.config.open', mock_open,
                        create=True):
            with mock.patch.object(os.path, 'isdir') as isdir:
                isdir.return_value = True
                result = self.runner.invoke(config,
                    ['username', 'luke', '--scope=global'],
                )
                isdir.assert_called_once_with('/etc/awx/')

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output.strip(),
                         'Configuration updated successfully.')

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call('/etc/awx/tower_cli.cfg', 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('username = luke\n'),
                      mock_open.mock_calls)
Example #2
0
    def test_write_local_setting(self):
        """Establish that if we attempt to write a valid setting locally, that
        the correct parser's write method is run.
        """
        # Invoke the command, but trap the file-write at the end
        # so we don't plow over real things.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.cli.misc.open', mock_open,
                        create=True):
            with mock.patch.object(os, 'chmod') as chmod:
                result = self.runner.invoke(
                    config, ['username', 'meagan', '--scope=local'],
                )
                filename = ".tower_cli.cfg"
                chmod.assert_called_once_with(filename, int('0600', 8))

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output.strip(),
                         'Configuration updated successfully.')

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call('.tower_cli.cfg', 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('username = meagan\n'),
                      mock_open.mock_calls)
Example #3
0
    def test_personal_access_token(self):
        """Establish that if `tower-cli login` is called with a username and
        password, we obtain and write an oauth token to the config file
        """
        # Invoke the command.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.cli.misc.open', mock_open,
                        create=True):
            with mock.patch.object(os, 'chmod'):
                with client.test_mode as t:
                    # You have to modify this internal private registry to
                    # register a URL endpoint that _doesn't_ have the version
                    # prefix
                    prefix = Client().get_prefix(include_version=False)
                    t._registry[URL(prefix + 'o/', method='HEAD')] = Resp(
                        ''.encode('utf-8'), 200, {}
                    )
                    t.register('/users/bob/personal_tokens/', json.dumps({
                        'token': 'abc123'
                    }), status_code=201, method='POST')
                    result = self.runner.invoke(
                        login, ['bob', '--password', 'secret', '--scope', 'read']
                    )

        # Ensure that we got a zero exit status
        self.assertEqual(result.exit_code, 0)
        assert json.loads(t.requests[-1].body)['scope'] == 'read'

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call(os.path.expanduser('~/.tower_cli.cfg'), 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('oauth_token = abc123\n'),
                      mock_open.mock_calls)
Example #4
0
    def test_write_global_setting_deprecated(self):
        """Establish that if we attempt to write a valid setting, that
        the parser's write method is run.
        """
        # Invoke the command, but trap the file-write at the end
        # so we don't plow over real things.
        mock_open = mock.mock_open()
        warning_text = 'The `--global` option is deprecated and will be '\
                       'removed. Use `--scope=global` to get the same effect.'
        with mock.patch('tower_cli.cli.misc.open', mock_open,
                        create=True):
            with mock.patch.object(os.path, 'isdir') as isdir:
                with mock.patch.object(os, 'chmod'):
                    with mock.patch.object(warnings, 'warn') as warn:
                        isdir.return_value = True
                        result = self.runner.invoke(
                            config, ['username', 'meagan', '--global'],
                        )
                        warn.assert_called_once_with(warning_text,
                                                     DeprecationWarning)
                        self.assertEqual(warn.mock_calls[0][1][1],
                                         DeprecationWarning)
                        isdir.assert_called_once_with('/etc/tower/')

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual('Configuration updated successfully.',
                         result.output.strip())

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call('/etc/tower/tower_cli.cfg', 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('username = meagan\n'),
                      mock_open.mock_calls)
Example #5
0
 def setUp(self):
     self.size_patch = mock.patch("os.path.getsize")
     self.getsize = self.size_patch.start()
     self.api = mock.Mock()
     self.vault = vault.Vault(self.api, None)
     self.vault.name = "myvault"
     self.mock_open = mock.mock_open()
     stringio = StringIO("content")
     self.mock_open.return_value.read = stringio.read
Example #6
0
 def test_reading_invalid_token_from_server(self):
     self.expires += timedelta(hours=-1)
     expires = self.expires.strftime(TOWER_DATETIME_FMT)
     with mock.patch('six.moves.builtins.open', new_callable=mock.mock_open()):
         with mock.patch('tower_cli.api.json.load', return_value={'token': 'foobar', 'expires': expires}):
             with client.test_mode as t:
                 with self.assertRaises(exc.AuthError):
                     t.register('/authtoken/', json.dumps({}), status_code=200, method='OPTIONS')
                     t.register('/authtoken/', json.dumps({'invalid': 'invalid'}), status_code=200, method='POST')
                     self.auth(self.req)
Example #7
0
 def test_reading_invalid_token(self):
     self.expires += timedelta(hours=1)
     expires = self.expires.strftime(TOWER_DATETIME_FMT)
     with mock.patch('six.moves.builtins.open', new_callable=mock.mock_open()):
         with mock.patch('tower_cli.api.json.load', return_value="invalid"):
             with client.test_mode as t:
                 t.register('/authtoken/', json.dumps({}), status_code=200, method='OPTIONS')
                 t.register('/authtoken/', json.dumps({'token': 'barfoo', 'expires': expires}), status_code=200,
                            method='POST')
                 self.auth(self.req)
                 self.assertEqual(self.req.headers['Authorization'], 'Token barfoo')
Example #8
0
    def test_read_from_file(self):
        """Give it some with '@' and test that it reads from the file"""
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.utils.parser.open', mock_open, create=True):
            manager = mock_open.return_value.__enter__.return_value
            manager.read.return_value = 'foo: bar'
            parser.extra_vars_loader_wrapper(["@fake_file1.yml"])
            parser.extra_vars_loader_wrapper(["@fake_file2.yml",
                                              "@fake_file3.yml"])

        # Ensure that "open" was triggered in test
        self.assertIn(mock.call("fake_file1.yml", 'r'), mock_open.mock_calls)
        self.assertIn(mock.call("fake_file2.yml", 'r'), mock_open.mock_calls)
        self.assertIn(mock.call("fake_file3.yml", 'r'), mock_open.mock_calls)
 def test_upload_function_zip_missing_project_id(self, get_conn, requests_put):
     m = mock.mock_open()
     with mock.patch('builtins.open', m):
         generate_upload_url_method = get_conn.return_value.projects.return_value.locations. \
             return_value.functions.return_value.generateUploadUrl
         execute_method = generate_upload_url_method.return_value.execute
         execute_method.return_value = {"uploadUrl": "http://uploadHere"}
         requests_put.return_value = None
         with self.assertRaises(AirflowException) as cm:
             self.gcf_function_hook_no_project_id.upload_function_zip(
                 location=GCF_LOCATION,
                 zip_path="/tmp/path.zip"
             )
             generate_upload_url_method.assert_not_called()
             execute_method.assert_not_called()
             m.assert_not_called()
             err = cm.exception
             self.assertIn("The project id must be passed", str(err))
    def test_unset(self):
        """Establish that calling `tower-cli config --unset` works in the
        way that we expect.
        """
        # Invoke the command, but trap the file-write at the end
        # so we don't plow over real things.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.commands.config.open', mock_open,
                        create=True):
            result = self.runner.invoke(config, ['username', '--unset'])

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output.strip(),
                         'Configuration updated successfully.')

        # Ensure that the output seems to be correct.
        self.assertNotIn(mock.call().write('username = luke\n'),
                         mock_open.mock_calls)
Example #11
0
    def test_public_application_scoped_token(self):
        """Establish that if `tower-cli login` is called with a username,
        password, and public OAuth2 client ID, we obtain and write an oauth
        token to the config file
        """
        # Invoke the command.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.cli.misc.open', mock_open,
                        create=True):
            with mock.patch.object(os, 'chmod'):
                with client.test_mode as t:
                    # You have to modify this internal private registry to
                    # register a URL endpoint that _doesn't_ have the version
                    # prefix
                    prefix = Client().get_prefix(include_version=False)
                    t._registry[URL(prefix + 'o/', method='HEAD')] = Resp(
                        ''.encode('utf-8'), 200, {}
                    )
                    t._registry[URL(prefix + 'o/token/', method='POST')] = Resp(
                        json.dumps({'access_token': 'abc123'}).encode('utf-8'),
                        201, {}
                    )
                    result = self.runner.invoke(
                        login, ['bob', '--password', 'secret', '--client-id',
                                'abc123']
                    )

        # Ensure that we got a zero exit status
        self.assertEqual(result.exit_code, 0)
        data = urlparse.parse_qs(t.requests[-1].body)
        assert data['scope'] == ['write']
        assert data['grant_type'] == ['password']
        assert data['password'] == ['secret']
        assert data['username'] == ['bob']
        assert data['client_id'] == ['abc123']

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call(os.path.expanduser('~/.tower_cli.cfg'), 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('oauth_token = abc123\n'),
                      mock_open.mock_calls)
Example #12
0
    def test_write_setting(self):
        """Establish that if we attempt to write a valid setting, that
        the parser's write method is run.
        """
        # Invoke the command, but trap the file-write at the end
        # so we don't plow over real things.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.commands.config.open', mock_open,
                        create=True):
            result = self.runner.invoke(config, ['username', 'luke'])

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output.strip(),
                         'Configuration updated successfully.')

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call(os.path.expanduser('~/.tower_cli.cfg'), 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('username = luke\n'),
                      mock_open.mock_calls)
Example #13
0
    def test_permissions_warning(self):
        """Warn user if configuration file permissions can not be set
        """
        # Try to set permissions on file that does not exist, expecting warning
        mock_open = mock.mock_open()
        filename = '.tower_cli.cfg'
        with mock.patch('tower_cli.cli.misc.open', mock_open,
                        create=True):
            with mock.patch.object(os, 'chmod') as chmod:
                chmod.side_effect = OSError
                with mock.patch.object(warnings, 'warn') as warn:
                    result = self.runner.invoke(
                        config, ['username', 'luke', '--scope=local'])
                    warn.assert_called_once_with(mock.ANY, UserWarning)
                    chmod.assert_called_once_with(
                        filename, stat.S_IRUSR | stat.S_IWUSR)

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output.strip(),
                         'Configuration updated successfully.')
Example #14
0
 def test_reading_expired_token(self):
     self.expires += timedelta(hours=-1)
     expires = self.expires.strftime(TOWER_DATETIME_FMT)
     with mock.patch('six.moves.builtins.open',
                     new_callable=mock.mock_open()):
         with mock.patch('tower_cli.api.json.load',
                         return_value={
                             'token': 'foobar',
                             'expires': expires
                         }):
             with client.test_mode as t:
                 t.register('/authtoken/',
                            json.dumps({
                                'token': 'barfoo',
                                'expires': expires
                            }),
                            status_code=200,
                            method='POST')
                 self.auth(self.req)
                 self.assertEqual(self.req.headers['Authorization'],
                                  'Token barfoo')
Example #15
0
 def test_reading_invalid_token_from_server(self):
     self.expires += timedelta(hours=-1)
     expires = self.expires.strftime(TOWER_DATETIME_FMT)
     with mock.patch('six.moves.builtins.open',
                     new_callable=mock.mock_open()):
         with mock.patch('tower_cli.api.json.load',
                         return_value={
                             'token': 'foobar',
                             'expires': expires
                         }):
             with client.test_mode as t:
                 with self.assertRaises(exc.AuthError):
                     t.register('/authtoken/',
                                json.dumps({}),
                                status_code=200,
                                method='OPTIONS')
                     t.register('/authtoken/',
                                json.dumps({'invalid': 'invalid'}),
                                status_code=200,
                                method='POST')
                     self.auth(self.req)
Example #16
0
    def test_application_scoped_token(self):
        """Establish that if `tower-cli login` is called with a username,
        password, and OAuth2 client ID and secret, we obtain and write an oauth
        token to the config file
        """
        # Invoke the command.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.cli.misc.open', mock_open,
                        create=True):
            with mock.patch.object(os, 'chmod'):
                with client.test_mode as t:
                    # You have to modify this internal private registry to
                    # register a URL endpoint that _doesn't_ have the version
                    # prefix
                    prefix = Client().get_prefix(include_version=False)
                    t._registry[URL(prefix + 'o/', method='HEAD')] = Resp(
                        ''.encode('utf-8'), 200, {}
                    )
                    t._registry[URL(prefix + 'o/token/', method='POST')] = Resp(
                        json.dumps({'access_token': 'abc123'}).encode('utf-8'),
                        201, {}
                    )
                    result = self.runner.invoke(
                        login, ['bob', '--password', 'secret', '--client-id',
                                'abc123', '--client-secret', 'some-secret']
                    )

        # Ensure that we got a zero exit status
        self.assertEqual(result.exit_code, 0)
        data = urlparse.parse_qs(t.requests[-1].body)
        assert data['scope'] == ['write']
        assert data['grant_type'] == ['password']
        assert data['password'] == ['secret']
        assert data['username'] == ['bob']

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call(os.path.expanduser('~/.tower_cli.cfg'), 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('oauth_token = abc123\n'),
                      mock_open.mock_calls)
Example #17
0
    def test_permissions_warning(self):
        """Warn user if configuration file permissions can not be set
        """
        # Try to set permissions on file that does not exist, expecting warning
        mock_open = mock.mock_open()
        filename = '.tower_cli.cfg'
        with mock.patch('tower_cli.commands.config.open',
                        mock_open,
                        create=True):
            with mock.patch.object(os, 'chmod') as chmod:
                chmod.side_effect = OSError
                with mock.patch.object(warnings, 'warn') as warn:
                    result = self.runner.invoke(
                        config, ['username', 'luke', '--scope=local'])
                    warn.assert_called_once_with(mock.ANY, UserWarning)
                    chmod.assert_called_once_with(filename,
                                                  stat.S_IRUSR | stat.S_IWUSR)

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output.strip(),
                         'Configuration updated successfully.')
Example #18
0
    def test_write_global_setting_deprecated(self):
        """Establish that if we attempt to write a valid setting, that
        the parser's write method is run.
        """
        # Invoke the command, but trap the file-write at the end
        # so we don't plow over real things.
        mock_open = mock.mock_open()
        warning_text = 'The `--global` option is deprecated and will be '\
                       'removed. Use `--scope=global` to get the same effect.'
        with mock.patch('tower_cli.commands.config.open',
                        mock_open,
                        create=True):
            with mock.patch.object(os.path, 'isdir') as isdir:
                with mock.patch.object(os, 'chmod'):
                    with mock.patch.object(warnings, 'warn') as warn:
                        isdir.return_value = True
                        result = self.runner.invoke(
                            config,
                            ['username', 'meagan', '--global'],
                        )
                        warn.assert_called_once_with(warning_text,
                                                     DeprecationWarning)
                        self.assertEqual(warn.mock_calls[0][1][1],
                                         DeprecationWarning)
                        isdir.assert_called_once_with('/etc/tower/')

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual('Configuration updated successfully.',
                         result.output.strip())

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call('/etc/tower/tower_cli.cfg', 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('username = meagan\n'),
                      mock_open.mock_calls)