Python系列13-Python测试代码

一.测试函数

要学习测试,得有要测试的代码。下面是一个简单的函数,它接受名和姓并返回整洁的姓名

name_function.py

def get_formatted_name(first, last):
    """Generate a neatly formatted full name. """
    full_name = first + ' ' + last
    return full_name.title()

names.py

from name_function import get_formatted_name

print("Enter 'q' at any time to quit.")
while True:
    first = input("\nPlease give me a first name: ")
    if first == 'q':
        break
    last = input("Please give me a last name: ")
    if last == 'q':
        break

    formatted_name = get_formatted_name(first, last)
    print("\tNeatly formatted name: " + formatted_name + '.')

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/names.py
Enter 'q' at any time to quit.

Please give me a first name: bill
Please give me a last name: gates
	Neatly formatted name: Bill Gates.

Please give me a first name: q

Process finished with exit code 0

从上述输出可知,合并得到的姓名正确无误。现在假设我们要修改get_formatted_name() ,使其还能够处理中间名。这样做时,我们要确保不破坏这个函数处理只有名和姓的姓名的方式。为此,我们可以在每次修改get_formatted_name() 后都进行测试:运行程序names.py,并输入像Janis Joplin 这样的姓名,但这太烦琐了。所幸Python提供了一种自动测试函数输出的高效方式。倘若我们对get_formatted_name() 进行自动测试,就能始终信心满满,确信给这个函数提供我们测试过的姓名时,它都能正确地工作。

1.1 单元测试和测试用例

Python标准库中的模块unittest 提供了代码测试工具。单元测试 用于核实函数的某个方面没有问题;测试用例 是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。良好的测试用例考虑到了函数可能收到的各种输入,包含针对所有这些情形的测试。全覆盖式测试 用例包含一整套单元测试,涵盖了各种可能的函数使用方式。对于大型项目,要实现全覆盖可能很难。通常,最初只要针对代码的重要行为编写测试即可,等项目被广泛使用时再考虑全覆盖。

1.2 可通过的测试

创建测试用例的语法需要一段时间才能习惯,但测试用例创建后,再添加针对函数的单元测试就很简单了。要为函数编写测试用例,可先导入模块unittest 以及要测试的函数,再创建一个继承unittest.TestCase 的类,并编写一系列方法对函数行为的不同方面进行测试。

下面是一个只包含一个方法的测试用例,它检查函数get_formatted_name() 在给定名和姓时能否正确地工作:

test_name_function.py

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """测试name_function.py"""

    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

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

首先,我们导入了模块unittest 和要测试的函数get_formatted_name() 。我们创建了一个名为NamesTestCase 的类,用于包含一系列针对get_formatted_name() 的单元测试。你可随便给这个类命名,但最好让它看起来与要测试的函数相关,并包含字样Test。这个类必须继承unittest.TestCase 类,这样Python才知道如何运行你编写的测试。

NamesTestCase 只包含一个方法,用于测试get_formatted_name() 的一个方面。我们将这个方法命名为test_first_last_name() ,因为我们要核实的是只有名和姓的姓名能否被正确地格式化。我们运行testname_function.py时,所有以test 打头的方法都将自动运行。在这个方法中,我们调用了要测试的函数,并存储了要测试的返回值。

在这个示例中,我们使用实参’janis’ 和’joplin’ 调用get_formatted_name() ,并将结果存储到变量formatted_name 中。我们使用了unittest 类最有用的功能之一:一个断言方法。断言方法用来核实得到的结果是否与期望的结果一致。在这里,我们知道get_formatted_name() 应返回这样的姓名,即名和姓的首字母为大写,且它们之间有一个空格,因此我们期望formatted_name 的值为Janis Joplin 。为检查是否确实如此,我们调用unittest的方法assertEqual() ,并向它传递formatted_name 和’Janis Joplin’ 。代码行self.assertEqual(formatted_name, ‘Janis Joplin’) 的意思是说:“将formatted_name 的值同字符串’Janis Joplin’ 进行比较,如果它们相等,就万事大吉,如果它们不相等,跟我说一声!

测试记录:

Testing started at 14:22 ...
E:\python\learn_python1\venv\Scripts\python.exe "D:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\_jb_unittest_runner.py" --target test_name_function.NamesTestCase

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
Launching unittests with arguments python -m unittest test_name_function.NamesTestCase in E:\python\learn_python1


Process finished with exit code 0
Empty test suite.

1.3 不能通过的测试

测试未通过时结果是什么样的呢?我们来修改get_formatted_name() ,使其能够处理中间名,但这样做时,故意让这个函数无法正确地处理像Janis Joplin这样只有名和姓的姓名。

下面是函数get_formatted_name() 的新版本,它要求通过一个实参指定中间名:
name_function.py

def get_formatted_name(first, middle, last):
    """Generate a neatly formatted full name. """
    full_name = first + ' ' + middle + ' ' + last
    return full_name.title()

测试1.2的测试代码:

Testing started at 14:39 ...
E:\python\learn_python1\venv\Scripts\python.exe "D:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\_jb_unittest_runner.py" --target test_name_function.NamesTestCase.test_first_last_name
Launching unittests with arguments python -m unittest test_name_function.NamesTestCase.test_first_last_name in E:\python\learn_python1



Ran 1 test in 0.002s

FAILED (errors=1)

Error
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\unittest\case.py", line 59, in testPartExecutor
    yield
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\unittest\case.py", line 605, in run
    testMethod()
  File "E:\python\learn_python1\test_name_function.py", line 9, in test_first_last_name
    formatted_name = get_formatted_name('janis', 'joplin')
TypeError: get_formatted_name() missing 1 required positional argument: 'last'


Process finished with exit code 1

1.4 测试未通过时怎么办

测试未通过时怎么办呢?如果你检查的条件没错,测试通过了意味着函数的行为是对的,而测试未通过意味着你编写的新代码有错。因此,测试未通过时,不要修改测试,而应修复导致测试不能通过的代码:检查刚对函数所做的修改,找出导致函数行为不符合预期的修改。

在这个示例中,get_formatted_name() 以前只需要两个实参——名和姓,但现在它要求提供名、中间名和姓。新增的中间名参数是必不可少的,这导致get_formatted_name() 的行为不符合预期。就这里而言,最佳的选择是让中间名变为可选的。这样做后,使用类似于Janis Joplin的姓名进行测试时,测试就会通过了,同
时这个函数还能接受中间名。下面来修改get_formatted_name() ,将中间名设置为可选的,然后再次运行这个测试用例。如果通过了,我们接着确认这个函数能够妥善地处理中间名。

要将中间名设置为可选的,可在函数定义中将形参middle 移到形参列表末尾,并将其默认值指定为一个空字符串。我们还要添加一个if 测试,以便根据是否提供了中间名相应
地创建姓名:

name_function.py

def get_formatted_name(first, last, middle = ''):
    """Generate a neatly formatted full name. """
    if middle:
        full_name = first + ' ' + middle + ' ' + last
    else:
        full_name = first + ' ' + last
    return full_name.title()

在get_formatted_name() 的这个新版本中,中间名是可选的。如果向这个函数传递了中间名(if middle: ),姓名将包含名、中间名和姓,否则姓名将只包含名和姓。
现在,对于两种不同的姓名,这个函数都应该能够正确地处理。为确定这个函数依然能够正确地处理像Janis Joplin这样的姓名,我们再次运行test_name_function.py:

测试记录:

Testing started at 14:46 ...
E:\python\learn_python1\venv\Scripts\python.exe "D:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\_jb_unittest_runner.py" --target test_name_function.NamesTestCase.test_first_last_name
Launching unittests with arguments python -m unittest test_name_function.NamesTestCase.test_first_last_name in E:\python\learn_python1



Ran 1 test in 0.000s

OK

Process finished with exit code 0

1.5 添加新测试

确定get_formatted_name() 又能正确地处理简单的姓名后,我们再编写一个测试,用于测试包含中间名的姓名。为此,我们在NamesTestCase 类中再添加一个方法:

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """测试name_function.py"""

    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

    def test_first_last_middle_name(self):
        """能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗? """
        formatted_name = get_formatted_name('Wolfgang', 'Mozart', 'Amadeus')

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

我们将这个方法命名为test_first_last_middle_name() 。方法名必须以test_打头,这样它才会在我们运行test_name_function.py时自动运行。这个方法名清楚地指出了它测
试的是get_formatted_name() 的哪个行为,这样,如果该测试未通过,我们就会马上知道受影响的是哪种类型的姓名。在TestCase 类中使用很长的方法名是可以的;这
些方法的名称必须是描述性的,这才能让你明白测试未通过时的输出;这些方法由Python自动调用,你根本不用编写调用它们的代码。
为测试函数get_formatted_name() ,我们使用名、姓和中间名调用它(见❶),再使用assertEqual() 检查返回的姓名是否与预期的姓名(名、中间名和姓)一致。我
们再次运行test_name_function.py时,两个测试都通过了:
···python
Testing started at 14:51 …
E:\python\learn_python1\venv\Scripts\python.exe “D:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm_jb_unittest_runner.py” --target test_name_function.NamesTestCase
Launching unittests with arguments python -m unittest test_name_function.NamesTestCase in E:\python\learn_python1

Ran 2 tests in 0.001s

OK

Process finished with exit code 0

···

二.测试类

很多程序中都会用到类,因此能够证明你的类能够正确地工作会大有裨益。如果针对类的测试通过
了,你就能确信对类所做的改进没有意外地破坏其原有的行为。

2.1 各种断言方法

Python在unittest.TestCase 类中提供了很多断言方法。前面说过,断言方法检查你认为应该满足的条件是否确实满足。如果该条件确实满足,你对程序行为的假设就得到了确认,你就可以确信其中没有错误。如果你认为应该满足的条件实际上并不满足,Python将引发异常。

下面描述了6个常用的断言方法。使用这些方法可核实返回的值等于或不等于预期的值、返回的值为True 或False 、返回的值在列表中或不在列表中。你只能在继承unittest.TestCase 的类中使用这些方法,下面来看看如何在测试类时使用其中的一个。

方法用途
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 中

2.2 一个要测试的类

类的测试与函数的测试相似——你所做的大部分工作都是测试类中方法的行为,但存在一些不同之处,下面来编写一个类进行测试。来看一个帮助管理匿名调查的类。

survey.py

class AnonymousSurvey():
    """收集匿名调查问卷答案"""

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

    def show_question(self):
        """显示调查问卷"""
        print(self.question)

    def store_reponse(self, new_response):
        """存储单份调查问卷"""
        self.responses.append(new_response)

    def show_results(self):
        """显示收集到的所有答卷"""
        print("Survey results:")
        for response in self.responses:
            print('- ' + response)

language_survey.py

from survey import AnonymousSurvey

# 定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

# 显示问题并存储答案
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_reponse(response)

# 显示调查结果
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/languate_suvey.py
What language did you first learn to speak?
Enter 'q' at any time to quit.

Language: Chinese
Language: English
Language: q

Thank you to everyone who participated in the survey!
Survey results:
- Chinese
- English

Process finished with exit code 0

2.3 测试AnonymousSurvey 类

下面来编写一个测试,对AnonymousSurvey 类的行为的一个方面进行验证:如果用户面对调查问题时只提供了一个答案,这个答案也能被妥善地存储。为此,我们将在这个答案被存储后,使用方法assertIn() 来核实它包含在答案列表中:

test_survey.py

import unittest
from survey import AnonymousSurvey

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

    def test_store_single_reponse(self):
        """测试三个答案会被妥善地存储"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['English', 'Spanish', 'Mandarin']
        for response in responses:
            my_survey.store_reponse(response)

        for response in responses:
            self.assertIn(response, my_survey.responses)


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

测试记录:

Testing started at 15:39 ...
E:\python\learn_python1\venv\Scripts\python.exe "D:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\_jb_unittest_runner.py" --target test_survey.TestAnonymousSurvey.test_store_single_reponse


Ran 1 test in 0.001s

Launching unittests with arguments python -m unittest test_survey.TestAnonymousSurvey.test_store_single_reponse in E:\python\learn_python1
OK

Process finished with exit code 0

2.4 方法setUp()

在前面的test_survey.py中,我们在每个测试方法中都创建了一个AnonymousSurvey 实例,并在每个方法中都创建了答案。unittest.TestCase 类包含方法setUp() ,让我们只需创建这些对象一次,并在每个测试方法中使用它们。如果你在TestCase 类中包含了方法setUp() ,Python将先运行它,再运行各个以test_打头的方法。这样,在你编写的每个测试方法中都可使用在方法setUp() 中创建的对象了。

下面使用setUp() 来创建一个调查对象和一组答案,供方法test_store_single_response() 和test_store_three_responses() 使用:

import unittest
from survey import AnonymousSurvey

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

    def setUp(self):
        """创建一个调查对象和一组答案,供使用的测试方法使用"""
        question = "What language did you first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['English', 'Spanish', 'Mandarin']


    def test_store_single_reponse(self):
        """测试单个答案会被妥善地存储"""
        self.my_survey.store_reponse(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)

    def test_store_three_reponse(self):
        """测试三个答案会被妥善地存储"""
        for response in self.responses:
            self.my_survey.store_reponse(response)

        for response in self.responses:
            self.assertIn(response, self.my_survey.responses)


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

测试记录:

Testing started at 15:50 ...
E:\python\learn_python1\venv\Scripts\python.exe "D:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\_jb_unittest_runner.py" --target test_survey.TestAnonymousSurvey.test_store_single_reponse


Ran 1 test in 0.001s

OK
Launching unittests with arguments python -m unittest test_survey.TestAnonymousSurvey.test_store_single_reponse in E:\python\learn_python1

Process finished with exit code 0

参考:

1.Python编程:从入门到实践

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值