11-1 城市和国家
city_functions.py
def get_city_country (city,country):
return city+","+country
test_cities.py
from city_functions import get_city_country
import unittest
class NameTestCase (unittest.TestCase):
def test_city_country(self):
string = get_city_country('santiago','chile')
self.assertEqual(string,'santiago,chile')
unittest.main()
输出结果是:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
11-2 人口数量
city_functions.py改为
def get_city_country (city,country,population):
return city+","+country+" - "+str(population)
输出结果是:
E
======================================================================
ERROR: test_city_country (__main__.NameTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "G:/Python/test/test1.py", line 6, in test_city_country
string = get_city_country('santiago','chile')
TypeError: get_city_country() missing 1 required positional argument: 'population'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
city_functions.py改为
def get_city_country (city,country,population=''):
if population:
return city+","+country+" - "+str(population)
else:
return city+","+country
输出结果是:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
test_cities.py改为:
from city_functions import get_city_country
import unittest
class NameTestCase (unittest.TestCase):
def test_city_country(self):
string = get_city_country('santiago','chile')
self.assertEqual(string,'santiago,chile')
def test_city_country_population(self):
string = get_city_country('santiago','chile','population = 5000000')
self.assertEqual(string,'santiago,chile - population = 5000000')
unittest.main()
输出结果是:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
11-3 雇员
Employee.py
class Employee():
def __init__(self,first,last,annualpay):
self.firstname = first
self.lastname = last
self.annualpay = annualpay
def give_raise(self,give = 5000):
self.annualpay += give
test.py
from Employee import Employee
import unittest
class TestEmployee (unittest.TestCase):
def setUp(self):
self.employee = Employee('Hua','Li',0)
self.gives = [5000,2000]
def test_single_employee(self):
self.employee.give_raise()
self.assertIn(str(self.gives[0]),str(self.employee.annualpay))
def test_two_employee(self):
sum = 0
for give in self.gives:
sum += give
self.employee.give_raise(give)
self.assertIn(str(sum),str(self.employee.annualpay))
unittest.main()
输出结果是:
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK