class TestLogin(unittest.TestCase): excel = ReadExcel(case_file, "login") cases = excel.read_data() request = SendRequest() @data(*cases) def test_login(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] data = eval(case["data"]) headers = eval(conf.get("env", "headers")) expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestUser(unittest.TestCase): excel = ReadExcel(os.path.join(data_dir, "test_cases.xlsx"), "username_email") cases = excel.read_data() request = SendRequest() @data(*cases) def test_user(self, case): # 准备用例数据 url = conf.get("env", "url") + CaseData.replace_data(case["url"]) data = eval(case["data"]) headers = eval(conf.get("env", "headers")) method = case["method"] expected = eval(case["expected"]) row = case["case_id"] + 1 # 发送请求,获取相应结果 reponse = self.request.send(url=url, method=method, headers=headers, params=data) res = reponse.json() print("预期结果", expected) print("实际结果", res) # 断言 try: self.assertEqual(res["count"], expected["count"]) except AssertionError as e: self.excel.write_data(row=row, column=8, value="不通过") raise e else: self.excel.write_data(row=row, column=8, value="通过")
class Test_Login(unittest.TestCase): excel = ReadExcel(case_file, "login") cases = excel.read_data() #列表==》2个及以上的字典==》1个字典就是一条用例 request = SendRequest() @data(*cases) def test001_login(self, case): #第一步:准备接口请求数据 url = conf1.get("env", "url") + case["url"] # print(url) method = case['method'] # eval这个内置函数的作用:执行一个字符串表达式、并且返回执行后的结果 params = eval(case['params']) # print(params) auth = HTTPBasicAuth("1000001".encode('utf-8'), "123456") expected = eval(case['expected']) #用来和实际结果进行对比==》断言 # print(expected) row = case['case_id'] + 1 # #第二步:发送接口请求 c = SendRequest() res = self.request.send(method, api="login", url=url, params=params, auth=auth) # res = self.request.send(method, api="login", url=url, params=params) result = res.json() print(result)
class Test_Login(unittest.TestCase): excel = ReadExcel(case_file, "能源管理中心") cases = excel.read_data() #列表==》2个及以上的字典==》1个字典就是一条用例 request = SendRequest() token = Token_cls().token() @data(*cases) def test001_login(self, case): #第一步:准备接口请求数据 url = conf1.get("env", "url") + case["url"] # print(url) method = case['method'] # eval这个内置函数的作用:执行一个字符串表达式、并且返回执行后的结果 params = eval(case['params']) # eval函数的参数必须为字符串,否则将报错: # params = case['params'] headers = {"Content-Type": "text/plain", "ID-Token": self.token} expected = eval(case['expected']) #用来和实际结果进行对比==》断言 classification = case['classification'] #用来和实际结果进行对比==》断言 row = case['case_id'] + 1 # 第二步:发送接口请求 # c = SendRequest() res = self.request.send(method, url=url, params=params, headers=headers) # res = self.request.send(method, api="login", url=url, params=params) result = res.json() # self.excel.write_data(row=row, column=10, value=str(result)) print(result)
class TestMainStream(unittest.TestCase): excel = ReadExcel(case_file, "main_stream") cases = excel.read_data() request = SendRequest() @data(*cases) def test_main_stream(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + replace_data(case["url"]) method = case["method"] if case["interface"] == "register": # 注册接口,则随机生成一个手机号码 CaseDate.mobilephone = self.random_phone() data = eval(replace_data(case["data"])) headers = eval(conf.get("env", "headers")) # 判断是否是登录接口,不是登录接口则需要添加token if case["interface"] != "login" and case["interface"] != "register": headers["Authorization"] = getattr(CaseDate, "token_value") expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 print("请求参数:", data) response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() print("预期结果", expected) print("实际结果", res) # 发送请求后,判断是否是登陆接口 if case["interface"].lower() == "login": # 提取用户id保存为类属性 CaseDate.member_id = str(jsonpath.jsonpath(res, "$..id")[0]) token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] # 提取token,保存为类属性 CaseDate.token_value = token_type + " " + token # 判断是否是加标的用例,如果是的则请求标id if case["interface"] == "add": CaseDate.loan_id = str(jsonpath.jsonpath(res, "$..id")[0]) # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertIn(expected["msg"], res["msg"]) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"])) def random_phone(self): phone = "137" n = random.randint(100000000, 999999999) phone += str(n)[1:] return phone
class TESTAdd(unittest.TestCase): excel = ReadExcel(file_path, "add") cases = excel.read_data() request = SendRequest() @classmethod def setUpClass(cls): """管理员账户登录""" url = conf.get("env", "url") + "/member/login" data = { "mobile_phone": conf.get("test_data", "admin_phone"), "pwd": conf.get("test_data", "admin_pwd") } headers = eval(conf.get("env", "headers")) response = cls.request.send(url=url, method="post", json=data, headers=headers) res = response.json() token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] member_id = jsonpath.jsonpath(res, "$..id")[0] # 将提取的数据保存到CaseData的属性中 CaseDate.admin_token_value = token_type + " " + token CaseDate.admin_member_id = member_id @data(*cases) def test_add(self, case): # 第一步:准备数据 url = conf.get("env", "url") + case["url"] headers = eval(conf.get("env", "headers")) headers["Authorization"] = getattr(CaseDate, "admin_token_value") data = eval(replace_data(case["data"])) expected = eval(case["expected"]) method = case["method"] row = case["case_id"] + 1 # 第二步:发请求获取实际结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) # 数据库校验 except AssertionError as e: print("预期结果:", expected) print("实际结果:", res) self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestRegister(unittest.TestCase): excel = ReadExcel(os.path.join(data_dir,"test_cases.xlsx"),"register") cases = excel.read_data() request = SendRequest() @data(*cases) def test_register(self,case): # 准备用例数据 user = self.random_user() email = self.random_email() url = conf.get("env","url") +case["url"] case["data"] = case["data"].replace("@username@",user) case["data"] = case["data"].replace("@email@",email) if case["title"] == "注册失败-用户名已注册" or case["title"] == "注册失败-邮箱已注册": case["data"] = CaseData.replace_data(case["data"]) data = eval(case["data"]) print(data) headers = eval(conf.get("env","headers")) method = case["method"] if case["title"]!="注册成功": expected = eval(case["expected"]) row = case["case_id"]+1 # 发送请求 response = self.request.send(url=url,json=data,headers=headers,method=method) res = response.json() if case["title"] == "注册成功": CaseData.pass_username = jsonpath.jsonpath(res,"$.username")[0] CaseData.passemail = email expected = eval(CaseData.replace_data(case["expected"])) print("预期结果",expected) print("实际结果",res) # 断言 try: if case["assert"]=="u": self.assertEqual(res["username"],expected["username"]) elif case["assert"]=="e": self.assertEqual(res["email"],expected["email"]) elif case["assert"]=="p": self.assertEqual(res["password"],expected["password"]) elif case["assert"] == "pc": self.assertEqual(res["password_confirm"], expected["password_confirm"]) elif case["assert"]=="nfe": self.assertEqual(res["non_field_errors"],expected["non_field_errors"]) except AssertionError as e: self.excel.write_data(row=row,column=8,value="不通过") raise e else: self.excel.write_data(row=row,column=8,value="通过") def random_user(self): username = "".join(random.sample("1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", 6)) return username def random_email(self): email = ("".join(random.sample("1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", 4)) + random.choice(("@163.com", "@126.com", "@qq.com"))) return email
class TestRegister(unittest.TestCase): excel = ReadExcel(case_file, "register") cases = excel.read_data() request = SendRequest() db = DB() def setUp(self): """测试用例运行前运行""" # 随机生成一个用户名,保存 CaseDate.name = self.random_name() @data(*cases) def test_register(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] # 替换用例数据 data = eval(replace_data(case["data"])) # 替换预期结果中的数据 expected = eval(replace_data(case["expected"])) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data) res = response.json() try: self.assert_dict_item(expected, res) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行通过".format(case["title"])) def assert_dict_item(self, dic1, dic2): """ 断言dic1中的所有元素都是diac2中的成员,成立返回True,不成立引发断言错误 :param dic1: 字典 :param dic2: 字典 :return: """ for item in dic1.items(): if item not in dic2.items(): raise AssertionError("{} items not in {}".format(dic1, dic2)) def random_name(self): """随机生成一个用户名""" print("---name-") while True: s1 = random.choice(["a", "b", "c", "d", "e"]) number = random.randint(1, 999999) name = s1 + str(number) # 判断数据库中是否存在该用户名, res = self.db.find_count( "SELECT * FROM test.auth_user WHERE username='******'".format( name)) if res == 0: return name
def token(self): # res = requests.post(url=url,params=params,auth=auth) c = SendRequest() res = c.send(method=self.method, url=self.url, params=self.params, auth=self.auth) result = res.json()['data']['accessToken'] return result
class TestUpdate(unittest.TestCase): excel = ReadExcel(case_file, "update") cases = excel.read_data() request = SendRequest() db = DB() @classmethod def setUpClass(cls): # 1、准备登录的数据 url = conf.get("env", "url") + "/member/login" data = { "mobile_phone": conf.get("test_data", "phone"), "pwd": conf.get("test_data", "pwd") } headers = eval(conf.get("env", "headers")) # 3、发送请求,进行登录 response = cls.request.send(url=url, method="post", json=data, headers=headers) # 获取返回的数据 res = response.json() # 3、提取token,保存为类属性 token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] # 将提取到的token设为类属性 CaseDate.token_value = token_type + " " + token # 提取用户的id,保存为类属性 CaseDate.member_id = str(jsonpath.jsonpath(res, "$..id")[0]) @data(*cases) def test_update(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] data = eval(replace_data(case["data"])) # 替换参数中的用户id headers = eval(conf.get("env", "headers")) headers["Authorization"] = getattr(CaseDate, "token_value") # 在请求头中加入setupclass中提取出来的token expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 print("请求参数为:",data,type(data)) response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) except AssertionError as e: print("预期结果:", expected) print("实际结果:", res) self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestWithdraw(unittest.TestCase): excel = ReadExcel(file_path, "withdraw") cases = excel.read_data() request = SendRequest() db = DB() @data(*cases) def test_withdraw(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] case["data"] = case["data"].replace("#phone#", conf.get("test_data", "phone")) case["data"] = case["data"].replace("#pwd#", conf.get("test_data", "pwd")) headers = eval(conf.get("env", "headers")) # 判断是否是取现接口,取现接口则加上请求头 if case["interface"].lower() == "withdraw": headers["Authorization"] = self.token_value case["data"] = case["data"].replace("#member_id#", str(self.member_id)) data = eval(case["data"]) expected = eval(case["expected"]) method = case["method"] row = case["case_id"] + 1 # 判断是否需要进行sql校验 if case["check_sql"]: sql = case["check_sql"].format(conf.get("test_data","phone")) start_money = self.db.find_one(sql)["leave_amount"] # 第二步:调用接口,获取实际结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 判断是否是登录接口 if case["interface"].lower() == "login": # 提取用户id保存为类属性 TestWithdraw.member_id = jsonpath.jsonpath(res, "$..id")[0] token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] # 提取token,保存为类属性 TestWithdraw.token_value = token_type + " " + token # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) if case["check_sql"]: sql = case["check_sql"].format(conf.get("test_data","phone")) end_money = self.db.find_one(sql)["leave_amount"] # 比对取现金额是否正确 self.assertEqual(Decimal(str(data["amount"])),start_money-end_money) except AssertionError as e: print("预期结果:", expected) print("实际结果:", res) self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestLogin(unittest.TestCase): excel = ReadExcel(case_file, "invest") cases = excel.read_data() request = SendRequest() @data(*cases) def test_login(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] case["data"] = replace_data(case["data"]) data = eval(case["data"]) headers = eval(conf.get("env", "headers")) # 判断是否是登录接口,不是登录接口则需要添加token if case["interface"] != "login": headers["Authorization"] = getattr(CaseDate, "token_value") expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 发送请求后,判断是否是登陆接口 if case["interface"].lower() == "login": # 提取用户id保存为类属性 CaseDate.member_id = str(jsonpath.jsonpath(res, "$..id")[0]) token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] # 提取token,保存为类属性 CaseDate.token_value = token_type + " " + token # 判断是否是加标的用例,如果是的则请求标id if case["interface"] == "add": CaseDate.loan_id = str(jsonpath.jsonpath(res, "$..id")[0]) # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) # self.assertEqual(expected["msg"], res["msg"]) self.assertIn(expected["msg"], res["msg"]) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestRegister(unittest.TestCase): excel = ReadExcel(case_file, "register") cases = excel.read_data() request = SendRequest() db = DB() @data(*cases) def test_register(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] # 生成一个手机号码 phone = self.random_phone() # 替换用例数据中的手机号码 case["data"] = case["data"].replace("#phone#", phone) data = eval(case["data"]) headers = eval(conf.get("env", "headers")) expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) if case["check_sql"]: sql = "SELECT * FROM futureloan.member WHERE mobile_phone={}".format( data["mobile_phone"]) count = self.db.find_count(sql) self.assertEqual(1, count) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"])) def random_phone(self): phone = "136" n = random.randint(100000000, 999999999) phone += str(n)[1:] return phone
class TestLogin(unittest.TestCase): excel = ReadExcel(case_file, "login") cases = excel.read_data() request = SendRequest() db = DB() # 读取excel用例数据 @data(*cases) # 进行拆包 def test_login(self, case): """登陆的测试用例""" # 第一步:准备用例数据 url = conf.get("evn", "url") + case["url"] headers = eval(conf.get("evn", "headers")) method = case["method"] # 登陆账号使用配置文件里面预设值的 TestLogin.mobile = eval(conf.get("test_data", "mobile")) case["data"] = case["data"].replace("#mobile#", str(self.mobile)) TestLogin.password = eval(conf.get("test_data", "password")) case["data"] = case["data"].replace("#password#", str(self.password)) data = eval(case["data"]) expected = eval(case["expected"]) row = case["case_id"] + 1 #第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 第三步:断言,回写数据 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class Test_Login(unittest.TestCase): """ 编写车辆监控中心的用例 :param case: :return: """ excel = ReadExcel(case_file, "车辆监控中心") cases = excel.read_data() #列表==》2个及以上的字典==》1个字典就是一条用例 request = SendRequest() token = Token_cls().token() auth = HTTPBasicAuth("101".encode('utf-8'), "123456") @data(*cases) def test001_login(self, case): """ 第一步:准备接口请求数据 :param case: :return: """ url = conf1.get("env", "url_vehicle") + case["url"] method = case['method'] # eval这个内置函数的作用:执行一个字符串表达式、并且返回执行后的结果,eval函数的参数必须为字符串,否则将报错 params = eval(case['params']) headers = {"ID-Token": self.token} # expected = eval(case['expected']) # 用来和实际结果进行对比==》断言 # classification = case['classification'] # 用来和实际结果进行对比==》断言 # row = case['case_id'] + 1 # 回写函数结果需要用到该行数 """发起接口请求""" res = self.request.send(method, url=url, params=params, headers=headers, auth=self.auth) result = res.json() print(result) # self.excel.write_data(row=row, column=10, value=str(result)) # 可回写返回的结果至对应excel表,主要做数据对比 """第三步:接口的断言"""
class TestLogin(unittest.TestCase): excel = ReadExcel(case_file, "login") cases = excel.read_data() request = SendRequest() @data(*cases) def test_login(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] data = eval(replace_data(case["data"])) expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data) res = response.json() # 第三步:断言(比对预期结果和实际结果) try: self.assert_dict_item(expected, res) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行通过".format(case["title"])) def assert_dict_item(self, dic1, dic2): """ 断言dic1中的所有元素都是diac2中的成员,成立返回True,不成立引发断言错误 :param dic1: 字典 :param dic2: 字典 :return: """ for item in dic1.items(): if item not in dic2.items(): raise AssertionError("{} items not in {}".format(dic1, dic2))
def test001_login(self, case): #第一步:准备接口请求数据 url = conf1.get("env", "url") + case["url"] # print(url) method = case['method'] # eval这个内置函数的作用:执行一个字符串表达式、并且返回执行后的结果 params = eval(case['params']) # print(params) auth = HTTPBasicAuth("1000001".encode('utf-8'), "123456") expected = eval(case['expected']) #用来和实际结果进行对比==》断言 # print(expected) row = case['case_id'] + 1 # #第二步:发送接口请求 c = SendRequest() res = self.request.send(method, api="login", url=url, params=params, auth=auth) # res = self.request.send(method, api="login", url=url, params=params) result = res.json() print(result)
class TestLogin(unittest.TestCase): excel = ReadExcel(os.path.join(data_dir, "test_cases.xlsx"), "login") cases = excel.read_data() request = SendRequest() @data(*cases) def test_login(self, case): # 准备用例数据 url = conf.get("env", "url") + case["url"] headers = eval(conf.get("env", "headers")) case["data"] = CaseData.replace_data(case["data"]) data = eval(case["data"]) method = case["method"] if case["title"] != "登录成功": expected = eval(case["expected"]) row = case["case_id"] + 1 # 发送请求并获取响应结果 response = self.request.send(url=url, method=method, headers=headers, json=data) res = response.json() if case["title"] == "登录成功": CaseData.pass_username = jsonpath.jsonpath(res, "$.username")[0] expected = eval(CaseData.replace_data(case["expected"])) print("预期结果:", expected) print("实际结果:", res) # 断言 try: if case["assert"] == "u": self.assertEqual(expected["username"], res["username"]) elif case["assert"] == "p": self.assertEqual(expected["password"], res["password"]) elif case["assert"] == "n": self.assertEqual(expected["non_field_errors"], res["non_field_errors"]) except AssertionError as e: self.excel.write_data(row=row, column=9, value="不通过") raise e else: self.excel.write_data(row=row, column=9, value="通过")
def random_testcases(): li = [] for i in range(1, 1001): s = "新增项目" s += str(i) li.append(s) res = random.choice(li) return res excel = ReadExcel(r"C:\sunny\test_develop_platform\data\test_cases.xlsx", "creatcases") case = excel.read_data() request = SendRequest() # user = random_user() # em = random_email() url = conf.get("env", "url") + case["url"] case["data"] = CaseData.replace_data(case["data"]) case["data"] = case["data"].replace("@testcases@", random_testcases()) data = eval(case["data"]) CaseData.pass_testcases = data["name"] expected = eval(case["expected"]) headers = eval(conf.get("env", "headers")) headers[ "Authorization"] = "JWT" + " " + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNDcsInVzZXJuYW1lIjoic3VubnkwMSIsImV4cCI6MTU4NDkzNTQ3NCwiZW1haWwiOiIxMTE3MkAxNjMuY29tIn0.pVMYwMnzUeuspM0MrqF_ssd5f4qbaOzwmBMvpTFcg7Y" method = case["method"]
class TestInterface(unittest.TestCase): excel = ReadExcel(case_file, "interface") cases = excel.read_data() request = SendRequest() db = DB() @classmethod def setUpClass(cls): """所有用例执行之前的环境准备:登录""" # 准备登录所需数据进行登录 url = conf.get("env", "url") + "/user/login/" login_data = { "username": conf.get("test_data", "username"), "password": conf.get("test_data", "password") } response = cls.request.send(url=url, method="post", json=login_data) res = response.json() # 提取登录之后的token token = jsonpath.jsonpath(res, "$..token")[0] # 保存token CaseDate.token = "JWT" + " " + token # 准备添加项目的数据,添加一个项目 pro_url = conf.get("env", "url") + "/projects/" pro_data = { "name": cls.random_project_name(), "leader": "lemonban", "tester": "木木木", "programmer": "zhang", "publish_app": "123", "desc": "jian" } headers = {"Authorization": getattr(CaseDate, "token")} # 发送请求添加项目 response = cls.request.send(url=pro_url, method="post", json=pro_data, headers=headers) res2 = response.json() # 保存添加的项目id CaseDate.project_id = str(jsonpath.jsonpath(res2, "$..id")[0]) # 保存添加的项目名 CaseDate.pro_name = pro_data["name"] @data(*cases) def test_interface(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] # 准备请求头 headers = {"Authorization": getattr(CaseDate, "token")} # 替换用例数据中的参数化 data = eval(replace_data(case["data"])) # 替换预期结果中的数据 expected = eval(replace_data(case["expected"])) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() try: self.assert_dict_item(expected, res) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行通过".format(case["title"])) def assert_dict_item(self, dic1, dic2): """ 断言dic1中的所有元素都是diac2中的成员,成立返回True,不成立引发断言错误 :param dic1: 字典 :param dic2: 字典 :return: """ for item in dic1.items(): if item not in dic2.items(): raise AssertionError("{} items not in {}".format(dic1, dic2)) @classmethod def random_project_name(cls): """随机生成一个项目名""" print("---name-") while True: s1 = random.choice(["前程贷", "开心贷", "新闻APP", "百度新闻", "秋秋"]) number = random.randint(1, 999999) name = s1 + str(number) # 判断数据库中是否存在该用户名, res = cls.db.find_count( "SELECT * FROM test.tb_projects WHERE name='{}'".format(name)) if res == 0: return name
class TestProjects(unittest.TestCase): excel = ReadExcel(os.path.join(data_dir, "test_cases.xlsx"), "projects") cases = excel.read_data() request = SendRequest() @classmethod def setUpClass(cls): url = conf.get("env", "url") + "/user/login/" headers = eval(conf.get("env", "headers")) data = { "username": conf.get("testcase", "username"), "password": "******" } response = cls.request.send(url=url, method="post", headers=headers, json=data) res = response.json() token = jsonpath.jsonpath(res, "$.token")[0] CaseData.token_value = "JWT" + " " + token @data(*cases) def test_projects(self, case): # 准备用例数据 url = conf.get("env", "url") + case["url"] headers = eval(conf.get("env", "headers")) headers["Authorization"] = getattr(CaseData, "token_value") case["data"] = case["data"].replace("@project@", self.random_project()) data = eval(case["data"]) if case["title"] != "新增失败—项目名称为空": CaseData.pass_project = data["name"] case["expected"] = CaseData.replace_data(case["expected"]) expected = eval(case["expected"]) method = case["method"] row = case["case_id"] + 1 # 发送请求并获取响应结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() print("预期结果", expected) print("实际结果", res) # 断言 try: if case["assert"] == "n": self.assertEqual(expected["name"], res["name"]) elif case["assert"] == "l": self.assertEqual(expected["leader"], res["leader"]) elif case["assert"] == "t": self.assertEqual(expected["tester"], res["tester"]) elif case["assert"] == "p": self.assertEqual(expected["programmer"], res["programmer"]) elif case["assert"] == "pa": self.assertEqual(expected["publish_app"], res["publish_app"]) elif case["assert"] == "d": self.assertEqual(expected["desc"], res["desc"]) else: self.assertEqual(expected["name"], res["name"]) except AssertionError as e: self.excel.write_data(row=row, column=8, value="不通过") raise e else: self.excel.write_data(row=row, column=8, value="通过") def random_project(self): li = [] for i in range(1, 10001): s = "新增项目" s += str(i) li.append(s) res = random.choice(li) return res
class TestRecharge(unittest.TestCase): excel = ReadExcel(case_file, "recharge") cases = excel.read_data() request = SendRequest() db = DB() @classmethod def setUpClass(cls): # 1、准备登录的数据 url = conf.get("env", "url") + "/member/login" data = { "mobile_phone": conf.get("test_data", "phone"), "pwd": conf.get("test_data", "pwd") } headers = eval(conf.get("env", "headers")) # 3、发送请求,进行登录 response = cls.request.send(url=url, method="post", json=data, headers=headers) # 获取返回的数据 res = response.json() # 3、提取token,保存为类属性 token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] # 将提取到的token设为CaseData类属性 CaseDate.token_value = token_type + " " + token # 提取用户的id,设为CaseData类属性 CaseDate.member_id = str(jsonpath.jsonpath(res, "$..id")[0]) @data(*cases) def test_recharge(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] # 替换参数中的用户id case["data"] = replace_data(case["data"]) data = eval(case["data"]) headers = eval(conf.get("env", "headers")) headers["Authorization"] = getattr(CaseDate, "token_value") # 在请求头中加入setupclass中提取出来的token expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 # 发送请求之前,获取用余额 if case["check_sql"]: sql = "SELECT leave_amount FROM futureloan.member WHERE mobile_phone={}".format( conf.get("test_data", "phone")) # 查询当前用户的余额 start_money = self.db.find_one(sql)["leave_amount"] response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 发送请求之后,获取用余额 if case["check_sql"]: sql = "SELECT leave_amount FROM futureloan.member WHERE mobile_phone={}".format( conf.get("test_data", "phone")) # 查询当前用户的余额 end_money = self.db.find_one(sql)["leave_amount"] # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) # 判断示范需要进行sql校验 if case["check_sql"]: self.assertEqual(end_money - start_money, Decimal(str(data["amount"]))) except AssertionError as e: print("预期结果:", expected) print("实际结果:", res) self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestProject(unittest.TestCase): excel = ReadExcel(case_file,"projects") cases = excel.read_data() request = SendRequest() @classmethod def setUpClass(cls) : # 1、准备登录的数据 url = conf.get("evn", "url") + "/user/login/" data = { "username": eval(conf.get("test_data", "username")), "password": conf.get("test_data", "password") } headers = eval(conf.get("evn", "headers")) # 3、发送请求,进行登录 response = cls.request.send(url=url, method="post", json=data, headers=headers) # 获取返回的数据 res = response.json() # 3、提取token,保存为类属性 # token = jsonpath.jsonpath(res, "token")[0] token = jsonpath.jsonpath(res, "token")[0] # 将提取到的token设为类属性 cls.token_value = "JWT" + " " + token @data(*cases) def test_project(self,case): """新建项目接口""" # 第一步:准备用例数据 url = conf.get("evn","url") + case["url"] method = case["method"] headers = eval(conf.get("evn","headers")) headers["Authorization"] = self.token_value # 随机生成项目名 name = random_name().replace(" ","") case["data"] = case["data"].replace("#name#", name) data= eval(case["data"]) # 在请求头中加入setupclass中提取出来的token expected = eval(case["expected"]) row = case["case_id"] + 1 #第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() ses = response.status_code # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["status"], ses) # 判断示范需要进行sql校验 # if case["check_sql"]: # self.assertEqual(end_money - start_money, Decimal(str(data["amount"]))) except AssertionError as e: print("预期结果:", expected) print("实际结果:", res) self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestInterfaces(unittest.TestCase): excel = ReadExcel(os.path.join(data_dir, "test_cases.xlsx"), "interfaces") cases = excel.read_data() request = SendRequest() @classmethod def setUpClass(cls): url = conf.get("env", "url") + "/user/login/" data = { "username": conf.get("testcase", "username"), "password": "******" } headers = eval(conf.get("env", "headers")) response = cls.request.send(url=url, method="post", headers=headers, json=data) res = response.json() token = jsonpath.jsonpath(res, "$.token")[0] CaseData.token_value = "JWT" + " " + token @data(*cases) def test_interfaces(self, case): # 准备用例数据 url = conf.get("env", "url") + case["url"] headers = eval(conf.get("env", "headers")) headers["Authorization"] = getattr(CaseData, "token_value") if case["title"] == "新增项目成功": case["data"] = case["data"].replace("@project@", RandomData.random_project()) if case["title"] != "新增项目成功": case["data"] = case["data"].replace("@interface@", RandomData.random_interface()) case["data"] = CaseData.replace_data(case["data"]) case["data"] = CaseData.replace_data(case["data"]) data = eval(case["data"]) if case["title"] != "创建失败-接口名称字段为空": CaseData.pass_project = data["name"] CaseData.pass_interface = data["name"] case["expected"] = CaseData.replace_data(case["expected"]) expected = eval(case["expected"]) method = case["method"] row = case["case_id"] + 1 # 发送请求并获取响应结果 response = self.request.send(url=url, headers=headers, method=method, json=data) res = response.json() if case["title"] == "新增项目成功": CaseData.project_id = str(jsonpath.jsonpath(res, "$.id")[0]) if case["title"] == "创建成功-创建接口成功": CaseData.repeat_interface = jsonpath.jsonpath(res, "$.name")[0] print("预期结果", expected) print("实际结果", res) # 断言 try: if case["assert"] == "n": self.assertEqual(expected["name"], res["name"]) elif case["assert"] == "t": self.assertEqual(expected["tester"], res["tester"]) elif case["assert"] == "p": self.assertEqual(expected["project_id"], res["project_id"]) elif case["assert"] == "d": self.assertEqual(expected["desc"], res["desc"]) elif case["assert"] == "j": self.assertLessEqual(expected["project_id"], res["project_id"]) else: self.assertEqual(expected["name"], res["name"]) except AssertionError as e: self.excel.write_data(row=row, column=9, value="不通过") raise e else: self.excel.write_data(row=row, column=9, value="通过")
class TestAudit(unittest.TestCase): excel = ReadExcel(file_path, "audit") cases = excel.read_data() request = SendRequest() db = DB() @classmethod def setUpClass(cls) -> None: """进行登录""" # 1、准备登录的数据 url = conf.get("env", "url") + "/member/login" data = { "mobile_phone": conf.get("test_data", "admin_phone"), "pwd": conf.get("test_data", "admin_pwd") } headers = eval(conf.get("env", "headers")) # 3、发送请求,进行登录 response = cls.request.send(url=url, method="post", json=data, headers=headers) # 获取返回的数据 res = response.json() # 3、提取token,保存为类属性 token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] # 将提取到的token设为CaseData类属性 CaseDate.admin_token_value = token_type + " " + token # 提取用户的id,设为CaseData类属性 CaseDate.admin_member_id = str(jsonpath.jsonpath(res, "$..id")[0]) def setUp(self) -> None: """进行加标""" # 1、准备加标的数据 url = conf.get("env", "url") + "/loan/add" headers = eval(conf.get("env", "headers")) headers["Authorization"] = getattr(CaseDate, "admin_token_value") data = {"member_id": getattr(CaseDate, "admin_member_id"), "title": "借钱实现财富自由", "amount": 2000, "loan_rate": 12.0, "loan_term": 3, "loan_date_type": 1, "bidding_days": 5} # 2、发送请求,添加项目 response = self.request.send(url=url, method="post", json=data, headers=headers) res = response.json() # 3、提取审核需要用到的项目id CaseDate.loan_id = str(jsonpath.jsonpath(res, "$..id")[0]) @data(*cases) def test_audit(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] case["data"] = replace_data(case["data"]) data = eval(case["data"]) headers = eval(conf.get("env", "headers")) headers["Authorization"] = getattr(CaseDate, "admin_token_value") expected = eval(case["expected"]) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 判断是否是审核通过的这条用例,并且审核通过 if res["code"] == 0 and case["title"] == "审核通过": CaseDate.pass_loan_id = str(data["loan_id"]) # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) # 判断是否需要进行sql校验 if case["check_sql"]: sql = replace_data(case["check_sql"]) status = self.db.find_one(sql)["status"] # 断言数据库中的标状态字段是否和预期一致。 self.assertEqual(expected["status"], status) except AssertionError as e: print("预期结果", expected) print("实际结果", res) self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestProjects(unittest.TestCase): excel = ReadExcel(case_file, "projects") cases = excel.read_data() request = SendRequest() db = DB() @classmethod def setUpClass(cls): """所有用例执行之前的环境准备:登录""" # 准备登录所需数据进行登录 url = conf.get("env", "url") + "/user/login/" login_data = { "username": conf.get("test_data", "username"), "password": conf.get("test_data", "password") } response = cls.request.send(url=url, method="post", json=login_data) res = response.json() # 提取登录之后的token token = jsonpath.jsonpath(res, "$..token")[0] CaseDate.token = "JWT" + " " + token # 数据库查询一个已存在的项目保存(给项目名已存在的用例使用) name = cls.db.find_one("SELECT NAME FROM test.tb_projects LIMIT 1") CaseDate.be_project_name = name["NAME"] def setUp(self): """测试用例运行前运行""" # 随机生成一个用户名,保存 CaseDate.project_name = self.random_project_name() @data(*cases) def test_projects(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] # 准备请求头 headers = {"Authorization": getattr(CaseDate, "token")} # 替换用例数据中的参数化 data = eval(replace_data(case["data"])) # 替换预期结果中的数据 expected = eval(replace_data(case["expected"])) row = case["case_id"] + 1 # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() try: self.assert_dict_item(expected, res) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行通过".format(case["title"])) def assert_dict_item(self, dic1, dic2): """ 断言dic1中的所有元素都是diac2中的成员,成立返回True,不成立引发断言错误 :param dic1: 字典 :param dic2: 字典 :return: """ for item in dic1.items(): if item not in dic2.items(): raise AssertionError("{} items not in {}".format(dic1, dic2)) @classmethod def random_project_name(cls): """随机生成一个项目名""" print("---name-") while True: s1 = random.choice(["前程贷", "开心贷", "新闻APP", "百度新闻", "秋秋"]) number = random.randint(1, 999999) name = s1 + str(number) # 判断数据库中是否存在该用户名, res = cls.db.find_count( "SELECT * FROM test.tb_projects WHERE name='{}'".format(name)) if res == 0: return name
class TestLogin(unittest.TestCase): excel = ReadExcel(case_file, "invest") cases = excel.read_data() request = SendRequest() db = DB() @data(*cases) def test_login(self, case): # 第一步:准备用例数据 url = conf.get("env", "url") + case["url"] method = case["method"] case["data"] = replace_data(case["data"]) data = eval(case["data"]) headers = eval(conf.get("env", "headers")) # 判断是否是登录接口,不是登录接口则需要添加token if case["interface"] != "login": headers["Authorization"] = getattr(CaseDate, "token_value") expected = eval(case["expected"]) row = case["case_id"] + 1 # 获取需要sql校验的数据: if case["check_sql"]: sql1 = "SELECT * FROM futureloan.member where id={}".format( CaseDate.member_id) sql2 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format( CaseDate.member_id, CaseDate.loan_id) sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format( CaseDate.member_id) # 获取开始的用户余额 start_amount = self.db.find_one(sql1)["leave_amount"] # 获取开始的投资记录条数 start_invest = self.db.find_count(sql2) # 获取用户开始的流水记录条数 start_fin = self.db.find_count(sql3) # 第二步:发送请求,获取结果 response = self.request.send(url=url, method=method, json=data, headers=headers) res = response.json() # 发送请求后,判断是否是登陆接口 if case["interface"].lower() == "login": # 提取用户id保存为类属性 CaseDate.member_id = str(jsonpath.jsonpath(res, "$..id")[0]) token = jsonpath.jsonpath(res, "$..token")[0] token_type = jsonpath.jsonpath(res, "$..token_type")[0] # 提取token,保存为类属性 CaseDate.token_value = token_type + " " + token # 判断是否是加标的用例,如果是的则请求标id if case["interface"] == "add": CaseDate.loan_id = str(jsonpath.jsonpath(res, "$..id")[0]) # 第三步:断言(比对预期结果和实际结果) try: self.assertEqual(expected["code"], res["code"]) self.assertIn(expected["msg"], res["msg"]) # 判断是否需要进行数据库校验 if case["check_sql"]: sql1 = "SELECT * FROM futureloan.member where id={}".format( CaseDate.member_id) sql2 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format( CaseDate.member_id, CaseDate.loan_id) sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format( CaseDate.member_id) # 获取投资后的用户余额 end_amount = self.db.find_one(sql1)["leave_amount"] self.assertEqual(start_amount - end_amount, Decimal(str(data["amount"]))) # 获取投资后投资记录条数 end_invest = self.db.find_count(sql2) self.assertEqual(end_invest - start_invest, 1) # 获取用户投资后的流水记录条数 end_fin = self.db.find_count(sql3) self.assertEqual(end_fin - start_fin, 1) # 在这里可以再判断是否是满标的投资用例,如果是满标的用例,再去校验该标的每一条投资记录有没有生成对应的回款计划表 if "满标" in case["title"]: # 获取当前标所有的投资记录id sql4 = "SELECT id FROM futureloan.invest WHERE loan_id={}".format( CaseDate.loan_id) invest_ids = self.db.find_all(sql4) # 遍历该标所有的投资记录的id for invest in invest_ids: sql5 = "SELECT * FROM futureloan.repayment WHERE invest_id={}".format( invest["id"]) # 获取当前这条投资记录,生成对应的回款计划 count = self.db.find_count(sql5) # 断言查询到的条数的布尔值是否为True(0的布尔值是False,只要不是0条,这个断言就会通过) self.assertTrue(count) except AssertionError as e: self.excel.write_data(row=row, column=8, value="未通过") log.error("用例:{},执行未通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=8, value="通过") log.info("用例:{},执行未通过".format(case["title"]))
class TestMainStream(unittest.TestCase): excel = ReadExcel(os.path.join(data_dir, "test_cases.xlsx"), "main_stream") cases = excel.read_data() request = SendRequest() @data(*cases) def test_main_stream(self, case): # 准备用例数据 url = conf.get("env", "url") + CaseData.replace_data(case["url"]) headers = eval(conf.get("env", "headers")) if case["interface"] == "projects" or case[ "interface"] == "interfaces" or case[ "interface"] == "testcases": headers["Authorization"] = getattr(CaseData, "token_value") case["data"] = CaseData.replace_data(case["data"]) if case["interface"] == "register": case["data"] = case["data"].replace("@username@", RandomData.random_user()) CaseData.pass_username = eval(case["data"])["username"] case["data"] = case["data"].replace("@email@", RandomData.random_email()) CaseData.pass_email = eval(case["data"])["email"] if case["interface"] == "projects": case["data"] = case["data"].replace("@project@", RandomData.random_project()) CaseData.pass_project = eval(case["data"])["name"] if case["interface"] == "interfaces": case["data"] = case["data"].replace("@interface@", RandomData.random_interface()) CaseData.pass_interface = eval(case["data"])["name"] if case["interface"] == "testcases": case["data"] = case["data"].replace("@testcases@", RandomData.random_testcases()) CaseData.pass_testcases = eval(case["data"])["name"] # case["data"] = CaseData.replace_data(case["data"]) data = eval(case["data"]) case["expected"] = CaseData.replace_data(case["expected"]) expected = eval(case["expected"]) method = case["method"] row = case["case_id"] + 1 # 发送请求并获取响应结果 response = self.request.send(url=url, method=method, headers=headers, json=data) res = response.json() print(res) if case["interface"] == "login": token = jsonpath.jsonpath(res, "$.token")[0] CaseData.token_value = "JWT" + " " + token if case["interface"] == "projects": CaseData.project_id = str(jsonpath.jsonpath(res, "$.id")[0]) if case["interface"] == "interfaces": CaseData.interface_id = str(jsonpath.jsonpath(res, "$.id")[0]) print("预期结果:", expected) print("实际结果:", res) # 断言 try: if case["assert"] == "c": self.assertEqual(expected["count"], res["count"]) elif case["assert"] == "u": self.assertEqual(expected["username"], res["username"]) else: self.assertEqual(expected["name"], res["name"]) except AssertionError as e: self.excel.write_data(row=row, column=9, value="不通过") log.error("用例:{}执行结果不通过".format(case["title"])) log.exception(e) raise e else: self.excel.write_data(row=row, column=9, value="通过") log.info("用例:{}执行通过".format(case["title"]))