AI智能
改变未来

python进阶(8)–测试函数与类

一、测试函数(unittest)

1、源文件方法(name_function.py):

def get_formatted_name(first,last):\"\"\"生成全名\"\"\"full_name=f\"{first} {last}\"return  full_name.title()

2、通过unittest测试(test_name_function.py)

import unittestfrom name_function import get_formatted_nameclass NamesTestCase( unittest.TestCase ):\"\"\"测试name_function.py\"\"\"def test_first_last_name(self):\"\"\"能够正确的处理Janis Joplin这样的姓名\"\"\"formatted_name=get_formatted_name(\'janis\',\'joplin\')self.assertEqual( formatted_name, \'Janis Joplin\' )if __name__ == \'__main__\':unittest.main()

查看运行结果:

Ran 1 test in 0.003sOK

二、测试类(unittest)

1、源文件类(survey.py)

class AnonymousSurvey:\"\"\"收集匿名蒂阿查问卷的答案\"\"\"def __init__(self,question):\"\"\"存储一个问题,并为存储答案做准备\"\"\"self.question=questionself.responses=[]def show_question(self):\"\"\"显示调查问卷\"\"\"print(self.question)def store_response(self,new_response):\"\"\"存储单份调查问卷\"\"\"self.responses.append(new_response)def show_results(self):\"\"\"显示收集到的手机答案\"\"\"print(\"Survey results\")for response in self.responses:print(f\" - {response}\")

2、通过unittest测试(test)

import unittestfrom survey import AnonymousSurveyclass TestAnonymousSurvey( unittest.TestCase ):\"\"\"针对AnonymousSurvey类的测试\"\"\"def test_store_single_response(self):question=\"What language did you first learn to speak?\"my_survey=AnonymousSurvey(question)my_survey.store_response(\'English\')self.assertIn( \'English\', my_survey.responses )def test_store_three_response(self):\"\"\"测试三个答案并存储正确\"\"\"question=\"What language did you first learn to speak?\"my_survey=AnonymousSurvey(question)responses=[\'English\',\'Spanish\',\'Chinese\']for response in responses:my_survey.store_response(response)for response in responses:self.assertIn( response, my_survey.responses )if __name__ == \'__main__\':unittest.main()

查看结果:

Ran 2 tests in 0.002sOK

1f1b三、setp()与tearDown()方法:初始化与清理程序

import unittestfrom survey import AnonymousSurveyclass TestAnonymousSurvey( unittest.TestCase ):def setUp(self):question = \"What language did you first learn to speak?\"self.my_survey=AnonymousSurvey(question)self.responses = [\'English\', \'Spanish\', \'Chinese\']def tearDown(self):self.responses.clear()def test_store_single_response(self):\"\"\"针对AnonymousSurvey类的测试\"\"\"self.my_survey.store_response( self.responses[0] )self.assertIn( self.responses[0], self.my_survey.responses )def test_store_three_response(self):\"\"\"测试三个答案并存储正确\"\"\"for response in self.responses:self.my_survey.store_response( response )for response in self.responses:self.assertIn( response, self.my_survey.responses )if __name__ == \'__main__\':unittest.main()

查看运行结果:

Ran 2 tests in 0.001sOK

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » python进阶(8)–测试函数与类