【python接口自动化】初见unittest架构

文中将详细介绍单元测试卷的基本版及应用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架构产出率数据可视化检测报告

评论(0条)

刀客源码 游客评论