0

这是为其编写 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]
    """

这是单元测试代码:

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 代码通过了,我不明白为什么,因为我认为唯一有效的结果是 list_outcome_1 从 swap_k 的文档字符串判断...

4

2 回答 2

5

首先,即使“valid_outcomes”包含的内容多于有效内容,测试也可以通过。(在您看来,list_outcome_1)。这只是意味着它有时不会在它应该失败的时候失败。

其次,我认为测试是正确的:文档没有说前“k”项将按原始顺序放在最后,也不保证最后“k”项相同。所以 [1,2] 的任何顺序都可以出现在列表的末尾,而 [5,6] 的任何顺序都可以出现在列表的开头。

一般来说,如果不能保证某些事情,那么我宁愿不假设它,即使它看起来合乎逻辑(毕竟,列表是有序的,所以假设它几乎是自然的)。

“修复”单元测试也意味着修复文档以保证顺序。

于 2013-04-12T09:30:59.693 回答
0
self.assertEqual(list_original, list_outcome_1)

self.assertIn(list_original, valid_outcomes)

两者都满足测试。在这里,您正在测试真实的结果是否在结果列表中,这是真实的,因此测试是有效的。

但是根据文档字符串

    self.assertEqual(list_original, list_outcome_1)

会更好,因为它会检查相等性。

于 2013-04-12T09:41:04.583 回答