python学习10:测试代码

python学习10:测试代码

1 测试函数

python标准库中的模块unittest提供了代码测试工具。
单元测试用于核实函数的某个方面没有问题。测试用例是一组单元测试,核实各种情形。
要测试的代码:

def get_formatted_name(first, last):
    """generate neat names"""
    full_name = f"{first} {last}"
    return full_name.title()

测试代码:

import unittest
from name_function import get_formatted_name


class NamesTestCase(unittest.TestCase):
    """test name_function.py"""

    def test_first_last_name(self):
        """can you handle names like liu yang correctly"""
        formatted_name = get_formatted_name('liu', 'yang')
        self.assertEqual(formatted_name, 'Liu Yang')


if __name__ == '__main__':
    unittest.main()
  • 先导入模块unittest和要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同进行测试。
  • 该类中包含一个方法,用于测试get_formatted_name的一个方面,方法命名为test_first_last_name(),因为所有开头为test_的方法都会自动运行
  • 使用了unittest类最有用的功能之一:断言方法。核实得到的结果是否与期望的结果一致
  • 测试未通过时,不要修改测试,而应该修复导致测试不能通过的代码。

2 测试类

2.1 各种断言方法

使用下述方法可核实返回值等或不等于预期值,返回值为True或False,以及返回的值是否在列表中,且只能再继承unittest.TestCase的类中使用这些方法。

方法用途
assertEqual(a,b)核实a==b
assertNotEqual(a,b)核实a!=b
assertTrue(a,b)核实x为True
assertFalse(x)核实x为False
assertIn(item,list)核实item在list中
assertNotIn(item,list)核实item不在list中

2.2 一个要测试的类

类如下:

class AnonymousSurvey:
    """collect answers to anonymous questionnaires"""

    def __init__(self, question):
        """store q question and prepare for storing answers"""
        self.question = question
        self.responses = []

    def show_question(self):
        """show questionnaire"""
        print(self.question)

    def store_response(self, new_response):
        """store a single questionnaire"""
        self.responses.append(new_response)

    def show_results(self):
        """display all questionnaires collected"""
        print("Survey results:")
        for response in self.responses:
            print(f"- {response}")

2.3 测试类

核实用户提供一个或三个答案时可以被妥善存储。

import unittest
from survey import AnonymousSurvey


class TestAnonymousSurvey(unittest.TestCase):
    """test for AnonymousSurvey class"""

    def test_store_single_response(self):
        """the single answers to the test will be stored properly"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')
        self.assertIn('English', my_survey.responses)

    def test_store_three_response(self):
        """three answers to the test will be stored properly"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['English', 'spanlish', 'chinese']
        for response in responses:
            my_survey.store_response(response)
        for response in responses:
            self.assertIn(response, my_survey.responses)


if __name__ == '__main__':
    unittest.main()

2.4 方法setUp()

  • unittest.TestCase类包含的方法setUp()让我们只需创建这些对象一次,就能在每个测试方法中使用。
  • 如果在TestCase类中包含了方法setUp(),python将先运行它,再运行各个以test_打头的方法。

3 参考文献

python从入门到实践

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值