I have a project, which consists out of source code and test code. The source code is stored in one directory, and my tests are stored in another.
root
|- src
| |- pkg
| | | - __init__.py
| | | - src1.py
| | | - src2.py
|- test
| |- tests_for_pkg
| | | - __init__.py
| | | - first_test.py
| | | - second_test.py
When I'm running my tests, I am required to import all of my source code in the _test.py
files.
from pkg.src1 import src1
from pkg.src2 import src2
I would like to run all of my tests in one go using python -m pytest <tests>
or running a script, but I keep getting errors about my imports.
I had issues with my Python path before in my Eclipse IDE, so I opted to use relative paths and add them as an external library to the Python path based on a relative path in my folder structure.
For example, my include path would be:
../src/pkg
How can I implement such a relative path in the Python command line/as a Python script?
EDIT: Using the provided links, I was able to get my test working by adding a conftest.py
file and appending the location of my code.
However, my actual project has a massive source tree as follows:
root
| - projectdir
| | - projectone
| | | - datedir
| | | | - trunk
| | | | | - sd
| | | | | | - code
| | | | | | | src
| | | | | | | - pkg
| | | | | | | | - __init__.py
| | | | | | | | - src1.py
| | | | | | | | - src2.py
| | | | | | - model
| | | | | | | - testdir
| | | | | | | | - testware
| | | | | | | | | - unittest_pkg
| | | | | | | | | | - test
| | | | | | | | | | | - tests_for_pkg
| | | | | | | | | | | | - first_test.py
| | | | | | | | | | | | - second_test.py
conftest.py
first source tree (allows me to run my tests from the test dir):
import sys
sys.path.append('..\..\src')
conftest.py
second source tree (can't run any tests from any dir):
import sys
sys.path.append('..\..\..\..\..\..\..\code\src')
When I use the exact same method as before, it doesn't work. Does conftest.py
have a limit on how far it can search for the src
directory?
EDIT: Solved with help from this question.
I ended up making a batch script which looks for any files ending in test.py
and runs them.
@echo off
for /r %%i in (*test.py) do (
setlocal
set PYTHONPATH=../../../src/pkg
python -m pytest --junitxml=%%~pi/JUnit_%%~ni.xml %%i
endlocal
)
@RD /S /Q .pytest_cache
Why not add current directory to PYTHONPATH
before running pytest?
export PYTHONPATH="$PYTHONPATH:$PWD"
Alternatively, you can add directory to PYTHONPATH in test .py
by:
import sys
import os
sys.path.append(os.path.abspath('../src/pkg'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With