Python2.6。unittest框架,断言:需要帮助

2024-05-23 17:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用unittest框架用python2.6编写一个测试套件,我想在代码中使用断言。我知道asserts得到了彻底的改进,并且在2.7+中更好,但是我现在只能使用2.6。在

我在使用断言时遇到问题。我希望能够使用assertIn(a,b)特性,但是遗憾的是,这只在2.7+中使用。所以我意识到我必须使用assertTrue(x),这也是2.6版本中的,但那没用。然后,我查看了this document,在以前的版本中,assertTrue(x)曾经是{},所以我在代码中使用了它,但仍然没有结果。在

我得到的信息是:

NameError: global name 'failUnless' is not defined

这和我为assertIn(a,b)和{}得到的结果是一样的。 所以我完全不知道该怎么做。在

我的简短版本:

我希望能够在Python2.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....就可以了。在


Tags: 代码testself版本baseisdefcode
3条回答

assertTrue对于in测试应该可以正常工作:

self.assertTrue('a' in somesequence)

assertIn所做的就是运行与上面相同的测试,并在测试失败时设置一条有用的消息。在

你的测试用例代码真的很有用。在

您的问题是您试图使用assert[Something]作为函数,而它们是TestCase类的方法。在

因此,您可以使用assertTrue来解决您的问题:

self.assertTrue(element in list_object)
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),它应该可以工作。在

相关问题 更多 >