I'm using pytest. NB W10.
I will be running my app by going > python src/core
. "core" is my central module, with a __main__.py
file.
For that reason I'm putting my "tests" directory in [project root]/src/core.
I have a test file test_xxx.py. In it I try to import __main__
:
import __main__
...
def test_xxxxx():
print(f'main {__main__} type {type(__main__)}')
This prints the following:
main <module '__main__' from 'D:\\apps\\Python\\virtual_envs\\doc_indexer v2.0.0\\Scripts\\pytest.exe\\__main__.py'> type <class 'module'>
... in other words, it is importing not my local __main__.py
from my local "core" module, but pytest's own __main__
from its module. So far so understandable. Then I look at sys.path:
path: D:\My Documents\software projects\EclipseWorkspace\doc_indexer\src\core\tests
path: D:\My Documents\software projects\EclipseWorkspace\doc_indexer\src\core
path: D:\apps\Python\virtual_envs\doc_indexer v2.0.0\Scripts\pytest.exe
path: D:\apps\Python\PyQt5
...
Now I'm scratching my head, not for the first time with pytest. This ...src\core path is listed before ...Scripts\pytest.exe. Why would pytest identify its own __main__.py
and import it, before importing __main__.py
from a path which precedes it?
I've also tried various experiments with importlib
. Nothing seems to work.
So generally, is there any way to actually import that file ...src/core/__main__py
?
I realise that this file should do minimal things before handing on to another file, but for completeness I'd just like to test that main()
does in fact do that. Is there any way to run __main__.main()
in a test?
Every Python program creates a module named __main__
on startup, based on the script being executed.
As a result, import __main__
always finds a module by that name, meaning it does not need to define one from, say, a file named __main__.py
. In your case, you executed pytest
(which is primarily a simple wrapper around import pytest; pytest.console_main()
. (The script pytest
, stored in a directory on your search path, is separate from a module defined by pytest.py
in your Python library.)
One solution would be to make sure you can import __main__.py
using another package, so that somepackage.__main__
is distinct from __main__
.
However, __main__.py
is never intended to be imported as a module. It's the file that defines a script when you try to execute a directory or an archive file as a script. If it contains code that needs to be tested, I would recommend factoring that into a separate module with __main__.py
itself imports.