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