为主要功能测试设置命令行参数 [英] Setting command line arguments for main function tests

查看:29
本文介绍了为主要功能测试设置命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中有一个 main() 函数,它可以获取命令行参数.有没有办法让我为此函数编写 pytest 测试并在代码中定义参数?

I have a main() function in python that gets command line arguments. Is there a way for me to write pytest tests for this function and define the arguments in the code?

例如

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")

推荐答案

parse_args 接受一个 argv 参数.文档在它的例子中反复使用这个

parse_args takes a argv parameter. 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'])

字符串列表复制了从命令行获取的 sys.argv[1:].如果参数是 None(或省略),解析器使用 sys.argv[1:].

where the string list replicates sys.argv[1:] that it would get from the commandline. If the argument is None (or omitted) the parser uses sys.argv[1:].

如果

def main(argv=None):
    # argparse code
    args, other = arg_parser.parse_known_args(argv)
    return args.first_arg

你可以测试

main(['foo', '-f','v'])

argparse.pyunittesting 文件既使用这种方法,也使用您直接修改 sys.argv 的方法.

The unittesting file for argparse.py uses both this approach, and your's of modifying sys.argv directly.

https://docs.python.org/3/library/argparse.html#beyond-sys-argv

https://docs.python.org/3/library/argparse.html#partial-parsing

这篇关于为主要功能测试设置命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆