python - pytest - how can i test a try and except code
问题描述
so i have this line of code, how can i test the try and except part using pytest ? i want to test if i input a string the test will notice it and response saying wrong input and if i input a integer the test will passed. help me please thanks
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)
解决方案
try
首先,您的代码块中有太多代码。那里唯一引发 a ValueError
(您的错误消息准确地解决)的是第一行的调用int
。其次,不要input
在计划测试的代码中硬编码;相反,传递第二个参数,该参数默认为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
不过,更好的是,要求输入的代码可能应该与 this 方法完全分开,它应该只接受一个项目名称和一组参与者及其角色(而不是两个单独的列表)。该集合可以是元组列表或字典,但它应该是不允许每个参与者的名称与其角色之间不匹配的东西。
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
推荐阅读
- scala - 如何在 .withColumn 函数中获取列的整数值?[火花-斯卡拉]
- linux - 如何使用 Bash 在行首删除换行符和字符?
- apache-spark - 数据块中的存储选项
- javascript - 如何默认选择第一个值?
- sql - 将表连接到视图
- javascript - 函数 findOne 将数组和查询作为输入并在包含查询的数组中查找对象
- r - 使用 %dopar% 和 %do% 的不同结果
- javascript - 当使用 JQuery 满足条件时如何自动运行 JS 函数而不会出错?
- javascript - 如何在打印页面上添加 CSS?
- php - Codeigniter 会话已过期 - 更新数据库