ruleForm.spec.tsx 14 KB

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