2012-08-12 123 views
1

我正在使用unittest框架在python 2.6中編寫測試套件,並且我想在我的代碼中使用斷言。我知道斷言得到了徹底的檢修,並且在2.7+以上更好,但我現在只侷限於使用2.6。python 2.6。單元測試框架,斷言:需要幫助

我有使用斷言的問題。我希望能夠使用assertIn(a,b)功能,但是,只有在2.7+以上。所以我意識到我必須使用也是2.6的assertTrue(x),但那不起作用。然後,我看着this document其中說,在以前的版本assertTrue(x)曾經是failUnless(x),所以我用我的代碼,並仍然沒有結果。

我得到的消息:

NameError: global name 'failUnless' is not defined

這是我得到了assertIn(a,b)assertTrue(x)同樣的事情。 因此,我完全不知所措。

較短的版本,我的問題:

我希望能夠在Python 2.6來實現assertIn(a,b)。 任何人有任何解決方案?

我的代碼:

import unittest 

class test_base(unittest.TestCase): 
    # some functions that are used by many tests 

class test_01(test_base): 
    def setUp(self): 
     #set up code 

    def tearDown(self): 
     #tear down code 

    def test_01001_something(self): 
     #gets a return value of a function 
     ret = do_something() 

     #here i want to check if foo is in ret 
     failUnless("foo" in ret) 

編輯:看來我是一個白癡。我所需要做的就是添加self.assert....,它工作。

+1

您能否提供您的測試用例的源代碼? – 2012-08-12 09:34:41

+0

@RostyslavDzinko我可以,我不認爲這會有很大的幫助。一會兒。 – 2012-08-12 09:36:29

+0

@InbarRose:發佈你的代碼使所有的區別.... :-) – 2012-08-12 09:49:57

回答

2
import unittest 

class MyTest(unittest.TestCase): 
    def test_example(self): 
     self.assertTrue(x) 

這應該工作,基於unittest from Python 2.6的文檔。一定要用它作爲TestCase.assertTrue()。

編輯:在你的例子中,將其設置爲self.failUnless("foo" in ret)它應該工作。

+0

即使馬丁首先回答,但接受了你的回答,因爲你沒有像他那樣多的積分。 :) – 2012-08-12 09:48:59

+0

謝謝!祝你好運。 – 2012-08-12 09:50:49

+1

@InbarRose:你知不知道有人擔心高級代表用戶在回答時總是贏?謝謝你證明他們錯了。 :-) – 2012-08-12 11:32:13

3

assertTrue應該只是罰款爲in測試:

self.assertTrue('a' in somesequence) 

所有assertIn確實運行相同的測試如上所述,如果測試失敗設置一個有用的消息。

+0

我必須包含'self'嗎?這將是一個簡單的錯誤。 – 2012-08-12 09:46:23

+0

@InbarRose:是的,'assert *'方法就是這個類的方法。 :-) – 2012-08-12 09:49:25

1

你的測試用例代碼確實有幫助。

你的問題是你試圖使用assert [Something]作爲函數,而它們是TestCase類的方法。

所以,你可以解決你的問題,例如, assertTrue

self.assertTrue(element in list_object) 
1

實際執行assertIn是相當瑣碎。這是我在我的單元測試用過:

class MyTestCase(unittest.TestCase)  
    def assertIn(self, item, iterable): 
     self.assertTrue(item in iterable, 
         msg="{item} not found in {iterable}" 
          .format(item=item, 
            iterable=iterable)) 

然後,您可以在此基礎上類所有的測試用例,而不是unittest.TestCase,甚至蟒蛇2.6和錯誤消息,安全地使用assertIn會比純assertTrue好得多。用於比較Python 2中assertIn的實際實現。7:

def assertIn(self, member, container, msg=None): 
    """Just like self.assertTrue(a in b), but with a nicer default message.""" 
    if member not in container: 
     standardMsg = '%s not found in %s' % (safe_repr(member), 
               safe_repr(container)) 
     self.fail(self._formatMessage(msg, standardMsg))