gpt4 book ai didi

python - 为什么 Python 的 unittest 在 WSL bash 中给出 "ImportError: Import by filename is not supported."?

转载 作者:可可西里 更新时间:2023-11-01 13:51:05 28 4
gpt4 key购买 nike

在 Windows 上,我有一个 Python 代码库,在子文件夹中有一些单元测试(基于 unittest)。

我使用 Windows 命令提示符切换到文件夹并使用 python -m unittest subfolder/tests.py 运行所有测试。然后检测并运行文件中的测试。

当我尝试在适用于 Linux bash shell 的 Windows 子系统中执行相同操作时,我收到以下堆栈跟踪错误:

Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/lib/python2.7/unittest/__main__.py", line 12, in <module>
main(module=None)
File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__
self.parseArgs(argv)
File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs
self.createTests()
File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests
self.module)
File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
module = __import__('.'.join(parts_copy))
ImportError: Import by filename is not supported.

为什么在WSL bash中会出现这个错误,而在cmd中却不会?我怎样才能解决这个问题以在两者中工作?

PS - 这是上面提到的 tests.py 的示例:

import unittest
from target import target

class tests(unittest.TestCase):

def test_pi(self):
expected = 3.1415926
actual = truncate(target.pi(), 7)
self.assertEqual(actual, expected)

def truncate(num, digits):
return int(num * 10**digits) / 10**digits

if __name__ == '__main__':
unittest.main()

最佳答案

首先尝试将目录更改为 <test_cases_dir>然后运行命令不带 .py 后缀

来自 python docs

python -m unittest test_module.TestClass

在你的例子中:

cd subfolder
python -m unittest tests.tests

(仅限爱好者)从 unittest 实现,无法导入相对路径:

def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.

The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.

The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
. . .

关于python - 为什么 Python 的 unittest 在 WSL bash 中给出 "ImportError: Import by filename is not supported."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48605957/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com