python, unittest: is there a way to pass command line options to the app

后端 未结 5 978
余生分开走
余生分开走 2020-12-04 14:22

I have a module that imports unittest and has some TestCases. I would like to accept some command line options (for example below, the name of a data file), but when I try t

5条回答
  •  甜味超标
    2020-12-04 15:04

    I thought I'd share my solution for adding a --debug switch to the test to control the logger:

    if __name__=='__main__':
         parser = argparse.ArgumentParser(description="Build a compilation script")
         parser.add_argument('--debug', help='Turn on debug messages', action='store_true', default=False)
    
         args = parser.parse_args()
    
         if args.debug:
             log_level = logging.DEBUG
         else:
             log_level = logging.INFO
    
         logging.basicConfig(level=log_level)
         sys.argv.pop()
         unittest.main()
    

    Then I extended unittest.TestCase to add logging:

     class mcs_TestCase(unittest.TestCase, object):
         def __init__(self, *args, **kwargs):
             super(mcs_TestCase,self).__init__(*args,**kwargs)
             logging.basicConfig()
             self.logger = logging.getLogger(__name__)
             ...
    

    Now I can turn messages on and off in my test using --debug, but it gets ignored in regular regressions.

提交回复
热议问题