@@ -405,7 +405,9 @@ Detect if running from within a pytest run
405
405
Usually it is a bad idea to make application code
406
406
behave differently if called from a test. But if you
407
407
absolutely must find out if your application code is
408
- running from a test you can do something like this:
408
+ running from a test, you can follow one of the two ways listed below.
409
+
410
+ This is a simple way to do it:
409
411
410
412
.. code-block :: python
411
413
@@ -421,6 +423,51 @@ running from a test you can do something like this:
421
423
# called "normally"
422
424
...
423
425
426
+ This works great, but you should be aware that there is an issue with it. If there is a pytest import anywhere
427
+ in your code flow, ``"pytest" in sys.modules `` will return True even if your code is not actually running from within a pytest run.
428
+
429
+ .. code-block :: python
430
+
431
+ import sys
432
+
433
+ import pytest # unused anywhere in your code
434
+
435
+
436
+ def is_called_from_test_by_pytest ():
437
+ return " pytest" in sys.modules
438
+
439
+
440
+ # This method above will return True even if your code is not actually running from within a pytest run
441
+ # as there is a pytest import in your code flow
442
+
443
+ This is a bit long but a robust way to do it:
444
+
445
+ .. code-block :: python
446
+
447
+ # content of your_module.py
448
+
449
+
450
+ _called_from_test_by_pytest = False
451
+
452
+ .. code-block :: python
453
+
454
+ # content of conftest.py
455
+
456
+
457
+ def pytest_configure (config ):
458
+ your_module._called_from_test_by_pytest = True
459
+
460
+ and then check for the ``your_module._called_from_test_by_pytest `` flag:
461
+
462
+ .. code-block :: python
463
+
464
+ if your_module._called_from_test_by_pytest:
465
+ # called from within a test run
466
+ ...
467
+ else :
468
+ # called "normally"
469
+ ...
470
+
424
471
accordingly in your application.
425
472
426
473
Adding info to test report header
0 commit comments