60 lines
2.9 KiB
JavaScript
60 lines
2.9 KiB
JavaScript
// promptlib 本地契约测试(纯 node):分享「带封面 / 不带封面」开关。
|
||
// 运行:node promptlib/tools/harness.mjs (退出码 0 = 全过)
|
||
// 做法:静态断言 manifest 开关声明 + 从真实 src 抠出 sharePayload 函数体,
|
||
// 在受控沙箱里跑两条分支,验证关掉开关时连封面都不读、分享文本不带 cover。
|
||
import fs from 'node:fs'
|
||
import path from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
import vm from 'node:vm'
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||
const ROOT = path.resolve(HERE, '..')
|
||
const src = fs.readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
|
||
let failed = 0
|
||
const ok = (name, cond) => {
|
||
if (!cond) failed++
|
||
console.log((cond ? '✓ ' : '✗ ') + name)
|
||
}
|
||
|
||
// 1) manifest 声明了布尔开关,默认带图(兼容老行为)
|
||
ok("manifest 有 shareWithCover 布尔开关(默认 true)",
|
||
/shareWithCover:\s*\{\s*type:\s*'boolean'[^}]*default:\s*true/.test(src))
|
||
ok('开关 label 提示关闭后分享内容更短', /关闭后分享内容更短/.test(src))
|
||
ok("manifest.version = 1.9.2", /version:\s*'1\.9\.2'/.test(src))
|
||
ok('package.json version = 1.9.2',
|
||
JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version === '1.9.2')
|
||
ok('shareWithCover() 从 ctx.settings 读、缺省按带图',
|
||
/function shareWithCover \(\)[\s\S]{0,200}S\.get\('shareWithCover'\) !== false/.test(src))
|
||
|
||
// 2) 两条分支:关掉开关时 coverToDataUrl 抛错也不能被调用
|
||
const m = src.match(/ function sharePayload \(p\) \{[\s\S]*?\n \}\n function doShare/)
|
||
ok('从 src 找到 sharePayload 函数体', !!m)
|
||
const fnSrc = m ? m[0].replace(/\n function doShare$/, '') : ''
|
||
const sandbox = {
|
||
SHARE_TAG: 'IWB-PROMPT-SHARE',
|
||
varsOf: () => [],
|
||
coverToDataUrl: () => { throw new Error('关掉开关后不该读封面') },
|
||
shareWithCover: () => false,
|
||
Promise, JSON, String, Number, Array, Object,
|
||
}
|
||
vm.createContext(sandbox)
|
||
vm.runInContext(fnSrc, sandbox)
|
||
const p = { name: '测试词', text: '一只猫', group: '分组A', tags: ['x'], cover: { img: 'a.jpg' } }
|
||
|
||
const text = await sandbox.sharePayload(p)
|
||
const body = JSON.parse(text.split('\n')[1])
|
||
ok('关掉开关:分享文本无 cover 字段', !('cover' in body.sharing))
|
||
ok('关掉开关:不读取封面(stub 抛错也未触发)', true)
|
||
ok('关掉开关:名字/正文/分组仍在',
|
||
body.sharing.name === '测试词' && body.sharing.text === '一只猫' && body.sharing.group === '分组A')
|
||
|
||
sandbox.shareWithCover = () => true
|
||
sandbox.coverToDataUrl = () => Promise.resolve('data:image/jpeg;base64,AAAA')
|
||
const text2 = await sandbox.sharePayload(p)
|
||
const body2 = JSON.parse(text2.split('\n')[1])
|
||
ok('打开开关:分享文本仍带 cover(默认行为不变)',
|
||
body2.sharing.cover === 'data:image/jpeg;base64,AAAA')
|
||
|
||
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过')
|
||
if (failed) process.exitCode = 1
|