Fixtures โ
Tutorial: Fixtures reference
Fixtures are requested by test functions or other fixtures by declaring them as argument names.
Example of a test requiring a fixture:
def test_output(capsys):
print("hello")
out, err = capsys.readouterr()
assert out == "hello\n"def test_output(capsys):
print("hello")
out, err = capsys.readouterr()
assert out == "hello\n"Example of a fixture requiring another fixture:
@pytest.fixture
def db_session(tmp_path):
fn = tmp_path / "db.file"
return connect(fn)@pytest.fixture
def db_session(tmp_path):
fn = tmp_path / "db.file"
return connect(fn)For more details, consult the full fixtures docs.
@pytest.fixture โ
@fixture(
fixture_function: FixtureFunction, *, scope: Union[Literal['session', 'package', 'module', 'class', 'function'], Callable[[str, Config], Literal['session', 'package', 'module', 'class', 'function']]] = 'function', params: Optional[Iterable[object]] = None, autouse: bool = False, ids: Optional[Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]] = None, name: Optional[str] = None) โFixtureFunctionโ@fixture(
fixture_function: None = None, *, scope: Union[Literal['session', 'package', 'module', 'class', 'function'], Callable[[str, Config], Literal['session', 'package', 'module', 'class', 'function']]] = 'function', params: Optional[Iterable[object]] = None, autouse: bool = False, ids: Optional[Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]] = None, name: Optional[str] = None) โFixtureFunctionMarkerโ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
returnoryieldstatements. When usingyieldthe code block after theyieldstatement 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". 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 inrequest.param.autouseโ IfTrue, the fixture func is activated for all tests that can see it. IfFalse(the default), an explicit reference is needed to activate the fixture.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.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 functionfixture_<fixturename>and then use@pytest.fixture(name='<fixturename>').
capfd โ
Tutorial: How to capture stdout/stderr output
capfd() โ
Enable text capturing of writes to file descriptors
1and2.The captured output is made available via
capfd.readouterr()method calls, which return a(out, err)namedtuple.outanderrwill betextobjects.Returns an instance of
CaptureFixture[str].Example:
pythondef test_system_echo(capfd): os.system('echo "hello"') captured = capfd.readouterr() assert captured.out == "hello\n"def test_system_echo(capfd): os.system('echo "hello"') captured = capfd.readouterr() assert captured.out == "hello\n"
capfdbinary โ
Tutorial: How to capture stdout/stderr output
capfdbinary() โ
Enable bytes capturing of writes to file descriptors
1and2.The captured output is made available via
capfd.readouterr()method calls, which return a(out, err)namedtuple.outanderrwill bebyteobjects.Returns an instance of
CaptureFixture[bytes].Example:
pythondef test_system_echo(capfdbinary): os.system('echo "hello"') captured = capfdbinary.readouterr() assert captured.out == b"hello\n"def test_system_echo(capfdbinary): os.system('echo "hello"') captured = capfdbinary.readouterr() assert captured.out == b"hello\n"
caplog โ
Tutorial: How to manage logging
caplog() โ
Access and control log capturing.
Captured logs are available through the following properties/methods:
shell* caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string* caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output stringReturns a
pytest.LogCaptureFixtureinstance.final classLogCaptureFixture โProvides access and control of log capturing.
propertyhandler:LogCaptureHandlerGet the logging handler used by the fixture.
get_records(
when)Get the logging records for one of the possible test phases.
Parameters:
when (Literal['setup', 'call', 'teardown'])โ 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.
Return type:
List[LogRecord]New in version 3.4.
propertytext:strThe formatted log text.
propertyrecords:List[LogRecord]The list of log records.
propertyrecord_tuples:List[Tuple[str, int, str]]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)propertymessages:List[str]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
logging.exception()or theexc_infoorstack_infoarguments to the logging functions) is not included, as this is added by the formatter in the handler.New in version 3.7.
clear()
Reset the list of log records and the captured log text.
set_level(
level, logger=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.
Changed in version 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
logging.disable().Parameters:
level (Union[int, str])โ The level.logger (Optional[str])โ The logger to update. If not given, the root logger.
withat_level(level, logger=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
logging.disable().Parameters:
level (Union[int, str])โ The level.logger (Optional[str])โ The logger to update. If not given, the root logger.
capsys โ
Tutorial: How to capture stdout/stderr output
capsys() โ
Enable text capturing of writes to
sys.stdoutandsys.stderr.The captured output is made available via
capsys.readouterr()method calls, which return a(out, err)namedtuple.outanderrwill betextobjects.Returns an instance of
CaptureFixture[str].Example:
pythondef test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n"def test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n"classCaptureFixture โObject returned by the
capsys,capsysbinary,capfdandcapfdbinaryfixtures.readouterr()
Read and return the captured output so far, resetting the internal buffer.
Returns: The captured content as a namedtuple with
outanderrstring attributes.Return type:
CaptureResultwithdisabled()Temporarily disable capturing while inside the
withblock.
capsysbinary โ
Tutorial: How to capture stdout/stderr output
capsysbinary() โ
Enable bytes capturing of writes to
sys.stdoutandsys.stderr.The captured output is made available via
capsysbinary.readouterr()method calls, which return a(out, err)namedtuple.outanderrwill bebytesobjects.Returns an instance of
CaptureFixture[bytes].Example:
pythondef test_output(capsysbinary): print("hello") captured = capsysbinary.readouterr() assert captured.out == b"hello\n"def test_output(capsysbinary): print("hello") captured = capsysbinary.readouterr() assert captured.out == b"hello\n"
config.cache โ
Tutorial: How to re-run failed tests and maintain state between test runs
The config.cache object allows other plugins and fixtures to store and retrieve values across test runs. To access it from fixtures request pytestconfig into your fixture and get it with pytestconfig.cache.
Under the hood, the cache plugin uses the simple dumps/loads API of the json stdlib module.
config.cache is an instance of pytest.Cache:
final classCache โInstance of the
cachefixture.mkdir(
name)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.
New in version 7.0.
Parameters:
name (str)โ 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.
get(
key, 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.
Parameters:
key (str)โ Must be a/separated value. Usually the first name is the name of your plugin or your application.defaultโ The value to return in case of a cache-miss or invalid cache value.
set(
key, value)Save value for the given key.
Parameters:
key (str)โ Must be a / separated value. Usually the first name is the name of your plugin or your application.value (object)โ Must be of any combination of basic python types, including nested types like lists of dictionaries.
doctest_namespace โ
Tutorial: How to run doctests
doctest_namespace() โ
Fixture that returns a
dictthat will be injected into the namespace of doctests.Usually this fixture is used in conjunction with another
autousefixture:python@pytest.fixture(autouse=True) def add_np(doctest_namespace): doctest_namespace["np"] = numpy@pytest.fixture(autouse=True) def add_np(doctest_namespace): doctest_namespace["np"] = numpyFor more details: โdoctest_namespaceโ fixture.
monkeypatch โ
Tutorial: How to monkeypatch/mock modules and environments
monkeypatch() โ
A convenient fixture for monkey-patching.
The fixture provides these methods to modify objects, dictionaries, or
os.environ:monkeypatch.setattr(obj, name, value, raising=True)monkeypatch.delattr(obj, name, raising=True)monkeypatch.setitem(mapping, name, value)monkeypatch.delitem(obj, name, raising=True)monkeypatch.setenv(name, value, prepend=None)monkeypatch.delenv(name, raising=True)monkeypatch.syspath_prepend(path)monkeypatch.chdir(path)monkeypatch.context()
All modifications will be undone after the requesting test function or fixture has finished. The
raisingparameter determines if aKeyErrororAttributeErrorwill be raised if the set/deletion operation does not have the specified target.To undo modifications done by the fixture in a contained scope, use
context().Returns a
MonkeyPatchinstance.final classMonkeyPatch โHelper to conveniently monkeypatch attributes/items/environment variables/syspath.
Returned by the
monkeypatchfixture.Changed in version 6.2: Can now also be used directly as
pytest.MonkeyPatch(), for when the fixture is not available. In this case, usewith MonkeyPatch.context() as mp: or remember to callundo()explicitly.classmethod withcontext()Context manager that returns a new
MonkeyPatchobject which undoes any patching done inside thewithblock upon exit.Example:
pythonimport functools def test_partial(monkeypatch): with monkeypatch.context() as m: m.setattr(functools, "partial", 3)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
stdlibfunctions that might break pytest itself if mocked (for examples of this see issue #3290).setattr(
target: str, name: object, value: ~_pytest.monkeypatch.Notset = <notset>, raising: bool = True) โNonesetattr(
target: object, name: str, value: object, raising: bool = True) โNoneSet attribute value on target, memorizing the old value.
For example:
pythonimport os monkeypatch.setattr(os, "getcwd", lambda: "/")import os monkeypatch.setattr(os, "getcwd", lambda: "/")The code above replaces the
os.getcwd()function by alambdawhich always returns"/".For convenience, you can specify a string as
targetwhich will be interpreted as a dotted import path, with the last part being the attribute name:pythonmonkeypatch.setattr("os.getcwd", lambda: "/")monkeypatch.setattr("os.getcwd", lambda: "/")Raises
AttributeErrorif the attribute does not exist, unlessraisingis set to False.Where to patch
monkeypatch.setattrworks 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 Where to patch in the
unittest.mockdocs for a complete explanation, which is meant forunittest.mock.patch()but applies tomonkeypatch.setattras well.delattr(
target, name=<notset>, raising=True)Delete attribute
namefromtarget.If no
nameis specified andtargetis 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
raisingis set to False.setitem(
dic, name, value)Set dictionary entry
nameto value.delitem(
dic, name, raising=True)Delete
namefrom dict.Raises
KeyErrorif it doesnโt exist, unlessraisingis set to False.setenv(
name, value, prepend=None)Set environment variable
nametovalue.If
prependis a character, read the current environment variable value and prepend thevalueadjoined with theprependcharacter.delenv(
name, raising=True)Delete
namefrom the environment.Raises
KeyErrorif it does not exist, unlessraisingis set to False.syspath_prepend(
path)Prepend
pathtosys.pathlist of import locations.chdir(
path)Change the current working directory to the specified path.
Parameters:
path (Union[str, PathLike[str]])โ The path to change into.
undo()
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
monkeypatchfixture is used across a single test function invocation. Ifmonkeypatchis used both by the test function itself and one of the test fixtures, callingundo()will undo all of the changes made in both functions.Prefer to use
context()instead.
pytestconfig โ
pytestconfig() โ
Session-scoped fixture that returns the sessionโs
pytest.Configobject.Example:
pythondef test_foo(pytestconfig): if pytestconfig.getoption("verbose") > 0: ...def test_foo(pytestconfig): if pytestconfig.getoption("verbose") > 0: ...
pytester โ
New in version 6.2.
Provides a Pytester instance that can be used to run and test pytest itself.
It provides an empty directory where pytest can be executed in isolation, and contains facilities to write tests, configuration files, and match against expected output.
To use it, include in your topmost conftest.py file:
pytest_plugins = "pytester"pytest_plugins = "pytester"final classPytester โ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
pathand environment variables during initialization.exceptionTimeoutExpiredplugins:
List[Union[str, object]]A list of plugins to use with
parseconfig()andrunpytest(). Initially this is an empty list but plugins can be added to the list. The type of items to add to the list depends on the method using them so refer to them for details.propertypath:PathTemporary directory path used to create files/run tests from, etc.
make_hook_recorder(
pluginmanager)Create a new
HookRecorderfor aPytestPluginManager.chdir()
Cd into the temporary directory.
This is done automatically upon instantiation.
makefile(
ext, *args, **kwargs)Create new text file(s) in the test directory.
Parameters:
ext (str)โ The extension the file(s) should use, including the dot, e.g..py.args (str)โ 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.kwargs (str)โ 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.
Return type:
PathExamples:
pythonpytester.makefile(".txt", "line1", "line2") pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")pytester.makefile(".txt", "line1", "line2") pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")To create binary files, use
pathlib.Path.write_bytes()directly:pythonfilename = pytester.path.joinpath("foo.bin") filename.write_bytes(b"...")filename = pytester.path.joinpath("foo.bin") filename.write_bytes(b"...")makeconftest(
source)Write a contest.py file.
Parameters:
source (str)โ The contents.
Returns: The
conftest.pyfile.Return type:
Pathmakeini(
source)Write a
tox.inifile.Parameters:
source (str)โ The contents.
Returns: The
tox.inifile.Return type:
Pathgetinicfg(
source)Return the pytest section from the
tox.iniconfig file.makepyprojecttoml(
source)Write a
pyproject.tomlfile.Parameters:
source (str)โ The contents.
Returns: The
pyproject.inifile.Return type:
PathNew in version 6.0.
makepyfile(
*args, **kwargs)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:
pythondef 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.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.maketxtfile(
*args, **kwargs)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:
pythondef 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.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.syspathinsert(
path=None)Prepend a directory to sys.path, defaults to
path.This is undone automatically when this object dies at the end of each test.
Parameters:
path (Optional[Union[str, PathLike[str]]])โ The path.
mkdir(
name)Create a new (sub)directory.
Parameters:
name (Union[str, PathLike[str]])โ The name of the directory, relative to the pytester path.
Returns: The created directory.
Return type:
Pathmkpydir(
name)Create a new python package.
This creates a (sub)directory with an empty
__init__.pyfile so it gets recognised as a Python package.copy_example(
name=None)Copy file from projectโs directory into the
testdir.Parameters:
name (Optional[str])โ The name of the file to copy.
Returns: Path to the copied directory (inside
self.path).Return type:
Pathgetnode(
config, arg)Get the collection node of a file.
Parameters:
config (Config)โ A pytest config. Seeparseconfig()for creating it.arg (Union[str, PathLike[str]])โ Path to the file.
Returns: The node.
Return type:
Union[Collector, Item]getpathnode(
path)Return the collection node of a file.
This is like
getnode()but usesparseconfigure()to create the (configured) pytest Config instance.Parameters:
path (Union[str, PathLike[str]])โ Path to the file.
Returns: The node.
Return type:
Union[Collector, Item]genitems(
colitems)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.
Parameters:
colitems (Sequence[Union[Item, Collector]])โ The collection nodes.
Returns: The collected items.
Return type:
List[Item]runitem(
source)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().inline_runsource(
source, *cmdlineargs)Run a test module in process using
pytest.main().This run writes โsourceโ into a temporary file and runs
pytest.main()on it, returning aHookRecorderinstance for the result.Parameters:
source (str)โ The source code of the test module.cmdlineargsโ Any extra command line arguments to use.
inline_genitems(
*args)Run
pytest.main(['--collectonly'])in-process.Runs the
pytest.main()function to run all of pytest inside the test process itselflike inline_run(), but returns a tuple of the collected items and aHookRecorderinstance.inline_run(
*args, plugins=(), no_reraise_ctrlc=False)Run
pytest.main()in-process, returning a HookRecorder.Runs the
pytest.main()function to run all of pytest inside the test process itself. This means it can return aHookRecorderinstance which gives more detailed results from that run than can be done by matching stdout/stderr fromrunpytest().Parameters:
args (Union[str, PathLike[str]])โ Command line arguments to pass topytest.main().pluginsโ Extra plugin instances thepytest.main()instance should use.no_reraise_ctrlc (bool)โ Typically we reraise keyboard interrupts from the child run. If True, theKeyboardInterruptexception is captured.
runpytest_inprocess(
*args, **kwargs)Return result of running pytest in-process, providing a similar interface to what
self.runpytest()provides.runpytest(
*args, **kwargs)Run pytest inline or in a subprocess, depending on the command line option โโrunpytestโ and return a
RunResult.parseconfig(
*args)Return a new pytest
pytest.Configinstance from given commandline args.This invokes the pytest bootstrapping code in _pytest.config to create a new
pytest.PytestPluginManagerand call thepytest_cmdline_parsehook to create a new pytest.Config instance.If
pluginshas been populated they should be plugin modules to be registered with the plugin manager.parseconfigure(
*args)Return a new pytest configured
Configinstance.Returns a new
pytest.Configinstance likeparseconfig(), but also calls thepytest_configurehook.getitem(
source, funcname='test_func')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.
Parameters:
source(Union[str, PathLike[str]])โ The module source.funcname(str)โ The name of the test function for which to return a test item.
Returns: The test item.
Return type:
Itemgetitems(
source)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(
source, configargs=(), *, withinit=False)Return the module collection node for
source.Writes
sourceto a file usingmakepyfile()and then runs the pytest collection on it, returning the collection node for the test module.Parameters:
source (Union[str, PathLike[str]])โ The source code of the module to collect.configargsโ Any extra arguments to pass toparseconfigure().withinit (bool)โ Whether to also write an__init__.pyfile to the same directory to ensure it is a package.
collect_by_name(
modcol, name)Return the collection node for name from the module collection.
Searches a module collection node for a collection node matching the given name.
Parameters:
modcol (Collector)โ A module collection node; see getmodulecol().name (str)โ The name of the node to return.
popen(
cmdargs, stdout=-1, stderr=-1, stdin=NotSetType.token, **kw)Invoke
subprocess.Popen.Calls
subprocess.Popenmaking sure the current working directory is inPYTHONPATH.You probably want to use
run()instead.run(
*cmdargs, timeout=None, stdin=NotSetType.token)Run a command with arguments.
Run a process using
subprocess.Popensaving thestdoutandstderr.Parameters:
cmdargs (Union[str, PathLike[str]])โ The sequence of arguments to pass tosubprocess.Popen, with path-like objects being converted to str automatically.timeout (Optional[float])โ The period in seconds after which to timeout and raisePytester.TimeoutExpired.stdin (Union[NotSetType, bytes, IO[Any], int])โ Optional standard input.If it is
CLOSE_STDIN(Default), then this method callssubprocess.Popenwithstdin=subprocess.PIPE, and the standard input is closed immediately after the new command is started.If it is of type
bytes, these bytes are sent to the standard input of the command.Otherwise, it is passed through to
subprocess.Popen. For further information in this case, consult the document of the ยท parameter insubprocess.Popen.
Returns: The result.
Return type:
RunResultrunpython(
script)Run a python script using
sys.executableas interpreter.runpython_c(
command)Run
python -c "command".runpytest_subprocess(
*args, timeout=None)Run pytest as a subprocess with given arguments.
Any plugins added to the
pluginslist will be added using the-pcommand line option. Additionally--basetempis 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.Parameters:
args (Union[str, PathLike[str]])โ The sequence of arguments to pass to the pytest subprocess.timeout (Optional[float])โ The period in seconds after which to timeout and raisePytester.TimeoutExpired.
Returns: The result.
Return type:
RunResultspawn_pytest(
string, expect_timeout=10.0)Run pytest using pexpect.
This makes sure to use the right pytest and sets up the temporary directory locations.
The pexpect child is returned.
spawn(
cmd, expect_timeout=10.0)Run a command using pexpect.
The pexpect child is returned.
final classRunResult โThe result of running a command from
Pytester.ret:
Union[int, ExitCode]The return value.
outlines
List of lines captured from
stdout.errlines
List of lines captured from
stderr.stdout
LineMatcherofstdout.Use e.g.
str(stdout)to reconstruct stdout, or the commonly usedstdout.fnmatch_lines()method.stderr
LineMatcherofstderr.
duration
- Duration in seconds.
parseoutcomes()
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:
shell======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s =========== 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====Will return
{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}.classmethodparse_summary_nouns(lines)Extract the nouns from a pytest terminal summary line.
It always returns the plural noun for consistency:
shell======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s =========== 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====Will return {"failed": 1, "passed": 1, "warnings": 1, "errors": 1}.
assert_outcomes(
passed=0, skipped=0, failed=0, errors=0, xpassed=0, xfailed=0, warnings=None, deselected=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.
warningsanddeselectedare only checked if not None.
classLineMatcher โ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().str()
Return the entire original text.
New in version 6.2: You can use
str()in older versions.fnmatch_lines_random(
lines2)Check lines exist in the output in any order (using
fnmatch.fnmatch()).re_match_lines_random(
lines2)Check lines exist in the output in any order (using
re.match()).get_lines_after(
fnline)Return all lines following the given line in the text.
The given line can contain glob wildcards.
fnmatch_lines(
lines2, *, consecutive=False)Check lines exist in the output (using
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.Parameters:
lines2 (Sequence[str])โ String patterns to match.consecutive (bool)โ Match lines consecutively?
re_match_lines(
lines2, *, consecutive=False)Check lines exist in the output (using
re.match()).The argument is a list of lines which have to match using
re.match. If they do not match apytest.fail()is called.The matches and non-matches are also shown as part of the error message.
Parameters:
lines2 (Sequence[str])โ string patterns to match.consecutive (bool)โ match lines consecutively?
no_fnmatch_line(
pat)Ensure captured lines do not match the given pattern, using
fnmatch.fnmatch.Parameters:
pat (str)โ The pattern to match lines.
no_re_match_line(
pat)Ensure captured lines do not match the given pattern, using
re.match.Parameters:
pat (str)โ The regular expression to match lines.
str()
Return the entire original text.
final classHookRecorder โRecord all hooks called in a plugin manager.
Hook recorders are created by
Pytester.This wraps all the hook calls in the plugin manager, recording each call before propagating the normal calls.
getcalls(
names)Get all recorded calls to hooks with the given names (or name).
matchreport(
inamepart='', names=('pytest_runtest_logreport', 'pytest_collectreport'), when=None)Return a testreport whose dotted import path matches.
final classRecordedHookCall โA recorded call to a hook.
The arguments to the hook call are set as attributes. For example:
pythoncalls = hook_recorder.getcalls("pytest_runtest_setup") # Suppose pytest_runtest_setup was called once with `item=an_item`. assert calls[0].item is an_itemcalls = hook_recorder.getcalls("pytest_runtest_setup") # Suppose pytest_runtest_setup was called once with `item=an_item`. assert calls[0].item is an_item
record_property โ
Tutorial: record_property
record_property() โ
Add extra properties to the calling test.
User properties become part of the test report and are available to the configured reporters, like JUnit XML.
The fixture is callable with
name, value. The value is automatically XML-encoded.Example:
pythondef test_function(record_property): record_property("example_key", 1)def test_function(record_property): record_property("example_key", 1)
record_testsuite_property โ
Tutorial: record_testsuite_property
record_testsuite_property() โ
Record a new
<property>tag as child of the root<testsuite>.This is suitable to writing global information regarding the entire test suite, and is compatible with
xunit2JUnit family.This is a
session-scopedfixture which is called with(name, value).Example:
pythondef test_foo(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH")def test_foo(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH")Parameters:
nameโ The property name.valueโ The property value. Will be converted to a string.
Warning
Currently this fixture does not work with the pytest-xdist plugin. See issue #7767 for details.
recwarn โ
Tutorial: Asserting warnings with the warns function
recwarn() โ
Return a
WarningsRecorderinstance that records all warnings emitted by test functions.See How to capture warnings for information on warning categories.
classWarningsRecorder โA context manager to record raised warnings.
Each recorded warning is an instance of
warnings.WarningMessage.Adapted from
warnings.catch_warnings.Note
DeprecationWarningandPendingDeprecationWarningare treated differently; see Ensuring code triggers a deprecation warning.propertylist:List[WarningMessage]The list of recorded warnings.
pop(
cls=<class 'Warning'>)Pop the first recorded warning which is an instance of
cls, but not an instance of a child class of any other match. RaisesAssertionErrorif there is no match.clear()
Clear the list of recorded warnings.
request โ
Example: Pass different values to a test function, depending on command line options
The request fixture is a special fixture providing information of the requesting test function.
classFixtureRequest โ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
paramattribute in case the fixture is parametrized indirectly.fixturename:
Optional[str]Fixture for which this request is being performed.
propertyscope:Literal['session', 'package', 'module', 'class', 'function']Scope string, one of โfunctionโ, โclassโ, โmoduleโ, โpackageโ, โsessionโ.
propertyfixturenames:List[str]Names of all active fixtures in this request.
propertynodeUnderlying collection node (depends on current request scope).
propertyconfig:ConfigThe pytest config object associated with this request.
propertyfunctionTest function object if the request has a per-function scope.
propertyclsClass (can be None) where the test function was collected.
propertyinstanceInstance (can be None) on which test function was collected.
propertymodulePython module object where the test function was collected.
propertypath:PathPath where the test function was collected.
propertykeywords:MutableMapping[str, Any]Keywords/markers dictionary for the underlying node.
propertysession:SessionPytest session object.
addfinalizer(
finalizer)Add finalizer/teardown function to be called without arguments after the last test within the requesting test context finished execution.
applymarker(
marker)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(Union[str, MarkDecorator])โ An object created by a call topytest.mark.NAME(...).
raiseerror(
msg)Raise a FixtureLookupError exception.
Parameters:
msg (Optional[str])โ An optional custom error message.
getfixturevalue(
argname)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.
Parameters:
argname (str)โ The fixture name.
Raises:
pytest.FixtureLookupErrorโ If the given fixture could not be found.
testdir โ
Identical to pytester, but provides an instance whose methods return legacy py.path.local objects instead when applicable.
New code should avoid using testdir in favor of pytester.
final classTestdir โSimilar to
Pytester, but this class works with legacylegacy_pathobjects instead.All methods just forward to an internal
Pytesterinstance, converting results tolegacy_pathobjects as necessary.exceptionTimeoutExpiredpropertytmpdir:LocalPathTemporary directory where tests are executed.
make_hook_recorder(
pluginmanager)See
Pytester.make_hook_recorder().chdir()
See
Pytester.chdir().finalize()
See
Pytester._finalize().makefile(
ext, *args, **kwargs)See
Pytester.makefile().makeconftest(
source)See
Pytester.makeconftest().makeini(
source)See
Pytester.makeini().getinicfg(
source)See
Pytester.getinicfg().makepyprojecttoml(
source)See
Pytester.makepyprojecttoml().makepyfile(
*args, **kwargs)See
Pytester.makepyfile().maketxtfile(
*args, **kwargs)See
Pytester.maketxtfile().syspathinsert(
path=None)See
Pytester.syspathinsert().mkdir(
name)See
Pytester.mkdir().mkpydir(
name)See
Pytester.mkpydir().copy_example(
name=None)See
Pytester.copy_example().getnode(
config, arg)See
Pytester.getnode().getpathnode(
path)See
Pytester.getpathnode().genitems(
colitems)See
Pytester.genitems().runitem(
source)See
Pytester.runitem().inline_runsource(
source, *cmdlineargs)See
Pytester.inline_runsource().inline_genitems(
*args)See
Pytester.inline_genitems().inline_run(
*args, plugins=(), no_reraise_ctrlc=False)See
Pytester.inline_run()].runpytest_inprocess(
*args, **kwargs)See
Pytester.runpytest_inprocess().runpytest(
*args, **kwargs)See
Pytester.runpytest().parseconfig(
*args)See
Pytester.parseconfig().parseconfigure(
*args)See
Pytester.parseconfigure().getitem(
source, funcname='test_func')See
Pytester.getitem().getitems(
source)See
Pytester.getitems().getmodulecol(
source, configargs=(), withinit=False)See
Pytester.getmodulecol().collect_by_name(
modcol, name)See
Pytester.collect_by_name().popen(
cmdargs, stdout=-1, stderr=-1, stdin=NotSetType.token, **kw)See
Pytester.popen().run(
*cmdargs, timeout=None, stdin=NotSetType.token)See
Pytester.run().runpython(
script)See
Pytester.runpython().runpython_c(
command)See
Pytester.runpython_c().runpytest_subprocess(
*args, timeout=None)See
Pytester.runpytest_subprocess().spawn_pytest(
string, expect_timeout=10.0)See
Pytester.spawn_pytest().spawn(
cmd, expect_timeout=10.0)See
Pytester.spawn().
tmp_path โ
Tutorial: How to use temporary directories and files in tests
tmp_path() โ
Return a temporary directory path object which is unique to each test function invocation, created as a sub directory of the base temporary directory.
By default, a new base temporary directory is created each test session, and old bases are removed after 3 sessions, to aid in debugging. This behavior can be configured with
tmp_path_retention_countandtmp_path_retention_policy. If--basetempis used then it is cleared each session. See The default base temporary directory.The returned object is a
pathlib.Pathobject.
tmp_path_factory โ
Tutorial: The tmp_path_factory fixture
tmp_path_factory is an instance of TempPathFactory:
final classTempPathFactory โFactory for temporary directories under the common base temp directory.
The base directory can be configured using the
--basetempoption.mktemp(
basename, numbered=True)Create a new temporary directory managed by the factory.
Parameters:
basename(str)โ Directory base name, must be a relative path.numbered(bool)โ IfTrue, ensure the directory is unique by adding a numbered suffix greater than - any existing one:basename="foo-"andnumbered=Truemeans that this function will create directories named"foo-0","foo-1","foo-2"and so on.
Returns: The path to the new directory.
Return type:
Pathgetbasetemp()
Return the base temporary directory, creating it if needed.
Returns: The base temporary directory.
Return type:
Path
tmpdir โ
Tutorial: The tmpdir and tmpdir_factory fixtures
tmpdir() โ
Return a temporary directory path object which is unique to each test function invocation, created as a sub directory of the base temporary directory.
By default, a new base temporary directory is created each test session, and old bases are removed after 3 sessions, to aid in debugging. If
--basetempis used then it is cleared each session. See The default base temporary directory.The returned object is a
legacy_pathobject.
tmpdir_factory โ
Tutorial: The tmpdir and tmpdir_factory fixtures
tmpdir_factory is an instance of TempdirFactory:
final classTempdirFactory โBackward compatibility wrapper that implements
py.path.localforTempPathFactory.Note
These days, it is preferred to use
tmp_path_factory.mktemp(
basename, numbered=True)Same as
TempPathFactory.mktemp(), but returns apy.path.localobject.getbasetemp()
Same as
TempPathFactory.getbasetemp(), but returns apy.path.localobject.