index.spec.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. const mockStatsResponse = {
  372. start: '2021-01-01T00:00:00Z',
  373. end: '2021-01-07T00:00:00Z',
  374. intervals: [
  375. '2021-01-01T00:00:00Z',
  376. '2021-01-02T00:00:00Z',
  377. '2021-01-03T00:00:00Z',
  378. '2021-01-04T00:00:00Z',
  379. '2021-01-05T00:00:00Z',
  380. '2021-01-06T00:00:00Z',
  381. '2021-01-07T00:00:00Z',
  382. ],
  383. groups: [
  384. {
  385. by: {
  386. project: 1,
  387. category: 'error',
  388. outcome: 'accepted',
  389. },
  390. totals: {
  391. 'sum(quantity)': 28,
  392. },
  393. series: {
  394. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  395. },
  396. },
  397. {
  398. by: {
  399. project: 1,
  400. category: 'error',
  401. outcome: 'filtered',
  402. },
  403. totals: {
  404. 'sum(quantity)': 7,
  405. },
  406. series: {
  407. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  408. },
  409. },
  410. {
  411. by: {
  412. project: 1,
  413. category: 'error',
  414. outcome: 'rate_limited',
  415. },
  416. totals: {
  417. 'sum(quantity)': 14,
  418. },
  419. series: {
  420. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  421. },
  422. },
  423. {
  424. by: {
  425. project: 1,
  426. category: 'error',
  427. outcome: 'abuse',
  428. },
  429. totals: {
  430. 'sum(quantity)': 2,
  431. },
  432. series: {
  433. 'sum(quantity)': [2, 0, 0, 0, 0, 0, 0],
  434. },
  435. },
  436. {
  437. by: {
  438. project: 1,
  439. category: 'error',
  440. outcome: 'cardinality_limited',
  441. },
  442. totals: {
  443. 'sum(quantity)': 1,
  444. },
  445. series: {
  446. 'sum(quantity)': [1, 0, 0, 0, 0, 0, 0],
  447. },
  448. },
  449. {
  450. by: {
  451. project: 1,
  452. category: 'error',
  453. outcome: 'invalid',
  454. },
  455. totals: {
  456. 'sum(quantity)': 15,
  457. },
  458. series: {
  459. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  460. },
  461. },
  462. {
  463. by: {
  464. project: 1,
  465. category: 'error',
  466. outcome: 'client_discard',
  467. },
  468. totals: {
  469. 'sum(quantity)': 15,
  470. },
  471. series: {
  472. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  473. },
  474. },
  475. ],
  476. };