修复构建与后端测试并发冲突并补充迁移验收记录
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-08 18:59:50 +08:00
1 parent b7d4805402
commit c33b8bbc2f
6 files changed
+232 -14

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
param([Parameter(Mandatory = $true)][string]$InvocationFile)
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
. (Join-Path $root 'deploy\workspace-lock.ps1')
$workspaceLock = Enter-SmailWorkspaceLock -Root $root
try {
# 参数从测试记录读取为字符串数组,不拼接或执行 Shell 命令。
$invocation = Get-Content -LiteralPath $InvocationFile -Raw -Encoding UTF8 | ConvertFrom-Json
if ($invocation.arguments -isnot [Array] -or $invocation.arguments.Count -eq 0) {
throw 'Go 测试参数必须是非空数组'
}
foreach ($argument in $invocation.arguments) {
if ($argument -isnot [string]) { throw 'Go 测试参数必须是字符串' }
}
$arguments = @($invocation.arguments)
Push-Location (Join-Path $root 'backend')
try {
& go @arguments
$code = $LASTEXITCODE
} finally {
Pop-Location
}
} finally {
$workspaceLock.ReleaseMutex()
$workspaceLock.Dispose()
}
exit $code
+96
View File
@@ -0,0 +1,96 @@
import assert from 'node:assert/strict'
import { spawn, spawnSync } from 'node:child_process'
import { once } from 'node:events'
import { mkdtemp, readFile, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
const root = fileURLToPath(new URL('../../', import.meta.url))
const lockScript = path.join(root, 'deploy', 'workspace-lock.ps1')
const shellArguments = ['-NoProfile', '-ExecutionPolicy', 'Bypass']
const windowsOnly = { skip: process.platform !== 'win32', timeout: 30000 }
const quote = value => `'${value.replaceAll("'", "''")}'`
function acquire(directory) {
return `$ErrorActionPreference = 'Stop'; . ${quote(lockScript)}; $lock = Enter-SmailWorkspaceLock -Root ${quote(directory)};`
}
function probe(directory) {
return spawnSync('powershell.exe', [...shellArguments, '-Command',
`${acquire(directory)} try { Write-Output 'acquired' } finally { $lock.ReleaseMutex(); $lock.Dispose() }`,
], { encoding: 'utf8', windowsHide: true, timeout: 10000 })
}
async function hold(directory, context) {
const child = spawn('powershell.exe', [...shellArguments, '-Command',
`${acquire(directory)} try { Write-Output 'ready'; [Console]::In.ReadLine() | Out-Null } finally { $lock.ReleaseMutex(); $lock.Dispose() }`,
], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] })
context.after(() => {
if (child.exitCode === null) child.kill()
})
await new Promise((resolve, reject) => {
let output = ''
let errors = ''
child.stderr.on('data', data => { errors += data })
child.stdout.on('data', data => {
output += data
if (output.includes('ready')) resolve()
})
child.once('error', reject)
child.once('exit', code => reject(new Error(`锁持有进程提前退出:${code};${errors}`)))
})
return child
}
async function release(child) {
const exited = once(child, 'exit')
child.stdin.end('\n')
await exited
}
test('构建入口在计算指纹和移动资源之前获取互斥量', async () => {
const source = await readFile(path.join(root, 'deploy', 'build.ps1'), 'utf8')
const acquireIndex = source.indexOf('$workspaceLock = Enter-SmailWorkspaceLock')
assert.ok(acquireIndex > 0)
assert.ok(acquireIndex < source.indexOf('fingerprint'))
assert.ok(acquireIndex < source.indexOf('Move-Item'))
assert.match(source, /finally\s*\{\s*\$workspaceLock\.ReleaseMutex\(\)/)
})
test('同工作区互斥,不同工作区可以并行,正常退出后可重试', windowsOnly, async context => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'smail-lock-'))
const other = await mkdtemp(path.join(os.tmpdir(), 'smail-lock-other-'))
const child = await hold(directory, context)
assert.notEqual(probe(directory).status, 0)
assert.equal(probe(other).status, 0)
await release(child)
assert.equal(probe(directory).status, 0)
})
test('持有进程异常退出后无需删除文件即可重新获取锁', windowsOnly, async context => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'smail-lock-crash-'))
const child = await hold(directory, context)
const exited = once(child, 'exit')
child.kill()
await exited
assert.equal(probe(directory).status, 0)
})
test('Go 入口与构建共用工作区锁,并保留 Go 退出码', windowsOnly, async context => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'smail-go-lock-'))
const invocation = path.join(directory, 'invocation.json')
const run = () => spawnSync('powershell.exe', [...shellArguments, '-File',
path.join(root, 'test', 'deployment', 'run-go.ps1'), '-InvocationFile', invocation,
], { encoding: 'utf8', windowsHide: true, timeout: 10000 })
await writeFile(invocation, JSON.stringify({ arguments: ['version'] }))
const child = await hold(root, context)
assert.notEqual(run().status, 0)
await release(child)
const success = run()
assert.equal(success.status, 0, success.stderr)
assert.match(success.stdout, /go version/)
await writeFile(invocation, JSON.stringify({ arguments: ['smail-invalid-test-command'] }))
assert.notEqual(run().status, 0)
})
+22 -5
View File
@@ -6,8 +6,8 @@ import path from 'node:path'
const root = fileURLToPath(new URL('../', import.meta.url))
const [suite = 'all', ...extra] = process.argv.slice(2)
if (!['all', 'frontend', 'backend'].includes(suite)) {
console.error('用法:node test/run.mjs [all|frontend|backend] [Go 测试参数]')
if (!['all', 'frontend', 'backend', 'deployment'].includes(suite)) {
console.error('用法:node test/run.mjs [all|frontend|backend|deployment] [Go 测试参数]')
process.exit(2)
}
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
@@ -31,14 +31,21 @@ async function run(name, command, args, cwd) {
}
let result = 0
if (suite !== 'backend') {
if (suite === 'all' || suite === 'frontend') {
const tests = (await readdir(path.join(root, 'test', 'frontend')))
.filter(name => name.endsWith('.test.mjs'))
.map(name => path.join(root, 'test', 'frontend', name))
if (!tests.length) throw new Error('没有找到前端测试,拒绝空测试通过')
result = await run('frontend', process.execPath, ['--test', ...tests], path.join(root, 'frontend'))
}
if (suite !== 'frontend' && result === 0) {
if ((suite === 'all' || suite === 'deployment') && result === 0) {
const tests = (await readdir(path.join(root, 'test', 'deployment')))
.filter(name => name.endsWith('.test.mjs'))
.map(name => path.join(root, 'test', 'deployment', name))
if (!tests.length) throw new Error('没有找到部署测试,拒绝空测试通过')
result = await run('deployment', process.execPath, ['--test', ...tests], root)
}
if ((suite === 'all' || suite === 'backend') && result === 0) {
const args = extra[0] === '--' ? extra.slice(1) : extra
// 独立回归源码集中放在 test/backend,通过 overlay 保留同包测试语义。
const replacements = {
@@ -59,7 +66,17 @@ if (suite !== 'frontend' && result === 0) {
await writeFile(overlay, JSON.stringify({ Replace }, null, 2) + '\n')
// 显式传入的审查 overlay 保持原有行为,默认入口自动包含本轮回归。
const overlayArgs = args.some(arg => arg === '-overlay' || arg.startsWith('-overlay=')) ? [] : [`-overlay=${overlay}`]
result = await run('backend', 'go', ['test', ...overlayArgs, ...(args.length ? args : ['./...'])], path.join(root, 'backend'))
const goArguments = ['test', ...overlayArgs, ...(args.length ? args : ['./...'])]
if (process.platform === 'win32') {
const invocation = path.join(directory, 'go-invocation.json')
await writeFile(invocation, JSON.stringify({ arguments: goArguments }, null, 2) + '\n')
result = await run('backend', 'powershell.exe', [
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
path.join(root, 'test', 'deployment', 'run-go.ps1'), '-InvocationFile', invocation,
], root)
} else {
result = await run('backend', 'go', goArguments, path.join(root, 'backend'))
}
}
console.log(`测试记录:${path.relative(root, directory)}`)
process.exitCode = result