本文整理匯總了Python中pytest.UsageError方法的典型用法代碼示例。如果您正苦於以下問題:Python pytest.UsageError方法的具體用法?Python pytest.UsageError怎麽用?Python pytest.UsageError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pytest
的用法示例。
在下文中一共展示了pytest.UsageError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: consider_pluginarg
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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)
示例2: _get_plugin_specs_as_list
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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 []
示例3: pytest_cmdline_parse
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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
示例4: consider_pluginarg
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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)
示例5: _get_plugin_specs_as_list
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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
)
示例6: _checkversion
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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__,)
)
示例7: _get_override_ini_value
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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
示例8: get_log_level_for_setting
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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
示例9: assert_required_ansible_parameters
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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)
示例10: _getrsyncdirs
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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
示例11: pytest_configure
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
def pytest_configure(config):
if config.getoption("--target") == "plugin" and config.getoption("numprocesses"):
raise pytest.UsageError("Cannot use xdist with plugin tests, try adding the '-n 0' flag")
if config.getoption("--evm"):
# reformat evm options - only do this once to avoid repeat queries for latest solc version
solc_versions, evm_verions, runs = [i.split(",") for i in config.option.evm]
runs = [int(i) for i in runs]
if "latest" in solc_versions:
latest_version = solcx.get_available_solc_versions()[0]
solc_versions.remove("latest")
solc_versions.append(latest_version)
config.option.evm = (evm_verions, runs, solc_versions)
示例12: pytest_sessionfinish
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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)
示例13: main
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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
示例14: filename_arg
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
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
示例15: directory_arg
# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import UsageError [as 別名]
def directory_arg(path, optname):
"""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.