簡體   English   中英

如何多次測試和記錄-nosetest unittest-Python

[英]How to test and log multiple times -nosetest unittest - python

這是問題的迷你版

a = [[1,2,3][0,0,0]]
b = [[1,0,1][0,0,0]]
c = [[0,0,0][1,0,1]]

因此,如果1級是[]而2級是[[]],那么我要嘗試的是測試列表以查看是否存在2級匹配(無論順序如何),因此在這種情況下b,c是等效的。

我正在使用單元測試和鼻子測試來運行它們,如果我只想對另一個表進行測試,我會做類似的事情:

函數true()創建我的表

def test_table1_table2(self):
    for row in truth(1,3):
        self.assertIn(row,truth(2,4))

但我的目標是對照我創建的所有其他表(大約20個並在不斷增長)測試所有表。 有些問題我無法解決(我不確定是否需要閱讀unittest文檔或鼻子測試,甚至不需要它們!)

我的猜測是僅使用更多的for循環來消除任何可能性。 但是使用

>>> nosetest 

與一個

assertIn 

只是在第一個錯誤處停止,這不是我想要的。 我需要掃描並收集有關哪些列表等效的信息(無論順序或嵌套列表如何)。 也許我應該只是創建一些東西而忘記單元測試?

所以我的首選輸出將是這樣的

table1 and table2 are not equivalent 
table1 and table2 are not equivalent

或可能更有用且更短

table1 and table10 are equivalent

這是我目前擁有的代碼,幾乎所有東西都只是一個整數,期望的是true(),它使真值表(嵌套列表):

114     def test_all(self):$                                                  |~                      
115         ''' will test all tables'''$                                      |~                      
116         for expression in range(self.count_expressions()):$               |~                      
117             num_var = count_vars(exp_choose(expression))$                 |~                      
118             for row in truth(expression, num_var):$                       |~                      
119                 for expression2 in range(self.count_expressions()):$      |~                      
120                     num_var2 = count_vars(exp_choose(expression2))$       |~                      
121                     for row2 in truth(expression2, num_var2):$            |~                      
122                         self.assertIn(row, truth(expression2,num_var2))

嘗試這種方法:在測試類外部運行外部循環,而不是在測試方法內部循環。 內部代碼應在測試類中添加新的測試方法。

請參見此處的示例: 如何在python中生成動態(參數化)單元測試?

更新為更短的解決方案:

def match(a,b):
  aSets = map(set, a)
  bSets = map(set, b)
  return ((aSets[0] == bSets[0]) and (aSets[1] == bSets[1])) \
      or ((aSets[0] == bSets[1]) and (aSets[1] == bSets[0]))

tables = {}
tables['a'] = [[1,2,3],[0,0,0]]
tables['b'] = [[1,0,1],[0,0,0]]
tables['c'] = [[0,0,0],[1,0,1]]
tables['d'] = [[0,0,0],[1,1,0]]

for key1, value1 in tables.items():
  for key2, value2 in tables.items():
    result = 'equivalent' if match(value1,value2) else 'not eqivalent'
    print '%s and %s are %s' % (key1, key2, result)

使用mapzip等功能可以說可以更優雅地完成此操作,但是重點是將代碼分解成較小的片段並減少循環的深度。

一種更簡單的方法是使用unittest的assertItemsEqual ,它正是為此目的而設計的。 給定OP'sa,b和c嵌套列表:

class CheckingEqualityIgnoreOrder(unittest.TestCase):
    def testAB(self):
        self.assertItemsEqual(a, b)
        #fails

    def testBC(self):
        self.assertItemsEqual(b, c)
        #passes

    def testAC(self):
        self.assertItemsEqual(a, c)
        #fails

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM