backup.test.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
  2. import { DatabaseBackup } from '../backup'
  3. import { promises as fs } from 'fs'
  4. import path from 'path'
  5. // Mock pg-dump-restore
  6. vi.mock('pg-dump-restore', () => ({
  7. pgDump: vi.fn().mockResolvedValue(undefined),
  8. pgRestore: vi.fn().mockResolvedValue(undefined),
  9. }))
  10. // Mock fs for tests
  11. vi.mock('fs', () => ({
  12. promises: {
  13. mkdir: vi.fn().mockResolvedValue(undefined),
  14. chmod: vi.fn().mockResolvedValue(undefined),
  15. readdir: vi.fn().mockResolvedValue([]),
  16. stat: vi.fn().mockResolvedValue({ size: 1024, mtimeMs: Date.now(), mode: 0o600, mtime: new Date() }),
  17. access: vi.fn().mockResolvedValue(undefined),
  18. unlink: vi.fn().mockResolvedValue(undefined),
  19. rm: vi.fn().mockResolvedValue(undefined),
  20. writeFile: vi.fn().mockResolvedValue(undefined),
  21. utimes: vi.fn().mockResolvedValue(undefined),
  22. }
  23. }))
  24. // Mock logger
  25. vi.mock('../logger', () => ({
  26. logger: {
  27. db: vi.fn(),
  28. error: vi.fn(),
  29. api: vi.fn(),
  30. middleware: vi.fn(),
  31. },
  32. }))
  33. describe('DatabaseBackup', () => {
  34. let backup: DatabaseBackup
  35. beforeEach(() => {
  36. vi.clearAllMocks()
  37. backup = DatabaseBackup.getInstance()
  38. })
  39. afterEach(() => {
  40. vi.restoreAllMocks()
  41. })
  42. describe('getInstance', () => {
  43. it('应该返回单例实例', () => {
  44. const instance1 = DatabaseBackup.getInstance()
  45. const instance2 = DatabaseBackup.getInstance()
  46. expect(instance1).toBe(instance2)
  47. })
  48. })
  49. describe('ensureBackupDir', () => {
  50. it('应该创建备份目录并设置权限', async () => {
  51. const fs = await import('fs')
  52. await backup.ensureBackupDir()
  53. expect(fs.promises.mkdir).toHaveBeenCalledWith('./backups', { recursive: true })
  54. expect(fs.promises.chmod).toHaveBeenCalledWith('./backups', 0o700)
  55. })
  56. it('应该在创建目录失败时抛出错误', async () => {
  57. const fs = await import('fs')
  58. const { logger } = await import('../logger')
  59. vi.mocked(fs.promises.mkdir).mockRejectedValueOnce(new Error('创建目录失败'))
  60. await expect(backup.ensureBackupDir()).rejects.toThrow('创建目录失败')
  61. expect(logger.error).toHaveBeenCalled()
  62. })
  63. })
  64. describe('getDbConfig', () => {
  65. it('应该返回正确的数据库配置', () => {
  66. process.env.DB_HOST = 'test-host'
  67. process.env.DB_PORT = '5433'
  68. process.env.DB_DATABASE = 'test-db'
  69. process.env.DB_USERNAME = 'test-user'
  70. process.env.DB_PASSWORD = 'test-password'
  71. const config = (backup as any).getDbConfig()
  72. expect(config).toEqual({
  73. host: 'test-host',
  74. port: 5433,
  75. database: 'test-db',
  76. username: 'test-user',
  77. password: 'test-password',
  78. })
  79. })
  80. it('应该使用默认值当环境变量未设置时', () => {
  81. delete process.env.DB_HOST
  82. delete process.env.DB_PORT
  83. delete process.env.DB_DATABASE
  84. delete process.env.DB_USERNAME
  85. delete process.env.DB_PASSWORD
  86. const config = (backup as any).getDbConfig()
  87. expect(config).toEqual({
  88. host: 'localhost',
  89. port: 5432,
  90. database: 'postgres',
  91. username: 'postgres',
  92. password: '',
  93. })
  94. })
  95. })
  96. describe('formatFileSize', () => {
  97. it('应该正确格式化文件大小', () => {
  98. const formatFileSize = (backup as any).formatFileSize
  99. expect(formatFileSize(0)).toBe('0 B')
  100. expect(formatFileSize(1024)).toBe('1 KB')
  101. expect(formatFileSize(1048576)).toBe('1 MB')
  102. expect(formatFileSize(1073741824)).toBe('1 GB')
  103. })
  104. })
  105. describe('backupExists', () => {
  106. it('应该返回true当备份文件存在时', async () => {
  107. const fs = await import('fs')
  108. const exists = await backup.backupExists('/path/to/backup.dump')
  109. expect(exists).toBe(true)
  110. expect(fs.promises.access).toHaveBeenCalledWith('/path/to/backup.dump')
  111. })
  112. it('应该返回false当备份文件不存在时', async () => {
  113. const fs = await import('fs')
  114. vi.mocked(fs.promises.access).mockRejectedValueOnce(new Error('文件不存在'))
  115. const exists = await backup.backupExists('/path/to/backup.dump')
  116. expect(exists).toBe(false)
  117. })
  118. })
  119. describe('cleanupOldBackups', () => {
  120. it('应该清理7天前的旧备份', async () => {
  121. const fs = await import('fs')
  122. const { logger } = await import('../logger')
  123. const now = Date.now()
  124. const oldFileTime = now - (8 * 24 * 60 * 60 * 1000) // 8天前
  125. const newFileTime = now - (6 * 24 * 60 * 60 * 1000) // 6天前
  126. vi.mocked(fs.promises.readdir).mockResolvedValue(['backup-old.dump', 'backup-new.dump'] as any)
  127. vi.mocked(fs.promises.stat)
  128. .mockResolvedValueOnce({ mtimeMs: oldFileTime } as any)
  129. .mockResolvedValueOnce({ mtimeMs: newFileTime } as any)
  130. await backup.cleanupOldBackups()
  131. expect(fs.promises.unlink).toHaveBeenCalledTimes(1)
  132. expect(fs.promises.unlink).toHaveBeenCalledWith(path.join('./backups', 'backup-old.dump'))
  133. expect(logger.db).toHaveBeenCalledWith('删除旧备份文件: backup-old.dump')
  134. })
  135. it('应该在清理失败时记录错误但不抛出', async () => {
  136. const fs = await import('fs')
  137. const { logger } = await import('../logger')
  138. vi.mocked(fs.promises.readdir).mockRejectedValueOnce(new Error('读取目录失败'))
  139. await expect(backup.cleanupOldBackups()).resolves.not.toThrow()
  140. expect(logger.error).toHaveBeenCalled()
  141. })
  142. })
  143. describe('startScheduledBackups', () => {
  144. it('应该启动定时备份任务', async () => {
  145. const cron = await import('node-cron')
  146. const { logger } = await import('../logger')
  147. backup.startScheduledBackups()
  148. // expect(cron.default.schedule).toHaveBeenCalledWith('0 2 * * *', expect.any(Function))
  149. expect(logger.db).toHaveBeenCalledWith('备份调度已启动: 0 2 * * *')
  150. })
  151. })
  152. describe('stopScheduledBackups', () => {
  153. it('应该停止定时备份任务', async () => {
  154. const { logger } = await import('../logger')
  155. // 先启动再停止
  156. backup.startScheduledBackups()
  157. backup.stopScheduledBackups()
  158. expect(logger.db).toHaveBeenCalledWith('备份调度已停止')
  159. })
  160. })
  161. })