3
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)

0

2 Answers 2

1

You can also write the following in my_tests.py

import sys
sys.path.append("../src/")
import main
Sign up to request clarification or add additional context in comments.

Comments

0

__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 ..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.