功能实现类Register(一般开发人员提供,看懂即可)
import unittest users = [{"user": 'python27', "password": '123456'}] def register(username, password1, password2): # 判断所有参数是否为空,其一为空,那返回报错信息 if not all([username, password1, password2]): return {"code": 0, "meg": "所有参数不能为空"} # 遍历列表,判断是否已注册,否则报错 for user in users: if username == user['user']: return {"code": 0, "msg": "账号已存在"} # 若未注册,判断密码是否一致 else: if password1 != password2: return {"code": 0, "msg": "两次密码不一致"} # 若一致,则判断长度是否是否符合,符合则注册成功 else: if 6 <= len(username) >= 6 and 6 <= len(password1) <= 18: users.append({'user': username, 'password': password2}) return {"code": 1, "msg": "注册成功"} else: return {"code": 0, "msg": "账号和密码长度必须在6-18位之间"} if __name__=="__main__": res=register('python26','12345678','12345678') print(res)
测试用例类test_registerCases
- 这里难点是为什么重写父类TestCase的init方法?思考why
- 测试方法 中,根据字典的键得到期望数据,字典的值是需要输入的测试数据
import unittest from day15.register import register class RegisterTestCases(unittest.TestCase): # 对父类TestCase的init方法重写,将测试数据通过对象属性保存下来 def __init__(self, methodName,case_data): super().__init__(methodName) self.case_data=case_data def test_register(self): # 1.准备测试数据 expected=self.case_data["expected"] data=self.case_data["data"] # 2.调用方法,得到实际结果 actualResult = register(*data) # 4.对比 self.assertEqual(expected, actualResult)
运行套件:
import unittest from BeautifulReport import BeautifulReport from day15.test_registercases import RegisterTestCases suite=unittest.TestSuite() cases = [ {"expected": {'code': 1, 'msg': '注册成功'}, "data": ['jack34394', '12345678', '12345678']}, {"expected": {"code": 0, "msg": "两次密码不一致"}, "data": ['jack3434', '12345679', '12345678']}, {"expected": {"code": 0, "meg": "所有参数不能为空"}, "data": ['', '12345679', '12345678']}, {"expected": {"code": 0, "msg": "账号和密码长度必须在6-18位之间"}, "data": ['jack9001', '12345', '12345']}, {"expected": {"code": 0, "msg": "账号已存在"}, "data": ['python27', '123456', '123456']}] # 单条用例添加至套件 # case={"expected": {'code': 1, 'msg': '注册成功'}, "data": ['jack34394', '12345678', '12345678']} # case_data=RegisterTestCases("test_register",case) # suite.addTest(case_data) # 多条用例添加至套件 for case_data in cases: case=RegisterTestCases("test_register",case_data) suite.addTest(case) # 3.生成测试报告 br = BeautifulReport(suite) br.report("第一份报告", "report5.html")
这里是还没有用到ddt,下篇介绍ddt,将会更加简单