python测试代码
2024-08-25 03:46:21
前言:
编写函数或者类时,需要编写测试代码,来保证其的功能运行是否按预期的那样工作。在程序添加新的代码时,用来测试是否会破坏本身的功能。
我们使用python自带的unittest模块来测试代码。
编写函数:
def get_formatted_name(first,last,middle=''):
"""生成整洁的姓名"""
if middle:
full_name = first + ' '+ middle +' '+ last
else:
full_name = first + ' ' + last
return full_name.title()
编写测试:
import unittest
from name_function import get_formatted_name class NameTestCase(unittest.TestCase):
"""测试name_function.py """
def test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin') def test_first_last_middle_name(self):
"""能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
formatted_name = get_formatted_name('wolfgang','mozart','amadeus')
self.assertEqual(formatted_name,'Wolfgang Amadeus Mozart') unittest.main()
编写类:
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)
编写测试:
import unittest
from survey import AnonymousSurvey class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试三个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
lists = ['English','China','Japanese']
for s in lists:
my_survey.store_response(s)
self.assertIn(s, my_survey.responses) unittest.main()
总结:
unittest模块不仅支持单元测试,在接口和功能测试也能直接套用其中的方法。编写unittest必须添加继承unittest.TestCase类,测试的函数必须以test*开头,以及使用unittest.mian方法来运行此测试模块。
最新文章
- 在Linux和Windows的Docker容器中运行ASP.NET Core
- MongoDB基础知识
- 【转】Android之自定义Adapter的ListView
- SQL Server 内存数据库原理解析
- virtualenv -- python虚拟沙盒(linux版本)
- iptables常用命令
- C# RAS 非对称加密类 支持长字符串
- lsof-列出当前系统打开文件
- 基于三星ARM9(S3C2410)的交通违章抓拍系统的开发
- Java命令模式以及来自lambda的优化
- input选择框样式修改与自定义
- <;p>;标签样式设置
- SharePoint 2010 之soap:Server服务器无法处理请求
- [PHP]实体类基类和序列化__sleep问题
- Unit 3.标签的分类和嵌套规则
- spring4笔记----spring4构造注入
- centos7-软件安装-mysql5.7
- redis集群redis-cloud搭建
- 【Pyton】【小甲鱼】爬虫
- CF 827E Rusty String FFT