我在 python 中有一个获取命令行参数的 main() 函数。
有没有办法让我为此函数编写 pytest 测试并在代码中定义参数?
e.g.
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")
添加到以前的答案,而不是修改sys.argv
使用上下文管理器会更安全,它可以掩盖和保护底层对象。一个例子是
with unittest.mock.patch('sys.argv', ['program_name', '--option1', 'inputFile']):
main()
这只适用于 python3。对于 python2 来说Mock http://www.voidspace.org.uk/python/mock/index.html图书馆就可以解决这个问题。
我在另一个 stackoverflow 帖子上找到了这个解决方案here https://stackoverflow.com/questions/18668947/how-do-i-set-sys-argv-so-i-can-unit-test-it#comment55008523_27765993.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)