概述

OpenClaw 插件测试的工具、模式和 lint 规则参考。测试辅助子路径是 OpenClaw 自身捆绑插件测试的仓库本地源入口点,不是第三方插件的包导出。

核心 API

测试辅助子路径

子路径用途
plugin-sdk/plugin-test-apicreateTestPluginApi — 直接注册单元测试的最小 API mock
plugin-sdk/agent-runtime-test-contracts原生 Agent 运行时适配器契约 fixture
plugin-sdk/channel-contract-testingChannel 入站上下文形状断言
plugin-sdk/channel-test-helpersChannel 账号生命周期上下文构建器
plugin-sdk/channel-target-testingChannel 目标解析错误用例
plugin-sdk/plugin-test-contracts插件注册契约检查
plugin-sdk/plugin-test-runtimeProvider 插件注册和运行时环境
plugin-sdk/provider-test-contractsProvider 运行时契约检查
plugin-sdk/provider-http-test-mocksProvider HTTP/认证 Vitest mock
plugin-sdk/test-env环境变量、HTTP 服务器、fetch 辅助工具
plugin-sdk/test-fixturesCLI 运行时捕获、沙箱上下文、技能写入器等
plugin-sdk/test-node-mocksNode 内置 Vitest mock

关键导出

导出用途
createTestPluginApi构建最小插件 API mock
expectChannelInboundContextContract断言 channel 入站上下文形状
createStartAccountContext构建 channel 账号生命周期上下文
describePluginRegistrationContract安装插件注册契约检查
registerSingleProviderPlugin在加载器冒烟测试中注册一个 Provider 插件
describeOpenAIProviderRuntimeContract安装 Provider 家族运行时契约检查
withEnv / withEnvAsync临时修补环境变量
withServer针对一次性本地 HTTP 服务器运行测试
bundledPluginRoot解析捆绑插件源或 dist fixture 路径
typedCases为表驱动测试保留字面类型

Lint 规则(仓库内插件)

  1. 禁止整体根导入 — 拒绝 openclaw/plugin-sdk 根 barrel
  2. 禁止直接 src/ 导入 — 插件不能直接导入 ../../src/
  3. 禁止自导入 — 插件不能导入自己的 plugin-sdk/<name> 子路径

使用示例

// Channel 插件单元测试
import { describe, it, expect } from "vitest";
 
describe("my-channel plugin", () => {
  it("resolves account from config", () => {
    const cfg = { channels: { "my-channel": { token: "test-token", allowFrom: ["user1"] } } };
    const account = myPlugin.setup.resolveAccount(cfg, undefined);
    expect(account.token).toBe("test-token");
  });
});
 
// Provider 插件单元测试
describe("my-provider plugin", () => {
  it("resolves dynamic models", () => {
    const model = myProvider.resolveDynamicModel({ modelId: "custom-v2" } as any);
    expect(model.id).toBe("custom-v2");
    expect(model.provider).toBe("my-provider");
  });
});
 
// Mock 运行时
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
const store = createPluginRuntimeStore<PluginRuntime>({ pluginId: "test-plugin", errorMessage: "..." });
store.setRuntime(mockRuntime);
// 测试后
store.clearRuntime();

运行测试

# 运行所有测试
pnpm test
 
# 运行特定插件测试
pnpm test -- <bundled-plugin-root>/my-channel/
 
# 运行契约测试
pnpm test -- src/plugins/contracts/shape.contract.test.ts
 
# 内存压力时限制并发
OPENCLAW_VITEST_MAX_WORKERS=1 pnpm test

相关页面

  • concepts/plugin-sdk-overview — 导入约定
  • concepts/plugin-sdk-channel-plugins — Channel 插件接口
  • concepts/plugin-sdk-provider-plugins — Provider 插件钩子
  • concepts/plugin-building — 插件构建入门