我使用下面的方法在python unittest中自动生成案例。
import unittest
class Tests(unittest.TestCase):
def check(self, i):
self.assertNotEquals(0, i)
for i in [0, 1, 2]:
def ch(i):
return lambda self: self.check(i)
setattr(Tests, "test_%d" % i, ch(i))
if __name__ == "__main__":
unittest.main()
当“python test.py”一起运行所有案例时,它运行良好。 但无法运行特定情况,例如“python test.py Tests.test_0”
Traceback (most recent call last):
File "test.py", line 12, in <module>
unittest.main()
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 128, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python2.7/unittest/loader.py", line 109, in loadTestsFromName
return self.suiteClass([parent(obj.__name__)])
File "/usr/lib/python2.7/unittest/case.py", line 191, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class '__main__.Tests'>: <lambda>
任何人都可以提供帮助吗?
答案 0 :(得分:0)
显示(来自错误消息)并且仔细阅读unittest
的来源,测试运行器获取对方法的引用,然后使用方法的__name__
属性来确定哪个方法跑。这有点傻(毕竟,我们已经选择了对方法的引用!),但它在代码简单性方面确实有一些好处。快速解决方法是确保在lambda函数上设置名称:
import unittest
class Tests(unittest.TestCase):
def check(self, i):
self.assertNotEquals(0, i)
for i in [0, 1, 2]:
def ch(i):
return lambda self: self.check(i)
f = ch(i)
name = "test_%d" % i
f.__name__ = name
setattr(Tests, name, f)
if __name__ == "__main__":
unittest.main()
现在一切正常:
mgilson$ python test.py Tests.test_0
F
======================================================================
FAIL: test_0 (__main__.Tests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 13, in <lambda>
return lambda self: self.check(i)
File "test.py", line 5, in check
self.assertNotEquals(0, i)
AssertionError: 0 == 0
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
和
mgilson$ python test.py Tests.test_1
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
请注意,这似乎是一个修复过的错误。在current HEAD中,我们可以看到名称是从字符串中解析出来的,而不是version which I have(显然是你做的),从对象(函数)中获取名称是运行