核心技术堆栈:pytest、requests、用例/api/数据分层
pytest、requests框架使用demo(一)
pytest
- pip install requests
- pytest的基本使用参考我前面的笔记
项目级配置config.py
api
config.py
config.py
import socket
import os
DIR_PATH = os.path.dirname(__file__)
USE_HOST = 'TEST'
# USE_HOST = 'PRODUCT'
CPA_WEB_TEST = 'http://omcr****.com'
CPA_TEST = 'http://omcr****2.com
CPA_PRODUCT = 'https://************'
RM_TEST = 'http://omcr-x-'
COMMON_SERVICE_TEST = 'http://ompm-x'
local_ip = socket.gethostbyname(socket.gethostnaame())
LOCALIP4 = f'http://{local_ip}:8081'
LOCALHOST = 'http://localhost:8080'
接口的相关api
api
base_http.py
base_http.py
import os
from src.common.utils import plan_log
from config import USE_HOST, DIR_PATH
from config import CPA_WEB_TEST
from config import CPA_TEST
from config import RM_TEST
from config import COMMON_SERVICE_TEST
from config import LOCALHOST
from config import LOCALIP4
from src.common.utils.get_data import GetData, IniFileReader
from src.testsuit.conftest import plan_data
class BaseHttp:
file_path = DIR_PATH + os.sep + 'src'+ os.sep + 'config' + os.sep + 'config.ini'
ini_reader = IniFileReader(file_path)
def request_http(self, req, desc=None, file=None):
sub_data = None
cookie_name = 'create_cookie' # create_cookie,verify_cookie
if USE_HOST == 'TEST': #使用测试环境的CPAhost
if 'cpa_web_host' in req['url']:
sub_data={
'cpa_web_host': CPA_WEB_TEST
}
if 'headers'in req.keys(): # 如果接口有请求头
if 'Cookie' in req['headers'].keys(): # 如果需要cookie
if req['headers']['Cookie'] == '$create_cookie': # 如果是普通规划创建者
if 'create_cookie' in plan_data.keys(): # 如果本次回归已经得到了cookie
req['headers']['Cookie'] = plan_data['create_cookie']
else: # 如果现在还没有create_cookie,使用配置的cookie
cookie = self.ini_reader.get_section_value('cpa_info','create_cookie')
req['headers']['Cookie'] = cookie
elif req['headers']['Cookie'] == '$verify_cookie': # 如果是普通规划审核者
cookie_name = 'verify_cookie'
if 'verify_cookie' in plan_data.keys(): # 如果本次回归已经得到了verify_cookie
req['headers']['Cookie'] = plan_data['verify_cookie']
else: # 如果现在还没有verify_cookie#使用配置的copokie
cookie = self.ini_reader.get_section_value('cpa_info','verify_cookie')
req['headers']['Cookie'] = cookie
elif 'rm_host' in req['url']: # 使用测试环境的rmhpst
sub_data={'rm_host': RM_TEST}
elif USE_HOST == 'PRODUCT': # 使用生产环境的host
pass
plan_log.info(f"正在调用接口>>>>>>>-{desc}-请求数据:\n\t{req}") #json.dumps(req)
if file is not None:
response = requests.post(req['url'], headers=req['headers'], files=file)
else:
response = requests.request(**req)
plan_log.info(f'{desc}<<<<<<<<<,响应状态码:{response.status_code}\n\t响应json:{response.text}') #json.loads(response.text)
if USE_HOST == "TEST':#使用测试环境的CPAhost
if 'cpa_web_host'in req['url']:
self.set_http_cookie(response, cookie_name)
return response
def set_http_cookie(self, response, cookie_name):
if 'Set-Cookie' in response.headers.keys(): # 如果果响应头中有cookie
cookie = response.headers.get('Set-Cookie').split(';')[0]
plan_data[cookie_name] = cookie
plan_log.info(f"响应头有返回cookie,plan_data已设置新{cookie_name}:{cookie}")
# 配置文件设置新的create_cookie
self.ini_reader.write_section('cpa_info',{cookie_name: cookie})
plan_log.info(f"已更新配置的{cookie_name}:{cookie}")
测试数据分离
http
cpa_login.yaml
common_service_login.yaml
cpa_login.yaml 请求的接口的链接、参数、方式
- request:
method:post
url: $cpa_web_host/******-service/login
headers:
Cookie: $create_cookie
json:
username: $username
password: $password
desc:'**平台登录'
common_service_login.yaml
request:
desc:'平台登录'
method: post
url: $common_service_host/v1/auth/api/session
json:
macAddress: 'c163f8e9-7fc4-4a39-822e-4c63302c31023'
password: '1
uid: 'liheng06704'
role_user:
creator:
name:'制定者'
roleid: 'cb172512-6017-41b7-bbf0-615Sa383630cd'
user:
-
username:'zhangsan'
password:'1'
token: '64e818e3-3833-41ea-a3e0-69331a6fif70b'
- username:'wangwu'
password:'1'
token:'64e818e3-3833-41ea-a3e0-69331a6ff70c'
reviewer:
name: "审核者"
roleid: '91458d98-7b2a-421e-889f-8616a6002edc'
user:
- username:'lisi'
password:'1'
token: '725aef9f-ce47-4317-9c54-4a1a9fd4efed'
test_cases
test0_plan_base.py
test0_plan_base.py 测试类
from src.testsuit.API.plan_base_data import PlaanBaseData
from src.common.utils import plan_log
from src.common.utils.get_data import GetData
from src.testsuit.conftest import plan_data
from src.config.test_data.http import http_path
from src.config.test_data.regression import reggression_path
from config import DIR_PATH
from datetime import datetime
import pytest
import time
import os
def setup_module():
plan_log.info('-----test0 setup_module------')
regression = pytest.mark.skipif(plan_data['all_regression'] is False, reason='不进行大回归测试,跳过')
class TestPlanBase:
def setup_class(self):
plan_log.info('-----TestPlanBase------')
self.plan_base_data = PlanBaseData()
@regression
@pytest.mark.parametrize('cpa_login', GetData.read_yaml(http_path + 'cpa_login.yaml'))
def test_cpa_login(self, cpa_login, get_plan_dlata, set_plan_data): # 登录
user = GetData.read_yaml(http_path + 'common_service_login.yaml')['request']['role_user']['creator'][0]
req = cpa_login['request']
req['json']['username'] = username'
req['json']['password'] = user['password']
self.plan_base_data.cpa_login(req, cpa_login['desc1)
plan_log.info(f"{user['username']}登录成功!")
api
cpa_login.yaml
plan_base_data.py 测试类调用的api
import uuid
from config import DIR_PATH
from src.common.utils.db_util import PgDbUtil
from src.common.utils import plan_log
from src.common.utils.get_data import GetData, IniFilReader
from src.testsuit.API.base_http import BaseHttEp
from src.testsuit.conftest import plan_data
class PlanBaseData(BaseHttp):
get_data = GetData()
def get_plan_id(self, plan_code):
title = f'根据plan_code{plan_code}查询plan_id'
sql = f"SELECT plan_id FROM {PgDbutil.cpa}.t_cpa WHERE plan_code = '{plan_code}'"
result = PgDbUtil.query_db(sql, title)
return result
def cpa_login(self, req_data, desc):
response = self.request_http(req_data, desc)
return response
def upload_file(self, req_data, desc, file_path):
file = {'fileUploaded': open(file_path, "rb")}
response = self.request_http(req_data, desc, file)
res_json_data = response.json()['data']
if response.status_code == 200 and res_json_datta is not None:
plan_log.info(f"{file_path}文件已上传!")
return response
else:
plan_log.error(f"{file_path}文件上传失败!")
即使今天做错了很多事情,那也没有什么大不了,人生的容错率高到离谱!