簡體   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