[英]Setting command line arguments for main function tests
I have a main() function in python that gets command line arguments.我在 python 中有一个 main() 函数,它可以获取命令行参数。 Is there a way for me to write pytest tests for this function and define the arguments in the code?有没有办法为这个函数编写 pytest 测试并在代码中定义参数?
eg例如
def main():
# argparse code
args, other = arg_parser.parse_known_args()
return args.first_arg
def test_main():
res = main() # call with first_arg = "abc"
assert(res == "abc")
To add to the previous answers, instead of modifying sys.argv
It is safer to use a context manager which can cover up and protect the underlying object.添加到前面的答案中,而不是修改sys.argv
使用可以覆盖和保护底层对象的上下文管理器更安全。 An example would be一个例子是
with unittest.mock.patch('sys.argv', ['program_name', '--option1', 'inputFile']):
main()
This works only with python3.这仅适用于 python3。 For python2 the Mock library does the trick.对于 python2, Mock库可以解决问题。
I found this solution on a different stackoverflow post here .我发现了一个不同的计算器后该解决方案在这里。
parse_args
takes a argv
parameter. parse_args
采用argv
参数。 The docs uses this repeatedly in it's examples文档在示例中反复使用它
parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='store_true')
parser.add_argument('bar')
parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
where the string list replicates sys.argv[1:]
that it would get from the commandline.其中字符串列表复制sys.argv[1:]
它将sys.argv[1:]
获得。 If the argument is None
(or omitted) the parser uses sys.argv[1:]
.如果参数是None
(或省略),解析器使用sys.argv[1:]
。
So if因此,如果
def main(argv=None):
# argparse code
args, other = arg_parser.parse_known_args(argv)
return args.first_arg
You could test with你可以测试
main(['foo', '-f','v'])
The unittesting
file for argparse.py
uses both this approach, and your's of modifying sys.argv
directly.该unittesting
文件argparse.py
同时使用这种方法,你的修改中的sys.argv
直接。
https://docs.python.org/3/library/argparse.html#beyond-sys-argv https://docs.python.org/3/library/argparse.html#beyond-sys-argv
https://docs.python.org/3/library/argparse.html#partial-parsing https://docs.python.org/3/library/argparse.html#partial-parsing
The best solution I found so far is this到目前为止我找到的最好的解决方案是这个
def test_main():
sys.argv = ["some_name", "abc"]
res = main()
and for flags:和标志:
sys.argv.append("-f")
sys.argv.append("v")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.