1
0

json-input.test.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { test } from 'node:test'
  2. import assert from 'node:assert/strict'
  3. import os from 'node:os'
  4. import path from 'node:path'
  5. import { promises as fs } from 'node:fs'
  6. import { readJsonInput } from '../../src/util/json-input.js'
  7. /**
  8. * P2-1:相对路径两处都找(先启动目录再书仓库),找不到把两处路径如实列出。
  9. * 宿主在启动目录写临时 JSON 传相对名,此前按 repoPath 解析必 ENOENT。
  10. */
  11. async function tmpDir(prefix) {
  12. return fs.mkdtemp(path.join(os.tmpdir(), prefix))
  13. }
  14. test('json-input:绝对路径直接读', async () => {
  15. const dir = await tmpDir('wnw-ji-')
  16. try {
  17. const p = path.join(dir, 'a.json')
  18. await fs.writeFile(p, '{"x":1}', 'utf8')
  19. const r = await readJsonInput({ repoPath: dir }, p, 'file')
  20. assert.equal(r.ok, true)
  21. assert.equal(r.data.x, 1)
  22. } finally {
  23. await fs.rm(dir, { recursive: true, force: true })
  24. }
  25. })
  26. test('json-input:相对路径按启动目录找得到(宿主临时 JSON 常写在这)', async () => {
  27. const cwdDir = await tmpDir('wnw-ji-cwd-')
  28. const repoDir = await tmpDir('wnw-ji-repo-')
  29. const oldCwd = process.cwd()
  30. try {
  31. await fs.writeFile(path.join(cwdDir, 'payload.json'), '{"来源":"启动目录"}', 'utf8')
  32. process.chdir(cwdDir)
  33. const r = await readJsonInput({ repoPath: repoDir }, 'payload.json', 'file')
  34. assert.equal(r.ok, true, r.error)
  35. assert.equal(r.data.来源, '启动目录')
  36. } finally {
  37. process.chdir(oldCwd)
  38. await fs.rm(cwdDir, { recursive: true, force: true })
  39. await fs.rm(repoDir, { recursive: true, force: true })
  40. }
  41. })
  42. test('json-input:启动目录没有 → 回落书仓库解析(SKILL 约定放 工作区/)', async () => {
  43. const repoDir = await tmpDir('wnw-ji-repo2-')
  44. try {
  45. await fs.mkdir(path.join(repoDir, '工作区'), { recursive: true })
  46. await fs.writeFile(path.join(repoDir, '工作区', 'p.json'), '{"来源":"书仓库"}', 'utf8')
  47. const r = await readJsonInput({ repoPath: repoDir }, path.join('工作区', 'p.json'), 'file')
  48. assert.equal(r.ok, true, r.error)
  49. assert.equal(r.data.来源, '书仓库')
  50. } finally {
  51. await fs.rm(repoDir, { recursive: true, force: true })
  52. }
  53. })
  54. test('json-input:两处都没有 → 报错列出找过的路径', async () => {
  55. const repoDir = await tmpDir('wnw-ji-repo3-')
  56. try {
  57. const r = await readJsonInput({ repoPath: repoDir }, '不存在.json', 'file')
  58. assert.equal(r.ok, false)
  59. assert.ok(r.error.includes('找过'), '报错应列出找过的路径')
  60. assert.ok(r.error.includes(repoDir), '报错应包含书仓库侧的候选路径')
  61. } finally {
  62. await fs.rm(repoDir, { recursive: true, force: true })
  63. }
  64. })