I was going to post this question in code review because rather than a solution I wanted for python experts to check my code. But while preparing the code I found some related issue so I finally decided to ask it here since it is not more just a code check
My question is how does pytest finds modules to test? Let me explain
Situation 1 First I have this code structure
|
|-tests
| |----test_sum.py
|
|--script_to_test.py
test_sum.py
import script_to_test
def test_sum():
d=script_to_test.sum(6,5)
assert d==11
script_to_test.py
def sum(a,b):
return a+b
If I create a virtual environment and install pytest there, or if I use a conda environment with pytest installed I can do
pytest
and I will get
pytest
====================================================================== test session starts ======================================================================
platform linux -- Python 3.9.16, pytest-7.2.2, pluggy-1.0.0
rootdir: /home/me/pytestExample
collected 1 item
tests/test_sum.py . [100%]
======================================================================= 1 passed in 0.01s =======================================================================
Situation 2
If I add a file pytest.ini
in the root
[pytest]
python_files = test_*
python_classes = *Tests
python_functions = test_*
pytest will not work anymore and I will get
pytest
========================================================= test session starts ==========================================================
platform linux -- Python 3.9.16, pytest-7.2.2, pluggy-1.0.0
rootdir: /home/me/pytestExample, configfile: pytest.ini
collected 0 items / 1 error
================================================================ ERRORS ================================================================
__________________________________________________ ERROR collecting tests/test_sum.py __________________________________________________
ImportError while importing test module '/home/me/pytestExample/tests/test_sum.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../../../.pyenv/versions/3.9.16/lib/python3.9/importlib/__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests/test_sum.py:1: in <module>
import script_to_test
E ModuleNotFoundError: No module named 'script_to_test'
======================================================= short test summary info ========================================================
ERROR tests/test_sum.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
=========================================================== 1 error in 0.07s ===========================================================
Now, I can solve this already, but the purpose of this question is to know why it fails to work when a pytest.ini
is added? and why does it work in the first place when that file is not present?