简体   繁体   English

将命令行参数传递给 python unittests

[英]Passing command-line arguments to python unittests

Is there a way to do something like this in python?有没有办法在python中做这样的事情?

$ python tests/tests.py verbose

# in the file
if __name__ == '__main__':
   unittest.main()

Basically I want to be able to parse extraneous sys args from the command line, but when I try, I get something like:基本上我希望能够从命令行解析无关的 sys args,但是当我尝试时,我得到类似的信息:

AttributeError: module ' main ' has no attribute 'verbose' AttributeError: 模块“ main ”没有属性“verbose”

Simply pass in --verbose from the command line, like this:只需从命令行传入--verbose ,如下所示:

python tests/tests.py --verbose

When the unittest framework is called with unittest.main() is will still understand the same command line arguments as when the framework is called with python -m unittest as documented here .当单元测试框架调用unittest.main()是仍然会理解相同的命令行参数时,框架调用python -m unittest记录在这里 To enable verbosity, the option is the flag (prepended with two hyphens) --verbose .要启用详细信息,选项是标志(前面带有两个连字符) --verbose There is no reason to make any changes to your code.没有理由对您的代码进行任何更改。 The following is all you need:以下是您所需要的:

if __name__ == '__main__':
   unittest.main()

Of course, if you want to support options other than those provided by the framework, then you would need to handle those yourself.当然,如果您想支持框架提供的选项以外的选项,那么您需要自己处理这些选项。

One way to do this is to process the sys args before those are passed to unittest.main() .一种方法是在将 sys args 传递给unittest.main()之前处理它们。 For example:例如:

if __name__ == '__main__':
    if 'verbose' in sys.argv:
        sys.argv = sys.argv[:-1]  
    else:
        logging.disable(1e6) # suppress logging
    unittest.main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM