pytest API Reference
Full documentation for pytest (8.3.3)
pytest.Cache
Python Library Documentation: class Cache in module _pytest.cacheprovider
class Cache(builtins.object)
| Cache(cachedir: 'Path', config: 'Config', *, _ispytest: 'bool' = False) -> 'None'
|
| Instance of the `cache` fixture.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, cachedir: 'Path', config: 'Config', *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| get(self, key: 'str', default)
| Return the cached value for the given key.
|
| If no value was yet cached or the value cannot be read, the specified
| default is returned.
|
| :param key:
| Must be a ``/`` separated value. Usually the first
| name is the name of your plugin or your application.
| :param default:
| The value to return in case of a cache-miss or invalid cache value.
|
| mkdir(self, name: 'str') -> 'Path'
| Return a directory path object with the given name.
|
| If the directory does not yet exist, it will be created. You can use
| it to manage files to e.g. store/retrieve database dumps across test
| sessions.
|
| .. versionadded:: 7.0
|
| :param name:
| Must be a string not containing a ``/`` separator.
| Make sure the name contains your plugin or application
| identifiers to prevent clashes with other cache users.
|
| set(self, key: 'str', value: 'object') -> 'None'
| Save value for the given key.
|
| :param key:
| Must be a ``/`` separated value. Usually the first
| name is the name of your plugin or your application.
| :param value:
| Must be of any combination of basic python types,
| including nested types like lists of dictionaries.
|
| warn(self, fmt: 'str', *, _ispytest: 'bool' = False, **args: 'object') -> 'None'
| Issue a cache warning.
|
| :meta private:
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| clear_cache(cachedir: 'Path', _ispytest: 'bool' = False) -> 'None'
| Clear the sub-directories used to hold cached directories and values.
|
| :meta private:
|
| for_config(config: 'Config', *, _ispytest: 'bool' = False) -> 'Cache'
| Create the Cache instance for a Config.
|
| :meta private:
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| cache_dir_from_config(config: 'Config', *, _ispytest: 'bool' = False) -> 'Path'
| Get the path to the cache directory for a Config.
|
| :meta private:
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_cachedir': 'Path', '_config': 'Config'}
|
| __dataclass_fields__ = {'_cachedir': Field(name='_cachedir',type='Path...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __final__ = True
|
| __hash__ = None
|
| __match_args__ = ('_cachedir', '_config')
pytest.CallInfo
Python Library Documentation: class CallInfo in module _pytest.runner
class CallInfo(typing.Generic)
| CallInfo(result: 'TResult | None', excinfo: 'ExceptionInfo[BaseException] | None', start: 'float', stop: 'float', duration: 'float', when: "Literal['collect', 'setup', 'call', 'teardown']", *, _ispytest: 'bool' = False) -> 'None'
|
| Result/Exception info of a function invocation.
|
| Method resolution order:
| CallInfo
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, result: 'TResult | None', excinfo: 'ExceptionInfo[BaseException] | None', start: 'float', stop: 'float', duration: 'float', when: "Literal['collect', 'setup', 'call', 'teardown']", *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_call(func: 'Callable[[], TResult]', when: "Literal['collect', 'setup', 'call', 'teardown']", reraise: 'type[BaseException] | tuple[type[BaseException], ...] | None' = None) -> 'CallInfo[TResult]'
| Call func, wrapping the result in a CallInfo.
|
| :param func:
| The function to call. Called without arguments.
| :type func: Callable[[], _pytest.runner.TResult]
| :param when:
| The phase in which the function is called.
| :param reraise:
| Exception or exceptions that shall propagate if raised by the
| function, instead of being wrapped in the CallInfo.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| result
| The return value of the call, if it didn't raise.
|
| Can only be accessed if excinfo is None.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_result': 'TResult | None', 'duration': 'float', '...
|
| __dataclass_fields__ = {'_result': Field(name='_result',type='TResult ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __final__ = True
|
| __hash__ = None
|
| __match_args__ = ('_result', 'excinfo', 'start', 'stop', 'duration', '...
|
| __orig_bases__ = (typing.Generic[+TResult],)
|
| __parameters__ = (+TResult,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pytest.CaptureFixture
Python Library Documentation: class CaptureFixture in module _pytest.capture
class CaptureFixture(typing.Generic)
| CaptureFixture(captureclass: 'type[CaptureBase[AnyStr]]', request: 'SubRequest', *, _ispytest: 'bool' = False) -> 'None'
|
| Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`,
| :fixture:`capfd` and :fixture:`capfdbinary` fixtures.
|
| Method resolution order:
| CaptureFixture
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, captureclass: 'type[CaptureBase[AnyStr]]', request: 'SubRequest', *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| close(self) -> 'None'
|
| disabled(self) -> 'Generator[None]'
| Temporarily disable capturing while inside the ``with`` block.
|
| readouterr(self) -> 'CaptureResult[AnyStr]'
| Read and return the captured output so far, resetting the internal
| buffer.
|
| :returns:
| The captured content as a namedtuple with ``out`` and ``err``
| string attributes.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~AnyStr],)
|
| __parameters__ = (~AnyStr,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pytest.Class
Python Library Documentation: class Class in module _pytest.python
class Class(PyCollector)
| Class(*k, **kw) -> 'NoReturn'
|
| Collector for test methods (and nested classes) in a Python class.
|
| Method resolution order:
| Class
| PyCollector
| PyobjMixin
| _pytest.nodes.Collector
| _pytest.nodes.Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| collect(self) -> 'Iterable[nodes.Item | nodes.Collector]'
| Collect children (items and collectors) for this collector.
|
| newinstance(self)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_parent(parent, *, name, obj=None, **kw) -> 'Self'
| The public constructor.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyCollector:
|
| classnamefilter(self, name: 'str') -> 'bool'
|
| funcnamefilter(self, name: 'str') -> 'bool'
|
| isnosetest(self, obj: 'object') -> 'bool'
| Look for the __test__ attribute, which is applied by the
| @nose.tools.istest decorator.
|
| istestclass(self, obj: 'object', name: 'str') -> 'bool'
|
| istestfunction(self, obj: 'object', name: 'str') -> 'bool'
|
| ----------------------------------------------------------------------
| Methods inherited from PyobjMixin:
|
| getmodpath(self, stopatmodule: 'bool' = True, includemodule: 'bool' = False) -> 'str'
| Return Python path relative to the containing module.
|
| reportinfo(self) -> 'tuple[os.PathLike[str] | str, int | None, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyobjMixin:
|
| cls
| Python class object this node was collected from (can be None).
|
| instance
| Python instance object the function is bound to.
|
| Returns None if not a test method, e.g. for a standalone test function,
| a class or a module.
|
| module
| Python module object this node was collected from (can be None).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyobjMixin:
|
| __weakref__
| list of weak references to the object
|
| obj
| Underlying Python object.
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Collector:
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _pytest.nodes.Collector:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __init__(self, name: 'str', parent: 'Node | None' = None, config: 'Config | None' = None, session: 'Session | None' = None, fspath: 'LEGACY_PATH | None' = None, path: 'Path | None' = None, nodeid: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _pytest.nodes.Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.CollectReport
Python Library Documentation: class CollectReport in module _pytest.reports
class CollectReport(BaseReport)
| CollectReport(nodeid: 'str', outcome: "Literal['passed', 'failed', 'skipped']", longrepr: 'None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr', result: 'list[Item | Collector] | None', sections: 'Iterable[tuple[str, str]]' = (), **extra) -> 'None'
|
| Collection report object.
|
| Reports can contain arbitrary extra attributes.
|
| Method resolution order:
| CollectReport
| BaseReport
| builtins.object
|
| Methods defined here:
|
| __init__(self, nodeid: 'str', outcome: "Literal['passed', 'failed', 'skipped']", longrepr: 'None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr', result: 'list[Item | Collector] | None', sections: 'Iterable[tuple[str, str]]' = (), **extra) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| location
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __final__ = True
|
| when = 'collect'
|
| ----------------------------------------------------------------------
| Methods inherited from BaseReport:
|
| get_sections(self, prefix: 'str') -> 'Iterator[tuple[str, str]]'
|
| toterminal(self, out: 'TerminalWriter') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseReport:
|
| caplog
| Return captured log lines, if log capturing is enabled.
|
| .. versionadded:: 3.5
|
| capstderr
| Return captured text from stderr, if capturing is enabled.
|
| .. versionadded:: 3.0
|
| capstdout
| Return captured text from stdout, if capturing is enabled.
|
| .. versionadded:: 3.0
|
| count_towards_summary
| **Experimental** Whether this report should be counted towards the
| totals shown at the end of the test session: "1 passed, 1 failure, etc".
|
| .. note::
|
| This function is considered **experimental**, so beware that it is subject to changes
| even in patch releases.
|
| failed
| Whether the outcome is failed.
|
| fspath
| The path portion of the reported node, as a string.
|
| head_line
| **Experimental** The head line shown with longrepr output for this
| report, more commonly during traceback representation during
| failures::
|
| ________ Test.foo ________
|
|
| In the example above, the head_line is "Test.foo".
|
| .. note::
|
| This function is considered **experimental**, so beware that it is subject to changes
| even in patch releases.
|
| longreprtext
| Read-only property that returns the full string representation of
| ``longrepr``.
|
| .. versionadded:: 3.0
|
| passed
| Whether the outcome is passed.
|
| skipped
| Whether the outcome is skipped.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseReport:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
pytest.Collector
Python Library Documentation: class Collector in module _pytest.nodes
class Collector(Node, abc.ABC)
| Collector(*k, **kw) -> 'NoReturn'
|
| Base class of all collectors.
|
| Collector create children through `collect()` and thus iteratively build
| the collection tree.
|
| Method resolution order:
| Collector
| Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| collect(self) -> 'Iterable[Item | Collector]'
| Collect children (items and collectors) for this collector.
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| __abstractmethods__ = frozenset({'collect'})
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __init__(self, name: 'str', parent: 'Node | None' = None, config: 'Config | None' = None, session: 'Session | None' = None, fspath: 'LEGACY_PATH | None' = None, path: 'Path | None' = None, nodeid: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Node:
|
| from_parent(parent: 'Node', **kw) -> 'Self'
| Public constructor for Nodes.
|
| This indirection got introduced in order to enable removing
| the fragile logic from the node constructors.
|
| Subclasses can use ``super().from_parent(...)`` when overriding the
| construction.
|
| :param parent: The parent node of this Node.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.Config
Python Library Documentation: class Config in module _pytest.config
class Config(builtins.object)
| Config(pluginmanager: 'PytestPluginManager', *, invocation_params: 'InvocationParams | None' = None) -> 'None'
|
| Access to configuration values, pluginmanager and plugin hooks.
|
| :param PytestPluginManager pluginmanager:
| A pytest PluginManager.
|
| :param InvocationParams invocation_params:
| Object containing parameters regarding the :func:`pytest.main`
| invocation.
|
| Methods defined here:
|
| __init__(self, pluginmanager: 'PytestPluginManager', *, invocation_params: 'InvocationParams | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| add_cleanup(self, func: 'Callable[[], None]') -> 'None'
| Add a function to be called when the config object gets out of
| use (usually coinciding with pytest_unconfigure).
|
| addinivalue_line(self, name: 'str', line: 'str') -> 'None'
| Add a line to an ini-file option. The option must have been
| declared but might not yet be set in which case the line becomes
| the first line in its value.
|
| cwd_relative_nodeid(self, nodeid: 'str') -> 'str'
|
| get_terminal_writer(self) -> 'TerminalWriter'
|
| get_verbosity(self, verbosity_type: 'str | None' = None) -> 'int'
| Retrieve the verbosity level for a fine-grained verbosity type.
|
| :param verbosity_type: Verbosity type to get level for. If a level is
| configured for the given type, that value will be returned. If the
| given type is not a known verbosity type, the global verbosity
| level will be returned. If the given type is None (default), the
| global verbosity level will be returned.
|
| To configure a level for a fine-grained verbosity type, the
| configuration file should have a setting for the configuration name
| and a numeric value for the verbosity level. A special value of "auto"
| can be used to explicitly use the global verbosity level.
|
| Example:
|
| .. code-block:: ini
|
| # content of pytest.ini
| [pytest]
| verbosity_assertions = 2
|
| .. code-block:: console
|
| pytest -v
|
| .. code-block:: python
|
| print(config.get_verbosity()) # 1
| print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS)) # 2
|
| getini(self, name: 'str')
| Return configuration value from an :ref:`ini file <configfiles>`.
|
| If a configuration value is not defined in an
| :ref:`ini file <configfiles>`, then the ``default`` value provided while
| registering the configuration through
| :func:`parser.addini <pytest.Parser.addini>` will be returned.
| Please note that you can even provide ``None`` as a valid
| default value.
|
| If ``default`` is not provided while registering using
| :func:`parser.addini <pytest.Parser.addini>`, then a default value
| based on the ``type`` parameter passed to
| :func:`parser.addini <pytest.Parser.addini>` will be returned.
| The default values based on ``type`` are:
| ``paths``, ``pathlist``, ``args`` and ``linelist`` : empty list ``[]``
| ``bool`` : ``False``
| ``string`` : empty string ``""``
|
| If neither the ``default`` nor the ``type`` parameter is passed
| while registering the configuration through
| :func:`parser.addini <pytest.Parser.addini>`, then the configuration
| is treated as a string and a default empty string '' is returned.
|
| If the specified name hasn't been registered through a prior
| :func:`parser.addini <pytest.Parser.addini>` call (usually from a
| plugin), a ValueError is raised.
|
| getoption(self, name: 'str', default=<NOTSET>, skip: 'bool' = False)
| Return command line option value.
|
| :param name: Name of the option. You may also specify
| the literal ``--OPT`` option instead of the "dest" option name.
| :param default: Default value if no option of that name exists.
| :param skip: If True, raise pytest.skip if option does not exists
| or has a None value.
|
| getvalue(self, name: 'str', path=None)
| Deprecated, use getoption() instead.
|
| getvalueorskip(self, name: 'str', path=None)
| Deprecated, use getoption(skip=True) instead.
|
| issue_config_time_warning(self, warning: 'Warning', stacklevel: 'int') -> 'None'
| Issue and handle a warning during the "configure" stage.
|
| During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item``
| function because it is not possible to have hook wrappers around ``pytest_configure``.
|
| This function is mainly intended for plugins that need to issue warnings during
| ``pytest_configure`` (or similar stages).
|
| :param warning: The warning instance.
| :param stacklevel: stacklevel forwarded to warnings.warn.
|
| notify_exception(self, excinfo: 'ExceptionInfo[BaseException]', option: 'argparse.Namespace | None' = None) -> 'None'
|
| parse(self, args: 'list[str]', addopts: 'bool' = True) -> 'None'
|
| pytest_cmdline_parse(self, pluginmanager: 'PytestPluginManager', args: 'list[str]') -> 'Config'
|
| pytest_collection(self) -> 'Generator[None, object, object]'
|
| pytest_load_initial_conftests(self, early_config: 'Config') -> 'None'
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| fromdictargs(option_dict, args) -> 'Config'
| Constructor usable for subprocesses.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| inipath
| The path to the :ref:`configfile <configfiles>`.
|
| .. versionadded:: 6.1
|
| rootpath
| The path to the :ref:`rootdir <rootdir>`.
|
| :type: pathlib.Path
|
| .. versionadded:: 6.1
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| ArgsSource = <enum 'ArgsSource'>
| Indicates the source of the test arguments.
|
| .. versionadded:: 7.2
|
|
| InvocationParams = <class '_pytest.config.Config.InvocationParams'>
| Holds parameters passed during :func:`pytest.main`.
|
| The object attributes are read-only.
|
| .. versionadded:: 5.1
|
| .. note::
|
| Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts``
| ini option are handled by pytest, not being included in the ``args`` attribute.
|
| Plugins accessing ``InvocationParams`` must be aware of that.
|
|
| VERBOSITY_ASSERTIONS = 'assertions'
|
| VERBOSITY_TEST_CASES = 'test_cases'
|
| __annotations__ = {'VERBOSITY_ASSERTIONS': 'Final', 'VERBOSITY_TEST_CA...
|
| __final__ = True
pytest.Dir
Python Library Documentation: class Dir in module _pytest.main
class Dir(_pytest.nodes.Directory)
| Dir(*k, **kw) -> 'NoReturn'
|
| Collector of files in a file system directory.
|
| .. versionadded:: 8.0
|
| .. note::
|
| Python directories with an `__init__.py` file are instead collected by
| :class:`~pytest.Package` by default. Both are :class:`~pytest.Directory`
| collectors.
|
| Method resolution order:
| Dir
| _pytest.nodes.Directory
| _pytest.nodes.FSCollector
| _pytest.nodes.Collector
| _pytest.nodes.Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| collect(self) -> 'Iterable[nodes.Item | nodes.Collector]'
| Collect children (items and collectors) for this collector.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_parent(parent: 'nodes.Collector', *, path: 'Path') -> 'Self'
| The public constructor.
|
| :param parent: The parent collector of this Dir.
| :param path: The directory's path.
| :type path: pathlib.Path
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __final__ = True
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.FSCollector:
|
| __init__(self, fspath: 'LEGACY_PATH | None' = None, path_or_parent: 'Path | Node | None' = None, path: 'Path | None' = None, name: 'str | None' = None, parent: 'Node | None' = None, config: 'Config | None' = None, session: 'Session | None' = None, nodeid: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Collector:
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Collector:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _pytest.nodes.Collector:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _pytest.nodes.Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.Directory
Python Library Documentation: class Directory in module _pytest.nodes
class Directory(FSCollector, abc.ABC)
| Directory(*k, **kw) -> 'NoReturn'
|
| Base class for collecting files from a directory.
|
| A basic directory collector does the following: goes over the files and
| sub-directories in the directory and creates collectors for them by calling
| the hooks :hook:`pytest_collect_directory` and :hook:`pytest_collect_file`,
| after checking that they are not ignored using
| :hook:`pytest_ignore_collect`.
|
| The default directory collectors are :class:`~pytest.Dir` and
| :class:`~pytest.Package`.
|
| .. versionadded:: 8.0
|
| :ref:`custom directory collectors`.
|
| Method resolution order:
| Directory
| FSCollector
| Collector
| Node
| abc.ABC
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'collect'})
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from FSCollector:
|
| __init__(self, fspath: 'LEGACY_PATH | None' = None, path_or_parent: 'Path | Node | None' = None, path: 'Path | None' = None, name: 'str | None' = None, parent: 'Node | None' = None, config: 'Config | None' = None, session: 'Session | None' = None, nodeid: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Class methods inherited from FSCollector:
|
| from_parent(parent, *, fspath: 'LEGACY_PATH | None' = None, path: 'Path | None' = None, **kw) -> 'Self'
| The public constructor.
|
| ----------------------------------------------------------------------
| Methods inherited from Collector:
|
| collect(self) -> 'Iterable[Item | Collector]'
| Collect children (items and collectors) for this collector.
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Collector:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Collector:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| ----------------------------------------------------------------------
| Methods inherited from Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.DoctestItem
Python Library Documentation: class DoctestItem in module _pytest.doctest
class DoctestItem(_pytest.nodes.Item)
| DoctestItem(*k, **kw) -> 'NoReturn'
|
| Method resolution order:
| DoctestItem
| _pytest.nodes.Item
| _pytest.nodes.Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', parent: 'DoctestTextfile | DoctestModule', runner: 'doctest.DocTestRunner', dtest: 'doctest.DocTest') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| reportinfo(self) -> 'tuple[os.PathLike[str] | str, int | None, str]'
| Get location information for this item for test reports.
|
| Returns a tuple with three elements:
|
| - The path of the test (default ``self.path``)
| - The 0-based line number of the test (default ``None``)
| - A name of the test to be shown (default ``""``)
|
| .. seealso:: :ref:`non-python tests`
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection or test failure.
|
| .. seealso:: :ref:`non-python tests`
|
| :param excinfo: Exception information for the failure.
|
| runtest(self) -> 'None'
| Run the test case for this item.
|
| Must be implemented by subclasses.
|
| .. seealso:: :ref:`non-python tests`
|
| setup(self) -> 'None'
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_parent(parent: 'DoctestTextfile | DoctestModule', *, name: 'str', runner: 'doctest.DocTestRunner', dtest: 'doctest.DocTest') -> 'Self'
| The public named constructor.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Item:
|
| add_report_section(self, when: 'str', key: 'str', content: 'str') -> 'None'
| Add a new report section, similar to what's done internally to add
| stdout and stderr captured output::
|
| item.add_report_section("call", "stdout", "report section contents")
|
| :param str when:
| One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``.
| :param str key:
| Name of the section, can be customized at will. Pytest uses ``"stdout"`` and
| ``"stderr"`` internally.
| :param str content:
| The full contents as a string.
|
| location = <functools.cached_property object>
| Returns a tuple of ``(relfspath, lineno, testname)`` for this item
| where ``relfspath`` is file path relative to ``config.rootpath``
| and lineno is a 0-based line number.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Item:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _pytest.nodes.Item:
|
| nextitem = None
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _pytest.nodes.Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.ExceptionInfo
Python Library Documentation: class ExceptionInfo in module _pytest._code.code
class ExceptionInfo(typing.Generic)
| ExceptionInfo(excinfo: 'tuple[type[E], E, TracebackType] | None', striptext: 'str' = '', traceback: 'Traceback | None' = None, *, _ispytest: 'bool' = False) -> 'None'
|
| Wraps sys.exc_info() objects and offers help for navigating the traceback.
|
| Method resolution order:
| ExceptionInfo
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, excinfo: 'tuple[type[E], E, TracebackType] | None', striptext: 'str' = '', traceback: 'Traceback | None' = None, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| errisinstance(self, exc: 'EXCEPTION_OR_MORE') -> 'bool'
| Return True if the exception is an instance of exc.
|
| Consider using ``isinstance(excinfo.value, exc)`` instead.
|
| exconly(self, tryshort: 'bool' = False) -> 'str'
| Return the exception as a string.
|
| When 'tryshort' resolves to True, and the exception is an
| AssertionError, only the actual exception part of the exception
| representation is returned (so 'AssertionError: ' is removed from
| the beginning).
|
| fill_unfilled(self, exc_info: 'tuple[type[E], E, TracebackType]') -> 'None'
| Fill an unfilled ExceptionInfo created with ``for_later()``.
|
| getrepr(self, showlocals: 'bool' = False, style: 'TracebackStyle' = 'long', abspath: 'bool' = False, tbfilter: 'bool | Callable[[ExceptionInfo[BaseException]], _pytest._code.code.Traceback]' = True, funcargs: 'bool' = False, truncate_locals: 'bool' = True, truncate_args: 'bool' = True, chain: 'bool' = True) -> 'ReprExceptionInfo | ExceptionChainRepr'
| Return str()able representation of this exception info.
|
| :param bool showlocals:
| Show locals per traceback entry.
| Ignored if ``style=="native"``.
|
| :param str style:
| long|short|line|no|native|value traceback style.
|
| :param bool abspath:
| If paths should be changed to absolute or left unchanged.
|
| :param tbfilter:
| A filter for traceback entries.
|
| * If false, don't hide any entries.
| * If true, hide internal entries and entries that contain a local
| variable ``__tracebackhide__ = True``.
| * If a callable, delegates the filtering to the callable.
|
| Ignored if ``style`` is ``"native"``.
|
| :param bool funcargs:
| Show fixtures ("funcargs" for legacy purposes) per traceback entry.
|
| :param bool truncate_locals:
| With ``showlocals==True``, make sure locals can be safely represented as strings.
|
| :param bool truncate_args:
| With ``showargs==True``, make sure args can be safely represented as strings.
|
| :param bool chain:
| If chained exceptions in Python 3 should be shown.
|
| .. versionchanged:: 3.9
|
| Added the ``chain`` parameter.
|
| group_contains(self, expected_exception: 'EXCEPTION_OR_MORE', *, match: 'str | Pattern[str] | None' = None, depth: 'int | None' = None) -> 'bool'
| Check whether a captured exception group contains a matching exception.
|
| :param Type[BaseException] | Tuple[Type[BaseException]] expected_exception:
| The expected exception type, or a tuple if one of multiple possible
| exception types are expected.
|
| :param str | Pattern[str] | None match:
| If specified, a string containing a regular expression,
| or a regular expression object, that is tested against the string
| representation of the exception and its `PEP-678 <https://peps.python.org/pep-0678/>` `__notes__`
| using :func:`re.search`.
|
| To match a literal string that may contain :ref:`special characters
| <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
|
| :param Optional[int] depth:
| If `None`, will search for a matching exception at any nesting depth.
| If >= 1, will only match an exception if it's at the specified depth (depth = 1 being
| the exceptions contained within the topmost exception group).
|
| .. versionadded:: 8.0
|
| match(self, regexp: 'str | Pattern[str]') -> 'Literal[True]'
| Check whether the regular expression `regexp` matches the string
| representation of the exception using :func:`python:re.search`.
|
| If it matches `True` is returned, otherwise an `AssertionError` is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| for_later() -> 'ExceptionInfo[E]'
| Return an unfilled ExceptionInfo.
|
| from_current(exprinfo: 'str | None' = None) -> 'ExceptionInfo[BaseException]'
| Return an ExceptionInfo matching the current traceback.
|
| .. warning::
|
| Experimental API
|
| :param exprinfo:
| A text string helping to determine if we should strip
| ``AssertionError`` from the output. Defaults to the exception
| message/``__str__()``.
|
| from_exc_info(exc_info: 'tuple[type[E], E, TracebackType]', exprinfo: 'str | None' = None) -> 'ExceptionInfo[E]'
| Like :func:`from_exception`, but using old-style exc_info tuple.
|
| from_exception(exception: 'E', exprinfo: 'str | None' = None) -> 'ExceptionInfo[E]'
| Return an ExceptionInfo for an existing exception.
|
| The exception must have a non-``None`` ``__traceback__`` attribute,
| otherwise this function fails with an assertion error. This means that
| the exception must have been raised, or added a traceback with the
| :py:meth:`~BaseException.with_traceback()` method.
|
| :param exprinfo:
| A text string helping to determine if we should strip
| ``AssertionError`` from the output. Defaults to the exception
| message/``__str__()``.
|
| .. versionadded:: 7.4
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| tb
| The exception raw traceback.
|
| type
| The exception class.
|
| typename
| The type name of the exception.
|
| value
| The exception value.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| traceback
| The traceback.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_assert_start_repr': 'ClassVar', '_excinfo': 'tupl...
|
| __dataclass_fields__ = {'_assert_start_repr': Field(name='_assert_star...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __final__ = True
|
| __hash__ = None
|
| __match_args__ = ('_excinfo', '_striptext', '_traceback')
|
| __orig_bases__ = (typing.Generic[+E],)
|
| __parameters__ = (+E,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pytest.ExitCode
Python Library Documentation: class ExitCode in module _pytest.config class ExitCode(enum.IntEnum) | ExitCode(*values) | | Encodes the valid exit codes by pytest. | | Currently users and plugins may supply other exit codes as well. | | .. versionadded:: 5.0 | | Method resolution order: | ExitCode | enum.IntEnum | builtins.int | enum.ReprEnum | enum.Enum | builtins.object | | Methods defined here: | | __format__(self, format_spec, /) from builtins.int | Convert to a string according to format_spec. | | __new__(cls, value) from enum.Enum | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | INTERNAL_ERROR = <ExitCode.INTERNAL_ERROR: 3> | | INTERRUPTED = <ExitCode.INTERRUPTED: 2> | | NO_TESTS_COLLECTED = <ExitCode.NO_TESTS_COLLECTED: 5> | | OK = <ExitCode.OK: 0> | | TESTS_FAILED = <ExitCode.TESTS_FAILED: 1> | | USAGE_ERROR = <ExitCode.USAGE_ERROR: 4> | | ---------------------------------------------------------------------- | Methods inherited from enum.IntEnum: | | __repr__(self) from enum.Enum | Return repr(self). | | __str__ = __repr__(self, /) from builtins.int | Return repr(self). | | ---------------------------------------------------------------------- | Methods inherited from builtins.int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __round__(...) | Rounding an Integral returns itself. | | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | __xor__(self, value, /) | Return self^value. | | as_integer_ratio(self, /) | Return a pair of integers, whose ratio is equal to the original int. | | The ratio is in lowest terms and has a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_count(self, /) | Number of ones in the binary representation of the absolute value of self. | | Also known as the population count. | | >>> bin(13) | '0b1101' | >>> (13).bit_count() | 3 | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | is_integer(self, /) | Returns True. Exists for duck type compatibility with float.is_integer. | | to_bytes(self, /, length=1, byteorder='big', *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. Default | is length 1. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from builtins.int: | | from_bytes(bytes, byteorder='big', *, signed=False) | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number | | ---------------------------------------------------------------------- | Methods inherited from enum.Enum: | | __dir__(self) | Returns public methods and other interesting attributes. | | __init__(self, *args, **kwds) | Initialize self. See help(type(self)) for accurate signature. | | __reduce_ex__(self, proto) | Helper for pickle. | | ---------------------------------------------------------------------- | Data descriptors inherited from enum.Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Static methods inherited from enum.EnumType: | | __contains__(value) | Return True if `value` is in `cls`. | | `value` is in `cls` if: | 1) `value` is a member of `cls`, or | 2) `value` is the value of one of the `cls`'s members. | | __getitem__(name) | Return the member matching `name`. | | __iter__() | Return members in definition order. | | __len__() | Return the number of members (no aliases) | | ---------------------------------------------------------------------- | Readonly properties inherited from enum.EnumType: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping.
pytest.File
Python Library Documentation: class File in module _pytest.nodes
class File(FSCollector, abc.ABC)
| File(*k, **kw) -> 'NoReturn'
|
| Base class for collecting tests from a file.
|
| :ref:`non-python tests`.
|
| Method resolution order:
| File
| FSCollector
| Collector
| Node
| abc.ABC
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'collect'})
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from FSCollector:
|
| __init__(self, fspath: 'LEGACY_PATH | None' = None, path_or_parent: 'Path | Node | None' = None, path: 'Path | None' = None, name: 'str | None' = None, parent: 'Node | None' = None, config: 'Config | None' = None, session: 'Session | None' = None, nodeid: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Class methods inherited from FSCollector:
|
| from_parent(parent, *, fspath: 'LEGACY_PATH | None' = None, path: 'Path | None' = None, **kw) -> 'Self'
| The public constructor.
|
| ----------------------------------------------------------------------
| Methods inherited from Collector:
|
| collect(self) -> 'Iterable[Item | Collector]'
| Collect children (items and collectors) for this collector.
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Collector:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Collector:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| ----------------------------------------------------------------------
| Methods inherited from Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.FixtureDef
Python Library Documentation: class FixtureDef in module _pytest.fixtures
class FixtureDef(typing.Generic)
| FixtureDef(config: 'Config', baseid: 'str | None', argname: 'str', func: '_FixtureFunc[FixtureValue]', scope: 'Scope | _ScopeName | Callable[[str, Config], _ScopeName] | None', params: 'Sequence[object] | None', ids: 'tuple[object | None, ...] | Callable[[Any], object | None] | None' = None, *, _ispytest: 'bool' = False) -> 'None'
|
| A container for a fixture definition.
|
| Note: At this time, only explicitly documented fields and methods are
| considered public stable API.
|
| Method resolution order:
| FixtureDef
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, config: 'Config', baseid: 'str | None', argname: 'str', func: '_FixtureFunc[FixtureValue]', scope: 'Scope | _ScopeName | Callable[[str, Config], _ScopeName] | None', params: 'Sequence[object] | None', ids: 'tuple[object | None, ...] | Callable[[Any], object | None] | None' = None, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| addfinalizer(self, finalizer: 'Callable[[], object]') -> 'None'
|
| cache_key(self, request: 'SubRequest') -> 'object'
|
| execute(self, request: 'SubRequest') -> 'FixtureValue'
| Return the value of this fixture, executing it if not cached.
|
| finish(self, request: 'SubRequest') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| scope
| Scope string, one of "function", "class", "module", "package", "session".
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __final__ = True
|
| __orig_bases__ = (typing.Generic[~FixtureValue],)
|
| __parameters__ = (~FixtureValue,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pytest.FixtureLookupError
Python Library Documentation: class FixtureLookupError in module _pytest.fixtures class FixtureLookupError(builtins.LookupError) | FixtureLookupError(argname: 'str | None', request: 'FixtureRequest', msg: 'str | None' = None) -> 'None' | | Could not return a requested fixture (missing or invalid). | | Method resolution order: | FixtureLookupError | builtins.LookupError | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, argname: 'str | None', request: 'FixtureRequest', msg: 'str | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | formatrepr(self) -> 'FixtureLookupErrorRepr' | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Static methods inherited from builtins.LookupError: | | __new__(*args, **kwargs) class method of builtins.LookupError | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.FixtureRequest
Python Library Documentation: class FixtureRequest in module _pytest.fixtures
class FixtureRequest(abc.ABC)
| FixtureRequest(pyfuncitem: 'Function', fixturename: 'str | None', arg2fixturedefs: 'dict[str, Sequence[FixtureDef[Any]]]', fixture_defs: 'dict[str, FixtureDef[Any]]', *, _ispytest: 'bool' = False) -> 'None'
|
| The type of the ``request`` fixture.
|
| A request object gives access to the requesting test context and has a
| ``param`` attribute in case the fixture is parametrized.
|
| Method resolution order:
| FixtureRequest
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, pyfuncitem: 'Function', fixturename: 'str | None', arg2fixturedefs: 'dict[str, Sequence[FixtureDef[Any]]]', fixture_defs: 'dict[str, FixtureDef[Any]]', *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| addfinalizer(self, finalizer: 'Callable[[], object]') -> 'None'
| Add finalizer/teardown function to be called without arguments after
| the last test within the requesting test context finished execution.
|
| applymarker(self, marker: 'str | MarkDecorator') -> 'None'
| Apply a marker to a single test function invocation.
|
| This method is useful if you don't want to have a keyword/marker
| on all function invocations.
|
| :param marker:
| An object created by a call to ``pytest.mark.NAME(...)``.
|
| getfixturevalue(self, argname: 'str') -> 'Any'
| Dynamically run a named fixture function.
|
| Declaring fixtures via function argument is recommended where possible.
| But if you can only decide whether to use another fixture at test
| setup time, you may use this function to retrieve it inside a fixture
| or test function body.
|
| This method can be used during the test setup phase or the test run
| phase, but during the test teardown phase a fixture's value may not
| be available.
|
| :param argname:
| The fixture name.
| :raises pytest.FixtureLookupError:
| If the given fixture could not be found.
|
| raiseerror(self, msg: 'str | None') -> 'NoReturn'
| Raise a FixtureLookupError exception.
|
| :param msg:
| An optional custom error message.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| cls
| Class (can be None) where the test function was collected.
|
| config
| The pytest config object associated with this request.
|
| fixturenames
| Names of all active fixtures in this request.
|
| function
| Test function object if the request has a per-function scope.
|
| instance
| Instance (can be None) on which test function was collected.
|
| keywords
| Keywords/markers dictionary for the underlying node.
|
| module
| Python module object where the test function was collected.
|
| node
| Underlying collection node (depends on current request scope).
|
| path
| Path where the test function was collected.
|
| scope
| Scope string, one of "function", "class", "module", "package", "session".
|
| session
| Pytest session object.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'_check_scope', '_scope', 'addfinaliz...
|
| __annotations__ = {}
pytest.Function
Python Library Documentation: class Function in module _pytest.python
class Function(PyobjMixin, _pytest.nodes.Item)
| Function(*k, **kw) -> 'NoReturn'
|
| Item responsible for setting up and executing a Python test function.
|
| :param name:
| The full function name, including any decorations like those
| added by parametrization (``my_func[my_param]``).
| :param parent:
| The parent Node.
| :param config:
| The pytest Config object.
| :param callspec:
| If given, this function has been parametrized and the callspec contains
| meta information about the parametrization.
| :param callobj:
| If given, the object which will be called when the Function is invoked,
| otherwise the callobj will be obtained from ``parent`` using ``originalname``.
| :param keywords:
| Keywords bound to the function object for "-k" matching.
| :param session:
| The pytest Session object.
| :param fixtureinfo:
| Fixture information already resolved at this fixture node..
| :param originalname:
| The attribute name to use for accessing the underlying function object.
| Defaults to ``name``. Set this if name is different from the original name,
| for example when it contains decorations like those added by parametrization
| (``my_func[my_param]``).
|
| Method resolution order:
| Function
| PyobjMixin
| _pytest.nodes.Item
| _pytest.nodes.Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', parent, config: 'Config | None' = None, callspec: 'CallSpec2 | None' = None, callobj=<NotSetType.token: 0>, keywords: 'Mapping[str, Any] | None' = None, session: 'Session | None' = None, fixtureinfo: 'FuncFixtureInfo | None' = None, originalname: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection or test failure.
|
| .. seealso:: :ref:`non-python tests`
|
| :param excinfo: Exception information for the failure.
|
| runtest(self) -> 'None'
| Execute the underlying test function.
|
| setup(self) -> 'None'
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_parent(parent, **kw) -> 'Self'
| The public constructor.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| function
| Underlying python 'function' object.
|
| instance
| Python instance object the function is bound to.
|
| Returns None if not a test method, e.g. for a standalone test function,
| a class or a module.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyobjMixin:
|
| getmodpath(self, stopatmodule: 'bool' = True, includemodule: 'bool' = False) -> 'str'
| Return Python path relative to the containing module.
|
| reportinfo(self) -> 'tuple[os.PathLike[str] | str, int | None, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyobjMixin:
|
| cls
| Python class object this node was collected from (can be None).
|
| module
| Python module object this node was collected from (can be None).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyobjMixin:
|
| __weakref__
| list of weak references to the object
|
| obj
| Underlying Python object.
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Item:
|
| add_report_section(self, when: 'str', key: 'str', content: 'str') -> 'None'
| Add a new report section, similar to what's done internally to add
| stdout and stderr captured output::
|
| item.add_report_section("call", "stdout", "report section contents")
|
| :param str when:
| One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``.
| :param str key:
| Name of the section, can be customized at will. Pytest uses ``"stdout"`` and
| ``"stderr"`` internally.
| :param str content:
| The full contents as a string.
|
| location = <functools.cached_property object>
| Returns a tuple of ``(relfspath, lineno, testname)`` for this item
| where ``relfspath`` is file path relative to ``config.rootpath``
| and lineno is a 0-based line number.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _pytest.nodes.Item:
|
| nextitem = None
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _pytest.nodes.Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.HookRecorder
Python Library Documentation: class HookRecorder in module _pytest.pytester
class HookRecorder(builtins.object)
| HookRecorder(pluginmanager: 'PytestPluginManager', *, _ispytest: 'bool' = False) -> 'None'
|
| Record all hooks called in a plugin manager.
|
| Hook recorders are created by :class:`Pytester`.
|
| This wraps all the hook calls in the plugin manager, recording each call
| before propagating the normal calls.
|
| Methods defined here:
|
| __init__(self, pluginmanager: 'PytestPluginManager', *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| assert_contains(self, entries: 'Sequence[tuple[str, str]]') -> 'None'
|
| assertoutcome(self, passed: 'int' = 0, skipped: 'int' = 0, failed: 'int' = 0) -> 'None'
|
| clear(self) -> 'None'
|
| countoutcomes(self) -> 'list[int]'
|
| finish_recording(self) -> 'None'
|
| getcall(self, name: 'str') -> 'RecordedHookCall'
|
| getcalls(self, names: 'str | Iterable[str]') -> 'list[RecordedHookCall]'
| Get all recorded calls to hooks with the given names (or name).
|
| getfailedcollections(self) -> 'Sequence[CollectReport]'
|
| getfailures(self, names: 'str | Iterable[str]' = ('pytest_collectreport', 'pytest_runtest_logreport')) -> 'Sequence[CollectReport | TestReport]'
|
| getreports(self, names: 'str | Iterable[str]' = ('pytest_collectreport', 'pytest_runtest_logreport')) -> 'Sequence[CollectReport | TestReport]'
|
| listoutcomes(self) -> 'tuple[Sequence[TestReport], Sequence[CollectReport | TestReport], Sequence[CollectReport | TestReport]]'
|
| matchreport(self, inamepart: 'str' = '', names: 'str | Iterable[str]' = ('pytest_runtest_logreport', 'pytest_collectreport'), when: 'str | None' = None) -> 'CollectReport | TestReport'
| Return a testreport whose dotted import path matches.
|
| popcall(self, name: 'str') -> 'RecordedHookCall'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __final__ = True
pytest.Item
Python Library Documentation: class Item in module _pytest.nodes
class Item(Node, abc.ABC)
| Item(*k, **kw) -> 'NoReturn'
|
| Base class of all test invocation items.
|
| Note that for a single function there might be multiple test invocation items.
|
| Method resolution order:
| Item
| Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, name, parent=None, config: 'Config | None' = None, session: 'Session | None' = None, nodeid: 'str | None' = None, **kw) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| add_report_section(self, when: 'str', key: 'str', content: 'str') -> 'None'
| Add a new report section, similar to what's done internally to add
| stdout and stderr captured output::
|
| item.add_report_section("call", "stdout", "report section contents")
|
| :param str when:
| One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``.
| :param str key:
| Name of the section, can be customized at will. Pytest uses ``"stdout"`` and
| ``"stderr"`` internally.
| :param str content:
| The full contents as a string.
|
| location = <functools.cached_property object>
| Returns a tuple of ``(relfspath, lineno, testname)`` for this item
| where ``relfspath`` is file path relative to ``config.rootpath``
| and lineno is a 0-based line number.
|
| reportinfo(self) -> 'tuple[os.PathLike[str] | str, int | None, str]'
| Get location information for this item for test reports.
|
| Returns a tuple with three elements:
|
| - The path of the test (default ``self.path``)
| - The 0-based line number of the test (default ``None``)
| - A name of the test to be shown (default ``""``)
|
| .. seealso:: :ref:`non-python tests`
|
| runtest(self) -> 'None'
| Run the test case for this item.
|
| Must be implemented by subclasses.
|
| .. seealso:: :ref:`non-python tests`
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'runtest'})
|
| __annotations__ = {}
|
| nextitem = None
|
| ----------------------------------------------------------------------
| Methods inherited from Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]', style: 'TracebackStyle | None' = None) -> 'str | TerminalRepr'
| Return a representation of a collection or test failure.
|
| .. seealso:: :ref:`non-python tests`
|
| :param excinfo: Exception information for the failure.
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Node:
|
| from_parent(parent: 'Node', **kw) -> 'Self'
| Public constructor for Nodes.
|
| This indirection got introduced in order to enable removing
| the fragile logic from the node constructors.
|
| Subclasses can use ``super().from_parent(...)`` when overriding the
| construction.
|
| :param parent: The parent node of this Node.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.LineMatcher
Python Library Documentation: class LineMatcher in module _pytest.pytester class LineMatcher(builtins.object) | LineMatcher(lines: 'list[str]') -> 'None' | | Flexible matching of text. | | This is a convenience class to test large texts like the output of | commands. | | The constructor takes a list of lines without their trailing newlines, i.e. | ``text.splitlines()``. | | Methods defined here: | | __init__(self, lines: 'list[str]') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return the entire original text. | | .. versionadded:: 6.2 | You can use :meth:`str` in older versions. | | fnmatch_lines(self, lines2: 'Sequence[str]', *, consecutive: 'bool' = False) -> 'None' | Check lines exist in the output (using :func:`python:fnmatch.fnmatch`). | | The argument is a list of lines which have to match and can use glob | wildcards. If they do not match a pytest.fail() is called. The | matches and non-matches are also shown as part of the error message. | | :param lines2: String patterns to match. | :param consecutive: Match lines consecutively? | | fnmatch_lines_random(self, lines2: 'Sequence[str]') -> 'None' | Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`). | | get_lines_after(self, fnline: 'str') -> 'Sequence[str]' | Return all lines following the given line in the text. | | The given line can contain glob wildcards. | | no_fnmatch_line(self, pat: 'str') -> 'None' | Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``. | | :param str pat: The pattern to match lines. | | no_re_match_line(self, pat: 'str') -> 'None' | Ensure captured lines do not match the given pattern, using ``re.match``. | | :param str pat: The regular expression to match lines. | | re_match_lines(self, lines2: 'Sequence[str]', *, consecutive: 'bool' = False) -> 'None' | Check lines exist in the output (using :func:`python:re.match`). | | The argument is a list of lines which have to match using ``re.match``. | If they do not match a pytest.fail() is called. | | The matches and non-matches are also shown as part of the error message. | | :param lines2: string patterns to match. | :param consecutive: match lines consecutively? | | re_match_lines_random(self, lines2: 'Sequence[str]') -> 'None' | Check lines exist in the output in any order (using :func:`python:re.match`). | | str(self) -> 'str' | Return the entire original text. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
pytest.LogCaptureFixture
Python Library Documentation: class LogCaptureFixture in module _pytest.logging class LogCaptureFixture(builtins.object) | LogCaptureFixture(item: 'nodes.Node', *, _ispytest: 'bool' = False) -> 'None' | | Provides access and control of log capturing. | | Methods defined here: | | __init__(self, item: 'nodes.Node', *, _ispytest: 'bool' = False) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | at_level(self, level: 'int | str', logger: 'str | None' = None) -> 'Generator[None]' | Context manager that sets the level for capturing of logs. After | the end of the 'with' statement the level is restored to its original | value. | | Will enable the requested logging level if it was disabled via :func:`logging.disable`. | | :param level: The level. | :param logger: The logger to update. If not given, the root logger. | | clear(self) -> 'None' | Reset the list of log records and the captured log text. | | filtering(self, filter_: 'logging.Filter') -> 'Generator[None]' | Context manager that temporarily adds the given filter to the caplog's | :meth:`handler` for the 'with' statement block, and removes that filter at the | end of the block. | | :param filter_: A custom :class:`logging.Filter` object. | | .. versionadded:: 7.5 | | get_records(self, when: "Literal['setup', 'call', 'teardown']") -> 'list[logging.LogRecord]' | Get the logging records for one of the possible test phases. | | :param when: | Which test phase to obtain the records from. | Valid values are: "setup", "call" and "teardown". | | :returns: The list of captured records at the given stage. | | .. versionadded:: 3.4 | | set_level(self, level: 'int | str', logger: 'str | None' = None) -> 'None' | Set the threshold level of a logger for the duration of a test. | | Logging messages which are less severe than this level will not be captured. | | .. versionchanged:: 3.4 | The levels of the loggers changed by this function will be | restored to their initial values at the end of the test. | | Will enable the requested logging level if it was disabled via :func:`logging.disable`. | | :param level: The level. | :param logger: The logger to update. If not given, the root logger. | | ---------------------------------------------------------------------- | Readonly properties defined here: | | handler | Get the logging handler used by the fixture. | | messages | A list of format-interpolated log messages. | | Unlike 'records', which contains the format string and parameters for | interpolation, log messages in this list are all interpolated. | | Unlike 'text', which contains the output from the handler, log | messages in this list are unadorned with levels, timestamps, etc, | making exact comparisons more reliable. | | Note that traceback or stack info (from :func:`logging.exception` or | the `exc_info` or `stack_info` arguments to the logging functions) is | not included, as this is added by the formatter in the handler. | | .. versionadded:: 3.7 | | record_tuples | A list of a stripped down version of log records intended | for use in assertion comparison. | | The format of the tuple is: | | (logger_name, log_level, message) | | records | The list of log records. | | text | The formatted log text. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __final__ = True
pytest.Mark
Python Library Documentation: class Mark in module _pytest.mark.structures
class Mark(builtins.object)
| Mark(name: 'str', args: 'tuple[Any, ...]', kwargs: 'Mapping[str, Any]', param_ids_from: 'Mark | None' = None, param_ids_generated: 'Sequence[str] | None' = None, *, _ispytest: 'bool' = False) -> 'None'
|
| A pytest mark.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, name: 'str', args: 'tuple[Any, ...]', kwargs: 'Mapping[str, Any]', param_ids_from: 'Mark | None' = None, param_ids_generated: 'Sequence[str] | None' = None, *, _ispytest: 'bool' = False) -> 'None'
| :meta private:
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| combined_with(self, other: 'Mark') -> 'Mark'
| Return a new Mark which is a combination of this
| Mark and another Mark.
|
| Combines by appending args and merging kwargs.
|
| :param Mark other: The mark to combine with.
| :rtype: Mark
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_param_ids_from': 'Mark | None', '_param_ids_gener...
|
| __dataclass_fields__ = {'_param_ids_from': Field(name='_param_ids_from...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __final__ = True
|
| __match_args__ = ('name', 'args', 'kwargs', '_param_ids_from', '_param...
pytest.MarkDecorator
Python Library Documentation: class MarkDecorator in module _pytest.mark.structures
class MarkDecorator(builtins.object)
| MarkDecorator(mark: 'Mark', *, _ispytest: 'bool' = False) -> 'None'
|
| A decorator for applying a mark on test functions and classes.
|
| ``MarkDecorators`` are created with ``pytest.mark``::
|
| mark1 = pytest.mark.NAME # Simple MarkDecorator
| mark2 = pytest.mark.NAME(name1=value) # Parametrized MarkDecorator
|
| and can then be applied as decorators to test functions::
|
| @mark2
| def test_function():
| pass
|
| When a ``MarkDecorator`` is called, it does the following:
|
| 1. If called with a single class as its only positional argument and no
| additional keyword arguments, it attaches the mark to the class so it
| gets applied automatically to all test cases found in that class.
|
| 2. If called with a single function as its only positional argument and
| no additional keyword arguments, it attaches the mark to the function,
| containing all the arguments already stored internally in the
| ``MarkDecorator``.
|
| 3. When called in any other case, it returns a new ``MarkDecorator``
| instance with the original ``MarkDecorator``'s content updated with
| the arguments passed to this call.
|
| Note: The rules above prevent a ``MarkDecorator`` from storing only a
| single function or class reference as its positional argument with no
| additional keyword or positional arguments. You can work around this by
| using `with_args()`.
|
| Methods defined here:
|
| __call__(self, *args: 'object', **kwargs: 'object')
| Call the MarkDecorator.
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, mark: 'Mark', *, _ispytest: 'bool' = False) -> 'None'
| :meta private:
|
| __repr__(self)
| Return repr(self).
|
| with_args(self, *args: 'object', **kwargs: 'object') -> 'MarkDecorator'
| Return a MarkDecorator with extra arguments added.
|
| Unlike calling the MarkDecorator, with_args() can be used even
| if the sole argument is a callable/class.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| args
| Alias for mark.args.
|
| kwargs
| Alias for mark.kwargs.
|
| markname
| :meta private:
|
| name
| Alias for mark.name.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'mark': 'Mark'}
|
| __dataclass_fields__ = {'mark': Field(name='mark',type='Mark',default=...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('mark',)
pytest.MarkGenerator
Python Library Documentation: class MarkGenerator in module _pytest.mark.structures
class MarkGenerator(builtins.object)
| MarkGenerator(*, _ispytest: 'bool' = False) -> 'None'
|
| Factory for :class:`MarkDecorator` objects - exposed as
| a ``pytest.mark`` singleton instance.
|
| Example::
|
| import pytest
|
|
| @pytest.mark.slowtest
| def test_function():
| pass
|
| applies a 'slowtest' :class:`Mark` on ``test_function``.
|
| Methods defined here:
|
| __getattr__(self, name: 'str') -> 'MarkDecorator'
| Generate a new :class:`MarkDecorator` with the given name.
|
| __init__(self, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __final__ = True
pytest.Metafunc
Python Library Documentation: class Metafunc in module _pytest.python
class Metafunc(builtins.object)
| Metafunc(definition: 'FunctionDefinition', fixtureinfo: 'fixtures.FuncFixtureInfo', config: 'Config', cls=None, module=None, *, _ispytest: 'bool' = False) -> 'None'
|
| Objects passed to the :hook:`pytest_generate_tests` hook.
|
| They help to inspect a test function and to generate tests according to
| test configuration or values specified in the class or module where a
| test function is defined.
|
| Methods defined here:
|
| __init__(self, definition: 'FunctionDefinition', fixtureinfo: 'fixtures.FuncFixtureInfo', config: 'Config', cls=None, module=None, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| parametrize(self, argnames: 'str | Sequence[str]', argvalues: 'Iterable[ParameterSet | Sequence[object] | object]', indirect: 'bool | Sequence[str]' = False, ids: 'Iterable[object | None] | Callable[[Any], object | None] | None' = None, scope: '_ScopeName | None' = None, *, _param_mark: 'Mark | None' = None) -> 'None'
| Add new invocations to the underlying test function using the list
| of argvalues for the given argnames. Parametrization is performed
| during the collection phase. If you need to setup expensive resources
| see about setting indirect to do it rather than at test setup time.
|
| Can be called multiple times per test function (but only on different
| argument names), in which case each call parametrizes all previous
| parametrizations, e.g.
|
| ::
|
| unparametrized: t
| parametrize ["x", "y"]: t[x], t[y]
| parametrize [1, 2]: t[x-1], t[x-2], t[y-1], t[y-2]
|
| :param argnames:
| A comma-separated string denoting one or more argument names, or
| a list/tuple of argument strings.
|
| :param argvalues:
| The list of argvalues determines how often a test is invoked with
| different argument values.
|
| If only one argname was specified argvalues is a list of values.
| If N argnames were specified, argvalues must be a list of
| N-tuples, where each tuple-element specifies a value for its
| respective argname.
| :type argvalues: Iterable[_pytest.mark.structures.ParameterSet | Sequence[object] | object]
| :param indirect:
| A list of arguments' names (subset of argnames) or a boolean.
| If True the list contains all names from the argnames. Each
| argvalue corresponding to an argname in this list will
| be passed as request.param to its respective argname fixture
| function so that it can perform more expensive setups during the
| setup phase of a test rather than at collection time.
|
| :param ids:
| Sequence of (or generator for) ids for ``argvalues``,
| or a callable to return part of the id for each argvalue.
|
| With sequences (and generators like ``itertools.count()``) the
| returned ids should be of type ``string``, ``int``, ``float``,
| ``bool``, or ``None``.
| They are mapped to the corresponding index in ``argvalues``.
| ``None`` means to use the auto-generated id.
|
| If it is a callable it will be called for each entry in
| ``argvalues``, and the return value is used as part of the
| auto-generated id for the whole set (where parts are joined with
| dashes ("-")).
| This is useful to provide more specific ids for certain items, e.g.
| dates. Returning ``None`` will use an auto-generated id.
|
| If no ids are provided they will be generated automatically from
| the argvalues.
|
| :param scope:
| If specified it denotes the scope of the parameters.
| The scope is used for grouping tests by parameter instances.
| It will also override any fixture-function defined scope, allowing
| to set a dynamic scope using test context or configuration.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __final__ = True
pytest.Module
Python Library Documentation: class Module in module _pytest.python
class Module(_pytest.nodes.File, PyCollector)
| Module(*k, **kw) -> 'NoReturn'
|
| Collector for test classes and functions in a Python module.
|
| Method resolution order:
| Module
| _pytest.nodes.File
| _pytest.nodes.FSCollector
| PyCollector
| PyobjMixin
| _pytest.nodes.Collector
| _pytest.nodes.Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| collect(self) -> 'Iterable[nodes.Item | nodes.Collector]'
| Collect children (items and collectors) for this collector.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.FSCollector:
|
| __init__(self, fspath: 'LEGACY_PATH | None' = None, path_or_parent: 'Path | Node | None' = None, path: 'Path | None' = None, name: 'str | None' = None, parent: 'Node | None' = None, config: 'Config | None' = None, session: 'Session | None' = None, nodeid: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Class methods inherited from _pytest.nodes.FSCollector:
|
| from_parent(parent, *, fspath: 'LEGACY_PATH | None' = None, path: 'Path | None' = None, **kw) -> 'Self'
| The public constructor.
|
| ----------------------------------------------------------------------
| Methods inherited from PyCollector:
|
| classnamefilter(self, name: 'str') -> 'bool'
|
| funcnamefilter(self, name: 'str') -> 'bool'
|
| isnosetest(self, obj: 'object') -> 'bool'
| Look for the __test__ attribute, which is applied by the
| @nose.tools.istest decorator.
|
| istestclass(self, obj: 'object', name: 'str') -> 'bool'
|
| istestfunction(self, obj: 'object', name: 'str') -> 'bool'
|
| ----------------------------------------------------------------------
| Methods inherited from PyobjMixin:
|
| getmodpath(self, stopatmodule: 'bool' = True, includemodule: 'bool' = False) -> 'str'
| Return Python path relative to the containing module.
|
| reportinfo(self) -> 'tuple[os.PathLike[str] | str, int | None, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyobjMixin:
|
| cls
| Python class object this node was collected from (can be None).
|
| instance
| Python instance object the function is bound to.
|
| Returns None if not a test method, e.g. for a standalone test function,
| a class or a module.
|
| module
| Python module object this node was collected from (can be None).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyobjMixin:
|
| __weakref__
| list of weak references to the object
|
| obj
| Underlying Python object.
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Collector:
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _pytest.nodes.Collector:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _pytest.nodes.Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.MonkeyPatch
Python Library Documentation: class MonkeyPatch in module _pytest.monkeypatch
class MonkeyPatch(builtins.object)
| MonkeyPatch() -> 'None'
|
| Helper to conveniently monkeypatch attributes/items/environment
| variables/syspath.
|
| Returned by the :fixture:`monkeypatch` fixture.
|
| .. versionchanged:: 6.2
| Can now also be used directly as `pytest.MonkeyPatch()`, for when
| the fixture is not available. In this case, use
| :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
| :meth:`undo` explicitly.
|
| Methods defined here:
|
| __init__(self) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| chdir(self, path: 'str | os.PathLike[str]') -> 'None'
| Change the current working directory to the specified path.
|
| :param path:
| The path to change into.
|
| delattr(self, target: 'object | str', name: 'str | Notset' = <notset>, raising: 'bool' = True) -> 'None'
| Delete attribute ``name`` from ``target``.
|
| If no ``name`` is specified and ``target`` is a string
| it will be interpreted as a dotted import path with the
| last part being the attribute name.
|
| Raises AttributeError it the attribute does not exist, unless
| ``raising`` is set to False.
|
| delenv(self, name: 'str', raising: 'bool' = True) -> 'None'
| Delete ``name`` from the environment.
|
| Raises ``KeyError`` if it does not exist, unless ``raising`` is set to
| False.
|
| delitem(self, dic: 'Mapping[K, V]', name: 'K', raising: 'bool' = True) -> 'None'
| Delete ``name`` from dict.
|
| Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to
| False.
|
| setattr(self, target: 'str | object', name: 'object | str', value: 'object' = <notset>, raising: 'bool' = True) -> 'None'
| Set attribute value on target, memorizing the old value.
|
| For example:
|
| .. code-block:: python
|
| import os
|
| monkeypatch.setattr(os, "getcwd", lambda: "/")
|
| The code above replaces the :func:`os.getcwd` function by a ``lambda`` which
| always returns ``"/"``.
|
| For convenience, you can specify a string as ``target`` which
| will be interpreted as a dotted import path, with the last part
| being the attribute name:
|
| .. code-block:: python
|
| monkeypatch.setattr("os.getcwd", lambda: "/")
|
| Raises :class:`AttributeError` if the attribute does not exist, unless
| ``raising`` is set to False.
|
| **Where to patch**
|
| ``monkeypatch.setattr`` works by (temporarily) changing the object that a name points to with another one.
| There can be many names pointing to any individual object, so for patching to work you must ensure
| that you patch the name used by the system under test.
|
| See the section :ref:`Where to patch <python:where-to-patch>` in the :mod:`unittest.mock`
| docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but
| applies to ``monkeypatch.setattr`` as well.
|
| setenv(self, name: 'str', value: 'str', prepend: 'str | None' = None) -> 'None'
| Set environment variable ``name`` to ``value``.
|
| If ``prepend`` is a character, read the current environment variable
| value and prepend the ``value`` adjoined with the ``prepend``
| character.
|
| setitem(self, dic: 'Mapping[K, V]', name: 'K', value: 'V') -> 'None'
| Set dictionary entry ``name`` to value.
|
| syspath_prepend(self, path) -> 'None'
| Prepend ``path`` to ``sys.path`` list of import locations.
|
| undo(self) -> 'None'
| Undo previous changes.
|
| This call consumes the undo stack. Calling it a second time has no
| effect unless you do more monkeypatching after the undo call.
|
| There is generally no need to call `undo()`, since it is
| called automatically during tear-down.
|
| .. note::
| The same `monkeypatch` fixture is used across a
| single test function invocation. If `monkeypatch` is used both by
| the test function itself and one of the test fixtures,
| calling `undo()` will undo all of the changes made in
| both functions.
|
| Prefer to use :meth:`context() <pytest.MonkeyPatch.context>` instead.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| context() -> 'Generator[MonkeyPatch]'
| Context manager that returns a new :class:`MonkeyPatch` object
| which undoes any patching done inside the ``with`` block upon exit.
|
| Example:
|
| .. code-block:: python
|
| import functools
|
|
| def test_partial(monkeypatch):
| with monkeypatch.context() as m:
| m.setattr(functools, "partial", 3)
|
| Useful in situations where it is desired to undo some patches before the test ends,
| such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
| of this see :issue:`3290`).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __final__ = True
pytest.OptionGroup
Python Library Documentation: class OptionGroup in module _pytest.config.argparsing
class OptionGroup(builtins.object)
| OptionGroup(name: 'str', description: 'str' = '', parser: 'Parser | None' = None, *, _ispytest: 'bool' = False) -> 'None'
|
| A group of options shown in its own section.
|
| Methods defined here:
|
| __init__(self, name: 'str', description: 'str' = '', parser: 'Parser | None' = None, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| addoption(self, *opts: 'str', **attrs: 'Any') -> 'None'
| Add an option to this group.
|
| If a shortened version of a long option is specified, it will
| be suppressed in the help. ``addoption('--twowords', '--two-words')``
| results in help showing ``--two-words`` only, but ``--twowords`` gets
| accepted **and** the automatic destination is in ``args.twowords``.
|
| :param opts:
| Option names, can be short or long options.
| :param attrs:
| Same attributes as the argparse library's :meth:`add_argument()
| <argparse.ArgumentParser.add_argument>` function accepts.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
pytest.Package
Python Library Documentation: class Package in module _pytest.python
class Package(_pytest.nodes.Directory)
| Package(*k, **kw) -> 'NoReturn'
|
| Collector for files and directories in a Python packages -- directories
| with an `__init__.py` file.
|
| .. note::
|
| Directories without an `__init__.py` file are instead collected by
| :class:`~pytest.Dir` by default. Both are :class:`~pytest.Directory`
| collectors.
|
| .. versionchanged:: 8.0
|
| Now inherits from :class:`~pytest.Directory`.
|
| Method resolution order:
| Package
| _pytest.nodes.Directory
| _pytest.nodes.FSCollector
| _pytest.nodes.Collector
| _pytest.nodes.Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, fspath: 'LEGACY_PATH | None', parent: 'nodes.Collector', config=None, session=None, nodeid=None, path: 'Path | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| collect(self) -> 'Iterable[nodes.Item | nodes.Collector]'
| Collect children (items and collectors) for this collector.
|
| setup(self) -> 'None'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Class methods inherited from _pytest.nodes.FSCollector:
|
| from_parent(parent, *, fspath: 'LEGACY_PATH | None' = None, path: 'Path | None' = None, **kw) -> 'Self'
| The public constructor.
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Collector:
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Collector:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _pytest.nodes.Collector:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _pytest.nodes.Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.Parser
Python Library Documentation: class Parser in module _pytest.config.argparsing
class Parser(builtins.object)
| Parser(usage: 'str | None' = None, processopt: 'Callable[[Argument], None] | None' = None, *, _ispytest: 'bool' = False) -> 'None'
|
| Parser for command line arguments and ini-file values.
|
| :ivar extra_info: Dict of generic param -> value to display in case
| there's an error processing the command line arguments.
|
| Methods defined here:
|
| __init__(self, usage: 'str | None' = None, processopt: 'Callable[[Argument], None] | None' = None, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| addini(self, name: 'str', help: 'str', type: "Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool'] | None" = None, default: 'Any' = <notset>) -> 'None'
| Register an ini-file option.
|
| :param name:
| Name of the ini-variable.
| :param type:
| Type of the variable. Can be:
|
| * ``string``: a string
| * ``bool``: a boolean
| * ``args``: a list of strings, separated as in a shell
| * ``linelist``: a list of strings, separated by line breaks
| * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell
| * ``pathlist``: a list of ``py.path``, separated as in a shell
|
| For ``paths`` and ``pathlist`` types, they are considered relative to the ini-file.
| In case the execution is happening without an ini-file defined,
| they will be considered relative to the current working directory (for example with ``--override-ini``).
|
| .. versionadded:: 7.0
| The ``paths`` variable type.
|
| .. versionadded:: 8.1
| Use the current working directory to resolve ``paths`` and ``pathlist`` in the absence of an ini-file.
|
| Defaults to ``string`` if ``None`` or not passed.
| :param default:
| Default value if no ini-file option exists but is queried.
|
| The value of ini-variables can be retrieved via a call to
| :py:func:`config.getini(name) <pytest.Config.getini>`.
|
| addoption(self, *opts: 'str', **attrs: 'Any') -> 'None'
| Register a command line option.
|
| :param opts:
| Option names, can be short or long options.
| :param attrs:
| Same attributes as the argparse library's :meth:`add_argument()
| <argparse.ArgumentParser.add_argument>` function accepts.
|
| After command line parsing, options are available on the pytest config
| object via ``config.option.NAME`` where ``NAME`` is usually set
| by passing a ``dest`` attribute, for example
| ``addoption("--long", dest="NAME", ...)``.
|
| getgroup(self, name: 'str', description: 'str' = '', after: 'str | None' = None) -> 'OptionGroup'
| Get (or create) a named option Group.
|
| :param name: Name of the option group.
| :param description: Long description for --help output.
| :param after: Name of another group, used for ordering --help output.
| :returns: The option group.
|
| The returned group object has an ``addoption`` method with the same
| signature as :func:`parser.addoption <pytest.Parser.addoption>` but
| will be shown in the respective group in the output of
| ``pytest --help``.
|
| parse(self, args: 'Sequence[str | os.PathLike[str]]', namespace: 'argparse.Namespace | None' = None) -> 'argparse.Namespace'
|
| parse_known_and_unknown_args(self, args: 'Sequence[str | os.PathLike[str]]', namespace: 'argparse.Namespace | None' = None) -> 'tuple[argparse.Namespace, list[str]]'
| Parse the known arguments at this point, and also return the
| remaining unknown arguments.
|
| :returns:
| A tuple containing an argparse namespace object for the known
| arguments, and a list of the unknown arguments.
|
| parse_known_args(self, args: 'Sequence[str | os.PathLike[str]]', namespace: 'argparse.Namespace | None' = None) -> 'argparse.Namespace'
| Parse the known arguments at this point.
|
| :returns: An argparse namespace object.
|
| parse_setoption(self, args: 'Sequence[str | os.PathLike[str]]', option: 'argparse.Namespace', namespace: 'argparse.Namespace | None' = None) -> 'list[str]'
|
| processoption(self, option: 'Argument') -> 'None'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'prog': 'str | None'}
|
| __final__ = True
|
| prog = None
pytest.PytestAssertRewriteWarning
Python Library Documentation: class PytestAssertRewriteWarning in module pytest class PytestAssertRewriteWarning(PytestWarning) | Warning emitted by the pytest assert rewrite module. | | Method resolution order: | PytestAssertRewriteWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestCacheWarning
Python Library Documentation: class PytestCacheWarning in module pytest class PytestCacheWarning(PytestWarning) | Warning emitted by the cache plugin in various situations. | | Method resolution order: | PytestCacheWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestCollectionWarning
Python Library Documentation: class PytestCollectionWarning in module pytest class PytestCollectionWarning(PytestWarning) | Warning emitted when pytest is not able to collect a file or symbol in a module. | | Method resolution order: | PytestCollectionWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestConfigWarning
Python Library Documentation: class PytestConfigWarning in module pytest class PytestConfigWarning(PytestWarning) | Warning emitted for configuration issues. | | Method resolution order: | PytestConfigWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestDeprecationWarning
Python Library Documentation: class PytestDeprecationWarning in module pytest class PytestDeprecationWarning(PytestWarning, builtins.DeprecationWarning) | Warning class for features that will be removed in a future version. | | Method resolution order: | PytestDeprecationWarning | PytestWarning | builtins.UserWarning | builtins.DeprecationWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestExperimentalApiWarning
Python Library Documentation: class PytestExperimentalApiWarning in module pytest class PytestExperimentalApiWarning(PytestWarning, builtins.FutureWarning) | Warning category used to denote experiments in pytest. | | Use sparingly as the API might change or even be removed completely in a | future version. | | Method resolution order: | PytestExperimentalApiWarning | PytestWarning | builtins.UserWarning | builtins.FutureWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Class methods defined here: | | simple(apiname: 'str') -> 'PytestExperimentalApiWarning' from _pytest.warning_types.PytestExperimentalApiWarning | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestPluginManager
Python Library Documentation: class PytestPluginManager in module _pytest.config class PytestPluginManager(pluggy._manager.PluginManager) | PytestPluginManager() -> 'None' | | A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with | additional pytest-specific functionality: | | * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and | ``pytest_plugins`` global variables found in plugins being loaded. | * ``conftest.py`` loading during start-up. | | Method resolution order: | PytestPluginManager | pluggy._manager.PluginManager | builtins.object | | Methods defined here: | | __init__(self) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | consider_conftest(self, conftestmodule: 'types.ModuleType', registration_name: 'str') -> 'None' | :meta private: | | consider_env(self) -> 'None' | :meta private: | | consider_module(self, mod: 'types.ModuleType') -> 'None' | :meta private: | | consider_pluginarg(self, arg: 'str') -> 'None' | :meta private: | | consider_preparse(self, args: 'Sequence[str]', *, exclude_only: 'bool' = False) -> 'None' | :meta private: | | getplugin(self, name: 'str') | | hasplugin(self, name: 'str') -> 'bool' | Return whether a plugin with the given name is registered. | | import_plugin(self, modname: 'str', consider_entry_points: 'bool' = False) -> 'None' | Import a plugin with ``modname``. | | If ``consider_entry_points`` is True, entry point names are also | considered to find a plugin. | | parse_hookimpl_opts(self, plugin: '_PluggyPlugin', name: 'str') -> 'HookimplOpts | None' | :meta private: | | parse_hookspec_opts(self, module_or_class, name: 'str') -> 'HookspecOpts | None' | :meta private: | | pytest_configure(self, config: 'Config') -> 'None' | :meta private: | | register(self, plugin: '_PluggyPlugin', name: 'str | None' = None) -> 'str | None' | Register a plugin and return its name. | | :param name: | The name under which to register the plugin. If not specified, a | name is generated using :func:`get_canonical_name`. | | :returns: | The plugin name. If the name is blocked from registering, returns | ``None``. | | If the plugin is already registered, raises a :exc:`ValueError`. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Methods inherited from pluggy._manager.PluginManager: | | add_hookcall_monitoring(self, before: '_BeforeTrace', after: '_AfterTrace') -> 'Callable[[], None]' | Add before/after tracing functions for all hooks. | | Returns an undo function which, when called, removes the added tracers. | | ``before(hook_name, hook_impls, kwargs)`` will be called ahead | of all hook calls and receive a hookcaller instance, a list | of HookImpl instances and the keyword arguments for the hook call. | | ``after(outcome, hook_name, hook_impls, kwargs)`` receives the | same arguments as ``before`` but also a :class:`~pluggy.Result` object | which represents the result of the overall hook call. | | add_hookspecs(self, module_or_class: '_Namespace') -> 'None' | Add new hook specifications defined in the given ``module_or_class``. | | Functions are recognized as hook specifications if they have been | decorated with a matching :class:`HookspecMarker`. | | check_pending(self) -> 'None' | Verify that all hooks which have not been verified against a | hook specification are optional, otherwise raise | :exc:`PluginValidationError`. | | enable_tracing(self) -> 'Callable[[], None]' | Enable tracing of hook calls. | | Returns an undo function which, when called, removes the added tracing. | | get_canonical_name(self, plugin: '_Plugin') -> 'str' | Return a canonical name for a plugin object. | | Note that a plugin may be registered under a different name | specified by the caller of :meth:`register(plugin, name) <register>`. | To obtain the name of a registered plugin use :meth:`get_name(plugin) | <get_name>` instead. | | get_hookcallers(self, plugin: '_Plugin') -> 'list[HookCaller] | None' | Get all hook callers for the specified plugin. | | :returns: | The hook callers, or ``None`` if ``plugin`` is not registered in | this plugin manager. | | get_name(self, plugin: '_Plugin') -> 'str | None' | Return the name the plugin is registered under, or ``None`` if | is isn't. | | get_plugin(self, name: 'str') -> 'Any | None' | Return the plugin registered under the given name, if any. | | get_plugins(self) -> 'set[Any]' | Return a set of all registered plugin objects. | | has_plugin(self, name: 'str') -> 'bool' | Return whether a plugin with the given name is registered. | | is_blocked(self, name: 'str') -> 'bool' | Return whether the given plugin name is blocked. | | is_registered(self, plugin: '_Plugin') -> 'bool' | Return whether the plugin is already registered. | | list_name_plugin(self) -> 'list[tuple[str, _Plugin]]' | Return a list of (name, plugin) pairs for all registered plugins. | | list_plugin_distinfo(self) -> 'list[tuple[_Plugin, DistFacade]]' | Return a list of (plugin, distinfo) pairs for all | setuptools-registered plugins. | | load_setuptools_entrypoints(self, group: 'str', name: 'str | None' = None) -> 'int' | Load modules from querying the specified setuptools ``group``. | | :param group: | Entry point group to load plugins. | :param name: | If given, loads only plugins with the given ``name``. | | :return: | The number of plugins loaded by this call. | | set_blocked(self, name: 'str') -> 'None' | Block registrations of the given name, unregister if already registered. | | subset_hook_caller(self, name: 'str', remove_plugins: 'Iterable[_Plugin]') -> 'HookCaller' | Return a proxy :class:`~pluggy.HookCaller` instance for the named | method which manages calls to all registered plugins except the ones | from remove_plugins. | | unblock(self, name: 'str') -> 'bool' | Unblocks a name. | | Returns whether the name was actually blocked. | | unregister(self, plugin: '_Plugin | None' = None, name: 'str | None' = None) -> 'Any | None' | Unregister a plugin and all of its hook implementations. | | The plugin can be specified either by the plugin object or the plugin | name. If both are specified, they must agree. | | Returns the unregistered plugin, or ``None`` if not found. | | ---------------------------------------------------------------------- | Data descriptors inherited from pluggy._manager.PluginManager: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
pytest.PytestRemovedIn9Warning
Python Library Documentation: class PytestRemovedIn9Warning in module pytest class PytestRemovedIn9Warning(PytestDeprecationWarning) | Warning class for features that will be removed in pytest 9. | | Method resolution order: | PytestRemovedIn9Warning | PytestDeprecationWarning | PytestWarning | builtins.UserWarning | builtins.DeprecationWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestReturnNotNoneWarning
Python Library Documentation: class PytestReturnNotNoneWarning in module pytest class PytestReturnNotNoneWarning(PytestWarning) | Warning emitted when a test function is returning value other than None. | | Method resolution order: | PytestReturnNotNoneWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestUnhandledCoroutineWarning
Python Library Documentation: class PytestUnhandledCoroutineWarning in module pytest class PytestUnhandledCoroutineWarning(PytestReturnNotNoneWarning) | Warning emitted for an unhandled coroutine. | | A coroutine was encountered when collecting test functions, but was not | handled by any async-aware plugin. | Coroutine test functions are not natively supported. | | Method resolution order: | PytestUnhandledCoroutineWarning | PytestReturnNotNoneWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestUnhandledThreadExceptionWarning
Python Library Documentation: class PytestUnhandledThreadExceptionWarning in module pytest class PytestUnhandledThreadExceptionWarning(PytestWarning) | An unhandled exception occurred in a :class:`~threading.Thread`. | | Such exceptions don't propagate normally. | | Method resolution order: | PytestUnhandledThreadExceptionWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestUnknownMarkWarning
Python Library Documentation: class PytestUnknownMarkWarning in module pytest class PytestUnknownMarkWarning(PytestWarning) | Warning emitted on use of unknown markers. | | See :ref:`mark` for details. | | Method resolution order: | PytestUnknownMarkWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestUnraisableExceptionWarning
Python Library Documentation: class PytestUnraisableExceptionWarning in module pytest class PytestUnraisableExceptionWarning(PytestWarning) | An unraisable exception was reported. | | Unraisable exceptions are exceptions raised in :meth:`__del__ <object.__del__>` | implementations and similar situations when the exception cannot be raised | as normal. | | Method resolution order: | PytestUnraisableExceptionWarning | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Data descriptors inherited from PytestWarning: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.PytestWarning
Python Library Documentation: class PytestWarning in module pytest class PytestWarning(builtins.UserWarning) | Base class for all warnings emitted by pytest. | | Method resolution order: | PytestWarning | builtins.UserWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.UserWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.UserWarning: | | __new__(*args, **kwargs) class method of builtins.UserWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.Pytester
Python Library Documentation: class Pytester in module _pytest.pytester
class Pytester(builtins.object)
| Pytester(request: 'FixtureRequest', tmp_path_factory: 'TempPathFactory', monkeypatch: 'MonkeyPatch', *, _ispytest: 'bool' = False) -> 'None'
|
| Facilities to write tests/configuration files, execute pytest in isolation, and match
| against expected output, perfect for black-box testing of pytest plugins.
|
| It attempts to isolate the test run from external factors as much as possible, modifying
| the current working directory to :attr:`path` and environment variables during initialization.
|
| Methods defined here:
|
| __init__(self, request: 'FixtureRequest', tmp_path_factory: 'TempPathFactory', monkeypatch: 'MonkeyPatch', *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| chdir(self) -> 'None'
| Cd into the temporary directory.
|
| This is done automatically upon instantiation.
|
| collect_by_name(self, modcol: 'Collector', name: 'str') -> 'Item | Collector | None'
| Return the collection node for name from the module collection.
|
| Searches a module collection node for a collection node matching the
| given name.
|
| :param modcol: A module collection node; see :py:meth:`getmodulecol`.
| :param name: The name of the node to return.
|
| copy_example(self, name: 'str | None' = None) -> 'Path'
| Copy file from project's directory into the testdir.
|
| :param name:
| The name of the file to copy.
| :return:
| Path to the copied directory (inside ``self.path``).
| :rtype: pathlib.Path
|
| genitems(self, colitems: 'Sequence[Item | Collector]') -> 'list[Item]'
| Generate all test items from a collection node.
|
| This recurses into the collection node and returns a list of all the
| test items contained within.
|
| :param colitems:
| The collection nodes.
| :returns:
| The collected items.
|
| getinicfg(self, source: 'str') -> 'SectionWrapper'
| Return the pytest section from the tox.ini config file.
|
| getitem(self, source: 'str | os.PathLike[str]', funcname: 'str' = 'test_func') -> 'Item'
| Return the test item for a test function.
|
| Writes the source to a python file and runs pytest's collection on
| the resulting module, returning the test item for the requested
| function name.
|
| :param source:
| The module source.
| :param funcname:
| The name of the test function for which to return a test item.
| :returns:
| The test item.
|
| getitems(self, source: 'str | os.PathLike[str]') -> 'list[Item]'
| Return all test items collected from the module.
|
| Writes the source to a Python file and runs pytest's collection on
| the resulting module, returning all test items contained within.
|
| getmodulecol(self, source: 'str | os.PathLike[str]', configargs=(), *, withinit: 'bool' = False)
| Return the module collection node for ``source``.
|
| Writes ``source`` to a file using :py:meth:`makepyfile` and then
| runs the pytest collection on it, returning the collection node for the
| test module.
|
| :param source:
| The source code of the module to collect.
|
| :param configargs:
| Any extra arguments to pass to :py:meth:`parseconfigure`.
|
| :param withinit:
| Whether to also write an ``__init__.py`` file to the same
| directory to ensure it is a package.
|
| getnode(self, config: 'Config', arg: 'str | os.PathLike[str]') -> 'Collector | Item'
| Get the collection node of a file.
|
| :param config:
| A pytest config.
| See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.
| :param arg:
| Path to the file.
| :returns:
| The node.
|
| getpathnode(self, path: 'str | os.PathLike[str]') -> 'Collector | Item'
| Return the collection node of a file.
|
| This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
| create the (configured) pytest Config instance.
|
| :param path:
| Path to the file.
| :returns:
| The node.
|
| inline_genitems(self, *args) -> 'tuple[list[Item], HookRecorder]'
| Run ``pytest.main(['--collect-only'])`` in-process.
|
| Runs the :py:func:`pytest.main` function to run all of pytest inside
| the test process itself like :py:meth:`inline_run`, but returns a
| tuple of the collected items and a :py:class:`HookRecorder` instance.
|
| inline_run(self, *args: 'str | os.PathLike[str]', plugins=(), no_reraise_ctrlc: 'bool' = False) -> 'HookRecorder'
| Run ``pytest.main()`` in-process, returning a HookRecorder.
|
| Runs the :py:func:`pytest.main` function to run all of pytest inside
| the test process itself. This means it can return a
| :py:class:`HookRecorder` instance which gives more detailed results
| from that run than can be done by matching stdout/stderr from
| :py:meth:`runpytest`.
|
| :param args:
| Command line arguments to pass to :py:func:`pytest.main`.
| :param plugins:
| Extra plugin instances the ``pytest.main()`` instance should use.
| :param no_reraise_ctrlc:
| Typically we reraise keyboard interrupts from the child run. If
| True, the KeyboardInterrupt exception is captured.
|
| inline_runsource(self, source: 'str', *cmdlineargs) -> 'HookRecorder'
| Run a test module in process using ``pytest.main()``.
|
| This run writes "source" into a temporary file and runs
| ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
| for the result.
|
| :param source: The source code of the test module.
| :param cmdlineargs: Any extra command line arguments to use.
|
| make_hook_recorder(self, pluginmanager: 'PytestPluginManager') -> 'HookRecorder'
| Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`.
|
| makeconftest(self, source: 'str') -> 'Path'
| Write a conftest.py file.
|
| :param source: The contents.
| :returns: The conftest.py file.
|
| makefile(self, ext: 'str', *args: 'str', **kwargs: 'str') -> 'Path'
| Create new text file(s) in the test directory.
|
| :param ext:
| The extension the file(s) should use, including the dot, e.g. `.py`.
| :param args:
| All args are treated as strings and joined using newlines.
| The result is written as contents to the file. The name of the
| file is based on the test function requesting this fixture.
| :param kwargs:
| Each keyword is the name of a file, while the value of it will
| be written as contents of the file.
| :returns:
| The first created file.
|
| Examples:
|
| .. code-block:: python
|
| pytester.makefile(".txt", "line1", "line2")
|
| pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")
|
| To create binary files, use :meth:`pathlib.Path.write_bytes` directly:
|
| .. code-block:: python
|
| filename = pytester.path.joinpath("foo.bin")
| filename.write_bytes(b"...")
|
| makeini(self, source: 'str') -> 'Path'
| Write a tox.ini file.
|
| :param source: The contents.
| :returns: The tox.ini file.
|
| makepyfile(self, *args, **kwargs) -> 'Path'
| Shortcut for .makefile() with a .py extension.
|
| Defaults to the test name with a '.py' extension, e.g test_foobar.py, overwriting
| existing files.
|
| Examples:
|
| .. code-block:: python
|
| def test_something(pytester):
| # Initial file is created test_something.py.
| pytester.makepyfile("foobar")
| # To create multiple files, pass kwargs accordingly.
| pytester.makepyfile(custom="foobar")
| # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
|
| makepyprojecttoml(self, source: 'str') -> 'Path'
| Write a pyproject.toml file.
|
| :param source: The contents.
| :returns: The pyproject.ini file.
|
| .. versionadded:: 6.0
|
| maketxtfile(self, *args, **kwargs) -> 'Path'
| Shortcut for .makefile() with a .txt extension.
|
| Defaults to the test name with a '.txt' extension, e.g test_foobar.txt, overwriting
| existing files.
|
| Examples:
|
| .. code-block:: python
|
| def test_something(pytester):
| # Initial file is created test_something.txt.
| pytester.maketxtfile("foobar")
| # To create multiple files, pass kwargs accordingly.
| pytester.maketxtfile(custom="foobar")
| # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.
|
| mkdir(self, name: 'str | os.PathLike[str]') -> 'Path'
| Create a new (sub)directory.
|
| :param name:
| The name of the directory, relative to the pytester path.
| :returns:
| The created directory.
| :rtype: pathlib.Path
|
| mkpydir(self, name: 'str | os.PathLike[str]') -> 'Path'
| Create a new python package.
|
| This creates a (sub)directory with an empty ``__init__.py`` file so it
| gets recognised as a Python package.
|
| parseconfig(self, *args: 'str | os.PathLike[str]') -> 'Config'
| Return a new pytest :class:`pytest.Config` instance from given
| commandline args.
|
| This invokes the pytest bootstrapping code in _pytest.config to create a
| new :py:class:`pytest.PytestPluginManager` and call the
| :hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config`
| instance.
|
| If :attr:`plugins` has been populated they should be plugin modules
| to be registered with the plugin manager.
|
| parseconfigure(self, *args: 'str | os.PathLike[str]') -> 'Config'
| Return a new pytest configured Config instance.
|
| Returns a new :py:class:`pytest.Config` instance like
| :py:meth:`parseconfig`, but also calls the :hook:`pytest_configure`
| hook.
|
| popen(self, cmdargs: 'Sequence[str | os.PathLike[str]]', stdout: 'int | TextIO' = -1, stderr: 'int | TextIO' = -1, stdin: 'NotSetType | bytes | IO[Any] | int' = <NotSetType.token: 0>, **kw)
| Invoke :py:class:`subprocess.Popen`.
|
| Calls :py:class:`subprocess.Popen` making sure the current working
| directory is in ``PYTHONPATH``.
|
| You probably want to use :py:meth:`run` instead.
|
| run(self, *cmdargs: 'str | os.PathLike[str]', timeout: 'float | None' = None, stdin: 'NotSetType | bytes | IO[Any] | int' = <NotSetType.token: 0>) -> 'RunResult'
| Run a command with arguments.
|
| Run a process using :py:class:`subprocess.Popen` saving the stdout and
| stderr.
|
| :param cmdargs:
| The sequence of arguments to pass to :py:class:`subprocess.Popen`,
| with path-like objects being converted to :py:class:`str`
| automatically.
| :param timeout:
| The period in seconds after which to timeout and raise
| :py:class:`Pytester.TimeoutExpired`.
| :param stdin:
| Optional standard input.
|
| - If it is ``CLOSE_STDIN`` (Default), then this method calls
| :py:class:`subprocess.Popen` with ``stdin=subprocess.PIPE``, and
| the standard input is closed immediately after the new command is
| started.
|
| - If it is of type :py:class:`bytes`, these bytes are sent to the
| standard input of the command.
|
| - Otherwise, it is passed through to :py:class:`subprocess.Popen`.
| For further information in this case, consult the document of the
| ``stdin`` parameter in :py:class:`subprocess.Popen`.
| :type stdin: _pytest.compat.NotSetType | bytes | IO[Any] | int
| :returns:
| The result.
|
| runitem(self, source: 'str') -> 'Any'
| Run the "test_func" Item.
|
| The calling test instance (class containing the test method) must
| provide a ``.getrunner()`` method which should return a runner which
| can run the test protocol for a single item, e.g.
| ``_pytest.runner.runtestprotocol``.
|
| runpytest(self, *args: 'str | os.PathLike[str]', **kwargs: 'Any') -> 'RunResult'
| Run pytest inline or in a subprocess, depending on the command line
| option "--runpytest" and return a :py:class:`~pytest.RunResult`.
|
| runpytest_inprocess(self, *args: 'str | os.PathLike[str]', **kwargs: 'Any') -> 'RunResult'
| Return result of running pytest in-process, providing a similar
| interface to what self.runpytest() provides.
|
| runpytest_subprocess(self, *args: 'str | os.PathLike[str]', timeout: 'float | None' = None) -> 'RunResult'
| Run pytest as a subprocess with given arguments.
|
| Any plugins added to the :py:attr:`plugins` list will be added using the
| ``-p`` command line option. Additionally ``--basetemp`` is used to put
| any temporary files and directories in a numbered directory prefixed
| with "runpytest-" to not conflict with the normal numbered pytest
| location for temporary files and directories.
|
| :param args:
| The sequence of arguments to pass to the pytest subprocess.
| :param timeout:
| The period in seconds after which to timeout and raise
| :py:class:`Pytester.TimeoutExpired`.
| :returns:
| The result.
|
| runpython(self, script: 'os.PathLike[str]') -> 'RunResult'
| Run a python script using sys.executable as interpreter.
|
| runpython_c(self, command: 'str') -> 'RunResult'
| Run ``python -c "command"``.
|
| spawn(self, cmd: 'str', expect_timeout: 'float' = 10.0) -> 'pexpect.spawn'
| Run a command using pexpect.
|
| The pexpect child is returned.
|
| spawn_pytest(self, string: 'str', expect_timeout: 'float' = 10.0) -> 'pexpect.spawn'
| Run pytest using pexpect.
|
| This makes sure to use the right pytest and sets up the temporary
| directory locations.
|
| The pexpect child is returned.
|
| syspathinsert(self, path: 'str | os.PathLike[str] | None' = None) -> 'None'
| Prepend a directory to sys.path, defaults to :attr:`path`.
|
| This is undone automatically when this object dies at the end of each
| test.
|
| :param path:
| The path.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| path
| Temporary directory path used to create files/run tests from, etc.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| CLOSE_STDIN = <NotSetType.token: 0>
|
| TimeoutExpired = <class '_pytest.pytester.Pytester.TimeoutExpired'>
|
| __annotations__ = {'CLOSE_STDIN': 'Final'}
|
| __final__ = True
|
| __test__ = False
pytest.RecordedHookCall
Python Library Documentation: class RecordedHookCall in module _pytest.pytester
class RecordedHookCall(builtins.object)
| RecordedHookCall(name: 'str', kwargs) -> 'None'
|
| A recorded call to a hook.
|
| The arguments to the hook call are set as attributes.
| For example:
|
| .. code-block:: python
|
| calls = hook_recorder.getcalls("pytest_runtest_setup")
| # Suppose pytest_runtest_setup was called once with `item=an_item`.
| assert calls[0].item is an_item
|
| Methods defined here:
|
| __init__(self, name: 'str', kwargs) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __final__ = True
pytest.RunResult
Python Library Documentation: class RunResult in module _pytest.pytester
class RunResult(builtins.object)
| RunResult(ret: 'int | ExitCode', outlines: 'list[str]', errlines: 'list[str]', duration: 'float') -> 'None'
|
| The result of running a command from :class:`~pytest.Pytester`.
|
| Methods defined here:
|
| __init__(self, ret: 'int | ExitCode', outlines: 'list[str]', errlines: 'list[str]', duration: 'float') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| assert_outcomes(self, passed: 'int' = 0, skipped: 'int' = 0, failed: 'int' = 0, errors: 'int' = 0, xpassed: 'int' = 0, xfailed: 'int' = 0, warnings: 'int | None' = None, deselected: 'int | None' = None) -> 'None'
| Assert that the specified outcomes appear with the respective
| numbers (0 means it didn't occur) in the text output from a test run.
|
| ``warnings`` and ``deselected`` are only checked if not None.
|
| parseoutcomes(self) -> 'dict[str, int]'
| Return a dictionary of outcome noun -> count from parsing the terminal
| output that the test process produced.
|
| The returned nouns will always be in plural form::
|
| ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
|
| Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| parse_summary_nouns(lines) -> 'dict[str, int]'
| Extract the nouns from a pytest terminal summary line.
|
| It always returns the plural noun for consistency::
|
| ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
|
| Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __final__ = True
pytest.Session
Python Library Documentation: class Session in module _pytest.main
class Session(_pytest.nodes.Collector)
| Session(*k, **kw) -> 'NoReturn'
|
| The root of the collection tree.
|
| ``Session`` collects the initial paths given as arguments to pytest.
|
| Method resolution order:
| Session
| _pytest.nodes.Collector
| _pytest.nodes.Node
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, config: 'Config') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| collect(self) -> 'Iterator[nodes.Item | nodes.Collector]'
| Collect children (items and collectors) for this collector.
|
| genitems(self, node: 'nodes.Item | nodes.Collector') -> 'Iterator[nodes.Item]'
|
| gethookproxy(self, fspath: 'os.PathLike[str]') -> 'pluggy.HookRelay'
|
| isinitpath(self, path: 'str | os.PathLike[str]', *, with_parents: 'bool' = False) -> 'bool'
| Is path an initial path?
|
| An initial path is a path explicitly given to pytest on the command
| line.
|
| :param with_parents:
| If set, also return True if the path is a parent of an initial path.
|
| .. versionchanged:: 8.0
| Added the ``with_parents`` parameter.
|
| perform_collect(self, args: 'Sequence[str] | None' = None, genitems: 'bool' = True) -> 'Sequence[nodes.Item | nodes.Collector]'
| Perform the collection phase for this session.
|
| This is called by the default :hook:`pytest_collection` hook
| implementation; see the documentation of this hook for more details.
| For testing purposes, it may also be called directly on a fresh
| ``Session``.
|
| This function normally recursively expands any collectors collected
| from the session to their items, and only items are returned. For
| testing purposes, this may be suppressed by passing ``genitems=False``,
| in which case the return value contains these collectors unexpanded,
| and ``session.items`` is empty.
|
| pytest_collectreport = pytest_runtest_logreport(self, report: 'TestReport | CollectReport') -> 'None'
|
| pytest_collectstart(self) -> 'None'
|
| pytest_runtest_logreport(self, report: 'TestReport | CollectReport') -> 'None'
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_config(config: 'Config') -> 'Session'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| startpath
| The path from which pytest was invoked.
|
| .. versionadded:: 7.0.0
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| shouldfail
|
| shouldstop
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| Failed = <class '_pytest.main.Failed'>
| Signals a stop as failed test run.
|
|
| Interrupted = <class 'Interrupted'>
| Signals that the test run was interrupted.
|
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'_fixturemanager': 'FixtureManager', '_setupstate':...
|
| __final__ = True
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Collector:
|
| repr_failure(self, excinfo: 'ExceptionInfo[BaseException]') -> 'str | TerminalRepr'
| Return a representation of a collection failure.
|
| :param excinfo: Exception information for the failure.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Collector:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _pytest.nodes.Collector:
|
| CollectError = <class '_pytest.nodes.Collector.CollectError'>
| An error during collection, contains a custom message.
|
|
| ----------------------------------------------------------------------
| Methods inherited from _pytest.nodes.Node:
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| add_marker(self, marker: 'str | MarkDecorator', append: 'bool' = True) -> 'None'
| Dynamically add a marker object to the node.
|
| :param marker:
| The marker.
| :param append:
| Whether to append the marker, or prepend it.
|
| addfinalizer(self, fin: 'Callable[[], object]') -> 'None'
| Register a function to be called without arguments when this node is
| finalized.
|
| This method can only be called when this node is active
| in a setup chain, for example during self.setup().
|
| get_closest_marker(self, name: 'str', default: 'Mark | None' = None) -> 'Mark | None'
| Return the first marker matching the name, from closest (for
| example function) to farther level (for example module level).
|
| :param default: Fallback return value if no marker was found.
| :param name: Name to filter by.
|
| getparent(self, cls: 'type[_NodeType]') -> '_NodeType | None'
| Get the closest parent node (including self) which is an instance of
| the given class.
|
| :param cls: The node class to search for.
| :returns: The node, if found.
|
| iter_markers(self, name: 'str | None' = None) -> 'Iterator[Mark]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of the markers of the node.
|
| iter_markers_with_node(self, name: 'str | None' = None) -> 'Iterator[tuple[Node, Mark]]'
| Iterate over all markers of the node.
|
| :param name: If given, filter the results by the name attribute.
| :returns: An iterator of (node, mark) tuples.
|
| iter_parents(self) -> 'Iterator[Node]'
| Iterate over all parent collectors starting from and including self
| up to the root of the collection tree.
|
| .. versionadded:: 8.1
|
| listchain(self) -> 'list[Node]'
| Return a list of all parent collectors starting from the root of the
| collection tree down to and including self.
|
| listextrakeywords(self) -> 'set[str]'
| Return a set of all extra keywords in self and any parents.
|
| listnames(self) -> 'list[str]'
|
| setup(self) -> 'None'
|
| teardown(self) -> 'None'
|
| warn(self, warning: 'Warning') -> 'None'
| Issue a warning for this Node.
|
| Warnings will be displayed after the test session, unless explicitly suppressed.
|
| :param Warning warning:
| The warning instance to issue.
|
| :raises ValueError: If ``warning`` instance is not a subclass of Warning.
|
| Example usage:
|
| .. code-block:: python
|
| node.warn(PytestWarning("some message"))
| node.warn(UserWarning("some message"))
|
| .. versionchanged:: 6.2
| Any subclass of :class:`Warning` is now accepted, rather than only
| :class:`PytestWarning <pytest.PytestWarning>` subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from _pytest.nodes.Node:
|
| from_parent(parent: 'Node', **kw) -> 'Self'
| Public constructor for Nodes.
|
| This indirection got introduced in order to enable removing
| the fragile logic from the node constructors.
|
| Subclasses can use ``super().from_parent(...)`` when overriding the
| construction.
|
| :param parent: The parent node of this Node.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _pytest.nodes.Node:
|
| ihook
| fspath-sensitive hook proxy used to call pytest hooks.
|
| nodeid
| A ::-separated string denoting its collection tree address.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _pytest.nodes.Node:
|
| __dict__
| dictionary for instance variables
|
| config
|
| name
|
| parent
|
| path
|
| session
pytest.Stash
Python Library Documentation: class Stash in module _pytest.stash class Stash(builtins.object) | Stash() -> 'None' | | ``Stash`` is a type-safe heterogeneous mutable mapping that | allows keys and value types to be defined separately from | where it (the ``Stash``) is created. | | Usually you will be given an object which has a ``Stash``, for example | :class:`~pytest.Config` or a :class:`~_pytest.nodes.Node`: | | .. code-block:: python | | stash: Stash = some_object.stash | | If a module or plugin wants to store data in this ``Stash``, it creates | :class:`StashKey`\s for its keys (at the module level): | | .. code-block:: python | | # At the top-level of the module | some_str_key = StashKey[str]() | some_bool_key = StashKey[bool]() | | To store information: | | .. code-block:: python | | # Value type must match the key. | stash[some_str_key] = "value" | stash[some_bool_key] = True | | To retrieve the information: | | .. code-block:: python | | # The static type of some_str is str. | some_str = stash[some_str_key] | # The static type of some_bool is bool. | some_bool = stash[some_bool_key] | | .. versionadded:: 7.0 | | Methods defined here: | | __contains__(self, key: 'StashKey[T]') -> 'bool' | Return whether key was set. | | __delitem__(self, key: 'StashKey[T]') -> 'None' | Delete the value for key. | | Raises ``KeyError`` if the key wasn't set before. | | __getitem__(self, key: 'StashKey[T]') -> 'T' | Get the value for key. | | Raises ``KeyError`` if the key wasn't set before. | | __init__(self) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __len__(self) -> 'int' | Return how many items exist in the stash. | | __setitem__(self, key: 'StashKey[T]', value: 'T') -> 'None' | Set a value for key. | | get(self, key: 'StashKey[T]', default: 'D') -> 'T | D' | Get the value for key, or return default if the key wasn't set | before. | | setdefault(self, key: 'StashKey[T]', default: 'T') -> 'T' | Return the value of key if already set, otherwise set the value | of key to default and return default.
pytest.StashKey
Python Library Documentation: class StashKey in module _pytest.stash
class StashKey(typing.Generic)
| ``StashKey`` is an object used as a key to a :class:`Stash`.
|
| A ``StashKey`` is associated with the type ``T`` of the value of the key.
|
| A ``StashKey`` is unique and cannot conflict with another key.
|
| .. versionadded:: 7.0
|
| Method resolution order:
| StashKey
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~T],)
|
| __parameters__ = (~T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pytest.TempPathFactory
Python Library Documentation: class TempPathFactory in module _pytest.tmpdir
class TempPathFactory(builtins.object)
| TempPathFactory(given_basetemp: 'Path | None', retention_count: 'int', retention_policy: 'RetentionType', trace, basetemp: 'Path | None' = None, *, _ispytest: 'bool' = False) -> 'None'
|
| Factory for temporary directories under the common base temp directory.
|
| The base directory can be configured using the ``--basetemp`` option.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, given_basetemp: 'Path | None', retention_count: 'int', retention_policy: 'RetentionType', trace, basetemp: 'Path | None' = None, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| getbasetemp(self) -> 'Path'
| Return the base temporary directory, creating it if needed.
|
| :returns:
| The base temporary directory.
|
| mktemp(self, basename: 'str', numbered: 'bool' = True) -> 'Path'
| Create a new temporary directory managed by the factory.
|
| :param basename:
| Directory base name, must be a relative path.
|
| :param numbered:
| If ``True``, ensure the directory is unique by adding a numbered
| suffix greater than any existing one: ``basename="foo-"`` and ``numbered=True``
| means that this function will create directories named ``"foo-0"``,
| ``"foo-1"``, ``"foo-2"`` and so on.
|
| :returns:
| The path to the new directory.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_config(config: 'Config', *, _ispytest: 'bool' = False) -> 'TempPathFactory'
| Create a factory according to pytest configuration.
|
| :meta private:
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_basetemp': 'Path | None', '_given_basetemp': 'Pat...
|
| __dataclass_fields__ = {'_basetemp': Field(name='_basetemp',type='Path...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __final__ = True
|
| __hash__ = None
|
| __match_args__ = ('_given_basetemp', '_trace', '_basetemp', '_retentio...
pytest.TempdirFactory
Python Library Documentation: class TempdirFactory in module _pytest.legacypath
class TempdirFactory(builtins.object)
| TempdirFactory(tmppath_factory: 'TempPathFactory', *, _ispytest: 'bool' = False) -> 'None'
|
| Backward compatibility wrapper that implements ``py.path.local``
| for :class:`TempPathFactory`.
|
| .. note::
| These days, it is preferred to use ``tmp_path_factory``.
|
| :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, tmppath_factory: 'TempPathFactory', *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| getbasetemp(self) -> 'LEGACY_PATH'
| Same as :meth:`TempPathFactory.getbasetemp`, but returns a ``py.path.local`` object.
|
| mktemp(self, basename: 'str', numbered: 'bool' = True) -> 'LEGACY_PATH'
| Same as :meth:`TempPathFactory.mktemp`, but returns a ``py.path.local`` object.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_tmppath_factory': 'TempPathFactory'}
|
| __dataclass_fields__ = {'_tmppath_factory': Field(name='_tmppath_facto...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __final__ = True
|
| __hash__ = None
|
| __match_args__ = ('_tmppath_factory',)
pytest.TestReport
Python Library Documentation: class TestReport in module _pytest.reports
class TestReport(BaseReport)
| TestReport(nodeid: 'str', location: 'tuple[str, int | None, str]', keywords: 'Mapping[str, Any]', outcome: "Literal['passed', 'failed', 'skipped']", longrepr: 'None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr', when: "Literal['setup', 'call', 'teardown']", sections: 'Iterable[tuple[str, str]]' = (), duration: 'float' = 0, start: 'float' = 0, stop: 'float' = 0, user_properties: 'Iterable[tuple[str, object]] | None' = None, **extra) -> 'None'
|
| Basic test report object (also used for setup and teardown calls if
| they fail).
|
| Reports can contain arbitrary extra attributes.
|
| Method resolution order:
| TestReport
| BaseReport
| builtins.object
|
| Methods defined here:
|
| __init__(self, nodeid: 'str', location: 'tuple[str, int | None, str]', keywords: 'Mapping[str, Any]', outcome: "Literal['passed', 'failed', 'skipped']", longrepr: 'None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr', when: "Literal['setup', 'call', 'teardown']", sections: 'Iterable[tuple[str, str]]' = (), duration: 'float' = 0, start: 'float' = 0, stop: 'float' = 0, user_properties: 'Iterable[tuple[str, object]] | None' = None, **extra) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_item_and_call(item: 'Item', call: 'CallInfo[None]') -> 'TestReport'
| Create and fill a TestReport with standard item and call info.
|
| :param item: The item.
| :param call: The call info.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'wasxfail': 'str'}
|
| __final__ = True
|
| __test__ = False
|
| ----------------------------------------------------------------------
| Methods inherited from BaseReport:
|
| get_sections(self, prefix: 'str') -> 'Iterator[tuple[str, str]]'
|
| toterminal(self, out: 'TerminalWriter') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseReport:
|
| caplog
| Return captured log lines, if log capturing is enabled.
|
| .. versionadded:: 3.5
|
| capstderr
| Return captured text from stderr, if capturing is enabled.
|
| .. versionadded:: 3.0
|
| capstdout
| Return captured text from stdout, if capturing is enabled.
|
| .. versionadded:: 3.0
|
| count_towards_summary
| **Experimental** Whether this report should be counted towards the
| totals shown at the end of the test session: "1 passed, 1 failure, etc".
|
| .. note::
|
| This function is considered **experimental**, so beware that it is subject to changes
| even in patch releases.
|
| failed
| Whether the outcome is failed.
|
| fspath
| The path portion of the reported node, as a string.
|
| head_line
| **Experimental** The head line shown with longrepr output for this
| report, more commonly during traceback representation during
| failures::
|
| ________ Test.foo ________
|
|
| In the example above, the head_line is "Test.foo".
|
| .. note::
|
| This function is considered **experimental**, so beware that it is subject to changes
| even in patch releases.
|
| longreprtext
| Read-only property that returns the full string representation of
| ``longrepr``.
|
| .. versionadded:: 3.0
|
| passed
| Whether the outcome is passed.
|
| skipped
| Whether the outcome is skipped.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseReport:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
pytest.TestShortLogReport
Python Library Documentation: class TestShortLogReport in module _pytest.terminal
class TestShortLogReport(builtins.tuple)
| TestShortLogReport(category: ForwardRef('str'), letter: ForwardRef('str'), word: ForwardRef('str | tuple[str, Mapping[str, bool]]'))
|
| Used to store the test status result category, shortletter and verbose word.
| For example ``"rerun", "R", ("RERUN", {"yellow": True})``.
|
| :ivar category:
| The class of result, for example ``“passed”``, ``“skipped”``, ``“error”``, or the empty string.
|
| :ivar letter:
| The short letter shown as testing progresses, for example ``"."``, ``"s"``, ``"E"``, or the empty string.
|
| :ivar word:
| Verbose word is shown as testing progresses in verbose mode, for example ``"PASSED"``, ``"SKIPPED"``,
| ``"ERROR"``, or the empty string.
|
| Method resolution order:
| TestShortLogReport
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __getnewargs__(self) from collections.TestShortLogReport
| Return self as a plain tuple. Used by copy and pickle.
|
| __repr__(self) from collections.TestShortLogReport
| Return a nicely formatted representation string
|
| _asdict(self) from collections.TestShortLogReport
| Return a new dict which maps field names to their values.
|
| _replace(self, /, **kwds) from collections.TestShortLogReport
| Return a new TestShortLogReport object replacing specified fields with new values
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| _make(iterable) from collections.TestShortLogReport
| Make a new TestShortLogReport object from a sequence or iterable
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(_cls, category: ForwardRef('str'), letter: ForwardRef('str'), word: ForwardRef('str | tuple[str, Mapping[str, bool]]')) from namedtuple_TestShortLogReport.TestShortLogReport
| Create new instance of TestShortLogReport(category, letter, word)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| category
| Alias for field number 0
|
| letter
| Alias for field number 1
|
| word
| Alias for field number 2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'category': ForwardRef('str'), 'letter': ForwardRef...
|
| __match_args__ = ('category', 'letter', 'word')
|
| __orig_bases__ = (<function NamedTuple>,)
|
| _field_defaults = {}
|
| _fields = ('category', 'letter', 'word')
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...)
| See PEP 585
pytest.Testdir
Python Library Documentation: class Testdir in module _pytest.legacypath
class Testdir(builtins.object)
| Testdir(pytester: 'Pytester', *, _ispytest: 'bool' = False) -> 'None'
|
| Similar to :class:`Pytester`, but this class works with legacy legacy_path objects instead.
|
| All methods just forward to an internal :class:`Pytester` instance, converting results
| to `legacy_path` objects as necessary.
|
| Methods defined here:
|
| __init__(self, pytester: 'Pytester', *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __str__(self) -> 'str'
| Return str(self).
|
| chdir(self) -> 'None'
| See :meth:`Pytester.chdir`.
|
| collect_by_name(self, modcol: 'Collector', name: 'str') -> 'Item | Collector | None'
| See :meth:`Pytester.collect_by_name`.
|
| copy_example(self, name=None) -> 'LEGACY_PATH'
| See :meth:`Pytester.copy_example`.
|
| finalize(self) -> 'None'
|
| genitems(self, colitems: 'list[Item | Collector]') -> 'list[Item]'
| See :meth:`Pytester.genitems`.
|
| getinicfg(self, source: 'str') -> 'SectionWrapper'
| See :meth:`Pytester.getinicfg`.
|
| getitem(self, source, funcname='test_func')
| See :meth:`Pytester.getitem`.
|
| getitems(self, source)
| See :meth:`Pytester.getitems`.
|
| getmodulecol(self, source, configargs=(), withinit=False)
| See :meth:`Pytester.getmodulecol`.
|
| getnode(self, config: 'Config', arg) -> 'Item | Collector | None'
| See :meth:`Pytester.getnode`.
|
| getpathnode(self, path)
| See :meth:`Pytester.getpathnode`.
|
| inline_genitems(self, *args)
| See :meth:`Pytester.inline_genitems`.
|
| inline_run(self, *args, plugins=(), no_reraise_ctrlc: 'bool' = False)
| See :meth:`Pytester.inline_run`.
|
| inline_runsource(self, source, *cmdlineargs)
| See :meth:`Pytester.inline_runsource`.
|
| make_hook_recorder(self, pluginmanager) -> 'HookRecorder'
| See :meth:`Pytester.make_hook_recorder`.
|
| makeconftest(self, source) -> 'LEGACY_PATH'
| See :meth:`Pytester.makeconftest`.
|
| makefile(self, ext, *args, **kwargs) -> 'LEGACY_PATH'
| See :meth:`Pytester.makefile`.
|
| makeini(self, source) -> 'LEGACY_PATH'
| See :meth:`Pytester.makeini`.
|
| makepyfile(self, *args, **kwargs) -> 'LEGACY_PATH'
| See :meth:`Pytester.makepyfile`.
|
| makepyprojecttoml(self, source) -> 'LEGACY_PATH'
| See :meth:`Pytester.makepyprojecttoml`.
|
| maketxtfile(self, *args, **kwargs) -> 'LEGACY_PATH'
| See :meth:`Pytester.maketxtfile`.
|
| mkdir(self, name) -> 'LEGACY_PATH'
| See :meth:`Pytester.mkdir`.
|
| mkpydir(self, name) -> 'LEGACY_PATH'
| See :meth:`Pytester.mkpydir`.
|
| parseconfig(self, *args) -> 'Config'
| See :meth:`Pytester.parseconfig`.
|
| parseconfigure(self, *args) -> 'Config'
| See :meth:`Pytester.parseconfigure`.
|
| popen(self, cmdargs, stdout=-1, stderr=-1, stdin=<NotSetType.token: 0>, **kw)
| See :meth:`Pytester.popen`.
|
| run(self, *cmdargs, timeout=None, stdin=<NotSetType.token: 0>) -> 'RunResult'
| See :meth:`Pytester.run`.
|
| runitem(self, source)
| See :meth:`Pytester.runitem`.
|
| runpytest(self, *args, **kwargs) -> 'RunResult'
| See :meth:`Pytester.runpytest`.
|
| runpytest_inprocess(self, *args, **kwargs) -> 'RunResult'
| See :meth:`Pytester.runpytest_inprocess`.
|
| runpytest_subprocess(self, *args, timeout=None) -> 'RunResult'
| See :meth:`Pytester.runpytest_subprocess`.
|
| runpython(self, script) -> 'RunResult'
| See :meth:`Pytester.runpython`.
|
| runpython_c(self, command)
| See :meth:`Pytester.runpython_c`.
|
| spawn(self, cmd: 'str', expect_timeout: 'float' = 10.0) -> 'pexpect.spawn'
| See :meth:`Pytester.spawn`.
|
| spawn_pytest(self, string: 'str', expect_timeout: 'float' = 10.0) -> 'pexpect.spawn'
| See :meth:`Pytester.spawn_pytest`.
|
| syspathinsert(self, path=None) -> 'None'
| See :meth:`Pytester.syspathinsert`.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| monkeypatch
|
| request
|
| test_tmproot
|
| tmpdir
| Temporary directory where tests are executed.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| plugins
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| CLOSE_STDIN = <NotSetType.token: 0>
|
| TimeoutExpired = <class '_pytest.pytester.Pytester.TimeoutExpired'>
|
| __annotations__ = {'CLOSE_STDIN': 'Final', 'TimeoutExpired': 'Final'}
|
| __final__ = True
|
| __test__ = False
pytest.UsageError
Python Library Documentation: class UsageError in module _pytest.config.exceptions class UsageError(builtins.Exception) | Error in pytest usage or invocation. | | Method resolution order: | UsageError | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __final__ = True | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pytest.WarningsRecorder
Python Library Documentation: class WarningsRecorder in module _pytest.recwarn class WarningsRecorder(warnings.catch_warnings) | WarningsRecorder(*, _ispytest: 'bool' = False) -> 'None' | | A context manager to record raised warnings. | | Each recorded warning is an instance of :class:`warnings.WarningMessage`. | | Adapted from `warnings.catch_warnings`. | | .. note:: | ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated | differently; see :ref:`ensuring_function_triggers`. | | Method resolution order: | WarningsRecorder | warnings.catch_warnings | builtins.object | | Methods defined here: | | __enter__(self) -> 'Self' | | __exit__(self, exc_type: 'type[BaseException] | None', exc_val: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None' | | __getitem__(self, i: 'int') -> 'warnings.WarningMessage' | Get a recorded warning by index. | | __init__(self, *, _ispytest: 'bool' = False) -> 'None' | Specify whether to record warnings and if an alternative module | should be used other than sys.modules['warnings']. | | For compatibility with Python 3.0, please consider all arguments to be | keyword-only. | | __iter__(self) -> 'Iterator[warnings.WarningMessage]' | Iterate through the recorded warnings. | | __len__(self) -> 'int' | The number of recorded warnings. | | clear(self) -> 'None' | Clear the list of recorded warnings. | | pop(self, cls: 'type[Warning]' = <class 'Warning'>) -> 'warnings.WarningMessage' | Pop the first recorded warning which is an instance of ``cls``, | but not an instance of a child class of any other match. | Raises ``AssertionError`` if there is no match. | | ---------------------------------------------------------------------- | Readonly properties defined here: | | list | The list of recorded warnings. | | ---------------------------------------------------------------------- | Methods inherited from warnings.catch_warnings: | | __repr__(self) | Return repr(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from warnings.catch_warnings: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
pytest.annotations
Python Library Documentation: _Feature in module __future__ object class _Feature(builtins.object) | _Feature(optionalRelease, mandatoryRelease, compiler_flag) | | Methods defined here: | | __init__(self, optionalRelease, mandatoryRelease, compiler_flag) | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) | Return repr(self). | | getMandatoryRelease(self) | Return release in which this feature will become mandatory. | | This is a 5-tuple, of the same form as sys.version_info, or, if | the feature was dropped, or the release date is undetermined, is None. | | getOptionalRelease(self) | Return first release in which this feature was recognized. | | This is a 5-tuple, of the same form as sys.version_info. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
pytest.approx
Python Library Documentation: function approx in module _pytest.python_api
approx(expected, rel=None, abs=None, nan_ok: 'bool' = False) -> 'ApproxBase'
Assert that two numbers (or two ordered sequences of numbers) are equal to each other
within some tolerance.
Due to the :doc:`python:tutorial/floatingpoint`, numbers that we
would intuitively expect to be equal are not always so::
>>> 0.1 + 0.2 == 0.3
False
This problem is commonly encountered when writing tests, e.g. when making
sure that floating-point values are what you expect them to be. One way to
deal with this problem is to assert that two floating-point numbers are
equal to within some appropriate tolerance::
>>> abs((0.1 + 0.2) - 0.3) < 1e-6
True
However, comparisons like this are tedious to write and difficult to
understand. Furthermore, absolute comparisons like the one above are
usually discouraged because there's no tolerance that works well for all
situations. ``1e-6`` is good for numbers around ``1``, but too small for
very big numbers and too big for very small ones. It's better to express
the tolerance as a fraction of the expected value, but relative comparisons
like that are even more difficult to write correctly and concisely.
The ``approx`` class performs floating-point comparisons using a syntax
that's as intuitive as possible::
>>> from pytest import approx
>>> 0.1 + 0.2 == approx(0.3)
True
The same syntax also works for ordered sequences of numbers::
>>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
True
``numpy`` arrays::
>>> import numpy as np # doctest: +SKIP
>>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
True
And for a ``numpy`` array against a scalar::
>>> import numpy as np # doctest: +SKIP
>>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
True
Only ordered sequences are supported, because ``approx`` needs
to infer the relative position of the sequences without ambiguity. This means
``sets`` and other unordered sequences are not supported.
Finally, dictionary *values* can also be compared::
>>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
True
The comparison will be true if both mappings have the same keys and their
respective values match the expected tolerances.
**Tolerances**
By default, ``approx`` considers numbers within a relative tolerance of
``1e-6`` (i.e. one part in a million) of its expected value to be equal.
This treatment would lead to surprising results if the expected value was
``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
To handle this case less surprisingly, ``approx`` also considers numbers
within an absolute tolerance of ``1e-12`` of its expected value to be
equal. Infinity and NaN are special cases. Infinity is only considered
equal to itself, regardless of the relative tolerance. NaN is not
considered equal to anything by default, but you can make it be equal to
itself by setting the ``nan_ok`` argument to True. (This is meant to
facilitate comparing arrays that use NaN to mean "no data".)
Both the relative and absolute tolerances can be changed by passing
arguments to the ``approx`` constructor::
>>> 1.0001 == approx(1)
False
>>> 1.0001 == approx(1, rel=1e-3)
True
>>> 1.0001 == approx(1, abs=1e-3)
True
If you specify ``abs`` but not ``rel``, the comparison will not consider
the relative tolerance at all. In other words, two numbers that are within
the default relative tolerance of ``1e-6`` will still be considered unequal
if they exceed the specified absolute tolerance. If you specify both
``abs`` and ``rel``, the numbers will be considered equal if either
tolerance is met::
>>> 1 + 1e-8 == approx(1)
True
>>> 1 + 1e-8 == approx(1, abs=1e-12)
False
>>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
True
You can also use ``approx`` to compare nonnumeric types, or dicts and
sequences containing nonnumeric types, in which case it falls back to
strict equality. This can be useful for comparing dicts and sequences that
can contain optional values::
>>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None})
True
>>> [None, 1.0000005] == approx([None,1])
True
>>> ["foo", 1.0000005] == approx([None,1])
False
If you're thinking about using ``approx``, then you might want to know how
it compares to other good ways of comparing floating-point numbers. All of
these algorithms are based on relative and absolute tolerances and should
agree for the most part, but they do have meaningful differences:
- ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative
tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
tolerance is met. Because the relative tolerance is calculated w.r.t.
both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor
``b`` is a "reference value"). You have to specify an absolute tolerance
if you want to compare to ``0.0`` because there is no tolerance by
default. More information: :py:func:`math.isclose`.
- ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
between ``a`` and ``b`` is less that the sum of the relative tolerance
w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance
is only calculated w.r.t. ``b``, this test is asymmetric and you can
think of ``b`` as the reference value. Support for comparing sequences
is provided by :py:func:`numpy.allclose`. More information:
:std:doc:`numpy:reference/generated/numpy.isclose`.
- ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
are within an absolute tolerance of ``1e-7``. No relative tolerance is
considered , so this function is not appropriate for very large or very
small numbers. Also, it's only available in subclasses of ``unittest.TestCase``
and it's ugly because it doesn't follow PEP8. More information:
:py:meth:`unittest.TestCase.assertAlmostEqual`.
- ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
Because the relative tolerance is only calculated w.r.t. ``b``, this test
is asymmetric and you can think of ``b`` as the reference value. In the
special case that you explicitly specify an absolute tolerance but not a
relative tolerance, only the absolute tolerance is considered.
.. note::
``approx`` can handle numpy arrays, but we recommend the
specialised test helpers in :std:doc:`numpy:reference/routines.testing`
if you need support for comparisons, NaNs, or ULP-based tolerances.
To match strings using regex, you can use
`Matches <https://github.com/asottile/re-assert#re_assertmatchespattern-str-args-kwargs>`_
from the
`re_assert package <https://github.com/asottile/re-assert>`_.
.. warning::
.. versionchanged:: 3.2
In order to avoid inconsistent behavior, :py:exc:`TypeError` is
raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.
The example below illustrates the problem::
assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)
assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)
In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
comparison. This is because the call hierarchy of rich comparisons
follows a fixed behavior. More information: :py:meth:`object.__ge__`
.. versionchanged:: 3.7.1
``approx`` raises ``TypeError`` when it encounters a dict value or
sequence element of nonnumeric type.
.. versionchanged:: 6.1.0
``approx`` falls back to strict equality for nonnumeric types instead
of raising ``TypeError``.
pytest.cmdline
Python Library Documentation: class cmdline in module _pytest.config class cmdline(builtins.object) | Static methods defined here: | | main(args: 'list[str] | os.PathLike[str] | None' = None, plugins: 'Sequence[str | _PluggyPlugin] | None' = None) -> 'int | ExitCode' from _pytest.config | Perform an in-process test run. | | :param args: | List of command line arguments. If `None` or not given, defaults to reading | arguments directly from the process command line (:data:`sys.argv`). | :param plugins: List of plugin objects to be auto-registered during initialization. | | :returns: An exit code. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
pytest.console_main
Python Library Documentation: function console_main in module _pytest.config
console_main() -> 'int'
The CLI entry point of pytest.
This function is not meant for programmable use; use `main()` instead.
pytest.deprecated_call
Python Library Documentation: function deprecated_call in module _pytest.recwarn
deprecated_call(func: 'Callable[..., Any] | None' = None, *args: 'Any', **kwargs: 'Any') -> 'WarningsRecorder | Any'
Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning`` or ``FutureWarning``.
This function can be used as a context manager::
>>> import warnings
>>> def api_call_v2():
... warnings.warn('use v3 of this api', DeprecationWarning)
... return 200
>>> import pytest
>>> with pytest.deprecated_call():
... assert api_call_v2() == 200
It can also be used by passing a function and ``*args`` and ``**kwargs``,
in which case it will ensure calling ``func(*args, **kwargs)`` produces one of
the warnings types above. The return value is the return value of the function.
In the context manager form you may use the keyword argument ``match`` to assert
that the warning matches a text or regex.
The context manager produces a list of :class:`warnings.WarningMessage` objects,
one for each warning raised.
pytest.exit
Python Library Documentation: function exit in module _pytest.outcomes
exit(reason: 'str' = '', returncode: 'int | None' = None) -> 'NoReturn'
Exit testing process.
:param reason:
The message to show as the reason for exiting pytest. reason has a default value
only because `msg` is deprecated.
:param returncode:
Return code to be used when exiting pytest. None means the same as ``0`` (no error), same as :func:`sys.exit`.
:raises pytest.exit.Exception:
The exception that is raised.
pytest.fail
Python Library Documentation: function fail in module _pytest.outcomes
fail(reason: 'str' = '', pytrace: 'bool' = True) -> 'NoReturn'
Explicitly fail an executing test with the given message.
:param reason:
The message to show the user as reason for the failure.
:param pytrace:
If False, msg represents the full failure information and no
python traceback will be reported.
:raises pytest.fail.Exception:
The exception that is raised.
pytest.fixture
Python Library Documentation: function fixture in module _pytest.fixtures
fixture(fixture_function: 'FixtureFunction | None' = None, *, scope: '_ScopeName | Callable[[str, Config], _ScopeName]' = 'function', params: 'Iterable[object] | None' = None, autouse: 'bool' = False, ids: 'Sequence[object | None] | Callable[[Any], object | None] | None' = None, name: 'str | None' = None) -> 'FixtureFunctionMarker | FixtureFunction'
Decorator to mark a fixture factory function.
This decorator can be used, with or without parameters, to define a
fixture function.
The name of the fixture function can later be referenced to cause its
invocation ahead of running tests: test modules or classes can use the
``pytest.mark.usefixtures(fixturename)`` marker.
Test functions can directly use fixture names as input arguments in which
case the fixture instance returned from the fixture function will be
injected.
Fixtures can provide their values to test functions using ``return`` or
``yield`` statements. When using ``yield`` the code block after the
``yield`` statement is executed as teardown code regardless of the test
outcome, and must yield exactly once.
:param scope:
The scope for which this fixture is shared; one of ``"function"``
(default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``.
This parameter may also be a callable which receives ``(fixture_name, config)``
as parameters, and must return a ``str`` with one of the values mentioned above.
See :ref:`dynamic scope` in the docs for more information.
:param params:
An optional list of parameters which will cause multiple invocations
of the fixture function and all of the tests using it. The current
parameter is available in ``request.param``.
:param autouse:
If True, the fixture func is activated for all tests that can see it.
If False (the default), an explicit reference is needed to activate
the fixture.
:param ids:
Sequence of ids each corresponding to the params so that they are
part of the test id. If no ids are provided they will be generated
automatically from the params.
:param name:
The name of the fixture. This defaults to the name of the decorated
function. If a fixture is used in the same module in which it is
defined, the function name of the fixture will be shadowed by the
function arg that requests the fixture; one way to resolve this is to
name the decorated function ``fixture_<fixturename>`` and then use
``@pytest.fixture(name='<fixturename>')``.
pytest.freeze_includes
Python Library Documentation: function freeze_includes in module _pytest.freeze_support
freeze_includes() -> 'list[str]'
Return a list of module names used by pytest that should be
included by cx_freeze.
pytest.hookimpl
Python Library Documentation: HookimplMarker in module pluggy._hooks object
class HookimplMarker(builtins.object)
| HookimplMarker(project_name: 'str') -> 'None'
|
| Decorator for marking functions as hook implementations.
|
| Instantiate it with a ``project_name`` to get a decorator.
| Calling :meth:`PluginManager.register` later will discover all marked
| functions if the :class:`PluginManager` uses the same project name.
|
| Methods defined here:
|
| __call__(self, function: '_F | None' = None, hookwrapper: 'bool' = False, optionalhook: 'bool' = False, tryfirst: 'bool' = False, trylast: 'bool' = False, specname: 'str | None' = None, wrapper: 'bool' = False) -> '_F | Callable[[_F], _F]'
| If passed a function, directly sets attributes on the function
| which will make it discoverable to :meth:`PluginManager.register`.
|
| If passed no function, returns a decorator which can be applied to a
| function later using the attributes supplied.
|
| :param optionalhook:
| If ``True``, a missing matching hook specification will not result
| in an error (by default it is an error if no matching spec is
| found). See :ref:`optionalhook`.
|
| :param tryfirst:
| If ``True``, this hook implementation will run as early as possible
| in the chain of N hook implementations for a specification. See
| :ref:`callorder`.
|
| :param trylast:
| If ``True``, this hook implementation will run as late as possible
| in the chain of N hook implementations for a specification. See
| :ref:`callorder`.
|
| :param wrapper:
| If ``True`` ("new-style hook wrapper"), the hook implementation
| needs to execute exactly one ``yield``. The code before the
| ``yield`` is run early before any non-hook-wrapper function is run.
| The code after the ``yield`` is run after all non-hook-wrapper
| functions have run. The ``yield`` receives the result value of the
| inner calls, or raises the exception of inner calls (including
| earlier hook wrapper calls). The return value of the function
| becomes the return value of the hook, and a raised exception becomes
| the exception of the hook. See :ref:`hookwrapper`.
|
| :param hookwrapper:
| If ``True`` ("old-style hook wrapper"), the hook implementation
| needs to execute exactly one ``yield``. The code before the
| ``yield`` is run early before any non-hook-wrapper function is run.
| The code after the ``yield`` is run after all non-hook-wrapper
| function have run The ``yield`` receives a :class:`Result` object
| representing the exception or result outcome of the inner calls
| (including earlier hook wrapper calls). This option is mutually
| exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`.
|
| :param specname:
| If provided, the given name will be used instead of the function
| name when matching this hook implementation to a hook specification
| during registration. See :ref:`specname`.
|
| .. versionadded:: 1.2.0
| The ``wrapper`` parameter.
|
| __init__(self, project_name: 'str') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| project_name
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __final__ = True
pytest.hookspec
Python Library Documentation: HookspecMarker in module pluggy._hooks object class HookspecMarker(builtins.object) | HookspecMarker(project_name: 'str') -> 'None' | | Decorator for marking functions as hook specifications. | | Instantiate it with a project_name to get a decorator. | Calling :meth:`PluginManager.add_hookspecs` later will discover all marked | functions if the :class:`PluginManager` uses the same project name. | | Methods defined here: | | __call__(self, function: '_F | None' = None, firstresult: 'bool' = False, historic: 'bool' = False, warn_on_impl: 'Warning | None' = None, warn_on_impl_args: 'Mapping[str, Warning] | None' = None) -> '_F | Callable[[_F], _F]' | If passed a function, directly sets attributes on the function | which will make it discoverable to :meth:`PluginManager.add_hookspecs`. | | If passed no function, returns a decorator which can be applied to a | function later using the attributes supplied. | | :param firstresult: | If ``True``, the 1:N hook call (N being the number of registered | hook implementation functions) will stop at I<=N when the I'th | function returns a non-``None`` result. See :ref:`firstresult`. | | :param historic: | If ``True``, every call to the hook will be memorized and replayed | on plugins registered after the call was made. See :ref:`historic`. | | :param warn_on_impl: | If given, every implementation of this hook will trigger the given | warning. See :ref:`warn_on_impl`. | | :param warn_on_impl_args: | If given, every implementation of this hook which requests one of | the arguments in the dict will trigger the corresponding warning. | See :ref:`warn_on_impl`. | | .. versionadded:: 1.5 | | __init__(self, project_name: 'str') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | project_name | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __final__ = True
pytest.importorskip
Python Library Documentation: function importorskip in module _pytest.outcomes
importorskip(modname: 'str', minversion: 'str | None' = None, reason: 'str | None' = None, *, exc_type: 'type[ImportError] | None' = None) -> 'Any'
Import and return the requested module ``modname``, or skip the
current test if the module cannot be imported.
:param modname:
The name of the module to import.
:param minversion:
If given, the imported module's ``__version__`` attribute must be at
least this minimal version, otherwise the test is still skipped.
:param reason:
If given, this reason is shown as the message when the module cannot
be imported.
:param exc_type:
The exception that should be captured in order to skip modules.
Must be :py:class:`ImportError` or a subclass.
If the module can be imported but raises :class:`ImportError`, pytest will
issue a warning to the user, as often users expect the module not to be
found (which would raise :class:`ModuleNotFoundError` instead).
This warning can be suppressed by passing ``exc_type=ImportError`` explicitly.
See :ref:`import-or-skip-import-error` for details.
:returns:
The imported module. This should be assigned to its canonical name.
:raises pytest.skip.Exception:
If the module cannot be imported.
Example::
docutils = pytest.importorskip("docutils")
.. versionadded:: 8.2
The ``exc_type`` parameter.
pytest.main
Python Library Documentation: function main in module _pytest.config
main(args: 'list[str] | os.PathLike[str] | None' = None, plugins: 'Sequence[str | _PluggyPlugin] | None' = None) -> 'int | ExitCode'
Perform an in-process test run.
:param args:
List of command line arguments. If `None` or not given, defaults to reading
arguments directly from the process command line (:data:`sys.argv`).
:param plugins: List of plugin objects to be auto-registered during initialization.
:returns: An exit code.
pytest.mark
Python Library Documentation: MarkGenerator in module _pytest.mark.structures object
class MarkGenerator(builtins.object)
| MarkGenerator(*, _ispytest: 'bool' = False) -> 'None'
|
| Factory for :class:`MarkDecorator` objects - exposed as
| a ``pytest.mark`` singleton instance.
|
| Example::
|
| import pytest
|
|
| @pytest.mark.slowtest
| def test_function():
| pass
|
| applies a 'slowtest' :class:`Mark` on ``test_function``.
|
| Methods defined here:
|
| __getattr__(self, name: 'str') -> 'MarkDecorator'
| Generate a new :class:`MarkDecorator` with the given name.
|
| __init__(self, *, _ispytest: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __final__ = True
pytest.param
Python Library Documentation: function param in module _pytest.mark
param(*values: 'object', marks: 'MarkDecorator | Collection[MarkDecorator | Mark]' = (), id: 'str | None' = None) -> 'ParameterSet'
Specify a parameter in `pytest.mark.parametrize`_ calls or
:ref:`parametrized fixtures <fixture-parametrize-marks>`.
.. code-block:: python
@pytest.mark.parametrize(
"test_input,expected",
[
("3+5", 8),
pytest.param("6*9", 42, marks=pytest.mark.xfail),
],
)
def test_eval(test_input, expected):
assert eval(test_input) == expected
:param values: Variable args of the values of the parameter set, in order.
:param marks: A single mark or a list of marks to be applied to this parameter set.
:param id: The id to attribute to this parameter set.
pytest.raises
Python Library Documentation: function raises in module _pytest.python_api
raises(expected_exception: 'type[E] | tuple[type[E], ...]', *args: 'Any', **kwargs: 'Any') -> 'RaisesContext[E] | _pytest._code.ExceptionInfo[E]'
Assert that a code block/function call raises an exception type, or one of its subclasses.
:param expected_exception:
The expected exception type, or a tuple if one of multiple possible
exception types are expected. Note that subclasses of the passed exceptions
will also match.
:kwparam str | re.Pattern[str] | None match:
If specified, a string containing a regular expression,
or a regular expression object, that is tested against the string
representation of the exception and its :pep:`678` `__notes__`
using :func:`re.search`.
To match a literal string that may contain :ref:`special characters
<re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
(This is only used when ``pytest.raises`` is used as a context manager,
and passed through to the function otherwise.
When using ``pytest.raises`` as a function, you can use:
``pytest.raises(Exc, func, match="passed on").match("my pattern")``.)
Use ``pytest.raises`` as a context manager, which will capture the exception of the given
type, or any of its subclasses::
>>> import pytest
>>> with pytest.raises(ZeroDivisionError):
... 1/0
If the code block does not raise the expected exception (:class:`ZeroDivisionError` in the example
above), or no exception at all, the check will fail instead.
You can also use the keyword argument ``match`` to assert that the
exception matches a text or regex::
>>> with pytest.raises(ValueError, match='must be 0 or None'):
... raise ValueError("value must be 0 or None")
>>> with pytest.raises(ValueError, match=r'must be \d+$'):
... raise ValueError("value must be 42")
The ``match`` argument searches the formatted exception string, which includes any
`PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``:
>>> with pytest.raises(ValueError, match=r"had a note added"): # doctest: +SKIP
... e = ValueError("value must be 42")
... e.add_note("had a note added")
... raise e
The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the
details of the captured exception::
>>> with pytest.raises(ValueError) as exc_info:
... raise ValueError("value must be 42")
>>> assert exc_info.type is ValueError
>>> assert exc_info.value.args[0] == "value must be 42"
.. warning::
Given that ``pytest.raises`` matches subclasses, be wary of using it to match :class:`Exception` like this::
with pytest.raises(Exception): # Careful, this will catch ANY exception raised.
some_function()
Because :class:`Exception` is the base class of almost all exceptions, it is easy for this to hide
real bugs, where the user wrote this expecting a specific exception, but some other exception is being
raised due to a bug introduced during a refactoring.
Avoid using ``pytest.raises`` to catch :class:`Exception` unless certain that you really want to catch
**any** exception raised.
.. note::
When using ``pytest.raises`` as a context manager, it's worthwhile to
note that normal context manager rules apply and that the exception
raised *must* be the final line in the scope of the context manager.
Lines of code after that, within the scope of the context manager will
not be executed. For example::
>>> value = 15
>>> with pytest.raises(ValueError) as exc_info:
... if value > 10:
... raise ValueError("value must be <= 10")
... assert exc_info.type is ValueError # This will not execute.
Instead, the following approach must be taken (note the difference in
scope)::
>>> with pytest.raises(ValueError) as exc_info:
... if value > 10:
... raise ValueError("value must be <= 10")
...
>>> assert exc_info.type is ValueError
**Using with** ``pytest.mark.parametrize``
When using :ref:`pytest.mark.parametrize ref`
it is possible to parametrize tests such that
some runs raise an exception and others do not.
See :ref:`parametrizing_conditional_raising` for an example.
.. seealso::
:ref:`assertraises` for more examples and detailed discussion.
**Legacy form**
It is possible to specify a callable by passing a to-be-called lambda::
>>> raises(ZeroDivisionError, lambda: 1/0)
<ExceptionInfo ...>
or you can specify an arbitrary callable with arguments::
>>> def f(x): return 1/x
...
>>> raises(ZeroDivisionError, f, 0)
<ExceptionInfo ...>
>>> raises(ZeroDivisionError, f, x=0)
<ExceptionInfo ...>
The form above is fully supported but discouraged for new code because the
context manager form is regarded as more readable and less error-prone.
.. note::
Similar to caught exception objects in Python, explicitly clearing
local references to returned ``ExceptionInfo`` objects can
help the Python interpreter speed up its garbage collection.
Clearing those references breaks a reference cycle
(``ExceptionInfo`` --> caught exception --> frame stack raising
the exception --> current frame stack --> local variables -->
``ExceptionInfo``) which makes Python keep all objects referenced
from that cycle (including all local variables in the current
frame) alive until the next cyclic garbage collection run.
More detailed information can be found in the official Python
documentation for :ref:`the try statement <python:try>`.
pytest.register_assert_rewrite
Python Library Documentation: function register_assert_rewrite in module _pytest.assertion
register_assert_rewrite(*names: 'str') -> 'None'
Register one or more module names to be rewritten on import.
This function will make sure that this module or all modules inside
the package will get their assert statements rewritten.
Thus you should make sure to call this before the module is
actually imported, usually in your __init__.py if you are a plugin
using a package.
:param names: The module names to register.
pytest.set_trace
Python Library Documentation: method set_trace in module _pytest.debugging
set_trace(*args, **kwargs) -> 'None' class method of _pytest.debugging.pytestPDB
Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.
pytest.skip
Python Library Documentation: function skip in module _pytest.outcomes
skip(reason: 'str' = '', *, allow_module_level: 'bool' = False) -> 'NoReturn'
Skip an executing test with the given message.
This function should be called only during testing (setup, call or teardown) or
during collection by using the ``allow_module_level`` flag. This function can
be called in doctests as well.
:param reason:
The message to show the user as reason for the skip.
:param allow_module_level:
Allows this function to be called at module level.
Raising the skip exception at module level will stop
the execution of the module and prevent the collection of all tests in the module,
even those defined before the `skip` call.
Defaults to False.
:raises pytest.skip.Exception:
The exception that is raised.
.. note::
It is better to use the :ref:`pytest.mark.skipif ref` marker when
possible to declare a test to be skipped under certain conditions
like mismatching platforms or dependencies.
Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`)
to skip a doctest statically.
pytest.version_tuple
Python Library Documentation: tuple object class tuple(object) | tuple(iterable=(), /) | | Built-in immutable sequence. | | If no argument is given, the constructor returns an empty tuple. | If iterable is specified the tuple is initialized from iterable's items. | | If the argument is a tuple, the return value is the same object. | | Built-in subclasses: | asyncgen_hooks | UnraisableHookArgs | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return bool(key in self). | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return value*self. | | count(self, value, /) | Return number of occurrences of value. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | See PEP 585 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.
pytest.warns
Python Library Documentation: function warns in module _pytest.recwarn
warns(expected_warning: 'type[Warning] | tuple[type[Warning], ...]' = <class 'Warning'>, *args: 'Any', match: 'str | Pattern[str] | None' = None, **kwargs: 'Any') -> 'WarningsChecker | Any'
Assert that code raises a particular class of warning.
Specifically, the parameter ``expected_warning`` can be a warning class or tuple
of warning classes, and the code inside the ``with`` block must issue at least one
warning of that class or classes.
This helper produces a list of :class:`warnings.WarningMessage` objects, one for
each warning emitted (regardless of whether it is an ``expected_warning`` or not).
Since pytest 8.0, unmatched warnings are also re-emitted when the context closes.
This function can be used as a context manager::
>>> import pytest
>>> with pytest.warns(RuntimeWarning):
... warnings.warn("my warning", RuntimeWarning)
In the context manager form you may use the keyword argument ``match`` to assert
that the warning matches a text or regex::
>>> with pytest.warns(UserWarning, match='must be 0 or None'):
... warnings.warn("value must be 0 or None", UserWarning)
>>> with pytest.warns(UserWarning, match=r'must be \d+$'):
... warnings.warn("value must be 42", UserWarning)
>>> with pytest.warns(UserWarning): # catch re-emitted warning
... with pytest.warns(UserWarning, match=r'must be \d+$'):
... warnings.warn("this is not here", UserWarning)
Traceback (most recent call last):
...
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
**Using with** ``pytest.mark.parametrize``
When using :ref:`pytest.mark.parametrize ref` it is possible to parametrize tests
such that some runs raise a warning and others do not.
This could be achieved in the same way as with exceptions, see
:ref:`parametrizing_conditional_raising` for an example.
pytest.xfail
Python Library Documentation: function xfail in module _pytest.outcomes
xfail(reason: 'str' = '') -> 'NoReturn'
Imperatively xfail an executing test or setup function with the given reason.
This function should be called only during testing (setup, call or teardown).
No other code is executed after using ``xfail()`` (it is implemented
internally by raising an exception).
:param reason:
The message to show the user as reason for the xfail.
.. note::
It is better to use the :ref:`pytest.mark.xfail ref` marker when
possible to declare a test to be xfailed under certain conditions
like known bugs or missing features.
:raises pytest.xfail.Exception:
The exception that is raised.
pytest.yield_fixture
Python Library Documentation: function yield_fixture in module _pytest.fixtures
yield_fixture(fixture_function=None, *args, scope='function', params=None, autouse=False, ids=None, name=None)
(Return a) decorator to mark a yield-fixture factory function.
.. deprecated:: 3.0
Use :py:func:`pytest.fixture` directly instead.