2013-04-12 30 views
0

這是它的功能是寫的單元測試:有人可以解釋令人困惑的單元測試代碼嗎?

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 

的單元測試代碼通過,我不明白爲什麼,因爲我想唯一的通過swap_k的文檔字符串判斷有效結果爲list_outcome_1 ...

+1

unittest更寬容;它提供了可接受結果的白名單,並且測試功能提供了適合的*和*結果。 *爲什麼這是一個問題?* –

回答

5

首先,即使「valid_outcomes」包含更多的,測試也可以通過,而不是有效。 (在你看來,list_outcome_1)。這只是意味着它應該不會在失敗

其次,我認爲這個測試是正確的:文檔並沒有說第一個「k」項將按最初的順序放在最後,也不保證最後的「k」項相同。所以[1,2]的任何順序都可以出現在列表的末尾,任何[5,6]的順序都可以出現在開頭。一般來說,如果某些東西不能保證,那麼我寧願不假定它,即使它看起來是合乎邏輯的(畢竟,一個列表是有序的,所以假設它是很自然的)。

「修復」單元測試也意味着修復文檔以保證順序。

+0

謝謝!這很好地解釋了它。 –

0
self.assertEqual(list_original, list_outcome_1) 

self.assertIn(list_original, valid_outcomes) 

既滿足測試。在這裏,您正在測試真實結果是否在結果列表中,這是真實的,因此測試是有效的。

但是按照文檔字符串

self.assertEqual(list_original, list_outcome_1) 

會更好,因爲它會檢查平等。