不通过命令行将变量分配给argparse

时间:2019-05-31 18:11:07

标签: python pytest argparse

我正在尝试为脚本编写测试(使用pytest),但是我不知道如何创建/传递参数给main(),特别是当它不接收参数时。即使我将其更改为def main(args = None):,它也会在第一行将其启动。

tests.py

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

script.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])```

2 个答案:

答案 0 :(得分:0)

在测试代码中,您将patch抽出sys.argv,然后再调用main

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

答案 1 :(得分:0)

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"