Python pytest.UsageError() Examples

The following are 30 code examples of pytest.UsageError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source File: __init__.py    From pytest with MIT License 6 votes vote down vote up
def consider_pluginarg(self, arg: str) -> None:
        if arg.startswith("no:"):
            name = arg[3:]
            if name in essential_plugins:
                raise UsageError("plugin %s cannot be disabled" % name)

            # PR #4304 : remove stepwise if cacheprovider is blocked
            if name == "cacheprovider":
                self.set_blocked("stepwise")
                self.set_blocked("pytest_stepwise")

            self.set_blocked(name)
            if not name.startswith("pytest_"):
                self.set_blocked("pytest_" + name)
        else:
            name = arg
            # Unblock the plugin.  None indicates that it has been blocked.
            # There is no interface with pluggy for this.
            if self._name2plugin.get(name, -1) is None:
                del self._name2plugin[name]
            if not name.startswith("pytest_"):
                if self._name2plugin.get("pytest_" + name, -1) is None:
                    del self._name2plugin["pytest_" + name]
            self.import_plugin(arg, consider_entry_points=True) 
Example #2
Source File: workermanage.py    From pytest-xdist with MIT License 6 votes vote down vote up
def _getrsyncdirs(self):
        for spec in self.specs:
            if not spec.popen or spec.chdir:
                break
        else:
            return []
        import pytest
        import _pytest

        pytestpath = pytest.__file__.rstrip("co")
        pytestdir = py.path.local(_pytest.__file__).dirpath()
        config = self.config
        candidates = [py._pydir, pytestpath, pytestdir]
        candidates += config.option.rsyncdir
        rsyncroots = config.getini("rsyncdirs")
        if rsyncroots:
            candidates.extend(rsyncroots)
        roots = []
        for root in candidates:
            root = py.path.local(root).realpath()
            if not root.check():
                raise pytest.UsageError("rsyncdir doesn't exist: {!r}".format(root))
            if root not in roots:
                roots.append(root)
        return roots 
Example #3
Source File: __init__.py    From pytest with MIT License 6 votes vote down vote up
def _get_plugin_specs_as_list(
    specs: Union[None, types.ModuleType, str, Sequence[str]]
) -> List[str]:
    """Parse a plugins specification into a list of plugin names."""
    # None means empty.
    if specs is None:
        return []
    # Workaround for #3899 - a submodule which happens to be called "pytest_plugins".
    if isinstance(specs, types.ModuleType):
        return []
    # Comma-separated list.
    if isinstance(specs, str):
        return specs.split(",") if specs else []
    # Direct specification.
    if isinstance(specs, collections.abc.Sequence):
        return list(specs)
    raise UsageError(
        "Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: %r"
        % specs
    ) 
Example #4
Source File: __init__.py    From pytest with MIT License 6 votes vote down vote up
def _checkversion(self) -> None:
        import pytest

        minver = self.inicfg.get("minversion", None)
        if minver:
            # Imported lazily to improve start-up time.
            from packaging.version import Version

            if not isinstance(minver, str):
                raise pytest.UsageError(
                    "%s: 'minversion' must be a single value" % self.inifile
                )

            if Version(minver) > Version(pytest.__version__):
                raise pytest.UsageError(
                    "%s: 'minversion' requires pytest-%s, actual pytest-%s'"
                    % (self.inifile, minver, pytest.__version__,)
                ) 
Example #5
Source File: __init__.py    From pytest with MIT License 6 votes vote down vote up
def _get_override_ini_value(self, name: str) -> Optional[str]:
        value = None
        # override_ini is a list of "ini=value" options
        # always use the last item if multiple values are set for same ini-name,
        # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2
        for ini_config in self._override_ini:
            try:
                key, user_ini_value = ini_config.split("=", 1)
            except ValueError as e:
                raise UsageError(
                    "-o/--override-ini expects option=value style (got: {!r}).".format(
                        ini_config
                    )
                ) from e
            else:
                if key == name:
                    value = user_ini_value
        return value 
Example #6
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def consider_pluginarg(self, arg):
        if arg.startswith("no:"):
            name = arg[3:]
            if name in essential_plugins:
                raise UsageError("plugin %s cannot be disabled" % name)

            # PR #4304 : remove stepwise if cacheprovider is blocked
            if name == "cacheprovider":
                self.set_blocked("stepwise")
                self.set_blocked("pytest_stepwise")

            self.set_blocked(name)
            if not name.startswith("pytest_"):
                self.set_blocked("pytest_" + name)
        else:
            name = arg
            # Unblock the plugin.  None indicates that it has been blocked.
            # There is no interface with pluggy for this.
            if self._name2plugin.get(name, -1) is None:
                del self._name2plugin[name]
            if not name.startswith("pytest_"):
                if self._name2plugin.get("pytest_" + name, -1) is None:
                    del self._name2plugin["pytest_" + name]
            self.import_plugin(arg, consider_entry_points=True) 
Example #7
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def _get_plugin_specs_as_list(specs):
    """
    Parses a list of "plugin specs" and returns a list of plugin names.

    Plugin specs can be given as a list of strings separated by "," or already as a list/tuple in
    which case it is returned as a list. Specs can also be `None` in which case an
    empty list is returned.
    """
    if specs is not None and not isinstance(specs, types.ModuleType):
        if isinstance(specs, str):
            specs = specs.split(",") if specs else []
        if not isinstance(specs, (list, tuple)):
            raise UsageError(
                "Plugin specs must be a ','-separated string or a "
                "list/tuple of strings for plugin names. Given: %r" % specs
            )
        return list(specs)
    return [] 
Example #8
Source File: logging.py    From pytest with MIT License 6 votes vote down vote up
def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]:
    for setting_name in setting_names:
        log_level = config.getoption(setting_name)
        if log_level is None:
            log_level = config.getini(setting_name)
        if log_level:
            break
    else:
        return None

    if isinstance(log_level, str):
        log_level = log_level.upper()
    try:
        return int(getattr(logging, log_level, log_level))
    except ValueError as e:
        # Python logging does not recognise this as a logging level
        raise pytest.UsageError(
            "'{}' is not recognized as a logging level name for "
            "'{}'. Please consider passing the "
            "logging level num instead.".format(log_level, setting_name)
        ) from e


# run after terminalreporter/capturemanager are configured 
Example #9
Source File: plugin.py    From pytest-ansible with MIT License 6 votes vote down vote up
def assert_required_ansible_parameters(config):
        """Assert whether the required --ansible-* parameters were provided."""
        errors = []

        # Verify --ansible-host-pattern was provided
        ansible_hostname = config.getoption('ansible_host_pattern')
        if ansible_hostname is None or ansible_hostname == '':
            errors.append("Missing required parameter --ansible-host-pattern/--host-pattern")

        # NOTE: I don't think this will ever catch issues since ansible_inventory
        # defaults to '/etc/ansible/hosts'
        # Verify --ansible-inventory was provided
        ansible_inventory = config.getoption('ansible_inventory')
        if ansible_inventory is None or ansible_inventory == "":
            errors.append("Unable to find an inventory file, specify one with the --ansible-inventory/--inventory "
                          "parameter.")

        if errors:
            raise pytest.UsageError(*errors) 
Example #10
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def pytest_cmdline_parse(self, pluginmanager, args):
        try:
            self.parse(args)
        except UsageError:

            # Handle --version and --help here in a minimal fashion.
            # This gets done via helpconfig normally, but its
            # pytest_cmdline_main is not called in case of errors.
            if getattr(self.option, "version", False) or "--version" in args:
                from _pytest.helpconfig import showversion

                showversion(self)
            elif (
                getattr(self.option, "help", False) or "--help" in args or "-h" in args
            ):
                self._parser._getparser().print_help()
                sys.stdout.write(
                    "\nNOTE: displaying only minimal help due to UsageError.\n\n"
                )

            raise

        return self 
Example #11
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def _get_plugin_specs_as_list(specs):
    """
    Parses a list of "plugin specs" and returns a list of plugin names.

    Plugin specs can be given as a list of strings separated by "," or already as a list/tuple in
    which case it is returned as a list. Specs can also be `None` in which case an
    empty list is returned.
    """
    if specs is not None and not isinstance(specs, types.ModuleType):
        if isinstance(specs, str):
            specs = specs.split(",") if specs else []
        if not isinstance(specs, (list, tuple)):
            raise UsageError(
                "Plugin specs must be a ','-separated string or a "
                "list/tuple of strings for plugin names. Given: %r" % specs
            )
        return list(specs)
    return [] 
Example #12
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def consider_pluginarg(self, arg):
        if arg.startswith("no:"):
            name = arg[3:]
            if name in essential_plugins:
                raise UsageError("plugin %s cannot be disabled" % name)

            # PR #4304 : remove stepwise if cacheprovider is blocked
            if name == "cacheprovider":
                self.set_blocked("stepwise")
                self.set_blocked("pytest_stepwise")

            self.set_blocked(name)
            if not name.startswith("pytest_"):
                self.set_blocked("pytest_" + name)
        else:
            name = arg
            # Unblock the plugin.  None indicates that it has been blocked.
            # There is no interface with pluggy for this.
            if self._name2plugin.get(name, -1) is None:
                del self._name2plugin[name]
            if not name.startswith("pytest_"):
                if self._name2plugin.get("pytest_" + name, -1) is None:
                    del self._name2plugin["pytest_" + name]
            self.import_plugin(arg, consider_entry_points=True) 
Example #13
Source File: conftest.py    From anchore-cli with Apache License 2.0 5 votes vote down vote up
def create_client():
    logger = get_logger('create_client')
    try:
        if use_environ():
            logger.info('using environment to create docker client')
            c = docker.from_env()
        else:
            c = docker.DockerClient(base_url='unix://var/run/docker.sock', version="auto")
        # XXX ?
        c.run = run(c)
        return c
    except DockerException as e:
        logger.exception('Unable to connect to a docker socket')
        raise pytest.UsageError("Could not connect to a running docker socket: %s" % str(e)) 
Example #14
Source File: conftest.py    From pytest with MIT License 5 votes vote down vote up
def pytest_configure(config):
    import pytest

    raise pytest.UsageError("hello") 
Example #15
Source File: conftest.py    From py-solc-x with MIT License 5 votes vote down vote up
def pytest_configure(config):
    global VERSIONS
    if config.getoption("--no-install"):
        VERSIONS = solcx.get_installed_solc_versions()
        return
    try:
        VERSIONS = solcx.get_available_solc_versions()
    except ConnectionError:
        raise pytest.UsageError(
            "ConnectionError while attempting to get solc versions.\n"
            "Use the --no-install flag to only run tests against already installed versions."
        )


# auto-parametrize the all_versions fixture with all target solc versions 
Example #16
Source File: master.py    From brownie with MIT License 5 votes vote down vote up
def pytest_sessionfinish(self, session):
        """
        Called after whole test run finished, right before returning the exit
        status to the system.

        * Aggregates results from `build/tests-{workerid}.json` files and stores
          them as `build/test.json`.
        """
        if session.testscollected == 0:
            raise pytest.UsageError(
                "xdist workers failed to collect tests. Ensure all test cases are "
                "isolated with the module_isolation or fn_isolation fixtures.\n\n"
                "https://eth-brownie.readthedocs.io/en/stable/tests.html#isolating-tests"
            )
        build_path = self.project._build_path

        # aggregate worker test results
        report = {"tests": {}, "contracts": self.contracts, "tx": {}}
        for path in list(build_path.glob("tests-*.json")):
            with path.open() as fp:
                data = json.load(fp)
            assert data["contracts"] == report["contracts"]
            report["tests"].update(data["tests"])
            report["tx"].update(data["tx"])
            path.unlink()

        # store worker coverage results - these are used in `pytest_terminal_summary`
        for hash_, coverage_eval in report["tx"].items():
            coverage._add_transaction(hash_, coverage_eval)

        # save aggregate test results
        with build_path.joinpath("tests.json").open("w") as fp:
            json.dump(report, fp, indent=2, sort_keys=True, default=sorted) 
Example #17
Source File: plugin.py    From pytest-ansible with MIT License 5 votes vote down vote up
def pytest_generate_tests(metafunc):
    """Generate tests when specific `ansible_*` fixtures are used by tests."""
    log.debug("pytest_generate_tests() called")

    if 'ansible_host' in metafunc.fixturenames:
        # assert required --ansible-* parameters were used
        PyTestAnsiblePlugin.assert_required_ansible_parameters(metafunc.config)
        try:
            plugin = metafunc.config.pluginmanager.getplugin("ansible")
            hosts = plugin.initialize(config=plugin.config, pattern=metafunc.config.getoption('ansible_host_pattern'))
        except ansible.errors.AnsibleError as e:
            raise pytest.UsageError(e)
        # Return the host name as a string
        # metafunc.parametrize("ansible_host", hosts.keys())
        # Return a HostManager instance where pattern=host (e.g. ansible_host.all.shell('date'))
        # metafunc.parametrize("ansible_host", iter(plugin.initialize(config=plugin.config, pattern=h) for h in
        #                                           hosts.keys()))
        # Return a ModuleDispatcher instance representing `host` (e.g. ansible_host.shell('date'))
        metafunc.parametrize("ansible_host", iter(hosts[h] for h in hosts.keys()))

    if 'ansible_group' in metafunc.fixturenames:
        # assert required --ansible-* parameters were used
        PyTestAnsiblePlugin.assert_required_ansible_parameters(metafunc.config)
        try:
            plugin = metafunc.config.pluginmanager.getplugin("ansible")
            hosts = plugin.initialize(config=plugin.config, pattern=metafunc.config.getoption('ansible_host_pattern'))
        except ansible.errors.AnsibleError as e:
            raise pytest.UsageError(e)
        # FIXME: Eeew, this shouldn't be interfacing with `hosts.options`
        groups = hosts.options['inventory_manager'].list_groups()
        # Return the group name as a string
        # metafunc.parametrize("ansible_group", groups)
        # Return a ModuleDispatcher instance representing the group (e.g. ansible_group.shell('date'))
        metafunc.parametrize("ansible_group", iter(hosts[g] for g in groups)) 
Example #18
Source File: session.py    From pytest-benchmark with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def check_regressions(self):
        if self.compare_fail and not self.compared_mapping:
            raise pytest.UsageError("--benchmark-compare-fail requires valid --benchmark-compare.")

        if self.performance_regressions:
            self.logger.error("Performance has regressed:\n%s" % "\n".join(
                "\t%s - %s" % line for line in self.performance_regressions
            ))
            raise PerformanceRegression("Performance has regressed.") 
Example #19
Source File: looponfail.py    From pytest-xdist with MIT License 5 votes vote down vote up
def pytest_cmdline_main(config):

    if config.getoption("looponfail"):
        usepdb = config.getoption("usepdb", False)  # a core option
        if usepdb:
            raise pytest.UsageError("--pdb is incompatible with --looponfail.")
        looponfail_main(config)
        return 2  # looponfail only can get stop with ctrl-C anyway 
Example #20
Source File: looponfail.py    From pytest-xdist with MIT License 5 votes vote down vote up
def pytest_collection(self, session):
        self.session = session
        self.trails = self.current_command
        hook = self.session.ihook
        try:
            items = session.perform_collect(self.trails or None)
        except pytest.UsageError:
            items = session.perform_collect(None)
        hook.pytest_collection_modifyitems(
            session=session, config=session.config, items=items
        )
        hook.pytest_collection_finish(session=session)
        return True 
Example #21
Source File: workermanage.py    From pytest-xdist with MIT License 5 votes vote down vote up
def parse_spec_config(config):
    xspeclist = []
    for xspec in config.getvalue("tx"):
        i = xspec.find("*")
        try:
            num = int(xspec[:i])
        except ValueError:
            xspeclist.append(xspec)
        else:
            xspeclist.extend([xspec[i + 1 :]] * num)
    if not xspeclist:
        raise pytest.UsageError(
            "MISSING test execution (tx) nodes: please specify --tx"
        )
    return xspeclist 
Example #22
Source File: plugin.py    From pytest-xdist with MIT License 5 votes vote down vote up
def pytest_cmdline_main(config):
    usepdb = config.getoption("usepdb", False)  # a core option
    if isinstance(config.option.numprocesses, AutoInt):
        config.option.numprocesses = 0 if usepdb else int(config.option.numprocesses)

    if config.option.numprocesses:
        if config.option.dist == "no":
            config.option.dist = "load"
        numprocesses = config.option.numprocesses
        if config.option.maxprocesses:
            numprocesses = min(numprocesses, config.option.maxprocesses)
        config.option.tx = ["popen"] * numprocesses
    if config.option.distload:
        config.option.dist = "load"
    val = config.getvalue
    if not val("collectonly"):
        if val("dist") != "no":
            if usepdb:
                raise pytest.UsageError(
                    "--pdb is incompatible with distributing tests; try using -n0 or -nauto."
                )  # noqa: E501


# -------------------------------------------------------------------------
# fixtures
# ------------------------------------------------------------------------- 
Example #23
Source File: __init__.py    From pytest with MIT License 5 votes vote down vote up
def directory_arg(path: str, optname: str) -> str:
    """Argparse type validator for directory arguments.

    :path: path of directory
    :optname: name of the option
    """
    if not os.path.isdir(path):
        raise UsageError("{} must be a directory, given: {}".format(optname, path))
    return path


# Plugins that cannot be disabled via "-p no:X" currently. 
Example #24
Source File: __init__.py    From pytest with MIT License 5 votes vote down vote up
def filename_arg(path: str, optname: str) -> str:
    """ Argparse type validator for filename arguments.

    :path: path of filename
    :optname: name of the option
    """
    if os.path.isdir(path):
        raise UsageError("{} must be a filename, given: {}".format(optname, path))
    return path 
Example #25
Source File: list_tests.py    From pex with Apache License 2.0 5 votes vote down vote up
def pytest_collectreport(self, report):
    if report.failed:
      raise pytest.UsageError('Errors during collection, aborting!') 
Example #26
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def _get_override_ini_value(self, name):
        value = None
        # override_ini is a list of "ini=value" options
        # always use the last item if multiple values are set for same ini-name,
        # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2
        for ini_config in self._override_ini:
            try:
                key, user_ini_value = ini_config.split("=", 1)
            except ValueError:
                raise UsageError("-o/--override-ini expects option=value style.")
            else:
                if key == name:
                    value = user_ini_value
        return value 
Example #27
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def _checkversion(self):
        import pytest

        minver = self.inicfg.get("minversion", None)
        if minver:
            if Version(minver) > Version(pytest.__version__):
                raise pytest.UsageError(
                    "%s:%d: requires pytest-%s, actual pytest-%s'"
                    % (
                        self.inicfg.config.path,
                        self.inicfg.lineof("minversion"),
                        minver,
                        pytest.__version__,
                    )
                ) 
Example #28
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def filename_arg(path, optname):
    """ Argparse type validator for filename arguments.

    :path: path of filename
    :optname: name of the option
    """
    if os.path.isdir(path):
        raise UsageError("{} must be a filename, given: {}".format(optname, path))
    return path 
Example #29
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def main(args=None, plugins=None):
    """ return exit code, after performing an in-process test run.

    :arg args: list of command line arguments.

    :arg plugins: list of plugin objects to be auto-registered during
                  initialization.
    """
    from _pytest.main import ExitCode

    try:
        try:
            config = _prepareconfig(args, plugins)
        except ConftestImportFailure as e:
            exc_info = ExceptionInfo(e.excinfo)
            tw = py.io.TerminalWriter(sys.stderr)
            tw.line(
                "ImportError while loading conftest '{e.path}'.".format(e=e), red=True
            )
            exc_info.traceback = exc_info.traceback.filter(filter_traceback)
            exc_repr = (
                exc_info.getrepr(style="short", chain=False)
                if exc_info.traceback
                else exc_info.exconly()
            )
            formatted_tb = str(exc_repr)
            for line in formatted_tb.splitlines():
                tw.line(line.rstrip(), red=True)
            return 4
        else:
            try:
                return config.hook.pytest_cmdline_main(config=config)
            finally:
                config._ensure_unconfigure()
    except UsageError as e:
        tw = py.io.TerminalWriter(sys.stderr)
        for msg in e.args:
            tw.line("ERROR: {}\n".format(msg), red=True)
        return ExitCode.USAGE_ERROR 
Example #30
Source File: logging.py    From python-netsurv with MIT License 5 votes vote down vote up
def get_actual_log_level(config, *setting_names):
    """Return the actual logging level."""

    for setting_name in setting_names:
        log_level = config.getoption(setting_name)
        if log_level is None:
            log_level = config.getini(setting_name)
        if log_level:
            break
    else:
        return

    if isinstance(log_level, str):
        log_level = log_level.upper()
    try:
        return int(getattr(logging, log_level, log_level))
    except ValueError:
        # Python logging does not recognise this as a logging level
        raise pytest.UsageError(
            "'{}' is not recognized as a logging level name for "
            "'{}'. Please consider passing the "
            "logging level num instead.".format(log_level, setting_name)
        )


# run after terminalreporter/capturemanager are configured