index.spec.tsx 13 KB

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