11-1 城市和国家
1. city _functions.py:
def get_city_country_name(city_name,country_name):
"""返回City, Country格式"""
full_name = city_name.title() + ', ' + country_name.title()
return full_name
2. test_cities.py
import unittest
from city_functions import get_city_country_name
class NameTestCase(unittest.TestCase):
"""测试city_functions.py"""
def test_city_country(self):
"""能够正确处理像Beijing, China这样的?"""
formatted_name = get_city_country_name('beijing','china')
self.assertEqual(formatted_name,'Beijing, China')
#equal: unittest.main
if __name__ == '__main__':
unittest
11-2 人口数量
2. population设置为可选的
city_functions.py
def get_city_country_name(city_name,country_name,population=''):
"""返回City, Country格式"""
if population:
full_name = city_name.title() + ', ' + country_name.title() + ' - population ' + str(population)
else:
full_name = city_name.title() + ', ' + country_name.title()
return full_name
test_cities.py
import unittest
from city_functions import get_city_country_name
class NameTestCase(unittest.TestCase):
"""测试city_functions.py"""
def test_city_country(self):
"""能够正确处理像Beijing, China这样的?"""
formatted_name = get_city_country_name('beijing','china')
self.assertEqual(formatted_name,'Beijing, China')
#equal: unittest.main
if __name__ == '__main__':
unittest
- 再编写一个名为 test_city_country_population()的测试,
1.city_functions.py
def get_city_country_name(city_name,country_name,population=''):
"""返回City, Country格式"""
if population:
full_name = city_name.title() + ', ' + country_name.title() + ' - population ' + str(population)
else:
full_name = city_name.title() + ', ' + country_name.title()
return full_name
2.test_cities.py
import unittest
from city_functions import get_city_country_name
class NameTestCase(unittest.TestCase):
"""测试city_functions.py"""
def test_city_country(self):
"""能够正确处理像Beijing, China这样的?"""
formatted_name = get_city_country_name('beijing','china')
self.assertEqual(formatted_name,'Beijing, China')
def test_city_country_population(self):
"""测试加上population"""
formatted_name = get_city_country_name('beijing','china',50000)
self.assertEqual(formatted_name,'Beijing, China - population 50000')
#equal: unittest.main
if __name__ == '__main__':
unittest
11-3 雇员
employee.py
# -*- coding: UTF-8 -*-
class Employee():
def __init__(self,f_name,l_name,salary_year):
self.f_name = f_name
self.l_name = l_name
self.salary_year = salary_year
def give_raise(self,amount=5000):
self.salary_year += amount
test_employee.py
# -*- coding: UTF-8 -*-
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
"""创建一个雇员实例"""
self.xqj = Employee('x','j',5000)
def test_give_default_raise(self):
"""测试默认"""
self.xqj.give_raise()
self.assertEqual(self.xqj.salary_year,10000)
def test_give_custom_raise(self):
"""测试随意生成"""
self.xqj.give_raise(1000)
self.assertEqual(self.xqj.salary_year,6000)
if __name__ == '__main__':
unittest