-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_logs_test.patch
More file actions
336 lines (335 loc) · 9.62 KB
/
diff_logs_test.patch
File metadata and controls
336 lines (335 loc) · 9.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
diff --git a/admin/src/pages/__tests__/Logs.test.tsx b/admin/src/pages/__tests__/Logs.test.tsx
new file mode 100644
index 00000000..a54100d5
--- /dev/null
+++ b/admin/src/pages/__tests__/Logs.test.tsx
@@ -0,0 +1,329 @@
+import React from 'react';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import Logs from '../Logs';
+import { useAuth } from '@/context/AuthContext';
+import type { AuthUser } from '@/context/AuthContext';
+import { getApiLogs, getValidationLogs, getAuditLogs, exportLogs } from '@/lib/api';
+import type {
+ ApiLogDto,
+ ValidationLogDto,
+ AuditLogDto,
+ LogsListResponse,
+ LogsExportResponse,
+} from '@/lib/types';
+
+vi.mock('@/context/AuthContext');
+vi.mock('@/lib/api');
+vi.mock('@/components/ui/LoadingSpinner', () => ({
+ LoadingSpinner: ({ size }: { size?: string }) => (
+ <div data-testid={`spinner-${size ?? 'md'}`} role="status">
+ Loading.
+ </div>
+ ),
+}));
+
+const mockUseAuth = vi.mocked(useAuth);
+const mockGetApiLogs = vi.mocked(getApiLogs);
+const mockGetValidationLogs = vi.mocked(getValidationLogs);
+const mockGetAuditLogs = vi.mocked(getAuditLogs);
+const mockExportLogs = vi.mocked(exportLogs);
+
+type AuthContextShape = ReturnType<typeof useAuth>;
+
+const adminUser: AuthUser = {
+ id: 'admin-1',
+ email: 'admin@example.com',
+ tenant_id: 'tenant-1',
+ role: 'system_admin',
+ first_name: 'Admin',
+ last_name: 'User',
+ is_active: true,
+ email_verified: true,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ last_login_at: null,
+};
+
+const createAuthContextMock = (user: AuthUser | null): AuthContextShape => ({
+ currentUser: user,
+ accessToken: null,
+ refreshToken: null,
+ isLoading: false,
+ login: vi.fn(async () => {}),
+ signup: vi.fn(async () => user ?? adminUser),
+ logout: vi.fn(),
+ refreshTokens: vi.fn(async () => true),
+});
+
+const buildResponse = <T,>(logs: T[]): LogsListResponse<T> => ({
+ logs,
+ total: logs.length,
+ page: 1,
+ per_page: 25,
+ has_next: false,
+ has_prev: false,
+});
+
+const apiLogs: ApiLogDto[] = [
+ {
+ id: 'log1',
+ timestamp: '2024-09-20T10:00:00Z',
+ method: 'GET',
+ endpoint: '/v1/rules',
+ status_code: 200,
+ processing_time_ms: 120,
+ ip_address: '203.0.113.10',
+ tenant_id: 'tenant-1',
+ },
+ {
+ id: 'log2',
+ timestamp: '2024-09-20T10:05:00Z',
+ method: 'POST',
+ endpoint: '/v1/rules',
+ status_code: 500,
+ processing_time_ms: 350,
+ error_message: 'Internal error',
+ },
+];
+
+const validationLogs: ValidationLogDto[] = [
+ {
+ id: 'val1',
+ timestamp: '2024-09-19T08:00:00Z',
+ document_id: 'doc-001',
+ tenant_id: 'tenant-1',
+ result: 'pass',
+ score: 92.5,
+ violations_count: 0,
+ rules_applied_count: 10,
+ processing_time_ms: 420,
+ },
+ {
+ id: 'val2',
+ timestamp: '2024-09-19T08:01:00Z',
+ document_id: 'doc-002',
+ result: 'fail',
+ score: 55.2,
+ violations_count: 4,
+ processing_time_ms: 610,
+ },
+];
+
+const auditLogs: AuditLogDto[] = [
+ {
+ id: 'audit1',
+ timestamp: '2024-09-18T12:00:00Z',
+ action: 'LOGIN',
+ description: 'User logged in',
+ resource_type: 'auth',
+ user_id: 'admin-1',
+ ip_address: '198.51.100.5',
+ },
+ {
+ id: 'audit2',
+ timestamp: '2024-09-18T12:05:00Z',
+ action: 'DELETE',
+ description: 'Rule removed',
+ resource_type: 'rules',
+ resource_id: 'rule-12',
+ },
+];
+
+const exportResponse: LogsExportResponse = {
+ download_url: 'https://example.com/logs.csv',
+ filename: 'logs.csv',
+ size_bytes: 1024,
+ expires_at: '2024-09-30T00:00:00Z',
+};
+
+const renderLogs = () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const user = userEvent.setup();
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <Logs />
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+
+ return { user };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockUseAuth.mockReturnValue(createAuthContextMock(adminUser));
+ mockGetApiLogs.mockResolvedValue(buildResponse(apiLogs));
+ mockGetValidationLogs.mockResolvedValue(buildResponse(validationLogs));
+ mockGetAuditLogs.mockResolvedValue(buildResponse(auditLogs));
+ mockExportLogs.mockResolvedValue(exportResponse);
+ vi.spyOn(window, 'open').mockReturnValue(null);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('Logs page', () => {
+ it('blocks non-admin users', () => {
+ const nonAdmin: AuthUser = {
+ ...adminUser,
+ id: 'user-1',
+ email: 'user@example.com',
+ role: 'user',
+ };
+
+ mockUseAuth.mockReturnValue(createAuthContextMock(nonAdmin));
+
+ renderLogs();
+
+ expect(screen.getByText('Access Denied')).toBeInTheDocument();
+ expect(
+ screen.getByText('You need admin privileges to access logs and monitoring.')
+ ).toBeInTheDocument();
+ expect(mockGetApiLogs).not.toHaveBeenCalled();
+ });
+
+ it('renders API logs with status badges', async () => {
+ renderLogs();
+
+ await waitFor(() => {
+ expect(screen.getByText('200 Success')).toBeInTheDocument();
+ expect(screen.getByText('500 Server Error')).toBeInTheDocument();
+ expect(screen.getByText('Internal error')).toBeInTheDocument();
+ });
+ });
+
+ it('updates API logs when status filter changes', async () => {
+ const { user } = renderLogs();
+
+ await waitFor(() => expect(mockGetApiLogs).toHaveBeenCalledTimes(1));
+
+ const statusSelect = screen.getByLabelText('Status') as HTMLSelectElement;
+ await user.selectOptions(statusSelect, 'success');
+
+ await waitFor(() => {
+ const latestCall = mockGetApiLogs.mock.calls.at(-1)?.[0];
+ expect(latestCall?.status).toBe('success');
+ });
+ });
+
+ it('renders validation logs and filters by result', async () => {
+ const { user } = renderLogs();
+
+ await user.click(screen.getByText('Validation Logs'));
+
+ await waitFor(() => {
+ expect(mockGetValidationLogs).toHaveBeenCalled();
+ expect(screen.getByText('doc-001')).toBeInTheDocument();
+ expect(screen.getByText('doc-002')).toBeInTheDocument();
+ });
+
+ const resultSelect = screen.getByLabelText('Result') as HTMLSelectElement;
+ await user.selectOptions(resultSelect, 'pass');
+
+ await waitFor(() => {
+ const latestCall = mockGetValidationLogs.mock.calls.at(-1)?.[0];
+ expect(latestCall?.result).toBe('pass');
+ });
+ });
+
+ it('renders audit logs and filters by action', async () => {
+ const { user } = renderLogs();
+
+ await user.click(screen.getByText('Audit Logs'));
+
+ await waitFor(() => {
+ expect(mockGetAuditLogs).toHaveBeenCalled();
+ expect(screen.getByText('User logged in')).toBeInTheDocument();
+ });
+
+ const actionSelect = screen.getByLabelText('Action') as HTMLSelectElement;
+ await user.selectOptions(actionSelect, 'LOGIN');
+
+ await waitFor(() => {
+ const latestCall = mockGetAuditLogs.mock.calls.at(-1)?.[0];
+ expect(latestCall?.action).toBe('LOGIN');
+ });
+ });
+
+ it('shows error alert when API logs fail to load', async () => {
+ mockGetApiLogs.mockRejectedValueOnce(new Error('API logs unavailable'));
+
+ renderLogs();
+
+ await waitFor(() => {
+ expect(screen.getByText('Unable to load API logs')).toBeInTheDocument();
+ expect(screen.getByText('API logs unavailable')).toBeInTheDocument();
+ });
+ });
+
+ it('shows error alert when validation logs fail to load', async () => {
+ mockGetValidationLogs.mockRejectedValueOnce(new Error('Validation service down'));
+
+ const { user } = renderLogs();
+ await user.click(screen.getByText('Validation Logs'));
+
+ await waitFor(() => {
+ expect(screen.getByText('Unable to load validation logs')).toBeInTheDocument();
+ expect(screen.getByText('Validation service down')).toBeInTheDocument();
+ });
+ });
+
+ it('shows error alert when audit logs fail to load', async () => {
+ mockGetAuditLogs.mockRejectedValueOnce(new Error('Audit service down'));
+
+ const { user } = renderLogs();
+ await user.click(screen.getByText('Audit Logs'));
+
+ await waitFor(() => {
+ expect(screen.getByText('Unable to load audit logs')).toBeInTheDocument();
+ expect(screen.getByText('Audit service down')).toBeInTheDocument();
+ });
+ });
+
+ it('allows exporting logs in CSV and JSON', async () => {
+ const { user } = renderLogs();
+
+ await waitFor(() => expect(mockGetApiLogs).toHaveBeenCalled());
+
+ await user.click(screen.getByText('Export CSV'));
+
+ await waitFor(() => {
+ expect(mockExportLogs).toHaveBeenCalledWith(
+ 'api',
+ expect.objectContaining({
+ format: 'csv',
+ filters: expect.objectContaining({ page: 1, per_page: 25, sort_by: 'timestamp' }),
+ })
+ );
+ expect(window.open).toHaveBeenCalledWith('https://example.com/logs.csv', '_blank', 'noopener');
+ });
+
+ await user.click(screen.getByText('Export JSON'));
+
+ await waitFor(() => {
+ expect(mockExportLogs).toHaveBeenCalledWith(
+ 'api',
+ expect.objectContaining({ format: 'json' })
+ );
+ });
+ });
+
+ it('shows empty state when no API logs are returned', async () => {
+ mockGetApiLogs.mockResolvedValueOnce(buildResponse<ApiLogDto>([]));
+
+ renderLogs();
+
+ await waitFor(() => {
+ expect(screen.getByText('No API logs available')).toBeInTheDocument();
+ });
+ });
+});