_pytest.fixtures module

class PseudoFixtureDef(cached_result, scope)[source]

Bases: object

pytest_sessionstart(session: Session)[source]
scopeproperty(name=None, doc=None)[source]
get_scope_package(node, fixturedef)[source]
get_scope_node(node, scope)[source]
add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager)[source]
getfixturemarker(obj)[source]

return fixturemarker or None if it doesn’t exist or raised exceptions.

for ... in get_parametrized_fixture_keys(item, scopenum)[source]

return list of keys for all parametrized arguments which match the specified scope.

reorder_items(items)[source]
fix_cache_order(item, argkeys_cache, items_by_argkey)[source]
reorder_items_atscope(items, argkeys_cache, items_by_argkey, scopenum)[source]
fillfixtures(function)[source]

fill missing funcargs for a test function.

get_direct_param_fixture_func(request)[source]
class FuncFixtureInfo(argnames: tuple, initialnames: tuple, names_closure, name2fixturedefs)[source]

Bases: object

argnames
initialnames
names_closure
name2fixturedefs
prune_dependency_tree()[source]

Recompute names_closure from initialnames and name2fixturedefs

Can only reduce names_closure, which means that the new closure will always be a subset of the old one. The order is preserved.

This method is needed because direct parametrization may shadow some of the fixtures that were included in the originally built dependency tree. In this way the dependency tree can get pruned, and the closure of argnames may get reduced.

class FixtureRequest(pyfuncitem)[source]

Bases: object

A request for a fixture from a test or fixture function.

A request object gives access to the requesting test context and has an optional param attribute in case the fixture is parametrized indirectly.

fixturename

fixture for which this request is being performed

scope

Scope string, one of “function”, “class”, “module”, “session”

fixturenames

names of all active fixtures in this request

funcargnames

alias attribute for fixturenames for pre-2.3 compatibility

node

underlying collection node (depends on current request scope)

_getnextfixturedef(argname)[source]
config

the pytest config object associated with this request.

function

test function object if the request has a per-function scope.

cls

class (can be None) where the test function was collected.

instance

instance (can be None) on which test function was collected.

module

python module object where the test function was collected.

fspath

the file system path of the test module which collected this test.

keywords

keywords/markers dictionary for the underlying node.

session

pytest session object.

addfinalizer(finalizer)[source]

add finalizer/teardown function to be called after the last test within the requesting test context finished execution.

_addfinalizer(finalizer, scope)[source]
applymarker(marker)[source]

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.

Parameters

marker – a _pytest.mark.MarkDecorator object created by a call to pytest.mark.NAME(...).

raiseerror(msg)[source]

raise a FixtureLookupError with the given message.

_fillfixtures()[source]
getfixturevalue(argname)[source]

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.

_get_active_fixturedef(argname)[source]
_get_fixturestack()[source]
_compute_fixture_value(fixturedef: _pytest.fixtures.FixtureDef)None[source]

Creates a SubRequest based on “self” and calls the execute method of the given fixturedef object. This will force the FixtureDef object to throw away any previous results and compute a new fixture value, which will be stored into the FixtureDef object itself.

_schedule_finalizers(fixturedef, subrequest)[source]
_check_scope(argname, invoking_scope, requested_scope)[source]
_factorytraceback()[source]
_getscopeitem(scope)[source]
class SubRequest(request: FixtureRequest, scope: _Scope, param, param_index: int, fixturedef: FixtureDef)[source]

Bases: _pytest.fixtures.FixtureRequest

a sub request for handling getting a fixture from a test function/fixture.

_phase
addfinalizer(finalizer)[source]

add finalizer/teardown function to be called after the last test within the requesting test context finished execution.

_schedule_finalizers(fixturedef, subrequest)[source]
scopemismatch(currentscope, newscope)[source]
scope2index(scope, descr, where=None)[source]

Look up the index of scope and raise a descriptive value error if not defined.

exception FixtureLookupError(argname, request, msg=None)[source]

Bases: LookupError

could not return a requested Fixture (missing or invalid).

formatrepr()_pytest.fixtures.FixtureLookupErrorRepr[source]
class FixtureLookupErrorRepr(filename, firstlineno, tblines, errorstring, argname)[source]

Bases: _pytest._code.code.TerminalRepr

toterminal(tw: _pytest._io.TerminalWriter)None[source]
fail_fixturefunc(fixturefunc, msg)[source]
call_fixture_func(fixturefunc, request, kwargs)[source]
_teardown_yield_fixture(fixturefunc, it)[source]

Executes the teardown of a fixture function by advancing the iterator after the yield and ensure the iteration ends (if not it means there is more than one yield in the function)

_eval_scope_callable(scope_callable, fixture_name, config)[source]
class FixtureDef(fixturemanager, baseid, argname, func, scope, params, unittest=False, ids=None)[source]

Bases: object

A container for a factory definition.

addfinalizer(finalizer)[source]
finish(request)[source]
execute(request)[source]
cache_key(request)[source]
resolve_fixture_function(fixturedef, request)[source]

Gets the actual callable that can be called to obtain the fixture value, dealing with unittest-specific instances and bound methods.

pytest_fixture_setup(fixturedef, request)[source]

Execution of fixture setup.

_ensure_immutable_ids(ids)[source]
wrap_function_to_error_out_if_called_directly(function, fixture_marker)[source]

Wrap the given fixture function so we can raise an error about it being called directly, instead of used as an argument in a test function.

class FixtureFunctionMarker(scope, params, autouse=False, ids=None, name=None)[source]

Bases: object

_parse_fixture_args(callable_or_scope, *args, **kwargs)[source]
fixture(callable_or_scope=None, *args, scope='function', params=None, autouse=False, ids=None, name=None)[source]

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.

Parameters
  • scope

    the scope for which this fixture is shared, one of "function" (default), "class", "module", "package" or "session" ("package" is considered experimental at this time).

    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 dynamic scope in the docs for more information.

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

  • autouse – if True, the fixture func is activated for all tests that can see it. If False (the default) then an explicit reference is needed to activate the fixture.

  • ids – list of string 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.

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

yield_fixture(callable_or_scope=None, *args, scope='function', params=None, autouse=False, ids=None, name=None)[source]

(return a) decorator to mark a yield-fixture factory function.

Deprecated since version 3.0: Use pytest.fixture() directly instead.

pytestconfig(request)[source]

Session-scoped fixture that returns the _pytest.config.Config object.

Example:

def test_foo(pytestconfig):
    if pytestconfig.getoption("verbose") > 0:
        ...
pytest_addoption(parser)[source]
class FixtureManager(session)[source]

Bases: object

pytest fixtures definitions and information is stored and managed from this class.

During collection fm.parsefactories() is called multiple times to parse fixture function definitions into FixtureDef objects and internal data structures.

During collection of test functions, metafunc-mechanics instantiate a FuncFixtureInfo object which is cached per node/func-name. This FuncFixtureInfo object is later retrieved by Function nodes which themselves offer a fixturenames attribute.

The FuncFixtureInfo object holds information about fixtures and FixtureDefs relevant for a particular function. An initial list of fixtures is assembled like this:

  • ini-defined usefixtures

  • autouse-marked fixtures along the collection chain up from the function

  • usefixtures markers at module/class/function level

  • test function funcargs

Subsequently the funcfixtureinfo.fixturenames attribute is computed as the closure of the fixtures needed to setup the initial fixtures, i. e. fixtures needed by fixture functions themselves are appended to the fixturenames list.

Upon the test-setup phases all fixturenames are instantiated, retrieved by a lookup of their FuncFixtureInfo.

exception FixtureLookupError(argname, request, msg=None)

Bases: LookupError

could not return a requested Fixture (missing or invalid).

formatrepr()_pytest.fixtures.FixtureLookupErrorRepr
class FixtureLookupErrorRepr(filename, firstlineno, tblines, errorstring, argname)

Bases: _pytest._code.code.TerminalRepr

toterminal(tw: _pytest._io.TerminalWriter)None
_get_direct_parametrize_args(node)[source]

This function returns all the direct parametrization arguments of a node, so we don’t mistake them for fixtures

Check https://github.com/pytest-dev/pytest/issues/5036

This things are done later as well when dealing with parametrization so this could be improved

getfixtureinfo(node, func, cls, funcargs=True)[source]
pytest_plugin_registered(plugin)[source]
_getautousenames(nodeid)[source]

return a tuple of fixture names to be used.

getfixtureclosure(fixturenames, parentnode, ignore_args=())[source]
pytest_generate_tests(metafunc)[source]
pytest_collection_modifyitems(items)[source]
parsefactories(node_or_obj, nodeid=<object object>, unittest=False)[source]
getfixturedefs(argname, nodeid)[source]

Gets a list of fixtures which are applicable to the given node id.

Parameters
  • argname (str) – name of the fixture to search for

  • nodeid (str) – full node id of the requesting test.

Returns

list[FixtureDef]

for ... in _matchfactories(fixturedefs, nodeid)[source]
get_use_fixtures_for_node(node) → Tuple[str, …][source]

Returns the names of all the usefixtures() marks on the given node