Tests should ideally be done in a "clean environment".
So instead of running script tests with relative imports, one solution is to write a setup.py
to install your project locally as a module.
Then you can write separate tests where you can do from mymodule import script1.script1
.
If you go that path you need to decide on a project structure. There is no best structure out there (see here). So as an example, here is my typical structure:
├── src/
│ ├── script1/
│ │ └── script1.py
│ └── script2/
│ └── script2.py
├── tests/
│ ├── test_script1.py
│ └── test_script2.py
└── venv/
and a setup.py like this:
import os
from setuptools import find_packages, setup
# load desc from readme
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="mymodule",
version="0.0.1",
author="you",
author_email="<you@you.com>",
description=("short description"),
license="<none>",
packages=find_packages("src"),
package_dir={"": "src"},
long_description=read("README.md"),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Topic :: Utilities",
# "License :: OSI Approved :: MIT License",
],
install_requires=[],
)
with this example you can now run python setup.py install
to install mymodule and then run all tests with pytest tests
.
This not only tests your tests but also checks that your package ist correctly installed/installable.
When using a virtual environment the setup.py
will install here instead of the full system.
Finally you can use relative imports in all of your files since you will have a top level module "mymodule" and your error will disappear.
PS: If you dont like to import script1.script1
you can write __init__.py
files in the directories to be able to do from mymodule import script1
or even from mymodule import ClassFromScript1