python 为类/类方法实现assertRaises单元测试

svmlkihl  于 2022-11-28  发布在  Python
关注(0)|答案(1)|浏览(144)

我用Python写了一个类,它是用几个参数初始化的。
我正在尝试写一个测试,检查是否所有的参数都是int,否则抛出TypeError。
下面是我的尝试:

import unittest
from footer import Footer

class TestFooter(unittest.TestCase):

    def test_validInput(self):
        footer = Footer(4,5,1,0)
        self.assertTrue(footer.validInput())
        #attempt 1:
        footer1 = Footer("four","five",1,0)
        self.assertRaises(TypeError, footer1.validInput())
        #attempt 2:
        with self.assertRaises(TypeError):
            Footer("four",5,1,0)

if __name__ == '__main__':
    unittest.main()

但是,这是行不通的,我不明白为什么。
下面是我正在编写的测试的类:

class Footer:
    def __init__(self, current_page: int, total_pages: int, boundaries: int, around: int):
        self.current_page = current_page
        self.total_pages = total_pages
        self.boundaries = boundaries
        self.around = around
        try:
            if (self.validInput()):
                footer = self.createFooter()
                self.addEllipsis(footer)
        except Exception as e:
            print(f"\nError while initializing Footer Class ({e.__class__}).\n Please fix the following: ", e)
        
    def validInput(self) -> bool:
        if (type(self.total_pages) != int or type(self.boundaries) != int or type(self.around) != int or type(self.current_page) != int ):
            raise TypeError("Invalid input. All the arguments must be of type int.")
        if (self.total_pages < 0 or self.boundaries < 0 or self.around < 0 or self.current_page < 0):
            raise ValueError("Invalid values. Please do not provide negative values.")
        if (self.current_page > self.total_pages):
            raise ValueError("Current page must be within the total number of pages")
        return True

    def createFooter(self) -> list:
        footer = []
        for page in range(1, self.total_pages + 1):
            if (page <= self.boundaries):
                footer.append(page)
            elif (page > self.total_pages-self.boundaries):
                footer.append(page)
            elif (page == self.current_page):
                footer.append(page)
            elif ((page > self.current_page and page <= (self.current_page + self.around)) or (page < self.current_page and page >= self.current_page - self.around)):
                footer.append(page)
        return footer

    def addEllipsis(self, footer: list) -> None:
        final_footer = [] 
        i = 0
        for page in footer:
            try :
                final_footer.append(page)
                if(footer[i + 1] - footer[i] > 1):
                    final_footer.append("...")
            except IndexError:
                break
            i += 1
        print("\n", ' '.join(str(page) for page in final_footer))

以下是测试的输出:

k10s72fa

k10s72fa1#

assertRaises的使用方法是错误的:

import unittest

def this_func_raises():
    raise ValueError

class TestClass(unittest.TestCase):
    def test1(self):
        self.assertRaises(ValueError, this_func_raises())

请注意,如果您包含(),则会引发ValueError,因为这会执行this_func_raises,而且不会拦截例外状况。
而这才是正确的方式:

import unittest

def this_func_raises():
    raise ValueError

class TestClass(unittest.TestCase):
    def test1(self):
        self.assertRaises(ValueError, this_func_raises)

请注意,您的程式码中还有其他几个问题。例如:

with self.assertRaises(TypeError):
    Footer("four", 5, 1, 0)

应该是这样的:

with self.assertRaises(TypeError):
    Footer("four", 5, 1, 0).validInput()

最后,您需要用pass替换self.createFooter(),直到您实现它,否则您将得到另一个错误。
为了通过测试,您的代码应该如下所示:

class Footer:
    def __init__(self, current_page: int, total_pages: int, boundaries: int, around: int):
        self.current_page = current_page
        self.total_pages = total_pages
        self.boundaries = boundaries
        self.around = around
        try:
            if (self.validInput()):
                # self.createFooter()
                pass
        except Exception as e:
            print(f"\nError while initializing Footer Class ({e.__class__}).\n Please fix the following: ", e)

    def validInput(self) -> bool:
        if (type(self.total_pages) != int or type(self.boundaries) != int or type(self.around) != int or type(
                self.current_page) != int):
            raise TypeError("Invalid input. All the arguments must be of type int.")
        if (self.total_pages < 0 or self.boundaries < 0 or self.around < 0 or self.current_page < 0):
            raise ValueError("Invalid values. Please do not provide negative values.")
        if (self.current_page > self.total_pages):
            raise ValueError("Current page must be within the total number of pages")
        return True

测试文件:

import unittest

class TestFooter(unittest.TestCase):

    def test_validInput(self):
        footer = Footer(4, 5, 1, 0)
        self.assertTrue(footer.validInput())
        # attempt 1:
        footer1 = Footer("four", "five", 1, 0)
        self.assertRaises(TypeError, footer1.validInput)
        # attempt 2:
        with self.assertRaises(TypeError):
            Footer("four", 5, 1, 0).validInput()

if __name__ == '__main__':
    unittest.main()

相关问题