如何使Python unittest以状态代码退出函数?在我的tearDown函数中,我必须进行一些处理以生成状态代码,但是想让unittest退出该代码吗? python脚本将从DOS-bat文件运行,需要回显%ERRORLEVEL%,我希望将%ERRORLEVEL%设置为myExitCode。当前,它总是返回0

import logging
import unittest
import sys

myExitCode = 0

class MyTest(unittest.TestCase):

    def setUp(self):
        logging.info('Setting up test: logged stdout')

    def test(self):
        logging.info('logged more stdout')
        self.assertTrue(True)

    def tearDown(self):
        ## Mocking some processing to generate customized exitcode:
        myExitCode = 1000
        logging.info('exit code = %d', myExitCode)
        return myExitCode

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger()
    logger.addHandler(logging.FileHandler('test.log', mode='a'))
    stderr_file = open('test.log', 'a')
    unittest.main(testRunner=unittest.TextTestRunner(stream=stderr_file),exit=False)
    logging.info('Exit Code from main: %d', myExitCode)
    sys.exit(myExitCode)


批处理脚本:

python myExitCode.py
echo %ERRORLEVEL%

最佳答案

您需要在此处使用全局变量。请记住,这不是很干净:

   def tearDown(self):
        global myExitCode
        myExitCode = 1000
        logging.info('exit code = %d', myExitCode)

10-08 19:24