index.spec.tsx 15 KB

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