refactor(tests): restructure into layered POM architecture with Allure reporting

- Split framework into core/ (config, logger, db, driver factories, screenshot,
  allure integration) and pages/ (PO layer: base/admin/driver); flatten test
  files per platform (web/admin, app/driver_android, cross_end)
- Slim root conftest.py 656 -> ~100 lines: drop inline CN HTML report, add
  Allure severity mapping (p0/p1/p2 -> blocker/normal/minor) and
  environment.properties; support both tests.*-prefixed and bare imports
- Preserve TC-D2S-001/002 cross-end E2E cases with business logic unchanged,
  add allure epic/feature/story/step annotations
- Deduplicate: single makereport hook, shared failure-screenshot helpers,
  single SCREENSHOTS_DIR constant; deterministic auth-state role loading
- Move DB credentials from db_helper.py into test_config.yaml (database section)
- Move pytest.ini to repo root; switch reporting to allure-pytest
  (drop pytest-html/junitxml); update requirements.txt accordingly
- Delete deprecated scaffolding: test_freight_full_flow + 6 stale page
  objects, iOS/shipper empty shells, dead utils
- Fix flaky vxe-table action-row wait: wait for a visible td instead of
  hidden placeholder rows (fixed shipper-payment timeouts)
- Verified end-to-end against live env: both E2E cases pass (2 passed 3m12s);
  run artifacts (logs/screenshots/allure) included per repo convention
This commit is contained in:
xst
2026-08-17 14:29:52 +08:00
parent 70bd7fede2
commit 18890c0437
597 changed files with 2184 additions and 3286 deletions
+1
View File
@@ -0,0 +1 @@
"""app 测试包。"""
-73
View File
@@ -1,73 +0,0 @@
"""通用 App Page Object 基类。"""
from datetime import datetime
from pathlib import Path
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
SCREENSHOTS_DIR = Path("output/screenshots")
class AppBasePage:
"""App Page Object 基类 — 各端通用。"""
def __init__(self, driver, platform: str, timeout_ms: int = 30_000):
self.driver = driver
self.platform = platform # "android" | "ios"
self.timeout = timeout_ms / 1000
def wait_visible_by_id(self, accessibility_id: str, timeout_s: float | None = None) -> None:
wait = WebDriverWait(self.driver, timeout=timeout_s or self.timeout)
wait.until(
EC.visibility_of_element_located((AppiumBy.ACCESSIBILITY_ID, accessibility_id))
)
def wait_visible_by_text(self, text: str, timeout_s: float | None = None) -> None:
wait = WebDriverWait(self.driver, timeout=timeout_s or self.timeout)
locator = (
(AppiumBy.XPATH, f"//*[@text='{text}']")
if self.platform == "android"
else (AppiumBy.XPATH, f"//*[@label='{text}']")
)
wait.until(EC.visibility_of_element_located(locator))
def tap_by_id(self, accessibility_id: str) -> None:
self.wait_visible_by_id(accessibility_id)
self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, accessibility_id).click()
def tap_by_text(self, text: str) -> None:
strategy = AppiumBy.XPATH
locator = (
f"//*[@text='{text}']"
if self.platform == "android"
else f"//*[@label='{text}']"
)
wait = WebDriverWait(self.driver, timeout=self.timeout)
wait.until(EC.visibility_of_element_located((strategy, locator)))
self.driver.find_element(strategy, locator).click()
def fill_by_id(self, accessibility_id: str, value: str) -> None:
self.wait_visible_by_id(accessibility_id)
element = self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, accessibility_id)
element.clear()
element.send_keys(value)
def scroll_down(self) -> None:
size = self.driver.get_window_size()
self.driver.swipe(
start_x=size["width"] // 2,
start_y=int(size["height"] * 0.7),
end_x=size["width"] // 2,
end_y=int(size["height"] * 0.3),
duration=500,
)
def screenshot(self, name: str) -> str:
scenario_dir = SCREENSHOTS_DIR / self.__class__.__name__
scenario_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
path = str(scenario_dir / f"{name}_{self.platform}_{ts}.png")
self.driver.save_screenshot(path)
return path
-197
View File
@@ -1,197 +0,0 @@
"""App 端公共模块 — driver 创建 + ensure_logged_in 工厂。
所有 App 端 conftest 调用 share_* 函数即可,避免重复代码。
"""
from datetime import datetime
from pathlib import Path
import pytest
SCREENSHOTS_DIR = Path("output/screenshots")
def create_driver(section_config: dict, platform: str):
"""创建 Appium driver。
Args:
section_config: 配置中对应端的 section(如 config["driver_android"])
platform: "android" | "ios"
"""
try:
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.options.ios import XCUITestOptions
except ImportError:
pytest.skip("Appium-Python-Client 未安装,跳过 App 测试。")
appium_host = section_config.get("appium_host", "http://localhost:4723")
if platform == "android":
options = UiAutomator2Options()
options.device_name = section_config["device_name"]
options.app_package = section_config["app_package"]
options.app_activity = section_config["app_activity"]
options.no_reset = section_config.get("no_reset", True)
options.new_command_timeout = section_config.get("new_command_timeout", 120)
options.automation_name = "UiAutomator2"
else:
options = XCUITestOptions()
options.device_name = section_config["device_name"]
options.bundle_id = section_config["bundle_id"]
options.no_reset = section_config.get("no_reset", True)
options.new_command_timeout = section_config.get("new_command_timeout", 120)
options.automation_name = "XCUITest"
return webdriver.Remote(appium_host, options=options)
def make_ensure_logged_in(
section_config: dict,
config: dict,
account_role: str,
home_indicator: str = "tab_home",
):
"""创建一个 ensure_logged_in 闭包。
策略:
1. 反复点击返回键,直到底部导航栏(首页/货源/我的)全部可见
2. 点击"我的"tab,检查"登录/注册"文本是否存在
3. 不存在 → 已登录;存在 → 未登录
Args:
section_config: App 端配置
config: 全局配置
account_role: 默认账号角色名(如 "driver"、"shipper")
home_indicator: 未使用,保留兼容
"""
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from appium.webdriver.common.appiumby import AppiumBy
def _ensure_logged_in(driver, timeout_s: float = 10.0) -> None:
skip_login = section_config.get("skip_login", True)
wait = WebDriverWait(driver, timeout=timeout_s)
# ── 底部导航栏三个 tab 定位(使用 text 定位,更可靠)──
home_tab = (AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("首页")')
freight_tab = (AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("货源")')
mine_tab = (AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("我的")')
# ── 步骤1: 返回到一级页面 ──
# 不断点返回键,直到三个底部导航 tab 都可见
max_back_presses = 20
for _ in range(max_back_presses):
home_visible = _is_displayed(driver, home_tab)
freight_visible = _is_displayed(driver, freight_tab)
mine_visible = _is_displayed(driver, mine_tab)
if home_visible and freight_visible and mine_visible:
break
# 不在一级页面 → 点击返回
try:
driver.back()
driver.implicitly_wait(1)
except Exception:
break
# ── 步骤2: 点击"我的"tab ──
wait.until(EC.visibility_of_element_located(mine_tab))
driver.find_element(*mine_tab).click()
driver.implicitly_wait(1)
# ── 步骤3: 判断登录态 ──
login_check = (AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("登录/注册")')
try:
el = driver.find_element(*login_check)
if el.is_displayed():
if skip_login:
raise RuntimeError(
"APP 未登录!请在设备上手动完成一次登录(含验证码),"
"之后重新运行用例即可。\n如需自动化登录,请设置 skip_login: false。"
)
_perform_ui_login(driver, config["accounts"].get(account_role, {}), wait)
return
except RuntimeError:
raise
except Exception:
pass # 没找到"登录/注册" → 已登录
# ── 步骤4: 回到首页 ──
try:
wait.until(EC.visibility_of_element_located(home_tab))
driver.find_element(*home_tab).click()
except Exception:
pass
return _ensure_logged_in
def _is_displayed(driver, locator) -> bool:
"""检查元素是否可见(不抛异常)。"""
try:
el = driver.find_element(*locator)
return el.is_displayed()
except Exception:
return False
def _perform_ui_login(driver, account: dict, wait) -> None:
"""执行 UI 自动登录(skip_login: false 时使用)。"""
from appium.webdriver.common.appiumby import AppiumBy
phone = account.get("phone", "")
password = account.get("password", "")
# 点击登录入口
login_entry = (AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("登录/注册")')
wait.until(lambda d: d.find_element(*login_entry))
driver.find_element(*login_entry).click()
driver.implicitly_wait(1)
# 填写手机号
phone_input = (AppiumBy.ID, "com.arpa.ynchenggangdriver:id/ed_phone")
wait.until(lambda d: d.find_element(*phone_input))
driver.find_element(*phone_input).send_keys(phone)
# 填写密码
password_input = (AppiumBy.ID, "com.arpa.ynchenggangdriver:id/ed_pwd")
driver.find_element(*password_input).send_keys(password)
# 点击登录
login_btn = (AppiumBy.ID, "com.arpa.ynchenggangdriver:id/tv_login")
driver.find_element(*login_btn).click()
driver.implicitly_wait(2)
# 回到首页
home_tab = (
AppiumBy.ANDROID_UIAUTOMATOR,
'new UiSelector().resourceId("com.arpa.ynchenggangdriver:id/fixed_bottom_navigation_icon").instance(0)',
)
try:
wait.until(lambda d: d.find_element(*home_tab))
driver.find_element(*home_tab).click()
except Exception:
pass
def save_failure_screenshot(driver, section_config, platform, request):
"""失败自动截图(各端 conftest teardown 中调用)。"""
if (
section_config.get("screenshot_on_failure", True)
and hasattr(request.node, "rep_call")
and request.node.rep_call.failed
):
scenario_dir = SCREENSHOTS_DIR / request.node.name
scenario_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
path = str(scenario_dir / f"FAIL_{platform}_{ts}.png")
driver.save_screenshot(path)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
setattr(item, f"rep_{rep.when}", rep)
+1
View File
@@ -0,0 +1 @@
"""driver_android 测试包。"""
+10 -4
View File
@@ -1,9 +1,12 @@
"""司机安卓端 fixture — Appium + 登录态复用。"""
"""司机安卓端 fixtures — Appium + 登录态复用。"""
import pytest
from tests.app._shared import create_driver, make_ensure_logged_in, save_failure_screenshot
from tests.app._shared import pytest_runtest_makereport # noqa: F401 — report hook
from tests.core.appium_support import (
create_driver,
make_ensure_logged_in,
save_failure_screenshot,
)
@pytest.fixture
@@ -17,7 +20,10 @@ def driver(driver_android_config, request):
save_failure_screenshot(d, cfg, "android", request)
finally:
if d is not None:
d.quit()
try:
d.quit()
except Exception:
pass
@pytest.fixture
@@ -1,26 +0,0 @@
"""司机安卓端 Page Object — 首页。"""
from tests.app._base_page import AppBasePage
class DriverHomePage(AppBasePage):
"""司机端 APP 首页。"""
def __init__(self, driver, platform: str = "android"):
super().__init__(driver, platform)
self.order_tab = "tab_orders"
self.mine_tab = "tab_mine"
self.home_tab = "tab_home"
def is_displayed(self) -> bool:
try:
self.wait_visible_by_id(self.home_tab, timeout_s=10)
return True
except Exception:
return False
def go_to_order_list(self) -> None:
self.tap_by_id(self.order_tab)
def go_to_mine(self) -> None:
self.tap_by_id(self.mine_tab)
@@ -1,18 +1,24 @@
"""司机安卓端 — 冒烟测试。"""
import allure
import pytest
from tests.pages.driver.home_page import DriverHomePage
pytestmark = [pytest.mark.driver_android]
@allure.epic("运八网络货运平台")
@allure.feature("司机安卓端")
class TestDriverAndroidSmoke:
"""司机安卓端基础验证。"""
@allure.story("首页")
@allure.title("验证登录态有效,首页正常")
@pytest.mark.p0
@pytest.mark.smoke
def test_home_page_loaded(self, driver, ensure_logged_in):
"""验证登录态有效,首页正常。"""
ensure_logged_in(driver)
from appium.webdriver.common.appiumby import AppiumBy
home = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "tab_home")
home = DriverHomePage(driver)
assert home.is_displayed(), "首页 tab 应可见"
-27
View File
@@ -1,27 +0,0 @@
"""司机苹果端 fixture — Appium + 登录态复用。"""
import pytest
from tests.app._shared import create_driver, make_ensure_logged_in, save_failure_screenshot
from tests.app._shared import pytest_runtest_makereport # noqa: F401
@pytest.fixture
def driver(driver_ios_config, request):
"""司机苹果端 driver。"""
cfg = driver_ios_config
d = None
try:
d = create_driver(cfg, platform="ios")
yield d
save_failure_screenshot(d, cfg, "ios", request)
finally:
if d is not None:
d.quit()
@pytest.fixture
def ensure_logged_in(driver_ios_config, config):
"""确保已登录态(司机角色)。"""
fn = make_ensure_logged_in(driver_ios_config, config, account_role="driver")
return lambda d: fn(d)
-18
View File
@@ -1,18 +0,0 @@
"""司机苹果端 — 冒烟测试。"""
import pytest
pytestmark = [pytest.mark.driver_ios]
class TestDriverIosSmoke:
"""司机苹果端基础验证。"""
@pytest.mark.p0
@pytest.mark.smoke
def test_home_page_loaded(self, driver, ensure_logged_in):
"""验证登录态有效,首页正常。"""
ensure_logged_in(driver)
from appium.webdriver.common.appiumby import AppiumBy
home = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "tab_home")
assert home.is_displayed(), "首页 tab 应可见"
-27
View File
@@ -1,27 +0,0 @@
"""货主安卓端 fixture — Appium + 登录态复用。"""
import pytest
from tests.app._shared import create_driver, make_ensure_logged_in, save_failure_screenshot
from tests.app._shared import pytest_runtest_makereport # noqa: F401
@pytest.fixture
def driver(shipper_android_config, request):
"""货主安卓端 driver。"""
cfg = shipper_android_config
d = None
try:
d = create_driver(cfg, platform="android")
yield d
save_failure_screenshot(d, cfg, "android", request)
finally:
if d is not None:
d.quit()
@pytest.fixture
def ensure_logged_in(shipper_android_config, config):
"""确保已登录态(货主角色)。"""
fn = make_ensure_logged_in(shipper_android_config, config, account_role="shipper")
return lambda d: fn(d)
@@ -1,18 +0,0 @@
"""货主安卓端 — 冒烟测试。"""
import pytest
pytestmark = [pytest.mark.shipper_android]
class TestShipperAndroidSmoke:
"""货主安卓端基础验证。"""
@pytest.mark.p0
@pytest.mark.smoke
def test_home_page_loaded(self, driver, ensure_logged_in):
"""验证登录态有效,首页正常。"""
ensure_logged_in(driver)
from appium.webdriver.common.appiumby import AppiumBy
home = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "tab_home")
assert home.is_displayed(), "首页 tab 应可见"
-27
View File
@@ -1,27 +0,0 @@
"""货主苹果端 fixture — Appium + 登录态复用。"""
import pytest
from tests.app._shared import create_driver, make_ensure_logged_in, save_failure_screenshot
from tests.app._shared import pytest_runtest_makereport # noqa: F401
@pytest.fixture
def driver(shipper_ios_config, request):
"""货主苹果端 driver。"""
cfg = shipper_ios_config
d = None
try:
d = create_driver(cfg, platform="ios")
yield d
save_failure_screenshot(d, cfg, "ios", request)
finally:
if d is not None:
d.quit()
@pytest.fixture
def ensure_logged_in(shipper_ios_config, config):
"""确保已登录态(货主角色)。"""
fn = make_ensure_logged_in(shipper_ios_config, config, account_role="shipper")
return lambda d: fn(d)
-18
View File
@@ -1,18 +0,0 @@
"""货主苹果端 — 冒烟测试。"""
import pytest
pytestmark = [pytest.mark.shipper_ios]
class TestShipperIosSmoke:
"""货主苹果端基础验证。"""
@pytest.mark.p0
@pytest.mark.smoke
def test_home_page_loaded(self, driver, ensure_logged_in):
"""验证登录态有效,首页正常。"""
ensure_logged_in(driver)
from appium.webdriver.common.appiumby import AppiumBy
home = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "tab_home")
assert home.is_displayed(), "首页 tab 应可见"