diff --git a/.gitignore b/.gitignore index 4f8fef49d82f196a131798ecf36b6e6354f5f700..1445dc73619cb1c02e85555e66b7a81ef21f2c9a 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ logs/ report/ .pytest_cache/ config/config.ini -test_suite/datas \ No newline at end of file +test_suite/datas +caches \ No newline at end of file diff --git a/README.md b/README.md index 69c3773df8e4a2a6ac770733ce14f5e080c94e5f..944322fca702ebce5779e0e0084fce9a1f62b157 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,62 @@ # **接口自动化测试框架** ## 目录结构 - |-- 接口自动化测试框架 # 主目录 - ├─common - ├─config - ├─scripts - ├─testsuite - ├─log - ├─report - ├─pytest.ini - ├─requirements.txt - ├─README.md - └─setupMain.py + |--接口自动化测试框架 # 主目录 + ├─common + ├─config + └─ config.ini + ├─scripts + ├─testsuite + ├─datas + └─ 项目文件夹 名称同config中 testname一致 + ├─ urlData.yml # 所有 url 具体格式参考下面YAML URL格式说明 + └─ login.yml # 用例数据 格式参考下面YAML PARAM格式说明 + ├─testcase + └─ 项目文件夹 名称同config中 testname一致 # 测试用例 + └─ test_login.py + ├─caches # 关联用的临时缓存文件夹 + ├─log + ├─report + ├─pytest.ini + ├─requirements.txt + ├─README.md + └─setupMain.py # 整体执行程序 -###yaml param格式 +## yaml param格式 - login: - - info: "用户名登录-成功" - headers: { - "Content-Type": "application/json" - } - data: { - "username": "finsiot", - "password": "finsiot" - } +``` yaml +login: + name: "登录" + token: false # 根据bool值判断此接口是否使用token + order: 1 # 执行顺序 @pytest.mark.run(order=1) + case: + - info: "用户名登录-成功" + host: 'host' + address: '/v1/apps/$url(region_id)$/' # $url(region_id)$ 正则匹配参数中的路径参数 + method: 'post' + relevance: + - cachefrom: 'body' # response : 从结果中获取 body : 从参数中获取 + path: '$.code' # body如果是 "id=2&path=haha" 会转换成字典 然后根据path使用jsonpath取值 + name: 'code' + - cachefrom: 'response' # response : 从结果中获取 body : 从参数中获取 + path: '$.data' + name: 'data' + headers: { + "Content-Type": "application/json" + } + data: + param: { + "username": "finsiot","password": "$caches(pwd)$" # 读取缓存值 + } + urlparam: { + id: 123 + }# 路径参数 v1/api/$url(id)$/ assert: jsonpath: + # 关联验证 - { - "path": "$.msg", - "value": "Success.", + "path": "$.data.expense_trend[0].peak_hour.peak_hour", + "value": "123", "asserttype": "==" } - { @@ -53,19 +81,55 @@ "name": "username" }, ], - "sql": "select * from saas.user where username = '****'", + "sql": "select * from saas.user where username = '****'", + # 取数据库查询出的第一条数据进行验证 如果存在 列名 username 值为$.data.username则通过 } time: 2 -###yaml url格式 - - login: - name: '登录' - address: '/v1/apps/login/' - method: 'post - +``` +## config.ini -### 其他 -jsonpath断言中value支持根据正则关联其他接口数据 -![img.png](img.png) -![img_1.png](img_1.png) - \ No newline at end of file +```ini +[directory] +pro_dir = 项目根目录 +log_dir = /logs/ +data_dir = /datas/ +page_dir = /page/ +report_xml_dir = /report/xml/ +report_html_dir = /report/html/ +test_suite = /test_suite/ +case_dir = /testcase/ +cache_dir = /caches/ +test_name = 测试项目名称 +[host] +http_type = http +host = +host_117 = +[email] +;服务器 +mail_host = smtp.sina.com +;发送邮箱 +mail_user = +;口令 +mail_pass = +;发送者 +sender = +;接收邮箱 +receivers = +[database] +host = 192. +port = 3306 +user = root +password = +;database = +database = +charset = utf8 +[dingding] +webhook = +secret = +``` +## 操作方法 +1. 新建config/config.ini文件 格式如上例子 +2. 执行scripts/newProject.py +3. 在生成的test_suite/datas/名称 文件夹下增加yaml测试用例 格式如上 +4. 执行writeCase.py生成测试脚本 关于token 需要根据自己项目情况修改writeCase.py的内容 (第59行) +5. 执行/setupMain.py开始测试 \ No newline at end of file diff --git a/common/basePage.py b/common/basePage.py index 1fd2c94e82372514e94006b5fcc19cb5a105cd3a..df859a04d5758d80dc2c8e53f5d51a17914a1021 100644 --- a/common/basePage.py +++ b/common/basePage.py @@ -3,15 +3,13 @@ import json import logging import os import random - import allure import requests -import simplejson from requests_toolbelt import MultipartEncoder - from scripts.log import Log from scripts.randomData import replace_random from config.confManage import host_manage +from scripts.relevance import Relevance Log() @@ -19,8 +17,8 @@ Log() class apiSend(object): def __init__(self): - self.host = host_manage(hos="${host}$") self.http_type = host_manage(hos="${http_type}$") + self.rel = Relevance() @staticmethod def iniDatas(data): @@ -29,30 +27,35 @@ class apiSend(object): if data is None: return data dataran = replace_random(data) - logging.info("请求参数: %s" % str(dataran)) return dataran - def post(self, address, header, request_parameter_type="json", timeout=8, data=None, files=None): + def post(self, address, header, rel, timeout=8, data=None, files=None, host="host"): """ post请求 + :param host: + :param rel: 关联情况 + - cachefrom: 'body' # response : 从结果中获取 body : 从参数中获取 + path: '$.code' # body如果是 "id=2&path=haha" 会转换成字典 然后根据path使用jsonpath取值 + name: 'code' :param address: 请求地址 :param header: 请求头 - :param request_parameter_type: 请求参数格式(form_data,raw) :param timeout: 超时时间 :param data: 请求参数 :param files: 文件路径 :return: """ - url = str(self.http_type) + "://" + self.host + address - logging.info("请求地址:%s" % "" + str(address)) + iniaddress = replace_random(address, param=data["urlparam"]) + url = str(self.http_type) + "://" + host_manage(hos='${{{}}}$'.format(host)) + iniaddress + data_random = self.iniDatas(data["param"]) + logging.info("请求地址:%s" % "" + url) logging.info("请求头: %s" % str(header)) - - if 'form-data' in request_parameter_type: + logging.info("请求参数: %s" % str(data_random)) + if "multipart/form-data" in header.values(): with allure.step("POST上传文件"): allure.attach(name="请求地址", body=url) allure.attach(name="请求头", body=str(header)) - allure.attach(name="请求参数", body=str(data)) + allure.attach(name="请求参数", body=str(data_random)) if files is not None: for i in files: value = files[i] @@ -69,16 +72,20 @@ class apiSend(object): boundary='-----------------------------' + str(random.randint(int(1e28), int(1e29 - 1))) ) header['Content-Type'] = multipart.content_type - response = requests.post(url=url, data=data, headers=header, timeout=timeout) else: - # print(type(data)) multipart = MultipartEncoder(data) - response = requests.post(url=url, data=multipart, headers={'Content-Type': multipart.content_type}, timeout=timeout) + elif 'application/json' in header.values(): + with allure.step("POST请求接口"): + allure.attach(name="请求地址", body=url) + allure.attach(name="请求头", body=str(header)) + allure.attach(name="请求参数", body=str(data_random)) + if data_random: + data_random = json.loads(data_random) + response = requests.post(url=url, json=data_random, headers=header, timeout=timeout) else: - data_random = self.iniDatas(data) with allure.step("POST请求接口"): allure.attach(name="请求地址", body=url) allure.attach(name="请求头", body=str(header)) @@ -90,31 +97,35 @@ class apiSend(object): return response.text else: logging.info("请求接口结果: %s" % str(response.json())) + self.rel.relevance(rel, bodys=data_random, res=response.json()) return response.json(), response.elapsed.total_seconds() - except json.decoder.JSONDecodeError: - return '' - except simplejson.errors.JSONDecodeError: - return '' except Exception as e: - logging.exception('ERROR') logging.error(e) raise - def get(self, address, header, data, timeout=8): + def get(self, address, rel, header, data, timeout=8, host="host"): """ get请求 + :param host: + :param rel: 关联情况 + - cachefrom: 'body' # response : 从结果中获取 body : 从参数中获取 + path: '$.code' # body如果是 "id=2&path=haha" 会转换成字典 然后根据path使用jsonpath取值 + name: 'code' :param address: :param header: 请求头 :param data: 请求参数 :param timeout: 超时时间 :return: """ - data_random = self.iniDatas(data) - url = str(self.http_type) + "://" + host_manage(hos='${host}$') + address - logging.info("请求地址:%s" % "" + str(address)) + iniaddress = replace_random(address, param=data["urlparam"]) + # if isinstance(data, dict): + # if "urlparam" in data.keys(): + # address = replace_random(address, param=data["urlparam"]) + data_random = self.iniDatas(data["param"]) + url = str(self.http_type) + "://" + host_manage(hos='${{{}}}$'.format(host)) + iniaddress + logging.info("请求地址:%s" % "" + url) logging.info("请求头: %s" % str(header)) logging.info("请求参数: %s" % str(data_random)) - with allure.step("GET请求接口"): allure.attach(name="请求地址", body=url) allure.attach(name="请求头", body=str(header)) @@ -124,68 +135,77 @@ class apiSend(object): response = requests.get(url=response.headers["location"]) try: logging.info("请求接口结果: %s" % str(response.json())) + self.rel.relevance(rel, bodys=data_random, res=response.json()) return response.json(), response.elapsed.total_seconds() - # except json.decoder.JSONDecodeError: - # return '' - # except simplejson.errors.JSONDecodeError: - # return '' except Exception as e: - logging.exception('ERROR') logging.error(e) raise - def put(self, address, header, request_parameter_type="json", timeout=8, data=None, files=None): + def put(self, address, rel, header, timeout=8, data=None, files=None, host="host"): """ put请求 + :param host: :param address: + :param rel: 关联情况 + - cachefrom: 'body' # response : 从结果中获取 body : 从参数中获取 + path: '$.code' # body如果是 "id=2&path=haha" 会转换成字典 然后根据path使用jsonpath取值 + name: 'code' :param header: 请求头 - :param request_parameter_type: 请求参数格式(form_data,raw) + :param timeout: 超时时间 :param data: 请求参数 :param files: 文件路径 :return: """ - - url = str(self.http_type) + "://" + host_manage(hos='${host}$') + address - logging.info("请求地址:%s" % "" + str(address)) + iniaddress = replace_random(address, param=data["urlparam"]) + url = str(self.http_type) + "://" + host_manage(hos='${{{}}}$'.format(host)) + iniaddress + logging.info("请求地址:%s" % "" + url) logging.info("请求头: %s" % str(header)) - - with allure.step("PUT请求接口"): - allure.attach(name="请求地址", body=url) - allure.attach(name="请求头", body=str(header)) - allure.attach(name="请求参数", body=str(data)) - - if request_parameter_type == 'raw': - data = self.iniDatas(data) + data_random = self.iniDatas(data["param"]) + logging.info("请求参数: %s" % str(data_random)) + if 'application/json' in header.values(): + with allure.step("PUT请求接口"): + allure.attach(name="请求地址", body=url) + allure.attach(name="请求头", body=str(header)) + allure.attach(name="请求参数", body=str(data_random)) + if data_random: + data_random = json.loads(data_random) + response = requests.put(url=url, json=data_random, headers=header, timeout=timeout, files=files) else: - data = data - response = requests.put(url=url, data=data, headers=header, timeout=timeout, files=files) + with allure.step("PUT请求接口"): + allure.attach(name="请求地址", body=url) + allure.attach(name="请求头", body=str(header)) + allure.attach(name="请求参数", body=str(data_random)) + + response = requests.put(url=url, data=data_random, headers=header, timeout=timeout, files=files) try: logging.info("请求接口结果: %s" % str(response.json())) + self.rel.relevance(rel, bodys=data_random, res=response.json()) return response.json(), response.elapsed.total_seconds() - except json.decoder.JSONDecodeError: - return '' - except simplejson.errors.JSONDecodeError: - return '' except Exception as e: - logging.exception('ERROR') logging.error(e) raise - def delete(self, address, header, data, timeout=8): + def delete(self, address, rel, header, data, timeout=8, host="host"): """ get请求 + :param host: + :param rel: 关联情况 + - cachefrom: 'body' # response : 从结果中获取 body : 从参数中获取 + path: '$.code' # body如果是 "id=2&path=haha" 会转换成字典 然后根据path使用jsonpath取值 + name: 'code' :param address: :param header: 请求头 :param data: 请求参数 :param timeout: 超时时间 :return: """ - data_random = self.iniDatas(data) - url = str(self.http_type) + "://" + host_manage(hos='${host}$') + address - logging.info("请求地址:%s" % "" + str(address)) + iniaddress = replace_random(address, param=data["urlparam"]) + data_random = self.iniDatas(data["param"]) + url = str(self.http_type) + "://" + host_manage(hos='${{{}}}$'.format(host)) + iniaddress + logging.info("请求地址:%s" % "" + url) logging.info("请求头: %s" % str(header)) - + logging.info("请求参数: %s" % str(data_random)) with allure.step("DELETE请求接口"): allure.attach(name="请求地址", body=url) allure.attach(name="请求头", body=str(header)) @@ -194,33 +214,31 @@ class apiSend(object): try: logging.info("请求接口结果: %s" % str(response.json())) + self.rel.relevance(rel, bodys=data_random, res=response.json()) return response.json(), response.elapsed.total_seconds() - except json.decoder.JSONDecodeError: - return '' - except simplejson.errors.JSONDecodeError: - return '' except Exception as e: - logging.exception('ERROR') logging.error(e) raise - def __call__(self, address, method, headers, data, **kwargs): + def __call__(self, rel, address, method, headers, data, **kwargs): try: if method == "post" or method == 'POST': - return self.post(address=address, data=data, header=headers, **kwargs) + return self.post(address=address, data=data, header=headers, rel=rel, **kwargs) elif method == "get" or method == 'GET': - return self.get(address=address, data=data, header=headers, **kwargs) + return self.get(address=address, data=data, header=headers, rel=rel, **kwargs) elif method == "delete" or method == 'DELETE': - return self.delete(address=address, data=data, header=headers ** kwargs) + return self.delete(address=address, data=data, header=headers, rel=rel, **kwargs) elif method == "put" or method == 'PUT': - return self.put(address=address, data=data, header=headers, **kwargs) + return self.put(address=address, data=data, header=headers, rel=rel, **kwargs) else: raise TypeError(f"请求异常,检查yml文件method") except Exception: - raise TypeError(f"请求异常,检查yml文件method") + raise apisend = apiSend() if __name__ == '__main__': - apisend.get() - apisend() \ No newline at end of file + ress = apisend("/$url(home_id)$", "get", data={"param": None, "urlparam": {"home_id": 123}}, headers={ + "Content-Type": "application/json" + }, host="host") + print(ress) diff --git a/common/checkResult.py b/common/checkResult.py index 839219f7c813e0f95dbde9a861078df0a740bf3c..69ec8888d4df0e0f8357ecd4f9161e0ee09276d9 100644 --- a/common/checkResult.py +++ b/common/checkResult.py @@ -1,7 +1,6 @@ # coding:utf-8 import logging -import time import allure import jsonpath @@ -14,64 +13,10 @@ from scripts.readYamlFile import ini_yaml Log() -def assert_json(data, key=None, value=None, asserttype="KEY"): - """ - json返回值断言 - :param data: 返回数据 - :param key: - :param value: - :param asserttype: "KEY" OR "VALUE" OR "KEY-VALUE" - :return: - """ - if asserttype == "KEY": - try: - assert data.get(key) is not None - with allure.step("判断JSON返回值KEY是否存在"): - allure.attach(name="期望存在KEY", body=str(key)) - allure.attach(name='实际data', body=str(data)) - logging.info( - "断言通过, 存在key'{}', value为'{}'.".format(key, data.get(key))) - except Exception: - logging.error("断言未通过, 不存在key:'{}'.".format(key)) - raise - elif asserttype == "VALUE": - try: - rs_values = list(data.values()) - with allure.step("判断JSON返回值VALUE是否存在"): - allure.attach(name="期望VALUE", body=str(value)) - allure.attach(name='实际VALUE', body=str(rs_values)) - assert value in rs_values - - logging.info("断言通过, 存在value为'{}', key为'{}'.".format(value, list(data.keys())[ - list(data.values()).index(value)])) - except AssertionError: - logging.error( - "断言未通过, 不存在类型为'{}'的value:''{}''.".format(type(value), value)) - raise - elif asserttype == "KEY-VALUE": - try: - - with allure.step("判断JSON返回值是否存在KEY-VALUE"): - allure.attach(name="期望KEY-VALUE", body=str({key: value})) - allure.attach(name='实际KEY-VALUE', body=str(data)) - if key in data: - assert value == data[key] - else: - logging.error("断言未通过, 不存在key:'{}'.".format(key)) - raise AssertionError - logging.info("断言通过, 存在键值对key为'{}',value为'{}'.".format(list(data.keys())[ - list(data.values()).index(value)], value)) - except AssertionError: - logging.error( - "断言未通过, 不存在key为'{}',类型为'{}'的value:''{}''.".format(key, type(value), value)) - raise - else: - logging.error("断言类型错误, 请选择断言类型.") - - -def assert_text(hope_res, real_res,third_data=None): +def assert_text(hope_res, real_res, third_data=None, third_datas=None): """ 文本判断 + :param third_datas: :param third_data: :param hope_res: 期望结果 :param real_res: 实际结果 @@ -83,35 +28,47 @@ def assert_text(hope_res, real_res,third_data=None): r_res = jsonpath.jsonpath(real_res, h_res["path"])[0] if h_res["asserttype"] == "==": try: - h_res["value"] = replace_random(str(h_res["value"]),res=third_data) - with allure.step("json断言判断相等"): - allure.attach(name="期望结果", body=str(h_res)) - allure.attach(name='实际实际结果', body=str(r_res)) - assert str(r_res) == str(h_res["value"]) - logging.info("json断言通过, 期望结果{0}, 实际结果{1}".format(h_res, r_res)) + if not third_datas: + h_res["value"] = replace_random(str(h_res["value"]), res=third_data) + with allure.step("json断言判断相等"): + allure.attach(name="期望结果", body=str(h_res)) + allure.attach(name='实际实际结果', body=str(r_res)) + assert str(r_res) == str(h_res["value"]) + logging.info("json断言通过, 期望结果'{0}', 实际结果'{1}'".format(h_res, r_res)) + elif third_datas: + if h_res["relevanceCheck"]: + h_res["value"] = replace_random(str(h_res["value"]), + res=third_datas[h_res["relevanceCheck"]]) + with allure.step("json断言判断相等"): + allure.attach(name="期望结果", body=str(h_res)) + allure.attach(name='实际实际结果', body=str(r_res)) + assert str(r_res) == str(h_res["value"]) + logging.info("json断言通过, 期望结果'{0}', 实际结果'{1}'".format(h_res, r_res)) except AssertionError: - logging.error("json断言未通过, 期望结果{0}, 实际结果{1}".format(h_res, r_res)) + logging.error("json断言未通过, 期望结果'{0}', 实际结果'{1}'".format(h_res, r_res)) raise elif h_res["asserttype"] == "!=": try: + h_res["value"] = replace_random(str(h_res["value"]), res=third_data) with allure.step("json断言判断不等"): allure.attach(name="json期望结果", body=str(h_res)) allure.attach(name='json实际实际结果', body=str(r_res)) assert str(r_res) != str(h_res["value"]) - logging.info("json断言通过, 期望结果{0}, 实际结果{1}".format(h_res, r_res)) + logging.info("json断言通过, 期望结果'{0}', 实际结果'{1}'".format(h_res, r_res)) except AssertionError: - logging.error("json断言未通过, 期望结果{0}, 实际结果{1}".format(h_res, r_res)) + logging.error("json断言未通过, 期望结果'{0}', 实际结果'{1}'".format(h_res, r_res)) raise elif h_res["asserttype"] == "in": r_res = str(r_res) try: + h_res["value"] = replace_random(str(h_res["value"]), res=third_data) with allure.step("json断言判断包含"): allure.attach(name="期望结果", body=str(h_res)) allure.attach(name='实际实际结果', body=str(r_res)) assert str(r_res) in str(h_res["value"]) - logging.info("json断言通过, 期望结果{0}, 实际结果{1}".format(h_res, real_res)) + logging.info("json断言通过, 期望结果'{0}', 实际结果'{1}'".format(h_res, real_res)) except AssertionError: - logging.error("json断言未通过, 期望结果{0}, 实际结果{1}".format(h_res, real_res)) + logging.error("json断言未通过, 期望结果'{0}', 实际结果'{1}'".format(h_res, real_res)) raise else: raise TypeError("asserttype方法错误") @@ -126,47 +83,65 @@ def assert_time(hope_res, real_res): allure.attach(name="期望响应时间", body=str(hope_time)) allure.attach(name='实际响应时间', body=str(real_res)) assert real_res <= hope_time - logging.info("time断言通过, 期望响应时间{0}, 实际响应时间{1}".format(hope_time, real_res)) + logging.info("time断言通过, 期望响应时间'{0}', 实际响应时间'{1}'".format(hope_time, real_res)) except AssertionError: - logging.error("请求响应时间过长, 期望时间{0}, 实际时间{1}".format(hope_time, real_res)) + logging.error("请求响应时间过长, 期望时间'{0}', 实际时间'{1}'".format(hope_time, real_res)) raise def assert_sql(hope_res, real_res): + """ + 一定要把断言的sql写精确写 只能通过sql查询出来的数据第一条进行断言 + :param hope_res: + :param real_res: + :return: + """ if isinstance(hope_res["sqlassert"], list): db = MYSQL() for h_res in hope_res["sqlassert"]: h_sql = h_res["sql"] + r_sql = replace_random(h_sql, real_res) + datas = db.run_sql(r_sql) for i in h_res["datas"]: if jsonpath.jsonpath(real_res, i["path"]): r_res = jsonpath.jsonpath(real_res, i["path"])[0] - i["name"] = replace_random(i["name"],real_res) - t1 = time.time() - r_sql = replace_random(h_sql,real_res) - datas = db.run_sql(r_sql) - + i["name"] = replace_random(i["name"], real_res) try: with allure.step("数据库校验"): allure.attach(name="期望结果", body=str(datas)) allure.attach(name='实际实际结果', body=str(r_res)) allure.attach(name='sql命令', body=str(r_sql)) - d = datas[0][i["name"]] - if isinstance(d,bytes): + if datas: + d = datas[0][i["name"]] + else: + d = None + if isinstance(d, bytes): d = d.decode("utf-8") assert str(r_res) == str(d) logging.info( - "sql断言通过, 期望结果{0}, 实际结果{1},sql耗时{2:.5f}秒".format(datas, r_res, time.time() - t1)) + "sql断言通过, 期望结果'{0}', 实际结果'{1}'".format(datas, r_res)) except AssertionError: - logging.error("sql断言未通过, 期望结果{0}, 实际结果{1},sql耗时{2:.5f}秒".format(datas, r_res, time.time() - t1)) + db.close() + logging.error("sql断言未通过, 期望结果'{0}', 实际结果'{1}'".format(datas, r_res)) raise else: + db.close() raise ValueError("获取json值失败,请检查jsonpath") db.close() -def asserting(hope_res, real_res, re_time=None,third_data=None): +def asserting(hope_res, real_res, re_time=None, third_data=None, third_datas=None): + """ + + :param hope_res: 期望结果 + :param real_res: 实际结果 + :param re_time: 实际响应时间 + :param third_data: 依赖数据 + :param third_datas: 依赖数据组 + :return: + """ if hope_res["jsonpath"]: - assert_text(hope_res, real_res,third_data) + assert_text(hope_res, real_res, third_data, third_datas) if hope_res["sqlassert"]: assert_sql(hope_res, real_res) if hope_res["time"]: @@ -212,5 +187,5 @@ if __name__ == '__main__': # "time": None # } hp = ini_yaml("loginData.yml") - print(hp) - asserting(hp, j,23) + # print(hp) + asserting(hp["login"][0]["assert"], j, 23) diff --git a/config/confManage.py b/config/confManage.py index c7982f2e5ee64bfaf5c8687edc38dc8f8c78fc95..4eff3c8a541927a4cd798742af34d58219586898 100644 --- a/config/confManage.py +++ b/config/confManage.py @@ -91,4 +91,6 @@ if __name__ == '__main__': # print(db_manage("${database}$")) # print(db_manage("${charset}$")) # print(int(db_manage("${port}$"))) - print(dingding_manage("${webhook}$")) + print(host_manage("${host}$")) + print("${{{haha}}}$".format(**{"haha":"123"})) + print(host_manage("${{{haha}}}$".format(**{"haha":"host2"}))) diff --git a/config/confRead.py b/config/confRead.py index 0c8fd0a28bc9b34c4be1bf90cc240ed0487dbcd1..eaf76f6233dfcafaa39b73624bed60461edcdd10 100644 --- a/config/confRead.py +++ b/config/confRead.py @@ -48,4 +48,4 @@ class Config(object): if __name__ == '__main__': c = Config() - print(c.read_db()["host"]) + print(c.read_host()["host"]) diff --git a/img.png b/img.png deleted file mode 100644 index 12b9ea0bcec2d7a385441f8a6bdbebabf66185bd..0000000000000000000000000000000000000000 Binary files a/img.png and /dev/null differ diff --git a/img_1.png b/img_1.png deleted file mode 100644 index 275c76e5908d33ef27a9b5d3a53a6a0292a42f81..0000000000000000000000000000000000000000 Binary files a/img_1.png and /dev/null differ diff --git a/scripts/dataBase.py b/scripts/dataBase.py index 3f6dbab03d67161cafa8f8886c79a0747aa6c2af..8787fe1e46d549f5152e0bfaa86f6970d05eb8e4 100644 --- a/scripts/dataBase.py +++ b/scripts/dataBase.py @@ -7,6 +7,7 @@ import pymysql from scripts.log import Log import logging from config.confManage import db_manage +import time Log() @@ -21,13 +22,13 @@ class MYSQL(object): self.charset = db_manage("${charset}$") self.port = int(db_manage("${port}$")) try: - logging.debug("正在连接数据库..") + logging.debug("正在连接数据库.") self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database, port=self.port, charset=self.charset) self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) - logging.debug("数据库连接成功..") + logging.debug("数据库连接成功.") except Exception as e: - logging.error("连接数据库失败..{}".format(e)) + logging.error("连接数据库失败,{}".format(e)) raise e def run_sql(self, sql): @@ -39,20 +40,28 @@ class MYSQL(object): try: logging.debug("准备执行SQL语句..") logging.debug("sql语句:{}".format(sql)) + t1 = time.time() self.cursor.execute(sql) rs = self.cursor.fetchall() + logging.info("执行成功,,sql耗时{0:.5f}秒".format(time.time() - t1)) return rs except Exception as e: - logging.error("执行SQL失败..{}".format(e)) - raise + self.close() + logging.error("执行SQL失败.{}".format(e)) + raise SystemError("执行SQL失败.{}".format(e)) def commit(self): self.conn.commit() def close(self): - self.conn.close() - self.cursor.close() - logging.debug("关闭数据库") + try: + self.conn.close() + self.cursor.close() + logging.debug("断开数据库连接.") + except Exception: + logging.debug("断开数据库连接错误,请手动断开.") + raise + if __name__ == "__main__": DB = MYSQL() @@ -86,4 +95,4 @@ select replace((select count(*) ) ad), 0, null) as "haha" """ ) - print(datas[0]["haha"].decode("utf-8")) \ No newline at end of file + print(datas[0]["haha"].decode("utf-8")) diff --git a/scripts/newProject.py b/scripts/newProject.py new file mode 100644 index 0000000000000000000000000000000000000000..80d1279f4e0771bd24ab73ac7434b7e4a99c5820 --- /dev/null +++ b/scripts/newProject.py @@ -0,0 +1,47 @@ +# coding:utf-8 +""" +@author: 井松 +@contact: 529548204@qq.com +@file: newProject.py +@time: 2021/12/22 15:52 +""" +from config.confManage import dir_manage +from scripts.mkDir import mk_dir +testname = dir_manage('${test_name}$') +pro_path = dir_manage('${pro_dir}$') + dir_manage('${test_suite}$') +casepath = pro_path + dir_manage('${case_dir}$') + testname + +datapath = pro_path + dir_manage('${data_dir}$') + testname +def newProject(): + mk_dir(casepath) + mk_dir(datapath) + with open(casepath + "/" + r"{}".format("__init__.py"), 'w', encoding='utf-8') as f: + f.write("""# coding:utf-8 + +import logging + +import allure +import pytest + +from common.checkResult import asserting +from scripts.log import Log +from scripts.readYamlFile import ini_yaml +from common.basePage import apisend + + +Log() +__all__ = [ + 'pytest', + 'asserting', + 'Log', + 'ini_yaml', + 'logging', + 'allure', + 'apisend', +]""") + with open(casepath + "/" + r"{}".format("conftest.py"), 'w', encoding='utf-8') as f: + f.write(f"""# coding:utf-8 +from test_suite.testcase.{testname} import *""") + +if __name__ == '__main__': + newProject() \ No newline at end of file diff --git a/scripts/randomData.py b/scripts/randomData.py index a9e6288c4a86cf5a9aebfbbec6039a376cb72914..402c119faf14af4b36fb4b4e43f4d5785825a892 100644 --- a/scripts/randomData.py +++ b/scripts/randomData.py @@ -6,6 +6,7 @@ import re import time import jsonpath +from scripts.relevance import Cache def choice_data(data): @@ -57,6 +58,15 @@ def sql_json(jspath, res): return jsonpath.jsonpath(res, jspath)[0] +def nomal(paramname, param): + return param[paramname] + +def caches(data): + c = Cache() + return c.get(data) + + + def random_int(scope): """ 获取随机整型数据 @@ -148,25 +158,46 @@ def get_time(time_type, layout, unit="0,0,0,0,0"): hours=int(resolution[2]), days=int(resolution[3]), weeks=int(resolution[4])) except ValueError: raise Exception("获取时间错误,时间单位%s" % unit) - if layout == "10timestamp": + if layout == "10timestampNOW": ti = ti.strftime('%Y-%m-%d %H:%M:%S') ti = int(time.mktime(time.strptime(ti, "%Y-%m-%d %H:%M:%S"))) return ti - elif layout == "13timestamp": + elif layout == "13timestampNOW": ti = ti.strftime('%Y-%m-%d %H:%M:%S') ti = int(time.mktime(time.strptime(ti, '%Y-%m-%d %H:%M:%S'))) # round()是四舍五入 ti = int(round(ti * 1000)) return ti + elif layout == "13timestampDAY": + ti = ti.strftime('%Y-%m-%d 00:00:00') + ti = int(time.mktime(time.strptime(ti, '%Y-%m-%d %H:%M:%S'))) + # round()是四舍五入 + ti = int(round(ti * 1000)) + return ti + elif layout == "10timestampDAYA": + ti = ti.strftime('%Y-%m-%d 00:00:00') + ti = int(time.mktime(time.strptime(ti, "%Y-%m-%d %H:%M:%S"))) + return ti else: ti = ti.strftime(layout) return ti -def replace_random(value, res=None): +def replace_random(value, res=None, param=None): """ 调用定义方法替换字符串 - :param res: + int_num = "$RandomPosInt(1,333)$" + str_num = '$RandomString($RandomPosInt(2,23)$)$$RandomPosInt(1,333)$' + float_num = '$RandomFloat($RandomPosInt(2,13)$,$RandomPosInt(2,13)$,$RandomPosInt(2,13)$)$' + time_num = '$GetTime(time_type=else,layout=%Y-%m-%d %H:%M:%S,unit=0,0,0,0,0)$' + choice_num = '$Choice($RandomPosInt(2,13)$)$' + json_value = '$json($.data[-$RandomPosInt(1,5)$:])$' + urls = "$url(home_id)$" + ca = "$caches(haha)$" + print(replace_random(urls,param={"home_id":"$caches(haha)$"})) + print(replace_random(ca)) + :param param: 路径参数数据 + :param res: jsonpath使用的返回结果 :param value: :return: """ @@ -177,6 +208,8 @@ def replace_random(value, res=None): time_list = re.findall(r"\$GetTime\(time_type=(.*?),layout=(.*?),unit=([0-9],[0-9],[0-9],[0-9],[0-9])\)\$", value) choice_list = re.findall(r"\$Choice\((.*?)\)\$", value) sqljson_list = re.findall(r"\$json\((.*?)\)\$", value) + urlparam_list = re.findall(r"\$url\((.*?)\)\$", value) + caches_list = re.findall(r"\$caches\((.*?)\)\$", value) if len(int_list): # 获取整型数据替换 @@ -194,26 +227,26 @@ def replace_random(value, res=None): value = replace_random(value, res) elif len(string_list): # 获取字符串数据替换 - for j in string_list: - pattern = re.compile(r'\$RandomString\(' + j + r'\)\$') - key = str(random_string(j)) + for i in string_list: + pattern = re.compile(r'\$RandomString\(' + i + r'\)\$') + key = str(random_string(i)) value = re.sub(pattern, key, value, count=1) value = replace_random(value, res) elif len(float_list): # 获取浮点数数据替换 - for n in float_list: - pattern = re.compile(r'\$RandomFloat\(' + n + r'\)\$') - key = str(random_float(n)) + for i in float_list: + pattern = re.compile(r'\$RandomFloat\(' + i + r'\)\$') + key = str(random_float(i)) value = re.sub(pattern, key, value, count=1) value = replace_random(value, res) elif len(time_list): # 获取时间替换 - for m in time_list: - if len(m[0]) and len(m[1]): - pattern = re.compile(r'\$GetTime\(time_type=' + m[0] + ',layout=' + m[1] + ',unit=' + m[2] + r'\)\$') - key = str(get_time(m[0], m[1], m[2])) + for i in time_list: + if len(i[0]) and len(i[1]): + pattern = re.compile(r'\$GetTime\(time_type=' + i[0] + ',layout=' + i[1] + ',unit=' + i[2] + r'\)\$') + key = str(get_time(i[0], i[1], i[2])) value = re.sub(pattern, key, value, count=1) else: print("$GetTime$参数错误,time_type, layout为必填") @@ -226,6 +259,7 @@ def replace_random(value, res=None): key = str(choice_data(i)) value = re.sub(pattern, key, value, count=1) value = replace_random(value, res) + elif len(sqljson_list): for i in sqljson_list: pattern = re.compile(r'\$json\(' + i.replace('$', "\$").replace('[', '\[') + r'\)\$') @@ -233,6 +267,23 @@ def replace_random(value, res=None): value = re.sub(pattern, key, value, count=1) value = replace_random(value, res) + elif len(urlparam_list): + + # urls = "$url(home_id)$" + # replace_random(urls,param={"home_id":"$caches(haha)$"}) + for i in urlparam_list: + pattern = re.compile(r'\$url\(' + i + r'\)\$') + key = str(nomal(i, param)) + value = re.sub(pattern, key, value, count=1) + value = replace_random(value, param) + elif len(caches_list): + # urls = "$url(home_id)$" + # replace_random(urls,param={"home_id":"$caches(haha)$"}) + for i in caches_list: + pattern = re.compile(r'\$caches\(' + i + r'\)\$') + key = str(caches(i)) + value = re.sub(pattern, key, value, count=1) + value = replace_random(value,param) else: pass return value @@ -240,18 +291,18 @@ def replace_random(value, res=None): if __name__ == '__main__': int_num = "$RandomPosInt(1,333)$" - str_num = '$RandomString($RandomPosInt(2,23)$)$' + str_num = '$RandomString($RandomPosInt(2,23)$)$$RandomPosInt(1,333)$' float_num = '$RandomFloat($RandomPosInt(2,13)$,$RandomPosInt(2,13)$,$RandomPosInt(2,13)$)$' time_num = '$GetTime(time_type=else,layout=%Y-%m-%d %H:%M:%S,unit=0,0,0,0,0)$' choice_num = '$Choice($RandomPosInt(2,13)$)$' '$json($.data[-$RandomPosInt(1,5)$:])$' jsons = """ -select count(*) '$json($.data[-$RandomPosInt(1,5)$:])$' +select count(*) '$json($.data[-$RandomPosInt(1,5)$:])$' $RandomString($RandomPosInt(2,23)$)$ ) as ad """ js = """ - select count(*) '$GetTime(time_type=past,layout=%Y-%m-%d,unit=0,0,0,1,0)$' from ( + select count(*) '$json($.data[-$RandomPosInt(1,5)$:])$' from ( select dr.qr_code, alarm.device_id, @@ -285,23 +336,12 @@ from alarm res1 = {'code': 0, 'msg': 'ok', 'data': [{'time': '2021-08-18', 'number': None}, {'time': '2021-08-19', 'number': None}, {'time': '2021-08-20', 'number': 1}, {'time': '2021-08-21', 'number': None}, - {'time': '2021-08-22', 'number': None}, {'time': '2021-08-23', 'number': 9}, - {'time': '2021-08-24', 'number': 7}, {'time': '2021-08-25', 'number': 11}, - {'time': '2021-08-26', 'number': 2}, {'time': '2021-08-27', 'number': 1}, - {'time': '2021-08-28', 'number': None}, {'time': '2021-08-29', 'number': None}, - {'time': '2021-08-30', 'number': None}, {'time': '2021-08-31', 'number': 1}, - {'time': '2021-09-01', 'number': 2}, {'time': '2021-09-02', 'number': 4}, - {'time': '2021-09-03', 'number': 3}, {'time': '2021-09-04', 'number': 3}, - {'time': '2021-09-05', 'number': 1}, {'time': '2021-09-06', 'number': 7}, - {'time': '2021-09-07', 'number': 13}, {'time': '2021-09-08', 'number': 23}, - {'time': '2021-09-09', 'number': 21}, {'time': '2021-09-10', 'number': 11}, - {'time': '2021-09-11', 'number': 7}, {'time': '2021-09-12', 'number': 4}, - {'time': '2021-09-13', 'number': 22}, {'time': '2021-09-14', 'number': 19}, - {'time': '2021-09-15', 'number': 38}, {'time': '2021-09-16', 'number': 39}]} + {'time': '2021-08-22', 'number': None}, {'time': '2021-08-23', 'number': 9}]} print(replace_random(js, res=res1)) - t = "$GetTime(time_type=past,layout=%Y-%m-%d 00:00:00,unit=0,0,0,1,4)$" + t = "$GetTime(time_type=past,layout=13timestampDAY,unit=0,0,0,1,4)$" # print(replace_random(choice_num)) - # print(replace_random(t)) + # print(replace_random(urls,param={"home_id":"$caches(haha)$"})) + # print(replace_random(ca)) # pattern = re.compile(r'\$json\(' + '$.data.alarm[1].number'.replace('$',"\$").replace('[','\[') + r'\)\$') # # key = str(sql_json(i)) # key = "123" diff --git a/scripts/readYamlFile.py b/scripts/readYamlFile.py index ded3c2018a0a0f7e087cc1703b31316ac1f815e9..ae000d40bdc834ae2f058bb55cb950aa8cdc56bc 100644 --- a/scripts/readYamlFile.py +++ b/scripts/readYamlFile.py @@ -7,17 +7,28 @@ datapath = dir_manage("${pro_dir}$") + dir_manage("${test_suite}$")+dir_manage(" def ini_yaml(filename, path=datapath): - with open(path + "/" + filename, 'r', encoding="utf-8") as f: - file_data = f.read() - data = yaml.load(file_data, Loader=yaml.FullLoader) + try: + with open(path + "/" + filename, 'r',encoding="utf-8") as f: + file_data = f.read() + data = yaml.safe_load(file_data) - return data + return data + except UnicodeDecodeError: + with open(path + "/" + filename, 'r') as f: + file_data = f.read() + data = yaml.safe_load(file_data) + + return data if __name__ == '__main__': + print(datapath) # get_yaml_data(r"F:\api2.0\config\runConfig.yml") - runConfig_dict = ini_yaml("thirdData.yml") - # case_level = runConfig_dict[0]["address"].format(**{"home_id": "123"}) + runConfig_dict = ini_yaml(r'login.yml')["login"]["case"] print(runConfig_dict) + # # case_level = runConfig_dict[0]["address"].format(**{"home_id": "123"}) + # print(runConfig_dict) + + # print(case_level) # print(type(case_level)) diff --git a/scripts/relevance.py b/scripts/relevance.py new file mode 100644 index 0000000000000000000000000000000000000000..3bab009e9f124b79be9223229e79789ad62d8457 --- /dev/null +++ b/scripts/relevance.py @@ -0,0 +1,127 @@ +# coding:utf-8 +""" +@author: 井松 +@contact: 529548204@qq.com +@file: relevance.py +@time: 2021/11/15 17:13 +""" + +import os +import shutil + +import jsonpath +from scripts.mkDir import mk_dir +from scripts.readYamlFile import ini_yaml +from config.confManage import dir_manage + +""" +response: 执行接口,根据jsonpath 读取返回结果的指定值 存入缓存 +body: 执行前 把body转化成json格式 根据jsonpath 读取指定参数值 存入缓存 + +取 +body: get请求 根据name replace参数 post 根据path 更新json数据 +""" +cachepath = dir_manage("${pro_dir}$") + dir_manage("${cache_dir}$") + + +def valueHandle(data: str): + param_dict = {} + param_list = data.split("&") + for param in param_list: + param_dict[param.split("=")[0]] = param.split("=")[1] + return param_dict + + +class Cache(object): + def __init__(self, path=cachepath): + self.path = path + mk_dir(path) + self.del_list = os.listdir(self.path) + + def set(self, key, value): + with open(self.path + key + ".text", 'w', encoding="utf-8") as f: + f.write(str(value)) + + def get(self, key): + + if key + ".text" in self.del_list: + with open(self.path + key + ".text", 'r', encoding="utf-8") as f: + value = f.read() + return value + else: + raise ValueError("{}不存在".format(key)) + + def set_many(self, data: dict): + for i in data: + with open(self.path + i + ".text", 'w', encoding="utf-8") as f: + f.write(str(data[i])) + + def clear_all_cache(self): + + del_list = os.listdir(self.path) + for f in del_list: + file_path = os.path.join(self.path, f) + if os.path.isfile(file_path): + os.remove(file_path) + elif os.path.isdir(file_path): + shutil.rmtree(file_path) + + def clear_cache(self, key: str): + file_path = os.path.join(self.path, key + ".text") + if os.path.isfile(file_path): + os.remove(file_path) + elif os.path.isdir(file_path): + shutil.rmtree(file_path) + + +class Relevance(object): + + def __init__(self): + self.caches = Cache() + + def respons_cache(self, data, respons): + values = jsonpath.jsonpath(respons, data['path']) + if not values: + raise ValueError("path错误") + self.caches.set(key=data["name"], value=values[0]) + + def body_cache(self, data, param): + if isinstance(param, dict): + values = jsonpath.jsonpath(param, data['path']) + + self.caches.set(key=data["name"], value=values[0]) + else: + values = jsonpath.jsonpath(valueHandle(param), data['path']) + if not values: + raise ValueError("path错误") + self.caches.set(key=data["name"], value=values[0]) + + def relevance(self, data: dict, bodys=None, res=None): + if data is not None: + for i in data: + if i["cachefrom"] == 'body': + self.body_cache(i, bodys) + elif i["cachefrom"] == 'response': + self.respons_cache(i, res) + else: + raise TypeError("datasfrom错误") + + + +if __name__ == '__main__': + s = {'regionList': {'name': '区域列表', 'host': 'host', 'address': '/v1/apps/region/', 'method': 'get', 'relevance': [ + # {'relevancetype': 'set', 'datasfrom': 'reponse', 'path': '$.data', 'name': "ceshi"}, + # {'relevancetype': 'get', 'datasfrom': 'reponse', 'path': '$.data', 'name': "ceshi"}, + {'relevancetype': 'set', 'datasfrom': 'body', 'path': "$.code", 'name': "code"}, + {'relevancetype': 'set', 'datasfrom': 'url', 'path': None, 'name': None}], 'relevanceCheck': None}} + ress = { + "data": { + "haha": 123 + } + } + bo = "code=200&msg=success" + + s1 = ini_yaml("urltest.yml", r"D:\apitest\test_suite\datas\saasApp") + rels = Relevance() + + rels.relevance(s1, bodys=bo, res=ress) diff --git a/scripts/writeCase.py b/scripts/writeCase.py new file mode 100644 index 0000000000000000000000000000000000000000..a61c77e68b6b8f2a01e2541856e3e32393795b0b --- /dev/null +++ b/scripts/writeCase.py @@ -0,0 +1,90 @@ +# coding:utf-8 +import os +import time + +from config.confManage import dir_manage +from scripts.log import Log +from scripts.readYamlFile import ini_yaml + +Log() +import logging + + +def getFilePathList(path): + filename = [] + # 获取所有文件下的子文件名称 + for root, dirs, files in os.walk(path): + # 过滤所有空文件 + if files: + for i in files: + # 判断只返回 yaml 的文件 + if '.yml' in i: + filename.append(str(i).split(".")[0]) + return filename + + +def write_pages(_file): + t1 = time.time() + testname = dir_manage('${test_name}$') + pro_path = dir_manage('${pro_dir}$') + dir_manage('${test_suite}$') + casepath = pro_path + dir_manage('${case_dir}$') + testname + + datapath = pro_path + dir_manage('${data_dir}$') + testname + filelist = getFilePathList(datapath) + print(filelist) + for file in filelist: + filedata = ini_yaml(file + ".yml") + if "test_" + file + ".py" in os.listdir(casepath): + pass + else: + with open(casepath + "/" + r"{}".format("test_" + file + ".py"), 'w', encoding='utf-8') as f: + f.write(f"""from test_suite.testcase.{testname} import * + +paramData = ini_yaml("{file}.yml") + +class Test_{file}(object):""") + for item in filedata: + order = filedata[item]["order"] + + f.write(f""" + @allure.story("Test_{file}") + @pytest.mark.parametrize('casedata', paramData["{item}"]["case"], + ids=[i["info"] for i in paramData["{item}"]["case"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order={order})""") + + if filedata[item]["token"]: + f.write(f""" + def test_{item}(self, casedata, setup_Login): + casedata["headers"]["Authorization"] = setup_Login""") # token类型是 Authorization + else: + f.write(f""" + def test_{item}(self, casedata):""") + f.write(""" + res, restime = apisend(host=casedata["host"], address=casedata["address"], method=casedata["method"], + headers=casedata["headers"], + data=casedata["data"], rel=casedata["relevance"]) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime)\n""") + + t2 = time.time() - t1 + print(t2) + + +# def write_case(f): +# for i in f: +# + + +if __name__ == '__main__': + # ym_path = r'thirdUrl.yml' + # pagenames = "third_pages_1.py" + + ym_path = r'urlData.yml' + pagenames = "saasApp_pages_1.py" + # write_case(ym_path,pagenames) + + # ym_path = r'urlData.yml' + # pagenames = "saasWeb_pages_1.py" + write_pages(ym_path) + # l = getFilePathList(r"D:\apitest\test_suite\datas\saasWeb") + # print(l) diff --git a/scripts/writePage.py b/scripts/writePage.py deleted file mode 100644 index 9773179bb5d074d4550819e50fcb57e6029a2e8b..0000000000000000000000000000000000000000 --- a/scripts/writePage.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding:utf-8 -import os - -from config.confManage import dir_manage -from scripts.log import Log -from scripts.readYamlFile import ini_yaml - -Log() -import logging - - -def getFilePathList(path, filetype): - pathList = [] - for root, dirs, files in os.walk(path): - for file in files: - if file.endswith(filetype): - pathList.append(os.path.join(root, file)) - return pathList - - -def write_case(_file): - path = dir_manage(dir_manage('${pro_dir}$') + dir_manage('${test_suite}$') + dir_manage('${page_dir}$')) - - with open(path + r"saasApp_pages_1.py", 'w+', encoding='utf-8') as f: - f.write("""# coding:utf-8\nfrom test_suite.page import *\n\nurlData = ini_yaml("urlData.yml")\n\n""") - yml_data = ini_yaml(_file) - - for item in yml_data.items(): - logging.debug("正在生成page文件.{}".format(str(item))) - f.write(""" -def {testtitle}(casedata):""".format(testtitle=item[0])) - f.write(""" - data = urlData["{0}"]""".format(item[0]) - ) - f.write( - """ - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime\n\n""" - ) - - -if __name__ == '__main__': - ym_path = r'urlData.yml' - write_case(ym_path) diff --git a/setupMain.py b/setupMain.py index 51dd5619c3a236c511cd9f33e15b7fee7857e90b..c2bba69768555238cc9792c2fa6b609505dab115 100644 --- a/setupMain.py +++ b/setupMain.py @@ -21,15 +21,17 @@ def run(): test_case_path = project_path + dir_manage('${test_suite}$') + dir_manage('${case_dir}$') + dir_manage( '${test_name}$') # temp地址变量 - temp_path = project_path + dir_manage('${report_xml_dir}$') + "temp/" + localtime + '/' + temp_path = project_path + dir_manage('${report_xml_dir}$') + "temp/" # html地址变量 - html_path = project_path + dir_manage('${report_html_dir}$') + date + '/' + html_path = project_path + dir_manage('${report_html_dir}$') # 如果不存在地址路径则创建文件夹 mk_dir(temp_path) mk_dir(html_path) # 执行命令行 args = ['-s', '-q', test_case_path, '--alluredir', temp_path] + # args = ['-s', '-q', test_case_path,] pytest.main(args) + cmd = 'allure generate %s -o %s -c' % (temp_path, html_path) os.system(cmd) # 发送报告 @@ -39,7 +41,7 @@ def run(): # ding.send_text("点击链接打开测试报告 http://192.168.1.2:9999",[13688400244]) # 生成html报告 os.system(r'allure generate {0} -o {1} '.format(temp_path, html_path)) - # 打开报告服务 并指定端口 + # # 打开报告服务 并指定端口 os.system(r'allure serve {0} -p 9999'.format(temp_path)) diff --git a/test_suite/page/saasApp_pages.py b/test_suite/page/saasApp_pages.py deleted file mode 100644 index 840c2194ca629038ac831cc6a31455616ff54151..0000000000000000000000000000000000000000 --- a/test_suite/page/saasApp_pages.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding:utf-8 -from test_suite.page import * - -urlData = ini_yaml("urlData.yml") - - -def login(casedata): - data = urlData["login"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def forgetPassword(casedata): - data = urlData["forgetPassword"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def mobileCode(casedata): - data = urlData["mobileCode"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def todayTask(casedata): - data = urlData["todayTask"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def companyName(casedata): - data = urlData["companyName"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def companyPower(casedata): - data = urlData["companyPower"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def deviceState(casedata): - data = urlData["deviceState"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def companyAlarm(casedata): - data = urlData["companyAlarm"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def todayTrend(casedata): - data = urlData["todayTrend"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmStatistic(casedata): - data = urlData["alarmStatistic"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmTrend(casedata): - data = urlData["alarmTrend"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmRank(casedata): - data = urlData["alarmRank"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmDistribute(casedata): - data = urlData["alarmDistribute"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - diff --git a/test_suite/page/saasApp_pages_1.py b/test_suite/page/saasApp_pages_1.py deleted file mode 100644 index 840c2194ca629038ac831cc6a31455616ff54151..0000000000000000000000000000000000000000 --- a/test_suite/page/saasApp_pages_1.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding:utf-8 -from test_suite.page import * - -urlData = ini_yaml("urlData.yml") - - -def login(casedata): - data = urlData["login"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def forgetPassword(casedata): - data = urlData["forgetPassword"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def mobileCode(casedata): - data = urlData["mobileCode"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def todayTask(casedata): - data = urlData["todayTask"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def companyName(casedata): - data = urlData["companyName"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def companyPower(casedata): - data = urlData["companyPower"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def deviceState(casedata): - data = urlData["deviceState"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def companyAlarm(casedata): - data = urlData["companyAlarm"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def todayTrend(casedata): - data = urlData["todayTrend"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmStatistic(casedata): - data = urlData["alarmStatistic"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmTrend(casedata): - data = urlData["alarmTrend"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmRank(casedata): - data = urlData["alarmRank"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - - -def alarmDistribute(casedata): - data = urlData["alarmDistribute"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime - diff --git a/test_suite/page/temple.py b/test_suite/page/temple.py deleted file mode 100644 index c749cd14224d6315d08ee0a2cde05f27ce4a9f0d..0000000000000000000000000000000000000000 --- a/test_suite/page/temple.py +++ /dev/null @@ -1,7 +0,0 @@ -# coding:utf-8 -""" -@author: 井松 -@contact: 529548204@qq.com -@file: temple.py -@time: 2021/9/14 16:44 -""" diff --git a/test_suite/page/third_pages.py b/test_suite/page/third_pages.py deleted file mode 100644 index 25b145d45b1b86fee25b01940d4bef718b996f73..0000000000000000000000000000000000000000 --- a/test_suite/page/third_pages.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding:utf-8 -""" -@author: 井松 -@contact: 529548204@qq.com -@file: third_pages.py -@time: 2021/9/17 13:48 -""" -from test_suite.page import * -urlData = ini_yaml("thirdUrl.yml") - - -def webalarm(casedata): - data = urlData["webalarm"] - logging.info("{}".format(casedata["info"])) - res, restime = apisend(address=data["address"], method=data["method"], headers=casedata["headers"], - data=casedata["data"]) - return res, restime \ No newline at end of file diff --git a/test_suite/page/__init__.py b/test_suite/testcase/fengling/__init__.py similarity index 68% rename from test_suite/page/__init__.py rename to test_suite/testcase/fengling/__init__.py index 72afa49f76be476e0fdc6961a123ffc222e3cb9f..910bcd204eb7b1dc60bca972d7fdf591fb19a547 100644 --- a/test_suite/page/__init__.py +++ b/test_suite/testcase/fengling/__init__.py @@ -1,14 +1,15 @@ # coding:utf-8 + import logging import allure import pytest -from common.checkResult import asserting,assert_json +from common.checkResult import asserting from scripts.log import Log from scripts.readYamlFile import ini_yaml from common.basePage import apisend -from test_suite.page import saasApp_pages + Log() __all__ = [ @@ -19,6 +20,4 @@ __all__ = [ 'logging', 'allure', 'apisend', - 'saasApp_pages', - 'assert_json' ] \ No newline at end of file diff --git a/test_suite/testcase/fengling/conftest.py b/test_suite/testcase/fengling/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..ec838acaf666a1eb4be990f258e770a9edab23e7 --- /dev/null +++ b/test_suite/testcase/fengling/conftest.py @@ -0,0 +1,2 @@ +# coding:utf-8 +from test_suite.testcase.fengling import * \ No newline at end of file diff --git a/test_suite/testcase/saasApp/conftest.py b/test_suite/testcase/saasApp/conftest.py index 7fb5d2458530e1d3177431d5746f7216fa1a0732..a62b901ca976a3d7d9f71990138219bc2cc41c47 100644 --- a/test_suite/testcase/saasApp/conftest.py +++ b/test_suite/testcase/saasApp/conftest.py @@ -1,6 +1,5 @@ # coding:utf-8 - -from test_suite.page.saasApp_pages import * +from test_suite.page.saasApp.saasApp_pages import * paramData = ini_yaml("loginData.yml")["login"][0] thirdParamData = ini_yaml("loginData.yml")["login"][0] @@ -12,7 +11,7 @@ def setup_login(): data = urlData["login"] logging.info("{}".format(paramData["info"])) res, restime = apisend(address=data["address"], method=data["method"], headers=paramData["headers"], - data=paramData["data"]) + data=paramData["data"],rel=data["relevance"]) logging.info("前置请求结束") return res @@ -20,10 +19,11 @@ def setup_login(): thirdURL = ini_yaml("thirdUrl.yml") + @pytest.fixture(scope="module") def third_login(): data = thirdURL["weblogin"] logging.info("{}".format(paramData["info"])) res, restime = apisend(address=data["address"], method=data["method"], headers=paramData["headers"], - data=paramData["data"]) - return res \ No newline at end of file + data=paramData["data"],rel=data["relevance"]) + return res diff --git a/test_suite/testcase/saasApp/test_alarm.py b/test_suite/testcase/saasApp/test_alarm.py index 777c315e19c7217fa2b853d6b5e9fb06355a548d..77e645c8f2b09d3a2a5b172f2cc849cb0a4df2c3 100644 --- a/test_suite/testcase/saasApp/test_alarm.py +++ b/test_suite/testcase/saasApp/test_alarm.py @@ -6,9 +6,8 @@ @time: 2021/9/14 16:40 """ from test_suite.page.saasApp_pages import * -from test_suite.page.third_pages import * paramData = ini_yaml("alarmData.yml") -thirdData = ini_yaml("thirdData.yml") + class Test_alarm(object): # def setup(self): @@ -36,13 +35,10 @@ class Test_alarm(object): @pytest.mark.parametrize('casedata', paramData["alarmRank"], ids=[i["info"] for i in paramData["alarmRank"]]) @pytest.mark.flaky(reruns=1, reruns_delay=1) @pytest.mark.run(order=1) - def test_alarmRank(self,third_login ,setup_login, casedata): + def test_alarmRank(self ,setup_login, casedata): casedata["headers"]["Authorization"] = "JWT " + setup_login["data"]["token"] - webdata = thirdData["webalarm"][0] - webdata["headers"]["Authorization"] = "JWT " + third_login["data"]["token"] - webres=webalarm(webdata)[0] res, restime = alarmRank(casedata) - asserting(hope_res=casedata["assert"], real_res=res, re_time=restime,third_data=webres) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) @allure.story("Test_alarmDistribute") @pytest.mark.parametrize('casedata', paramData["alarmDistribute"], ids=[i["info"] for i in paramData["alarmDistribute"]]) @@ -51,4 +47,7 @@ class Test_alarm(object): def test_alarmDistribute(self, setup_login, casedata): casedata["headers"]["Authorization"] = "JWT " + setup_login["data"]["token"] res, restime = alarmDistribute(casedata) - asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) \ No newline at end of file + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) + +if __name__ == '__main__': + print(111) \ No newline at end of file diff --git a/test_suite/testcase/saasApp/test_function.py b/test_suite/testcase/saasApp/test_function.py new file mode 100644 index 0000000000000000000000000000000000000000..6b608b9d3f17d31c628cefd546a7bf68de944205 --- /dev/null +++ b/test_suite/testcase/saasApp/test_function.py @@ -0,0 +1,21 @@ +# coding:utf-8 +""" +@author: 井松 +@contact: 529548204@qq.com +@file: test_function.py +@time: 2021/10/8 15:02 +""" +from test_suite.page.saasApp.saasApp_pages import * +# from test_suite.page.third_pages import * +paramData = ini_yaml("functionData.yml") +# thirdData = ini_yaml("thirdData.yml") + +class Test_function(object): + @allure.story("Test_functionList") + @pytest.mark.parametrize('casedata', paramData["functionList"], ids=[i["info"] for i in paramData["functionList"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=1) + def test_functionList(self, setup_login, casedata): + casedata["headers"]["Authorization"] = "JWT " + setup_login["data"]["token"] + res, restime = functionList(casedata) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) \ No newline at end of file diff --git a/test_suite/testcase/saasApp/test_homePage.py b/test_suite/testcase/saasApp/test_homePage.py index c62a5b7beeb997ff80694d286942b6a87ef20d2b..17a399b21d8ee403f5ea031763dc8658fd858455 100644 --- a/test_suite/testcase/saasApp/test_homePage.py +++ b/test_suite/testcase/saasApp/test_homePage.py @@ -1,5 +1,5 @@ # coding:utf-8 -from test_suite.page.saasApp_pages import * +from test_suite.page.saasApp.saasApp_pages import * paramData = ini_yaml("homePageData.yml") diff --git a/test_suite/testcase/saasApp/test_login.py b/test_suite/testcase/saasApp/test_login.py index 20252a514082f7654702f2a2cf961cd0c626fb1d..dc09f949b6087550da4f82cd55f928bd155845a7 100644 --- a/test_suite/testcase/saasApp/test_login.py +++ b/test_suite/testcase/saasApp/test_login.py @@ -1,5 +1,7 @@ # coding:utf-8 -from test_suite.page.saasApp_pages import * +import pytest + +from test_suite.page.saasApp.saasApp_pages import * paramData = ini_yaml("loginData.yml") @@ -25,12 +27,14 @@ class Test_login(object): asserting(hope_res=casedata["assert"], real_res=res,re_time=restime) # cache.set("session_id", res["session_id"]) + @allure.story("Test_forgetPassword") @pytest.mark.parametrize('casedata', paramData["forgetPassword"], ids=[i["info"] for i in paramData["forgetPassword"]]) @pytest.mark.flaky(reruns=1, reruns_delay=1) @pytest.mark.run(order=1) - def test_forgetPassword(self, casedata): + @pytest.mark.skip("验证码异常") + def test_forgetPassword(self, casedata,cache): res, restime = mobileCode(paramData["mobileCode"][1]) - casedata['data']['session_key'] = res["data"]['session_id'] + casedata['data']["param"]['session_key'] = cache.get('k',None) res, restime = forgetPassword(casedata) asserting(hope_res=casedata["assert"], real_res=res,re_time=restime) diff --git a/test_suite/testcase/saasApp/test_power.py b/test_suite/testcase/saasApp/test_power.py index 4a4636df89863ed7e2c4eddf72b99118d3e107ad..8bbffe7050c888fbe586b83060e452f0ba7a032b 100644 --- a/test_suite/testcase/saasApp/test_power.py +++ b/test_suite/testcase/saasApp/test_power.py @@ -5,3 +5,40 @@ @file: test_power.py @time: 2021/9/17 16:56 """ +from test_suite.page.saasApp.saasApp_pages import * +from test_suite.page.saasApp.third_pages import * + +paramData = ini_yaml("powerData.yml") +thirdData = ini_yaml("thirdData.yml") + + +class Test_power(object): + # def setup(self): + # self.re = saasPages() + # ids=[i["info"] for i in paramData["login"]] + @allure.story("Test_powerToday") + @pytest.mark.parametrize('casedata', paramData["powerToday"], ids=[i["info"] for i in paramData["powerToday"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=1) + def test_powerToday(self, setup_login, casedata): + casedata["headers"]["Authorization"] = "JWT " + setup_login["data"]["token"] + res, restime = powerToday(casedata) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) + + @allure.story("Test_powerFees") + @pytest.mark.parametrize('casedata', paramData["powerFees"], ids=[i["info"] for i in paramData["powerFees"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=1) + def test_powerFees(self, third_login, setup_login, casedata): + + casedata["headers"]["Authorization"] = "JWT " + setup_login["data"]["token"] + + thirdData["webFees"][0]["headers"]["Authorization"] = "JWT " + third_login["data"]["token"] + thirdData["webPower"][0]["headers"]["Authorization"] = "JWT " + third_login["data"]["token"] + webFeesRes = webFees(thirdData["webFees"][0])[0] + webPowerRes = webPower(thirdData["webPower"][0])[0] + third_datas = {**webFeesRes,**webPowerRes} + # 电费断言 + res, restime = powerFees(casedata) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime,third_datas=third_datas) + diff --git a/test_suite/testcase/saasApp/test_region.py b/test_suite/testcase/saasApp/test_region.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd387c7a05ebb9c939bc0c18b25dea56e1eb19d --- /dev/null +++ b/test_suite/testcase/saasApp/test_region.py @@ -0,0 +1,21 @@ +# coding:utf-8 +""" +@author: 井松 +@contact: 529548204@qq.com +@file: test_region.py +@time: 2021/10/8 16:11 +""" +from test_suite.page.saasApp.saasApp_pages import * +# from test_suite.page.third_pages import * +paramData = ini_yaml("regionData.yml") +# thirdData = ini_yaml("thirdData.yml") + +class Test_function(object): + @allure.story("Test_functionList") + @pytest.mark.parametrize('casedata', paramData["functionList"], ids=[i["info"] for i in paramData["functionList"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=1) + def test_functionList(self, setup_login, casedata): + casedata["headers"]["Authorization"] = "JWT " + setup_login["data"]["token"] + res, restime = functionList(casedata) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) \ No newline at end of file diff --git a/test_suite/testcase/saasWeb/__init__.py b/test_suite/testcase/saasWeb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..910bcd204eb7b1dc60bca972d7fdf591fb19a547 --- /dev/null +++ b/test_suite/testcase/saasWeb/__init__.py @@ -0,0 +1,23 @@ +# coding:utf-8 + +import logging + +import allure +import pytest + +from common.checkResult import asserting +from scripts.log import Log +from scripts.readYamlFile import ini_yaml +from common.basePage import apisend + + +Log() +__all__ = [ + 'pytest', + 'asserting', + 'Log', + 'ini_yaml', + 'logging', + 'allure', + 'apisend', +] \ No newline at end of file diff --git a/test_suite/testcase/saasWeb/conftest.py b/test_suite/testcase/saasWeb/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..85c1bf96eb9dd8c1c7409177a6a8258f06f71405 --- /dev/null +++ b/test_suite/testcase/saasWeb/conftest.py @@ -0,0 +1,21 @@ +# coding:utf-8 +""" +@author: 井松 +@contact: 529548204@qq.com +@file: conftest.py +@time: 2021/12/3 14:25 +""" +from test_suite.testcase.saasWeb import * + +paramData = ini_yaml("login.yml")["login"]["case"][0] + + +@pytest.fixture(scope="module") +def setup_Login(): + logging.info("前置请求登录") + logging.info("{}".format(paramData["info"])) + res, restime = apisend(host=paramData["host"],address=paramData["address"], method=paramData["method"], headers=paramData["headers"], + data=paramData["data"],rel=paramData["relevance"]) + + logging.info("前置请求结束") + return "JWT " + res["data"]["token"] diff --git a/test_suite/testcase/saasWeb/test_firmware.py b/test_suite/testcase/saasWeb/test_firmware.py new file mode 100644 index 0000000000000000000000000000000000000000..644cd71472f46e8639e10d986a909eb4d4a4e3d2 --- /dev/null +++ b/test_suite/testcase/saasWeb/test_firmware.py @@ -0,0 +1,52 @@ +from test_suite.testcase.saasWeb import * + +paramData = ini_yaml("firmware.yml") + +class Test_firmware(object): + @allure.story("Test_firmware") + @pytest.mark.parametrize('casedata', paramData["firmwareList"]["case"], + ids=[i["info"] for i in paramData["firmwareList"]["case"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=1) + def test_firmwareList(self, casedata, setup_Login): + casedata["headers"]["Authorization"] = setup_Login + res, restime = apisend(host=casedata["host"], address=casedata["address"], method=casedata["method"], + headers=casedata["headers"], + data=casedata["data"], rel=casedata["relevance"]) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) + + @allure.story("Test_firmware") + @pytest.mark.parametrize('casedata', paramData["firmwareAdd"]["case"], + ids=[i["info"] for i in paramData["firmwareAdd"]["case"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=1) + def test_firmwareAdd(self, casedata, setup_Login): + casedata["headers"]["Authorization"] = setup_Login + res, restime = apisend(host=casedata["host"], address=casedata["address"], method=casedata["method"], + headers=casedata["headers"], + data=casedata["data"], rel=casedata["relevance"]) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) + + @allure.story("Test_firmware") + @pytest.mark.parametrize('casedata', paramData["firmwareDetail"]["case"], + ids=[i["info"] for i in paramData["firmwareDetail"]["case"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=2) + def test_firmwareDetail(self, casedata, setup_Login): + casedata["headers"]["Authorization"] = setup_Login + res, restime = apisend(host=casedata["host"], address=casedata["address"], method=casedata["method"], + headers=casedata["headers"], + data=casedata["data"], rel=casedata["relevance"]) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) + + @allure.story("Test_firmware") + @pytest.mark.parametrize('casedata', paramData["firmwareDel"]["case"], + ids=[i["info"] for i in paramData["firmwareDel"]["case"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=3) + def test_firmwareDel(self, casedata, setup_Login): + casedata["headers"]["Authorization"] = setup_Login + res, restime = apisend(host=casedata["host"], address=casedata["address"], method=casedata["method"], + headers=casedata["headers"], + data=casedata["data"], rel=casedata["relevance"]) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime) diff --git a/test_suite/testcase/saasWeb/test_login.py b/test_suite/testcase/saasWeb/test_login.py new file mode 100644 index 0000000000000000000000000000000000000000..303bbcb34f001674e863a487589c5afe3a51a0b1 --- /dev/null +++ b/test_suite/testcase/saasWeb/test_login.py @@ -0,0 +1,15 @@ +from test_suite.testcase.saasWeb import * + +paramData = ini_yaml("login.yml") + +class Test_login(object): + @allure.story("Test_login") + @pytest.mark.parametrize('casedata', paramData["login"]["case"], + ids=[i["info"] for i in paramData["login"]["case"]]) + @pytest.mark.flaky(reruns=1, reruns_delay=1) + @pytest.mark.run(order=1) + def test_login(self, casedata): + res, restime = apisend(host=casedata["host"], address=casedata["address"], method=casedata["method"], + headers=casedata["headers"], + data=casedata["data"], rel=casedata["relevance"]) + asserting(hope_res=casedata["assert"], real_res=res, re_time=restime)