atomic.test.js 974 B

123456789101112131415161718192021222324252627
  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 { writeAtomicBatch } from '../../src/storage/atomic.js'
  7. test('writeAtomicBatch:后续文件失败时,已替换文件恢复原样', async () => {
  8. const root = await fs.mkdtemp(path.join(os.tmpdir(), 'wnw-atomic-'))
  9. try {
  10. await fs.writeFile(path.join(root, 'a.txt'), 'old', 'utf8')
  11. await fs.mkdir(path.join(root, 'b.txt'))
  12. await assert.rejects(() =>
  13. writeAtomicBatch(root, [
  14. { path: 'a.txt', content: 'new' },
  15. { path: 'b.txt', content: 'bad' },
  16. ])
  17. )
  18. assert.equal(await fs.readFile(path.join(root, 'a.txt'), 'utf8'), 'old')
  19. const bStat = await fs.stat(path.join(root, 'b.txt'))
  20. assert.equal(bStat.isDirectory(), true, '既有目录不应被批量写删除')
  21. } finally {
  22. await fs.rm(root, { recursive: true, force: true })
  23. }
  24. })