uri*_*rig 4 python windows bash python-unittest
在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.
Run Code Online (Sandbox Code Playgroud)
为什么在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()
Run Code Online (Sandbox Code Playgroud)
小智 12
尝试先将目录更改为<test_cases_dir>,然后运行不带 .py后缀的命令
python -m unittest test_module.TestClass
Run Code Online (Sandbox Code Playgroud)
在你的例子中:
cd subfolder
python -m unittest tests.tests
Run Code Online (Sandbox Code Playgroud)
(仅限爱好者)来自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:
. . .
Run Code Online (Sandbox Code Playgroud)