index.spec.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. import {ProjectFixture} from 'sentry-fixture/project';
  2. import {initializeOrg} from 'sentry-test/initializeOrg';
  3. import {act, cleanup, render, screen, userEvent} 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', () => {
  60. const newOrg = initializeOrg();
  61. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  62. context: newOrg.routerContext,
  63. });
  64. expect(screen.getByText('Organization Usage Stats')).toBeInTheDocument();
  65. });
  66. it('renders header state with tabs', () => {
  67. render(<OrganizationStats {...defaultProps} />, {context: routerContext});
  68. expect(screen.getByText('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', () => {
  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(screen.getByText('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', () => {
  126. MockApiClient.clearMockResponses();
  127. MockApiClient.addMockResponse({
  128. url: endpoint,
  129. statusCode: 500,
  130. });
  131. render(<OrganizationStats {...defaultProps} />, {context: routerContext});
  132. expect(screen.getByTestId('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', () => {
  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(screen.getByTestId('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(screen.getByText('Category'));
  154. await userEvent.click(screen.getByText('Attachments'));
  155. expect(router.push).toHaveBeenCalledWith(
  156. expect.objectContaining({
  157. query: {dataCategory: DATA_CATEGORY_INFO.attachment.plural},
  158. })
  159. );
  160. await userEvent.click(screen.getByText('Periodic'));
  161. await userEvent.click(screen.getByText('Cumulative'));
  162. expect(router.push).toHaveBeenCalledWith(
  163. expect.objectContaining({
  164. query: {transform: ChartDataTransform.CUMULATIVE},
  165. })
  166. );
  167. const inputQuery = 'proj-1';
  168. await userEvent.type(
  169. screen.getByPlaceholderText('Filter your projects'),
  170. `${inputQuery}{enter}`
  171. );
  172. expect(router.push).toHaveBeenCalledWith(
  173. expect.objectContaining({
  174. query: {query: inputQuery},
  175. })
  176. );
  177. });
  178. it('does not leak query params onto next page links', () => {
  179. const dummyLocation = PAGE_QUERY_PARAMS.reduce(
  180. (location, param) => {
  181. location.query[param] = '';
  182. return location;
  183. },
  184. {query: {}}
  185. );
  186. render(<OrganizationStats {...defaultProps} location={dummyLocation as any} />, {
  187. context: routerContext,
  188. });
  189. const projectLinks = screen.getAllByTestId('badge-display-name');
  190. expect(projectLinks.length).toBeGreaterThan(0);
  191. const leakingRegex = PAGE_QUERY_PARAMS.join('|');
  192. for (const projectLink of projectLinks) {
  193. expect(projectLink.closest('a')).toHaveAttribute(
  194. 'href',
  195. expect.not.stringMatching(leakingRegex)
  196. );
  197. }
  198. });
  199. /**
  200. * Project Selection
  201. */
  202. it('renders single project without global-views', () => {
  203. const newOrg = initializeOrg();
  204. newOrg.organization.features = [
  205. 'team-insights',
  206. // TODO(Leander): Remove the following check once the project-stats flag is GA
  207. 'project-stats',
  208. ];
  209. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  210. context: newOrg.routerContext,
  211. organization: newOrg.organization,
  212. });
  213. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  214. expect(screen.queryByTestId('usage-stats-chart')).toBeInTheDocument();
  215. expect(screen.queryByText('usage-stats-table')).not.toBeInTheDocument();
  216. });
  217. it('renders default projects with global-views', () => {
  218. const newOrg = initializeOrg();
  219. newOrg.organization.features = [
  220. 'global-views',
  221. 'team-insights',
  222. // TODO(Leander): Remove the following check once the project-stats flag is GA
  223. 'project-stats',
  224. ];
  225. OrganizationStore.onUpdate(newOrg.organization, {replace: true});
  226. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  227. context: newOrg.routerContext,
  228. organization: newOrg.organization,
  229. });
  230. expect(screen.getByText('All Projects')).toBeInTheDocument();
  231. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  232. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  233. mockRequest.mock.calls.forEach(([_path, {query}]) => {
  234. // Ignore UsageStatsPerMin's query
  235. if (query?.statsPeriod === '5m') {
  236. return;
  237. }
  238. expect(query.project).toEqual([ALL_ACCESS_PROJECTS]);
  239. expect(defaultSelection.projects).toEqual([]);
  240. });
  241. });
  242. it('renders with multiple projects selected', () => {
  243. const newOrg = initializeOrg();
  244. newOrg.organization.features = [
  245. 'global-views',
  246. 'team-insights',
  247. // TODO(Leander): Remove the following check once the project-stats flag is GA
  248. 'project-stats',
  249. ];
  250. const selectedProjects = [1, 2];
  251. const newSelection = {
  252. ...defaultSelection,
  253. projects: selectedProjects,
  254. };
  255. render(
  256. <OrganizationStats
  257. {...defaultProps}
  258. organization={newOrg.organization}
  259. selection={newSelection}
  260. />,
  261. {
  262. context: newOrg.routerContext,
  263. organization: newOrg.organization,
  264. }
  265. );
  266. act(() => PageFiltersStore.updateProjects(selectedProjects, []));
  267. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  268. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  269. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  270. expect(mockRequest).toHaveBeenCalledWith(
  271. endpoint,
  272. expect.objectContaining({
  273. query: {
  274. statsPeriod: DEFAULT_STATS_PERIOD,
  275. interval: '1h',
  276. groupBy: ['category', 'outcome'],
  277. project: selectedProjects,
  278. field: ['sum(quantity)'],
  279. },
  280. })
  281. );
  282. });
  283. it('renders with a single project selected', () => {
  284. const newOrg = initializeOrg();
  285. newOrg.organization.features = [
  286. 'global-views',
  287. 'team-insights',
  288. // TODO(Leander): Remove the following check once the project-stats flag is GA
  289. 'project-stats',
  290. ];
  291. const selectedProject = [1];
  292. const newSelection = {
  293. ...defaultSelection,
  294. projects: selectedProject,
  295. };
  296. render(
  297. <OrganizationStats
  298. {...defaultProps}
  299. organization={newOrg.organization}
  300. selection={newSelection}
  301. />,
  302. {
  303. context: newOrg.routerContext,
  304. organization: newOrg.organization,
  305. }
  306. );
  307. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  308. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  309. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  310. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  311. expect(screen.getByText('All Projects')).toBeInTheDocument();
  312. expect(mockRequest).toHaveBeenCalledWith(
  313. endpoint,
  314. expect.objectContaining({
  315. query: {
  316. statsPeriod: DEFAULT_STATS_PERIOD,
  317. interval: '1h',
  318. groupBy: ['category', 'outcome'],
  319. project: selectedProject,
  320. field: ['sum(quantity)'],
  321. },
  322. })
  323. );
  324. });
  325. it('renders a project when its graph icon is clicked', async () => {
  326. const newOrg = initializeOrg();
  327. newOrg.organization.features = [
  328. 'global-views',
  329. 'team-insights',
  330. // TODO(Leander): Remove the following check once the project-stats flag is GA
  331. 'project-stats',
  332. ];
  333. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  334. context: newOrg.routerContext,
  335. organization: newOrg.organization,
  336. });
  337. await userEvent.click(screen.getByTestId('proj-1'));
  338. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  339. expect(screen.getAllByText('proj-1').length).toBe(2);
  340. });
  341. /**
  342. * Feature Flagging
  343. */
  344. it('renders legacy organization stats without appropriate flags', () => {
  345. const selectedProject = [1];
  346. const newSelection = {
  347. ...defaultSelection,
  348. projects: selectedProject,
  349. };
  350. for (const features of [['team-insights'], ['team-insights', 'project-stats']]) {
  351. const newOrg = initializeOrg();
  352. newOrg.organization.features = features;
  353. render(
  354. <OrganizationStats
  355. {...defaultProps}
  356. organization={newOrg.organization}
  357. selection={newSelection}
  358. />,
  359. {
  360. context: newOrg.routerContext,
  361. organization: newOrg.organization,
  362. }
  363. );
  364. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  365. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  366. cleanup();
  367. }
  368. });
  369. });
  370. const mockStatsResponse = {
  371. start: '2021-01-01T00:00:00Z',
  372. end: '2021-01-07T00:00:00Z',
  373. intervals: [
  374. '2021-01-01T00:00:00Z',
  375. '2021-01-02T00:00:00Z',
  376. '2021-01-03T00:00:00Z',
  377. '2021-01-04T00:00:00Z',
  378. '2021-01-05T00:00:00Z',
  379. '2021-01-06T00:00:00Z',
  380. '2021-01-07T00:00:00Z',
  381. ],
  382. groups: [
  383. {
  384. by: {
  385. project: 1,
  386. category: 'attachment',
  387. outcome: 'accepted',
  388. },
  389. totals: {
  390. 'sum(quantity)': 28000,
  391. },
  392. series: {
  393. 'sum(quantity)': [1000, 2000, 3000, 4000, 5000, 6000, 7000],
  394. },
  395. },
  396. {
  397. by: {
  398. project: 1,
  399. outcome: 'accepted',
  400. category: 'transaction',
  401. },
  402. totals: {
  403. 'sum(quantity)': 28,
  404. },
  405. series: {
  406. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  407. },
  408. },
  409. {
  410. by: {
  411. project: 1,
  412. category: 'error',
  413. outcome: 'accepted',
  414. },
  415. totals: {
  416. 'sum(quantity)': 28,
  417. },
  418. series: {
  419. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  420. },
  421. },
  422. {
  423. by: {
  424. project: 1,
  425. category: 'error',
  426. outcome: 'filtered',
  427. },
  428. totals: {
  429. 'sum(quantity)': 7,
  430. },
  431. series: {
  432. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  433. },
  434. },
  435. {
  436. by: {
  437. project: 1,
  438. category: 'error',
  439. outcome: 'rate_limited',
  440. },
  441. totals: {
  442. 'sum(quantity)': 14,
  443. },
  444. series: {
  445. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  446. },
  447. },
  448. {
  449. by: {
  450. project: 1,
  451. category: 'error',
  452. outcome: 'invalid',
  453. },
  454. totals: {
  455. 'sum(quantity)': 15,
  456. },
  457. series: {
  458. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  459. },
  460. },
  461. {
  462. by: {
  463. project: 1,
  464. category: 'error',
  465. outcome: 'client_discard',
  466. },
  467. totals: {
  468. 'sum(quantity)': 15,
  469. },
  470. series: {
  471. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  472. },
  473. },
  474. ],
  475. };