11-1 城市和国家
city_function.py:
# in city_function.py
def city_country(city,country):
name=city+', '+country
return name.title()
test_cities.py:
import unittest
from city_function import city_country
class CityTestCase(unittest.TestCase):
def test_city_country(self):
formatted_name=city_country('santiago','chile')
self.assertEqual(formatted_name,'Santiago, Chile')
unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
11-2 人口数量
Test1:
city_function.py:
# in city_function.py
def city_country(city,country,population):
name=city+', '+country+' - population'+str(population)
return name.title()
Output:
E
======================================================================
ERROR: test_city_country (__main__.CityTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_cities.py", line 7, in test_city_country
formatted_name=city_country('santiago','chile')
TypeError: city_country() takes exactly 3 arguments (2 given)
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Test2:
city_function.py:
# in city_function.py
def city_country(city,country,population=''):
name=city+', '+country
if(population!=''):
return name.title()+' - population'+str(population)
else:
return name.title()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Test3:
test_cities.py:
import unittest
from city_function import city_country
class CityTestCase(unittest.TestCase):
def test_city_country_2(self):
formatted_name=city_country('santiago','chile')
self.assertEqual(formatted_name,'Santiago, Chile')
def test_city_country_3(self):
formatted_name=city_country('santiago','chile',5000000)
self.assertEqual(formatted_name,'Santiago, Chile - population 5000000')
unittest.main()
Output:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
11-3 雇员
Employee.py:
class Employee:
def __init__(self,last,first,money):
self.first_name=first
self.last_name=last
self.pay=money
def give_raise(self,money=5000):
self.pay=self.pay+money
test_Employee.py:
import unittest
from Employee import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.people=Employee('harden','james',1000)
def test_give_default_raise(self):
self.people.give_raise()
self.assertEqual(self.people.pay,6000)
def test_give_custom_raise(self):
self.people.give_raise(4000)
self.assertEqual(self.people.pay,5000)
unittest.main()
Output:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK