restore.test.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
  2. import { DatabaseRestore } from '../restore'
  3. import { promises as fs } from 'fs'
  4. import path from 'path'
  5. // Mock pg-dump-restore
  6. vi.mock('pg-dump-restore', () => ({
  7. pgRestore: vi.fn().mockResolvedValue(undefined),
  8. }))
  9. // Mock fs with importOriginal for partial mocking
  10. vi.mock('fs', async (importOriginal) => {
  11. const actual = await importOriginal() as typeof import('fs')
  12. return {
  13. ...actual,
  14. promises: {
  15. ...actual.promises,
  16. readdir: vi.fn().mockResolvedValue([]),
  17. access: vi.fn().mockResolvedValue(undefined),
  18. stat: vi.fn().mockResolvedValue({ size: 1024, mtime: new Date() }),
  19. },
  20. }
  21. })
  22. // Mock logger
  23. vi.mock('../logger', () => ({
  24. logger: {
  25. db: vi.fn(),
  26. error: vi.fn(),
  27. api: vi.fn(),
  28. middleware: vi.fn(),
  29. },
  30. }))
  31. describe('DatabaseRestore', () => {
  32. let restore: DatabaseRestore
  33. beforeEach(() => {
  34. vi.clearAllMocks()
  35. restore = new DatabaseRestore()
  36. })
  37. afterEach(() => {
  38. vi.restoreAllMocks()
  39. })
  40. describe('getDbConfig', () => {
  41. it('应该返回正确的数据库配置', () => {
  42. process.env.DB_HOST = 'test-host'
  43. process.env.DB_PORT = '5433'
  44. process.env.DB_DATABASE = 'test-db'
  45. process.env.DB_USERNAME = 'test-user'
  46. process.env.DB_PASSWORD = 'test-password'
  47. const config = (restore as any).getDbConfig()
  48. expect(config).toEqual({
  49. host: 'test-host',
  50. port: 5433,
  51. database: 'test-db',
  52. username: 'test-user',
  53. password: 'test-password',
  54. })
  55. })
  56. it('应该使用默认值当环境变量未设置时', () => {
  57. delete process.env.DB_HOST
  58. delete process.env.DB_PORT
  59. delete process.env.DB_DATABASE
  60. delete process.env.DB_USERNAME
  61. delete process.env.DB_PASSWORD
  62. const config = (restore as any).getDbConfig()
  63. expect(config).toEqual({
  64. host: 'localhost',
  65. port: 5432,
  66. database: 'postgres',
  67. username: 'postgres',
  68. password: '',
  69. })
  70. })
  71. })
  72. describe('findLatestBackup', () => {
  73. it('应该返回最新的备份文件', async () => {
  74. const fs = await import('fs')
  75. vi.mocked(fs.promises.readdir).mockResolvedValue([
  76. 'backup-2024-01-01T00-00-00Z.dump',
  77. 'backup-2024-01-03T00-00-00Z.dump',
  78. 'backup-2024-01-02T00-00-00Z.dump',
  79. ] as any)
  80. const latest = await restore.findLatestBackup()
  81. expect(latest).toBe(path.join('./backups', 'backup-2024-01-03T00-00-00Z.dump'))
  82. })
  83. it('应该返回null当没有备份文件时', async () => {
  84. const fs = await import('fs')
  85. vi.mocked(fs.promises.readdir).mockResolvedValue([
  86. 'some-other-file.txt'
  87. ] as any)
  88. const latest = await restore.findLatestBackup()
  89. expect(latest).toBeNull()
  90. })
  91. it('应该在读取目录失败时返回null', async () => {
  92. const fs = await import('fs')
  93. const { logger } = await import('../logger')
  94. vi.mocked(fs.promises.readdir).mockRejectedValueOnce(new Error('读取目录失败'))
  95. const latest = await restore.findLatestBackup()
  96. expect(latest).toBeNull()
  97. expect(logger.error).toHaveBeenCalled()
  98. })
  99. })
  100. describe('listBackups', () => {
  101. it('应该返回所有备份文件列表', async () => {
  102. const fs = await import('fs')
  103. vi.mocked(fs.promises.readdir).mockResolvedValue([
  104. 'backup-2024-01-01.dump',
  105. 'some-other-file.txt',
  106. 'backup-2024-01-02.dump',
  107. ] as any)
  108. const backups = await restore.listBackups()
  109. expect(backups).toEqual([
  110. 'backup-2024-01-01.dump',
  111. 'backup-2024-01-02.dump',
  112. ])
  113. })
  114. it('应该在读取目录失败时返回空数组', async () => {
  115. const fs = await import('fs')
  116. const { logger } = await import('../logger')
  117. vi.mocked(fs.promises.readdir).mockRejectedValueOnce(new Error('读取目录失败'))
  118. const backups = await restore.listBackups()
  119. expect(backups).toEqual([])
  120. expect(logger.error).toHaveBeenCalled()
  121. })
  122. })
  123. describe('backupExists', () => {
  124. it('应该返回true当备份文件存在时', async () => {
  125. const fs = await import('fs')
  126. const exists = await restore.backupExists('/path/to/backup.dump')
  127. expect(exists).toBe(true)
  128. expect(fs.promises.access).toHaveBeenCalledWith('/path/to/backup.dump')
  129. })
  130. it('应该返回false当备份文件不存在时', async () => {
  131. const fs = await import('fs')
  132. vi.mocked(fs.promises.access).mockRejectedValueOnce(new Error('文件不存在'))
  133. const exists = await restore.backupExists('/path/to/backup.dump')
  134. expect(exists).toBe(false)
  135. })
  136. })
  137. describe('getBackupInfo', () => {
  138. it('应该返回备份文件信息', async () => {
  139. const fs = await import('fs')
  140. const testDate = new Date()
  141. vi.mocked(fs.promises.stat).mockResolvedValueOnce({
  142. size: 1048576,
  143. mtime: testDate,
  144. } as any)
  145. const info = await restore.getBackupInfo('/path/to/backup.dump')
  146. expect(info).toEqual({
  147. size: 1048576,
  148. mtime: testDate,
  149. formattedSize: '1 MB',
  150. })
  151. })
  152. it('应该在获取信息失败时抛出错误', async () => {
  153. const fs = await import('fs')
  154. vi.mocked(fs.promises.stat).mockRejectedValueOnce(new Error('获取文件信息失败'))
  155. await expect(restore.getBackupInfo('/path/to/backup.dump')).rejects.toThrow('获取备份信息失败')
  156. })
  157. })
  158. describe('formatFileSize', () => {
  159. it('应该正确格式化文件大小', () => {
  160. const formatFileSize = (restore as any).formatFileSize
  161. expect(formatFileSize(0)).toBe('0 B')
  162. expect(formatFileSize(1024)).toBe('1 KB')
  163. expect(formatFileSize(1048576)).toBe('1 MB')
  164. expect(formatFileSize(1073741824)).toBe('1 GB')
  165. })
  166. })
  167. })