feat: MES 接口自动化测试框架(unittest + HTMLTestRunner + 数据驱动)
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,88 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""登录态管理:JSESSIONID + 业务 token 的获取、持久化与读取。
|
||||
|
||||
设计要点:
|
||||
1. 会话只落 artifacts/session.json,该目录已 gitignore —— 凭据不进版本库;
|
||||
2. 路径统一走 core.path,不出现硬编码的用户目录,跨平台可跑;
|
||||
3. 账号密码一律走环境变量 MES_USER / MES_PASS,缺省为合成 demo 账号。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
|
||||
from core import config
|
||||
from core.path import artifact_path
|
||||
|
||||
_SESSION_FILE = artifact_path('session.json')
|
||||
|
||||
# 进程内缓存,避免每次请求都读盘
|
||||
_cache = {}
|
||||
|
||||
|
||||
def login(user=None, pwd=None):
|
||||
"""调 /mes/login 换取 JSESSIONID,再取 token,落盘到 artifacts/。"""
|
||||
user = user or config.username()
|
||||
pwd = pwd or config.password()
|
||||
url = config.base_url() + '/mes/login'
|
||||
resp = requests.post(url, data={'username': user, 'password': pwd, 'encrypt': 0},
|
||||
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
|
||||
body = resp.json()
|
||||
if body.get('code') != 200:
|
||||
raise RuntimeError('登录失败: {0}'.format(body))
|
||||
|
||||
session = {
|
||||
'cookie': resp.cookies.get('JSESSIONID', ''),
|
||||
'username': user,
|
||||
'mes_id': None,
|
||||
'token': None,
|
||||
}
|
||||
|
||||
# 换取业务 token
|
||||
cookie_header = 'JSESSIONID=' + session['cookie']
|
||||
token_resp = requests.get(config.base_url() + '/mes/login/token',
|
||||
headers={'Cookie': cookie_header})
|
||||
if token_resp.text:
|
||||
session['token'] = token_resp.json().get('token')
|
||||
|
||||
user_resp = requests.get(config.base_url() + '/mes/login/user',
|
||||
headers={'Cookie': cookie_header})
|
||||
if user_resp.text:
|
||||
session['mes_id'] = user_resp.json().get('data', {}).get('mesId')
|
||||
|
||||
with open(_SESSION_FILE, 'w', encoding='utf-8') as f:
|
||||
f.write(json.dumps(session, ensure_ascii=False))
|
||||
_cache.update(session)
|
||||
return session
|
||||
|
||||
|
||||
def _load():
|
||||
if not _cache:
|
||||
if os.path.exists(_SESSION_FILE):
|
||||
with open(_SESSION_FILE, encoding='utf-8') as f:
|
||||
_cache.update(json.load(f))
|
||||
else:
|
||||
login()
|
||||
return _cache
|
||||
|
||||
|
||||
def get_cookie():
|
||||
return _load().get('cookie', '')
|
||||
|
||||
|
||||
def get_token():
|
||||
return _load().get('token')
|
||||
|
||||
|
||||
def get_mes_id():
|
||||
return _load().get('mes_id')
|
||||
|
||||
|
||||
def get_username():
|
||||
return _load().get('username')
|
||||
|
||||
|
||||
def new_session_id():
|
||||
"""给 mock / 单测用的合成会话 id。"""
|
||||
return uuid.uuid4().hex
|
||||
@@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""多环境配置:local / ci / test 三套,节名对应 config/config.ini 的 section。
|
||||
|
||||
优先级:环境变量 > config/config.ini > 内置默认值(local)。
|
||||
内置默认值一律指向 127.0.0.1;仓库只带 config.example.ini 模板,
|
||||
真实地址与口令由本地 config.ini(已 gitignore)或环境变量注入。
|
||||
"""
|
||||
import os
|
||||
from configparser import ConfigParser
|
||||
|
||||
from core.path import get_path
|
||||
|
||||
_ENV = os.environ.get('MES_ENV', 'local')
|
||||
|
||||
|
||||
def _cfg():
|
||||
cfg = ConfigParser()
|
||||
ini = get_path('config', 'config.ini')
|
||||
if os.path.exists(ini):
|
||||
cfg.read(ini, encoding='utf-8')
|
||||
return cfg
|
||||
|
||||
|
||||
def base_url():
|
||||
"""当前环境的 MES 服务地址,默认本地 mock。"""
|
||||
if os.environ.get('MES_BASE_URL'):
|
||||
return os.environ['MES_BASE_URL']
|
||||
cfg = _cfg()
|
||||
if cfg.has_section(_ENV) and cfg.has_option(_ENV, 'base_url'):
|
||||
return cfg.get(_ENV, 'base_url')
|
||||
return 'http://127.0.0.1:8080'
|
||||
|
||||
|
||||
def username():
|
||||
return os.environ.get('MES_USER', 'demo_user')
|
||||
|
||||
|
||||
def password():
|
||||
return os.environ.get('MES_PASS', 'demo_pass')
|
||||
|
||||
|
||||
def env_name():
|
||||
return _ENV
|
||||
@@ -0,0 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""用例数据读取:fixtures/*.yml → namedtuple 行对象。
|
||||
|
||||
用例数据与代码分离,读取后按字段名访问,写错字段名立刻 AttributeError:
|
||||
rows = load('login') # fixtures/login.yml
|
||||
rows[0].username / rows[0].result
|
||||
"""
|
||||
from collections import namedtuple
|
||||
|
||||
import yaml
|
||||
|
||||
from core.path import get_path
|
||||
|
||||
|
||||
def load(name):
|
||||
"""读取 fixtures/<name>.yml,返回 namedtuple 行对象列表。"""
|
||||
path = get_path('fixtures', '{0}.yml'.format(name))
|
||||
with open(path, encoding='utf-8') as f:
|
||||
doc = yaml.safe_load(f)
|
||||
rows = doc.get('cases', doc) if isinstance(doc, dict) else doc
|
||||
if not rows:
|
||||
return []
|
||||
Row = namedtuple('Row', list(rows[0].keys()))
|
||||
return [Row(*[r.get(k) for k in Row._fields]) for r in rows]
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""测试报告邮件发送:HTML 正文 / 文件附件两种。
|
||||
|
||||
SMTP 凭据一律从环境变量读取,源码里不出现任何账号口令:
|
||||
MES_SMTP_HOST / MES_SMTP_USER / MES_SMTP_PASS / MES_MAIL_TO(逗号分隔)
|
||||
未配置时 send_* 直接返回 False,不报错——Demo 默认不发邮件。
|
||||
"""
|
||||
import os
|
||||
import smtplib
|
||||
from email.encoders import encode_base64
|
||||
from email.mime.base import MIMEBase
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
|
||||
class EmailSender:
|
||||
def __init__(self):
|
||||
self.host = os.environ.get('MES_SMTP_HOST', '')
|
||||
self.user = os.environ.get('MES_SMTP_USER', '')
|
||||
self.password = os.environ.get('MES_SMTP_PASS', '')
|
||||
self.to_address = [a for a in os.environ.get('MES_MAIL_TO', '').split(',') if a]
|
||||
|
||||
def _ready(self):
|
||||
return bool(self.host and self.user and self.password and self.to_address)
|
||||
|
||||
def send_email(self, report_path, title='自动化测试报告'):
|
||||
"""HTML 正文方式发送报告。"""
|
||||
if not self._ready():
|
||||
return False
|
||||
with open(report_path, 'r', encoding='utf-8') as f:
|
||||
message = MIMEText(f.read(), 'html', 'utf-8')
|
||||
message['From'] = self.user
|
||||
message['To'] = ','.join(self.to_address)
|
||||
message['Subject'] = title
|
||||
self._send(message)
|
||||
return True
|
||||
|
||||
def send_file(self, report_path, title='自动化测试报告'):
|
||||
"""附件方式发送报告。"""
|
||||
if not self._ready():
|
||||
return False
|
||||
message = MIMEMultipart()
|
||||
message['From'] = self.user
|
||||
message['To'] = ','.join(self.to_address)
|
||||
message['Subject'] = title
|
||||
with open(report_path, 'rb') as f:
|
||||
part = MIMEBase('application', 'octet-stream')
|
||||
part.set_payload(f.read())
|
||||
encode_base64(part)
|
||||
part.add_header('Content-Disposition',
|
||||
'attachment; filename="{0}"'.format(os.path.basename(report_path)))
|
||||
message.attach(part)
|
||||
self._send(message)
|
||||
return True
|
||||
|
||||
def _send(self, message):
|
||||
smtp = smtplib.SMTP()
|
||||
smtp.connect(host=self.host)
|
||||
smtp.login(self.user, self.password)
|
||||
smtp.sendmail(self.user, self.to_address, message.as_string())
|
||||
smtp.quit()
|
||||
@@ -0,0 +1,57 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""HTTP 请求封装:get / post_form / post_json / post_file / put / delete。
|
||||
|
||||
公共请求头(Accept / UA / Cookie)收敛在 _base_headers(),各方法只声明自己的
|
||||
差异(Content-Type)——否则改一处 UA 要改 6 遍。Cookie 统一从 core.auth 取,
|
||||
本模块不直接读文件。见 README「关键难点」。
|
||||
"""
|
||||
import requests
|
||||
|
||||
from core import auth
|
||||
|
||||
_UA = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
|
||||
|
||||
|
||||
class HttpClient:
|
||||
"""每个方法各自组装 headers,差异部分在方法内声明。"""
|
||||
|
||||
@staticmethod
|
||||
def _base_headers():
|
||||
return {
|
||||
'Accept': 'application/json, text/javascript, */*; q=0.01',
|
||||
'User-Agent': _UA,
|
||||
'Cookie': 'JSESSIONID=' + auth.get_cookie(),
|
||||
}
|
||||
|
||||
def get(self, url, data=None):
|
||||
headers = self._base_headers()
|
||||
headers['Content-Type'] = 'application/json; charset=UTF-8'
|
||||
return requests.get(url, params=data, headers=headers)
|
||||
|
||||
def post_form(self, url, data=None):
|
||||
headers = self._base_headers()
|
||||
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
|
||||
return requests.post(url, data=data, headers=headers)
|
||||
|
||||
def post_json(self, url, data=None):
|
||||
headers = self._base_headers()
|
||||
headers['Accept'] = 'application/json, text/javascript, */*'
|
||||
headers['Content-Type'] = 'application/json; charset=UTF-8'
|
||||
return requests.post(url, json=data, headers=headers)
|
||||
|
||||
def post_file(self, url, files=None):
|
||||
headers = self._base_headers()
|
||||
# multipart 的 Content-Type 由 requests 自动生成(带 boundary),不能手动指定
|
||||
headers.pop('Content-Type', None)
|
||||
return requests.post(url, files=files, headers=headers)
|
||||
|
||||
def put(self, url, data=None):
|
||||
headers = self._base_headers()
|
||||
headers['Content-Type'] = 'application/json; charset=UTF-8'
|
||||
return requests.put(url, json=data, headers=headers)
|
||||
|
||||
def delete(self, url, data=None):
|
||||
headers = self._base_headers()
|
||||
headers['Content-Type'] = 'application/json; charset=UTF-8'
|
||||
return requests.delete(url, params=data, headers=headers)
|
||||
@@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""日志装饰器 @setLog():记录用例方法拿到的接口返回。
|
||||
|
||||
两个要点:
|
||||
1. 装饰器模式,用例方法加一行即可记录返回,不侵入业务代码;
|
||||
2. 需要 json.dumps(...).encode().decode('unicode_escape') 中文转码,
|
||||
否则日志里的中文会写成 unicode 转义序列(形如反斜杠 u 加四位十六进制)。
|
||||
日志落 artifacts/logs/(已 gitignore)。
|
||||
"""
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from core.path import artifact_path
|
||||
|
||||
_LOG_FILE = artifact_path('logs', 'log_{0}.log'.format(datetime.now().strftime('%Y-%m-%d')))
|
||||
|
||||
logging.basicConfig(
|
||||
filename=_LOG_FILE,
|
||||
filemode='a',
|
||||
level=logging.DEBUG,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s',
|
||||
datefmt='%m/%d/%Y %H:%M:%S %p',
|
||||
)
|
||||
|
||||
|
||||
def setLog():
|
||||
"""装饰器:把被装饰函数的返回值以 info 级写入日志,异常写 error。"""
|
||||
def get_func(func):
|
||||
@functools.wraps(func)
|
||||
def get_args(*args, **kwargs):
|
||||
try:
|
||||
temp = func(*args, **kwargs)
|
||||
# 中文转码:否则日志里的中文会写成 \uXXXX
|
||||
msg = json.dumps(temp, ensure_ascii=True).encode('utf-8').decode('unicode_escape')
|
||||
logging.info(msg)
|
||||
return temp
|
||||
except Exception as e:
|
||||
logging.error(repr(e))
|
||||
raise
|
||||
return get_args
|
||||
return get_func
|
||||
@@ -0,0 +1,21 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""统一路径入口:所有文件路径都基于项目根目录计算。
|
||||
|
||||
路径不在别处硬编码,跨平台可跑;运行期产物统一落 artifacts/。
|
||||
"""
|
||||
import os
|
||||
|
||||
# 项目根目录(core/ 的上一级)
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def get_path(*parts):
|
||||
"""返回项目根目录下的拼接路径,如 get_path('fixtures', 'login.yml')。"""
|
||||
return os.path.join(ROOT, *parts)
|
||||
|
||||
|
||||
def artifact_path(*parts):
|
||||
"""返回 artifacts/ 下的路径(运行时产物目录,已 gitignore),不存在则创建。"""
|
||||
path = get_path('artifacts', *parts)
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
return path
|
||||
Reference in New Issue
Block a user