Python 第十一章部分习题

11-1 城市和国家:






代码:

homework.py

def city_fun(city, country):
    return city.title()+", "+country
test_cities.py
import unittest
from homework import city_fun

class CityTestCase(unittest.TestCase):
    def test_city_country(self):
        formatted_string = city_fun("Santiago", "Chile")
        self.assertEqual(formatted_string, "Santiago, Chile")
        
unittest.main()

输出:



11-2 人口数量

代码:

homework.py:

def city_fun(city, country, population):
    return city.title()+", "+country + " - population " + str(population)

test_cities.py:

import unittest
from homework import city_fun

class CityTestCase(unittest.TestCase):
    def test_city_country(self):
        formatted_string = city_fun("Santiago", "Chile")
        self.assertEqual(formatted_string, "Santiago, Chile")
        
unittest.main()

输出:



修改city_fun函数如下:

homework.py

def city_fun(city, country, population = None):
    if population == None:
        return city.title()+", "+country
    return city.title()+", "+country + " - population " + str(population)

运行test_cities:



修改CityTestCase,增加一个测试函数如下:

import unittest
from homework import city_fun

class CityTestCase(unittest.TestCase):
    def test_city_country(self):
        formatted_string = city_fun("Santiago", "Chile")
        self.assertEqual(formatted_string, "Santiago, Chile")
    
    def test_city_country_population(self):
        formatted_string = city_fun("Santiago", "Chile", population = 5000000)
        self.assertEqual(formatted_string, "Santiago, Chile - population 5000000")
        
unittest.main()

运行test_cities.py




11-3 雇员

homework.py:

class Employee():
    def __init__(self, first_name, last_name, annual_salary):
        self.first_name = first_name
        self.last_name = last_name
        self.annual_salary = annual_salary
    
    def give_raise(self, addition = 5000):
        self.annual_salary += addition

Employee_test.py:

import unittest
from homework import Employee

class EmployeeTestCase(unittest.TestCase):
    
    def setUp(self):
        self.employee = Employee("Mark", "White", 2000)


    def test_give_default_raise(self):
        old = self.employee.annual_salary
        self.employee.give_raise()
        new = self.employee.annual_salary 
        self.assertEqual(new-old, 5000)
    
    
    def test_give_custom_raise(self):
        old = self.employee.annual_salary
        self.employee.give_raise(10000)
        new = self.employee.annual_salary
        self.assertEqual(new-old, 10000)
    
    
unittest.main()

输出:




明明只有两个test,为什么会输出4个test呢……重开一次spyder再运行同样的代码,发现就显示ran 2 tests












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值