_pytest.python module

Python test discovery, setup and run of test functions.

pyobj_property(name)[source]
pytest_addoption(parser)[source]
pytest_cmdline_main(config)[source]
pytest_generate_tests(metafunc: _pytest.python.Metafunc)None[source]
pytest_configure(config)[source]
async_warn(pyfuncitem: _pytest.python.Function)None[source]
pytest_pyfunc_call(pyfuncitem: _pytest.python.Function)[source]
pytest_collect_file(path, parent)[source]
path_matches_patterns(path, patterns)[source]

Returns True if the given py.path.local matches one of the patterns in the list of globs given

pytest_pycollect_makemodule(path, parent)[source]
for ... in pytest_pycollect_makeitem(collector, name, obj)[source]
class PyobjContext[source]

Bases: object

module

python module object this node was collected from (can be None).

cls

python class object this node was collected from (can be None).

instance

python instance object this node was collected from (can be None).

class PyobjMixin[source]

Bases: _pytest.python.PyobjContext

_ALLOW_MARKERS = True
obj

Underlying Python object.

_getobj()[source]

Gets the underlying Python object. May be overwritten by subclasses.

getmodpath(stopatmodule=True, includemodule=False)[source]

return python path relative to the containing module.

reportinfo() → Tuple[Union[py._path.local.LocalPath, str], int, str][source]
class PyCollector(*k, **kw)[source]

Bases: _pytest.python.PyobjMixin, _pytest.nodes.Collector

funcnamefilter(name)[source]
isnosetest(obj)[source]

Look for the __test__ attribute, which is applied by the @nose.tools.istest decorator

classnamefilter(name)[source]
istestfunction(obj, name)[source]
istestclass(obj, name)[source]
_matches_prefix_or_glob_option(option_name, name)[source]

checks if the given name matches the prefix or glob-pattern defined in ini configuration.

collect()[source]

returns a list of children (items and collectors) for this collection node.

_makeitem(name, obj)[source]
for ... in _genfunctions(name, funcobj)[source]
class Module(*k, **kw)[source]

Bases: _pytest.nodes.File, _pytest.python.PyCollector

Collector for test classes and functions.

_getobj()[source]

Gets the underlying Python object. May be overwritten by subclasses.

collect()[source]

returns a list of children (items and collectors) for this collection node.

_inject_setup_module_fixture()[source]

Injects a hidden autouse, module scoped fixture into the collected module object that invokes setUpModule/tearDownModule if either or both are available.

Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with other fixtures (#517).

_inject_setup_function_fixture()[source]

Injects a hidden autouse, function scoped fixture into the collected module object that invokes setup_function/teardown_function if either or both are available.

Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with other fixtures (#517).

_importtestmodule() → module[source]
class Package(*k, **kw)[source]

Bases: _pytest.python.Module

setup()[source]
gethookproxy(fspath: py._path.local.LocalPath)[source]
isinitpath(path)[source]
for ... in collect()[source]

returns a list of children (items and collectors) for this collection node.

_call_with_optional_argument(func, arg)[source]

Call the given function with the given argument if func accepts one argument, otherwise calls func without arguments

_get_first_non_fixture_func(obj, names)[source]

Return the attribute from the given object to be used as a setup/teardown xunit-style function, but only if not marked as a fixture to avoid calling it twice.

class Class(*k, **kw)[source]

Bases: _pytest.python.PyCollector

Collector for test methods.

classmethod from_parent(parent, *, name, obj=None)[source]

The public constructor

collect()[source]

returns a list of children (items and collectors) for this collection node.

_inject_setup_class_fixture()[source]

Injects a hidden autouse, class scoped fixture into the collected class object that invokes setup_class/teardown_class if either or both are available.

Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with other fixtures (#517).

_inject_setup_method_fixture()[source]

Injects a hidden autouse, function scoped fixture into the collected class object that invokes setup_method/teardown_method if either or both are available.

Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with other fixtures (#517).

class Instance(*k, **kw)[source]

Bases: _pytest.python.PyCollector

_ALLOW_MARKERS = False
_getobj()[source]

Gets the underlying Python object. May be overwritten by subclasses.

collect()[source]

returns a list of children (items and collectors) for this collection node.

newinstance()[source]
hasinit(obj)[source]
hasnew(obj)[source]
class CallSpec2(metafunc)[source]

Bases: object

copy()[source]
_checkargnotcontained(arg)[source]
getparam(name)[source]
id
setmulti2(valtypes, argnames, valset, id, marks, scopenum, param_index)[source]
class Metafunc(definition: _pytest.python.FunctionDefinition, fixtureinfo: _pytest.fixtures.FuncFixtureInfo, config: _pytest.config.Config, cls=None, module=None)[source]

Bases: object

Metafunc objects are passed to the 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.

config

access to the _pytest.config.Config object for the test session

module

the module object where the test function is defined in.

function

underlying python test function

fixturenames

set of fixture names required by the test function

cls

class object where the test function is defined in or None.

funcargnames

alias attribute for fixturenames for pre-2.3 compatibility

parametrize(argnames: Union[str, List[str], Tuple[str, …]], argvalues: Iterable[Union[_pytest.mark.structures.ParameterSet, Sequence[object], object]], indirect: Union[bool, Sequence[str]] = False, ids: Optional[Union[Iterable[Union[None, str, float, int, bool]], Callable[[object], Optional[object]]]] = None, scope: Optional[str] = None, *, _param_mark: Optional[_pytest.mark.structures.Mark] = None)None[source]

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 at test setup time.

Parameters
  • argnames – a comma-separated string denoting one or more argument names, or a list/tuple of argument strings.

  • 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.

  • indirect – The list of argnames or boolean. A list of arguments’ names (subset of argnames). 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.

  • 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.

  • 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.

_resolve_arg_ids(argnames: Sequence[str], ids: Optional[Union[Iterable[Union[None, str, float, int, bool]], Callable[[object], Optional[object]]]], parameters: Sequence[_pytest.mark.structures.ParameterSet], item) → List[str][source]

Resolves the actual ids for the given argnames, based on the ids parameter given to parametrize.

Parameters
  • argnames (List[str]) – list of argument names passed to parametrize().

  • ids – the ids parameter of the parametrized call (see docs).

  • parameters (List[ParameterSet]) – the list of parameter values, same size as argnames.

  • item (Item) – the item that generated this parametrized call.

Return type

List[str]

Returns

the list of ids for each argname given

_validate_ids(ids: Iterable[Union[None, str, float, int, bool]], parameters: Sequence[_pytest.mark.structures.ParameterSet], func_name: str) → List[Union[None, str]][source]
_resolve_arg_value_types(argnames: Sequence[str], indirect: Union[bool, Sequence[str]]) → Dict[str, str][source]

Resolves if each parametrized argument must be considered a parameter to a fixture or a “funcarg” to the function, based on the indirect parameter of the parametrized() call.

Parameters
  • argnames (List[str]) – list of argument names passed to parametrize().

  • indirect – same indirect parameter of parametrize().

Return type

Dict[str, str] A dict mapping each arg name to either: * “params” if the argname should be the parameter of a fixture of the same name. * “funcargs” if the argname should be a parameter to the parametrized test function.

_validate_if_using_arg_names(argnames: Sequence[str], indirect: Union[bool, Sequence[str]])None[source]

Check if all argnames are being used, by default values, or directly/indirectly.

Parameters
  • argnames (List[str]) – list of argument names passed to parametrize().

  • indirect – same indirect parameter of parametrize().

Raises

ValueError – if validation fails.

_validate_explicit_parameters(argnames: Sequence[str], indirect: Union[bool, Sequence[str]])None[source]

The argnames in parametrize should either be declared explicitly via indirect list or in the function signature

Parameters
  • argnames (List[str]) – list of argument names passed to parametrize().

  • indirect – same indirect parameter of parametrize().

Raises

ValueError – if validation fails

_find_parametrized_scope(argnames, arg2fixturedefs, indirect)[source]

Find the most appropriate scope for a parametrized call based on its arguments.

When there’s at least one direct argument, always use “function” scope.

When a test function is parametrized and all its arguments are indirect (e.g. fixtures), return the most narrow scope based on the fixtures used.

Related to issue #1832, based on code posted by @Kingdread.

_ascii_escaped_by_config(val: Union[str, bytes], config: Optional[_pytest.config.Config])str[source]
_idval(val: object, argname: str, idx: int, idfn: Optional[Callable[[object], Optional[object]]], item, config: Optional[_pytest.config.Config])str[source]
_idvalset(idx: int, parameterset: _pytest.mark.structures.ParameterSet, argnames: Iterable[str], idfn: Optional[Callable[[object], Optional[object]]], ids: Optional[List[Union[None, str]]], item, config: Optional[_pytest.config.Config])[source]
idmaker(argnames: Iterable[str], parametersets: Iterable[_pytest.mark.structures.ParameterSet], idfn: Optional[Callable[[object], Optional[object]]] = None, ids: Optional[List[Union[None, str]]] = None, config: Optional[_pytest.config.Config] = None, item=None) → List[str][source]
show_fixtures_per_test(config)[source]
_show_fixtures_per_test(config, session)[source]
showfixtures(config)[source]
_showfixtures_main(config, session)[source]
write_docstring(tw: _pytest._io.TerminalWriter, doc: str, indent: str = ' ')None[source]
class Function(*k, **kw)[source]

Bases: _pytest.python.PyobjMixin, _pytest.nodes.Item

a Function Item is responsible for setting up and executing a Python test function.

_ALLOW_MARKERS = False
originalname

original function name, without any decorations (for example parametrization adds a "[...]" suffix to function names).

New in version 3.0.

classmethod from_parent(parent, **kw)[source]

The public constructor

_initrequest()[source]
function

underlying python ‘function’ object

_getobj()[source]

Gets the underlying Python object. May be overwritten by subclasses.

_pyfuncitem

(compatonly) for code expecting pytest-2.2 style request objects

funcargnames

alias attribute for fixturenames for pre-2.3 compatibility

runtest()None[source]

execute the underlying test function.

setup()None[source]
_prunetraceback(excinfo: _pytest._code.code.ExceptionInfo)None[source]
repr_failure(excinfo, outerr=None)[source]
class FunctionDefinition(*k, **kw)[source]

Bases: _pytest.python.Function

internal hack until we get actual definition nodes instead of the crappy metafunc hack

runtest()None[source]

execute the underlying test function.

setup()None

execute the underlying test function.