pytest - 我如何测试 try 和 except 代码

所以我有这行代码,我如何使用 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)


婷婷同学_
浏览 432回答 1
1回答

摇曳的蔷薇

首先,try块中的代码太多。唯一引发 a ValueError(您的错误消息准确解决)的是int第一行的调用。其次,不要input在你计划测试的代码中硬编码;相反,传递默认为的第二个参数input,但允许您提供用于测试的确定性函数。def add_member(self, input=input):&nbsp; &nbsp; p_name = input("Enter your project name: ")&nbsp; &nbsp; participant_names = []&nbsp; &nbsp; roles = []&nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; many = int(input("How many member do you want to add? "))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Enter an integer")&nbsp; &nbsp; for i in range(many):&nbsp; &nbsp; &nbsp; &nbsp; name = input("Enter name: ")&nbsp; &nbsp; &nbsp; &nbsp; role = input("Enter role: ")&nbsp; &nbsp; &nbsp; &nbsp; participant_names.append(name)&nbsp; &nbsp; &nbsp; &nbsp; roles.append(role)&nbsp; &nbsp; self.notebook.add_member(p_name, participant_names, roles)def make_input(stream):&nbsp; &nbsp; def _(prompt):&nbsp; &nbsp; &nbsp; &nbsp; return next(stream)&nbsp; &nbsp; return _def test_add_member():&nbsp; &nbsp; x = Foo()&nbsp; &nbsp; x.add_member(make_input(["Manhattan", "0"])&nbsp; &nbsp; # assert that x.notebook has 0 participants and roles&nbsp; &nbsp; x = Foo()&nbsp; &nbsp; x.add_member(make_input(["Omega", "ten", "2", "bob", "documentation", "alice", "code"]))&nbsp; &nbsp; # assert that self.notebook has bob and alice in the expected roles不过,更好的是,要求输入的代码可能应该与 this 方法完全分开,它应该只需要一个项目名称和一组参与者及其角色(而不是两个单独的列表)。该集合可以是元组列表或字典,但它应该是不允许每个参与者的名称与其角色不匹配的东西。def add_member(self, name, participants):&nbsp; &nbsp; self.notebook.add(name, [x[0] for x in participants], [x[1] for x in participants])def test_add_member():&nbsp; &nbsp; x = Foo()&nbsp; &nbsp; x.add_member("Manhattan", [("bob", "documentation"), ("alice", "code")])&nbsp; &nbsp; # same assertion as before
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python