所以我有这行代码,我该如何使用pytest测试try和except部分?我想测试是否输入了字符串,测试将注意到它,并回答说输入错误,如果输入整数,则测试将通过。请帮助我,谢谢
def add_member(self):
p_name = input("Enter your project name: ")
i = 0
participant_name=[]
role=[]
while True:
try:
many = int(input ("How many member do you want to add ?: "))
while i< many:
i+=1
participant_name.append(str(input("Enter name: ")) )
role.append(str(input("Enter role: ")))
break
except ValueError:
print("Insert an integer")
self.notebook.add_member(p_name, participant_name, role)
答案 0 :(得分:0)
首先,您在try
块中有太多代码。唯一引起ValueError
(错误消息准确解决)的问题是第一行对int
的调用。其次,不要在计划测试的代码中硬编码input
;而是将第二个参数 defaults 传递给input
,但允许您提供确定性的函数进行测试。
def add_member(self, input=input):
p_name = input("Enter your project name: ")
participant_names = []
roles = []
while True:
try:
many = int(input("How many member do you want to add? "))
break
except ValueError:
print("Enter an integer")
for i in range(many):
name = input("Enter name: ")
role = input("Enter role: ")
participant_names.append(name)
roles.append(role)
self.notebook.add_member(p_name, participant_names, roles)
def make_input(stream):
def _(prompt):
return next(stream)
return _
def test_add_member():
x = Foo()
x.add_member(make_input(["Manhattan", "0"])
# assert that x.notebook has 0 participants and roles
x = Foo()
x.add_member(make_input(["Omega", "ten", "2", "bob", "documentation", "alice", "code"]))
# assert that self.notebook has bob and alice in the expected roles
但是,更好的是,要求输入的代码可能应该与该方法完全分开,该方法应仅使用项目名称和一组参与者 及其角色(不是两个单独的列表)。该集合可以是一个元组列表,也可以是一个字典,但是它应该不允许每个参与者的名字和他们的角色不匹配。
def add_member(self, name, participants):
self.notebook.add(name, [x[0] for x in participants], [x[1] for x in participants])
def test_add_member():
x = Foo()
x.add_member("Manhattan", [("bob", "documentation"), ("alice", "code")])
# same assertion as before