ruleForm.spec.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. import selectEvent from 'react-select-event';
  2. import {EventsStats} from 'sentry-fixture/events';
  3. import {IncidentTrigger} from 'sentry-fixture/incidentTrigger';
  4. import {MetricRule} from 'sentry-fixture/metricRule';
  5. import {initializeOrg} from 'sentry-test/initializeOrg';
  6. import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  7. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  8. import FormModel from 'sentry/components/forms/model';
  9. import ProjectsStore from 'sentry/stores/projectsStore';
  10. import {metric} from 'sentry/utils/analytics';
  11. import RuleFormContainer from 'sentry/views/alerts/rules/metric/ruleForm';
  12. import {Dataset} from 'sentry/views/alerts/rules/metric/types';
  13. import {permissionAlertText} from 'sentry/views/settings/project/permissionAlert';
  14. jest.mock('sentry/actionCreators/indicator');
  15. jest.mock('sentry/utils/analytics', () => ({
  16. metric: {
  17. startTransaction: jest.fn(() => ({
  18. setTag: jest.fn(),
  19. setData: jest.fn(),
  20. })),
  21. endTransaction: jest.fn(),
  22. },
  23. }));
  24. describe('Incident Rules Form', () => {
  25. let organization, project, routerContext, location;
  26. const createWrapper = props =>
  27. render(
  28. <RuleFormContainer
  29. params={{orgId: organization.slug, projectId: project.slug}}
  30. organization={organization}
  31. location={location}
  32. project={project}
  33. {...props}
  34. />,
  35. {context: routerContext}
  36. );
  37. beforeEach(() => {
  38. const initialData = initializeOrg({
  39. organization: {features: ['metric-alert-threshold-period', 'change-alerts']},
  40. });
  41. organization = initialData.organization;
  42. project = initialData.project;
  43. location = initialData.router.location;
  44. ProjectsStore.loadInitialData([project]);
  45. routerContext = initialData.routerContext;
  46. MockApiClient.addMockResponse({
  47. url: '/organizations/org-slug/tags/',
  48. body: [],
  49. });
  50. MockApiClient.addMockResponse({
  51. url: '/organizations/org-slug/users/',
  52. body: [],
  53. });
  54. MockApiClient.addMockResponse({
  55. url: '/projects/org-slug/project-slug/environments/',
  56. body: [],
  57. });
  58. MockApiClient.addMockResponse({
  59. url: '/organizations/org-slug/events-stats/',
  60. body: EventsStats({
  61. isMetricsData: true,
  62. }),
  63. });
  64. MockApiClient.addMockResponse({
  65. url: '/organizations/org-slug/events-meta/',
  66. body: {count: 5},
  67. });
  68. MockApiClient.addMockResponse({
  69. url: '/organizations/org-slug/alert-rules/available-actions/',
  70. body: [
  71. {
  72. allowedTargetTypes: ['user', 'team'],
  73. integrationName: null,
  74. type: 'email',
  75. integrationId: null,
  76. },
  77. ],
  78. });
  79. MockApiClient.addMockResponse({
  80. url: '/organizations/org-slug/metrics-estimation-stats/',
  81. body: EventsStats(),
  82. });
  83. });
  84. afterEach(() => {
  85. MockApiClient.clearMockResponses();
  86. jest.clearAllMocks();
  87. });
  88. describe('Viewing the rule', () => {
  89. const rule = MetricRule();
  90. it('is enabled without org-level alerts:write', () => {
  91. organization.access = [];
  92. project.access = [];
  93. createWrapper({rule});
  94. expect(screen.queryByText(permissionAlertText)).toBeInTheDocument();
  95. expect(screen.queryByLabelText('Save Rule')).toBeDisabled();
  96. });
  97. it('is enabled with org-level alerts:write', () => {
  98. organization.access = ['alerts:write'];
  99. project.access = [];
  100. createWrapper({rule});
  101. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  102. expect(screen.queryByLabelText('Save Rule')).toBeEnabled();
  103. });
  104. it('is enabled with project-level alerts:write', () => {
  105. organization.access = [];
  106. project.access = ['alerts:write'];
  107. createWrapper({rule});
  108. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  109. expect(screen.queryByLabelText('Save Rule')).toBeEnabled();
  110. });
  111. });
  112. describe('Creating a new rule', () => {
  113. let createRule;
  114. beforeEach(() => {
  115. ProjectsStore.loadInitialData([
  116. project,
  117. {
  118. ...project,
  119. id: '10',
  120. slug: 'project-slug-2',
  121. },
  122. ]);
  123. createRule = MockApiClient.addMockResponse({
  124. url: '/organizations/org-slug/alert-rules/',
  125. method: 'POST',
  126. });
  127. MockApiClient.addMockResponse({
  128. url: '/projects/org-slug/project-slug-2/environments/',
  129. body: [],
  130. });
  131. });
  132. /**
  133. * Note this isn't necessarily the desired behavior, as it is just documenting the behavior
  134. */
  135. it('creates a rule', async () => {
  136. const rule = MetricRule();
  137. createWrapper({
  138. rule: {
  139. ...rule,
  140. id: undefined,
  141. eventTypes: ['default'],
  142. },
  143. });
  144. // Clear field
  145. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  146. // Enter in name so we can submit
  147. await userEvent.type(
  148. screen.getByPlaceholderText('Enter Alert Name'),
  149. 'Incident Rule'
  150. );
  151. // Set thresholdPeriod
  152. await selectEvent.select(screen.getAllByText('For 1 minute')[0], 'For 10 minutes');
  153. await userEvent.click(screen.getByLabelText('Save Rule'));
  154. expect(createRule).toHaveBeenCalledWith(
  155. expect.anything(),
  156. expect.objectContaining({
  157. data: expect.objectContaining({
  158. name: 'Incident Rule',
  159. projects: ['project-slug'],
  160. eventTypes: ['default'],
  161. thresholdPeriod: 10,
  162. }),
  163. })
  164. );
  165. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  166. });
  167. it('can create a rule for a different project', async () => {
  168. const rule = MetricRule();
  169. createWrapper({
  170. rule: {
  171. ...rule,
  172. id: undefined,
  173. eventTypes: ['default'],
  174. },
  175. });
  176. // Clear field
  177. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  178. // Enter in name so we can submit
  179. await userEvent.type(
  180. screen.getByPlaceholderText('Enter Alert Name'),
  181. 'Incident Rule'
  182. );
  183. // Change project
  184. await userEvent.click(screen.getByText('project-slug'));
  185. await userEvent.click(screen.getByText('project-slug-2'));
  186. await userEvent.click(screen.getByLabelText('Save Rule'));
  187. expect(createRule).toHaveBeenCalledWith(
  188. expect.anything(),
  189. expect.objectContaining({
  190. data: expect.objectContaining({
  191. name: 'Incident Rule',
  192. projects: ['project-slug-2'],
  193. }),
  194. })
  195. );
  196. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  197. });
  198. it('creates a rule with generic_metrics dataset', async () => {
  199. organization.features = [...organization.features, 'mep-rollout-flag'];
  200. const rule = MetricRule();
  201. createWrapper({
  202. rule: {
  203. ...rule,
  204. id: undefined,
  205. aggregate: 'count()',
  206. eventTypes: ['transaction'],
  207. dataset: 'transactions',
  208. },
  209. });
  210. expect(await screen.findByTestId('alert-total-events')).toHaveTextContent('Total5');
  211. await userEvent.click(screen.getByLabelText('Save Rule'));
  212. expect(createRule).toHaveBeenCalledWith(
  213. expect.anything(),
  214. expect.objectContaining({
  215. data: expect.objectContaining({
  216. name: 'My Incident Rule',
  217. projects: ['project-slug'],
  218. aggregate: 'count()',
  219. eventTypes: ['transaction'],
  220. dataset: 'generic_metrics',
  221. thresholdPeriod: 1,
  222. }),
  223. })
  224. );
  225. });
  226. it('switches to custom metric and selects event.type:error', async () => {
  227. organization.features = [...organization.features, 'performance-view'];
  228. const rule = MetricRule();
  229. createWrapper({
  230. rule: {
  231. ...rule,
  232. id: undefined,
  233. eventTypes: ['default'],
  234. },
  235. });
  236. await userEvent.click(screen.getAllByText('Number of Errors').at(1)!);
  237. await userEvent.click(await screen.findByText('Custom Measurement'));
  238. await userEvent.click(screen.getAllByText('event.type:transaction').at(1)!);
  239. await userEvent.click(await screen.findByText('event.type:error'));
  240. expect(screen.getAllByText('Custom Measurement')).toHaveLength(2);
  241. await userEvent.click(screen.getByLabelText('Save Rule'));
  242. expect(createRule).toHaveBeenLastCalledWith(
  243. expect.anything(),
  244. expect.objectContaining({
  245. data: expect.objectContaining({
  246. aggregate: 'count()',
  247. alertType: 'custom_transactions',
  248. dataset: 'events',
  249. datasource: 'error',
  250. environment: null,
  251. eventTypes: ['error'],
  252. name: 'My Incident Rule',
  253. projectId: '2',
  254. projects: ['project-slug'],
  255. query: '',
  256. }),
  257. })
  258. );
  259. });
  260. });
  261. describe('Editing a rule', () => {
  262. let editRule;
  263. let editTrigger;
  264. const rule = MetricRule();
  265. beforeEach(() => {
  266. editRule = MockApiClient.addMockResponse({
  267. url: `/organizations/org-slug/alert-rules/${rule.id}/`,
  268. method: 'PUT',
  269. body: rule,
  270. });
  271. editTrigger = MockApiClient.addMockResponse({
  272. url: `/organizations/org-slug/alert-rules/${rule.id}/triggers/1/`,
  273. method: 'PUT',
  274. body: IncidentTrigger({id: '1'}),
  275. });
  276. });
  277. afterEach(() => {
  278. editRule.mockReset();
  279. editTrigger.mockReset();
  280. });
  281. it('edits metric', async () => {
  282. createWrapper({
  283. ruleId: rule.id,
  284. rule,
  285. });
  286. // Clear field
  287. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  288. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'new name');
  289. await userEvent.click(screen.getByLabelText('Save Rule'));
  290. expect(editRule).toHaveBeenLastCalledWith(
  291. expect.anything(),
  292. expect.objectContaining({
  293. data: expect.objectContaining({
  294. name: 'new name',
  295. }),
  296. })
  297. );
  298. });
  299. it('switches from percent change to count', async () => {
  300. createWrapper({
  301. ruleId: rule.id,
  302. rule: {
  303. ...rule,
  304. timeWindow: 60,
  305. comparisonDelta: 100,
  306. eventTypes: ['error'],
  307. resolution: 2,
  308. },
  309. });
  310. expect(screen.getByLabelText('Static: above or below {x}')).not.toBeChecked();
  311. await userEvent.click(screen.getByText('Static: above or below {x}'));
  312. await waitFor(() =>
  313. expect(screen.getByLabelText('Static: above or below {x}')).toBeChecked()
  314. );
  315. await userEvent.click(screen.getByLabelText('Save Rule'));
  316. expect(editRule).toHaveBeenLastCalledWith(
  317. expect.anything(),
  318. expect.objectContaining({
  319. data: expect.objectContaining({
  320. // Comparison delta is reset
  321. comparisonDelta: null,
  322. }),
  323. })
  324. );
  325. });
  326. it('switches event type from error to default', async () => {
  327. createWrapper({
  328. ruleId: rule.id,
  329. rule: {
  330. ...rule,
  331. eventTypes: ['error', 'default'],
  332. },
  333. });
  334. await userEvent.click(screen.getByText('event.type:error OR event.type:default'));
  335. await userEvent.click(await screen.findByText('event.type:default'));
  336. expect(screen.getAllByText('Number of Errors')).toHaveLength(2);
  337. await userEvent.click(screen.getByLabelText('Save Rule'));
  338. expect(editRule).toHaveBeenLastCalledWith(
  339. expect.anything(),
  340. expect.objectContaining({
  341. data: expect.objectContaining({
  342. eventTypes: ['default'],
  343. }),
  344. })
  345. );
  346. });
  347. it('saves a valid on demand metric rule', async () => {
  348. const validOnDemandMetricRule = MetricRule({
  349. query: 'transaction.duration:<1s',
  350. });
  351. const onSubmitSuccess = jest.fn();
  352. createWrapper({
  353. ruleId: validOnDemandMetricRule.id,
  354. rule: {
  355. ...validOnDemandMetricRule,
  356. eventTypes: ['transaction'],
  357. },
  358. onSubmitSuccess,
  359. });
  360. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  361. expect(onSubmitSuccess).toHaveBeenCalled();
  362. });
  363. it('shows errors for an invalid on demand metric rule', async () => {
  364. const invalidOnDemandMetricRule = TestStubs.MetricRule({
  365. aggregate: 'percentile()',
  366. query: 'transaction.duration:<1s',
  367. dataset: 'generic_metrics',
  368. });
  369. const onSubmitSuccess = jest.fn();
  370. createWrapper({
  371. ruleId: invalidOnDemandMetricRule.id,
  372. rule: {
  373. ...invalidOnDemandMetricRule,
  374. eventTypes: ['transaction'],
  375. },
  376. onSubmitSuccess,
  377. });
  378. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  379. expect(onSubmitSuccess).not.toHaveBeenCalled();
  380. });
  381. it('hides fields when migrating error metric alerts to filter archived issues', async () => {
  382. const errorAlert = MetricRule({
  383. dataset: Dataset.ERRORS,
  384. query: 'example-error',
  385. });
  386. organization.features = [...organization.features, 'metric-alert-ignore-archived'];
  387. location = {...location, query: {migration: '1'}};
  388. const onSubmitSuccess = jest.fn();
  389. createWrapper({
  390. ruleId: errorAlert.id,
  391. rule: {
  392. ...errorAlert,
  393. eventTypes: ['transaction'],
  394. },
  395. onSubmitSuccess,
  396. });
  397. expect(
  398. await screen.findByText(/please make sure the current thresholds are still valid/)
  399. ).toBeInTheDocument();
  400. await userEvent.click(screen.getByLabelText('Looks good to me!'), {delay: null});
  401. expect(onSubmitSuccess).toHaveBeenCalled();
  402. const formModel = onSubmitSuccess.mock.calls[0][1] as FormModel;
  403. expect(formModel.getData()).toEqual(
  404. expect.objectContaining({query: 'is:unresolved example-error'})
  405. );
  406. });
  407. });
  408. describe('Slack async lookup', () => {
  409. const uuid = 'xxxx-xxxx-xxxx';
  410. beforeEach(() => {
  411. jest.useFakeTimers();
  412. });
  413. afterEach(() => {
  414. jest.runOnlyPendingTimers();
  415. jest.useRealTimers();
  416. });
  417. it('success status updates the rule', async () => {
  418. const alertRule = MetricRule({name: 'Slack Alert Rule'});
  419. MockApiClient.addMockResponse({
  420. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  421. method: 'PUT',
  422. body: {uuid},
  423. statusCode: 202,
  424. });
  425. MockApiClient.addMockResponse({
  426. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  427. body: {
  428. status: 'success',
  429. alertRule,
  430. },
  431. });
  432. const onSubmitSuccess = jest.fn();
  433. createWrapper({
  434. ruleId: alertRule.id,
  435. rule: alertRule,
  436. onSubmitSuccess,
  437. });
  438. await userEvent.type(
  439. screen.getByPlaceholderText('Enter Alert Name'),
  440. 'Slack Alert Rule',
  441. {delay: null}
  442. );
  443. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  444. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  445. act(jest.runAllTimers);
  446. await waitFor(
  447. () => {
  448. expect(onSubmitSuccess).toHaveBeenCalledWith(
  449. expect.objectContaining({
  450. id: alertRule.id,
  451. name: alertRule.name,
  452. }),
  453. expect.anything()
  454. );
  455. },
  456. {timeout: 2000, interval: 10}
  457. );
  458. });
  459. it('pending status keeps loading true', () => {
  460. const alertRule = MetricRule({name: 'Slack Alert Rule'});
  461. MockApiClient.addMockResponse({
  462. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  463. method: 'PUT',
  464. body: {uuid},
  465. statusCode: 202,
  466. });
  467. MockApiClient.addMockResponse({
  468. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  469. body: {
  470. status: 'pending',
  471. },
  472. });
  473. const onSubmitSuccess = jest.fn();
  474. createWrapper({
  475. ruleId: alertRule.id,
  476. rule: alertRule,
  477. onSubmitSuccess,
  478. });
  479. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  480. expect(onSubmitSuccess).not.toHaveBeenCalled();
  481. });
  482. it('failed status renders error message', async () => {
  483. const alertRule = MetricRule({name: 'Slack Alert Rule'});
  484. MockApiClient.addMockResponse({
  485. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  486. method: 'PUT',
  487. body: {uuid},
  488. statusCode: 202,
  489. });
  490. MockApiClient.addMockResponse({
  491. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  492. body: {
  493. status: 'failed',
  494. error: 'An error occurred',
  495. },
  496. });
  497. const onSubmitSuccess = jest.fn();
  498. createWrapper({
  499. ruleId: alertRule.id,
  500. rule: alertRule,
  501. onSubmitSuccess,
  502. });
  503. await userEvent.type(
  504. screen.getByPlaceholderText('Enter Alert Name'),
  505. 'Slack Alert Rule',
  506. {delay: null}
  507. );
  508. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  509. act(jest.runAllTimers);
  510. await waitFor(
  511. () => {
  512. expect(addErrorMessage).toHaveBeenCalledWith('An error occurred');
  513. },
  514. {timeout: 2000, interval: 10}
  515. );
  516. expect(onSubmitSuccess).not.toHaveBeenCalled();
  517. });
  518. });
  519. });