我是 Python 和 PyTest 的新手。我编写了一个程序,计算另一个 python 文件的代码行数。源代码如下:
import os.path
import sys
def main():
print(count_loc(is_input_valid(sys.argv)))
def is_input_valid(cl_arg)->str:
if len(cl_arg) == 2:
if cl_arg[1][-3:] == '.py':
if os.path.isfile(cl_arg[1]):
filename = cl_arg[1]
else:
sys.exit("File does not exist")
else:
sys.exit("File is not a python(.py) file")
else:
sys.exit("Too few or many command-line arguments")
return filename
def count_loc(filename:str)->int:
counter = 0
with open(filename) as file:
for row in file:
if row[0].lstrip() != '#' and not row.isspace():
counter += 1
return counter
if __name__ == '__main__':
main()
基于此,我使用 PyTest 编写了一个测试文件,如下所示:
from lines import is_input_valid, count_loc
import pytest
def test_input():
with pytest.raises(SystemExit, match = "Too few or many command-line arguments"):
is_input_valid("filename foo.bar lang.py")
is_input_valid("filename")
def test_file_name():
with pytest.raises(SystemExit, match = "File is not a python(.py) file"):
is_input_valid("filename foo.bar")
is_input_valid("filename file.txt")
def test_file_exists():
with pytest.raises(SystemExit) as e:
is_input_valid("filename abdcgr.py")
assert e.value == "File does not exist"
def test_count_loc():
assert count_loc("fuel.py") == 20
尝试调试后,看起来 PyTest 函数只是跳转到 is_input_valid 函数中的最后一个 else 语句,无论我在那里给出什么输入,因此只有第一个测试函数通过“命令行参数太少或太多” 。所有其他 test_input 函数都会失败。我使用相同的输入运行源代码,它的工作原理与预期完全一致。我不知道 PyTest 函数出了什么问题以及为什么它们无法捕获其他退出异常。
运行源代码时,我尝试了与命令行参数相同的输入,并且输出与预期完全一致。
但是当 PyTest 函数执行时,它总是跳转到 is_valid_input 函数中的最后一个 else 语句,并捕获相同的退出异常,无论该函数的输入如何。
您的测试用例是错误的。
is_input_valid()
的参数应该是一个字符串列表——第一个字符串是脚本名称,第二个字符串是要检查的文件的名称。您只需传递一个字符串,即整个命令行。
您可以使用
split()
将其拆分为列表。
def test_input():
with pytest.raises(SystemExit, match = "Too few or many command-line arguments"):
is_input_valid("filename foo.bar lang.py".split())
is_input_valid("filename".split())
def test_file_name():
with pytest.raises(SystemExit, match = "File is not a python(.py) file"):
is_input_valid("filename foo.bar".split())
is_input_valid("filename file.txt".split())
def test_file_exists():
with pytest.raises(SystemExit) as e:
is_input_valid("filename abdcgr.py".split())
assert e.value == "File does not exist"