我需要通过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)
。那么在所有测试通过后我怎么能断断续续?
最诚挚的问候。
答案 0 :(得分:11)
如果要为所有测试保持相同的连接,则应使用setUpClass和tearDownClass。您还需要将disconnect
方法设为静态,因此它属于该类,而不属于该类的实例。
class TestCase(unittest.TestCase):
def setUpClass(cls):
cls.connection = <your connection setup>
@staticmethod
def disconnect():
... disconnect TestCase.connection
def tearDownClass(cls):
cls.disconnect()
答案 1 :(得分:0)
您可以通过定义startTestRun
类的stopTestRun
,unittest.TestResult
来实现。 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)
答案 2 :(得分:-1)
在disconnect
课程的拆解中致电TestCase
: -
class TestCase(unittest.TestCase):
...
......
....your existing code here....
.....
def tearDown(self):
self.disconnect()
每个测试用例类 tearDown
运行一次