将变量分配给argparse而不是通过命令行输入

2024-04-25 15:14:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为脚本编写测试(使用pytest),但是我不知道如何创建/传递参数到main(),尤其是当它没有收到参数时。即使我把它改成def main(args = None):,它也会在第一行启动它。你知道吗

测试.py

def test_main(capfd):
    main()
    out, err = capfd.readouterr()
    assert out == "my expected output"

脚本.py

def init_parser():
    parser = argparse.ArgumentParser(description="The script searches one or \
                                     more named input files for lines \
                                     containing a match to a regular \
                                     expression pattern.")
    parser.add_argument('regex', help='the regular expression.')
    parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), default=[sys.stdin],
                        help='the name of the file(s) to search.')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-u', '--underscore', action='store_true', help='prints \
                       "^" under the matching text.')
    group.add_argument('-c', '--color', action='store_true', help='highlights \
                       matching text.')
    group.add_argument('-m', '--machine', action='store_true', help='generates \
                       machine readable output.')

    return parser


def main():
    args = init_parser().parse_args()
    for file in args.infile:
        for i, line in enumerate(iter(file.readline, '')):
            for substring in re.finditer(args.regex, line):
                    if args.underscore:
                        underscore_output(file.name, i + 1, line[:-1],
                                          substring.start(), substring.end())
                    elif args.color:
                        color_output(file.name, i + 1, line[:-1],
                                     substring.group())
                    elif args.machine:
                        machine_output(file.name, i + 1, substring.start(),
                                       substring.group())
                    else:
                        print_line(file.name, i + 1, line[:-1])```

Tags: thenameaddparserforoutputmaindef
2条回答

在测试代码中,您可以在调用main之前patch退出sys.argv

def test_main(monkeypatch):
    monkeypatch.setattr("sys.argv", ["script.py", "test_regex", "test_infile"])
    main()
    # put your assertions here

parse_args可以使用显式的None参数来告诉它解析sys.argv[1:]。编写代码以便于测试:

def main(args=None):
    args = init_parser().parse_args(args)
    ...

在生产使用中,您将调用main(),让它解析sys.argv。对于测试,您将传递一组特定的参数。你知道吗

def test_main(capfd):
    main(['[a-z]*', 'foo.txt', '-u'])  # For example
    out, err = capfd.readouterr()
    assert out == "my expected output"

相关问题 更多 >