ruleForm.spec.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 {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. startSpan: jest.fn(() => ({
  18. setTag: jest.fn(),
  19. setData: jest.fn(),
  20. })),
  21. endSpan: 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, organization}
  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: EventsStatsFixture({
  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: EventsStatsFixture(),
  82. });
  83. });
  84. afterEach(() => {
  85. MockApiClient.clearMockResponses();
  86. jest.clearAllMocks();
  87. });
  88. describe('Viewing the rule', () => {
  89. const rule = MetricRuleFixture();
  90. it('is enabled without org-level alerts:write', async () => {
  91. organization.access = [];
  92. project.access = [];
  93. createWrapper({rule});
  94. expect(await screen.findByText(permissionAlertText)).toBeInTheDocument();
  95. expect(screen.queryByLabelText('Save Rule')).toBeDisabled();
  96. });
  97. it('is enabled with org-level alerts:write', async () => {
  98. organization.access = ['alerts:write'];
  99. project.access = [];
  100. createWrapper({rule});
  101. expect(await screen.findByLabelText('Save Rule')).toBeEnabled();
  102. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  103. });
  104. it('is enabled with project-level alerts:write', async () => {
  105. organization.access = [];
  106. project.access = ['alerts:write'];
  107. createWrapper({rule});
  108. expect(await screen.findByLabelText('Save Rule')).toBeEnabled();
  109. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  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 = MetricRuleFixture();
  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.startSpan).toHaveBeenCalledWith({name: 'saveAlertRule'});
  166. });
  167. it('can create a rule for a different project', async () => {
  168. const rule = MetricRuleFixture();
  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.startSpan).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 = MetricRuleFixture();
  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 = MetricRuleFixture();
  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 = MetricRuleFixture();
  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: IncidentTriggerFixture({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 = MetricRuleFixture({
  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('hides fields when migrating error metric alerts to filter archived issues', async () => {
  364. const errorAlert = MetricRuleFixture({
  365. dataset: Dataset.ERRORS,
  366. query: 'example-error',
  367. });
  368. organization.features = [...organization.features, 'metric-alert-ignore-archived'];
  369. location = {...location, query: {migration: '1'}};
  370. const onSubmitSuccess = jest.fn();
  371. createWrapper({
  372. ruleId: errorAlert.id,
  373. rule: {
  374. ...errorAlert,
  375. eventTypes: ['transaction'],
  376. },
  377. onSubmitSuccess,
  378. });
  379. expect(
  380. await screen.findByText(/please make sure the current thresholds are still valid/)
  381. ).toBeInTheDocument();
  382. await userEvent.click(screen.getByLabelText('Looks good to me!'), {delay: null});
  383. expect(onSubmitSuccess).toHaveBeenCalled();
  384. const formModel = onSubmitSuccess.mock.calls[0][1] as FormModel;
  385. expect(formModel.getData()).toEqual(
  386. expect.objectContaining({query: 'is:unresolved example-error'})
  387. );
  388. });
  389. });
  390. describe('Slack async lookup', () => {
  391. const uuid = 'xxxx-xxxx-xxxx';
  392. beforeEach(() => {
  393. jest.useFakeTimers();
  394. });
  395. afterEach(() => {
  396. jest.useRealTimers();
  397. });
  398. it('success status updates the rule', async () => {
  399. const alertRule = MetricRuleFixture({name: 'Slack Alert Rule'});
  400. MockApiClient.addMockResponse({
  401. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  402. method: 'PUT',
  403. body: {uuid},
  404. statusCode: 202,
  405. });
  406. MockApiClient.addMockResponse({
  407. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  408. body: {
  409. status: 'success',
  410. alertRule,
  411. },
  412. });
  413. const onSubmitSuccess = jest.fn();
  414. createWrapper({
  415. ruleId: alertRule.id,
  416. rule: alertRule,
  417. onSubmitSuccess,
  418. });
  419. act(jest.runAllTimers);
  420. await userEvent.type(
  421. await screen.findByPlaceholderText('Enter Alert Name'),
  422. 'Slack Alert Rule',
  423. {delay: null}
  424. );
  425. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  426. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  427. act(jest.runAllTimers);
  428. await waitFor(
  429. () => {
  430. expect(onSubmitSuccess).toHaveBeenCalledWith(
  431. expect.objectContaining({
  432. id: alertRule.id,
  433. name: alertRule.name,
  434. }),
  435. expect.anything()
  436. );
  437. },
  438. {timeout: 2000, interval: 10}
  439. );
  440. });
  441. it('pending status keeps loading true', async () => {
  442. const alertRule = MetricRuleFixture({name: 'Slack Alert Rule'});
  443. MockApiClient.addMockResponse({
  444. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  445. method: 'PUT',
  446. body: {uuid},
  447. statusCode: 202,
  448. });
  449. MockApiClient.addMockResponse({
  450. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  451. body: {
  452. status: 'pending',
  453. },
  454. });
  455. const onSubmitSuccess = jest.fn();
  456. createWrapper({
  457. ruleId: alertRule.id,
  458. rule: alertRule,
  459. onSubmitSuccess,
  460. });
  461. act(jest.runAllTimers);
  462. expect(await screen.findByTestId('loading-indicator')).toBeInTheDocument();
  463. expect(onSubmitSuccess).not.toHaveBeenCalled();
  464. });
  465. it('failed status renders error message', async () => {
  466. const alertRule = MetricRuleFixture({name: 'Slack Alert Rule'});
  467. MockApiClient.addMockResponse({
  468. url: `/organizations/org-slug/alert-rules/${alertRule.id}/`,
  469. method: 'PUT',
  470. body: {uuid},
  471. statusCode: 202,
  472. });
  473. MockApiClient.addMockResponse({
  474. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  475. body: {
  476. status: 'failed',
  477. error: 'An error occurred',
  478. },
  479. });
  480. const onSubmitSuccess = jest.fn();
  481. createWrapper({
  482. ruleId: alertRule.id,
  483. rule: alertRule,
  484. onSubmitSuccess,
  485. });
  486. act(jest.runAllTimers);
  487. await userEvent.type(
  488. await screen.findByPlaceholderText('Enter Alert Name'),
  489. 'Slack Alert Rule',
  490. {delay: null}
  491. );
  492. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  493. act(jest.runAllTimers);
  494. await waitFor(
  495. () => {
  496. expect(addErrorMessage).toHaveBeenCalledWith('An error occurred');
  497. },
  498. {timeout: 2000, interval: 10}
  499. );
  500. expect(onSubmitSuccess).not.toHaveBeenCalled();
  501. });
  502. });
  503. });