《Python编程-从入门到实践》课后习题(11)

11-1

city_functions.py

def foo(city, country):
    return city.title()+', '+country.title()

test_cities.py

import unittest
from city_functions import foo

class test(unittest.TestCase):
    def test_city_country(self):
        cityname = foo('santiago', 'chile')
        self.assertEqual(cityname, 'Santiago, Chile')

unittest.main()

11-2

修改前

city_functions.py

def foo(city, country, population=0):
    return city.title()+', '+country.title()+' - population '+str(population)

test_cities.py

import unittest
from city_functions import foo

class test(unittest.TestCase):
    def test_city_country(self):
        cityname = foo('santiago', 'chile')
        self.assertEqual(cityname, 'Santiago, Chile')

unittest.main()

修改后

city_functions.py

def foo(city, country, population=0):
    return city.title()+', '+country.title()+' - population '+str(population)

test_cities.py

import unittest
from city_functions import foo

class test(unittest.TestCase):
    def test_city_country(self):
        cityname = foo('santiago', 'chile')
        self.assertEqual(cityname, 'Santiago, Chile')
    def test_city_country_population(self):
        cityname = foo('santiago', 'chile', population=5000000)
        self.assertEqual(cityname, 'Santiago, Chile - population 5000000')

unittest.main()

11-3

import unittest

class 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, dollar = 5000):
        self.salary += dollar

class TestEmployee(unittest.TestCase):
    def setUp(self):
        self.employee = Employee(0, 0, 0)
        default_salary = 5000
        custom_salary = 10000
    def test_give_default_raise(self):
        self.employee.give_raise()
        self.assertEqual(5000, self.employee.salary)
    def test_give_default_raise(self):
        self.employee.give_raise(dollar=1000)
        self.assertEqual(1000, self.employee.salary)

unittest.main()

猜你喜欢

转载自blog.csdn.net/wanghj47/article/details/79954716
今日推荐