首页 > 解决方案 > 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)

标签: pythonpython-3.xpytest

解决方案


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

推荐阅读