Python单元测试在所有测试之后运行函数
我需要通过ssh在python上测试smth。我不想为每个测试建立ssh连接,因为它太长了,我写了以下内容:Python单元测试在所有测试之后运行函数,python,unit-testing,ssh,python-unittest,Python,Unit Testing,Ssh,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 = pa
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())
在这个版本中,我得到了errorTypeError:unbound方法disconnect()必须用TestCase实例作为第一个参数来调用(没有得到任何结果)
。那么,在所有测试通过后,我如何调用disconnect?
致以最诚挚的问候。如果您希望在所有测试中保持相同的连接,则应使用and。您还需要将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.TestCase):
def设置等级(cls):
cls.connection=
@静力学方法
def disconnect():
... 断开TestCase.connection连接
def拆卸类(cls):
cls.disconnect()
您可以通过定义unittest.TestResult
类的startTestRun
、stopTestRun
来实现setUpClass
和tearDownClass
是针对每个测试类(每个测试文件)运行的,因此如果您有多个文件,则此方法将针对每个文件运行
通过将以下代码添加到我的测试/_uinit_uuuuy.py
中,我成功地实现了它。此代码对所有测试只运行一次(无论测试类和测试文件的数量如何)
在
python3
中,在类函数上需要一个@classmethod
装饰器。如何让TestSuite使用定制的测试结果?
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)