• Python基础学习总结(九)


    11测试代码

       1.编写函数和类时,还可以编写测试函数,通过测试可以确定代码面对各种输入都能正常工作。在程序中添加新代码时,也可以对其进行测试,确定他们不会破坏程序的既有程序。要经常测试模块。

      2.通过python的模块unittest中的工具来测试代码。将明白测试通过是怎么样的,未通过是什么样的,知道未通过测试怎么来改善代码,知道要为项目编写多少测试。知道怎么测试函数和类。

      3.在程序运行过程中,总会遇到各种各样的错误。有的错误是程序编写有问题造成的,比如本来应该输出整数结果输出了字符串,这种错误我们通常称之为bug,bug是必须修复的。

    11.1测试函数

    11.1.1单元测试和测试用例

       Python中的unittest模块提供代码测试工具,单元测试用来核实函数某个方面没有问题。测试用例是一组单元测试,确保函数在各个方面都没有问题。

      全覆盖式测试用例包含一整套的测试用例,涵盖了各种可能的函数使用方式。

    11.1.2可通过测试

      要为函数编写测试函数,先导入模块unittest和要测试的涵数,在创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。命名最好带有test。

      name_function.py

    1 def get_formatted_name(first, last):   
    2   """获得全名."""   
    3   full_name = first + ' ' + last   
    4   return full_name.title()

      names.py

     1 from name_function import get_formatted_name
     2 print("Enter 'q' at any time to quit.")
     3 while True:   
     4     first = input("
    Please give me a first name: ")   
     5     if first == 'q':       
     6         break   
     7     last = input("Please give me a last name: ")   
     8     if last == 'q':       
     9         break   
    10     formatted_name = get_formatted_name(first, last)   
    11   print("	Neatly formatted name: " + formatted_name + '.')

      test_name_function.py

    1 import unittest 
    2 from name_function import get_formatted_name
    3 class NamesTestCase(unittest.TestCase):     
    4     """测试name_function.py"""     
    5     def test_first_last_name(self):         
    6     """能够正确地处理像Janis Joplin这样的姓名吗?"""          
    7         formatted_name = get_formatted_name('janis', 'joplin')  
    8         self.assertEqual(formatted_name, 'Janis Joplin') 
    9   unittest.main()   

      unittest最有用的功能之一:一个断言方法,assertEqual断言方法用来核实得到的结果是否和期望的值一样。

    11.1.3不能通过的测试

      测试没有通过,不要修改测试,而应修复导致测试不能通过的代码:检查刚对函数所做的修改,找出导致函数行为不符合预期的修改。

    11.2.1模块中的各种断言方法

      6个常见断言

    方法

    用途

    assertEqual(a, b)

    核实a == b

    assertNotEqual(a, b)

    核实 a != b

    assertTrue(x)

    核实 x 为True

    assertFalse(x)

    核实 x 为False

    assertIn(item, list)

    核实 item在list中

    assertNotIn(item, list)

    核实 item不在list中

  • 相关阅读:
    转:NetBackup 7.5:放下磁带,才能走更远?
    HP NIC Teaming技术探讨
    Lagged Mailbox Database Copy in Exchange 2010
    Netbackup SSO
    Move or migrate user accounts from old Linux server to a new Linux server
    转:VMware vsphere 5.0新体验总结
    VMware vSphere: What’s New [V 5.1]
    windows server 2008 R2上安装MRTG指南
    VMware vCenter vDS 分布式交换机
    VMware vSphere: Install, Configure, Manage [V5.0]
  • 原文地址:https://www.cnblogs.com/zt19994/p/7183246.html
Copyright © 2020-2023  润新知