index.spec.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. it('renders a project when its graph icon is clicked', async () => {
  316. const newOrg = initializeOrg();
  317. newOrg.organization.features = [
  318. 'global-views',
  319. 'team-insights',
  320. // TODO(Leander): Remove the following check once the project-stats flag is GA
  321. 'project-stats',
  322. ];
  323. render(<OrganizationStats {...defaultProps} organization={newOrg.organization} />, {
  324. context: newOrg.routerContext,
  325. });
  326. await userEvent.click(screen.getByTestId('proj-1'));
  327. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  328. expect(screen.getAllByText('proj-1').length).toBe(2);
  329. });
  330. /**
  331. * Feature Flagging
  332. */
  333. it('renders legacy organization stats without appropriate flags', () => {
  334. const selectedProject = [1];
  335. const newSelection = {
  336. ...defaultSelection,
  337. projects: selectedProject,
  338. };
  339. for (const features of [['team-insights'], ['team-insights', 'project-stats']]) {
  340. const newOrg = initializeOrg();
  341. newOrg.organization.features = features;
  342. render(
  343. <OrganizationStats
  344. {...defaultProps}
  345. organization={newOrg.organization}
  346. selection={newSelection}
  347. />,
  348. {context: newOrg.routerContext}
  349. );
  350. act(() => PageFiltersStore.updateProjects(selectedProject, []));
  351. expect(screen.queryByText('My Projects')).not.toBeInTheDocument();
  352. cleanup();
  353. }
  354. });
  355. });
  356. const mockStatsResponse = {
  357. start: '2021-01-01T00:00:00Z',
  358. end: '2021-01-07T00:00:00Z',
  359. intervals: [
  360. '2021-01-01T00:00:00Z',
  361. '2021-01-02T00:00:00Z',
  362. '2021-01-03T00:00:00Z',
  363. '2021-01-04T00:00:00Z',
  364. '2021-01-05T00:00:00Z',
  365. '2021-01-06T00:00:00Z',
  366. '2021-01-07T00:00:00Z',
  367. ],
  368. groups: [
  369. {
  370. by: {
  371. project: 1,
  372. category: 'attachment',
  373. outcome: 'accepted',
  374. },
  375. totals: {
  376. 'sum(quantity)': 28000,
  377. },
  378. series: {
  379. 'sum(quantity)': [1000, 2000, 3000, 4000, 5000, 6000, 7000],
  380. },
  381. },
  382. {
  383. by: {
  384. project: 1,
  385. outcome: 'accepted',
  386. category: 'transaction',
  387. },
  388. totals: {
  389. 'sum(quantity)': 28,
  390. },
  391. series: {
  392. 'sum(quantity)': [1, 2, 3, 4, 5, 6, 7],
  393. },
  394. },
  395. {
  396. by: {
  397. project: 1,
  398. category: 'error',
  399. outcome: 'accepted',
  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: 'filtered',
  413. },
  414. totals: {
  415. 'sum(quantity)': 7,
  416. },
  417. series: {
  418. 'sum(quantity)': [1, 1, 1, 1, 1, 1, 1],
  419. },
  420. },
  421. {
  422. by: {
  423. project: 1,
  424. category: 'error',
  425. outcome: 'rate_limited',
  426. },
  427. totals: {
  428. 'sum(quantity)': 14,
  429. },
  430. series: {
  431. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 2],
  432. },
  433. },
  434. {
  435. by: {
  436. project: 1,
  437. category: 'error',
  438. outcome: 'invalid',
  439. },
  440. totals: {
  441. 'sum(quantity)': 15,
  442. },
  443. series: {
  444. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  445. },
  446. },
  447. {
  448. by: {
  449. project: 1,
  450. category: 'error',
  451. outcome: 'client_discard',
  452. },
  453. totals: {
  454. 'sum(quantity)': 15,
  455. },
  456. series: {
  457. 'sum(quantity)': [2, 2, 2, 2, 2, 2, 3],
  458. },
  459. },
  460. ],
  461. };