index.spec.tsx 15 KB

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