我尝试使用文件夹结构来组织我的 Python 项目。当我需要进行测试时,我使用类似以下的东西。
.
|-- src
| |-- b.py
| `-- main.py
`-- tests
`-- test_main.py
Run Code Online (Sandbox Code Playgroud)
这种方法有一个大问题。main.py如果正在导入,Pytest 将不会运行b.py。
到目前为止,我已经尝试将空__init__.py文件单独或一起放置在src和文件夹中,但其中任何一个似乎都有效。tests
在我看来,这是一个非常标准的项目,但我无法在网上找到解决方案。我应该使用不同的文件夹结构吗?有没有推荐的方法在此类项目中使用 pytest?
这是文件的内容:
# b.py
def triplicate(x):
return x * 3
Run Code Online (Sandbox Code Playgroud)
# main.py
from b import triplicate
def duplicate(x):
return x * 2
Run Code Online (Sandbox Code Playgroud)
# test_main.py
from src.main import duplicate
def test_duplicate():
assert duplicate(2) == 4
Run Code Online (Sandbox Code Playgroud)
这是我运行 pytest 时遇到的错误:
==================================================================================================== ERRORS ====================================================================================================
_____________________________________________________________________________________ ERROR collecting tests/test_main.py ______________________________________________________________________________________
ImportError while importing test module 'C:\Users\edwar\test_pytest\tests\test_main.py'. …Run Code Online (Sandbox Code Playgroud) python directory-structure working-directory pytest python-3.x