码迷,mamicode.com
首页 > 其他好文 > 详细

unittest单元测试案例(一)

时间:2020-06-23 15:34:05      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:assert   password   lis   exce   username   账号   stc   count   用例   

实现登陆功能的单元测试

验证参数有效性函数

def login_check(username, password):
    """

    :param username: 登陆用户名
    :param password: 登陆密码
    :return:
    """
    if 6 <= len(password) <= 18:
        if username == "admin" and password == "123456":
            return {"code": 0, "msg": "登陆成功"}
        else:
            return {"code": 1, "msg": "账号或者密码不正确"}
    else:
        return {"code": 1, "msg": "密码长度在6-18之间"}

创建测试类

import unittest

class Login_test(unittest.TestCase):
    def __init__(self, method, username, password, ex):
        super().__init__(method)
        self.username = username
        self.password = password
        self.ex = ex

    def test_login(self):
        result = login_check(self.username, self.password)
        excepted = result["msg"]
        try:
            self.assertEqual(excepted, self.ex)
        except AssertionError as e:
            print("该用例未通过")
            result = "不通过"
            raise e
        else:
            print("该用例通过")
            result = "通过"

进行测试

s = unittest.TestSuite()
data = [(test_login,admin, 123456, 登录成功),
               (test_login,adddd, 123456, 账号密码不正确),
               (test_login,admin,11234565, 账号密码不正确),
               (test_login,admin,12345, 密码长度在6-18之间),
               (test_login,admin,12345678912345678912, 密码长度在6-18之间)]
for i in data:
    s.addTest(Login_test(*i))
r = unittest.TextTestRunner()
r.run(s)

也可以通过将参数放置excel中的方式,进行测试

excel内容如下:

技术图片

 

 代码如下:

import openpyxl
s = unittest.TestSuite()
wb = openpyxl.load_workbook("test_code.xlsx")
sheet = wb["Sheet1"]
max_row = sheet.max_row
name_list = []
pwd_list = []
ex_list = []
for i in range(2, max_row + 1):
    name_list.append(sheet.cell(row=i, column=1).value)
    pwd_list.append(sheet.cell(row=i, column=2).value)
    ex_list.append(sheet.cell(row=i, column=3).value)
count = len(name_list)
for j in range(0, count):
    data = (test_login, name_list[j], str(pwd_list[j]), ex_list[j])
    s.addTest(Login_test(*data))

r = unittest.TextTestRunner()
r.run(s)

 

unittest单元测试案例(一)

标签:assert   password   lis   exce   username   账号   stc   count   用例   

原文地址:https://www.cnblogs.com/zhouzetian/p/13181947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!