python自动化--如何用unittest创建一个测试类
创建一个测试类
# 创建一个名为login的.py文件 # 登录系统 def login_check(username, password): """ 登录校验的函数 :param username: 账号 :param password: 密码 :return: """ if 6 <= len(password) <= 18: if username == 'python' and password == '123456': return {'code': 0, 'msg': '登录成功'} elif username != 'python' and password == '123456': return {'code': 1, 'msg': '账号不正确'} elif username == 'python' and password != '123456': return {'code': 2, 'msg': '密码不正确'} else: return {'code': 1, 'msg': '密码长度在6~18位之间'}
#创建一个以test开头的.py文件 import unittest from login import login_check # 创建测试类,继承unittest.TestCase类,测试用例 class TestLogin(unittest.TestCase): """ 测试登录功能 """ #如果有初始(前置)条件和结束(后置)条件,重写手脚架(fixture)方法 #定义单元测试函数,函数名一定要以test开头 #账号密码正确 {"username": "python", "password": "123456"}{"code": 0, "msg": "登录成功"} def test_login_ok(self): """ 账户密码正确 :return: """ # 1. 测试数据 test_data = {'username': 'python', 'password':'123456'} # 期望数据 expect_data = {'code': 0, 'msg': '登录成功'} # 2. 测试步骤 # 执行测试 res = login_check(**test_data) # 3. 断言 # 参数:前面的参数是期望结果,后面的参数是实际结果 self.assertEqual(expect_data, res) #调用unittest.main()来执行测试用例 if __name__ == '__main__': unittest.main()

浙公网安备 33010602011771号