python unittest for argparse

前端 未结 2 2019
心在旅途
心在旅途 2021-01-06 23:31

I have a function inside a module that creates an argparse:

def get_options(prog_version=\'1.0\', prog_usage=\'\', misc_opts=None):
     options         


        
2条回答
  •  感情败类
    2021-01-06 23:55

    I prefer explicitly passing arguments instead of relying on globally available attributes such as sys.argv (which parser.parse_args() does internally). Thus I usually use argparse by passing the list of arguments myself (to main() and subsequently get_options() and wherever you need them):

    def get_options(args, prog_version='1.0', prog_usage='', misc_opts=None):
        # ...
        return parser.parse_args(args)
    

    and then pass in the arguments

    def main(args):
        get_options(args)
    
    if __name__ == "__main__":
        main(sys.argv[1:])
    

    that way I can replace and test any list of arguments I like

    options = get_options(['-c','config.yaml'])
    self.assertEquals('config.yaml', options.config) 
    

提交回复
热议问题