Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pytest always says " ImportError: attempted relative import with no known parent package"

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 pytestunder 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!

like image 930
Jacques Yang Avatar asked Mar 21 '20 15:03

Jacques Yang


People also ask

How do I fix attempted relative import beyond top level package?

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.

What is relative import in Python?

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.


2 Answers

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
like image 194
Jacques Yang Avatar answered Sep 19 '22 08:09

Jacques Yang


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

like image 36
MMS Avatar answered Sep 20 '22 08:09

MMS