-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathEventDefinitionFormContainer.test.tsx
More file actions
362 lines (304 loc) · 13 KB
/
Copy pathEventDefinitionFormContainer.test.tsx
File metadata and controls
362 lines (304 loc) · 13 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import * as React from 'react';
import { render, screen } from 'wrappedTestingLibrary';
import userEvent from '@testing-library/user-event';
import { defaultUser as mockDefaultUser } from 'defaultMockValues';
import useLocation from 'routing/useLocation';
import useSendTelemetry from 'logic/telemetry/useSendTelemetry';
import { asMock } from 'helpers/mocking';
import { simpleEventDefinition as mockEventDefinition } from 'fixtures/eventDefinition';
import useScopePermissions from 'hooks/useScopePermissions';
import useCurrentUser from 'hooks/useCurrentUser';
import usePluginEntities from 'hooks/usePluginEntities';
import useEventDefinitionConfigFromLocalStorage from 'components/event-definitions/hooks/useEventDefinitionConfigFromLocalStorage';
import { SYSTEM_EVENT_DEFINITION_TYPE as mockSYSTEM_EVENT_DEFINITION_TYPE } from 'components/event-definitions/constants';
import type { PermissionsByScopeReturnType } from 'hooks/useScopePermissions';
import type { GenericEntityType } from 'logic/lookup-tables/types';
import fetch from 'logic/rest/FetchProvider';
import EventDefinitionFormContainer from './EventDefinitionFormContainer';
const mockAggregationEventDefinition = {
...mockEventDefinition,
config: {
...mockEventDefinition.config,
query: 'http_response_code:400',
},
};
const exampleEntityScopeMutable: PermissionsByScopeReturnType = {
loadingScopePermissions: false,
scopePermissions: { is_mutable: true },
checkPermissions: (_inEntity: Partial<GenericEntityType>) => true,
};
const exampleEntityScopeImmutable: PermissionsByScopeReturnType = {
loadingScopePermissions: false,
scopePermissions: { is_mutable: false },
checkPermissions: (_inEntity: Partial<GenericEntityType>) => false,
};
jest.mock('react-router-dom', () => {
const original = jest.requireActual('react-router-dom');
return {
...original,
useNavigate: () => jest.fn(),
};
});
jest.mock('stores/connect', () => ({
__esModule: true,
useStore: jest.fn((store) => store.getInitialState()),
default: jest.fn(
(
Component: React.ComponentType<React.ComponentProps<any>>,
stores: { [key: string]: any },
_mapProps: (args: { [key: string]: any }) => any,
) => {
const storeProps = Object.fromEntries(
Object.entries(stores).map(([key, store]) => [key, store.getInitialState()]),
);
const componentProps = {
...storeProps,
eventDefinition: {
...mockEventDefinition,
config: {
...mockEventDefinition.config,
query: 'http_response_code:400',
},
},
};
const ConnectStoreWrapper = () => <Component {...componentProps} />;
return ConnectStoreWrapper;
},
),
}));
jest.mock('logic/rest/FetchProvider', () => {
const mockFetch = jest.fn(() => Promise.resolve({}));
const MockBuilder = () => ({ json: () => ({ build: () => Promise.resolve({}) }) });
return { __esModule: true, default: mockFetch, Builder: MockBuilder };
});
const mockEntityTypes = {
aggregation_functions: [
'avg',
'card',
'count',
'max',
'min',
'sum',
'stddev',
'sumofsquares',
'variance',
'percentage',
'percentile',
'latest',
],
field_provider_types: ['template-v1', 'lookup-v1'],
processor_types: ['aggregation-v1', mockSYSTEM_EVENT_DEFINITION_TYPE, 'correlation-v1', 'anomaly-v1', 'sigma-v1'],
storage_handler_types: ['persist-to-streams-v1'],
};
const mockEventNotifications = [
{
id: 'mock-notification-id',
title: 'mock-notification-title',
description: 'mock-notification-description',
config: {
body_template: '',
email_recipients: ['test-user@graylog.com'],
html_body_template: '',
lookup_recipient_emails: false,
lookup_reply_to_email: false,
lookup_sender_email: false,
recipients_lut_key: null,
recipients_lut_name: null,
reply_to: '',
reply_to_lut_key: null,
reply_to_lut_name: null,
sender: 'info-test@graylog.com',
sender_lut_key: null,
sender_lut_name: null,
subject: 'Mock test email notification subject',
time_zone: 'UTC',
type: 'email-notification-v1',
user_recipients: [],
},
},
];
jest.mock('stores/event-notifications/EventNotificationsStore', () => ({
EventNotificationsActions: { listAll: jest.fn() },
EventNotificationsStore: {
listen: () => jest.fn(),
listAll: jest.fn(() => Promise.resolve({ notifications: mockEventNotifications })),
getInitialState: () => ({
all: mockEventNotifications,
allLegacyTypes: [],
notifications: mockEventNotifications,
query: '',
pagination: {
count: 1,
page: 1,
pageSize: 10,
total: 1,
grandTotal: 1,
},
}),
},
}));
jest.mock('stores/configurations/ConfigurationsStore', () => ({
ConfigurationsActions: {
listEventsClusterConfig: jest.fn(() =>
Promise.resolve({
events_catchup_window: 3600000,
events_notification_default_backlog: 50,
events_notification_retry_period: 300000,
events_notification_tcp_keepalive: false,
events_search_timeout: 60000,
}),
),
},
}));
jest.mock('stores/users/CurrentUserStore', () => ({
__esModule: true,
CurrentUserStore: {
listen: () => jest.fn(),
getInitialState: () => ({ currentUser: mockDefaultUser.toJSON() }),
},
}));
jest.mock('logic/telemetry/withTelemetry', () => ({
__esModule: true,
default: (Component: React.FC) => (props: any) => (
<Component
{...props}
streams={[{ id: 'stream-id', title: 'stream-title' }]}
sendTelemetry={() => {}}
onChange={() => {}}
currentUser={mockDefaultUser}
validation={{ errors: {} }}
/>
),
}));
jest.mock('components/event-definitions/hooks/useEventDefinitionConfigFromLocalStorage');
jest.mock('routing/useLocation');
jest.mock('logic/telemetry/useSendTelemetry');
jest.mock('hooks/useScopePermissions');
jest.mock('hooks/useCurrentUser');
jest.mock('hooks/usePluginEntities');
describe('EventDefinitionFormContainer', () => {
beforeEach(() => {
asMock(fetch).mockResolvedValue(mockEntityTypes);
asMock(useLocation).mockImplementation(() => ({
pathname: '/event-definitions',
search: '',
hash: '',
state: null,
key: 'mock-key',
}));
asMock(useSendTelemetry).mockImplementation(() => jest.fn());
asMock(useCurrentUser).mockImplementation(() => mockDefaultUser);
asMock(useEventDefinitionConfigFromLocalStorage).mockImplementation(() => ({
hasLocalStorageConfig: false,
configFromLocalStorage: undefined,
}));
asMock(useScopePermissions).mockImplementation(() => exampleEntityScopeMutable);
asMock(usePluginEntities).mockImplementation(
(entityKey) =>
({
'views.components.eventProcedureSummary': [],
'licenseCheck': [(_license: string) => ({ data: { valid: false } })],
})[entityKey] ?? [],
);
});
it('should render Event Details form enabled', async () => {
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const titles = await screen.findAllByText(/event details/i);
titles.forEach((title) => expect(title).toBeInTheDocument());
expect(screen.getByRole('textbox', { name: /^title/i })).toBeEnabled();
expect(screen.getByRole('textbox', { name: /description/i })).toBeEnabled();
});
it('should render Event Details form disabled for immutable entities', async () => {
asMock(useScopePermissions).mockImplementation(() => exampleEntityScopeImmutable);
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const titles = await screen.findAllByText(/event details/i);
titles.forEach((title) => expect(title).toBeInTheDocument());
expect(screen.getByRole('textbox', { name: /^title/i })).toHaveAttribute('readonly');
expect(screen.getByRole('textbox', { name: /description/i })).toHaveAttribute('readonly');
});
it('should render Filters & Aggregation form enabled', async () => {
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /condition/i });
await userEvent.click(tab);
const conditionTypeSelect = await screen.findByLabelText('Condition Type');
expect(conditionTypeSelect).toBeInTheDocument();
});
it('Filters & Aggregation should not be accessible for immutable entities', async () => {
asMock(useScopePermissions).mockImplementation(() => exampleEntityScopeImmutable);
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /condition/i });
await userEvent.click(tab);
expect(screen.getByText(/cannot be edited/i)).toBeVisible();
});
it('should render Fields form enabled', async () => {
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /fields/i });
await userEvent.click(tab);
expect(screen.getByRole('button', { name: /add custom field/i })).toBeEnabled();
});
it('Fields should not be accessible for immutable entities', async () => {
asMock(useScopePermissions).mockImplementation(() => exampleEntityScopeImmutable);
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /fields/i });
await userEvent.click(tab);
expect(screen.getByText(/cannot be edited/i)).toBeVisible();
});
it('should render Notifications form enabled', async () => {
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /notifications/i });
await userEvent.click(tab);
expect(screen.getByRole('button', { name: /add notification/i })).toBeEnabled();
});
it('Notifications should be accessible for immutable entities', async () => {
asMock(useScopePermissions).mockImplementation(() => exampleEntityScopeImmutable);
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /notification/i });
await userEvent.click(tab);
expect(screen.getByRole('button', { name: /add notification/i })).toBeEnabled();
});
it('should be able to add notifications', async () => {
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /notification/i });
await userEvent.click(tab);
const addNotificationButton = screen.getByRole('button', { name: /add notification/i });
expect(addNotificationButton).toBeEnabled();
await userEvent.click(addNotificationButton);
await userEvent.type(screen.getByText(/select notification/i), 'mock-notification-title{enter}');
await userEvent.click(screen.getByRole('button', { name: /add notification/i }));
expect(screen.getByText(/mock-notification-title/i)).toBeVisible();
});
it('should be able to add notifications to immutable entities', async () => {
asMock(useScopePermissions).mockImplementation(() => exampleEntityScopeImmutable);
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /notification/i });
await userEvent.click(tab);
const addNotificationButton = screen.getByRole('button', { name: /add notification/i });
expect(addNotificationButton).toBeEnabled();
await userEvent.click(addNotificationButton);
await userEvent.type(screen.getByText(/select notification/i), 'mock-notification-title{enter}');
await userEvent.click(screen.getByRole('button', { name: /add notification/i }));
expect(screen.getByText(/mock-notification-title/i)).toBeVisible();
});
it('should show summary with update action on edit', async () => {
render(<EventDefinitionFormContainer action="edit" eventDefinition={mockAggregationEventDefinition} />);
const tab = await screen.findByRole('button', { name: /^summary$/i });
await userEvent.click(tab);
expect(screen.getByRole('button', { name: /update event definition/i })).toBeVisible();
});
});