所有测试后,Python单元测试运行功能

Mik*_*aev 9 python ssh unit-testing python-unittest

我需要通过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()
Run Code Online (Sandbox Code Playgroud)

和我的跑步者

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

在这个版本中我得到错误TypeError: unbound method disconnect() must be called with TestCase instance as first argument (got nothing instead).那么在所有测试通过后我怎么能断断续续?最诚挚的问候.

Reu*_*ani 15

如果要为所有测试保持相同的连接,则应使用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()
Run Code Online (Sandbox Code Playgroud)

  • 在`python 3`中,你需要在类函数上使用`@ classmethod`装饰器 (2认同)

ism*_*ail 9

你可以通过定义startTestRun, stopTestRunof unittest.TestResultclass 来做到这一点。setUpClass并且tearDownClass正在每个测试类(每个测试文件)运行,因此如果您有多个文件,此方法将为每个文件运行。

通过将以下代码添加到我的我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)
Run Code Online (Sandbox Code Playgroud)