Skip to main content
 首页 » 编程设计

python 2.6。单元测试框架,断言 : help required

2025年05月04日31zhoujg

我正在使用 unittest 框架在 python 2.6 中编写测试套件,我想在我的代码中使用断言。我知道断言得到了彻底的检修,并且在 2.7+ 中要好得多,但我现在仅限于使用 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.... 并且它起作用了。

请您参考如下方法:

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) 它应该可以工作。