11.1
# city_functions.py def city_function(City, Country): return City + ", " + Country
# test_cities.py import unittest from city_functions import city_function class CityTestCase(unittest.TestCase): """Tests for 'city_function.py'.""" def test_city_country(self): formatted_str = city_function('Santiago', 'Chile') self.assertEqual(formatted_str, 'Santiago, Chile') unittest.main()
//运行结果 . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
11.2
# city_functions.py def city_function(City, Country, population = None): if population: return City + ", " + Country + " - population: " + str(population) else: return City + ", " + Country
# test_cities.py import unittest from city_functions import city_function class CityTestCase(unittest.TestCase): """Tests for 'city_function.py'.""" def test_city_country(self): formatted_str = city_function('Santiago', 'Chile') self.assertEqual(formatted_str, 'Santiago, Chile') def test_city_country_population(self): formatted_str = city_function('Santiago', 'Chile', 5000000) self.assertEqual(formatted_str, 'Santiago, Chile - population: 5000000') unittest.main()
//运行结果 .. ---------------------------------------------------------------------- Ran 2 tests in 0.001s OK
11.3
# Employer.py import unittest class Employee(): """docstring for 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, my_raise = 5000): self.salary += my_raise class TestEmployee(unittest.TestCase): def setUp(self): self.E1 = Employee('Alien', 'Turing', 5000) def test_give_default_raise(self): self.E1.give_raise() self.assertEqual(self.E1.salary, 10000) def test_give_custom_raise(self): self.E1.give_raise(10000) self.assertEqual(self.E1.salary, 15000) unittest.main()
//运行结果 .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK