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

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

问题描述

我在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天全站免登陆