《Python编程:从入门到实践》知识点 第11章 测试代码

《Python编程:从入门到实践》知识点 第2-4章

《Python编程:从入门到实践》知识点 第5-7章

《Python编程:从入门到实践》知识点 第8章 函数

《Python编程:从入门到实践》知识点 第9章 类

《Python编程:从入门到实践》知识点 第10章 文件和异常

测试函数

  • Python标准库中的模块unittest提供了代码测试工具
  • 单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求
  • 测试的类命名时,最好让它看起来与要测试的函数相关,并包含字样Test,这个类必须继承 unittest.TestCase类,类里所有以test_打头的方法都将自动运行
  • assertEqual是断言方法,用来核实得到的结果是否与期望的结果一致
  • 运行测试用例时,每完成一个单元测试,Python都打印一个字符:测试通过时打印一个句点;测试引发错误时打印一个E;测试导致断言失败时打印一个F
. 
#第1行的句点表明有一个测试通过了
---------------------------------------------------------------------- 
Ran 1 test in 0.000s 
#接下来的一行指出Python运行了一个测试,消耗的时间不到0.001秒
OK 
#最后的OK表明该测试用例中的所有单元测试都通过了
#name_function.py
def get_formatted_name(first, last, middle=''):
    """Generate a neatly-formatted full name."""
    full_name = first + ' ' + middle + ' ' + last
    return full_name.title()
#test_name_function.py
import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """Tests for 'name_function.py'."""
    
    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')
        
    def test_first_last_middle_name(self):
        formatted_name = get_formatted_name(
            'wolfgang', 'mozart', 'amadeus')
        self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
            

unittest.main()
#运行结果
.E
======================================================================
ERROR: test_first_last_name (__main__.NamesTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "E:/project/python_work/hello/helloworld.py", line 9, in test_first_last_name
    formatted_name = get_formatted_name('janis', 'joplin')
TypeError: get_formatted_name() missing 1 required positional argument: 'middle'

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (errors=1)
  • 第一行有一个E error,测试用例中有一个单元测试导致了错误
  • 可以看出来是test_first_last_name导致了错误
  • 可以看出来是get_formatted_name有问题,少了参数
  • 运行了两个单元测试,有一个错误

测试类

在这里插入图片描述

  • 如果在TestCase类中包含了方法setUp(),Python将先运行它,再运行各个以test_打头的方法。这样每个测试方法中都可使用在方法setUp()中创建的对象了
#survey.py
class AnonymousSurvey():
    """收集匿名调查问卷的答案"""

    def __init__(self, question):
        """存储问题,并为存储答案做准备"""
        self.question = question
        self.responses = []

    def show_question(self):
        """显示问题"""
        print(question)

    def store_response(self, new_responses):
        """存储答案"""
        self.responses.append(new_responses)

    def show_results(self):
        """显示答卷"""
        print("Survey results:")
        for response in responses:
            print('- ' + response)
#test_survey.py
import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""

    def setUp(self) -> None:
        """创建一个问题和一组答案,供测试方法使用"""
        question = "What language did you first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['English', 'Spanish', 'Mandarin']
        #变量名包含前缀self(即存储在属性中),因此可在这个类的任何地方使用

    def test_store_single_response(self):
        """测试单个答案"""
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)

    def test_store_three_responses(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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值