如何告诉Python unittest退出函数中设置的自定义代码?

时间:2014-01-29 02:02:28

标签: python batch-file python-unittest

如何从我的函数中使用状态代码退出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%

1 个答案:

答案 0 :(得分:1)

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

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