标签:actual python userLogin unittest expected 初识 msg python666
本文将介绍单元测试的基础版及使用unittest框架的单元测试。
完成以下需求的代码编写,并实现单元测试
账号正确,密码正确,返回{"msg":"账号密码正确,登录成功"}
账号和密码任一为空,返回{"msg":"所有参数不能为空"}
账号/密码错误,返回{"msg":"账号/密码错误"}
基础代码实现:
- 定义方法,实现基本需求:
account_right = "python"
pwd_right = "python666"
def userLogin(account=None, pwd=None):
if not account or not pwd:
return {"msg":"所有参数不能为空"}
if account != account_right or pwd != pwd_right:
return {"msg":"账号/密码错误"}
if account == account_right and pwd == pwd_right:
return {"msg":"账号密码正确,登录成功"}
return {"msg":"未知错误,请联系管理员"}
对代码进行验证,是否符合需求:
- 验证方法1:
print(userLogin("",""))
print(userLogin("python666","python"))
print(userLogin("","python666"))
print(userLogin("python",""))
print(userLogin("python","python666"))
验证结果:
分析:直接调用userLogin方法,获取各种参数对应的返回结果
- 验证方法2:
if __name__ == '__main__':
try:
assert userLogin("","") == {"msg":"所有参不能为空"}
assert userLogin("python666","python") == {'msg': '账号/密码错误'}
assert userLogin("","python666") == {'msg': '所有参数不能为空'}
assert userLogin("python","") =={'msg': '所有参数不能为空'}
assert userLogin("python","python666") == {'msg': '账号密码正确,登录成功'}
except Exception as e:
print("啊哦,测试失败")
else:
print("恭喜!全部用例测试通过")
验证结果:
分析:通过assert判断,写入参数调取userLogin方法时得到的响应和预期的响应是否一致,如果一致就打印“全部通过”,如果有不一致的则会打印“测试失败”
此处使用到的try...except...else组合:不论如何一定会执行try下的代码,如果有报错则执行except下的代码,如果没有,则执行else下的代码。
- 验证方法3:使用unittest框架
另写一个python文件,则需导入userLogin方法
import unittest
class MyTestCase(unittest.TestCase):
def test_empty(self):
expected = {"msg":"所有参数不能为空"}
actual = userLogin("","")
self.assertEqual(expected,actual)
def test_pwd_wrong(self):
expected = {"msg":"账号/密码错误"}
actual = userLogin("python","python6")
self.assertEqual(expected,actual)
def test_account_empty(self):
expected = {"msg":"账号/密码错误"}
actual = userLogin("python666","python")
self.assertEqual(expected,actual)
def test_login_ok(self):
expected = {"msg":"账号密码正确,登录成功"}
actual = userLogin("python","python666")
self.assertEqual(expected,actual)
if __name__ == '__main__':
unittest.TestCase()
验证结果:
分析:unittest框架中自带assert,实现的效果和方法1、2并无不同,只不过这样更好管理用例,可视化测试结果,以及产出测试报告。
self.assertEqual(expected,actual)即是,判断expected和actual的返回值相等。
下一节:如何使用unittest框架产出可视化测试报告
标签:actual,python,userLogin,unittest,expected,初识,msg,python666 来源: https://www.cnblogs.com/rita-liu/p/14829620.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。