首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Appium 2.x 扩展工程——协议层、Plugin 机制与自研能力

Appium 2.x 扩展工程——协议层、Plugin 机制与自研能力

原创
作者头像
用户12339161
发布于 2026-12-05 18:05:37
发布于 2026-12-05 18:05:37
120
举报

引言

上一篇从"用法"角度讲了定位与框架,本篇换到协议与扩展角度:一条命令在 W3C 协议里长什么样?Appium 2.x 为什么把 driver 和 plugin 从内核剥离?当内置能力不够(需要调用系统命令、注入 mock、做命令级审计)时,如何在不 fork Appium 的前提下扩展它?理解这一层,才能把 Appium 从"黑盒工具"变成"可编程平台"。

一、协议层:一切皆 REST

Appium 服务端实现 W3C WebDriver 规范,核心端点极简:

代码语言:javascript
复制
POST /session                         创建会话
POST /session/{sid}/element           查找元素,返回 W3C element id
POST /session/{sid}/element/{eid}/click
POST /session/{sid}/execute/sync      同步执行脚本
DELETE /session/{sid}                 结束会话

所有响应统一为 {"value": ...}。这个事实推出三条工程结论:element id 是会话内的临时句柄(页面刷新即失效,这正是 StaleElement 的协议根源);每次操作都是一次 HTTP 往返(所以批量操作用 mobile: 命令合并比多次 find 更划算);服务端可被任意 HTTP 代理拦截(这给了做录制回放、请求审计的空间)。

二、Appium 2 的驱动/插件分离

Appium 1.x 把各平台驱动打包在内核里,导致安装包臃肿、版本耦合。Appium 2 拆成三层:appium 内核(协议路由与插件宿主)、driver(uiautomator2/xcuitest,真正与设备通信)、plugin(横切能力,如 images、gestures、element-wait)。安装方式变为显式:

代码语言:javascript
复制
appium driver install uiautomator2
appium driver install xcuitest
appium plugin install --source=npm appium-reporter-plugin
appium --use-plugins=my-retry-plugin --base-path /wd/hub

关键推论:driver 决定能力边界,plugin 决定横切行为。想加"命令重试"不该改 driver,应写 plugin;想加"新的定位方式"才需要碰 driver 的 findElement 扩展。

三、mobile: 命令体系:驱动暴露的原生入口

Appium 通过 execute/sync 端点扩展了 mobile: 命名空间,这是调用驱动原生能力的唯一稳定通道:

命令

平台

用途

mobile: shell

Android

执行 adb shell 命令(需 --relaxed-security)

mobile: startActivity

Android

直接启动 Activity

mobile: scrollGesture

Android

原生滚动,比手写 Actions 稳

mobile: setPasteboard

iOS

注入剪贴板(绕过输入法)

mobile: alert

iOS

处理系统弹窗

mobile: pressButton

iOS

硬件键(home/volume)

注意 mobile: shell 默认被禁用,必须在服务端加 --relaxed-security,且只应在测试设备上开启——这是安全红线。

四、自研 Plugin:在命令流中插桩

Plugin 的核心是 handle(next, driver, cmdName, ...args):它在每个命令执行前后各拿到一次机会,可以记录耗时、重试、改写参数、甚至返回伪造结果(做 mock)。这比在客户端包一层更彻底——因为并行执行的所有 worker 共享同一个服务端策略。

五、工程实现

Plugin 骨架(TypeScript,appium-plugin-retry):

代码语言:javascript
复制
// index.ts
import { BasePlugin } from 'appium/plugin';
import { errors } from 'appium/driver';

const RETRYABLE = new Set(['findElement', 'click', 'getElementRect']);
const TRANSIENT = new Set(['stale element reference', 'no such element', 'timeout']);

interface Opts { maxRetries: number; retryDelayMs: number; slowCmdMs: number }

export default class RetryPlugin extends BasePlugin<Opts> {
  constructor(name: string, opts: Partial<Opts> = {}) {
    super(name, {
      maxRetries: 1, retryDelayMs: 300, slowCmdMs: 2000, ...opts,
    } as Opts);
  }

  async handle(next: () => Promise<any>, driver: any, cmdName: string, ...args: any[]) {
    const started = Date.now();
    let attempt = 0;
    for (;;) {
      try {
        const result = await next();
        const cost = Date.now() - started;
        if (cost > this.opts.slowCmdMs) {
          this.log.warn(`[slow] ${cmdName} ${cost}ms args=${JSON.stringify(args).slice(0, 120)}`);
        }
        return result;
      } catch (err: any) {
        const msg = String(err?.message ?? err).toLowerCase();
        const transient = TRANSIENT.has(err?.constructor?.name?.toLowerCase() ?? '')
          || [...TRANSIENT].some((k) => msg.includes(k));
        if (!transient || !RETRYABLE.has(cmdName) || attempt >= this.opts.maxRetries) {
          throw err;
        }
        attempt += 1;
        this.log.info(`[retry ${attempt}/${this.opts.maxRetries}] ${cmdName}: ${msg}`);
        await new Promise((r) => setTimeout(r, this.opts.retryDelayMs * attempt));
      }
    }
  }
}
代码语言:javascript
复制
// package.json
{
  "name": "appium-plugin-retry",
  "version": "0.1.0",
  "main": "build/index.js",
  "peerDependencies": { "appium": "^2.0.0" },
  "appium": { "pluginName": "retry", "mainClass": "RetryPlugin" }
}
代码语言:javascript
复制
npm run build && appium plugin install --source=local $(pwd)
appium --use-plugins=retry --plugin-retry-max-retries=2

Python 客户端侧:把 mobile: 命令封装成有类型的方法,并做会话级超时控制:

代码语言:javascript
复制
from dataclasses import dataclass
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

class MobileCommands:
    """封装 mobile: 命名空间,隔离平台差异与参数拼写错误。"""
    def __init__(self, driver: webdriver.Remote, platform: str):
        self.d, self.platform = driver, platform

    def shell(self, command: str, args: list[str] | None = None, timeout_s: int = 10):
        if self.platform != "android":
            raise NotImplementedError("mobile: shell 仅 Android")
        self.d.set_script_timeout(timeout_s)
        return self.d.execute_script("mobile: shell", {
            "command": command, "args": args or [], "timeout": timeout_s * 1000,
        })

    def start_activity(self, pkg: str, activity: str, wait: bool = True):
        return self.d.execute_script("mobile: startActivity", {
            "component": f"{pkg}/{activity}", "wait": wait, "stop": True,
        })

    def set_clipboard(self, text: str):
        """注入剪贴板后长按粘贴,绕开输入法导致的不可控输入。"""
        if self.platform == "android":
            self.shell("am", ["broadcast", "-a", "clipper.set", "-e", "text", text])
        else:
            self.d.execute_script("mobile: setPasteboard", {"content": text})

    def scroll_gesture(self, percent: float = 0.6, direction: str = "down"):
        if self.platform == "android":
            size = self.d.get_window_size()
            return self.d.execute_script("mobile: scrollGesture", {
                "left": int(size["width"] * 0.1), "top": int(size["height"] * 0.2),
                "width": int(size["width"] * 0.8), "height": int(size["height"] * 0.6),
                "direction": direction, "percent": percent,
            })
        return self.d.execute_script("mobile: scroll", {"direction": direction})

# 用法
m = MobileCommands(driver, "android")
m.start_activity("com.example.app", ".MainActivity")
m.shell("pm", ["grant", "com.example.app", "android.permission.CAMERA"])
assert "Root" in m.shell("df", ["/data"]).strip() or True

六、小结

协议层决定了 Appium 的一切工程特性:命令是 HTTP 往返、element id 是临时句柄、服务端可插桩。Appium 2 的 driver/plugin 拆分让"能力扩展"有了标准位置——新增定位或设备交互能力写 driver,新增命令级横切策略写 plugin,调用系统能力走 mobile:。这也是判断团队 Appium 成熟度的分水岭:还在客户端层层包装的是在用工具,能在服务端插桩的才是在建平台。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 引言
    • 一、协议层:一切皆 REST
    • 二、Appium 2 的驱动/插件分离
    • 三、mobile: 命令体系:驱动暴露的原生入口
    • 四、自研 Plugin:在命令流中插桩
    • 五、工程实现
    • 六、小结
问题归档专栏文章快讯文章归档关键词归档