在Windows上,我有一个Python代码库,在子文件夹中有一些单元测试(基于unittest
)。
我使用Windows命令提示符更改为该文件夹并使用python -m unittest subfolder/tests.py
运行所有测试。然后检测并运行文件中的测试。
当我尝试在Windows子系统for Linux bash shell中执行相同操作时,堆栈跟踪出现以下错误:
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()
答案 0 :(得分:11)
尝试首先将目录更改为<test_cases_dir>
,然后运行命令,不带 .py后缀
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:
. . .