| 1 |
|
| 2 |
|
| 3 |
Basic patterns and examples |
| 4 |
========================================================== |
| 5 |
|
| 6 |
How to change command line options defaults |
| 7 |
------------------------------------------- |
| 8 |
|
| 9 |
It can be tedious to type the same series of command line options |
| 10 |
every time you use ``pytest``. For example, if you always want to see |
| 11 |
detailed info on skipped and xfailed tests, as well as have terser "dot" |
| 12 |
progress output, you can write it into a configuration file: |
| 13 |
|
| 14 |
.. code-block:: toml |
| 15 |
|
| 16 |
# content of pytest.toml |
| 17 |
[pytest] |
| 18 |
addopts = ["-ra", "-q"] |
| 19 |
|
| 20 |
Alternatively, you can set a ``PYTEST_ADDOPTS`` environment variable to add command |
| 21 |
line options while the environment is in use: |
| 22 |
|
| 23 |
.. code-block:: bash |
| 24 |
|
| 25 |
export PYTEST_ADDOPTS="-v" |
| 26 |
|
| 27 |
Here's how the command-line is built in the presence of ``addopts`` or the environment variable: |
| 28 |
|
| 29 |
.. code-block:: text |
| 30 |
|
| 31 |
<configuration file addopts> $PYTEST_ADDOPTS <extra command-line arguments> |
| 32 |
|
| 33 |
So if the user executes in the command-line: |
| 34 |
|
| 35 |
.. code-block:: bash |
| 36 |
|
| 37 |
pytest -m slow |
| 38 |
|
| 39 |
The actual command line executed is: |
| 40 |
|
| 41 |
.. code-block:: bash |
| 42 |
|
| 43 |
pytest -ra -q -v -m slow |
| 44 |
|
| 45 |
Note that as usual for other command-line applications, in case of conflicting options the last one wins, so the example |
| 46 |
above will show verbose output because :option:`-v` overwrites :option:`-q`. |
| 47 |
|
| 48 |
|
| 49 |
.. _request example: |
| 50 |
|
| 51 |
Pass different values to a test function, depending on command line options |
| 52 |
---------------------------------------------------------------------------- |
| 53 |
|
| 54 |
.. regendoc:wipe |
| 55 |
|
| 56 |
Suppose we want to write a test that depends on a command line option. |
| 57 |
Here is a basic pattern to achieve this: |
| 58 |
|
| 59 |
.. code-block:: python |
| 60 |
|
| 61 |
# content of test_sample.py |
| 62 |
def test_answer(cmdopt): |
| 63 |
if cmdopt == "type1": |
| 64 |
print("first") |
| 65 |
elif cmdopt == "type2": |
| 66 |
print("second") |
| 67 |
assert 0 # to see what was printed |
| 68 |
|
| 69 |
|
| 70 |
For this to work we need to add a command line option and |
| 71 |
provide the ``cmdopt`` through a :ref:`fixture function <fixture>`: |
| 72 |
|
| 73 |
.. code-block:: python |
| 74 |
|
| 75 |
# content of conftest.py |
| 76 |
import pytest |
| 77 |
|
| 78 |
|
| 79 |
def pytest_addoption(parser): |
| 80 |
parser.addoption( |
| 81 |
"--cmdopt", action="store", default="type1", help="my option: type1 or type2" |
| 82 |
) |
| 83 |
|
| 84 |
|
| 85 |
@pytest.fixture |
| 86 |
def cmdopt(request): |
| 87 |
return request.config.getoption("--cmdopt") |
| 88 |
|
| 89 |
Let's run this without supplying our new option: |
| 90 |
|
| 91 |
.. code-block:: pytest |
| 92 |
|
| 93 |
$ pytest -q test_sample.py |
| 94 |
F [100%] |
| 95 |
================================= FAILURES ================================= |
| 96 |
_______________________________ test_answer ________________________________ |
| 97 |
|
| 98 |
cmdopt = 'type1' |
| 99 |
|
| 100 |
def test_answer(cmdopt): |
| 101 |
if cmdopt == "type1": |
| 102 |
print("first") |
| 103 |
elif cmdopt == "type2": |
| 104 |
print("second") |
| 105 |
> assert 0 # to see what was printed |
| 106 |
^^^^^^^^ |
| 107 |
E assert 0 |
| 108 |
|
| 109 |
test_sample.py:6: AssertionError |
| 110 |
--------------------------- Captured stdout call --------------------------- |
| 111 |
first |
| 112 |
========================= short test summary info ========================== |
| 113 |
FAILED test_sample.py::test_answer - assert 0 |
| 114 |
1 failed in 0.12s |
| 115 |
|
| 116 |
And now with supplying a command line option: |
| 117 |
|
| 118 |
.. code-block:: pytest |
| 119 |
|
| 120 |
$ pytest -q --cmdopt=type2 |
| 121 |
F [100%] |
| 122 |
================================= FAILURES ================================= |
| 123 |
_______________________________ test_answer ________________________________ |
| 124 |
|
| 125 |
cmdopt = 'type2' |
| 126 |
|
| 127 |
def test_answer(cmdopt): |
| 128 |
if cmdopt == "type1": |
| 129 |
print("first") |
| 130 |
elif cmdopt == "type2": |
| 131 |
print("second") |
| 132 |
> assert 0 # to see what was printed |
| 133 |
^^^^^^^^ |
| 134 |
E assert 0 |
| 135 |
|
| 136 |
test_sample.py:6: AssertionError |
| 137 |
--------------------------- Captured stdout call --------------------------- |
| 138 |
second |
| 139 |
========================= short test summary info ========================== |
| 140 |
FAILED test_sample.py::test_answer - assert 0 |
| 141 |
1 failed in 0.12s |
| 142 |
|
| 143 |
You can see that the command line option arrived in our test. |
| 144 |
|
| 145 |
We could add simple validation for the input by listing the choices: |
| 146 |
|
| 147 |
.. code-block:: python |
| 148 |
|
| 149 |
# content of conftest.py |
| 150 |
import pytest |
| 151 |
|
| 152 |
|
| 153 |
def pytest_addoption(parser): |
| 154 |
parser.addoption( |
| 155 |
"--cmdopt", |
| 156 |
action="store", |
| 157 |
default="type1", |
| 158 |
help="my option: type1 or type2", |
| 159 |
choices=("type1", "type2"), |
| 160 |
) |
| 161 |
|
| 162 |
Now we'll get feedback on a bad argument: |
| 163 |
|
| 164 |
.. code-block:: pytest |
| 165 |
|
| 166 |
$ pytest -q --cmdopt=type3 |
| 167 |
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] |
| 168 |
pytest: error: argument --cmdopt: invalid choice: 'type3' (choose from 'type1', 'type2') |
| 169 |
inifile: None |
| 170 |
rootdir: /home/sweet/project |
| 171 |
|
| 172 |
|
| 173 |
If you need to provide more detailed error messages, you can use the |
| 174 |
``type`` parameter and raise :exc:`pytest.UsageError`: |
| 175 |
|
| 176 |
.. code-block:: python |
| 177 |
|
| 178 |
# content of conftest.py |
| 179 |
import pytest |
| 180 |
|
| 181 |
|
| 182 |
def type_checker(value): |
| 183 |
msg = "cmdopt must specify a numeric type as typeNNN" |
| 184 |
if not value.startswith("type"): |
| 185 |
raise pytest.UsageError(msg) |
| 186 |
try: |
| 187 |
int(value[4:]) |
| 188 |
except ValueError: |
| 189 |
raise pytest.UsageError(msg) |
| 190 |
|
| 191 |
return value |
| 192 |
|
| 193 |
|
| 194 |
def pytest_addoption(parser): |
| 195 |
parser.addoption( |
| 196 |
"--cmdopt", |
| 197 |
action="store", |
| 198 |
default="type1", |
| 199 |
help="my option: type1 or type2", |
| 200 |
type=type_checker, |
| 201 |
) |
| 202 |
|
| 203 |
This completes the basic pattern. However, one often rather wants to |
| 204 |
process command line options outside of the test and rather pass in |
| 205 |
different or more complex objects. |
| 206 |
|
| 207 |
Dynamically adding command line options |
| 208 |
-------------------------------------------------------------- |
| 209 |
|
| 210 |
.. regendoc:wipe |
| 211 |
|
| 212 |
Through :confval:`addopts` you can statically add command line |
| 213 |
options for your project. You can also dynamically modify |
| 214 |
the command line arguments before they get processed: |
| 215 |
|
| 216 |
.. code-block:: python |
| 217 |
|
| 218 |
# installable external plugin |
| 219 |
import sys |
| 220 |
|
| 221 |
|
| 222 |
def pytest_load_initial_conftests(args): |
| 223 |
if "xdist" in sys.modules: # pytest-xdist plugin |
| 224 |
import multiprocessing |
| 225 |
|
| 226 |
num = max(multiprocessing.cpu_count() / 2, 1) |
| 227 |
args[:] = ["-n", str(num)] + args |
| 228 |
|
| 229 |
If you have the :pypi:`xdist plugin <pytest-xdist>` installed |
| 230 |
you will now always perform test runs using a number |
| 231 |
of subprocesses close to your CPU. Running in an empty |
| 232 |
directory with the above conftest.py: |
| 233 |
|
| 234 |
.. code-block:: pytest |
| 235 |
|
| 236 |
$ pytest |
| 237 |
=========================== test session starts ============================ |
| 238 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 239 |
rootdir: /home/sweet/project |
| 240 |
collected 0 items |
| 241 |
|
| 242 |
========================== no tests ran in 0.12s =========================== |
| 243 |
|
| 244 |
.. _`excontrolskip`: |
| 245 |
|
| 246 |
Control skipping of tests according to command line option |
| 247 |
-------------------------------------------------------------- |
| 248 |
|
| 249 |
.. regendoc:wipe |
| 250 |
|
| 251 |
Here is a ``conftest.py`` file adding a ``--runslow`` command |
| 252 |
line option to control skipping of ``pytest.mark.slow`` marked tests: |
| 253 |
|
| 254 |
.. code-block:: python |
| 255 |
|
| 256 |
# content of conftest.py |
| 257 |
|
| 258 |
import pytest |
| 259 |
|
| 260 |
|
| 261 |
def pytest_addoption(parser): |
| 262 |
parser.addoption( |
| 263 |
"--runslow", action="store_true", default=False, help="run slow tests" |
| 264 |
) |
| 265 |
|
| 266 |
|
| 267 |
def pytest_configure(config): |
| 268 |
config.addinivalue_line("markers", "slow: mark test as slow to run") |
| 269 |
|
| 270 |
|
| 271 |
def pytest_collection_modifyitems(config, items): |
| 272 |
if config.getoption("--runslow"): |
| 273 |
# --runslow given in cli: do not skip slow tests |
| 274 |
return |
| 275 |
skip_slow = pytest.mark.skip(reason="need --runslow option to run") |
| 276 |
for item in items: |
| 277 |
if "slow" in item.keywords: |
| 278 |
item.add_marker(skip_slow) |
| 279 |
|
| 280 |
We can now write a test module like this: |
| 281 |
|
| 282 |
.. code-block:: python |
| 283 |
|
| 284 |
# content of test_module.py |
| 285 |
import pytest |
| 286 |
|
| 287 |
|
| 288 |
def test_func_fast(): |
| 289 |
pass |
| 290 |
|
| 291 |
|
| 292 |
@pytest.mark.slow |
| 293 |
def test_func_slow(): |
| 294 |
pass |
| 295 |
|
| 296 |
and when running it will see a skipped "slow" test: |
| 297 |
|
| 298 |
.. code-block:: pytest |
| 299 |
|
| 300 |
$ pytest -rs # "-rs" means report details on the little 's' |
| 301 |
=========================== test session starts ============================ |
| 302 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 303 |
rootdir: /home/sweet/project |
| 304 |
collected 2 items |
| 305 |
|
| 306 |
test_module.py .s [100%] |
| 307 |
|
| 308 |
========================= short test summary info ========================== |
| 309 |
SKIPPED [1] test_module.py:8: need --runslow option to run |
| 310 |
======================= 1 passed, 1 skipped in 0.12s ======================= |
| 311 |
|
| 312 |
Or run it including the ``slow`` marked test: |
| 313 |
|
| 314 |
.. code-block:: pytest |
| 315 |
|
| 316 |
$ pytest --runslow |
| 317 |
=========================== test session starts ============================ |
| 318 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 319 |
rootdir: /home/sweet/project |
| 320 |
collected 2 items |
| 321 |
|
| 322 |
test_module.py .. [100%] |
| 323 |
|
| 324 |
============================ 2 passed in 0.12s ============================= |
| 325 |
|
| 326 |
.. _`__tracebackhide__`: |
| 327 |
|
| 328 |
Writing well integrated assertion helpers |
| 329 |
----------------------------------------- |
| 330 |
|
| 331 |
.. regendoc:wipe |
| 332 |
|
| 333 |
If you have a test helper function called from a test you can |
| 334 |
use the ``pytest.fail`` marker to fail a test with a certain message. |
| 335 |
The test support function will not show up in the traceback if you |
| 336 |
set the ``__tracebackhide__`` option somewhere in the helper function. |
| 337 |
Example: |
| 338 |
|
| 339 |
.. code-block:: python |
| 340 |
|
| 341 |
# content of test_checkconfig.py |
| 342 |
import pytest |
| 343 |
|
| 344 |
|
| 345 |
def checkconfig(x): |
| 346 |
__tracebackhide__ = True |
| 347 |
if not hasattr(x, "config"): |
| 348 |
pytest.fail(f"not configured: {x}") |
| 349 |
|
| 350 |
|
| 351 |
def test_something(): |
| 352 |
checkconfig(42) |
| 353 |
|
| 354 |
The ``__tracebackhide__`` setting influences ``pytest`` showing |
| 355 |
of tracebacks: the ``checkconfig`` function will not be shown |
| 356 |
unless the :option:`--full-trace` command line option is specified. |
| 357 |
Let's run our little function: |
| 358 |
|
| 359 |
.. code-block:: pytest |
| 360 |
|
| 361 |
$ pytest -q test_checkconfig.py |
| 362 |
F [100%] |
| 363 |
================================= FAILURES ================================= |
| 364 |
______________________________ test_something ______________________________ |
| 365 |
|
| 366 |
def test_something(): |
| 367 |
> checkconfig(42) |
| 368 |
E Failed: not configured: 42 |
| 369 |
|
| 370 |
test_checkconfig.py:11: Failed |
| 371 |
========================= short test summary info ========================== |
| 372 |
FAILED test_checkconfig.py::test_something - Failed: not configured: 42 |
| 373 |
1 failed in 0.12s |
| 374 |
|
| 375 |
If you only want to hide certain exceptions, you can set ``__tracebackhide__`` |
| 376 |
to a callable which gets the ``ExceptionInfo`` object. You can for example use |
| 377 |
this to make sure unexpected exception types aren't hidden: |
| 378 |
|
| 379 |
.. code-block:: python |
| 380 |
|
| 381 |
import operator |
| 382 |
|
| 383 |
import pytest |
| 384 |
|
| 385 |
|
| 386 |
class ConfigException(Exception): |
| 387 |
pass |
| 388 |
|
| 389 |
|
| 390 |
def checkconfig(x): |
| 391 |
__tracebackhide__ = operator.methodcaller("errisinstance", ConfigException) |
| 392 |
if not hasattr(x, "config"): |
| 393 |
raise ConfigException(f"not configured: {x}") |
| 394 |
|
| 395 |
|
| 396 |
def test_something(): |
| 397 |
checkconfig(42) |
| 398 |
|
| 399 |
This will avoid hiding the exception traceback on unrelated exceptions (i.e. |
| 400 |
bugs in assertion helpers). |
| 401 |
|
| 402 |
|
| 403 |
Detect if running from within a pytest run |
| 404 |
-------------------------------------------------------------- |
| 405 |
|
| 406 |
.. regendoc:wipe |
| 407 |
|
| 408 |
Usually it is a bad idea to make application code |
| 409 |
behave differently if called from a test. But if you |
| 410 |
absolutely must find out if your application code is |
| 411 |
running from a test you can do this: |
| 412 |
|
| 413 |
.. code-block:: python |
| 414 |
|
| 415 |
import os |
| 416 |
|
| 417 |
|
| 418 |
if os.environ.get("PYTEST_VERSION") is not None: |
| 419 |
# Things you want to do if your code is called by pytest. |
| 420 |
... |
| 421 |
else: |
| 422 |
# Things you want to do if your code is not called by pytest. |
| 423 |
... |
| 424 |
|
| 425 |
|
| 426 |
Adding info to test report header |
| 427 |
-------------------------------------------------------------- |
| 428 |
|
| 429 |
.. regendoc:wipe |
| 430 |
|
| 431 |
It's easy to present extra information in a ``pytest`` run: |
| 432 |
|
| 433 |
.. code-block:: python |
| 434 |
|
| 435 |
# content of conftest.py |
| 436 |
|
| 437 |
|
| 438 |
def pytest_report_header(config): |
| 439 |
return "project deps: mylib-1.1" |
| 440 |
|
| 441 |
which will add the string to the test header accordingly: |
| 442 |
|
| 443 |
.. code-block:: pytest |
| 444 |
|
| 445 |
$ pytest |
| 446 |
=========================== test session starts ============================ |
| 447 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 448 |
project deps: mylib-1.1 |
| 449 |
rootdir: /home/sweet/project |
| 450 |
collected 0 items |
| 451 |
|
| 452 |
========================== no tests ran in 0.12s =========================== |
| 453 |
|
| 454 |
.. regendoc:wipe |
| 455 |
|
| 456 |
It is also possible to return a list of strings which will be considered as several |
| 457 |
lines of information. You may consider ``config.getoption('verbose')`` in order to |
| 458 |
display more information if applicable: |
| 459 |
|
| 460 |
.. code-block:: python |
| 461 |
|
| 462 |
# content of conftest.py |
| 463 |
|
| 464 |
|
| 465 |
def pytest_report_header(config): |
| 466 |
if config.get_verbosity() > 0: |
| 467 |
return ["info1: did you know that ...", "did you?"] |
| 468 |
|
| 469 |
which will add info only when run with "--v": |
| 470 |
|
| 471 |
.. code-block:: pytest |
| 472 |
|
| 473 |
$ pytest -v |
| 474 |
=========================== test session starts ============================ |
| 475 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python |
| 476 |
cachedir: .pytest_cache |
| 477 |
info1: did you know that ... |
| 478 |
did you? |
| 479 |
rootdir: /home/sweet/project |
| 480 |
collecting ... collected 0 items |
| 481 |
|
| 482 |
========================== no tests ran in 0.12s =========================== |
| 483 |
|
| 484 |
and nothing when run plainly: |
| 485 |
|
| 486 |
.. code-block:: pytest |
| 487 |
|
| 488 |
$ pytest |
| 489 |
=========================== test session starts ============================ |
| 490 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 491 |
rootdir: /home/sweet/project |
| 492 |
collected 0 items |
| 493 |
|
| 494 |
========================== no tests ran in 0.12s =========================== |
| 495 |
|
| 496 |
Profiling test duration |
| 497 |
-------------------------- |
| 498 |
|
| 499 |
.. regendoc:wipe |
| 500 |
|
| 501 |
.. versionadded: 2.2 |
| 502 |
|
| 503 |
If you have a slow running large test suite you might want to find |
| 504 |
out which tests are the slowest. Let's make an artificial test suite: |
| 505 |
|
| 506 |
.. code-block:: python |
| 507 |
|
| 508 |
# content of test_some_are_slow.py |
| 509 |
import time |
| 510 |
|
| 511 |
|
| 512 |
def test_funcfast(): |
| 513 |
time.sleep(0.1) |
| 514 |
|
| 515 |
|
| 516 |
def test_funcslow1(): |
| 517 |
time.sleep(0.2) |
| 518 |
|
| 519 |
|
| 520 |
def test_funcslow2(): |
| 521 |
time.sleep(0.3) |
| 522 |
|
| 523 |
Now we can profile which test functions execute the slowest: |
| 524 |
|
| 525 |
.. code-block:: pytest |
| 526 |
|
| 527 |
$ pytest --durations=3 |
| 528 |
=========================== test session starts ============================ |
| 529 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 530 |
rootdir: /home/sweet/project |
| 531 |
collected 3 items |
| 532 |
|
| 533 |
test_some_are_slow.py ... [100%] |
| 534 |
|
| 535 |
=========================== slowest 3 durations ============================ |
| 536 |
0.30s call test_some_are_slow.py::test_funcslow2 |
| 537 |
0.20s call test_some_are_slow.py::test_funcslow1 |
| 538 |
0.10s call test_some_are_slow.py::test_funcfast |
| 539 |
============================ 3 passed in 0.12s ============================= |
| 540 |
|
| 541 |
Incremental testing - test steps |
| 542 |
--------------------------------------------------- |
| 543 |
|
| 544 |
.. regendoc:wipe |
| 545 |
|
| 546 |
Sometimes you may have a testing situation which consists of a series |
| 547 |
of test steps. If one step fails it makes no sense to execute further |
| 548 |
steps as they are all expected to fail anyway and their tracebacks |
| 549 |
add no insight. Here is a simple ``conftest.py`` file which introduces |
| 550 |
an ``incremental`` marker which is to be used on classes: |
| 551 |
|
| 552 |
.. code-block:: python |
| 553 |
|
| 554 |
# content of conftest.py |
| 555 |
|
| 556 |
import pytest |
| 557 |
|
| 558 |
# store history of failures per test class name and per index in parametrize (if parametrize used) |
| 559 |
_test_failed_incremental: dict[str, dict[tuple[int, ...], str]] = {} |
| 560 |
|
| 561 |
|
| 562 |
def pytest_runtest_makereport(item, call): |
| 563 |
if "incremental" in item.keywords: |
| 564 |
# incremental marker is used |
| 565 |
if call.excinfo is not None: |
| 566 |
# the test has failed |
| 567 |
# retrieve the class name of the test |
| 568 |
cls_name = str(item.cls) |
| 569 |
# retrieve the index of the test (if parametrize is used in combination with incremental) |
| 570 |
parametrize_index = ( |
| 571 |
tuple(item.callspec.indices.values()) |
| 572 |
if hasattr(item, "callspec") |
| 573 |
else () |
| 574 |
) |
| 575 |
# retrieve the name of the test function |
| 576 |
test_name = item.originalname or item.name |
| 577 |
# store in _test_failed_incremental the original name of the failed test |
| 578 |
_test_failed_incremental.setdefault(cls_name, {}).setdefault( |
| 579 |
parametrize_index, test_name |
| 580 |
) |
| 581 |
|
| 582 |
|
| 583 |
def pytest_runtest_setup(item): |
| 584 |
if "incremental" in item.keywords: |
| 585 |
# retrieve the class name of the test |
| 586 |
cls_name = str(item.cls) |
| 587 |
# check if a previous test has failed for this class |
| 588 |
if cls_name in _test_failed_incremental: |
| 589 |
# retrieve the index of the test (if parametrize is used in combination with incremental) |
| 590 |
parametrize_index = ( |
| 591 |
tuple(item.callspec.indices.values()) |
| 592 |
if hasattr(item, "callspec") |
| 593 |
else () |
| 594 |
) |
| 595 |
# retrieve the name of the first test function to fail for this class name and index |
| 596 |
test_name = _test_failed_incremental[cls_name].get(parametrize_index, None) |
| 597 |
# if name found, test has failed for the combination of class name & test name |
| 598 |
if test_name is not None: |
| 599 |
pytest.xfail(f"previous test failed ({test_name})") |
| 600 |
|
| 601 |
|
| 602 |
These two hook implementations work together to abort incremental-marked |
| 603 |
tests in a class. Here is a test module example: |
| 604 |
|
| 605 |
.. code-block:: python |
| 606 |
|
| 607 |
# content of test_step.py |
| 608 |
|
| 609 |
import pytest |
| 610 |
|
| 611 |
|
| 612 |
@pytest.mark.incremental |
| 613 |
class TestUserHandling: |
| 614 |
def test_login(self): |
| 615 |
pass |
| 616 |
|
| 617 |
def test_modification(self): |
| 618 |
assert 0 |
| 619 |
|
| 620 |
def test_deletion(self): |
| 621 |
pass |
| 622 |
|
| 623 |
|
| 624 |
def test_normal(): |
| 625 |
pass |
| 626 |
|
| 627 |
If we run this: |
| 628 |
|
| 629 |
.. code-block:: pytest |
| 630 |
|
| 631 |
$ pytest -rx |
| 632 |
=========================== test session starts ============================ |
| 633 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 634 |
rootdir: /home/sweet/project |
| 635 |
collected 4 items |
| 636 |
|
| 637 |
test_step.py .Fx. [100%] |
| 638 |
|
| 639 |
================================= FAILURES ================================= |
| 640 |
____________________ TestUserHandling.test_modification ____________________ |
| 641 |
|
| 642 |
self = <test_step.TestUserHandling object at 0xdeadbeef0001> |
| 643 |
|
| 644 |
def test_modification(self): |
| 645 |
> assert 0 |
| 646 |
E assert 0 |
| 647 |
|
| 648 |
test_step.py:11: AssertionError |
| 649 |
========================= short test summary info ========================== |
| 650 |
XFAIL test_step.py::TestUserHandling::test_deletion - previous test failed (test_modification) |
| 651 |
================== 1 failed, 2 passed, 1 xfailed in 0.12s ================== |
| 652 |
|
| 653 |
We'll see that ``test_deletion`` was not executed because ``test_modification`` |
| 654 |
failed. It is reported as an "expected failure". |
| 655 |
|
| 656 |
|
| 657 |
Package/Directory-level fixtures (setups) |
| 658 |
------------------------------------------------------- |
| 659 |
|
| 660 |
If you have nested test directories, you can have per-directory fixture scopes |
| 661 |
by placing fixture functions in a ``conftest.py`` file in that directory. |
| 662 |
You can use all types of fixtures including :ref:`autouse fixtures |
| 663 |
<autouse fixtures>` which are the equivalent of xUnit's setup/teardown |
| 664 |
concept. It's however recommended to have explicit fixture references in your |
| 665 |
tests or test classes rather than relying on implicitly executing |
| 666 |
setup/teardown functions, especially if they are far away from the actual tests. |
| 667 |
|
| 668 |
Here is an example for making a ``db`` fixture available in a directory: |
| 669 |
|
| 670 |
.. code-block:: python |
| 671 |
|
| 672 |
# content of a/conftest.py |
| 673 |
import pytest |
| 674 |
|
| 675 |
|
| 676 |
class DB: |
| 677 |
pass |
| 678 |
|
| 679 |
|
| 680 |
@pytest.fixture(scope="package") |
| 681 |
def db(): |
| 682 |
return DB() |
| 683 |
|
| 684 |
and then a test module in that directory: |
| 685 |
|
| 686 |
.. code-block:: python |
| 687 |
|
| 688 |
# content of a/test_db.py |
| 689 |
def test_a1(db): |
| 690 |
assert 0, db # to show value |
| 691 |
|
| 692 |
another test module: |
| 693 |
|
| 694 |
.. code-block:: python |
| 695 |
|
| 696 |
# content of a/test_db2.py |
| 697 |
def test_a2(db): |
| 698 |
assert 0, db # to show value |
| 699 |
|
| 700 |
and then a module in a sister directory which will not see |
| 701 |
the ``db`` fixture: |
| 702 |
|
| 703 |
.. code-block:: python |
| 704 |
|
| 705 |
# content of b/test_error.py |
| 706 |
def test_root(db): # no db here, will error out |
| 707 |
pass |
| 708 |
|
| 709 |
We can run this: |
| 710 |
|
| 711 |
.. code-block:: pytest |
| 712 |
|
| 713 |
$ pytest |
| 714 |
=========================== test session starts ============================ |
| 715 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 716 |
rootdir: /home/sweet/project |
| 717 |
collected 7 items |
| 718 |
|
| 719 |
a/test_db.py F [ 14%] |
| 720 |
a/test_db2.py F [ 28%] |
| 721 |
b/test_error.py E [ 42%] |
| 722 |
test_step.py .Fx. [100%] |
| 723 |
|
| 724 |
================================== ERRORS ================================== |
| 725 |
_______________________ ERROR at setup of test_root ________________________ |
| 726 |
file /home/sweet/project/b/test_error.py, line 1 |
| 727 |
def test_root(db): # no db here, will error out |
| 728 |
E fixture 'db' not found |
| 729 |
> available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory |
| 730 |
> use 'pytest --fixtures [testpath]' for help on them. |
| 731 |
|
| 732 |
/home/sweet/project/b/test_error.py:1 |
| 733 |
================================= FAILURES ================================= |
| 734 |
_________________________________ test_a1 __________________________________ |
| 735 |
|
| 736 |
db = <conftest.DB object at 0xdeadbeef0002> |
| 737 |
|
| 738 |
def test_a1(db): |
| 739 |
> assert 0, db # to show value |
| 740 |
^^^^^^^^^^^^ |
| 741 |
E AssertionError: <conftest.DB object at 0xdeadbeef0002> |
| 742 |
E assert 0 |
| 743 |
|
| 744 |
a/test_db.py:2: AssertionError |
| 745 |
_________________________________ test_a2 __________________________________ |
| 746 |
|
| 747 |
db = <conftest.DB object at 0xdeadbeef0002> |
| 748 |
|
| 749 |
def test_a2(db): |
| 750 |
> assert 0, db # to show value |
| 751 |
^^^^^^^^^^^^ |
| 752 |
E AssertionError: <conftest.DB object at 0xdeadbeef0002> |
| 753 |
E assert 0 |
| 754 |
|
| 755 |
a/test_db2.py:2: AssertionError |
| 756 |
____________________ TestUserHandling.test_modification ____________________ |
| 757 |
|
| 758 |
self = <test_step.TestUserHandling object at 0xdeadbeef0003> |
| 759 |
|
| 760 |
def test_modification(self): |
| 761 |
> assert 0 |
| 762 |
E assert 0 |
| 763 |
|
| 764 |
test_step.py:11: AssertionError |
| 765 |
========================= short test summary info ========================== |
| 766 |
FAILED a/test_db.py::test_a1 - AssertionError: <conftest.DB object at 0x7... |
| 767 |
FAILED a/test_db2.py::test_a2 - AssertionError: <conftest.DB object at 0x... |
| 768 |
FAILED test_step.py::TestUserHandling::test_modification - assert 0 |
| 769 |
ERROR b/test_error.py::test_root |
| 770 |
============= 3 failed, 2 passed, 1 xfailed, 1 error in 0.12s ============== |
| 771 |
|
| 772 |
The two test modules in the ``a`` directory see the same ``db`` fixture instance |
| 773 |
while the one test in the sister-directory ``b`` doesn't see it. We could of course |
| 774 |
also define a ``db`` fixture in that sister directory's ``conftest.py`` file. |
| 775 |
Note that each fixture is only instantiated if there is a test actually needing |
| 776 |
it (unless you use "autouse" fixtures which are always executed ahead of the first test |
| 777 |
executing). |
| 778 |
|
| 779 |
|
| 780 |
Post-process test reports / failures |
| 781 |
--------------------------------------- |
| 782 |
|
| 783 |
If you want to postprocess test reports and need access to the executing |
| 784 |
environment you can implement a hook that gets called when the test |
| 785 |
"report" object is about to be created. Here we write out all failing |
| 786 |
test calls and also access a fixture (if it was used by the test) in |
| 787 |
case you want to query/look at it during your post processing. In our |
| 788 |
case we just write some information out to a ``failures`` file: |
| 789 |
|
| 790 |
.. code-block:: python |
| 791 |
|
| 792 |
# content of conftest.py |
| 793 |
|
| 794 |
import os.path |
| 795 |
|
| 796 |
import pytest |
| 797 |
|
| 798 |
|
| 799 |
@pytest.hookimpl(wrapper=True, tryfirst=True) |
| 800 |
def pytest_runtest_makereport(item, call): |
| 801 |
# execute all other hooks to obtain the report object |
| 802 |
rep = yield |
| 803 |
|
| 804 |
# we only look at actual failing test calls, not setup/teardown |
| 805 |
if rep.when == "call" and rep.failed: |
| 806 |
mode = "a" if os.path.exists("failures") else "w" |
| 807 |
with open("failures", mode, encoding="utf-8") as f: |
| 808 |
# let's also access a fixture for the fun of it |
| 809 |
if "tmp_path" in item.fixturenames: |
| 810 |
extra = " ({})".format(item.funcargs["tmp_path"]) |
| 811 |
else: |
| 812 |
extra = "" |
| 813 |
|
| 814 |
f.write(rep.nodeid + extra + "\n") |
| 815 |
|
| 816 |
return rep |
| 817 |
|
| 818 |
|
| 819 |
if you then have failing tests: |
| 820 |
|
| 821 |
.. code-block:: python |
| 822 |
|
| 823 |
# content of test_module.py |
| 824 |
def test_fail1(tmp_path): |
| 825 |
assert 0 |
| 826 |
|
| 827 |
|
| 828 |
def test_fail2(): |
| 829 |
assert 0 |
| 830 |
|
| 831 |
and run them: |
| 832 |
|
| 833 |
.. code-block:: pytest |
| 834 |
|
| 835 |
$ pytest test_module.py |
| 836 |
=========================== test session starts ============================ |
| 837 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 838 |
rootdir: /home/sweet/project |
| 839 |
collected 2 items |
| 840 |
|
| 841 |
test_module.py FF [100%] |
| 842 |
|
| 843 |
================================= FAILURES ================================= |
| 844 |
________________________________ test_fail1 ________________________________ |
| 845 |
|
| 846 |
tmp_path = PosixPath('PYTEST_TMPDIR/test_fail10') |
| 847 |
|
| 848 |
def test_fail1(tmp_path): |
| 849 |
> assert 0 |
| 850 |
E assert 0 |
| 851 |
|
| 852 |
test_module.py:2: AssertionError |
| 853 |
________________________________ test_fail2 ________________________________ |
| 854 |
|
| 855 |
def test_fail2(): |
| 856 |
> assert 0 |
| 857 |
E assert 0 |
| 858 |
|
| 859 |
test_module.py:6: AssertionError |
| 860 |
========================= short test summary info ========================== |
| 861 |
FAILED test_module.py::test_fail1 - assert 0 |
| 862 |
FAILED test_module.py::test_fail2 - assert 0 |
| 863 |
============================ 2 failed in 0.12s ============================= |
| 864 |
|
| 865 |
you will have a "failures" file which contains the failing test ids: |
| 866 |
|
| 867 |
.. code-block:: bash |
| 868 |
|
| 869 |
$ cat failures |
| 870 |
test_module.py::test_fail1 (PYTEST_TMPDIR/test_fail10) |
| 871 |
test_module.py::test_fail2 |
| 872 |
|
| 873 |
Making test result information available in fixtures |
| 874 |
----------------------------------------------------------- |
| 875 |
|
| 876 |
.. regendoc:wipe |
| 877 |
|
| 878 |
If you want to make test result reports available in fixture finalizers |
| 879 |
here is a little example implemented via a local plugin: |
| 880 |
|
| 881 |
.. code-block:: python |
| 882 |
|
| 883 |
# content of conftest.py |
| 884 |
import pytest |
| 885 |
from pytest import StashKey, CollectReport |
| 886 |
|
| 887 |
phase_report_key = StashKey[dict[str, CollectReport]]() |
| 888 |
|
| 889 |
|
| 890 |
@pytest.hookimpl(wrapper=True, tryfirst=True) |
| 891 |
def pytest_runtest_makereport(item, call): |
| 892 |
# execute all other hooks to obtain the report object |
| 893 |
rep = yield |
| 894 |
|
| 895 |
# store test results for each phase of a call, which can |
| 896 |
# be "setup", "call", "teardown" |
| 897 |
item.stash.setdefault(phase_report_key, {})[rep.when] = rep |
| 898 |
|
| 899 |
return rep |
| 900 |
|
| 901 |
|
| 902 |
@pytest.fixture |
| 903 |
def something(request): |
| 904 |
yield |
| 905 |
# request.node is an "item" because we use the default |
| 906 |
# "function" scope |
| 907 |
report = request.node.stash[phase_report_key] |
| 908 |
if report["setup"].failed: |
| 909 |
print("setting up a test failed", request.node.nodeid) |
| 910 |
elif report["setup"].skipped: |
| 911 |
print("setting up a test skipped", request.node.nodeid) |
| 912 |
elif ("call" not in report) or report["call"].failed: |
| 913 |
print("executing test failed or skipped", request.node.nodeid) |
| 914 |
|
| 915 |
|
| 916 |
if you then have failing tests: |
| 917 |
|
| 918 |
.. code-block:: python |
| 919 |
|
| 920 |
# content of test_module.py |
| 921 |
|
| 922 |
import pytest |
| 923 |
|
| 924 |
|
| 925 |
@pytest.fixture |
| 926 |
def other(): |
| 927 |
assert 0 |
| 928 |
|
| 929 |
|
| 930 |
def test_setup_fails(something, other): |
| 931 |
pass |
| 932 |
|
| 933 |
|
| 934 |
def test_call_fails(something): |
| 935 |
assert 0 |
| 936 |
|
| 937 |
|
| 938 |
def test_fail2(): |
| 939 |
assert 0 |
| 940 |
|
| 941 |
and run it: |
| 942 |
|
| 943 |
.. code-block:: pytest |
| 944 |
|
| 945 |
$ pytest -s test_module.py |
| 946 |
=========================== test session starts ============================ |
| 947 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 948 |
rootdir: /home/sweet/project |
| 949 |
collected 3 items |
| 950 |
|
| 951 |
test_module.py Esetting up a test failed test_module.py::test_setup_fails |
| 952 |
Fexecuting test failed or skipped test_module.py::test_call_fails |
| 953 |
F |
| 954 |
|
| 955 |
================================== ERRORS ================================== |
| 956 |
____________________ ERROR at setup of test_setup_fails ____________________ |
| 957 |
|
| 958 |
@pytest.fixture |
| 959 |
def other(): |
| 960 |
> assert 0 |
| 961 |
E assert 0 |
| 962 |
|
| 963 |
test_module.py:7: AssertionError |
| 964 |
================================= FAILURES ================================= |
| 965 |
_____________________________ test_call_fails ______________________________ |
| 966 |
|
| 967 |
something = None |
| 968 |
|
| 969 |
def test_call_fails(something): |
| 970 |
> assert 0 |
| 971 |
E assert 0 |
| 972 |
|
| 973 |
test_module.py:15: AssertionError |
| 974 |
________________________________ test_fail2 ________________________________ |
| 975 |
|
| 976 |
def test_fail2(): |
| 977 |
> assert 0 |
| 978 |
E assert 0 |
| 979 |
|
| 980 |
test_module.py:19: AssertionError |
| 981 |
========================= short test summary info ========================== |
| 982 |
FAILED test_module.py::test_call_fails - assert 0 |
| 983 |
FAILED test_module.py::test_fail2 - assert 0 |
| 984 |
ERROR test_module.py::test_setup_fails - assert 0 |
| 985 |
======================== 2 failed, 1 error in 0.12s ======================== |
| 986 |
|
| 987 |
You'll see that the fixture finalizers could use the precise reporting |
| 988 |
information. |
| 989 |
|
| 990 |
.. _pytest current test env: |
| 991 |
|
| 992 |
``PYTEST_CURRENT_TEST`` environment variable |
| 993 |
-------------------------------------------- |
| 994 |
|
| 995 |
|
| 996 |
|
| 997 |
Sometimes a test session might get stuck and there might be no easy way to figure out |
| 998 |
which test got stuck, for example if pytest was run in quiet mode (:option:`-q`) or you don't have access to the console |
| 999 |
output. This is particularly a problem if the problem happens only sporadically, the famous "flaky" kind of tests. |
| 1000 |
|
| 1001 |
``pytest`` sets the :envvar:`PYTEST_CURRENT_TEST` environment variable when running tests, which can be inspected |
| 1002 |
by process monitoring utilities or libraries like :pypi:`psutil` to discover which test got stuck if necessary: |
| 1003 |
|
| 1004 |
.. code-block:: python |
| 1005 |
|
| 1006 |
import psutil |
| 1007 |
|
| 1008 |
for pid in psutil.pids(): |
| 1009 |
environ = psutil.Process(pid).environ() |
| 1010 |
if "PYTEST_CURRENT_TEST" in environ: |
| 1011 |
print(f'pytest process {pid} running: {environ["PYTEST_CURRENT_TEST"]}') |
| 1012 |
|
| 1013 |
During the test session pytest will set ``PYTEST_CURRENT_TEST`` to the current test |
| 1014 |
:ref:`nodeid <nodeids>` and the current stage, which can be ``setup``, ``call``, |
| 1015 |
or ``teardown``. |
| 1016 |
|
| 1017 |
For example, when running a single test function named ``test_foo`` from ``foo_module.py``, |
| 1018 |
``PYTEST_CURRENT_TEST`` will be set to: |
| 1019 |
|
| 1020 |
#. ``foo_module.py::test_foo (setup)`` |
| 1021 |
#. ``foo_module.py::test_foo (call)`` |
| 1022 |
#. ``foo_module.py::test_foo (teardown)`` |
| 1023 |
|
| 1024 |
In that order. |
| 1025 |
|
| 1026 |
.. note:: |
| 1027 |
|
| 1028 |
The contents of ``PYTEST_CURRENT_TEST`` is meant to be human readable and the actual format |
| 1029 |
can be changed between releases (even bug fixes) so it shouldn't be relied on for scripting |
| 1030 |
or automation. |
| 1031 |
|
| 1032 |
.. _freezing-pytest: |
| 1033 |
|
| 1034 |
Freezing pytest |
| 1035 |
--------------- |
| 1036 |
|
| 1037 |
If you freeze your application using a tool like |
| 1038 |
`PyInstaller <https://pyinstaller.readthedocs.io>`_ |
| 1039 |
in order to distribute it to your end-users, it is a good idea to also package |
| 1040 |
your test runner and run your tests using the frozen application. This way packaging |
| 1041 |
errors such as dependencies not being included into the executable can be detected early |
| 1042 |
while also allowing you to send test files to users so they can run them in their |
| 1043 |
machines, which can be useful to obtain more information about a hard to reproduce bug. |
| 1044 |
|
| 1045 |
Fortunately recent ``PyInstaller`` releases already have a custom hook |
| 1046 |
for pytest, but if you are using another tool to freeze executables |
| 1047 |
such as ``cx_freeze`` or ``py2exe``, you can use ``pytest.freeze_includes()`` |
| 1048 |
to obtain the full list of internal pytest modules. How to configure the tools |
| 1049 |
to find the internal modules varies from tool to tool, however. |
| 1050 |
|
| 1051 |
Instead of freezing the pytest runner as a separate executable, you can make |
| 1052 |
your frozen program work as the pytest runner by some clever |
| 1053 |
argument handling during program startup. This allows you to |
| 1054 |
have a single executable, which is usually more convenient. |
| 1055 |
Please note that the mechanism for plugin discovery used by pytest (:ref:`entry |
| 1056 |
points <pip-installable plugins>`) doesn't work with frozen executables so pytest |
| 1057 |
can't find any third party plugins automatically. To include third party plugins |
| 1058 |
like ``pytest-timeout`` they must be imported explicitly and passed on to pytest.main. |
| 1059 |
|
| 1060 |
.. code-block:: python |
| 1061 |
|
| 1062 |
# contents of app_main.py |
| 1063 |
import sys |
| 1064 |
|
| 1065 |
import pytest_timeout # Third party plugin |
| 1066 |
|
| 1067 |
if len(sys.argv) > 1 and sys.argv[1] == "--pytest": |
| 1068 |
import pytest |
| 1069 |
|
| 1070 |
sys.exit(pytest.main(sys.argv[2:], plugins=[pytest_timeout])) |
| 1071 |
else: |
| 1072 |
# normal application execution: at this point argv can be parsed |
| 1073 |
# by your argument-parsing library of choice as usual |
| 1074 |
... |
| 1075 |
|
| 1076 |
|
| 1077 |
This allows you to execute tests using the frozen |
| 1078 |
application with standard ``pytest`` command-line options: |
| 1079 |
|
| 1080 |
.. code-block:: bash |
| 1081 |
|
| 1082 |
./app_main --pytest --verbose --tb=long --junit=xml=results.xml test-suite/ |