index.spec.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. 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: DATA_CATEGORY_INFO.attachment.plural},
  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 single project without global-views', () => {
  201. const newOrg = initializeOrg();
  202. newOrg.organization.features = [
  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.queryByText('My Projects')).not.toBeInTheDocument();
  211. expect(screen.queryByTestId('usage-stats-chart')).toBeInTheDocument();
  212. expect(screen.queryByText('usage-stats-table')).not.toBeInTheDocument();
  213. });
  214. it('renders default projects with global-views', () => {
  215. const newOrg = initializeOrg();
  216. newOrg.organization.features = [
  217. 'global-views',
  218. 'team-insights',
  219. // TODO(Leander): Remove the following check once the project-stats flag is GA
  220. 'project-stats',
  221. ];
  222. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  223. context: newOrg.routerContext,
  224. });
  225. expect(screen.getByText('My Projects')).toBeInTheDocument();
  226. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  227. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  228. mockRequest.mock.calls.forEach(([_path, {query}]) => {
  229. // Ignore UsageStatsPerMin's query
  230. if (query?.statsPeriod === '5m') {
  231. return;
  232. }
  233. expect(query.project).toEqual([ALL_ACCESS_PROJECTS]);
  234. expect(defaultSelection.projects).toEqual([]);
  235. });
  236. });
  237. it('renders with multiple projects selected', () => {
  238. const newOrg = initializeOrg();
  239. newOrg.organization.features = [
  240. 'global-views',
  241. 'team-insights',
  242. // TODO(Leander): Remove the following check once the project-stats flag is GA
  243. 'project-stats',
  244. ];
  245. const selectedProjects = [1, 2];
  246. const newSelection = {
  247. ...defaultSelection,
  248. projects: selectedProjects,
  249. };
  250. render(
  251. <OrganizationStats
  252. {...defaultProps}
  253. organization={newOrg.organization}
  254. selection={newSelection}
  255. />,
  256. {context: newOrg.routerContext}
  257. );
  258. act(() => PageFiltersStore.updateProjects(selectedProjects, []));
  259. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  260. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  261. expect(screen.getByTestId('usage-stats-table')).toBeInTheDocument();
  262. expect(mockRequest).toHaveBeenCalledWith(
  263. endpoint,
  264. expect.objectContaining({
  265. query: {
  266. statsPeriod: DEFAULT_STATS_PERIOD,
  267. interval: '1h',
  268. groupBy: ['category', 'outcome'],
  269. project: selectedProjects,
  270. field: ['sum(quantity)'],
  271. },
  272. })
  273. );
  274. });
  275. it('renders with a single project selected', () => {
  276. const newOrg = initializeOrg();
  277. newOrg.organization.features = [
  278. 'global-views',
  279. 'team-insights',
  280. // TODO(Leander): Remove the following check once the project-stats flag is GA
  281. 'project-stats',
  282. ];
  283. const selectedProject = [1];
  284. const newSelection = {
  285. ...defaultSelection,
  286. projects: selectedProject,
  287. };
  288. render(
  289. <OrganizationStats
  290. {...defaultProps}
  291. organization={newOrg.organization}
  292. selection={newSelection}
  293. />,
  294. {context: newOrg.routerContext}
  295. );
  296. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  297. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  298. expect(screen.getByTestId('usage-stats-chart')).toBeInTheDocument();
  299. // Doesn't render for single project view
  300. expect(screen.queryByTestId('usage-stats-table')).not.toBeInTheDocument();
  301. expect(mockRequest).toHaveBeenCalledWith(
  302. endpoint,
  303. expect.objectContaining({
  304. query: {
  305. statsPeriod: DEFAULT_STATS_PERIOD,
  306. interval: '1h',
  307. groupBy: ['category', 'outcome'],
  308. project: selectedProject,
  309. field: ['sum(quantity)'],
  310. },
  311. })
  312. );
  313. });
  314. /**
  315. * Feature Flagging
  316. */
  317. it('renders legacy organization stats without appropriate flags', () => {
  318. const selectedProject = [1];
  319. const newSelection = {
  320. ...defaultSelection,
  321. projects: selectedProject,
  322. };
  323. for (const features of [['team-insights'], ['team-insights', 'project-stats']]) {
  324. const newOrg = initializeOrg();
  325. newOrg.organization.features = features;
  326. render(
  327. <OrganizationStats
  328. {...defaultProps}
  329. organization={newOrg.organization}
  330. selection={newSelection}
  331. />,
  332. {context: newOrg.routerContext}
  333. );
  334. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  335. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  336. cleanup();
  337. }
  338. });
  339. });
  340. const mockStatsResponse = {
  341. start: '2021-01-01T00:00:00Z',
  342. end: '2021-01-07T00:00:00Z',
  343. intervals: [
  344. '2021-01-01T00:00:00Z',
  345. '2021-01-02T00:00:00Z',
  346. '2021-01-03T00:00:00Z',
  347. '2021-01-04T00:00:00Z',
  348. '2021-01-05T00:00:00Z',
  349. '2021-01-06T00:00:00Z',
  350. '2021-01-07T00:00:00Z',
  351. ],
  352. groups: [
  353. {
  354. by: {
  355. project: 1,
  356. category: 'attachment',
  357. outcome: 'accepted',
  358. },
  359. totals: {
  360. 'sum(quantity)': 28000,
  361. },
  362. series: {
  363. 'sum(quantity)': [1000, 2000, 3000, 4000, 5000, 6000, 7000],
  364. },
  365. },
  366. {
  367. by: {
  368. project: 1,
  369. outcome: 'accepted',
  370. category: 'transaction',
  371. },
  372. totals: {
  373. 'sum(quantity)': 28,
  374. },
  375. series: {
  376. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  377. },
  378. },
  379. {
  380. by: {
  381. project: 1,
  382. category: 'error',
  383. outcome: 'accepted',
  384. },
  385. totals: {
  386. 'sum(quantity)': 28,
  387. },
  388. series: {
  389. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  390. },
  391. },
  392. {
  393. by: {
  394. project: 1,
  395. category: 'error',
  396. outcome: 'filtered',
  397. },
  398. totals: {
  399. 'sum(quantity)': 7,
  400. },
  401. series: {
  402. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  403. },
  404. },
  405. {
  406. by: {
  407. project: 1,
  408. category: 'error',
  409. outcome: 'rate_limited',
  410. },
  411. totals: {
  412. 'sum(quantity)': 14,
  413. },
  414. series: {
  415. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  416. },
  417. },
  418. {
  419. by: {
  420. project: 1,
  421. category: 'error',
  422. outcome: 'invalid',
  423. },
  424. totals: {
  425. 'sum(quantity)': 15,
  426. },
  427. series: {
  428. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  429. },
  430. },
  431. {
  432. by: {
  433. project: 1,
  434. category: 'error',
  435. outcome: 'client_discard',
  436. },
  437. totals: {
  438. 'sum(quantity)': 15,
  439. },
  440. series: {
  441. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  442. },
  443. },
  444. ],
  445. };