ruleForm.spec.tsx 20 KB

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