index.spec.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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';
  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 = [
  211. 'team-insights',
  212. // TODO(Leander): Remove the following check once the project-stats flag is GA
  213. 'project-stats',
  214. ];
  215. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  216. context: newOrg.routerContext,
  217. organization: newOrg.organization,
  218. });
  219. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  220. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  221. expect(screen.queryByText('usage-stats-table')).not.toBeInTheDocument();
  222. });
  223. it('renders default projects with global-views', async () => {
  224. const newOrg = initializeOrg();
  225. newOrg.organization.features = [
  226. 'global-views',
  227. 'team-insights',
  228. // TODO(Leander): Remove the following check once the project-stats flag is GA
  229. 'project-stats',
  230. ];
  231. OrganizationStore.onUpdate(newOrg.organization, {replace: true});
  232. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  233. context: newOrg.routerContext,
  234. organization: newOrg.organization,
  235. });
  236. expect(await screen.findByText('All Projects')).toBeInTheDocument();
  237. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  238. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  239. mockRequest.mock.calls.forEach(([_path, {query}]) => {
  240. // Ignore UsageStatsPerMin's query
  241. if (query?.statsPeriod === '5m') {
  242. return;
  243. }
  244. expect(query.project).toEqual([ALL_ACCESS_PROJECTS]);
  245. expect(defaultSelection.projects).toEqual([]);
  246. });
  247. });
  248. it('renders with multiple projects selected', async () => {
  249. const newOrg = initializeOrg();
  250. newOrg.organization.features = [
  251. 'global-views',
  252. 'team-insights',
  253. // TODO(Leander): Remove the following check once the project-stats flag is GA
  254. 'project-stats',
  255. ];
  256. const selectedProjects = [1, 2];
  257. const newSelection = {
  258. ...defaultSelection,
  259. projects: selectedProjects,
  260. };
  261. render(
  262. <OrganizationStats
  263. {...defaultProps}
  264. organization={newOrg.organization}
  265. selection={newSelection}
  266. />,
  267. {
  268. context: newOrg.routerContext,
  269. organization: newOrg.organization,
  270. }
  271. );
  272. act(() => PageFiltersStore.updateProjects(selectedProjects, []));
  273. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  274. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  275. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  276. expect(mockRequest).toHaveBeenCalledWith(
  277. endpoint,
  278. expect.objectContaining({
  279. query: {
  280. statsPeriod: DEFAULT_STATS_PERIOD,
  281. interval: '1h',
  282. groupBy: ['category', 'outcome'],
  283. project: selectedProjects,
  284. field: ['sum(quantity)'],
  285. },
  286. })
  287. );
  288. });
  289. it('renders with a single project selected', async () => {
  290. const newOrg = initializeOrg();
  291. newOrg.organization.features = [
  292. 'global-views',
  293. 'team-insights',
  294. // TODO(Leander): Remove the following check once the project-stats flag is GA
  295. 'project-stats',
  296. ];
  297. const selectedProject = [1];
  298. const newSelection = {
  299. ...defaultSelection,
  300. projects: selectedProject,
  301. };
  302. render(
  303. <OrganizationStats
  304. {...defaultProps}
  305. organization={newOrg.organization}
  306. selection={newSelection}
  307. />,
  308. {
  309. context: newOrg.routerContext,
  310. organization: newOrg.organization,
  311. }
  312. );
  313. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  314. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  315. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  316. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  317. expect(screen.getByText('All Projects')).toBeInTheDocument();
  318. expect(mockRequest).toHaveBeenCalledWith(
  319. endpoint,
  320. expect.objectContaining({
  321. query: {
  322. statsPeriod: DEFAULT_STATS_PERIOD,
  323. interval: '1h',
  324. groupBy: ['category', 'outcome'],
  325. project: selectedProject,
  326. field: ['sum(quantity)'],
  327. },
  328. })
  329. );
  330. });
  331. it('renders a project when its graph icon is clicked', async () => {
  332. const newOrg = initializeOrg();
  333. newOrg.organization.features = [
  334. 'global-views',
  335. 'team-insights',
  336. // TODO(Leander): Remove the following check once the project-stats flag is GA
  337. 'project-stats',
  338. ];
  339. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  340. context: newOrg.routerContext,
  341. organization: newOrg.organization,
  342. });
  343. await userEvent.click(screen.getByTestId('proj-1'));
  344. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  345. expect(screen.getAllByText('proj-1').length).toBe(2);
  346. });
  347. /**
  348. * Feature Flagging
  349. */
  350. it('renders legacy organization stats without appropriate flags', async () => {
  351. const selectedProject = [1];
  352. const newSelection = {
  353. ...defaultSelection,
  354. projects: selectedProject,
  355. };
  356. for (const features of [['team-insights'], ['team-insights', 'project-stats']]) {
  357. const newOrg = initializeOrg();
  358. newOrg.organization.features = features;
  359. render(
  360. <OrganizationStats
  361. {...defaultProps}
  362. organization={newOrg.organization}
  363. selection={newSelection}
  364. />,
  365. {
  366. context: newOrg.routerContext,
  367. organization: newOrg.organization,
  368. }
  369. );
  370. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  371. await act(tick);
  372. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  373. }
  374. });
  375. });
  376. const mockStatsResponse = {
  377. start: '2021-01-01T00:00:00Z',
  378. end: '2021-01-07T00:00:00Z',
  379. intervals: [
  380. '2021-01-01T00:00:00Z',
  381. '2021-01-02T00:00:00Z',
  382. '2021-01-03T00:00:00Z',
  383. '2021-01-04T00:00:00Z',
  384. '2021-01-05T00:00:00Z',
  385. '2021-01-06T00:00:00Z',
  386. '2021-01-07T00:00:00Z',
  387. ],
  388. groups: [
  389. {
  390. by: {
  391. project: 1,
  392. category: 'attachment',
  393. outcome: 'accepted',
  394. },
  395. totals: {
  396. 'sum(quantity)': 28000,
  397. },
  398. series: {
  399. 'sum(quantity)': [1000, 2000, 3000, 4000, 5000, 6000, 7000],
  400. },
  401. },
  402. {
  403. by: {
  404. project: 1,
  405. outcome: 'accepted',
  406. category: 'transaction',
  407. },
  408. totals: {
  409. 'sum(quantity)': 28,
  410. },
  411. series: {
  412. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  413. },
  414. },
  415. {
  416. by: {
  417. project: 1,
  418. category: 'error',
  419. outcome: 'accepted',
  420. },
  421. totals: {
  422. 'sum(quantity)': 28,
  423. },
  424. series: {
  425. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  426. },
  427. },
  428. {
  429. by: {
  430. project: 1,
  431. category: 'error',
  432. outcome: 'filtered',
  433. },
  434. totals: {
  435. 'sum(quantity)': 7,
  436. },
  437. series: {
  438. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  439. },
  440. },
  441. {
  442. by: {
  443. project: 1,
  444. category: 'error',
  445. outcome: 'rate_limited',
  446. },
  447. totals: {
  448. 'sum(quantity)': 14,
  449. },
  450. series: {
  451. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  452. },
  453. },
  454. {
  455. by: {
  456. project: 1,
  457. category: 'error',
  458. outcome: 'invalid',
  459. },
  460. totals: {
  461. 'sum(quantity)': 15,
  462. },
  463. series: {
  464. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  465. },
  466. },
  467. {
  468. by: {
  469. project: 1,
  470. category: 'error',
  471. outcome: 'client_discard',
  472. },
  473. totals: {
  474. 'sum(quantity)': 15,
  475. },
  476. series: {
  477. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  478. },
  479. },
  480. ],
  481. };