• Python学习笔记之测试函数


    11-1 城市和国家:编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为City, Country 的字符串,如Santiago, Chile。将这个函数存储在一个名为city _functions.py 的模块中。

    创建一个名为test_cities.py 的程序,对刚编写的函数进行测试(别忘了,你需要导入模块unittest 以及要测试的函数)。编写一个名为test_city_country()的方法,核实使用类似于'santiago'和'chile'这样的值来调用前述函数时,得到的字符串是正确的。运行test_cities.py,确认测试test_city_country()通过了。

    city _functions.py

    1 def city_country(city, country):
    2     city_name = city + ', ' + country
    3     return city_name.title()

    test_city_country()

     1 import unittest
     2 from city_function import city_country
     3 
     4 class CityTestCase(unittest.TestCase):
     5     """测试city_function.py"""
     6 
     7     def test_city_country(self):
     8         city_name = city_country('santiago', 'chile')
     9         self.assertEqual(city_name, 'Santiago, Chile')
    10 
    11 unittest.main()

    11-2 人口数量:修改前面的函数,使其包含第三个必不可少的形参population,并返回一个格式为City, Country – population xxx 的字符串,如Santiago, Chile – population 5000000。运行test_cities.py,确认测试test_city_country()未通过。
    修改上述函数,将形参population 设置为可选的。再次运行test_cities.py,确认测试test_city_country()又通过了。
    再编写一个名为test_city_country_population()的测试,核实可以使用类似于'santiago'、'chile'和'population=5000000'这样的值来调用这个函数。再次运行test_cities.py,确认测试test_city_country_population()通过了。

    city _functions.py

    def city_country(city, country, population=''):
        if population:
            city_name = city + ', ' + country + ' - population ' + str(population)
        else:
            city_name = city + ', ' + country
        return city_name.title()

    test_cities.py

     1 import unittest
     2 from city_function import city_country
     3 
     4 class CityTestCase(unittest.TestCase):
     5     """测试city_function.py"""
     6 
     7     def test_city_country(self):
     8         city_name = city_country('santiago', 'chile')
     9         self.assertEqual(city_name, 'Santiago, Chile')
    10 
    11     def test_city_country_population(self):
    12         city_name = city_country('santiago', 'chile', population=5000000)
    13         self.assertEqual(city_name, "Santiago, Chile - Population 5000000")
    14 
    15 unittest.main()
    assertEqual()方法的作用是将要测试函数的执行结果返回的值与预期的结果对比,如果相等则Ok通过
    而assertNotEqual()与assertEqual()是相反的,若是不相等则Ok通过
    想了解更多unittest类的功能请查阅Python标准库
  • 相关阅读:
    五、drf路由组件
    四、drf视图组件
    三、drf请求&响应
    二、drf序列化器
    解决SQL Server管理器无法连接远程数据库的问题
    常见网络摄像机(摄像头)的端口及RTSP地址
    海康、大华网络摄像机RTSP URL格式组成及参数配置
    SQL 查询某字段不为空
    SqlServer中保留几位小数的两种做法
    sql重复数据只取一条记录
  • 原文地址:https://www.cnblogs.com/rainights/p/11778303.html
Copyright © 2020-2023  润新知