Beispiel #1
0
def test_anonymous_login():
    with patch('sys.stdin.readline', return_value='\n'), \
            patch('uuid.uuid1', return_value='anonymous@email'):

        assert _mock_dcos_run([util.which('dcos'),
                               'help'], False) == 0
        assert _mock_dcos_run([util.which('dcos'), 'config',
                               'show', 'core.email'], False) == 0
        assert _mock_dcos_run([util.which('dcos'), 'config',
                               'unset', 'core.email'], False) == 0
Beispiel #2
0
def test_exc():
    '''Tests that a command which does raise an exception does report an
    exception.

    '''

    args = [util.which('dcos')]
    env = _env_reporting()

    with patch('sys.argv', args), \
            patch.dict(os.environ, env), \
            patch('dcoscli.analytics._wait_and_capture',
                  return_value=(1, 'Traceback')):
        assert main() == 1

        # segment.io
        props = _base_properties()
        props['err'] = 'Traceback'
        props['exit_code'] = 1
        data = {'userId': USER_ID,
                'event': SEGMENT_IO_CLI_ERROR_EVENT,
                'properties': props}

        assert mock_called_some_args(requests.post,
                                     '{}/track'.format(SEGMENT_URL),
                                     json=data,
                                     timeout=1)

        # rollbar
        props = _base_properties()
        props['exit_code'] = 1
        props['stderr'] = 'Traceback'
        rollbar.report_message.assert_called_with('Traceback', 'error',
                                                  extra_data=props)
Beispiel #3
0
    def copy_to_cache(self, target_dir):
        """Copies the source content to the supplied local directory.

        :param target_dir: Path to the destination directory.
        :type target_dir: str
        :returns: The error, if one occurred
        :rtype: None
        """

        try:
            # TODO(SS): add better url parsing

            # Ensure git is installed properly.
            git_program = util.which('git')
            if git_program is None:
                raise DCOSException("""Could not locate the git program.  Make sure \
it is installed and on the system search path.
PATH = {}""".format(os.environ[constants.PATH_ENV]))

            # Clone git repo into the supplied target directory.
            git.Repo.clone_from(self._url,
                                to_path=target_dir,
                                progress=None,
                                branch='master')

            # Remove .git directory to save space.
            shutil.rmtree(os.path.join(target_dir, ".git"),
                          onerror=_rmtree_on_error)
            return None

        except git.exc.GitCommandError:
            logger.exception('Unable to fetch packages from git: %s', self.url)

            raise DCOSException(
                'Unable to fetch packages from [{}]'.format(self.url))
Beispiel #4
0
def test_no_exc():
    '''Tests that a command which does not raise an exception does not
    report an exception.

    '''

    args = [util.which('dcos')]
    env = _env_reporting()
    version = 'release'

    with patch('sys.argv', args), \
            patch.dict(os.environ, env), \
            patch('dcoscli.version', version):
        assert main() == 0

        # segment.io
        data = {'userId': USER_ID,
                'event': SEGMENT_IO_CLI_EVENT,
                'properties': _base_properties()}
        assert mock_called_some_args(http.post,
                                     '{}/track'.format(SEGMENT_URL),
                                     json=data,
                                     timeout=(1, 1))

        # rollbar
        assert rollbar.report_message.call_count == 0
Beispiel #5
0
def mock_args(args):
    """ Context manager that mocks sys.args and captures stdout/stderr

    :param args: sys.args values to mock
    :type args: [str]
    :rtype: None
    """
    with mock.patch('sys.argv', [util.which('dcos')] + args):
        stdout, stderr = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = six.StringIO(), six.StringIO()
        try:
            yield sys.stdout, sys.stderr
        finally:
            sys.stdout, sys.stderr = stdout, stderr
Beispiel #6
0
def test_cluster_id_not_sent():
    '''Tests that cluster_id is sent to segment.io'''

    args = [util.which('dcos'), 'config', 'show']
    env = _env_reporting_with_url()
    version = 'release'

    with patch('sys.argv', args), \
            patch.dict(os.environ, env), \
            patch('dcoscli.version', version), \
            patch('dcos.mesos.DCOSClient.metadata') as get_cluster_id:
        assert main() == 0

        assert get_cluster_id.call_count == 0
Beispiel #7
0
def test_config_reporting_false():
    '''Test that "core.reporting = false" blocks exception reporting.'''

    args = [util.which('dcos')]
    env = _env_no_reporting()

    with patch('sys.argv', args), \
            patch.dict(os.environ, env), \
            patch('dcoscli.analytics._wait_and_capture',
                  return_value=(1, 'Traceback')):

        assert main() == 1

        assert rollbar.report_message.call_count == 0
        assert requests.post.call_count == 0
Beispiel #8
0
def test_config_set():
    '''Tests that a `dcos config set core.email <email>` makes a
    segment.io identify call'''

    args = [util.which('dcos'), 'config', 'set', 'core.email', '*****@*****.**']
    env = _env_reporting()

    with patch('sys.argv', args), patch.dict(os.environ, env):
        assert config_main() == 0

        # segment.io
        assert mock_called_some_args(requests.post,
                                     '{}/identify'.format(SEGMENT_URL),
                                     json={'userId': '*****@*****.**'},
                                     timeout=1)
Beispiel #9
0
def _find_virtualenv(bin_directory):
    """
    :param bin_directory: directory to first use to find virtualenv
    :type bin_directory: str
    :returns: Absolute path to virutalenv program
    :rtype: str
    """

    virtualenv_path = os.path.join(bin_directory, 'virtualenv')
    if not os.path.exists(virtualenv_path):
        virtualenv_path = util.which('virtualenv')

    if virtualenv_path is None:
        raise DCOSException('Unable to find the virtualenv program')

    return virtualenv_path
Beispiel #10
0
def test_no_exc():
    '''Tests that a command which does not raise an exception does not
    report an exception.

    '''

    args = [util.which('dcos')]
    env = _env_reporting()
    version = 'release'

    with patch('sys.argv', args), \
            patch.dict(os.environ, env), \
            patch('dcoscli.version', version):
        assert main() == 0

        assert rollbar.report_message.call_count == 0
Beispiel #11
0
def test_config_reporting_false():
    '''Test that "core.reporting = false" blocks exception reporting.'''

    args = [util.which('dcos')]
    env = _env_no_reporting()
    version = 'release'

    with patch('sys.argv', args), \
            patch('dcoscli.version', version), \
            patch.dict(os.environ, env), \
            patch('dcoscli.analytics.wait_and_capture',
                  return_value=(1, 'Traceback')), \
            patch('dcoscli.analytics._segment_track_cli') as track:

        assert main() == 1
        assert track.call_count == 0
Beispiel #12
0
def test_production_setting_false():
    '''Test that env var DCOS_PRODUCTION=false sends exceptions to
    the 'dev' environment.

    '''

    args = [util.which('dcos')]
    env = _env_reporting()
    env['DCOS_PRODUCTION'] = 'false'

    with patch('sys.argv', args), patch.dict(os.environ, env):
        assert main() == 0

        _, kwargs = requests.post.call_args_list[0]
        assert kwargs['auth'].username == SEGMENT_IO_WRITE_KEY_DEV

        rollbar.init.assert_called_with(ROLLBAR_SERVER_POST_KEY, 'dev')
Beispiel #13
0
def test_exc():
    '''Tests that a command which does raise an exception does report an
    exception.

    '''

    args = [util.which('dcos')]
    env = _env_reporting()
    version = 'release'
    with patch('sys.argv', args), \
            patch('dcoscli.version', version), \
            patch.dict(os.environ, env), \
            patch('dcoscli.analytics.wait_and_capture',
                  return_value=(1, 'Traceback')), \
            patch('dcoscli.analytics._segment_track_cli') as track:

        assert main() == 1
        assert track.call_count == 1
        assert rollbar.report_message.call_count == 1
Beispiel #14
0
def _find_virtualenv(bin_directory):
    """
    :param bin_directory: directory to first use to find virtualenv
    :type bin_directory: str
    :returns: Absolute path to virutalenv program
    :rtype: str
    """

    virtualenv_path = os.path.join(bin_directory, 'virtualenv')
    if not os.path.exists(virtualenv_path):
        virtualenv_path = util.which('virtualenv')

    if virtualenv_path is None:
        msg = ("Unable to install CLI subcommand. "
               "Missing required program 'virtualenv'.\n"
               "Please see installation instructions: "
               "https://virtualenv.pypa.io/en/latest/installation.html")
        raise DCOSException(msg)

    return virtualenv_path
Beispiel #15
0
def _find_virtualenv(bin_directory):
    """
    :param bin_directory: directory to first use to find virtualenv
    :type bin_directory: str
    :returns: Absolute path to virutalenv program
    :rtype: str
    """

    virtualenv_path = os.path.join(bin_directory, 'virtualenv')
    if not os.path.exists(virtualenv_path):
        virtualenv_path = util.which('virtualenv')

    if virtualenv_path is None:
        msg = ("Unable to install CLI subcommand. "
               "Missing required program 'virtualenv'.\n"
               "Please see installation instructions: "
               "https://virtualenv.pypa.io/en/latest/installation.html")
        raise DCOSException(msg)

    return virtualenv_path
Beispiel #16
0
def test_cluster_id_sent():
    '''Tests that cluster_id is sent to segment.io'''

    args = [util.which('dcos')]
    env = _env_reporting_with_url()
    version = 'release'

    with patch('sys.argv', args), \
            patch.dict(os.environ, env), \
            patch('dcoscli.version', version):
        assert main() == 0

        props = _base_properties()
        # segment.io
        data = {'userId': USER_ID,
                'event': SEGMENT_IO_CLI_EVENT,
                'properties': props}
        assert props.get('CLUSTER_ID')
        assert mock_called_some_args(http.post,
                                     '{}/track'.format(SEGMENT_URL),
                                     json=data,
                                     timeout=(1, 1))
Beispiel #17
0
def test_exc():
    '''Tests that a command which does raise an exception does report an
    exception.

    '''

    args = [util.which('dcos')]
    env = _env_reporting()
    version = 'release'
    with patch('sys.argv', args), \
            patch('dcoscli.version', version), \
            patch.dict(os.environ, env), \
            patch('dcoscli.analytics.wait_and_capture',
                  return_value=(1, 'Traceback')):
        assert main() == 1

        # segment.io
        props = _base_properties()
        props['err'] = 'Traceback'
        props['exit_code'] = 1
        data = {
            'userId': USER_ID,
            'event': SEGMENT_IO_CLI_ERROR_EVENT,
            'properties': props
        }

        assert mock_called_some_args(http.post,
                                     '{}/track'.format(SEGMENT_URL),
                                     json=data,
                                     timeout=(1, 1))

        # rollbar
        props = _base_properties()
        props['exit_code'] = 1
        props['stderr'] = 'Traceback'
        rollbar.report_message.assert_called_with('Traceback',
                                                  'error',
                                                  extra_data=props)
Beispiel #18
0
    def copy_to_cache(self, target_dir):
        """Copies the source content to the supplied local directory.

        :param target_dir: Path to the destination directory.
        :type target_dir: str
        :returns: The error, if one occurred
        :rtype: None
        """

        try:
            # TODO(SS): add better url parsing

            # Ensure git is installed properly.
            git_program = util.which('git')
            if git_program is None:
                raise DCOSException(
                    """Could not locate the git program.  Make sure \
it is installed and on the system search path.
PATH = {}""".format(os.environ[constants.PATH_ENV]))

            # Clone git repo into the supplied target directory.
            git.Repo.clone_from(self._url,
                                to_path=target_dir,
                                progress=None,
                                branch='master')

            # Remove .git directory to save space.
            shutil.rmtree(os.path.join(target_dir, ".git"),
                          onerror=_rmtree_on_error)
            return None

        except git.exc.GitCommandError:
            logger.exception('Unable to fetch packages from git: %s', self.url)

            raise DCOSException('Unable to fetch packages from [{}]'.format(
                self.url))
Beispiel #19
0
def test_cluster_id_sent():
    '''Tests that cluster_id is sent to segment.io'''

    args = [util.which('dcos')]
    env = _env_reporting_with_url()
    version = 'release'

    with patch('sys.argv', args), \
            patch.dict(os.environ, env), \
            patch('dcoscli.version', version):
        assert main() == 0

        props = _base_properties()
        # segment.io
        data = {
            'userId': USER_ID,
            'event': SEGMENT_IO_CLI_EVENT,
            'properties': props
        }
        assert props.get('CLUSTER_ID')
        assert mock_called_some_args(http.post,
                                     '{}/track'.format(SEGMENT_URL),
                                     json=data,
                                     timeout=(1, 1))
Beispiel #20
0
def test_when_authenticated():
    with patch('dcos.auth.force_auth'):

        _mock_dcos_run([util.which('dcos')], True)
        assert auth.force_auth.call_count == 0
Beispiel #21
0
def test_no_browser_auth():
    webbrowser.get = Mock(side_effect=webbrowser.Error())
    with patch('webbrowser.open') as op:
        _mock_dcos_run([util.which('dcos')], False)
        assert op.call_count == 0
Beispiel #22
0
def test_no_browser_auth():
    webbrowser.get = Mock(side_effect=webbrowser.Error())
    with patch('webbrowser.open') as op:
        _mock_dcos_run([util.which('dcos')], False)
        assert op.call_count == 0