GitHubBackupSettingsWiring.test.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /**
  2. * Backup settings wiring: local backup restore/delete target the clicked
  3. * file and only after the confirm, "Backup Now"/"Run Now" hit their run
  4. * endpoints, the connection test uses the stored token unless a new one is
  5. * typed, Clear empties the backup history after a confirm, and a refused
  6. * delete says so.
  7. */
  8. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
  9. import { screen, waitFor, within } from '@testing-library/react';
  10. import userEvent from '@testing-library/user-event';
  11. import { http, HttpResponse } from 'msw';
  12. import { render } from '../utils';
  13. import { server } from '../mocks/server';
  14. import { api, setAuthToken } from '../../api/client';
  15. import { GitHubBackupSettings } from '../../components/GitHubBackupSettings';
  16. type Captured = { method: string; path: string; search: string };
  17. let captured: Captured[];
  18. const CONFIG = {
  19. id: 1,
  20. provider: 'github',
  21. repository_url: 'https://github.com/test/backup-repo',
  22. has_token: true,
  23. branch: 'main',
  24. enabled: true,
  25. schedule_enabled: false,
  26. schedule_type: 'daily',
  27. schedule_time: '02:00',
  28. backup_kprofiles: true,
  29. backup_cloud_profiles: false,
  30. backup_spools: true,
  31. backup_archives: true,
  32. backup_settings: true,
  33. allow_insecure_http: false,
  34. last_backup_at: null,
  35. last_backup_status: null,
  36. };
  37. const BACKUPS = [
  38. { filename: 'bambuddy-backup-2026-10-01.zip', size: 1048576, created_at: '2026-10-01T03:00:00Z' },
  39. { filename: 'bambuddy backup #2.zip', size: 2097152, created_at: '2026-10-02T03:00:00Z' },
  40. ];
  41. function record(request: Request) {
  42. const url = new URL(request.url);
  43. captured.push({ method: request.method, path: url.pathname, search: url.search });
  44. }
  45. const writes = () => captured.filter((c) => c.method !== 'GET');
  46. function fileRow(filename: string): HTMLElement {
  47. return screen.getByText(filename).closest('div.flex.items-center.justify-between') as HTMLElement;
  48. }
  49. beforeEach(() => {
  50. captured = [];
  51. server.use(
  52. http.get('*/api/v1/github-backup/config', () => HttpResponse.json(CONFIG)),
  53. http.get('*/api/v1/github-backup/status', () =>
  54. HttpResponse.json({
  55. configured: true,
  56. enabled: true,
  57. is_running: false,
  58. restore_running: false,
  59. progress: null,
  60. last_backup_at: null,
  61. last_backup_status: null,
  62. next_run: null,
  63. }),
  64. ),
  65. http.get('*/api/v1/github-backup/logs', () =>
  66. HttpResponse.json([
  67. {
  68. id: 1, config_id: 1, started_at: '2026-10-01T09:00:00', completed_at: '2026-10-01T09:00:05',
  69. status: 'success', trigger: 'manual', commit_sha: null, files_changed: 1, error_message: null,
  70. },
  71. ]),
  72. ),
  73. http.get('*/api/v1/local-backup/status', () =>
  74. HttpResponse.json({
  75. enabled: true, is_running: false, last_backup_at: null, last_status: null,
  76. last_message: null, next_run: null, path: '/data/backups',
  77. }),
  78. ),
  79. http.get('*/api/v1/local-backup/path-check', () => HttpResponse.json({ writable: true, path: '/data/backups', code: 'ok' })),
  80. http.get('*/api/v1/local-backup/backups', () => HttpResponse.json(BACKUPS)),
  81. http.post('*/api/v1/local-backup/backups/:name/restore', ({ request }) => {
  82. record(request);
  83. return HttpResponse.json({ success: true, message: 'restored' });
  84. }),
  85. http.delete('*/api/v1/local-backup/backups/:name', ({ request }) => {
  86. record(request);
  87. return HttpResponse.json({ success: true, message: 'deleted' });
  88. }),
  89. http.post('*/api/v1/local-backup/run', ({ request }) => {
  90. record(request);
  91. return HttpResponse.json({ success: true, message: 'ok', filename: 'x.zip' });
  92. }),
  93. http.post('*/api/v1/github-backup/run', ({ request }) => {
  94. record(request);
  95. return HttpResponse.json({ success: true, message: 'ok', files_changed: 0 });
  96. }),
  97. http.delete('*/api/v1/github-backup/logs', ({ request }) => {
  98. record(request);
  99. return HttpResponse.json({ deleted: 1, message: 'ok' });
  100. }),
  101. );
  102. });
  103. afterEach(() => {
  104. vi.restoreAllMocks();
  105. setAuthToken(null);
  106. });
  107. describe('GitHubBackupSettings wiring', () => {
  108. it('restore of a local backup asks first, then POSTs restore for the clicked file (URL-encoded)', async () => {
  109. const user = userEvent.setup();
  110. render(<GitHubBackupSettings />);
  111. await screen.findByText('bambuddy backup #2.zip');
  112. await user.click(within(fileRow('bambuddy backup #2.zip')).getByTitle('Restore'));
  113. expect(writes()).toHaveLength(0);
  114. await user.click(screen.getByRole('button', { name: /^restore backup$/i }));
  115. await waitFor(() => expect(writes()).toHaveLength(1));
  116. expect(writes()[0]).toMatchObject({
  117. method: 'POST',
  118. path: '/api/v1/local-backup/backups/bambuddy%20backup%20%232.zip/restore',
  119. });
  120. });
  121. it('cancelling the restore confirm sends nothing', async () => {
  122. const user = userEvent.setup();
  123. render(<GitHubBackupSettings />);
  124. await screen.findByText('bambuddy-backup-2026-10-01.zip');
  125. await user.click(within(fileRow('bambuddy-backup-2026-10-01.zip')).getByTitle('Restore'));
  126. await user.click(screen.getByRole('button', { name: /^cancel$/i }));
  127. await waitFor(() => expect(screen.queryByRole('button', { name: /^restore backup$/i })).not.toBeInTheDocument());
  128. expect(writes()).toHaveLength(0);
  129. });
  130. it('delete of a local backup asks first, then DELETEs the clicked file; cancel sends nothing', async () => {
  131. const user = userEvent.setup();
  132. render(<GitHubBackupSettings />);
  133. await screen.findByText('bambuddy-backup-2026-10-01.zip');
  134. await user.click(within(fileRow('bambuddy-backup-2026-10-01.zip')).getByTitle('Delete'));
  135. await user.click(screen.getByRole('button', { name: /^cancel$/i }));
  136. expect(writes()).toHaveLength(0);
  137. await user.click(within(fileRow('bambuddy-backup-2026-10-01.zip')).getByTitle('Delete'));
  138. // The confirm modal's button (the row button has a title, the modal's does not)
  139. const confirm = screen.getAllByRole('button', { name: /^delete$/i }).find((b) => !b.hasAttribute('title'));
  140. await user.click(confirm as HTMLElement);
  141. await waitFor(() => expect(writes()).toHaveLength(1));
  142. expect(writes()[0]).toMatchObject({
  143. method: 'DELETE',
  144. path: '/api/v1/local-backup/backups/bambuddy-backup-2026-10-01.zip',
  145. });
  146. });
  147. it('Run Now triggers the local backup', async () => {
  148. const user = userEvent.setup();
  149. render(<GitHubBackupSettings />);
  150. await user.click(await screen.findByRole('button', { name: /run now/i }));
  151. await waitFor(() => expect(writes()).toHaveLength(1));
  152. expect(writes()[0]).toMatchObject({ method: 'POST', path: '/api/v1/local-backup/run' });
  153. });
  154. it('Backup Now triggers the Git backup', async () => {
  155. const user = userEvent.setup();
  156. render(<GitHubBackupSettings />);
  157. await user.click(await screen.findByRole('button', { name: /backup now/i }));
  158. await waitFor(() => expect(writes()).toHaveLength(1));
  159. expect(writes()[0]).toMatchObject({ method: 'POST', path: '/api/v1/github-backup/run' });
  160. });
  161. it('Test with the token field blank uses the stored token', async () => {
  162. const stored = vi.spyOn(api, 'testGitHubStoredConnection').mockResolvedValue({ success: true, message: 'ok', is_private: true } as never);
  163. const typed = vi.spyOn(api, 'testGitHubConnection').mockResolvedValue({ success: true, message: 'ok', is_private: true } as never);
  164. const user = userEvent.setup();
  165. render(<GitHubBackupSettings />);
  166. await user.click(await screen.findByRole('button', { name: /^test$/i }));
  167. await waitFor(() => expect(stored).toHaveBeenCalledTimes(1));
  168. expect(typed).not.toHaveBeenCalled();
  169. });
  170. it('Test with a newly typed token tests those credentials, not the stored ones', async () => {
  171. const stored = vi.spyOn(api, 'testGitHubStoredConnection').mockResolvedValue({ success: true, message: 'ok', is_private: true } as never);
  172. const typed = vi.spyOn(api, 'testGitHubConnection').mockResolvedValue({ success: true, message: 'ok', is_private: true } as never);
  173. const user = userEvent.setup();
  174. render(<GitHubBackupSettings />);
  175. await user.type(await screen.findByPlaceholderText(/enter new token to update/i), 'test-token-value-1');
  176. await user.click(screen.getByRole('button', { name: /^test$/i }));
  177. await waitFor(() => expect(typed).toHaveBeenCalledTimes(1));
  178. expect(typed).toHaveBeenCalledWith('https://github.com/test/backup-repo', 'test-token-value-1', 'github');
  179. expect(stored).not.toHaveBeenCalled();
  180. });
  181. it('Clear in the backup history asks first, then deletes all logs (keep_last=0); cancel sends nothing', async () => {
  182. const user = userEvent.setup();
  183. render(<GitHubBackupSettings />);
  184. const history = (await screen.findByText('History')).closest('div[id="card-backup-history"]') as HTMLElement;
  185. await user.click(within(history).getByRole('button', { name: /^clear$/i }));
  186. const dialog = () => screen.getByText('Clear backup history?').closest('div.fixed') as HTMLElement;
  187. await user.click(within(dialog()).getByRole('button', { name: 'Cancel' }));
  188. expect(screen.queryByText('Clear backup history?')).toBeNull();
  189. expect(writes()).toEqual([]);
  190. await user.click(within(history).getByRole('button', { name: /^clear$/i }));
  191. await user.click(within(dialog()).getByRole('button', { name: /^clear$/i }));
  192. await waitFor(() => expect(writes()).toHaveLength(1));
  193. expect(writes()[0]).toMatchObject({ method: 'DELETE', path: '/api/v1/github-backup/logs', search: '?keep_last=0' });
  194. });
  195. it.each([
  196. ['refused (200, success false)', () => HttpResponse.json({ success: false, message: 'Invalid backup file' }), 'Invalid backup file'],
  197. ['failed (500)', () => HttpResponse.json({ detail: 'Disk is read-only' }, { status: 500 }), 'Disk is read-only'],
  198. ])('a %s local backup delete is reported', async (_label, reply, text) => {
  199. server.use(http.delete('*/api/v1/local-backup/backups/:name', reply));
  200. const user = userEvent.setup();
  201. render(<GitHubBackupSettings />);
  202. await user.click(within(await waitFor(() => fileRow('bambuddy-backup-2026-10-01.zip'))).getByTitle('Delete'));
  203. const confirm = screen.getAllByRole('button', { name: /^delete$/i }).find((b) => !b.hasAttribute('title'));
  204. await user.click(confirm!);
  205. expect(await screen.findByText(text)).toBeInTheDocument();
  206. });
  207. it('a non-admin gets no Restore (or Download) button on local backups', async () => {
  208. setAuthToken('test-token', 'session');
  209. server.use(
  210. http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
  211. http.get('*/api/v1/auth/me', () =>
  212. HttpResponse.json({ id: 2, username: 'operator', is_admin: false, permissions: ['settings:read', 'settings:update'] }),
  213. ),
  214. );
  215. render(<GitHubBackupSettings />);
  216. await screen.findByText('bambuddy-backup-2026-10-01.zip');
  217. // Wait for the auth state to settle (admin is assumed while auth status loads)
  218. await waitFor(() =>
  219. expect(within(fileRow('bambuddy-backup-2026-10-01.zip')).queryByTitle('Restore')).not.toBeInTheDocument(),
  220. );
  221. expect(within(fileRow('bambuddy-backup-2026-10-01.zip')).queryByTitle('Download')).not.toBeInTheDocument();
  222. });
  223. });