zoukankan      html  css  js  c++  java
  • 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标准库
  • 相关阅读:
    如何优雅的进行表结构设计
    获取windows身份认证网站页面内容
    angularjs filter 详解
    OpenFileDialog 害人的RestoreDirectory
    iscroll5 版本下的 上拉,下拉 加载数据
    EasyUI Combotree 只允许选择 叶子节点
    国内5款优秀的WEB前端框架
    Serv-U无法连接到服务器127.0.0.1,端口43958 FTP服务器不能启动
    Directory.GetCurrentDirectory和Application.StartupPath的区别
    Winform 窗体设计器 无法识别重复成员变量声明的问题
  • 原文地址:https://www.cnblogs.com/rainights/p/11778303.html
Copyright © 2011-2022 走看看