python-3.x 解析测试中的系统路径

zsohkypk  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(72)

我的代码结构如下:

<root>
+-- src
|    +- module1.py
|    |
|    +- module2.py
|    |
|    + __init__.py
|
+-- test
     +- test1
     |    +- test1.py
     |    |
     |    + __init__.py
     |
     +- test2.py
     |
     +- __init__.py

字符串
test/__init__.py包含以下内容:

import sys
sys.path.append(".")


test/test1/__init__.py包含:

import sys
sys.path.append("..")


test1.pytest2.py都包含from src import module1, module2
当我运行pytest test1时,它工作正常,但当我只运行pytest时,test 2的import语句失败,因为它无法解析src
我试过修改test/__init__.py,在sys.path后面加上“..”,但没有用。
另外,我已经尝试了import语句作为from ..src import module1, module2-它也不工作。
在这种情况下,如何解决系统路径?

lqfhib0f

lqfhib0f1#

我的经验告诉我不要在测试中修复sys.path:不应该关心这个。最好在这些测试之外控制sys.path。这里有一种方法。我将保持相同的文件结构,然后
1.删除测试目录中的所有__init__.py文件

find test -name __init__.py -delete

字符串
1.发出pytest命令:

PYTHONPATH=. pytest


这样,你的文件结构就简单多了,测试并不关心模块在哪里,他们只是导入它们。
另一种方法是安装python-path插件,该插件为测试管理PYTHONPATH。

相关问题