Python中的批处理测试(unittest)

时间:2013-10-03 20:44:15

标签: python unit-testing batch-processing

我有一个测试网址连接的unittest。它可以单独使用,但我有几个网址需要测试,所以我试着调用这个测试模块并批量测试它们!但是我在调​​用测试函数时遇到错误。你能帮帮我吗?

test.py:

class TestConnector(unittest.TestCase):

    def setUp(self):
        [...]

    def test_connection(self, url):
        conn = Connector(self.user)
        self.assertNotEqual(conn.read(url), None)

if __name__ == '__main__':
    unittest.main()

现在我想测试几个网址,所以我用它们创建了文件,并尝试调用测试函数:

import test

with open('URL_list.txt') as f:
    urls = f.readlines()

suite = unittest.TestLoader().loadTestsFromModule(test.TestConnector)

for url in urls:
    unittest.TextTestRunner().run(suite)

我得到的信息和我的网址一样多次:

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

----------------------------------------------------------------------

出了什么问题?

1 个答案:

答案 0 :(得分:3)

您的测试方法会被忽略,因为它需要参数。测试方法从不采取参数。这是因为Python不会将局部变量名称神奇地传递给函数作为参数;你必须明确传递它。

将您的网址加载集成到测试中:

class TestConnector(unittest.TestCase):

    def setUp(self):
        [...]

    def test_connections(self):

        with open('URL_list.txt') as f:
            for url in f:
                conn = Connector(self.user)
                self.assertNotEqual(conn.read(url.strip()), None)

if __name__ == '__main__':
    unittest.main()

或动态创建测试方法:

class TestConnector(unittest.TestCase):
    def setUp(self):
        [...]

def generate_test(url):
    def test(self):
        conn = Connector(self.user)
        self.assertNotEqual(conn.read(url), None)

if __name__ == '__main__':
    with open('URL_list.txt') as f:
        for i, url in enumerate(f):
            test_name = 'test_{}'.format(i)
            setattr(TestConnector, test_name, generate_test(url.strip()))

    unittest.main()