[英]How to write unit test for code with inputs (Python)
我是单元测试的新手,我必须添加一个单元测试类来解决问题。 问题是在这里找到的一个https://practice.geeksforgeeks.org/problems/penalty-shooters/0# ,我的代码如下。 我无法弄清楚如何使用用户输入进行单元测试。
T = int(input())
for x in range(T):
# Allows us to input and apply method to all iterables in a | no. of tests \n x_energy y_energy z_energy | format. T = number of tests, x is Lohia energy, y is Gosu energy and z is Goalkeeper energy
x, y, z = list(map(int, input().split(" ")))
Goal_Lohia, Goal_Gosu = 0, 0
# Session ends when goalkeepers energy decrements to 1
while z > 1:
# Goalkeepers energy in this case is a factor of both strikers' energy, so both score.
if x % z == 0 and y%z == 0:
x = x - 1
Goal_Lohia = Goal_Lohia + 1
y = y - 1
Goal_Gosu = Goal_Gosu + 1
# In this case, the goalkeepers energy is only a factor of Lohia's. Note Lohia goes first as the problem states.
elif x % z == 0:
x = x - 1
Goal_Lohia = Goal_Lohia + 1
# And in this case, it is only a factor of Gosu's
elif y % z == 0:
y = y - 1
Goal_Gosu = Goal_Gosu + 1
# If goalkeepers energy is a factor of neither Gosu nor Lohia, the goalkeeper will save (no goal scored) and will lose energy.
else:
z = z - 1
print(Goal_Lohia, Goal_Gosu)
非常感谢!
您想重构您的代码,以便您可以通过获取用户输入和提供硬编码值来调用代码。 然后可以在程序正常运行时调用一个版本,在运行测试时调用另一个版本。
您可以类似地分离出对输出执行的操作,以便您可以在正常情况下打印输出,但在测试用例中检查它的正确性。
以下是您的代码的样子:
def function_to_test(T):
for x in range(T):
# Allows us to input and apply method to all iterables in a | no. of tests \n x_energy y_energy z_energy | format. T = number of tests, x is Lohia energy, y is Gosu energy and z is Goalkeeper energy
x, y, z = list(map(int, input().split(" ")))
Goal_Lohia, Goal_Gosu = 0, 0
...
return Goal_Lohia, Goal_Gosu
def function_that_takes_user__input():
T = int(input())
Goal_Lohia, Goal_Gosu = function_to_test(T)
print(Goal_Lohia, Goal_Gosu)
def test_the_function():
Goal_Lohia, Goal_Gosu = function_to_test(<test input 1>)
# add code to test result here
Goal_Lohia, Goal_Gosu = function_to_test(<test input 2>)
# add code to test result here
最好的方法是将此逻辑提取为纯函数并将解析后的数据传递给它:
def logic(records):
for x, y, z in records:
...
return goal_lohia, goal_gosu
def main():
t = int(input())
records = []
for _ in range(t):
records.append(list(int(c) for c in input().split()))
print(logic(records))
现在您可以独立于输入/输出问题来测试logic()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.