繁体   English   中英

Python 单元测试在所有测试后运行函数

[英]Python unit tests run function after all test

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

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 argument (got nothing instead) 那么我如何在所有测试通过后调用断开连接? 最诚挚的问候。

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

class TestCase(unittest.TestCase):

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

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

     def tearDownClass(cls):
         cls.disconnect()

您可以通过定义unittest.TestResult类的startTestRunstopTestRun来实现。 setUpClasstearDownClass正在每个测试类(每个测试文件)运行,因此如果您有多个文件,则此方法将为每个文件运行。

通过将以下代码添加到我的tests/__init__.py我设法实现了它。 此代码仅对所有测试运行一次(无论测试类和测试文件的数量如何)。

def startTestRun(self):
    """
    https://docs.python.org/3/library/unittest.html#unittest.TestResult.startTestRun
    Called once before any tests are executed.

    :return:
    """
    DockerCompose().start()


setattr(unittest.TestResult, 'startTestRun', startTestRun)


def stopTestRun(self):
    """
    https://docs.python.org/3/library/unittest.html#unittest.TestResult.stopTestRun
    Called once after all tests are executed.

    :return:
    """
    DockerCompose().compose.stop()


setattr(unittest.TestResult, 'stopTestRun', stopTestRun)

暂无
暂无

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

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