index.spec.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 {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 {DataCategory, 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. field: ['sum(quantity)'],
  106. },
  107. UsageStatsProjects: {
  108. statsPeriod: DEFAULT_STATS_PERIOD,
  109. interval: '1h',
  110. groupBy: ['outcome', 'project'],
  111. project: [-1],
  112. field: ['sum(quantity)'],
  113. category: 'error',
  114. },
  115. };
  116. for (const query of Object.values(mockExpectations)) {
  117. expect(mockRequest).toHaveBeenCalledWith(
  118. endpoint,
  119. expect.objectContaining({query})
  120. );
  121. }
  122. });
  123. it('renders with an error on stats endpoint', () => {
  124. MockApiClient.clearMockResponses();
  125. MockApiClient.addMockResponse({
  126. url: endpoint,
  127. statusCode: 500,
  128. });
  129. render(<OrganizationStats {...defaultProps} />, {context: routerContext});
  130. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  131. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  132. expect(screen.getByTestId('error-messages')).toBeInTheDocument();
  133. });
  134. it('renders with an error when user has no projects', () => {
  135. MockApiClient.clearMockResponses();
  136. MockApiClient.addMockResponse({
  137. url: endpoint,
  138. statusCode: 400,
  139. body: {detail: 'No projects available'},
  140. });
  141. render(<OrganizationStats {...defaultProps} />, {context: routerContext});
  142. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  143. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  144. expect(screen.getByTestId('empty-message')).toBeInTheDocument();
  145. });
  146. /**
  147. * Router Handling
  148. */
  149. it('pushes state changes to the route', () => {
  150. render(<OrganizationStats {...defaultProps} />, {context: routerContext});
  151. userEvent.click(screen.getByText('Category'));
  152. userEvent.click(screen.getByText('Attachments'));
  153. expect(router.push).toHaveBeenCalledWith(
  154. expect.objectContaining({
  155. query: {dataCategory: DataCategory.ATTACHMENTS},
  156. })
  157. );
  158. userEvent.click(screen.getByText('Periodic'));
  159. userEvent.click(screen.getByText('Cumulative'));
  160. expect(router.push).toHaveBeenCalledWith(
  161. expect.objectContaining({
  162. query: {transform: ChartDataTransform.CUMULATIVE},
  163. })
  164. );
  165. const inputQuery = 'proj-1';
  166. userEvent.type(
  167. screen.getByPlaceholderText('Filter your projects'),
  168. `${inputQuery}{enter}`
  169. );
  170. expect(router.push).toHaveBeenCalledWith(
  171. expect.objectContaining({
  172. query: {query: inputQuery},
  173. })
  174. );
  175. });
  176. it('does not leak query params onto next page links', () => {
  177. const dummyLocation = PAGE_QUERY_PARAMS.reduce(
  178. (location, param) => {
  179. location.query[param] = '';
  180. return location;
  181. },
  182. {query: {}}
  183. );
  184. render(<OrganizationStats {...defaultProps} location={dummyLocation as any} />, {
  185. context: routerContext,
  186. });
  187. const projectLinks = screen.getAllByTestId('badge-display-name');
  188. expect(projectLinks.length).toBeGreaterThan(0);
  189. const leakingRegex = PAGE_QUERY_PARAMS.join('|');
  190. for (const projectLink of projectLinks) {
  191. expect(projectLink.closest('a')).toHaveAttribute(
  192. 'href',
  193. expect.not.stringMatching(leakingRegex)
  194. );
  195. }
  196. });
  197. /**
  198. * Project Selection
  199. */
  200. it('renders with no projects selected', () => {
  201. const newOrg = initializeOrg();
  202. newOrg.organization.features = [
  203. 'global-views',
  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. });
  211. expect(screen.getByText('My Projects')).toBeInTheDocument();
  212. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  213. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  214. mockRequest.mock.calls.forEach(([_path, {query}]) => {
  215. // Ignore UsageStatsPerMin's query
  216. if (query?.statsPeriod === '5m') {
  217. return;
  218. }
  219. expect(query.project).toEqual([ALL_ACCESS_PROJECTS]);
  220. expect(defaultSelection.projects).toEqual([]);
  221. });
  222. });
  223. it('renders with multiple projects selected', () => {
  224. const newOrg = initializeOrg();
  225. newOrg.organization.features = [
  226. 'global-views',
  227. 'team-insights',
  228. // TODO(Leander): Remove the following check once the project-stats flag is GA
  229. 'project-stats',
  230. ];
  231. const selectedProjects = [1, 2];
  232. const newSelection = {
  233. ...defaultSelection,
  234. projects: selectedProjects,
  235. };
  236. render(
  237. <OrganizationStats
  238. {...defaultProps}
  239. organization={newOrg.organization}
  240. selection={newSelection}
  241. />,
  242. {context: newOrg.routerContext}
  243. );
  244. act(() => PageFiltersStore.updateProjects(selectedProjects, []));
  245. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  246. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  247. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  248. expect(mockRequest).toHaveBeenCalledWith(
  249. endpoint,
  250. expect.objectContaining({
  251. query: {
  252. statsPeriod: DEFAULT_STATS_PERIOD,
  253. interval: '1h',
  254. groupBy: ['category', 'outcome'],
  255. project: selectedProjects,
  256. field: ['sum(quantity)'],
  257. },
  258. })
  259. );
  260. });
  261. it('renders with a single project selected', () => {
  262. const newOrg = initializeOrg();
  263. newOrg.organization.features = [
  264. 'global-views',
  265. 'team-insights',
  266. // TODO(Leander): Remove the following check once the project-stats flag is GA
  267. 'project-stats',
  268. ];
  269. const selectedProject = [1];
  270. const newSelection = {
  271. ...defaultSelection,
  272. projects: selectedProject,
  273. };
  274. render(
  275. <OrganizationStats
  276. {...defaultProps}
  277. organization={newOrg.organization}
  278. selection={newSelection}
  279. />,
  280. {context: newOrg.routerContext}
  281. );
  282. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  283. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  284. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  285. // Doesn't render for single project view
  286. expect(screen.queryByTestId('usage-stats-table')).not.toBeInTheDocument();
  287. expect(mockRequest).toHaveBeenCalledWith(
  288. endpoint,
  289. expect.objectContaining({
  290. query: {
  291. statsPeriod: DEFAULT_STATS_PERIOD,
  292. interval: '1h',
  293. groupBy: ['category', 'outcome'],
  294. project: selectedProject,
  295. field: ['sum(quantity)'],
  296. },
  297. })
  298. );
  299. });
  300. /**
  301. * Feature Flagging
  302. */
  303. it('renders legacy organization stats without appropriate flags', () => {
  304. const selectedProject = [1];
  305. const newSelection = {
  306. ...defaultSelection,
  307. projects: selectedProject,
  308. };
  309. for (const features of [
  310. ['team-insights'],
  311. ['team-insights', 'project-stats'],
  312. ['team-insights', 'global-views'],
  313. ]) {
  314. const newOrg = initializeOrg();
  315. newOrg.organization.features = features;
  316. render(
  317. <OrganizationStats
  318. {...defaultProps}
  319. organization={newOrg.organization}
  320. selection={newSelection}
  321. />,
  322. {context: newOrg.routerContext}
  323. );
  324. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  325. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  326. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  327. cleanup();
  328. }
  329. });
  330. });
  331. const mockStatsResponse = {
  332. start: '2021-01-01T00:00:00Z',
  333. end: '2021-01-07T00:00:00Z',
  334. intervals: [
  335. '2021-01-01T00:00:00Z',
  336. '2021-01-02T00:00:00Z',
  337. '2021-01-03T00:00:00Z',
  338. '2021-01-04T00:00:00Z',
  339. '2021-01-05T00:00:00Z',
  340. '2021-01-06T00:00:00Z',
  341. '2021-01-07T00:00:00Z',
  342. ],
  343. groups: [
  344. {
  345. by: {
  346. project: 1,
  347. category: 'attachment',
  348. outcome: 'accepted',
  349. },
  350. totals: {
  351. 'sum(quantity)': 28000,
  352. },
  353. series: {
  354. 'sum(quantity)': [1000, 2000, 3000, 4000, 5000, 6000, 7000],
  355. },
  356. },
  357. {
  358. by: {
  359. project: 1,
  360. outcome: 'accepted',
  361. category: 'transaction',
  362. },
  363. totals: {
  364. 'sum(quantity)': 28,
  365. },
  366. series: {
  367. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  368. },
  369. },
  370. {
  371. by: {
  372. project: 1,
  373. category: 'error',
  374. outcome: 'accepted',
  375. },
  376. totals: {
  377. 'sum(quantity)': 28,
  378. },
  379. series: {
  380. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  381. },
  382. },
  383. {
  384. by: {
  385. project: 1,
  386. category: 'error',
  387. outcome: 'filtered',
  388. },
  389. totals: {
  390. 'sum(quantity)': 7,
  391. },
  392. series: {
  393. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  394. },
  395. },
  396. {
  397. by: {
  398. project: 1,
  399. category: 'error',
  400. outcome: 'rate_limited',
  401. },
  402. totals: {
  403. 'sum(quantity)': 14,
  404. },
  405. series: {
  406. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  407. },
  408. },
  409. {
  410. by: {
  411. project: 1,
  412. category: 'error',
  413. outcome: 'invalid',
  414. },
  415. totals: {
  416. 'sum(quantity)': 15,
  417. },
  418. series: {
  419. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  420. },
  421. },
  422. {
  423. by: {
  424. project: 1,
  425. category: 'error',
  426. outcome: 'client_discard',
  427. },
  428. totals: {
  429. 'sum(quantity)': 15,
  430. },
  431. series: {
  432. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  433. },
  434. },
  435. ],
  436. };