python测试类

待测试的类survey.py

python 复制代码
class AnonymousSurvey():
	'''收集匿名调查问卷的答案'''
	
	def __init__(self,question):
		'''储存一个问题并为储存答案做准备'''
		self.question=question
		self.responses=[]
		
	def show_question(self):
		'''显示调查问卷'''
		print(self.question)
		
	def store_response(self,new_response):
		'''储存单份调查问卷'''
		self.responses.append(new_response)
		
	def show_results(self):
		'''显示收集到的答案'''
		print("survey results:")
		for response in self.responses:
			print('-'+response)

用于测试的类

python 复制代码
import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
	
	def test_store_single_response(self):
		'''测试一个答案也会被妥善储存'''
		question="What language did you first learn to speak?"
		#survey的属性question
		my_survey=AnonymousSurvey(question)
		#形成实例my_survey
		my_survey.store_response('english')
		#实例.方法名(形参)调用方法
		
		self.assertIn('english',my_survey.responses)
		#断言进行匹配
		
		
	def test_store_three_responses(self):
		question="what language did you learn first?"
		#survey的属性
		my_survey=AnonymousSurvey(question)
		#形成实例
		responses=['english','spanish','mandarin']
		#survey的另一个属性,一个不为空的测试用列表
		for response in responses:
			my_survey.store_response(response)
		#对测试列表中的每个元素调用survey中的方法store_response(元素)
		#调用后应该形成了一个试后列表
			
		for response in responses:
			self.assertIn(response,my_survey.responses)
		#对测试列表中的每个元素进行循环,检测它们是否在试后列表中
		#my_survey.responses就是前面survey中的self.responses
			
unittest.main()

输出

python 复制代码
..
----------------------------------------------------------------------
Ran 2 tests in 0.004s

OK


------------------
(program exited with code: 0)

请按任意键继续. . .
相关推荐
小羊没烦恼!5 分钟前
Windows Azure Platform体验(1):Windows Azure
java·大数据·后端·python·flask·word·.net
夏幻灵6 分钟前
前端八股:JavaScript 深拷贝详解:实现方式、递归原理与循环引用
开发语言·前端·javascript
JWASX9 分钟前
【agent 开发】agent 开发学习 - LangChain(1)
python·学习·agent
jason.zeng@150220714 分钟前
(五)多轮对话上下文,实现交互。
python·交互·llama
wangchunyu11415 分钟前
食韵味简 —— 免费开源的中式菜谱 API 服务
python·django·开源
znx93915 分钟前
因子分析:量化交易的底层核心与盈利逻辑基石
人工智能·python·机器学习·期魔方
jason.zeng@150220720 分钟前
(十)分层架构的多文件工程
python·架构·prompt·交互·ai编程·llama
小小张说故事21 分钟前
Python 装饰器到底是个啥?从 @ 符号到手写一个,5 个例子讲透
后端·python
傲世仙尊22 分钟前
C++起步-命名空间解决命名冲突与cin-cout缺省参数
开发语言·c++
hljqwb25 分钟前
java服务异常日志只打印异常类型,没有堆栈定位分析(十)
java·开发语言