index.spec.tsx 15 KB

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