1
0

CacheManager.test.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { test } from 'node:test'
  2. import assert from 'node:assert/strict'
  3. import path from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. import { promises as fs } from 'node:fs'
  6. import os from 'node:os'
  7. import { CacheManager } from '../../src/cache/index.js'
  8. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  9. const fixtureRoot = path.join(__dirname, '../fixtures/sample-book')
  10. test('ensureReady:创建数据库并执行 DDL', async () => {
  11. const tmpDb = path.join(os.tmpdir(), `test-${Date.now()}.db`)
  12. const cache = new CacheManager(tmpDb)
  13. await cache.ensureReady(fixtureRoot)
  14. // 验证表是否创建
  15. const tables = await cache.query("SELECT name FROM sqlite_master WHERE type='table'")
  16. const tableNames = tables.map((t) => t.name)
  17. assert.ok(tableNames.includes('chapters'))
  18. assert.ok(tableNames.includes('threads'))
  19. assert.ok(tableNames.includes('entities'))
  20. await cache.close()
  21. await fs.unlink(tmpDb)
  22. })
  23. test('rebuildFromSource:全量重建填充数据', async () => {
  24. const tmpDb = path.join(os.tmpdir(), `test-rebuild-${Date.now()}.db`)
  25. const cache = new CacheManager(tmpDb)
  26. const result = await cache.rebuildFromSource(fixtureRoot)
  27. assert.equal(result.ok, true)
  28. // 验证 chapters 表有数据
  29. const chapters = await cache.query('SELECT * FROM chapters')
  30. assert.ok(chapters.length > 0)
  31. assert.equal(chapters[0].title, '开局')
  32. // 验证 threads 表有数据
  33. const threads = await cache.query('SELECT * FROM threads')
  34. assert.ok(threads.length > 0)
  35. // 验证 entity_aliases 表有数据
  36. const aliases = await cache.query('SELECT * FROM entity_aliases')
  37. assert.ok(aliases.length > 0)
  38. await cache.close()
  39. await fs.unlink(tmpDb)
  40. })
  41. test('删除缓存后全量重建,查询结果不变(AC1)', async () => {
  42. const tmpDb = path.join(os.tmpdir(), `test-delete-rebuild-${Date.now()}.db`)
  43. const cache1 = new CacheManager(tmpDb)
  44. // 第一次重建
  45. await cache1.ensureReady(fixtureRoot)
  46. const count1 = await cache1.query('SELECT COUNT(*) as count FROM chapters')
  47. await cache1.close()
  48. // 删除缓存
  49. await fs.unlink(tmpDb)
  50. // 第二次重建
  51. const cache2 = new CacheManager(tmpDb)
  52. await cache2.ensureReady(fixtureRoot)
  53. const count2 = await cache2.query('SELECT COUNT(*) as count FROM chapters')
  54. await cache2.close()
  55. // 结果应相同
  56. assert.equal(count1[0].count, count2[0].count)
  57. await fs.unlink(tmpDb)
  58. })