day 8 python 从入门到实践——测试代码

  • 测试单个函数——使用到unittest模块
import unittest
from name_function import get_formatted_name
class 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')#assertEqual()断言方法,检验formatted_name的值与'Janis Joplin'是否相等
   def test_first_last_middle_name(self):
       """正确处理Wolfgang Amadeus Mozart这样的名字?"""
       formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
       self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')

unittest.main()

#practice
from city_functions import city_country
import unittest
class City_CountryTestCase(unittest.TestCase):
   """测试city_country()"""
   def test_city_country(self):
       """正确处理Santiago, Chile这样的字符串?"""
       full_city_country_test = city_country('santiago', 'chile', 5000000)
       self.assertEqual(full_city_country_test, 'Santiago, Chile-Population 5000000')
unittest.main()
  • 测试类
#测试类——通过创建实例
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""
    def setUp(self):
        """
        创建一个调查对象与一组答案
        供使用的测试方法使用
        """
        question = 'What language did you first learn to speak?'
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['English', 'Spanish', 'Mandarin']
    def test_store_single_response(self):
        """测试单个答案被妥善存储"""
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)#断言assertIn()判断第一个元素是否在第二个列表中
    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)

unittest.main()

你可能感兴趣的:(学习记录,python)