简体   繁体   English

Python中的批处理测试(单元测试)

[英]Batch tests (unittest) in Python

I have a unittest that tests the connection of an url. 我有一个单元测试,用于测试url的连接。 Individually it works, but I have several urls to test, so I'm trying to call this test module and batch-test them! 个别地它可以工作,但是我有几个要测试的URL,所以我试图调用此测试模块并对它们进行批处理! But I get errors in calling the test function. 但是在调用测试函数时出现错误。 Could you help me? 你可以帮帮我吗?

test.py: 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()

Now I want to test several urls, so I created file with them, and try to call the test function: 现在我想测试几个URL,所以我用它们创建了文件,并尝试调用测试函数:

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)

And I get this message as many times as urls I have: 而且我收到此消息的次数与我获得的网址一样多:

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

OK

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

What's wrong? 怎么了?

Your test method is ignored because it takes an argument. 您的测试方法将被忽略,因为它带有一个参数。 Test methods never take an argument. 测试方法从不接受参数。 This is quite beside the fact that Python won't ever magically pass a local variable name into a function as an argument; 这与Python永远不会神奇地将局部变量名传递给函数作为参数这一事实完全无关。 you'd have to explicitly pass it in. 您必须显式传递它。

Integrate your url loading into the test itself instead: 而是将您的url加载集成到测试本身中:

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()

or create test methods dynamically: 或动态创建测试方法:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM