ruleForm.spec.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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 ProjectsStore from 'sentry/stores/projectsStore';
  9. import {metric} from 'sentry/utils/analytics';
  10. import RuleFormContainer from 'sentry/views/alerts/rules/metric/ruleForm';
  11. import {permissionAlertText} from 'sentry/views/settings/project/permissionAlert';
  12. jest.mock('sentry/actionCreators/indicator');
  13. jest.mock('sentry/utils/analytics', () => ({
  14. metric: {
  15. startTransaction: jest.fn(() => ({
  16. setTag: jest.fn(),
  17. setData: jest.fn(),
  18. })),
  19. endTransaction: jest.fn(),
  20. },
  21. }));
  22. describe('Incident Rules Form', () => {
  23. let organization, project, routerContext;
  24. const createWrapper = props =>
  25. render(
  26. <RuleFormContainer
  27. params={{orgId: organization.slug, projectId: project.slug}}
  28. organization={organization}
  29. project={project}
  30. {...props}
  31. />,
  32. {context: routerContext}
  33. );
  34. beforeEach(() => {
  35. const initialData = initializeOrg({
  36. organization: {features: ['metric-alert-threshold-period', 'change-alerts']},
  37. });
  38. organization = initialData.organization;
  39. project = initialData.project;
  40. ProjectsStore.loadInitialData([project]);
  41. routerContext = initialData.routerContext;
  42. MockApiClient.addMockResponse({
  43. url: '/organizations/org-slug/tags/',
  44. body: [],
  45. });
  46. MockApiClient.addMockResponse({
  47. url: '/organizations/org-slug/users/',
  48. body: [],
  49. });
  50. MockApiClient.addMockResponse({
  51. url: '/projects/org-slug/project-slug/environments/',
  52. body: [],
  53. });
  54. MockApiClient.addMockResponse({
  55. url: '/organizations/org-slug/events-stats/',
  56. body: EventsStats({
  57. isMetricsData: true,
  58. }),
  59. });
  60. MockApiClient.addMockResponse({
  61. url: '/organizations/org-slug/events-meta/',
  62. body: {count: 5},
  63. });
  64. MockApiClient.addMockResponse({
  65. url: '/organizations/org-slug/alert-rules/available-actions/',
  66. body: [
  67. {
  68. allowedTargetTypes: ['user', 'team'],
  69. integrationName: null,
  70. type: 'email',
  71. integrationId: null,
  72. },
  73. ],
  74. });
  75. MockApiClient.addMockResponse({
  76. url: '/organizations/org-slug/metrics-estimation-stats/',
  77. body: EventsStats(),
  78. });
  79. });
  80. afterEach(() => {
  81. MockApiClient.clearMockResponses();
  82. jest.clearAllMocks();
  83. });
  84. describe('Viewing the rule', () => {
  85. const rule = MetricRule();
  86. it('is enabled without org-level alerts:write', () => {
  87. organization.access = [];
  88. project.access = [];
  89. createWrapper({rule});
  90. expect(screen.queryByText(permissionAlertText)).toBeInTheDocument();
  91. expect(screen.queryByLabelText('Save Rule')).toBeDisabled();
  92. });
  93. it('is enabled with org-level alerts:write', () => {
  94. organization.access = ['alerts:write'];
  95. project.access = [];
  96. createWrapper({rule});
  97. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  98. expect(screen.queryByLabelText('Save Rule')).toBeEnabled();
  99. });
  100. it('is enabled with project-level alerts:write', () => {
  101. organization.access = [];
  102. project.access = ['alerts:write'];
  103. createWrapper({rule});
  104. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  105. expect(screen.queryByLabelText('Save Rule')).toBeEnabled();
  106. });
  107. });
  108. describe('Creating a new rule', () => {
  109. let createRule;
  110. beforeEach(() => {
  111. ProjectsStore.loadInitialData([
  112. project,
  113. {
  114. ...project,
  115. id: '10',
  116. slug: 'project-slug-2',
  117. },
  118. ]);
  119. createRule = MockApiClient.addMockResponse({
  120. url: '/organizations/org-slug/alert-rules/',
  121. method: 'POST',
  122. });
  123. MockApiClient.addMockResponse({
  124. url: '/projects/org-slug/project-slug-2/environments/',
  125. body: [],
  126. });
  127. });
  128. /**
  129. * Note this isn't necessarily the desired behavior, as it is just documenting the behavior
  130. */
  131. it('creates a rule', async () => {
  132. const rule = MetricRule();
  133. createWrapper({
  134. rule: {
  135. ...rule,
  136. id: undefined,
  137. eventTypes: ['default'],
  138. },
  139. });
  140. // Clear field
  141. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  142. // Enter in name so we can submit
  143. await userEvent.type(
  144. screen.getByPlaceholderText('Enter Alert Name'),
  145. 'Incident Rule'
  146. );
  147. // Set thresholdPeriod
  148. await selectEvent.select(screen.getAllByText('For 1 minute')[0], 'For 10 minutes');
  149. await userEvent.click(screen.getByLabelText('Save Rule'));
  150. expect(createRule).toHaveBeenCalledWith(
  151. expect.anything(),
  152. expect.objectContaining({
  153. data: expect.objectContaining({
  154. name: 'Incident Rule',
  155. projects: ['project-slug'],
  156. eventTypes: ['default'],
  157. thresholdPeriod: 10,
  158. }),
  159. })
  160. );
  161. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  162. });
  163. it('can create a rule for a different project', async () => {
  164. const rule = MetricRule();
  165. createWrapper({
  166. rule: {
  167. ...rule,
  168. id: undefined,
  169. eventTypes: ['default'],
  170. },
  171. });
  172. // Clear field
  173. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  174. // Enter in name so we can submit
  175. await userEvent.type(
  176. screen.getByPlaceholderText('Enter Alert Name'),
  177. 'Incident Rule'
  178. );
  179. // Change project
  180. await userEvent.click(screen.getByText('project-slug'));
  181. await userEvent.click(screen.getByText('project-slug-2'));
  182. await userEvent.click(screen.getByLabelText('Save Rule'));
  183. expect(createRule).toHaveBeenCalledWith(
  184. expect.anything(),
  185. expect.objectContaining({
  186. data: expect.objectContaining({
  187. name: 'Incident Rule',
  188. projects: ['project-slug-2'],
  189. }),
  190. })
  191. );
  192. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  193. });
  194. it('creates a rule with generic_metrics dataset', async () => {
  195. organization.features = [...organization.features, 'mep-rollout-flag'];
  196. const rule = MetricRule();
  197. createWrapper({
  198. rule: {
  199. ...rule,
  200. id: undefined,
  201. aggregate: 'count()',
  202. eventTypes: ['transaction'],
  203. dataset: 'transactions',
  204. },
  205. });
  206. await waitFor(() =>
  207. expect(screen.getByTestId('alert-total-events')).toHaveTextContent(
  208. 'Total Transactions5'
  209. )
  210. );
  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 Metric'));
  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 Metric')).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',
  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. });
  382. describe('Slack async lookup', () => {
  383. const uuid = 'xxxx-xxxx-xxxx';
  384. beforeEach(() => {
  385. jest.useFakeTimers();
  386. });
  387. afterEach(() => {
  388. jest.runOnlyPendingTimers();
  389. jest.useRealTimers();
  390. });
  391. it('success status updates the rule', async () => {
  392. const alertRule = MetricRule({name: 'Slack Alert Rule'});
  393. MockApiClient.addMockResponse({
  394. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  395. method: 'PUT',
  396. body: {uuid},
  397. statusCode: 202,
  398. });
  399. MockApiClient.addMockResponse({
  400. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  401. body: {
  402. status: 'success',
  403. alertRule,
  404. },
  405. });
  406. const onSubmitSuccess = jest.fn();
  407. createWrapper({
  408. ruleId: alertRule.id,
  409. rule: alertRule,
  410. onSubmitSuccess,
  411. });
  412. await userEvent.type(
  413. screen.getByPlaceholderText('Enter Alert Name'),
  414. 'Slack Alert Rule',
  415. {delay: null}
  416. );
  417. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  418. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  419. act(jest.runAllTimers);
  420. await waitFor(
  421. () => {
  422. expect(onSubmitSuccess).toHaveBeenCalledWith(
  423. expect.objectContaining({
  424. id: alertRule.id,
  425. name: alertRule.name,
  426. }),
  427. expect.anything()
  428. );
  429. },
  430. {timeout: 2000, interval: 10}
  431. );
  432. });
  433. it('pending status keeps loading true', () => {
  434. const alertRule = MetricRule({name: 'Slack Alert Rule'});
  435. MockApiClient.addMockResponse({
  436. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  437. method: 'PUT',
  438. body: {uuid},
  439. statusCode: 202,
  440. });
  441. MockApiClient.addMockResponse({
  442. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  443. body: {
  444. status: 'pending',
  445. },
  446. });
  447. const onSubmitSuccess = jest.fn();
  448. createWrapper({
  449. ruleId: alertRule.id,
  450. rule: alertRule,
  451. onSubmitSuccess,
  452. });
  453. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  454. expect(onSubmitSuccess).not.toHaveBeenCalled();
  455. });
  456. it('failed status renders error message', async () => {
  457. const alertRule = MetricRule({name: 'Slack Alert Rule'});
  458. MockApiClient.addMockResponse({
  459. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  460. method: 'PUT',
  461. body: {uuid},
  462. statusCode: 202,
  463. });
  464. MockApiClient.addMockResponse({
  465. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  466. body: {
  467. status: 'failed',
  468. error: 'An error occurred',
  469. },
  470. });
  471. const onSubmitSuccess = jest.fn();
  472. createWrapper({
  473. ruleId: alertRule.id,
  474. rule: alertRule,
  475. onSubmitSuccess,
  476. });
  477. await userEvent.type(
  478. screen.getByPlaceholderText('Enter Alert Name'),
  479. 'Slack Alert Rule',
  480. {delay: null}
  481. );
  482. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  483. act(jest.runAllTimers);
  484. await waitFor(
  485. () => {
  486. expect(addErrorMessage).toHaveBeenCalledWith('An error occurred');
  487. },
  488. {timeout: 2000, interval: 10}
  489. );
  490. expect(onSubmitSuccess).not.toHaveBeenCalled();
  491. });
  492. });
  493. });