您的位置:首页 > 编程语言 > Python开发

Python 第十一章部分习题

2018-04-10 01:17 302 查看
11-1 城市和国家:







代码:
homework.pydef city_fun(city, country):
return city.title()+", "+country
test_cities.py
import unittest
from homework import city_fun

class CityTestCase(unittest.TestCase):
def test_city_country(self):
formatted_string = city_fun("Santiago", "Chile")
self.assertEqual(formatted_string, "Santiago, Chile")

unittest.main()
输出:



11-2 人口数量
代码:
homework.py:def city_fun(city, country, population):
return city.title()+", "+country + " - population " + str(population)test_cities.py:import unittest from homework import city_fun class CityTestCase(unittest.TestCase): def test_city_country(self): formatted_string = city_fun("Santiago", "Chile") self.assertEqual(formatted_string, "Santiago, Chile") unittest.main()
输出:



修改city_fun函数如下:
homework.pydef city_fun(city, country, population = None):
if population == None:
return city.title()+", "+country
return city.title()+", "+country + " - population " + str(population)运行test_cities:



修改CityTestCase,增加一个测试函数如下:import unittest
from homework import city_fun

class CityTestCase(unittest.TestCase):
def test_city_country(self):
formatted_string = city_fun("Santiago", "Chile")
self.assertEqual(formatted_string, "Santiago, Chile")

def test_city_country_population(self):
formatted_string = city_fun("Santiago", "Chile", population = 5000000)
self.assertEqual(formatted_string, "Santiago, Chile - population 5000000")

unittest.main()
运行test_cities.py



11-3 雇员
homework.py:class Employee():
def __init__(self, first_name, last_name, annual_salary):
self.first_name = first_name
self.last_name = last_name
self.annual_salary = annual_salary

def give_raise(self, addition = 5000):
self.annual_salary += additionEmployee_test.py:import unittest
from homework import Employee

class EmployeeTestCase(unittest.TestCase):

def setUp(self):
self.employee = Employee("Mark", "White", 2000)

def test_give_default_raise(self):
old = self.employee.annual_salary
self.employee.give_raise()
new = self.employee.annual_salary
self.assertEqual(new-old, 5000)

def test_give_custom_raise(self):
old = self.employee.annual_salary
self.employee.give_raise(10000)
new = self.employee.annual_salary
self.assertEqual(new-old, 10000)

unittest.main()输出:



明明只有两个test,为什么会输出4个test呢……重开一次spyder再运行同样的代码,发现就显示ran 2 tests

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: