Python 如何测试没有用户函数但使用内置输入函数的脚本?

Python 如何测试没有用户函数但使用内置输入函数的脚本?,python,Python,给定脚本rectangle.py 如何按原样测试脚本。 我不知道如何按原样在doctest、unittest或pytest中测试它。 我的问题本质上是,测试如何在测试期间响应输入提示 """ Compute the area of a rectangle. """ width = int(input("Enter the width: ")) height = int(input("Enter the he

给定脚本rectangle.py
如何按原样测试脚本。
我不知道如何按原样在doctest、unittest或pytest中测试它。
我的问题本质上是,测试如何在测试期间响应输入提示

"""
Compute the area of a rectangle.
"""
width = int(input("Enter the width: "))
height = int(input("Enter the height: "))
area = width * height
print (f"The area is {area}.")
通过多次运行脚本进行测试的示例

C:\TestingDoctest>py rectangle.py
Enter the width: 9
Enter the height: 8
The area is 72.

C:\TestingDoctest>py rectangle.py
Enter the width: 6
Enter the height: 7
The area is 42.

C:\TestingDoctest>py rectangle.py
Enter the width: 8
Enter the height: 9
The area is 72.

C:\TestingDoctest>py rectangle.py
Enter the width: 8.8
Traceback (most recent call last):
  File "C:\TestingDoctest\rectangle.py", line 1, in <module>
    width = int(input("Enter the width: "))
ValueError: invalid literal for int() with base 10: '8.8'

C:\TestingDoctest>
C:\TestingDoctest>py rectangle.py
输入宽度:9
输入高度:8
面积是72。
C:\TestingDoctest>py rectangle.py
输入宽度:6
输入高度:7
面积是42。
C:\TestingDoctest>py rectangle.py
输入宽度:8
输入高度:9
面积是72。
C:\TestingDoctest>py rectangle.py
输入宽度:8.8
回溯(最近一次呼叫最后一次):
文件“C:\TestingDoctest\rectangle.py”,第1行,在
宽度=int(输入(“输入宽度:”)
ValueError:基数为10的int()的文本无效:“8.8”
C:\TestingDoctest>

如果不将其包装在函数中,我不确定您将如何测试它。然而,简单地将其包装在一个函数中,如

chris.py

def rectangle_area():
"""
计算矩形的面积。
"""
宽度=int(输入(“输入宽度:”)
高度=整数(输入(“输入高度:”)
面积=宽度*高度
打印(f“区域为{area}.”)
如果名称=“\uuuuu main\uuuuuuuu”:
矩形面积()
我将通过模拟输入函数并使用sideaffect传递值来测试它。然后使用capf捕获打印输出。我在这里使用模块
pytest mock
,但unittest及其mock方法也可以实现类似的功能

测试chris.py

从chris导入矩形区域
导入pytest
def测试\矩形\区域\有效\字符串\输入(模拟、capfd):
测试输入=mocker.patch(“chris.input”)
测试输入。副作用=(“5”,“10”)
矩形面积()
out,err=capfd.readouterr()
assert out==f“面积为50。\n”
def test_rectange_area_无效_字符串(模拟程序):
使用pytest.raises(ValueError):
测试输入=mocker.patch(“chris.input”)
测试输入。副作用=(“10.5”,“10”)
矩形面积()
我添加了两个测试函数,一个用于检查有效整数是否返回预期输出,另一个用于检查无效整数是否引发ValueError

输出

插件:Faker-8.1.2,mock-3.6.1
收集2项
test\u chris.py::test\u矩形\u区域\u有效\u字符串\u通过的整数[50%]
test\u chris.py::test\u rectange\u area\u传递的字符串无效[100%]
===================================================================================================================2以0.17秒通过==================================================================

这是否回答了您的问题?你不把它放在函数中有什么原因吗?我不放在函数中的原因是我不会测试我的代码。我将有多个学生提交每个作业的代码。我刚刚开始研究测试他们代码的可行性。我看到了许多潜在的问题。在课程的早期,他们不会意识到用户函数。我将查看链接。@Superformer我将进一步查看建议的链接。谢谢您的输入。我将对其进行审查并作出进一步回应。感谢您的投入。我学到了一些新东西。根据提供的注释和代码,我认为我应该尝试另一种方法。解析文件以验证其符合分配规范和测试的一些组合。也许将学生代码包装在函数中并使用装饰器。