I'm trying to run coverage with the unittest module on my python project. The project has the following structure:
project/
src/
__init__.py
foo1.py
foo2.py
tests/
__init__.py
data.py
test_foo1.py
test_foo2.py
.venv/
.venv is the virtual environment where the project dependencies are installed as well as the coverage module.
The file "data.py" has some of the datasets used in the testing and is imported into the test file, as well as the module being tested. These imports are done using the following code:
#test_foo1.py
import unittest
from .data import *
from src.foo1 import ClassFoo #Code to be tested
Just running the tests works fine with the following command (ubuntu terminal):
~/project $ sudo .venv/bin/python -m unittest tests/test_foo1.py
The problem is when I try run coverage with the command
~/project $ sudo .venv/bin/coverage run tests/test_foo1.py
It starts giving me some import errors such as:
Traceback (most recent call last):
File "tests/foo1.py", line 3, in <module>
from .data import *
ImportError: attempted relative import with no known parent package
When I take the '.' out from .data (which is how it works with just unittest) it seems to fix this problem and gives the following problem:
Traceback (most recent call last):
File "tests/test_foo1.py", line 4, in <module>
from src.foo1 import ClassFoo
ModuleNotFoundError: No module named 'src'
Can someone explain why these exceptions occour with coverage but not with unittest and how I can make it so that these tests run normally on both? Do I have to change the import syntax when using coverage?