【发布时间】:2015-05-28 14:23:31
【问题描述】:
我要做的是对一个函数执行数百个单元测试,我可以从字典中派生这些单元测试。不幸的是,我不能使用任何现有的包进行参数化测试(如鼻子),所以我试图获得自己的解决方案。
我对以下示例代码的意图是创建 3 个类(每个测试一个),它们将存在于全局范围内,以便单元测试可以选择它并运行相应的测试。
tests = [
{'text': 'text1fdskla3fsda4',
'result': [1, 3, 4],
},
{'text': 'fdsg45tg5b',
'result': [4, 5, 5,5 ],
},
{'text': 'fsddf4',
'result': [4, 2],
}
]
def evaluate(text):
out = []
for char in text:
if char.isdigit():
out.append(int(char))
return out
class TestMeta(type):
def __new__(cls, name, bases, attrs):
name = str(test['text'])
return type.__new__(cls, name, (unittest.TestCase,), attrs)
for test in tests:
class T(object):
__metaclass__ = TestMeta
def testOne(self):
self.assertEqual(test['result'], evaluate(test['text']))
globals()[(test['text'])] = copy.deepcopy(T)
unittest.main()
当我运行上面的代码时,我得到了四个单元测试,这比预期的多一个,但最重要的是,我创建的类似乎总是相同的,而不是每个单元测试的输出(即使我实际上为每个设置了不同的名称和参数):
======================================================================
FAIL: testOne (__main__.fsddf4)
----------------------------------------------------------------------
Traceback (most recent call last):
File "ble.py", line 45, in testOne
self.assertEqual(test['result'], evaluate(test['text']))
AssertionError: [4, 2] != [4]
======================================================================
FAIL: testOne (__main__.fdsg45tg5b)
----------------------------------------------------------------------
Traceback (most recent call last):
File "ble.py", line 45, in testOne
self.assertEqual(test['result'], evaluate(test['text']))
AssertionError: [4, 2] != [4]
======================================================================
FAIL: testOne (__main__.fsddf4)
----------------------------------------------------------------------
Traceback (most recent call last):
File "ble.py", line 45, in testOne
self.assertEqual(test['result'], evaluate(test['text']))
AssertionError: [4, 2] != [4]
======================================================================
FAIL: testOne (__main__.text1fdskla3fsda4)
----------------------------------------------------------------------
Traceback (most recent call last):
File "ble.py", line 45, in testOne
self.assertEqual(test['result'], evaluate(test['text']))
AssertionError: [4, 2] != [4]
----------------------------------------------------------------------
Ran 4 tests in 0.002s
FAILED (failures=4)
deepcopy 试图获得不同的输出,但没有帮助。在 globals dict 中显式创建类是因为简单地在 for 循环上创建类只会产生一个单元测试。
【问题讨论】:
标签: python unit-testing metaclass