【发布时间】:2019-03-17 15:27:48
【问题描述】:
我有一堆函数适用于类似的对象,例如代表 n 维框的 Numpy 数组:
# 3-D box parameterized as:
# box[0] = 3-D min coordinate
# box[1] = 3-D max coordinate
box = np.array([
[1, 3, 0],
[4, 5, 7]
])
现在我有一大堆要在框列表上运行的函数,例如。 volumes、intersection、smallest_containing_box 等。在我看来,这是我希望的设置方式:
# list of test functions:
test_funcs = [volume, intersection, smallest_containing_box, ...]
# manually create a bunch of inputs and outputs
test_set_1 = (
input = [boxA, boxB, ...], # where each of these are np.Array objects
output = [
[volA, volB, ...], # floats I calculated manually
intersection, # np.Array representing the correct intersection
smallest_containing_box, # etc.
]
)
# Create a bunch of these, eg. test_set_2, test_set_3, etc. and bundle them in a list:
test_sets = [test_set_1, ...]
# Now run the set of tests over each of these:
test_results = [[assertEqual(test(t.input), t.output) for test in test_funcs] for t in test_sets]
我想以这种方式构建它的原因是,我可以创建多组(输入,答案)对,并在每个对上运行所有测试。除非我遗漏了什么,否则unittest 的结构似乎不适用于这种方法。相反,它似乎希望我为每对函数和输入创建一个单独的 TestCase 对象,即
class TestCase1(unittest.TestCase):
def setUp(self):
self.input = [...]
self.volume = [volA, volB, ...]
self.intersection = ...
# etc.
def test_volume(self):
self.assertEqual(volume(self.input), self.volume)
def test_intersection(self):
self.assertEqual(intersection(self.input), self.output)
# etc.
# Repeat this for every test case!?
这似乎是一个疯狂的样板数量。我错过了什么吗?
【问题讨论】:
-
This answer 可能是我想要的。我看起来可以写一个
TestCase,制作一组输入和输出,然后使用subTest上下文对所有输入和输出运行每个测试函数。如果这是“正确的方法”,那么模组可以随意将其作为副本关闭,但如果有更好/更惯用的方法,我会很想听听。 -
此外,如果我只是以错误的方式考虑单元测试(即以其他方式拆分它有一些显着的好处),我也想知道 :)
标签: python unit-testing testing