سؤال

How do I get Python unittest to exit with a status code from my function?

In my tearDown function I have to do some processing to generate the status code, but I would like unittest to exit with that code. The Python script will be run from a DOS bat file and need to echo the %ERRORLEVEL% and I want the %ERRORLEVEL% to be set with myExitCode.

Currently, it always return 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)

Batch script:

python myExitCode.py
echo %ERRORLEVEL%
هل كانت مفيدة؟

المحلول

You'd need to use a global variable here. Bear in mind this isn't very clean:

   def tearDown(self): 
        global myExitCode
        myExitCode = 1000
        logging.info('exit code = %d', myExitCode)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top