测试代码

编写函数或类时,可以为其编写测试。通过测试,可确定代码面对各种输入都能够按要求的那样工作。接下来将学习如何使用Python模块unittest中的工具来测试代码。将学习编写测试用例,核实一系列输入都将得到预期的输出。将看到测试通过是什么样子,测试未通过又是什么样子,并且可以知道测试未通过如何有助于改进代码。还将学习如何测试函数和类,并将知道该为项目编写多少个测试。

1.测试函数

下面先来了解一下和学习怎么测试,需要一个简单的函数,它接受名和姓并返回整洁的姓名:
name_function.py

def get_formatted_name(first,last):
	"""生成整洁的姓名"""
	full_name = first + ' ' + last
	return full_name.title()

函数get_formatted_name()将名和姓合并成姓名,在名和姓之间加上一个空格,并将它们的手写字母都大写,再返回结果。为了合适函数是否可以按预期的逻辑执行,我们来编写一个使用这个函数的程序。程序names.py让用户输入名和姓,并显示整洁的全名:
names.py

from name_function import get_formatted_name
print("Enter 'q' at any time to quit.")
while True:
	first = input("\n Please 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 + '.')

程序从name_function.py中导入get_formatted_name().用户可输入一系列的名和姓,并看到格式整洁的全名

Enter 'q' at any time to quit.

Please give me a first name: aaron
Please give me a last name: yun
        Neatly formatted name: Aaron Yun.

Please give me a first name: q

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):
		"""能够正确地处理像Jains_Joplin这样的姓名吗?"""
		formatted_name = get_formatted_name('janis','joplin')
		self.assertEqual(formatted_name,'Janis Joplin')

unittest.main()

看看执行结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

首先,我们导入了模块unittest和要测试的函数get_formatted_name(),然后我们创建了一个名为Names TestCase的类,用于包含一系列针对get_formatted_name()的单元测试。该类继承unittest.TestCase类。
NamesTestCase只包含一个方法,用于测试get_formatted_name()的一个方面。我们将这个方法命名为test_first_last_name(),因为我们要核实的是只有名和姓的姓名能否被正确地格式化。我们在运行test_name_function.py时,所有以test_打头的方法都将自动运行。在这个方法中,我们调用了要测试的函数,并存储了要测试的返回值。
然后,我们使用了unittest类最有用的功能之一:一个断言方法断言方法用来核实得到的结果是否与期望的结果一致。
为了验证是否能够达到我们的预期,我们调用了unittest的方法assertEqual(),并向它传递formatted_name和‘Janis Joplin’。让它们相互比较,看看结果是否能够达到我们的预期。
代码行unittest.main()让Python运行这个文件中的测试。
执行结果中第一行的句点表明有一个测试通过了。接下来的一行指出Python运行了一个测试,消耗的时间不到0.001秒。最后的OK表明该测试用例中的所有单元测试都通过了。

1.3不能通过的测试

上面说了测试通过了表现,那测试未通过呢?接下来,修改一下**get_formatted_name()使其能够处理中间名,但这样做时,故意让这个函数无法正确处理像Janis Joplin这样只有名和姓的姓名。
下面时函数
get_formatted_name()**的新版本,它要求通过一个实参指定中间名:

def get_formatted_name(first,middls,last):
    """生成整洁的姓名"""
    full_name = first + ' ' + middle +' ' + last
    return full_name.title()

看看执行结果:

E
======================================================================
ERROR: test_first_last_name (__main__.NamesTestCase)
能够正确地处理像Jains_Joplin这样的姓名吗?
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\Users\Administrator\Desktop\python\0511\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'

----------------------------------------------------------------------
Ran 1 test in 0.005s

FAILED (errors=1)

执行结果中,第一行输出了一个E,指出测试用例中有一个单元测试导致了错误。然后,就是**NamesTestCase中的test_first_last_name()导致了错误,在有多个单元测试时,知道那个测试未通过至关重要。然后呢,我们看到了具体的错误信息,指出函数调用get_formatted_name(‘janis’,‘joplin’)**有问题,因为它缺少一个必不可少的位置实参(last)。
接下来,看到显示运行了一个单元测试,然后告诉我们整个测试用例未通过,运行测试用例时发生了一个错误。

1.4测试未通过时怎么办

那既然发现了测试未通过,那怎么办呢?我们需要检查我们编写代码块,我们把**get_formatted_name()**的中间名改为可选的,然后再测试看看结果。

def get_formatted_name(first,last,middle=''):
    """生成整洁的姓名"""
    if middle:
        full_name = first + ' ' + middle +' ' + last
    else:
        full_name = first + ' ' + last
    return full_name.title()

看看执行结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

执行通过了,我们再测试用例中可以再添加机几项针对编写函数的测试用例,来验证是否还有其他需要改进的。

1.5添加新测试

我们就在添加一个新的测试,我们再类中添加一个方法:

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
	"""测试name_function.py"""
	
	def test_first_last_name(self):
		"""能够正确地处理像Jains_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'
		)
		self.assertEqual(formatted_name,'Wolfgang Amadeus Mozart')

unittest.main()

看看执行结果:

..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK

我们将新添加的方法命名为test_first_last_middle_name()。方法名必须以test_打头,这样才会再我们运行test_name_function.py时自动运行,方法名字指出了,新添加的方法测试的是函数的那个行为。
练习:
11-1: City, Country
Write a function that accepts two parameters: a city name and a country name. The function should return a single string of the form City, Country, such as Santiago, Chile. Store the function in a module called city_functions.py.
Create a file called test_cities.py that tests the function you just wrote (remember that you need to import unittest and the function you want to test). Write a method called test_city_country() to verify that calling your function with values such as santiago and chile results in the correct string. Run test_cities.py, and make sure test_city_country() passes.
city_functions.py:

"""A collection of functions for working with cities."""

def city_country(city, country):
    """Return a string like 'Santiago, Chile'."""
    return(city.title() + ", " + country.title())

Note: This is the function we wrote in Exercise 8-6.
test_cities.py:

import unittest

from city_functions import city_country

class CitiesTestCase(unittest.TestCase):
    """Tests for 'city_functions.py'."""

def test_city_country(self):
        """Does a simple city and country pair work?"""
        santiago_chile = city_country('santiago', 'chile')
        self.assertEqual(santiago_chile, 'Santiago, Chile')

unittest.main()

执行结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

11-2: Population
Modify your function so it requires a third parameter, population. It should now return a single string of the form City, Country - population xxx, such as Santiago, Chile - population 5000000. Runtest_cities.py again. Make sure test_city_country() fails this time.
Modify the function so the population parameter is optional. Run test_cities.py again, and make sure test_city_country() passes again.
Write a second test called test_city_country_population() that verifies you can call your function with the values ‘santiago’, ‘chile’, and ‘population=5000000’. Run test_cities.py again, and make sure this new test passes.
Modified city_functions.py, with required population parameter:

"""A collection of functions for working with cities."""

def city_country(city, country, population):
    """Return a string like 'Santiago, Chile - population 5000000'."""
    output_string = city.title() + ", " + country.title()
    output_string += ' - population ' + str(population)
    return output_string

Output from running test_cities.py:

E
======================================================================
ERROR: test_city_country (__main__.CitiesTestCase)
Does a simple city and country pair work?
----------------------------------------------------------------------
Traceback (most recent call last):
  File "pcc\solutions\test_cities.py", line 10, in test_city_country
    santiago_chile = city_country('santiago', 'chile')
TypeError: city_country() missing 1 required positional argument: 'population'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

Modified city_functions.py, with optional population parameter:

"""A collection of functions for working with cities."""

def city_country(city, country, population=0):
    """Return a string representing a city-country pair."""
    output_string = city.title() + ", " + country.title()
    if population:
        output_string += ' - population ' + str(population)
    return output_string
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

Modified test_cities.py:

import unittest

from city_functions import city_country

class CitiesTestCase(unittest.TestCase):
    """Tests for 'city_functions.py'."""

    def test_city_country(self):
        """Does a simple city and country pair work?"""
        santiago_chile = city_country('santiago', 'chile')
        self.assertEqual(santiago_chile, 'Santiago, Chile')

    def test_city_country_population(self):
        """Can I include a population argument?"""
        santiago_chile = city_country('santiago', 'chile', population=5000000)
        self.assertEqual(santiago_chile, 'Santiago, Chile - population 5000000')

unittest.main()

Output:

..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

2.测试类

2.1各种断言方法

断言(也就是assert,我在做项目的时候,领导就说当不确定会发生什么的时候,就是用assert,然后如果程序确定不会跑到逻辑就大胆的加assert进行检查,在这里又看到了assert)。
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_response(self,new_response):
		"""存储单份调查问卷"""
		self.responses.append(new_response)
	def show_results(self):
		"""显示收集到的所有答卷"""
		print("Survey results:")
		for response in self.responses:
			print('- ' + response)

该类首先存储一个指定的调查问题,并创建一个空的列表,用于存储答案。这个类包含打印调查问题的方法、在答案列表中添加新答案的方法,以及将存储在列表中的答案都打印出来的方法。要创建该类的实例,只需提供一个问题即可,有了表示调查的实例后,就可使用show_question()来显示其中的问题,可使用store_response()来存储答案,并使用show_results()来显示调查结果。
下面来编写一个使用它的程序:
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_response(response)
#显示调查结果
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()

该程序定义了一个问题(“what language did you first learn to speak?”),并使用这个问题创建一个AnonymousSurvey对象。接下来,这个程序调用show_question()来显示问题,并提示用户输入答案。收到每个答案的同时将其存储起来。用户输入所有答案(输入q要求退出)后,调用show_results()来打印调查结果:

What language did you first learn to speak?
enter 'q' at any time to quit.

Language: english
Language: spanish
Language: english
Language: mandarin
Language: q

Thank you to everyone who participated in the survey!
Survey results:
- english
- spanish
- english
- mandarin

2.3测试AnonymousSurvey类

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

import unittest
from survey import AnonymousSurvey

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

	def test_store_single_response(self):
		"""测试单个答案会被妥善地存储"""
		question = "What language did you first learn to speak?"
		my_survey = AnonymousSurvey(question)
		my_survey.store_response('English')
		
		self.assertIn('English',my_survey.responses)

unittest.main()

我们首先导入了模块unittest以及要测试的类AnonymousSurvey. 我们将测试用例命名为TestAnonymousSurvey,它也继承了unittest.TestCase,第一个测试方法验证调查问题的单个答案被存储后,会包含在调查结果列表中。对于这个方法,一个不错的描述性名称是test_store_single_response().如果这个测试未通过,我们就能通过输出中的方法名得知,在存储单个调查答案方面存在问题。
要测试类的行为,需要创建其实例,我们使用问题“What language did you first learn to speak?”创建一个名为my_survey的实例,然后使用方法store_response()存储了单个答案English。接下来,我们检查English是否包含在列表my_survey.response中,以核实这个答案是否被妥善地存储了。

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

测试通过了,下面我们来核实用户提供三个答案时,它们也将被妥善地存储,为此,我们在TestAnonymousSurvey中再添加一个方法:

import unittest
from survey import AnonymousSurvey

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

	def test_store_single_response(self):
		"""测试单个答案会被妥善地存储"""
		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_responses(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_response(response)

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


unittest.main()
..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK

在这些测试中,有些重复的地方。下面使用unittest的另一项功能来提高它们的效率。

2.4方法setUp()

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):
	"""针对AnonymousSurvey类的测试"""

	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_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()
..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK

方法setUp()做两件事:创建一个调查对象;创建以恶搞答案列表。存储这两样东西的变量名包含前缀self(即存储在属性中),因此可在这个类的任何地方使用,这让两个测试方法都很简单,因为它们不用创建调查对象和答案。方法test_store_single_response()核实self.responses中的第一个答案------self.responses[0]--------被妥善地存储,而方法test_store_three_responses()核实self.responses中的全部三个答案都被妥善地存储。
测试自己编写的类时,方法setUp()让测试方法编写起来更容易:可在setUp()方法中创建一系列实例并设置它们的属性,再在测试方法中直接使用这些实例。相比于在每个测试方法中都创建实例并设置其属性,这要容易的多。
**注意:运行测试用例时,每完成一个单元测试,Python都打印一个字符:测试通过时打印一个句点;测试引发错误时打印一个E;测试导致断言失败时打印一个F。这就是你运行测试用例时,在输出的第一行中看到的句点和字符数量各不相同的原因。如果测试用例包含很多单元测试,需要运行很长时间,就可通过观察这些结果来获悉有多少个测试通过了。
**
11-3: Employee
Write a class called Employee. The init() method should take in a first name, a last name, and an annual salary, and store each of these as attributes. Write a method called give_raise() that adds $5000 to the annual salary by default but also accepts a different raise amount.
Write a test case for Employee. Write two test methods, test_give_default_raise() andtest_give_custom_raise(). Use the setUp() method so you don’t have to create a new employee instance in each test method. Run your test case, and make sure both tests pass.
employee.py:

class Employee():
    """A class to represent an employee."""

    def __init__(self, f_name, l_name, salary):
        """Initialize the employee."""
        self.first = f_name.title()
        self.last = l_name.title()
        self.salary = salary

    def give_raise(self, amount=5000):
        """Give the employee a raise."""
        self.salary += amount

test_employee.py:

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):
    """Tests for the module employee."""

    def setUp(self):
        """Make an employee to use in tests."""
        self.eric = Employee('eric', 'matthes', 65000)

    def test_give_default_raise(self):
        """Test that a default raise works correctly."""
        self.eric.give_raise()
        self.assertEqual(self.eric.salary, 70000)

    def test_give_custom_raise(self):
  """Test that a custom raise works correctly."""
        self.eric.give_raise(10000)
        self.assertEqual(self.eric.salary, 75000)

unittest.main()
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK