index.spec.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. // Default to Errors category
  82. expect(screen.getAllByText('Errors')[0]).toBeInTheDocument();
  83. // Render the chart and project table
  84. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  85. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  86. // Render the cards
  87. expect(screen.getAllByText('Total')[0]).toBeInTheDocument();
  88. expect(screen.getByText('64')).toBeInTheDocument();
  89. expect(screen.getAllByText('Accepted')[0]).toBeInTheDocument();
  90. expect(screen.getByText('28')).toBeInTheDocument();
  91. expect(await screen.findByText('6 in last min')).toBeInTheDocument();
  92. expect(screen.getAllByText('Filtered')[0]).toBeInTheDocument();
  93. expect(screen.getAllByText('7')[0]).toBeInTheDocument();
  94. expect(screen.getAllByText('Dropped')[0]).toBeInTheDocument();
  95. expect(screen.getAllByText('29')[0]).toBeInTheDocument();
  96. // Correct API Calls
  97. const mockExpectations = {
  98. UsageStatsOrg: {
  99. statsPeriod: DEFAULT_STATS_PERIOD,
  100. interval: '1h',
  101. groupBy: ['category', 'outcome'],
  102. project: [-1],
  103. field: ['sum(quantity)'],
  104. },
  105. UsageStatsPerMin: {
  106. statsPeriod: '5m',
  107. interval: '1m',
  108. groupBy: ['category', 'outcome'],
  109. project: [-1],
  110. field: ['sum(quantity)'],
  111. },
  112. UsageStatsProjects: {
  113. statsPeriod: DEFAULT_STATS_PERIOD,
  114. interval: '1h',
  115. groupBy: ['outcome', 'project'],
  116. project: [-1],
  117. field: ['sum(quantity)'],
  118. category: 'error',
  119. },
  120. };
  121. for (const query of Object.values(mockExpectations)) {
  122. expect(mockRequest).toHaveBeenCalledWith(
  123. endpoint,
  124. expect.objectContaining({query})
  125. );
  126. }
  127. });
  128. it('renders with an error on stats endpoint', async () => {
  129. MockApiClient.clearMockResponses();
  130. MockApiClient.addMockResponse({
  131. url: endpoint,
  132. statusCode: 500,
  133. });
  134. render(<OrganizationStats {...defaultProps} />, {router});
  135. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  136. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  137. expect(screen.getByTestId('error-messages')).toBeInTheDocument();
  138. });
  139. it('renders with an error when user has no projects', async () => {
  140. MockApiClient.clearMockResponses();
  141. MockApiClient.addMockResponse({
  142. url: endpoint,
  143. statusCode: 400,
  144. body: {detail: 'No projects available'},
  145. });
  146. render(<OrganizationStats {...defaultProps} />, {router});
  147. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  148. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  149. expect(screen.getByTestId('empty-message')).toBeInTheDocument();
  150. });
  151. it('renders with just errors category for errors-only self-hosted', async () => {
  152. ConfigStore.set('isSelfHostedErrorsOnly', true);
  153. render(<OrganizationStats {...defaultProps} />, {router});
  154. await userEvent.click(await screen.findByText('Category'));
  155. // Shows only errors as stats category
  156. expect(screen.getAllByRole('option')).toHaveLength(1);
  157. expect(screen.getByRole('option', {name: 'Errors'})).toBeInTheDocument();
  158. });
  159. /**
  160. * Router Handling
  161. */
  162. it('pushes state changes to the route', async () => {
  163. render(<OrganizationStats {...defaultProps} />, {router});
  164. await userEvent.click(await screen.findByText('Category'));
  165. await userEvent.click(screen.getByText('Attachments'));
  166. await waitFor(() =>
  167. expect(router.push).toHaveBeenCalledWith(
  168. expect.objectContaining({
  169. query: {dataCategory: DATA_CATEGORY_INFO.attachment.plural},
  170. })
  171. )
  172. );
  173. await userEvent.click(screen.getByText('Periodic'));
  174. await userEvent.click(screen.getByText('Cumulative'));
  175. await waitFor(() =>
  176. expect(router.push).toHaveBeenCalledWith(
  177. expect.objectContaining({
  178. query: {transform: ChartDataTransform.CUMULATIVE},
  179. })
  180. )
  181. );
  182. const inputQuery = 'proj-1';
  183. await userEvent.type(
  184. screen.getByRole('textbox', {name: 'Filter projects'}),
  185. `${inputQuery}{Enter}`
  186. );
  187. await waitFor(() =>
  188. expect(router.push).toHaveBeenCalledWith(
  189. expect.objectContaining({
  190. query: {query: inputQuery},
  191. })
  192. )
  193. );
  194. });
  195. it('does not leak query params onto next page links', async () => {
  196. const dummyLocation = PAGE_QUERY_PARAMS.reduce(
  197. (location, param) => {
  198. location.query[param] = '';
  199. return location;
  200. },
  201. {query: {}}
  202. );
  203. render(<OrganizationStats {...defaultProps} location={dummyLocation as any} />, {
  204. router,
  205. });
  206. const projectLinks = await screen.findAllByTestId('badge-display-name');
  207. expect(projectLinks.length).toBeGreaterThan(0);
  208. const leakingRegex = PAGE_QUERY_PARAMS.join('|');
  209. for (const projectLink of projectLinks) {
  210. expect(projectLink.closest('a')).toHaveAttribute(
  211. 'href',
  212. expect.not.stringMatching(leakingRegex)
  213. );
  214. }
  215. });
  216. /**
  217. * Project Selection
  218. */
  219. it('renders single project without global-views', async () => {
  220. const newOrg = initializeOrg();
  221. newOrg.organization.features = ['team-insights'];
  222. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  223. router: newOrg.router,
  224. organization: newOrg.organization,
  225. });
  226. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  227. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  228. expect(screen.queryByText('usage-stats-table')).not.toBeInTheDocument();
  229. });
  230. it('renders default projects with global-views', async () => {
  231. const newOrg = initializeOrg();
  232. newOrg.organization.features = ['global-views', 'team-insights'];
  233. OrganizationStore.onUpdate(newOrg.organization, {replace: true});
  234. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  235. router: newOrg.router,
  236. organization: newOrg.organization,
  237. });
  238. expect(await screen.findByText('All Projects')).toBeInTheDocument();
  239. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  240. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  241. mockRequest.mock.calls.forEach(([_path, {query}]) => {
  242. // Ignore UsageStatsPerMin's query
  243. if (query?.statsPeriod === '5m') {
  244. return;
  245. }
  246. expect(query.project).toEqual([ALL_ACCESS_PROJECTS]);
  247. expect(defaultSelection.projects).toEqual([]);
  248. });
  249. });
  250. it('renders with multiple projects selected', async () => {
  251. const newOrg = initializeOrg();
  252. newOrg.organization.features = ['global-views', 'team-insights'];
  253. const selectedProjects = [1, 2];
  254. const newSelection = {
  255. ...defaultSelection,
  256. projects: selectedProjects,
  257. };
  258. render(
  259. <OrganizationStats
  260. {...defaultProps}
  261. organization={newOrg.organization}
  262. selection={newSelection}
  263. />,
  264. {
  265. router: newOrg.router,
  266. organization: newOrg.organization,
  267. }
  268. );
  269. act(() => PageFiltersStore.updateProjects(selectedProjects, []));
  270. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  271. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  272. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  273. expect(mockRequest).toHaveBeenCalledWith(
  274. endpoint,
  275. expect.objectContaining({
  276. query: {
  277. statsPeriod: DEFAULT_STATS_PERIOD,
  278. interval: '1h',
  279. groupBy: ['category', 'outcome'],
  280. project: selectedProjects,
  281. field: ['sum(quantity)'],
  282. },
  283. })
  284. );
  285. });
  286. it('renders with a single project selected', async () => {
  287. const newOrg = initializeOrg();
  288. newOrg.organization.features = ['global-views', 'team-insights'];
  289. const selectedProject = [1];
  290. const newSelection = {
  291. ...defaultSelection,
  292. projects: selectedProject,
  293. };
  294. render(
  295. <OrganizationStats
  296. {...defaultProps}
  297. organization={newOrg.organization}
  298. selection={newSelection}
  299. />,
  300. {
  301. router: newOrg.router,
  302. organization: newOrg.organization,
  303. }
  304. );
  305. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  306. expect(await screen.findByTestId('usage-stats-chart')).toBeInTheDocument();
  307. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  308. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  309. expect(screen.getByText('All Projects')).toBeInTheDocument();
  310. expect(mockRequest).toHaveBeenCalledWith(
  311. endpoint,
  312. expect.objectContaining({
  313. query: {
  314. statsPeriod: DEFAULT_STATS_PERIOD,
  315. interval: '1h',
  316. groupBy: ['category', 'outcome'],
  317. project: selectedProject,
  318. field: ['sum(quantity)'],
  319. },
  320. })
  321. );
  322. });
  323. it('renders a project when its graph icon is clicked', async () => {
  324. const newOrg = initializeOrg();
  325. newOrg.organization.features = ['global-views', 'team-insights'];
  326. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  327. router: newOrg.router,
  328. organization: newOrg.organization,
  329. });
  330. await userEvent.click(screen.getByTestId('proj-1'));
  331. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  332. expect(screen.getAllByText('proj-1').length).toBe(2);
  333. });
  334. /**
  335. * Feature Flagging
  336. */
  337. it('renders legacy organization stats without appropriate flags', async () => {
  338. const selectedProject = [1];
  339. const newSelection = {
  340. ...defaultSelection,
  341. projects: selectedProject,
  342. };
  343. for (const features of [['team-insights'], ['team-insights']]) {
  344. const newOrg = initializeOrg();
  345. newOrg.organization.features = features;
  346. render(
  347. <OrganizationStats
  348. {...defaultProps}
  349. organization={newOrg.organization}
  350. selection={newSelection}
  351. />,
  352. {
  353. router: newOrg.router,
  354. organization: newOrg.organization,
  355. }
  356. );
  357. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  358. await act(tick);
  359. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  360. }
  361. });
  362. });
  363. const mockStatsResponse = {
  364. start: '2021-01-01T00:00:00Z',
  365. end: '2021-01-07T00:00:00Z',
  366. intervals: [
  367. '2021-01-01T00:00:00Z',
  368. '2021-01-02T00:00:00Z',
  369. '2021-01-03T00:00:00Z',
  370. '2021-01-04T00:00:00Z',
  371. '2021-01-05T00:00:00Z',
  372. '2021-01-06T00:00:00Z',
  373. '2021-01-07T00:00:00Z',
  374. ],
  375. groups: [
  376. {
  377. by: {
  378. project: 1,
  379. category: 'attachment',
  380. outcome: 'accepted',
  381. },
  382. totals: {
  383. 'sum(quantity)': 28000,
  384. },
  385. series: {
  386. 'sum(quantity)': [1000, 2000, 3000, 4000, 5000, 6000, 7000],
  387. },
  388. },
  389. {
  390. by: {
  391. project: 1,
  392. outcome: 'accepted',
  393. category: 'transaction',
  394. },
  395. totals: {
  396. 'sum(quantity)': 28,
  397. },
  398. series: {
  399. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  400. },
  401. },
  402. {
  403. by: {
  404. project: 1,
  405. category: 'error',
  406. outcome: 'accepted',
  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: 'filtered',
  420. },
  421. totals: {
  422. 'sum(quantity)': 7,
  423. },
  424. series: {
  425. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  426. },
  427. },
  428. {
  429. by: {
  430. project: 1,
  431. category: 'error',
  432. outcome: 'rate_limited',
  433. },
  434. totals: {
  435. 'sum(quantity)': 14,
  436. },
  437. series: {
  438. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  439. },
  440. },
  441. {
  442. by: {
  443. project: 1,
  444. category: 'error',
  445. outcome: 'invalid',
  446. },
  447. totals: {
  448. 'sum(quantity)': 15,
  449. },
  450. series: {
  451. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  452. },
  453. },
  454. {
  455. by: {
  456. project: 1,
  457. category: 'error',
  458. outcome: 'client_discard',
  459. },
  460. totals: {
  461. 'sum(quantity)': 15,
  462. },
  463. series: {
  464. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  465. },
  466. },
  467. ],
  468. };