我正在尝试为脚本编写测试(使用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])```
在测试代码中,您可以在调用
main
之前patch退出sys.argv
:parse_args
可以使用显式的None
参数来告诉它解析sys.argv[1:]
。编写代码以便于测试:在生产使用中,您将调用
main()
,让它解析sys.argv
。对于测试,您将传递一组特定的参数。你知道吗相关问题 更多 >
编程相关推荐