如何告诉Python unittest在函数中使用自定义代码集退出
如何让Python如何告诉Python unittest在函数中使用自定义代码集退出,python,batch-file,python-unittest,Python,Batch File,Python Unittest,如何让Pythonunittest从我的函数中带着状态代码退出 在我的tearDown函数中,我必须进行一些处理以生成状态代码,但我希望unittest与该代码一起退出。Python脚本将从DOS bat文件运行,需要回显%ERRORLEVEL%,我希望%ERRORLEVEL%设置为myExitCode 当前,它总是返回0: import logging import unittest import sys myExitCode = 0 class MyTest(unittest.TestC
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 a customized exit code:
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)
你能发布你用来调用python脚本的相关批处理文件代码吗?我添加了批处理脚本的内容。谢谢你,托马斯,这对我很有用。是的,它没有清洗,但这是我必须使用的系统。不幸的是,unittest将报告为失败,因为我必须使用自定义退出代码退出:(对于没有“全局”的情况下发生的事情,有什么解释?可以添加到答案中。