您的位置:首页 > 编程语言 > Python开发

【python接口自动化】初识unittest框架

2021-05-31 22:22 976 查看

本文将介绍单元测试的基础版及使用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框架产出可视化测试报告

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: