index.spec.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. import {ProjectFixture} from 'sentry-fixture/project';
  2. import {UserFixture} from 'sentry-fixture/user';
  3. import {initializeOrg} from 'sentry-test/initializeOrg';
  4. import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  5. import {DATA_CATEGORY_INFO, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  6. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  7. import ConfigStore from 'sentry/stores/configStore';
  8. import OrganizationStore from 'sentry/stores/organizationStore';
  9. import PageFiltersStore from 'sentry/stores/pageFiltersStore';
  10. import ProjectsStore from 'sentry/stores/projectsStore';
  11. import type {PageFilters} from 'sentry/types/core';
  12. import {OrganizationStats, PAGE_QUERY_PARAMS} from 'sentry/views/organizationStats';
  13. import {ChartDataTransform} from './usageChart';
  14. describe('OrganizationStats', function () {
  15. const defaultSelection: PageFilters = {
  16. projects: [],
  17. environments: [],
  18. datetime: {
  19. start: null,
  20. end: null,
  21. period: DEFAULT_STATS_PERIOD,
  22. utc: false,
  23. },
  24. };
  25. const projects = ['1', '2', '3'].map(id => ProjectFixture({id, slug: `proj-${id}`}));
  26. const {organization, router} = initializeOrg({
  27. organization: {features: ['global-views', 'team-insights']},
  28. projects,
  29. router: undefined,
  30. });
  31. const endpoint = `/organizations/${organization.slug}/stats_v2/`;
  32. const defaultProps: OrganizationStats['props'] = {
  33. router,
  34. organization,
  35. ...router,
  36. selection: defaultSelection,
  37. route: {},
  38. params: {orgId: organization.slug as string},
  39. routeParams: {},
  40. };
  41. let mockRequest;
  42. beforeEach(() => {
  43. MockApiClient.clearMockResponses();
  44. PageFiltersStore.init();
  45. PageFiltersStore.onInitializeUrlState(defaultSelection, new Set());
  46. OrganizationStore.onUpdate(organization, {replace: true});
  47. ProjectsStore.loadInitialData(projects);
  48. mockRequest = MockApiClient.addMockResponse({
  49. method: 'GET',
  50. url: endpoint,
  51. body: mockStatsResponse,
  52. });
  53. ConfigStore.init();
  54. ConfigStore.set('user', UserFixture());
  55. });
  56. afterEach(() => {
  57. PageFiltersStore.reset();
  58. });
  59. /**
  60. * Features and Alerts
  61. */
  62. it('renders header state without tabs', async () => {
  63. const newOrg = initializeOrg();
  64. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  65. router: newOrg.router,
  66. });
  67. expect(await screen.findByText('Organization Usage Stats')).toBeInTheDocument();
  68. });
  69. it('renders header state with tabs', async () => {
  70. render(<OrganizationStats {...defaultProps} />, {router});
  71. expect(await screen.findByText('Stats')).toBeInTheDocument();
  72. expect(screen.getByText('Usage')).toBeInTheDocument();
  73. expect(screen.getByText('Issues')).toBeInTheDocument();
  74. expect(screen.getByText('Health')).toBeInTheDocument();
  75. });
  76. /**
  77. * Base + Error Handling
  78. */
  79. it('renders the base view', async () => {
  80. render(<OrganizationStats {...defaultProps} />, {router});
  81. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  82. // Default to Errors category
  83. expect(screen.getAllByText('Errors')[0]).toBeInTheDocument();
  84. // Render the chart and project table
  85. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  86. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  87. // Render the cards
  88. expect(screen.getAllByText('Total')[0]).toBeInTheDocument();
  89. // Total from cards and project table should match
  90. expect(screen.getAllByText('67')).toHaveLength(2);
  91. expect(screen.getAllByText('Accepted')[0]).toBeInTheDocument();
  92. // Total from cards and project table should match
  93. expect(screen.getAllByText('28')).toHaveLength(2);
  94. expect(await screen.findByText('6 in last min')).toBeInTheDocument();
  95. expect(screen.getAllByText('Filtered')[0]).toBeInTheDocument();
  96. expect(screen.getAllByText('7')[0]).toBeInTheDocument();
  97. expect(screen.getAllByText('Rate Limited')[0]).toBeInTheDocument();
  98. expect(screen.getAllByText('17')[0]).toBeInTheDocument();
  99. expect(screen.getAllByText('Invalid')[0]).toBeInTheDocument();
  100. expect(screen.getAllByText('15')[0]).toBeInTheDocument();
  101. // Correct API Calls
  102. const mockExpectations = {
  103. UsageStatsOrg: {
  104. statsPeriod: DEFAULT_STATS_PERIOD,
  105. interval: '1h',
  106. groupBy: ['outcome', 'reason'],
  107. project: [-1],
  108. field: ['sum(quantity)'],
  109. category: 'error',
  110. },
  111. UsageStatsPerMin: {
  112. statsPeriod: '5m',
  113. interval: '1m',
  114. groupBy: ['category', 'outcome'],
  115. project: [-1],
  116. field: ['sum(quantity)'],
  117. },
  118. UsageStatsProjects: {
  119. statsPeriod: DEFAULT_STATS_PERIOD,
  120. interval: '1h',
  121. groupBy: ['outcome', 'project'],
  122. project: [-1],
  123. field: ['sum(quantity)'],
  124. category: 'error',
  125. },
  126. };
  127. for (const query of Object.values(mockExpectations)) {
  128. expect(mockRequest).toHaveBeenCalledWith(
  129. endpoint,
  130. expect.objectContaining({query})
  131. );
  132. }
  133. });
  134. it('renders with an error on stats endpoint', async () => {
  135. MockApiClient.clearMockResponses();
  136. MockApiClient.addMockResponse({
  137. url: endpoint,
  138. statusCode: 500,
  139. });
  140. render(<OrganizationStats {...defaultProps} />, {router});
  141. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  142. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  143. expect(screen.getByTestId('error-messages')).toBeInTheDocument();
  144. });
  145. it('renders with an error when user has no projects', async () => {
  146. MockApiClient.clearMockResponses();
  147. MockApiClient.addMockResponse({
  148. url: endpoint,
  149. statusCode: 400,
  150. body: {detail: 'No projects available'},
  151. });
  152. render(<OrganizationStats {...defaultProps} />, {router});
  153. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  154. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  155. expect(screen.getByTestId('empty-message')).toBeInTheDocument();
  156. });
  157. it('renders with just errors category for errors-only self-hosted', async () => {
  158. ConfigStore.set('isSelfHostedErrorsOnly', true);
  159. render(<OrganizationStats {...defaultProps} />, {router});
  160. await userEvent.click(await screen.findByText('Category'));
  161. // Shows only errors as stats category
  162. expect(screen.getAllByRole('option')).toHaveLength(1);
  163. expect(screen.getByRole('option', {name: 'Errors'})).toBeInTheDocument();
  164. });
  165. /**
  166. * Router Handling
  167. */
  168. it('pushes state changes to the route', async () => {
  169. render(<OrganizationStats {...defaultProps} />, {router});
  170. await userEvent.click(await screen.findByText('Category'));
  171. await userEvent.click(screen.getByText('Attachments'));
  172. await waitFor(() =>
  173. expect(router.push).toHaveBeenCalledWith(
  174. expect.objectContaining({
  175. query: {dataCategory: DATA_CATEGORY_INFO.attachment.plural},
  176. })
  177. )
  178. );
  179. await userEvent.click(screen.getByText('Periodic'));
  180. await userEvent.click(screen.getByText('Cumulative'));
  181. await waitFor(() =>
  182. expect(router.push).toHaveBeenCalledWith(
  183. expect.objectContaining({
  184. query: {transform: ChartDataTransform.CUMULATIVE},
  185. })
  186. )
  187. );
  188. const inputQuery = 'proj-1';
  189. await userEvent.type(
  190. screen.getByRole('textbox', {name: 'Filter projects'}),
  191. `${inputQuery}{Enter}`
  192. );
  193. await waitFor(() =>
  194. expect(router.push).toHaveBeenCalledWith(
  195. expect.objectContaining({
  196. query: {query: inputQuery},
  197. })
  198. )
  199. );
  200. });
  201. it('does not leak query params onto next page links', async () => {
  202. const dummyLocation = PAGE_QUERY_PARAMS.reduce(
  203. (location, param) => {
  204. location.query[param] = '';
  205. return location;
  206. },
  207. {query: {}}
  208. );
  209. render(<OrganizationStats {...defaultProps} location={dummyLocation as any} />, {
  210. router,
  211. });
  212. const projectLinks = await screen.findAllByTestId('badge-display-name');
  213. expect(projectLinks.length).toBeGreaterThan(0);
  214. const leakingRegex = PAGE_QUERY_PARAMS.join('|');
  215. for (const projectLink of projectLinks) {
  216. expect(projectLink.closest('a')).toHaveAttribute(
  217. 'href',
  218. expect.not.stringMatching(leakingRegex)
  219. );
  220. }
  221. });
  222. /**
  223. * Project Selection
  224. */
  225. it('renders single project without global-views', async () => {
  226. const newOrg = initializeOrg();
  227. newOrg.organization.features = ['team-insights'];
  228. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  229. router: newOrg.router,
  230. organization: newOrg.organization,
  231. });
  232. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  233. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  234. expect(screen.queryByText('usage-stats-table')).not.toBeInTheDocument();
  235. });
  236. it('renders default projects with global-views', async () => {
  237. const newOrg = initializeOrg();
  238. newOrg.organization.features = ['global-views', 'team-insights'];
  239. OrganizationStore.onUpdate(newOrg.organization, {replace: true});
  240. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  241. router: newOrg.router,
  242. organization: newOrg.organization,
  243. });
  244. expect(await screen.findByText('All Projects')).toBeInTheDocument();
  245. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  246. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  247. mockRequest.mock.calls.forEach(([_path, {query}]) => {
  248. // Ignore UsageStatsPerMin's query
  249. if (query?.statsPeriod === '5m') {
  250. return;
  251. }
  252. expect(query.project).toEqual([ALL_ACCESS_PROJECTS]);
  253. expect(defaultSelection.projects).toEqual([]);
  254. });
  255. });
  256. it('renders with multiple projects selected', async () => {
  257. const newOrg = initializeOrg();
  258. newOrg.organization.features = ['global-views', 'team-insights'];
  259. const selectedProjects = [1, 2];
  260. const newSelection = {
  261. ...defaultSelection,
  262. projects: selectedProjects,
  263. };
  264. render(
  265. <OrganizationStats
  266. {...defaultProps}
  267. organization={newOrg.organization}
  268. selection={newSelection}
  269. />,
  270. {
  271. router: newOrg.router,
  272. organization: newOrg.organization,
  273. }
  274. );
  275. act(() => PageFiltersStore.updateProjects(selectedProjects, []));
  276. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  277. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  278. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  279. expect(mockRequest).toHaveBeenCalledWith(
  280. endpoint,
  281. expect.objectContaining({
  282. query: {
  283. statsPeriod: DEFAULT_STATS_PERIOD,
  284. interval: '1h',
  285. groupBy: ['outcome', 'reason'],
  286. project: selectedProjects,
  287. field: ['sum(quantity)'],
  288. category: 'error',
  289. },
  290. })
  291. );
  292. });
  293. it('renders with a single project selected', async () => {
  294. const newOrg = initializeOrg();
  295. newOrg.organization.features = ['global-views', 'team-insights'];
  296. const selectedProject = [1];
  297. const newSelection = {
  298. ...defaultSelection,
  299. projects: selectedProject,
  300. };
  301. render(
  302. <OrganizationStats
  303. {...defaultProps}
  304. organization={newOrg.organization}
  305. selection={newSelection}
  306. />,
  307. {
  308. router: newOrg.router,
  309. organization: newOrg.organization,
  310. }
  311. );
  312. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  313. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  314. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  315. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  316. expect(screen.getByText('All Projects')).toBeInTheDocument();
  317. expect(mockRequest).toHaveBeenCalledWith(
  318. endpoint,
  319. expect.objectContaining({
  320. query: {
  321. statsPeriod: DEFAULT_STATS_PERIOD,
  322. interval: '1h',
  323. groupBy: ['outcome', 'reason'],
  324. project: selectedProject,
  325. field: ['sum(quantity)'],
  326. category: 'error',
  327. },
  328. })
  329. );
  330. });
  331. it('renders a project when its graph icon is clicked', async () => {
  332. const newOrg = initializeOrg();
  333. newOrg.organization.features = ['global-views', 'team-insights'];
  334. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  335. router: newOrg.router,
  336. organization: newOrg.organization,
  337. });
  338. await userEvent.click(screen.getByTestId('proj-1'));
  339. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  340. expect(screen.getAllByText('proj-1').length).toBe(2);
  341. });
  342. /**
  343. * Feature Flagging
  344. */
  345. it('renders legacy organization stats without appropriate flags', async () => {
  346. const selectedProject = [1];
  347. const newSelection = {
  348. ...defaultSelection,
  349. projects: selectedProject,
  350. };
  351. for (const features of [['team-insights'], ['team-insights']]) {
  352. const newOrg = initializeOrg();
  353. newOrg.organization.features = features;
  354. render(
  355. <OrganizationStats
  356. {...defaultProps}
  357. organization={newOrg.organization}
  358. selection={newSelection}
  359. />,
  360. {
  361. router: newOrg.router,
  362. organization: newOrg.organization,
  363. }
  364. );
  365. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  366. await act(tick);
  367. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  368. }
  369. });
  370. /**
  371. * Feature Flagging - Continuous Profiling
  372. */
  373. it('shows only profile duration category with continuous-profiling-stats feature', async () => {
  374. const newOrg = initializeOrg({
  375. organization: {
  376. features: ['global-views', 'team-insights', 'continuous-profiling-stats'],
  377. },
  378. });
  379. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  380. router: newOrg.router,
  381. });
  382. await userEvent.click(await screen.findByText('Category'));
  383. // Should show Profile Hours option
  384. expect(screen.getByRole('option', {name: 'Profile Hours'})).toBeInTheDocument();
  385. // Should not show Profiles (transaction) option
  386. expect(screen.queryByRole('option', {name: 'Profiles'})).not.toBeInTheDocument();
  387. });
  388. it('shows both profile hours and profiles categories with continuous-profiling feature', async () => {
  389. const newOrg = initializeOrg({
  390. organization: {
  391. features: ['global-views', 'team-insights', 'continuous-profiling'],
  392. },
  393. });
  394. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  395. router: newOrg.router,
  396. });
  397. await userEvent.click(await screen.findByText('Category'));
  398. // Should show Profile Hours option
  399. expect(screen.getByRole('option', {name: 'Profile Hours'})).toBeInTheDocument();
  400. // Should show Profiles (transaction) option
  401. expect(screen.queryByRole('option', {name: 'Profiles'})).toBeInTheDocument();
  402. });
  403. it('shows only profile duration category when both profiling features are enabled', async () => {
  404. const newOrg = initializeOrg({
  405. organization: {
  406. features: [
  407. 'global-views',
  408. 'team-insights',
  409. 'continuous-profiling-stats',
  410. 'continuous-profiling',
  411. ],
  412. },
  413. });
  414. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  415. router: newOrg.router,
  416. });
  417. await userEvent.click(await screen.findByText('Category'));
  418. // Should show Profile Hours option
  419. expect(screen.getByRole('option', {name: 'Profile Hours'})).toBeInTheDocument();
  420. // Should not show Profiles (transaction) option
  421. expect(screen.queryByRole('option', {name: 'Profiles'})).not.toBeInTheDocument();
  422. });
  423. it('shows only Profiles category without profiling features', async () => {
  424. const newOrg = initializeOrg({
  425. organization: {
  426. features: ['global-views', 'team-insights'],
  427. },
  428. });
  429. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  430. router: newOrg.router,
  431. });
  432. await userEvent.click(await screen.findByText('Category'));
  433. // Should show Profile Hours option
  434. expect(screen.queryByRole('option', {name: 'Profile Hours'})).not.toBeInTheDocument();
  435. // Should show Profiles (transaction) option
  436. expect(screen.getByRole('option', {name: 'Profiles'})).toBeInTheDocument();
  437. });
  438. });
  439. const mockStatsResponse = {
  440. start: '2021-01-01T00:00:00Z',
  441. end: '2021-01-07T00:00:00Z',
  442. intervals: [
  443. '2021-01-01T00:00:00Z',
  444. '2021-01-02T00:00:00Z',
  445. '2021-01-03T00:00:00Z',
  446. '2021-01-04T00:00:00Z',
  447. '2021-01-05T00:00:00Z',
  448. '2021-01-06T00:00:00Z',
  449. '2021-01-07T00:00:00Z',
  450. ],
  451. groups: [
  452. {
  453. by: {
  454. project: 1,
  455. category: 'error',
  456. outcome: 'accepted',
  457. },
  458. totals: {
  459. 'sum(quantity)': 28,
  460. },
  461. series: {
  462. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  463. },
  464. },
  465. {
  466. by: {
  467. project: 1,
  468. category: 'error',
  469. outcome: 'filtered',
  470. },
  471. totals: {
  472. 'sum(quantity)': 7,
  473. },
  474. series: {
  475. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  476. },
  477. },
  478. {
  479. by: {
  480. project: 1,
  481. category: 'error',
  482. outcome: 'rate_limited',
  483. },
  484. totals: {
  485. 'sum(quantity)': 14,
  486. },
  487. series: {
  488. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  489. },
  490. },
  491. {
  492. by: {
  493. project: 1,
  494. category: 'error',
  495. outcome: 'abuse',
  496. },
  497. totals: {
  498. 'sum(quantity)': 2,
  499. },
  500. series: {
  501. 'sum(quantity)': [2, 0, 0, 0, 0, 0, 0],
  502. },
  503. },
  504. {
  505. by: {
  506. project: 1,
  507. category: 'error',
  508. outcome: 'cardinality_limited',
  509. },
  510. totals: {
  511. 'sum(quantity)': 1,
  512. },
  513. series: {
  514. 'sum(quantity)': [1, 0, 0, 0, 0, 0, 0],
  515. },
  516. },
  517. {
  518. by: {
  519. project: 1,
  520. category: 'error',
  521. outcome: 'invalid',
  522. },
  523. totals: {
  524. 'sum(quantity)': 15,
  525. },
  526. series: {
  527. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  528. },
  529. },
  530. {
  531. by: {
  532. project: 1,
  533. category: 'error',
  534. outcome: 'client_discard',
  535. },
  536. totals: {
  537. 'sum(quantity)': 15,
  538. },
  539. series: {
  540. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  541. },
  542. },
  543. ],
  544. };