I'm new to pytest and python. My project structure is :
projroot/
|-src/
|-a.py
|-test/
|-test_a.py
and test_a.py is:
from ..src import a
def test_a():
pass
Then run pytest
under projroot
:
projroot>pytest
And always there is the error info: E ImportError: attempted relative import with no known parent package
.
Python verison: 3.8 on windows 10 x64.
I read a lot articles and blogs and official suggestions, but still failed to figure out. Help me, please!
The beyond top level package error in relative import error occurs when you use a relative import without the file you are importing being part of a package. To fix this error, make sure that any directories that you import relatively are in their own packages.
A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit. Implicit relative imports have been deprecated in Python 3, so I won't be covering them here.
I found I must add __init__.py
in test
and projroot
. __init__.py
in src
is not necessary.
And pytest
could run correctly in 3 folders:
# parent folder of project root
C:\>pytest projroot
# project root
C:\>cd projroot
C:\projroot>pytest
# test folder
C:\projroot>cd test
C:\projroot\test>pytest
By including a setup.py file in root directory and init.py in every folder worked for me and for importing a package inside any file just give that package location from parent directory
setup.py
from setuptools import setup, find_packages
setup(name="PACKAGENAME", packages=find_packages())
projroot/
|-__init__.py
|-setup.py
|-src/
|-a.py
|-__init__.py
|-test/
|-test_a.py
|-__init__.py
from src import a
def test_a():
pass
Reference https://docs.pytest.org/en/6.2.x/goodpractices.html
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