python从入门到实践 第十一章习题(高级编程技术 week6-1)
python标准库中的模块unittest提供的代码测试工具。
11.1 测试函数
要为函数编写测试用例,可先导入模块unittest以及要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。在测试类中,test_开头的函数都会自动运行。
11-1/2
编写了一个简单的测试类,并且探索了解释错误和断言错误的两种不同的测试错误。
# test.py
import unittest
from main import make_city
class CityTestCase(unittest.TestCase):
def test_city_country(self):
format_city = make_city('Beijing', 'China')
self.assertEqual(format_city, 'Beijing,China')
def test_city_country_population(self):
format_city = make_city('Beijing', 'China', '1300000000')
self.assertEqual(format_city, 'Beijing,China - population 1300000000')
unittest.main()
# main.py
def make_city(city_name, country_name, population = ''):
if population:
format_city = city_name+','+country_name+' - population '+str(population)
else:
format_city = city_name+','+country_name
return format_city
11.2 测试类
unstteset.TestCase类中提供了很多断言方法。常见的有以下这几种
对现有的类进行修改的时候,可能不小心修改了类原有的行为,为了避免(或者说侦察到)这种情况的发生,我们可以编写针对这个类的测试。
同时,为了解决在对一个类测试的时候需要在每个测试函数中实例化的问题,可以使用setUp()方法创建对象。这样,就只需要创建一次对象,就可以在每个测试方法中使用它们。
原理:python将先运行setUp()再运行各个以test_打头的方法。这样,编写的每个测试方法中都可使用方法setUp()中创建的对象了。
class Employee():
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def give_raise(self, increment=5000):
self.salary += increment
if __name__ == '__main__':
import unittest
from test import Employee
class EmployeeTestCase(unittest.TestCase):
def setUp(self):
self.my_employee = Employee('Lily', 'Wang', 500)
self.increment = 10001
def test_give_default_raise(self):
self.my_employee.give_raise()
self.assertEqual(self.my_employee.salary, 5500)
def test_give_custom_raise(self):
self.my_employee.give_raise(self.increment)
self.assertEqual(self.my_employee.salary, 10501)
unittest.main()