How can I structure my folders to test my code:

Deadly 提交于 2021-01-29 07:38:37

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/64623668/how-can-i-structure-my-folders-to-test-my-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!