Python测试代码

1、使用test_cities.py来测试city_function.py中的city_country函数

city_function.py文件内容

def city_country(city,country,population = 0):
	"""返回一个形如'Santiago,Chile'的字符串"""
	output_string = f"{city.title()}, {country.title()}"
	if population:
		output_string += f" - population {population}"
	return output_string

test_cities.py文件内容

import unittest

from city_functions import city_country

class CitiesTestCase(unittest.TestCase):
	"""测试city_functions.py"""

	def test_city_country(self):
		"""传入简单的城市和国家"""
		santiago_chile = city_country('santiago','chile')
		self.assertEqual(santiago_chile,'Santiago, Chile')

	def test_city_country_population(self):
		santiago_chile = city_country('santiago','chile',population = 5_000_000)
		self.assertEqual(santiago_chile,'Santiago, Chile - population 5000000')

if __name__ == '__main__':
	unittest.main()

测试结果:

..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
[Finished in 161ms]

2、使用test_employee.py测试employee.py中的类的功能

employee.py:

class Employee():
	"""一个表示雇员的类"""

	def __init__(self,f_name,l_name,salary):
		"""初始化雇员"""
		self.first = f_name.title()
		self.last = l_name.title()
		self.salary = salary

	def give_raise(self,amount = 5000):
		"""给雇员加薪"""
		self.salary += amount

test_employee.py:

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):
	"""测试模块employee"""
	def setUp(self):
		"""创建一个Employee实例,以便在测试中使用"""
		self.eric = Employee('eric','matthes',65_000)

	def test_give_default_raise(self):
		"""测试使用默认的年薪增加量是否可行。"""
		self.eric.give_raise()
		self.assertEqual(self.eric.salary,70000)

	def test_give_custom_raise(self):
		"""测试自定义年薪增加量是否可行。"""
		self.eric.give_raise(10000)
		self.assertEqual(self.eric.salary,75000)
if __name__ == '__main__':
	unittest.main()

测试结果全部通过:

..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值