0

I'm working on a project and would like to write some unit tests for my code. Here is a minimal example of my project structure

myproject
└── scripts
    ├── tests
    │   └── test_func.py
    └── tools
        ├── __init__.py
        └── func.py

func.py contains

def f(x):
    return 0

and test_func.py contains

import pytest 
from ..tools import f

def test_f():

    assert f(1)==0

When I try to run my tests with pytest pytest scripts/tests/test_func.py, I get the following error ImportError: attempted relative import with no known parent package.

Clearly, there is a problem with the structure of my project. There is a solution here which involves adding something to my path but I'd rather not do that if there is a way I can just structure my project to avoid this instead.

Demetri Pananos
  • 6,770
  • 9
  • 42
  • 73

1 Answers1

0

You need to add (empty) __init__.py files to the directories scripts/ and scripts/tests/. These files provide the scaffolding that lets import find modules, especially when using relative imports.

The __init__.py files are required to make Python treat directories containing the file as packages.

From https://docs.python.org/3/tutorial/modules.html

Josh Karpel
  • 2,110
  • 2
  • 10
  • 21