@@ -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,50 @@ 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
+ # This method above will return True even if your code is not actually running from within a pytest run
440
+ # as there is a pytest import in your code flow
441
+
442
+ This is a bit long but a robust way to do it:
443
+
444
+ .. code-block :: python
445
+
446
+ # content of your_module.py
447
+
448
+
449
+ _called_from_test_by_pytest = False
450
+
451
+ .. code-block :: python
452
+
453
+ # content of conftest.py
454
+
455
+
456
+ def pytest_configure (config ):
457
+ your_module._called_from_test_by_pytest = True
458
+
459
+ and then check for the ``your_module._called_from_test_by_pytest `` flag:
460
+
461
+ .. code-block :: python
462
+
463
+ if your_module._called_from_test_by_pytest:
464
+ # called from within a test run
465
+ ...
466
+ else :
467
+ # called "normally"
468
+ ...
469
+
424
470
accordingly in your application.
425
471
426
472
Adding info to test report header
0 commit comments