'How to import a python package in pytest using relative import

my-proj
├── src
│   ├── main.py
└── test
│   ├── my_tests.py

I have the above directory structure for my python project. I have some unittests in the my_test.py and when I run them, I get the following error using following imports:

import os, sys
import json
from ..src import main
import unittest

running like this from my-proj/test/ directory: python my_tests.py

from ..src import main

ValueError: attempted relative import beyond top-level package

Apologies if this was answered but i tried a few things, even included __ main __.py in both directories (src and test) but didn't work. Any idea how I can get this to work? It is a FLASK application in python (main.py)



Solution 1:[1]

__main__.py has no effect on packages, only so you can run python -m pkg. You're probably thinking of __init__.py, which makes a directory a package.

In general, it'd be better to store tests in the directory structure alongside your source files, not in a separate structure. That way pytest src/, as discussed e.g. here will just work. (You may need to plant a conftest.py in src/ to have Py.test recognize it as a source root and fix up things accordingly.)

Another way is to make your package properly installable (setup.py, etc.), then install it in develop mode using pip install -e ..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKX