Python unittest发现无法导入源码
Python unittest discovery can not import source code
我正在使用 Python 集成在 VSCode 中的单元测试进行测试。我有这样的目录
project_root/
src/
module/
__init__.py
a.py
test/
module/
__init__.py
test_a.py
test_a.py
有导入 from module.a import SomeClass
我有参数
"-v",
"-s",
"./test",
"-p",
"test*.py"
当 运行 测试发现失败并引发 ModuleNotFound
或 Can not import
模块或 类 in a.py
PS:我在settings.json
中设置了PYTHONPATH
,代码分析和程序启动都正常。但它似乎对 unittest
插件没有帮助。一个问题是 src
、test
都有名为 module
的模块,我不确定这是否重要。
如何让它发挥作用?
更新:似乎是名称冲突问题,unittest_discovery 无法处理。在我将 args 更改为 -s ./test/module
之后,它可以导入 src 模块。
您需要在 .env
文件中配置 PYTHONPATH
。
An example of when to use PYTHONPATH would be if you have source code
in a src folder and tests in a tests folder. When running tests,
however, those tests can't normally access modules in src unless you
hard-code relative paths.
To solve this problem, you could add the path to src to PYTHONPATH by
creating an .env file within your VS Code workspace.
PYTHONPATH=src
因为
When the terminal settings are used, PYTHONPATH affects any tools that
are run within the terminal by a user, as well as any action the
extension performs for a user that is routed through the terminal such
as debugging. However, in this case when the extension is performing
an action that isn't routed through the terminal, such as the use of a
linter or formatter, then this setting will not have an effect on
module look-up.
详情请参考official docs
我正在使用 Python 集成在 VSCode 中的单元测试进行测试。我有这样的目录
project_root/
src/
module/
__init__.py
a.py
test/
module/
__init__.py
test_a.py
test_a.py
有导入 from module.a import SomeClass
我有参数
"-v",
"-s",
"./test",
"-p",
"test*.py"
当 运行 测试发现失败并引发 ModuleNotFound
或 Can not import
模块或 类 in a.py
PS:我在settings.json
中设置了PYTHONPATH
,代码分析和程序启动都正常。但它似乎对 unittest
插件没有帮助。一个问题是 src
、test
都有名为 module
的模块,我不确定这是否重要。
如何让它发挥作用?
更新:似乎是名称冲突问题,unittest_discovery 无法处理。在我将 args 更改为 -s ./test/module
之后,它可以导入 src 模块。
您需要在 .env
文件中配置 PYTHONPATH
。
An example of when to use PYTHONPATH would be if you have source code in a src folder and tests in a tests folder. When running tests, however, those tests can't normally access modules in src unless you hard-code relative paths.
To solve this problem, you could add the path to src to PYTHONPATH by creating an .env file within your VS Code workspace.
PYTHONPATH=src
因为
When the terminal settings are used, PYTHONPATH affects any tools that are run within the terminal by a user, as well as any action the extension performs for a user that is routed through the terminal such as debugging. However, in this case when the extension is performing an action that isn't routed through the terminal, such as the use of a linter or formatter, then this setting will not have an effect on module look-up.
详情请参考official docs