Commit 3edad9b6 authored by 邓莹莹's avatar 邓莹莹

backend调用层接口自动化初次提交

parents
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
\ No newline at end of file
# Default ignored files
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.7 (backendauto)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PackageRequirementsSettings">
<option name="requirementsPath" value="" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="pytest" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (backendauto)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/backend_auto.iml" filepath="$PROJECT_DIR$/.idea/backend_auto.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
import path_setting
from in_common.base_request import BaseRequest
class send_reqest(BaseRequest):
def __init__(self):
self.data = self.api_load(path_setting.APYAML_CONFIG)
def login_vfc(self,current_city_id,phone_num,vfc_code,vfc_type="",face_token=""):
self.params["current_city_id"] = current_city_id
self.params["phone_num"] = phone_num
self.params["vfc_code"] = vfc_code
self.params["vfc_type"] = vfc_type
self.params["face_token"] = face_token
return self.api_send(self.data["login_vfc"])
if __name__ == '__main__':
print(send_reqest().login_vfc("beijing", "+8612345678912", 1234, "", ""))
\ No newline at end of file
login_vfc:
method: post
url: /api/account/login/login_vfc
params:
current_city_id: ${current_city_id}
data:
phone_num: ${phone_num}
vfc_code: ${vfc_code}
vfc_type: ${vfc_type}
face_token: ${face_token}
json: {}
'''
钩子函数,解决ids乱码问题
'''
def pytest_collection_modifyitems(items):
for item in items:
item.name = item.name.encode("utf-8").decode("unicode_escape")
item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
develop_host:
url: http://backend.paas-develop.env
'''
此文件是用来将case转换成list
'''
def get_ids(data, path):
params = data[path]
case = []
for ids in params:
case.append(ids["case"])
# print('-@@@@@@@@@@@@',case,params)
return case, params
import json
import random
import string
import requests
import yaml
from jsonpath import jsonpath
# from pymysql import OperationalError
import path_setting
class BaseRequest:
params = {}
data = {}
@classmethod
def format(cls, r):
cls.r = r
print(json.dumps(json.loads(r.text), indent=2, ensure_ascii=False))
# 封装yaml文件读取
@classmethod
def yaml_load(cls, path) -> list:
with open(path, encoding='utf-8') as f:
return yaml.safe_load(f)
# 调用yaml加载文件API加载
def api_load(self, path):
return self.yaml_load(path)
def jsonpath(self, path, r=None, **kwargs):
if r is None:
r = self.r.json()
return jsonpath(r, path)
def get_cookie(self, req: dict):
host = self.api_load(path_setting.HOSTYAML_CONFIG)
print(host)
r = requests.request(
req['method'],
url=host['develop_host']['url'] + req['url'],
params=req['params'],
headers=req['headers'],
data=req['data'],
json=req['json']
)
dict = {}
for i in r.cookies:
dict[i.name] = i.value
headers = '_gtid={};sessionid={}'.format(dict["_gtid"], dict["sessionid"])
# item = r.cookies.values()
# print("ppppppp",item)
# if len(item) == 1:
# headers = '_gtid={}'.format(item[0])
# print("cookie异常")
#
# else:
# headers = '_gtid={};sessionid={}'.format(item[0], item[1])
#
return headers
def read_header(self):
with open("../in_common/get_cookie.txt", 'r', encoding='utf-8') as f:
cookies = f.read()
headers = {"cookie": cookies}
return headers
# 接口请求的封装
def api_send(self, req: dict):
host = self.api_load(path_setting.HOSTYAML_CONFIG)
raw = yaml.dump(req) # 将一个python对象生成为yaml文档
for key, value in self.params.items():
raw = raw.replace(f"${{{key}}}", repr(value))
req = yaml.safe_load(raw)
# print('------', req.get('headers'))
# hd = req.get('headers')
# if hd == None:
# user_headers = self.read_header()
# elif hd["Cookie"]:
# user_headers = req.get('headers')
# else:
# user_headers = self.read_header()
r = requests.request(
req['method'],
url=host['develop_host']['url'] + req['url'],
params=req.get('params'),
# headers=user_headers,
data=req.get('data'),
json=req.get('json')
)
return r.json()
# 随机生成trace_id
def trace_id(self):
return ''.join(random.sample(string.ascii_lowercase + string.digits, 32))
if __name__ == '__main__':
BaseRequest().api_load("../api/api.yaml")
# print(BaseApi().trace_id())
BaseRequest().read_header()
import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_DIR)
HOSTYAML_CONFIG = os.path.join(BASE_DIR, "backend_auto", "host.yaml")
APYAML_CONFIG = os.path.join(BASE_DIR, "backend_auto/all_backend_api", "account_request.yaml")
LOGIN_VFC = os.path.join(BASE_DIR, "backend_auto/test_backend_data/account_data", "login_vfc.yaml")
if __name__ == '__main__':
print(HOSTYAML_CONFIG)
\ No newline at end of file
all_backend_api里面的文件命名规则是根据backend里面api节点下的各个节点命名,这样更容易区分定位
test_backend_data里面的文件夹也是根据api节点下的各个节点命名,这样更容易区分定位
test_backend_request里面的文件夹也是根据api节点下的各个节点命名,这样更容易区分定位
\ No newline at end of file
from test_backend_request.account_request import test_login_vfc
import pytest
pytest.main()
\ No newline at end of file
login_vfc:
#成功登录case
-
case: "成功登录case--验证码正常登录case"
current_city_id: "beijing"
phone_num: "+8612345678912"
vfc_code: 1234
assert: "12345678912"
#登录失败case
-
case: "登录失败case--手机号错误"
current_city_id: "beijing"
phone_num: "+8612345678913"
vfc_code: 1234
assert: "验证码错误"
-
case: "登录失败case--验证码错误"
current_city_id: "beijing"
phone_num: "+8612345678912"
vfc_code: 12345
assert: "验证码错误"
-
case: "登录失败case--手机号格式非数字"
current_city_id: "beijing"
phone_num: "+86123456789qq"
vfc_code: 12345
assert: "手机号无效, 请检查输入"
\ No newline at end of file
import pytest
from ids_list import get_ids
import path_setting
from in_common.base_request import BaseRequest
from all_backend_api.account_request import send_reqest
class TestLoginVfc:
data = BaseRequest().api_load(path_setting.LOGIN_VFC)
loginvfc_case, loginvfc_data = get_ids(data, "login_vfc")
@pytest.mark.parametrize("param",loginvfc_data,ids=loginvfc_case)
def test_login_vfc(self,param):
print(param["vfc_code"])
r = send_reqest().login_vfc(param["current_city_id"], param["phone_num"], param["vfc_code"])
if r["error"] == 0:
assert r["data"]["account_phone"] == param["assert"]
if r["error"] == 1:
assert r["message"] == param["assert"]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment