1. 程式人生 > >python學習——測試函式

python學習——測試函式

題目參照《python程式設計——從入門到實踐》第十一章習題

11-1、11-2

city_functions.py

def city_name(city,country,population=''):
	name=city+','+country
	if population:
		name+='-population '+str(population)
	return name.title()

test_city.py

import unittest
from city_functions import city_name

class CityTest(unittest.TestCase):
	def test_city_country(self):
		name=city_name('santiago','chile')
		self.assertEqual(name,'Santiago,Chile')
	def test_city_country_population(self):
		name=city_name('santiago','chile',population=5000000)
		self.assertEqual(name,'Santiago,Chile-Population 5000000')
	
unittest.main()

11-3

employee.py

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,increament=500):
		self.salary+=increament
		

test_employee.py

import unittest
from employee import Employee
class EmployeeTest(unittest.TestCase):
	def setUp(self):
		self.emp=Employee('yang','li',500)
	def test_give_default_raise(self):
		newSalary=self.emp.salary+500
		self.emp.give_raise()
		self.assertEqual(self.emp.salary,newSalary)
	def test_give_custom_salary(self):
		newSalary=self.emp.salary+1000
		self.emp.give_raise(1000)
		self.assertEqual(self.emp.salary,newSalary)
unittest.main()