这是为其编写unittest的函数:
def swap_k(L, k):
""" (list, int) -> NoneType
Precondtion: 0 <= k <= len(L) // 2
Swap the first k items of L with the last k items of L.
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swap_k(nums, 2)
>>> nums
[5, 6, 3, 4, 1, 2]
"""
这是unittest代码:
def test_swap_k_list_length_6_swap_2(self):
"""Test swap_k with list of length 6 and number of items to swap 2.
Also allow for the fact that there are potentially four alternate
valid outcomes.
"""
list_original = [1, 2, 3, 4, 5, 6]
list_outcome_1 = [5, 6, 3, 4, 1, 2]
list_outcome_2 = [5, 6, 3, 4, 2, 1]
list_outcome_3 = [6, 5, 3, 4, 1, 2]
list_outcome_4 = [6, 5, 3, 4, 2, 1]
valid_outcomes = [list_outcome_1, list_outcome_2, list_outcome_3, list_outcome_4]
k = 2
a1.swap_k(list_original,k)
self.assertIn(list_original, valid_outcomes)
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
unittest代码通过了,我不明白为什么,因为根据swap的docstring判断,我认为唯一有效的结果应该是list\u outcome\u 1。。。你知道吗
以及
两者都满足测试要求。在这里,您将测试真实的结果是否在结果列表中,结果列表是真的,因此测试是有效的。你知道吗
但是根据docstring
如果它检查平等性的话会更好。你知道吗
首先,即使“有效的结果”包含比有效结果更多的内容,测试也可以通过。(在您看来,请列出结果1)。它只是意味着它有时不会在应该失败的时候失败。你知道吗
第二,我认为测试是正确的:doc没有说第一个“k”项将按其原始顺序放在最后,也没有保证最后一个“k”项也是如此。所以[1,2]的任何顺序都可以出现在列表的末尾,而[5,6]的任何顺序都可以出现在列表的开头。你知道吗
一般来说,如果某件事没有得到保证,那么我宁愿不去假设它,即使它看起来是合乎逻辑的(毕竟列表是有序的,所以假设它几乎是自然的)。你知道吗
“修复”unittest也意味着修复doc以保证订单。你知道吗
相关问题 更多 >
编程相关推荐