Python 单元测试在所有测试后运行函数 [英] Python unit tests run function after all test

查看:36
本文介绍了Python 单元测试在所有测试后运行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过 ssh 在 python 上测试 smth.我不想每次测试都建立ssh连接,因为太长了,我写了这个:

I need to test smth on python via ssh. I don't want to make ssh connection for every test, because it is to long, I have written this:

class TestCase(unittest.TestCase):
    client = None
    def setUp(self):
        if not hasattr(self.__class__, 'client') or self.__class__.client is None:
            self.__class__.client = paramiko.SSHClient()
            self.__class__.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.__class__.client.connect(hostname=consts.get_host(), port=consts.get_port(), username=consts.get_user(),
                                password=consts.get_password())

    def test_a(self):
        pass

    def test_b(self):
        pass

    def test_c(self):
        pass

    def disconnect(self):
        self.__class__.client.close()

和我的跑步者

if __name__ == '__main__':
    suite = unittest.TestSuite((
        unittest.makeSuite(TestCase),
    ))
    result = unittest.TextTestRunner().run(suite)
    TestCase.disconnect()
    sys.exit(not result.wasSuccessful())

在这个版本中我得到错误TypeError: unbound method disconnect() must be called with TestCase instance as first parameter (got nothing instead).那么我如何在所有测试通过后调用断开连接?最好的问候.

In this version I get error TypeError: unbound method disconnect() must be called with TestCase instance as first argument (got nothing instead). So how i can call disconnect after all tests pass? With best regards.

推荐答案

你应该使用 setUpClasstearDownClass 相反,如果您想为所有测试保持相同的连接.您还需要将 disconnect 方法设为静态,因此它属于类而不是类的实例.

You should use setUpClass and tearDownClass instead, if you want to keep the same connection for all tests. You'll also need to make the disconnect method static, so it belongs to the class and not an instance of the class.

class TestCase(unittest.TestCase):

     def setUpClass(cls):
         cls.connection = <your connection setup>

     @staticmethod
     def disconnect():
         ... disconnect TestCase.connection

     def tearDownClass(cls):
         cls.disconnect()

这篇关于Python 单元测试在所有测试后运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆