I've got the following project tree:
SomeDir
|- script.py
|- TestDir
| |- test.py
script.py is designed to be called in CLI and contains several classes: notably one that does the actual job and one that is a class exit_codes(Enum) that defines exit codes.
test.py is to be used by pytest and typical tests consist of calling script.py with arguments that are used to initialize a working class object. This object then does some processing and calls sys.exit(<some enumerator>.value), using the exit codes in the Enum class.
In the test I'm giving the command line to subprocess.run and assert its returncode against the desired exit code.
Thus test.py and script.py should use the same code and I'd like to do something like
from script import exit_codes
but without additional actions script cannot be found.
There are a few possibilities that works.
The typical workaround is sys.path.append using .. from __file__ (Importing files from different folder).
As suggested in comments I can also save sys.path before editing it and importing my symbols and then restore it's original value.
Eventually, as suggested in a first answer I can make script.py a module by adding __init__.py in its directory, but then I can only run pytest from this directory.
With respect to pytest, it seems that a pytest.ini file can also be used but I didn't experiment with it so far.
It could also be a combination of these technics.
What is considered as the best practice?
test.pyfrom script import exit_codesgivesModuleNotFoundError: No module named 'script'sys.paththenfrom script import exit_codesthen restoresys.pathto previous value