From 76aece2c260c0db059c68a30f7c512ed695db5e4 Mon Sep 17 00:00:00 2001 From: WbiubiuW Date: Tue, 22 Sep 2026 14:28:44 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20MES=20=E6=8E=A5=E5=8F=A3=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8C=96=E6=B5=8B=E8=AF=95=E6=A1=86=E6=9E=B6=EF=BC=88?= =?UTF-8?q?unittest=20+=20HTMLTestRunner=20+=20=E6=95=B0=E6=8D=AE=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ._.git | Bin 0 -> 163 bytes ._.gitignore | Bin 0 -> 163 bytes ._README.md | Bin 0 -> 163 bytes ._apis | Bin 0 -> 163 bytes ._config | Bin 0 -> 163 bytes ._conftest.py | Bin 0 -> 163 bytes ._core | Bin 0 -> 163 bytes ._dao | Bin 0 -> 163 bytes ._fixtures | Bin 0 -> 163 bytes ._mock | Bin 0 -> 163 bytes ._requirements.txt | Bin 0 -> 163 bytes ._runner.py | Bin 0 -> 163 bytes ._vendor | Bin 0 -> 163 bytes .gitignore | 21 ++++ README.md | 116 ++++++++++++++++++++ apis/.___init__.py | Bin 0 -> 163 bytes apis/._equipment | Bin 0 -> 163 bytes apis/._login | Bin 0 -> 163 bytes apis/._mold | Bin 0 -> 163 bytes apis/._plan | Bin 0 -> 163 bytes apis/._product | Bin 0 -> 163 bytes apis/._quality | Bin 0 -> 163 bytes apis/._system | Bin 0 -> 163 bytes apis/__init__.py | 0 apis/equipment/.___init__.py | Bin 0 -> 163 bytes apis/equipment/._test_oee_export.py | Bin 0 -> 163 bytes apis/equipment/__init__.py | 0 apis/equipment/test_oee_export.py | 35 ++++++ apis/login/.___init__.py | Bin 0 -> 163 bytes apis/login/._test_login.py | Bin 0 -> 163 bytes apis/login/__init__.py | 0 apis/login/test_login.py | 64 +++++++++++ apis/mold/.___init__.py | Bin 0 -> 163 bytes apis/mold/._test_mold.py | Bin 0 -> 163 bytes apis/mold/__init__.py | 0 apis/mold/test_mold.py | 53 ++++++++++ apis/plan/.___init__.py | Bin 0 -> 163 bytes apis/plan/._test_work_order.py | Bin 0 -> 163 bytes apis/plan/__init__.py | 0 apis/plan/test_work_order.py | 58 ++++++++++ apis/product/.___init__.py | Bin 0 -> 163 bytes apis/product/__init__.py | 0 apis/quality/.___init__.py | Bin 0 -> 163 bytes apis/quality/._test_quality.py | Bin 0 -> 163 bytes apis/quality/__init__.py | 0 apis/quality/test_quality.py | 49 +++++++++ apis/system/.___init__.py | Bin 0 -> 163 bytes apis/system/._test_material.py | Bin 0 -> 163 bytes apis/system/._test_user.py | Bin 0 -> 163 bytes apis/system/__init__.py | 0 apis/system/test_material.py | 42 ++++++++ apis/system/test_user.py | 59 +++++++++++ config/._config.example.ini | Bin 0 -> 163 bytes config/config.example.ini | 17 +++ conftest.py | 17 +++ core/.___init__.py | Bin 0 -> 163 bytes core/._auth.py | Bin 0 -> 163 bytes core/._config.py | Bin 0 -> 163 bytes core/._data.py | Bin 0 -> 163 bytes core/._email_sender.py | Bin 0 -> 163 bytes core/._http_client.py | Bin 0 -> 163 bytes core/._logger.py | Bin 0 -> 163 bytes core/._path.py | Bin 0 -> 163 bytes core/__init__.py | 0 core/auth.py | 88 ++++++++++++++++ core/config.py | 43 ++++++++ core/data.py | 24 +++++ core/email_sender.py | 61 +++++++++++ core/http_client.py | 57 ++++++++++ core/logger.py | 43 ++++++++ core/path.py | 21 ++++ dao/.___init__.py | Bin 0 -> 163 bytes dao/._conn.py | Bin 0 -> 163 bytes dao/._equipment.py | Bin 0 -> 163 bytes dao/._fake_db.py | Bin 0 -> 163 bytes dao/._mold.py | Bin 0 -> 163 bytes dao/._quality.py | Bin 0 -> 163 bytes dao/._user.py | Bin 0 -> 163 bytes dao/._work.py | Bin 0 -> 163 bytes dao/__init__.py | 0 dao/conn.py | 58 ++++++++++ dao/equipment.py | 9 ++ dao/fake_db.py | 81 ++++++++++++++ dao/mold.py | 9 ++ dao/quality.py | 16 +++ dao/user.py | 9 ++ dao/work.py | 10 ++ fixtures/._login.yml | Bin 0 -> 163 bytes fixtures/._materials.yml | Bin 0 -> 163 bytes fixtures/._users.yml | Bin 0 -> 163 bytes fixtures/._work_orders.yml | Bin 0 -> 163 bytes fixtures/login.yml | 22 ++++ fixtures/materials.yml | 12 +++ fixtures/users.yml | 20 ++++ fixtures/work_orders.yml | 20 ++++ mock/.___init__.py | Bin 0 -> 163 bytes mock/._server.py | Bin 0 -> 163 bytes mock/__init__.py | 0 mock/server.py | 158 ++++++++++++++++++++++++++++ requirements.txt | 5 + runner.py | 54 ++++++++++ vendor/._HTMLTestRunner.py | Bin 0 -> 163 bytes vendor/.___init__.py | Bin 0 -> 163 bytes vendor/HTMLTestRunner.py | 112 ++++++++++++++++++++ vendor/__init__.py | 0 105 files changed, 1463 insertions(+) create mode 100755 ._.git create mode 100644 ._.gitignore create mode 100644 ._README.md create mode 100755 ._apis create mode 100755 ._config create mode 100644 ._conftest.py create mode 100755 ._core create mode 100755 ._dao create mode 100755 ._fixtures create mode 100755 ._mock create mode 100644 ._requirements.txt create mode 100644 ._runner.py create mode 100755 ._vendor create mode 100644 .gitignore create mode 100644 README.md create mode 100644 apis/.___init__.py create mode 100755 apis/._equipment create mode 100755 apis/._login create mode 100755 apis/._mold create mode 100755 apis/._plan create mode 100755 apis/._product create mode 100755 apis/._quality create mode 100755 apis/._system create mode 100644 apis/__init__.py create mode 100644 apis/equipment/.___init__.py create mode 100644 apis/equipment/._test_oee_export.py create mode 100644 apis/equipment/__init__.py create mode 100644 apis/equipment/test_oee_export.py create mode 100644 apis/login/.___init__.py create mode 100644 apis/login/._test_login.py create mode 100644 apis/login/__init__.py create mode 100644 apis/login/test_login.py create mode 100644 apis/mold/.___init__.py create mode 100644 apis/mold/._test_mold.py create mode 100644 apis/mold/__init__.py create mode 100644 apis/mold/test_mold.py create mode 100644 apis/plan/.___init__.py create mode 100644 apis/plan/._test_work_order.py create mode 100644 apis/plan/__init__.py create mode 100644 apis/plan/test_work_order.py create mode 100644 apis/product/.___init__.py create mode 100644 apis/product/__init__.py create mode 100644 apis/quality/.___init__.py create mode 100644 apis/quality/._test_quality.py create mode 100644 apis/quality/__init__.py create mode 100644 apis/quality/test_quality.py create mode 100644 apis/system/.___init__.py create mode 100644 apis/system/._test_material.py create mode 100644 apis/system/._test_user.py create mode 100644 apis/system/__init__.py create mode 100644 apis/system/test_material.py create mode 100644 apis/system/test_user.py create mode 100644 config/._config.example.ini create mode 100644 config/config.example.ini create mode 100644 conftest.py create mode 100644 core/.___init__.py create mode 100644 core/._auth.py create mode 100644 core/._config.py create mode 100644 core/._data.py create mode 100644 core/._email_sender.py create mode 100644 core/._http_client.py create mode 100644 core/._logger.py create mode 100644 core/._path.py create mode 100644 core/__init__.py create mode 100644 core/auth.py create mode 100644 core/config.py create mode 100644 core/data.py create mode 100644 core/email_sender.py create mode 100644 core/http_client.py create mode 100644 core/logger.py create mode 100644 core/path.py create mode 100644 dao/.___init__.py create mode 100644 dao/._conn.py create mode 100644 dao/._equipment.py create mode 100644 dao/._fake_db.py create mode 100644 dao/._mold.py create mode 100644 dao/._quality.py create mode 100644 dao/._user.py create mode 100644 dao/._work.py create mode 100644 dao/__init__.py create mode 100644 dao/conn.py create mode 100644 dao/equipment.py create mode 100644 dao/fake_db.py create mode 100644 dao/mold.py create mode 100644 dao/quality.py create mode 100644 dao/user.py create mode 100644 dao/work.py create mode 100644 fixtures/._login.yml create mode 100644 fixtures/._materials.yml create mode 100644 fixtures/._users.yml create mode 100644 fixtures/._work_orders.yml create mode 100644 fixtures/login.yml create mode 100644 fixtures/materials.yml create mode 100644 fixtures/users.yml create mode 100644 fixtures/work_orders.yml create mode 100644 mock/.___init__.py create mode 100644 mock/._server.py create mode 100644 mock/__init__.py create mode 100644 mock/server.py create mode 100644 requirements.txt create mode 100644 runner.py create mode 100644 vendor/._HTMLTestRunner.py create mode 100644 vendor/.___init__.py create mode 100644 vendor/HTMLTestRunner.py create mode 100644 vendor/__init__.py diff --git a/._.git b/._.git new file mode 100755 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ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ignore)或环境变量注入。 +""" +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 diff --git a/core/data.py b/core/data.py new file mode 100644 index 0000000..e8ebf59 --- /dev/null +++ b/core/data.py @@ -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/.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] diff --git a/core/email_sender.py b/core/email_sender.py new file mode 100644 index 0000000..4f5b0c2 --- /dev/null +++ b/core/email_sender.py @@ -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() diff --git a/core/http_client.py b/core/http_client.py new file mode 100644 index 0000000..0359da1 --- /dev/null +++ b/core/http_client.py @@ -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) diff --git a/core/logger.py b/core/logger.py new file mode 100644 index 0000000..e1bddfc --- /dev/null +++ b/core/logger.py @@ -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 diff --git a/core/path.py b/core/path.py new file mode 100644 index 0000000..828a93b --- /dev/null +++ b/core/path.py @@ -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 diff --git a/dao/.___init__.py b/dao/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K" 映射到内置合成数据表, +让 dao 层与用例在没有真实 MySQL 的环境下开箱可跑。 +""" +import re + +_TABLES = { + 'mes_user': { + 'columns': ['id', 'account_num', 'name', 'organization_id', 'del_flag'], + 'rows': [ + (1, 'demo_user', '张三', 10, 0), + (2, 'operator01', '李四', 11, 0), + ], + }, + 'mes_device': { + 'columns': ['id', 'name', 'del_flag'], + 'rows': [(101, '注塑机-01', 0), (102, '注塑机-02', 0)], + }, + 'mes_mold': { + 'columns': ['id', 'name', 'del_flag'], + 'rows': [(201, '模具-A', 0), (202, '模具-B', 0)], + }, + 'mes_quality_inspection_point': { + 'columns': ['id', 'name', 'del_flag'], + 'rows': [(301, '外观缺陷', 0), (302, '尺寸不良', 0)], + }, + 'mes_quality_inspection_type': { + 'columns': ['id', 'name', 'del_flag'], + 'rows': [(401, '首检', 0)], + }, + 'mes_work_order': { + 'columns': ['id', 'product_id', 'plan_yield', 'del_flag'], + 'rows': [(501, 601, 300, 0)], + }, +} + + +class FakeCursor: + def __init__(self): + self.description = None + self._rows = [] + self._sql = '' + + def execute(self, sql, params=None): + self._sql = sql + m = re.search(r'from\s+(\w+)', sql, re.IGNORECASE) + table = _TABLES.get(m.group(1) if m else '', None) + if table is None: + self.description = None + self._rows = [] + return 0 + self.description = [(c,) for c in table['columns']] + self._rows = list(table['rows']) + # 支持演示所需的最小 WHERE 过滤:account_num = %s + if params and 'account_num' in sql: + idx = table['columns'].index('account_num') + self._rows = [r for r in self._rows if r[idx] == params[0]] + return len(self._rows) + + def fetchall(self): + return self._rows + + def close(self): + pass + + +class FakeDB: + def cursor(self): + return FakeCursor() + + def commit(self): + pass + + def rollback(self): + pass + + def close(self): + pass diff --git a/dao/mold.py b/dao/mold.py new file mode 100644 index 0000000..735839d --- /dev/null +++ b/dao/mold.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +"""模具域 SQL。""" +from dao.conn import DBConn + + +class MoldDao(DBConn): + def get_molds(self): + sql = "select id, name from mes_mold where del_flag=0 order by create_date desc" + return self.select(sql) diff --git a/dao/quality.py b/dao/quality.py new file mode 100644 index 0000000..55a10ed --- /dev/null +++ b/dao/quality.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +"""质检域 SQL。 + +连接统一走 dao.conn 分发,模块内不写死租户 id。 +""" +from dao.conn import DBConn + + +class QualityDao(DBConn): + def get_points(self, mes_id): + sql = "select id, name from mes_quality_inspection_point where del_flag=0" + return self.select(sql) + + def get_types(self, mes_id): + sql = "select id, name from mes_quality_inspection_type where del_flag=0" + return self.select(sql) diff --git a/dao/user.py b/dao/user.py new file mode 100644 index 0000000..54e4df2 --- /dev/null +++ b/dao/user.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +"""用户域 SQL。""" +from dao.conn import DBConn + + +class UserDao(DBConn): + def get_user(self, account_num): + sql = "select * from mes_user where del_flag=0 and account_num=%s" + return self.select(sql, (account_num,)) diff --git a/dao/work.py b/dao/work.py new file mode 100644 index 0000000..2a86d2c --- /dev/null +++ b/dao/work.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +"""生产工单域 SQL。""" +from dao.conn import DBConn + + +class WorkDao(DBConn): + def get_work_orders(self): + sql = ("select id, product_id, plan_yield from mes_work_order " + "where del_flag=0 order by id desc") + return self.select(sql) diff --git a/fixtures/._login.yml b/fixtures/._login.yml new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K=2.28 +PyYAML>=6.0 + +# 可选:走 pytest 入口(python -m pytest -q)时另装 +# pip install pytest diff --git a/runner.py b/runner.py new file mode 100644 index 0000000..aa671e0 --- /dev/null +++ b/runner.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +"""统一入口:mock → unittest discover → HTMLTestRunner 报告。 + +流程:启动本地 mock MES 服务 → unittest discover 组装 suite → +HTMLTestRunner 生成报告到 artifacts/reports/。 + +两个细节: +- 报告文件名不用空格(带空格的路径在 CI / 邮件附件场景容易出问题); +- 用例目录不写死相对路径,统一走 core.path。 +""" +import os +import sys +import unittest +from datetime import datetime + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from core.path import artifact_path, get_path # noqa: E402 +from mock.server import start_mock_server # noqa: E402 +from vendor.HTMLTestRunner import HTMLTestRunner # noqa: E402 + +START_DIR = get_path('apis') + + +def build_suite(): + suite = unittest.TestSuite() + all_cases = unittest.defaultTestLoader.discover( + START_DIR, pattern='test_*.py', top_level_dir=get_path()) + for case in all_cases: + suite.addTests(case) + return suite + + +def main(): + start_mock_server(port=8080) + + suite = build_suite() + stamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + report = artifact_path('reports', 'mes_demo_{0}.html'.format(stamp)) + with open(report, 'wb') as fp: + runner = HTMLTestRunner(stream=fp, + title='MES 接口自动化测试报告', + description='unittest + HTMLTestRunner + 数据驱动(yaml)') + result = runner.run(suite) + + ok = len(result.failures) == 0 and len(result.errors) == 0 + print('报告已生成: {0}'.format(report)) + print('总计 {0},失败 {1},错误 {2}'.format( + result.testsRun, len(result.failures), len(result.errors))) + return 0 if ok else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/vendor/._HTMLTestRunner.py b/vendor/._HTMLTestRunner.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K + + + +{title} + + + +

{title}

+

{description}

+

开始时间:{start} 耗时:{duration:.2f}s  + 总计:{total}  + 通过 {passed}  + 失败 {failed}  + 错误 {errors}

+ + +{rows} +
用例说明结果详情
+ + +""" + +_ROW = ('{name}{doc}' + '{status}{detail}') + + +class HTMLTestRunner: + """与 Py2 版 HTMLTestRunner 相同的调用接口。""" + + def __init__(self, stream, title='测试报告', description=''): + self.stream = stream + self.title = title + self.description = description + + def run(self, suite): + result = _Result() + start_time = time.time() + suite.run(result) + duration = time.time() - start_time + + status_cls = {'通过': 'pass', '失败': 'fail', '错误': 'error'} + rows = [] + for name, doc, status, detail in result.rows: + detail_html = '' + if detail: + detail_html = '
{0}
'.format(html.escape(detail)) + rows.append(_ROW.format( + name=html.escape(name), doc=html.escape(doc), + cls=status_cls[status], status=status, detail=detail_html)) + + page = _TEMPLATE.format( + title=html.escape(self.title), + description=html.escape(self.description), + start=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time)), + duration=duration, + total=result.testsRun, + passed=len(result.rows) - len(result.failures) - len(result.errors), + failed=len(result.failures), + errors=len(result.errors), + rows='\n'.join(rows), + ) + # stream 兼容二进制 / 文本两种打开方式 + try: + self.stream.write(page.encode('utf-8')) + except TypeError: + self.stream.write(page) + return result diff --git a/vendor/__init__.py b/vendor/__init__.py new file mode 100644 index 0000000..e69de29