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