restore.test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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()
  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 { readdir } = await import('fs')
  75. vi.mocked(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. ])
  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 { readdir } = await import('fs')
  85. vi.mocked(readdir).mockResolvedValue(['some-other-file.txt'])
  86. const latest = await restore.findLatestBackup()
  87. expect(latest).toBeNull()
  88. })
  89. it('应该在读取目录失败时返回null', async () => {
  90. const { readdir } = await import('fs')
  91. const { logger } = await import('../logger')
  92. vi.mocked(readdir).mockRejectedValueOnce(new Error('读取目录失败'))
  93. const latest = await restore.findLatestBackup()
  94. expect(latest).toBeNull()
  95. expect(logger.error).toHaveBeenCalled()
  96. })
  97. })
  98. describe('listBackups', () => {
  99. it('应该返回所有备份文件列表', async () => {
  100. const { readdir } = await import('fs')
  101. vi.mocked(readdir).mockResolvedValue([
  102. 'backup-2024-01-01.dump',
  103. 'some-other-file.txt',
  104. 'backup-2024-01-02.dump',
  105. ])
  106. const backups = await restore.listBackups()
  107. expect(backups).toEqual([
  108. 'backup-2024-01-01.dump',
  109. 'backup-2024-01-02.dump',
  110. ])
  111. })
  112. it('应该在读取目录失败时返回空数组', async () => {
  113. const { readdir } = await import('fs')
  114. const { logger } = await import('../logger')
  115. vi.mocked(readdir).mockRejectedValueOnce(new Error('读取目录失败'))
  116. const backups = await restore.listBackups()
  117. expect(backups).toEqual([])
  118. expect(logger.error).toHaveBeenCalled()
  119. })
  120. })
  121. describe('backupExists', () => {
  122. it('应该返回true当备份文件存在时', async () => {
  123. const { access } = await import('fs')
  124. const exists = await restore.backupExists('/path/to/backup.dump')
  125. expect(exists).toBe(true)
  126. expect(access).toHaveBeenCalledWith('/path/to/backup.dump')
  127. })
  128. it('应该返回false当备份文件不存在时', async () => {
  129. const { access } = await import('fs')
  130. vi.mocked(access).mockRejectedValueOnce(new Error('文件不存在'))
  131. const exists = await restore.backupExists('/path/to/backup.dump')
  132. expect(exists).toBe(false)
  133. })
  134. })
  135. describe('getBackupInfo', () => {
  136. it('应该返回备份文件信息', async () => {
  137. const { stat } = await import('fs')
  138. const testDate = new Date()
  139. vi.mocked(stat).mockResolvedValueOnce({
  140. size: 1048576,
  141. mtime: testDate,
  142. } as any)
  143. const info = await restore.getBackupInfo('/path/to/backup.dump')
  144. expect(info).toEqual({
  145. size: 1048576,
  146. mtime: testDate,
  147. formattedSize: '1 MB',
  148. })
  149. })
  150. it('应该在获取信息失败时抛出错误', async () => {
  151. const { stat } = await import('fs')
  152. vi.mocked(stat).mockRejectedValueOnce(new Error('获取文件信息失败'))
  153. await expect(restore.getBackupInfo('/path/to/backup.dump')).rejects.toThrow('获取备份信息失败')
  154. })
  155. })
  156. describe('formatFileSize', () => {
  157. it('应该正确格式化文件大小', () => {
  158. const formatFileSize = (restore as any).formatFileSize
  159. expect(formatFileSize(0)).toBe('0 B')
  160. expect(formatFileSize(1024)).toBe('1 KB')
  161. expect(formatFileSize(1048576)).toBe('1 MB')
  162. expect(formatFileSize(1073741824)).toBe('1 GB')
  163. })
  164. })
  165. })