Ejemplo n.º 1
0
def test_pip_version_check(monkeypatch, stored_time, newver, check, warn):
    monkeypatch.setattr(outdated, 'get_installed_version', lambda name: '1.0')

    resp = pretend.stub(
        raise_for_status=pretend.call_recorder(lambda: None),
        json=pretend.call_recorder(lambda: {"releases": {
            newver: {}
        }}),
    )
    session = pretend.stub(
        get=pretend.call_recorder(lambda u, headers=None: resp), )

    fake_state = pretend.stub(
        state={
            "last_check": stored_time,
            'pypi_version': '1.0'
        },
        save=pretend.call_recorder(lambda v, t: None),
    )

    monkeypatch.setattr(outdated, 'load_selfcheck_statefile',
                        lambda: fake_state)

    monkeypatch.setattr(outdated.logger, 'warning',
                        pretend.call_recorder(lambda s: None))
    monkeypatch.setattr(outdated.logger, 'debug',
                        pretend.call_recorder(lambda s, exc_info=None: None))

    with freezegun.freeze_time(
            "1970-01-09 10:00:00",
            ignore=[
                "six.moves",
                "pip._vendor.six.moves",
                "pip._vendor.requests.packages.urllib3.packages.six.moves",
            ]):
        outdated.pip_version_check(session)

    assert not outdated.logger.debug.calls

    if check:
        assert session.get.calls == [
            pretend.call("https://pypi.python.org/pypi/pip/json",
                         headers={"Accept": "application/json"})
        ]
        assert fake_state.save.calls == [
            pretend.call(newver, datetime.datetime(1970, 1, 9, 10, 00, 00)),
        ]
        if warn:
            assert len(outdated.logger.warning.calls) == 1
        else:
            assert len(outdated.logger.warning.calls) == 0
    else:
        assert session.get.calls == []
        assert fake_state.save.calls == []
Ejemplo n.º 2
0
def test_pip_version_check(monkeypatch, stored_time, newver, check, warn):
    monkeypatch.setattr(outdated, 'get_installed_version', lambda name: '1.0')

    resp = pretend.stub(
        raise_for_status=pretend.call_recorder(lambda: None),
        json=pretend.call_recorder(lambda: {"releases": {newver: {}}}),
    )
    session = pretend.stub(
        get=pretend.call_recorder(lambda u, headers=None: resp),
    )

    fake_state = pretend.stub(
        state={"last_check": stored_time, 'pypi_version': '1.0'},
        save=pretend.call_recorder(lambda v, t: None),
    )

    monkeypatch.setattr(
        outdated, 'load_selfcheck_statefile', lambda: fake_state
    )

    monkeypatch.setattr(outdated.logger, 'warning',
                        pretend.call_recorder(lambda s: None))
    monkeypatch.setattr(outdated.logger, 'debug',
                        pretend.call_recorder(lambda s, exc_info=None: None))

    with freezegun.freeze_time(
            "1970-01-09 10:00:00",
            ignore=[
                "six.moves",
                "pip._vendor.six.moves",
                "pip._vendor.requests.packages.urllib3.packages.six.moves",
            ]):
        outdated.pip_version_check(session)

    assert not outdated.logger.debug.calls

    if check:
        assert session.get.calls == [pretend.call(
            "https://pypi.python.org/pypi/pip/json",
            headers={"Accept": "application/json"}
        )]
        assert fake_state.save.calls == [
            pretend.call(newver, datetime.datetime(1970, 1, 9, 10, 00, 00)),
        ]
        if warn:
            assert len(outdated.logger.warning.calls) == 1
        else:
            assert len(outdated.logger.warning.calls) == 0
    else:
        assert session.get.calls == []
        assert fake_state.save.calls == []
Ejemplo n.º 3
0
def test_pip_version_check(monkeypatch, stored_time, newver, check, warn):
    monkeypatch.setattr(outdated, 'get_installed_version', lambda name: '1.0')

    version = pretend.stub(base_version=newver, )

    install_candidate = pretend.stub(version=version, )

    finder = pretend.stub(find_requirement=pretend.call_recorder(
        lambda _, upgrade: install_candidate), )

    fake_state = pretend.stub(
        state={
            "last_check": stored_time,
            'remote_version': '1.0'
        },
        save=pretend.call_recorder(lambda v, t: None),
    )

    monkeypatch.setattr(outdated, 'load_selfcheck_statefile',
                        lambda: fake_state)

    monkeypatch.setattr(outdated.logger, 'warning',
                        pretend.call_recorder(lambda *a, **kw: None))
    monkeypatch.setattr(outdated.logger, 'debug',
                        pretend.call_recorder(lambda s, exc_info=None: None))

    with freezegun.freeze_time(
            "1970-01-09 10:00:00",
            ignore=[
                "six.moves",
                "pip._vendor.six.moves",
                "pip._vendor.requests.packages.urllib3.packages.six.moves",
            ]):
        outdated.pip_version_check(finder)

    assert not outdated.logger.debug.calls

    if check:
        assert len(finder.find_requirement.calls) == 1
        assert fake_state.save.calls == [
            pretend.call(newver, datetime.datetime(1970, 1, 9, 10, 00, 00)),
        ]
        if warn:
            assert len(outdated.logger.warning.calls) == 1
        else:
            assert len(outdated.logger.warning.calls) == 0
    else:
        assert finder.find_requirement.calls == []
        assert fake_state.save.calls == []
Ejemplo n.º 4
0
def test_pip_version_check(monkeypatch, stored_time, installed_ver, new_ver,
                           check_if_upgrade_required, check_warn_logs):
    monkeypatch.setattr(outdated, 'get_installed_version',
                        lambda name: installed_ver)
    monkeypatch.setattr(outdated, 'PackageFinder', MockPackageFinder)
    monkeypatch.setattr(outdated.logger, 'warning',
                        pretend.call_recorder(lambda *a, **kw: None))
    monkeypatch.setattr(outdated.logger, 'debug',
                        pretend.call_recorder(lambda s, exc_info=None: None))

    fake_state = pretend.stub(
        state={
            "last_check": stored_time,
            'pypi_version': installed_ver
        },
        save=pretend.call_recorder(lambda v, t: None),
    )
    monkeypatch.setattr(outdated, 'load_selfcheck_statefile',
                        lambda: fake_state)

    with freezegun.freeze_time(
            "1970-01-09 10:00:00",
            ignore=[
                "six.moves",
                "pip._vendor.six.moves",
                "pip._vendor.requests.packages.urllib3.packages.six.moves",
            ]):
        latest_pypi_version = outdated.pip_version_check(None, _options())

    # See we return None if not installed_version
    if not installed_ver:
        assert not latest_pypi_version
    # See that we saved the correct version
    elif check_if_upgrade_required:
        assert fake_state.save.calls == [
            pretend.call(new_ver, datetime.datetime(1970, 1, 9, 10, 00, 00)),
        ]
    else:
        # Make sure no Exceptions
        assert not outdated.logger.debug.calls
        # See that save was not called
        assert fake_state.save.calls == []

    # Ensure we warn the user or not
    if check_warn_logs:
        assert len(outdated.logger.warning.calls) == 1
    else:
        assert len(outdated.logger.warning.calls) == 0
Ejemplo n.º 5
0
    def main(self, args):
        options, args = self.parse_args(args)

        if options.quiet:
            if options.quiet == 1:
                level = "WARNING"
            if options.quiet == 2:
                level = "ERROR"
            else:
                level = "CRITICAL"
        elif options.verbose:
            level = "DEBUG"
        else:
            level = "INFO"

        # The root logger should match the "console" level *unless* we
        # specified "--log" to send debug logs to a file.
        root_level = level
        if options.log:
            root_level = "DEBUG"

        logging_dictConfig({
            "version":
            1,
            "disable_existing_loggers":
            False,
            "filters": {
                "exclude_warnings": {
                    "()": "pip.utils.logging.MaxLevelFilter",
                    "level": logging_t.WARNING,
                },
            },
            "formatters": {
                "indent": {
                    "()": IndentingFormatter,
                    "format": "%(message)s",
                },
            },
            "handlers": {
                "console": {
                    "level": level,
                    "class": "pip.utils.logging.ColorizedStreamHandler",
                    "stream": self.log_streams[0],
                    "filters": ["exclude_warnings"],
                    "formatter": "indent",
                },
                "console_errors": {
                    "level": "WARNING",
                    "class": "pip.utils.logging.ColorizedStreamHandler",
                    "stream": self.log_streams[1],
                    "formatter": "indent",
                },
                "user_log": {
                    "level": "DEBUG",
                    "class": "pip.utils.logging.BetterRotatingFileHandler",
                    "filename": options.log or "/dev/null",
                    "delay": True,
                    "formatter": "indent",
                },
            },
            "root": {
                "level":
                root_level,
                "handlers":
                list(
                    filter(None, [
                        "console",
                        "console_errors",
                        "user_log" if options.log else None,
                    ])),
            },
            # Disable any logging besides WARNING unless we have DEBUG level
            # logging enabled. These use both pip._vendor and the bare names
            # for the case where someone unbundles our libraries.
            "loggers":
            dict((
                name,
                {
                    "level": (
                        "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"),
                },
            ) for name in ["pip._vendor", "distlib", "requests", "urllib3"]),
        })

        if sys.version_info[:2] == (2, 6):
            warnings.warn(
                "Python 2.6 is no longer supported by the Python core team, "
                "please upgrade your Python. A future version of pip will "
                "drop support for Python 2.6",
                deprecation.Python26DeprecationWarning)

        # TODO: try to get these passing down from the command?
        #      without resorting to os.environ to hold these.

        if options.no_input:
            os.environ['PIP_NO_INPUT'] = '1'

        if options.exists_action:
            os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)

        if options.require_venv:
            # If a venv is required check if it can really be found
            if not running_under_virtualenv():
                logger.critical(
                    'Could not find an activated virtualenv (required).')
                sys.exit(VIRTUALENV_NOT_FOUND)

        try:
            status = self.run(options, args)
            # FIXME: all commands should return an exit status
            # and when it is done, isinstance is not needed anymore
            if isinstance(status, int):
                return status
        except PreviousBuildDirError as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:', exc_info=True)

            return PREVIOUS_BUILD_DIR_ERROR
        except (InstallationError, UninstallationError, BadCommand) as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:', exc_info=True)

            return ERROR
        except CommandError as exc:
            logger.critical('ERROR: %s', exc)
            logger.debug('Exception information:', exc_info=True)

            return ERROR
        except KeyboardInterrupt:
            logger.critical('Operation cancelled by user')
            logger.debug('Exception information:', exc_info=True)

            return ERROR
        except:
            logger.critical('Exception:', exc_info=True)

            return UNKNOWN_ERROR
        finally:
            # Check if we're using the latest version of pip available
            if (not options.disable_pip_version_check
                    and not getattr(options, "no_index", False)):
                with self._build_session(options,
                                         retries=0,
                                         timeout=min(
                                             5, options.timeout)) as session:
                    pip_version_check(session)

        return SUCCESS
Ejemplo n.º 6
0
    def main(self, args):
        options, args = self.parse_args(args)

        if options.quiet:
            level = "WARNING"
        elif options.verbose:
            level = "DEBUG"
        else:
            level = "INFO"

        # Compute the path for our debug log.
        debug_log_path = os.path.join(appdirs.user_log_dir("pip"), "debug.log")

        # Ensure that the path for our debug log is owned by the current user
        # and if it is not, disable the debug log.
        write_debug_log = check_path_owner(debug_log_path)

        logging_dictConfig({
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "indent": {
                    "()": IndentingFormatter,
                    "format": (
                        "%(message)s"
                        if not options.log_explicit_levels
                        else "[%(levelname)s] %(message)s"
                    ),
                },
            },
            "handlers": {
                "console": {
                    "level": level,
                    "class": "pip.utils.logging.ColorizedStreamHandler",
                    "stream": self.log_stream,
                    "formatter": "indent",
                },
                "debug_log": {
                    "level": "DEBUG",
                    "class": "pip.utils.logging.BetterRotatingFileHandler",
                    "filename": debug_log_path,
                    "maxBytes": 10 * 1000 * 1000,  # 10 MB
                    "backupCount": 1,
                    "delay": True,
                    "formatter": "indent",
                },
                "user_log": {
                    "level": "DEBUG",
                    "class": "pip.utils.logging.BetterRotatingFileHandler",
                    "filename": options.log or "/dev/null",
                    "delay": True,
                    "formatter": "indent",
                },
            },
            "root": {
                "level": level,
                "handlers": list(filter(None, [
                    "console",
                    "debug_log" if write_debug_log else None,
                    "user_log" if options.log else None,
                ])),
            },
            # Disable any logging besides WARNING unless we have DEBUG level
            # logging enabled. These use both pip._vendor and the bare names
            # for the case where someone unbundles our libraries.
            "loggers": dict(
                (
                    name,
                    {
                        "level": (
                            "WARNING"
                            if level in ["INFO", "ERROR"]
                            else "DEBUG"
                        ),
                    },
                )
                for name in ["pip._vendor", "distlib", "requests", "urllib3"]
            ),
        })

        # We add this warning here instead of up above, because the logger
        # hasn't been configured until just now.
        if not write_debug_log:
            logger.warning(
                "The directory '%s' or its parent directory is not owned by "
                "the current user and the debug log has been disabled. Please "
                "check the permissions and owner of that directory. If "
                "executing pip with sudo, you may want the -H flag.",
                os.path.dirname(debug_log_path),
            )

        if options.log_explicit_levels:
            warnings.warn(
                "--log-explicit-levels has been deprecated and will be removed"
                " in a future version.",
                RemovedInPip8Warning,
            )

        # TODO: try to get these passing down from the command?
        #      without resorting to os.environ to hold these.

        if options.no_input:
            os.environ['PIP_NO_INPUT'] = '1'

        if options.exists_action:
            os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)

        if options.require_venv:
            # If a venv is required check if it can really be found
            if not running_under_virtualenv():
                logger.critical(
                    'Could not find an activated virtualenv (required).'
                )
                sys.exit(VIRTUALENV_NOT_FOUND)

        # Check if we're using the latest version of pip available
        if (not options.disable_pip_version_check
                and not getattr(options, "no_index", False)):
            with self._build_session(
                    options,
                    retries=0,
                    timeout=min(5, options.timeout)) as session:
                pip_version_check(session)

        try:
            status = self.run(options, args)
            # FIXME: all commands should return an exit status
            # and when it is done, isinstance is not needed anymore
            if isinstance(status, int):
                return status
        except PreviousBuildDirError as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:\n%s', format_exc())

            return PREVIOUS_BUILD_DIR_ERROR
        except (InstallationError, UninstallationError, BadCommand) as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:\n%s', format_exc())

            return ERROR
        except CommandError as exc:
            logger.critical('ERROR: %s', exc)
            logger.debug('Exception information:\n%s', format_exc())

            return ERROR
        except KeyboardInterrupt:
            logger.critical('Operation cancelled by user')
            logger.debug('Exception information:\n%s', format_exc())

            return ERROR
        except:
            logger.critical('Exception:\n%s', format_exc())

            return UNKNOWN_ERROR

        return SUCCESS
Ejemplo n.º 7
0
    def main(self, args):
        options, args = self.parse_args(args)

        if options.quiet:
            if options.quiet == 1:
                level = "WARNING"
            if options.quiet == 2:
                level = "ERROR"
            else:
                level = "CRITICAL"
        elif options.verbose:
            level = "DEBUG"
        else:
            level = "INFO"

        # The root logger should match the "console" level *unless* we
        # specified "--log" to send debug logs to a file.
        root_level = level
        if options.log:
            root_level = "DEBUG"

        logging_dictConfig({
            "version": 1,
            "disable_existing_loggers": False,
            "filters": {
                "exclude_warnings": {
                    "()": "pip.utils.logging.MaxLevelFilter",
                    "level": logging.WARNING,
                },
            },
            "formatters": {
                "indent": {
                    "()": IndentingFormatter,
                    "format": "%(message)s",
                },
            },
            "handlers": {
                "console": {
                    "level": level,
                    "class": "pip.utils.logging.ColorizedStreamHandler",
                    "stream": self.log_streams[0],
                    "filters": ["exclude_warnings"],
                    "formatter": "indent",
                },
                "console_errors": {
                    "level": "WARNING",
                    "class": "pip.utils.logging.ColorizedStreamHandler",
                    "stream": self.log_streams[1],
                    "formatter": "indent",
                },
                "user_log": {
                    "level": "DEBUG",
                    "class": "pip.utils.logging.BetterRotatingFileHandler",
                    "filename": options.log or "/dev/null",
                    "delay": True,
                    "formatter": "indent",
                },
            },
            "root": {
                "level": root_level,
                "handlers": list(filter(None, [
                    "console",
                    "console_errors",
                    "user_log" if options.log else None,
                ])),
            },
            # Disable any logging besides WARNING unless we have DEBUG level
            # logging enabled. These use both pip._vendor and the bare names
            # for the case where someone unbundles our libraries.
            "loggers": dict(
                (
                    name,
                    {
                        "level": (
                            "WARNING"
                            if level in ["INFO", "ERROR"]
                            else "DEBUG"
                        ),
                    },
                )
                for name in ["pip._vendor", "distlib", "requests", "urllib3"]
            ),
        })

        if sys.version_info[:2] == (2, 6):
            warnings.warn(
                "Python 2.6 is no longer supported by the Python core team, "
                "please upgrade your Python. A future version of pip will "
                "drop support for Python 2.6",
                deprecation.Python26DeprecationWarning
            )

        # TODO: try to get these passing down from the command?
        #      without resorting to os.environ to hold these.

        if options.no_input:
            os.environ['PIP_NO_INPUT'] = '1'

        if options.exists_action:
            os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)

        if options.require_venv:
            # If a venv is required check if it can really be found
            if not running_under_virtualenv():
                logger.critical(
                    'Could not find an activated virtualenv (required).'
                )
                sys.exit(VIRTUALENV_NOT_FOUND)

        try:
            status = self.run(options, args)
            # FIXME: all commands should return an exit status
            # and when it is done, isinstance is not needed anymore
            if isinstance(status, int):
                return status
        except PreviousBuildDirError as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:', exc_info=True)

            return PREVIOUS_BUILD_DIR_ERROR
        except (InstallationError, UninstallationError, BadCommand) as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:', exc_info=True)

            return ERROR
        except CommandError as exc:
            logger.critical('ERROR: %s', exc)
            logger.debug('Exception information:', exc_info=True)

            return ERROR
        except KeyboardInterrupt:
            logger.critical('Operation cancelled by user')
            logger.debug('Exception information:', exc_info=True)

            return ERROR
        except:
            logger.critical('Exception:', exc_info=True)

            return UNKNOWN_ERROR
        finally:
            # Check if we're using the latest version of pip available
            if (not options.disable_pip_version_check and not
                    getattr(options, "no_index", False)):
                with self._build_session(
                        options,
                        retries=0,
                        timeout=min(5, options.timeout)) as session:
                    pip_version_check(session)

        return SUCCESS
    def main(self, args):
        options, args = self.parse_args(args)

        if options.quiet:
            if options.quiet == 1:
                level = "WARNING"
            if options.quiet == 2:
                level = "ERROR"
            else:
                level = "CRITICAL"
        elif options.verbose:
            level = "DEBUG"
        else:
            level = "INFO"

        logging_dictConfig(
            {
                "version": 1,
                "disable_existing_loggers": False,
                "filters": {"exclude_warnings": {"()": "pip.utils.logging.MaxLevelFilter", "level": logging.WARNING}},
                "formatters": {
                    "indent": {
                        "()": IndentingFormatter,
                        "format": ("%(message)s" if not options.log_explicit_levels else "[%(levelname)s] %(message)s"),
                    }
                },
                "handlers": {
                    "console": {
                        "level": level,
                        "class": "pip.utils.logging.ColorizedStreamHandler",
                        "stream": self.log_streams[0],
                        "filters": ["exclude_warnings"],
                        "formatter": "indent",
                    },
                    "console_errors": {
                        "level": "WARNING",
                        "class": "pip.utils.logging.ColorizedStreamHandler",
                        "stream": self.log_streams[1],
                        "formatter": "indent",
                    },
                    "user_log": {
                        "level": "DEBUG",
                        "class": "pip.utils.logging.BetterRotatingFileHandler",
                        "filename": options.log or "/dev/null",
                        "delay": True,
                        "formatter": "indent",
                    },
                },
                "root": {
                    "level": level,
                    "handlers": list(filter(None, ["console", "console_errors", "user_log" if options.log else None])),
                },
                # Disable any logging besides WARNING unless we have DEBUG level
                # logging enabled. These use both pip._vendor and the bare names
                # for the case where someone unbundles our libraries.
                "loggers": dict(
                    (name, {"level": ("WARNING" if level in ["INFO", "ERROR"] else "DEBUG")})
                    for name in ["pip._vendor", "distlib", "requests", "urllib3"]
                ),
            }
        )

        if options.log_explicit_levels:
            warnings.warn(
                "--log-explicit-levels has been deprecated and will be removed" " in a future version.",
                RemovedInPip8Warning,
            )

        # TODO: try to get these passing down from the command?
        #      without resorting to os.environ to hold these.

        if options.no_input:
            os.environ["PIP_NO_INPUT"] = "1"

        if options.exists_action:
            os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)

        if options.require_venv:
            # If a venv is required check if it can really be found
            if not running_under_virtualenv():
                logger.critical("Could not find an activated virtualenv (required).")
                sys.exit(VIRTUALENV_NOT_FOUND)

        # Check if we're using the latest version of pip available
        if not options.disable_pip_version_check and not getattr(options, "no_index", False):
            with self._build_session(options, retries=0, timeout=min(5, options.timeout)) as session:
                pip_version_check(session)

        try:
            status = self.run(options, args)
            # FIXME: all commands should return an exit status
            # and when it is done, isinstance is not needed anymore
            if isinstance(status, int):
                return status
        except PreviousBuildDirError as exc:
            logger.critical(str(exc))
            logger.debug("Exception information:\n%s", format_exc())

            return PREVIOUS_BUILD_DIR_ERROR
        except (InstallationError, UninstallationError, BadCommand) as exc:
            logger.critical(str(exc))
            logger.debug("Exception information:\n%s", format_exc())

            return ERROR
        except CommandError as exc:
            logger.critical("ERROR: %s", exc)
            logger.debug("Exception information:\n%s", format_exc())

            return ERROR
        except KeyboardInterrupt:
            logger.critical("Operation cancelled by user")
            logger.debug("Exception information:\n%s", format_exc())

            return ERROR
        except:
            logger.critical("Exception:\n%s", format_exc())

            return UNKNOWN_ERROR

        return SUCCESS
Ejemplo n.º 9
0
    def main(self, args):
        options, args = self.parse_args(args)

        if options.quiet:
            level = "WARNING"
        elif options.verbose:
            level = "DEBUG"
        else:
            level = "INFO"

        logging_dictConfig({
            "version":
            1,
            "disable_existing_loggers":
            False,
            "formatters": {
                "indent": {
                    "()":
                    IndentingFormatter,
                    "format": ("%(message)s" if not options.log_explicit_levels
                               else "[%(levelname)s] %(message)s"),
                },
            },
            "handlers": {
                "console": {
                    "level": level,
                    "class": "pip.utils.logging.ColorizedStreamHandler",
                    "stream": self.log_stream,
                    "formatter": "indent",
                },
                "debug_log": {
                    "level":
                    "DEBUG",
                    "class":
                    "pip.utils.logging.BetterRotatingFileHandler",
                    "filename":
                    os.path.join(
                        appdirs.user_log_dir("pip"),
                        "debug.log",
                    ),
                    "maxBytes":
                    10 * 1000 * 1000,  # 10 MB
                    "backupCount":
                    1,
                    "delay":
                    True,
                    "formatter":
                    "indent",
                },
                "user_log": {
                    "level": "DEBUG",
                    "class": "pip.utils.logging.BetterRotatingFileHandler",
                    "filename": options.log or "/dev/null",
                    "delay": True,
                    "formatter": "indent",
                },
            },
            "root": {
                "level":
                level,
                "handlers":
                list(
                    filter(None, [
                        "console",
                        "debug_log",
                        "user_log" if options.log else None,
                    ])),
            },
            # Disable any logging besides WARNING unless we have DEBUG level
            # logging enabled. These use both pip._vendor and the bare names
            # for the case where someone unbundles our libraries.
            "loggers":
            dict((
                name,
                {
                    "level": (
                        "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"),
                },
            ) for name in ["pip._vendor", "distlib", "requests", "urllib3"]),
        })

        if options.log_explicit_levels:
            warnings.warn(
                "--log-explicit-levels has been deprecated and will be removed"
                " in a future version.",
                RemovedInPip8Warning,
            )

        # TODO: try to get these passing down from the command?
        #      without resorting to os.environ to hold these.

        if options.no_input:
            os.environ['PIP_NO_INPUT'] = '1'

        if options.exists_action:
            os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)

        if options.require_venv:
            # If a venv is required check if it can really be found
            if not running_under_virtualenv():
                logger.critical(
                    'Could not find an activated virtualenv (required).')
                sys.exit(VIRTUALENV_NOT_FOUND)

        # Check if we're using the latest version of pip available
        if (not options.disable_pip_version_check
                and not getattr(options, "no_index", False)):
            with self._build_session(options,
                                     retries=0,
                                     timeout=min(5,
                                                 options.timeout)) as session:
                pip_version_check(session)

        try:
            status = self.run(options, args)
            # FIXME: all commands should return an exit status
            # and when it is done, isinstance is not needed anymore
            if isinstance(status, int):
                return status
        except PreviousBuildDirError as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:\n%s', format_exc())

            return PREVIOUS_BUILD_DIR_ERROR
        except (InstallationError, UninstallationError, BadCommand) as exc:
            logger.critical(str(exc))
            logger.debug('Exception information:\n%s', format_exc())

            return ERROR
        except CommandError as exc:
            logger.critical('ERROR: %s', exc)
            logger.debug('Exception information:\n%s', format_exc())

            return ERROR
        except KeyboardInterrupt:
            logger.critical('Operation cancelled by user')
            logger.debug('Exception information:\n%s', format_exc())

            return ERROR
        except:
            logger.critical('Exception:\n%s', format_exc())

            return UNKNOWN_ERROR

        return SUCCESS