我用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))
以下是测试的输出:
1条答案
按热度按时间k10s72fa1#
assertRaises
的使用方法是错误的:请注意,如果您包含
()
,则会引发ValueError,因为这会执行this_func_raises
,而且不会拦截例外状况。而这才是正确的方式:
请注意,您的程式码中还有其他几个问题。例如:
应该是这样的:
最后,您需要用
pass
替换self.createFooter()
,直到您实现它,否则您将得到另一个错误。为了通过测试,您的代码应该如下所示:
测试文件: