widgetQueries.spec.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. import {EventsStatsFixture} from 'sentry-fixture/events';
  2. import {OrganizationFixture} from 'sentry-fixture/organization';
  3. import {initializeOrg} from 'sentry-test/initializeOrg';
  4. import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary';
  5. import type {PageFilters} from 'sentry/types/core';
  6. import {MetricsResultsMetaProvider} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
  7. import {MEPSettingProvider} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  8. import {DashboardFilterKeys, DisplayType} from 'sentry/views/dashboards/types';
  9. import {DashboardsMEPContext} from 'sentry/views/dashboards/widgetCard/dashboardsMEPContext';
  10. import type {GenericWidgetQueriesChildrenProps} from 'sentry/views/dashboards/widgetCard/genericWidgetQueries';
  11. import WidgetQueries, {
  12. flattenMultiSeriesDataWithGrouping,
  13. } from 'sentry/views/dashboards/widgetCard/widgetQueries';
  14. describe('Dashboards > WidgetQueries', function () {
  15. const initialData = initializeOrg();
  16. const renderWithProviders = component =>
  17. render(
  18. <MetricsResultsMetaProvider>
  19. <MEPSettingProvider forceTransactions={false}>{component}</MEPSettingProvider>
  20. </MetricsResultsMetaProvider>
  21. );
  22. const multipleQueryWidget = {
  23. title: 'Errors',
  24. interval: '5m',
  25. displayType: DisplayType.LINE,
  26. queries: [
  27. {
  28. conditions: 'event.type:error',
  29. fields: ['count()'],
  30. aggregates: ['count()'],
  31. columns: [],
  32. name: 'errors',
  33. orderby: '',
  34. },
  35. {
  36. conditions: 'event.type:default',
  37. fields: ['count()'],
  38. aggregates: ['count()'],
  39. columns: [],
  40. name: 'default',
  41. orderby: '',
  42. },
  43. ],
  44. };
  45. const singleQueryWidget = {
  46. title: 'Errors',
  47. interval: '5m',
  48. displayType: DisplayType.LINE,
  49. queries: [
  50. {
  51. conditions: 'event.type:error',
  52. fields: ['count()'],
  53. aggregates: ['count()'],
  54. columns: [],
  55. name: 'errors',
  56. orderby: '',
  57. },
  58. ],
  59. };
  60. const tableWidget = {
  61. title: 'SDK',
  62. interval: '5m',
  63. displayType: DisplayType.TABLE,
  64. queries: [
  65. {
  66. conditions: 'event.type:error',
  67. fields: ['sdk.name'],
  68. aggregates: [],
  69. columns: ['sdk.name'],
  70. name: 'sdk',
  71. orderby: '',
  72. },
  73. ],
  74. };
  75. const selection: PageFilters = {
  76. projects: [1],
  77. environments: ['prod'],
  78. datetime: {
  79. period: '14d',
  80. start: null,
  81. end: null,
  82. utc: false,
  83. },
  84. };
  85. afterEach(function () {
  86. MockApiClient.clearMockResponses();
  87. });
  88. it('can send multiple API requests', async function () {
  89. const errorMock = MockApiClient.addMockResponse({
  90. url: '/organizations/org-slug/events-stats/',
  91. body: [],
  92. match: [MockApiClient.matchQuery({query: 'event.type:error'})],
  93. });
  94. const defaultMock = MockApiClient.addMockResponse({
  95. url: '/organizations/org-slug/events-stats/',
  96. body: [],
  97. match: [MockApiClient.matchQuery({query: 'event.type:default'})],
  98. });
  99. renderWithProviders(
  100. <WidgetQueries
  101. api={new MockApiClient()}
  102. widget={multipleQueryWidget}
  103. organization={initialData.organization}
  104. selection={selection}
  105. >
  106. {() => <div data-test-id="child" />}
  107. </WidgetQueries>
  108. );
  109. // Child should be rendered and 2 requests should be sent.
  110. await screen.findByTestId('child');
  111. expect(errorMock).toHaveBeenCalledTimes(1);
  112. expect(defaultMock).toHaveBeenCalledTimes(1);
  113. });
  114. it('appends dashboard filters to events series request', async function () {
  115. const mock = MockApiClient.addMockResponse({
  116. url: '/organizations/org-slug/events-stats/',
  117. body: [],
  118. });
  119. renderWithProviders(
  120. <WidgetQueries
  121. api={new MockApiClient()}
  122. widget={singleQueryWidget}
  123. organization={initialData.organization}
  124. selection={selection}
  125. dashboardFilters={{[DashboardFilterKeys.RELEASE]: ['abc@1.2.0', 'abc@1.3.0']}}
  126. >
  127. {() => <div data-test-id="child" />}
  128. </WidgetQueries>
  129. );
  130. await screen.findByTestId('child');
  131. expect(mock).toHaveBeenCalledWith(
  132. '/organizations/org-slug/events-stats/',
  133. expect.objectContaining({
  134. query: expect.objectContaining({
  135. query: '(event.type:error) release:["abc@1.2.0","abc@1.3.0"] ',
  136. }),
  137. })
  138. );
  139. });
  140. it('appends dashboard filters to events table request', async function () {
  141. const mock = MockApiClient.addMockResponse({
  142. url: '/organizations/org-slug/events/',
  143. body: [],
  144. });
  145. renderWithProviders(
  146. <WidgetQueries
  147. api={new MockApiClient()}
  148. widget={tableWidget}
  149. organization={initialData.organization}
  150. selection={selection}
  151. dashboardFilters={{[DashboardFilterKeys.RELEASE]: ['abc@1.3.0']}}
  152. >
  153. {() => <div data-test-id="child" />}
  154. </WidgetQueries>
  155. );
  156. await screen.findByTestId('child');
  157. expect(mock).toHaveBeenCalledWith(
  158. '/organizations/org-slug/events/',
  159. expect.objectContaining({
  160. query: expect.objectContaining({
  161. query: '(event.type:error) release:"abc@1.3.0" ',
  162. }),
  163. })
  164. );
  165. });
  166. it('sets errorMessage when the first request fails', async function () {
  167. const okMock = MockApiClient.addMockResponse({
  168. url: '/organizations/org-slug/events-stats/',
  169. match: [MockApiClient.matchQuery({query: 'event.type:error'})],
  170. body: [],
  171. });
  172. const failMock = MockApiClient.addMockResponse({
  173. url: '/organizations/org-slug/events-stats/',
  174. statusCode: 400,
  175. body: {detail: 'Bad request data'},
  176. match: [MockApiClient.matchQuery({query: 'event.type:default'})],
  177. });
  178. let error: string | undefined;
  179. renderWithProviders(
  180. <WidgetQueries
  181. api={new MockApiClient()}
  182. widget={multipleQueryWidget}
  183. organization={initialData.organization}
  184. selection={selection}
  185. >
  186. {({errorMessage}: {errorMessage?: string}) => {
  187. error = errorMessage;
  188. return <div data-test-id="child" />;
  189. }}
  190. </WidgetQueries>
  191. );
  192. // Child should be rendered and 2 requests should be sent.
  193. expect(await screen.findByTestId('child')).toBeInTheDocument();
  194. await waitFor(() => {
  195. expect(error).toEqual('Bad request data');
  196. });
  197. expect(okMock).toHaveBeenCalledTimes(1);
  198. expect(failMock).toHaveBeenCalledTimes(1);
  199. });
  200. it('adjusts interval based on date window', async function () {
  201. const errorMock = MockApiClient.addMockResponse({
  202. url: '/organizations/org-slug/events-stats/',
  203. body: [],
  204. });
  205. const widget = {...singleQueryWidget, interval: '1m'};
  206. const longSelection: PageFilters = {
  207. projects: [1],
  208. environments: ['prod', 'dev'],
  209. datetime: {
  210. period: '90d',
  211. start: null,
  212. end: null,
  213. utc: false,
  214. },
  215. };
  216. renderWithProviders(
  217. <WidgetQueries
  218. api={new MockApiClient()}
  219. widget={widget}
  220. organization={initialData.organization}
  221. selection={longSelection}
  222. >
  223. {() => <div data-test-id="child" />}
  224. </WidgetQueries>
  225. );
  226. // Child should be rendered and interval bumped up.
  227. await screen.findByTestId('child');
  228. expect(errorMock).toHaveBeenCalledTimes(1);
  229. expect(errorMock).toHaveBeenCalledWith(
  230. '/organizations/org-slug/events-stats/',
  231. expect.objectContaining({
  232. query: expect.objectContaining({
  233. interval: '4h',
  234. statsPeriod: '90d',
  235. environment: ['prod', 'dev'],
  236. project: [1],
  237. }),
  238. })
  239. );
  240. });
  241. it('adjusts interval based on date window 14d', async function () {
  242. const errorMock = MockApiClient.addMockResponse({
  243. url: '/organizations/org-slug/events-stats/',
  244. body: [],
  245. });
  246. const widget = {...singleQueryWidget, interval: '1m'};
  247. renderWithProviders(
  248. <WidgetQueries
  249. api={new MockApiClient()}
  250. widget={widget}
  251. organization={initialData.organization}
  252. selection={selection}
  253. >
  254. {() => <div data-test-id="child" />}
  255. </WidgetQueries>
  256. );
  257. // Child should be rendered and interval bumped up.
  258. await screen.findByTestId('child');
  259. expect(errorMock).toHaveBeenCalledTimes(1);
  260. expect(errorMock).toHaveBeenCalledWith(
  261. '/organizations/org-slug/events-stats/',
  262. expect.objectContaining({
  263. query: expect.objectContaining({interval: '30m'}),
  264. })
  265. );
  266. });
  267. it('can send table result queries', async function () {
  268. const tableMock = MockApiClient.addMockResponse({
  269. url: '/organizations/org-slug/events/',
  270. body: {
  271. meta: {'sdk.name': 'string'},
  272. data: [{'sdk.name': 'python'}],
  273. },
  274. });
  275. let childProps: GenericWidgetQueriesChildrenProps | undefined;
  276. renderWithProviders(
  277. <WidgetQueries
  278. api={new MockApiClient()}
  279. widget={tableWidget}
  280. organization={initialData.organization}
  281. selection={selection}
  282. >
  283. {props => {
  284. childProps = props;
  285. return <div data-test-id="child" />;
  286. }}
  287. </WidgetQueries>
  288. );
  289. // Child should be rendered and 1 requests should be sent.
  290. await screen.findByTestId('child');
  291. expect(tableMock).toHaveBeenCalledTimes(1);
  292. expect(tableMock).toHaveBeenCalledWith(
  293. '/organizations/org-slug/events/',
  294. expect.objectContaining({
  295. query: expect.objectContaining({
  296. query: 'event.type:error',
  297. field: ['sdk.name'],
  298. statsPeriod: '14d',
  299. environment: ['prod'],
  300. project: [1],
  301. }),
  302. })
  303. );
  304. expect(childProps?.timeseriesResults).toBeUndefined();
  305. await waitFor(() => expect(childProps?.tableResults?.[0].data).toHaveLength(1));
  306. expect(childProps?.tableResults?.[0].meta).toBeDefined();
  307. });
  308. it('can send multiple table queries', async function () {
  309. const firstQuery = MockApiClient.addMockResponse({
  310. url: '/organizations/org-slug/events/',
  311. body: {
  312. meta: {'sdk.name': 'string'},
  313. data: [{'sdk.name': 'python'}],
  314. },
  315. match: [MockApiClient.matchQuery({query: 'event.type:error'})],
  316. });
  317. const secondQuery = MockApiClient.addMockResponse({
  318. url: '/organizations/org-slug/events/',
  319. body: {
  320. meta: {title: 'string'},
  321. data: [{title: 'ValueError'}],
  322. },
  323. match: [MockApiClient.matchQuery({query: 'title:ValueError'})],
  324. });
  325. const widget = {
  326. title: 'SDK',
  327. interval: '5m',
  328. displayType: DisplayType.TABLE,
  329. queries: [
  330. {
  331. conditions: 'event.type:error',
  332. fields: ['sdk.name'],
  333. aggregates: [],
  334. columns: ['sdk.name'],
  335. name: 'sdk',
  336. orderby: '',
  337. },
  338. {
  339. conditions: 'title:ValueError',
  340. fields: ['title'],
  341. aggregates: [],
  342. columns: ['sdk.name'],
  343. name: 'title',
  344. orderby: '',
  345. },
  346. ],
  347. };
  348. let childProps: GenericWidgetQueriesChildrenProps | undefined;
  349. renderWithProviders(
  350. <WidgetQueries
  351. api={new MockApiClient()}
  352. widget={widget}
  353. organization={initialData.organization}
  354. selection={selection}
  355. >
  356. {props => {
  357. childProps = props;
  358. return <div data-test-id="child" />;
  359. }}
  360. </WidgetQueries>
  361. );
  362. // Child should be rendered and 2 requests should be sent.
  363. await screen.findByTestId('child');
  364. expect(firstQuery).toHaveBeenCalledTimes(1);
  365. expect(secondQuery).toHaveBeenCalledTimes(1);
  366. await waitFor(() => expect(childProps?.tableResults).toHaveLength(2));
  367. expect(childProps?.tableResults?.[0].data[0]['sdk.name']).toBeDefined();
  368. expect(childProps?.tableResults?.[1].data[0].title).toBeDefined();
  369. });
  370. it('can send big number result queries', async function () {
  371. const tableMock = MockApiClient.addMockResponse({
  372. url: '/organizations/org-slug/events/',
  373. body: {
  374. meta: {'sdk.name': 'string'},
  375. data: [{'sdk.name': 'python'}],
  376. },
  377. });
  378. let childProps: GenericWidgetQueriesChildrenProps | undefined;
  379. renderWithProviders(
  380. <WidgetQueries
  381. api={new MockApiClient()}
  382. widget={{
  383. title: 'SDK',
  384. interval: '5m',
  385. displayType: DisplayType.BIG_NUMBER,
  386. queries: [
  387. {
  388. conditions: 'event.type:error',
  389. fields: ['sdk.name'],
  390. aggregates: [],
  391. columns: ['sdk.name'],
  392. name: 'sdk',
  393. orderby: '',
  394. },
  395. ],
  396. }}
  397. organization={initialData.organization}
  398. selection={selection}
  399. >
  400. {props => {
  401. childProps = props;
  402. return <div data-test-id="child" />;
  403. }}
  404. </WidgetQueries>
  405. );
  406. // Child should be rendered and 1 requests should be sent.
  407. await screen.findByTestId('child');
  408. expect(tableMock).toHaveBeenCalledTimes(1);
  409. expect(tableMock).toHaveBeenCalledWith(
  410. '/organizations/org-slug/events/',
  411. expect.objectContaining({
  412. query: expect.objectContaining({
  413. referrer: 'api.dashboards.bignumberwidget',
  414. query: 'event.type:error',
  415. field: ['sdk.name'],
  416. statsPeriod: '14d',
  417. environment: ['prod'],
  418. project: [1],
  419. }),
  420. })
  421. );
  422. expect(childProps?.timeseriesResults).toBeUndefined();
  423. await waitFor(() => expect(childProps?.tableResults?.[0]?.data).toHaveLength(1));
  424. expect(childProps?.tableResults?.[0]?.meta).toBeDefined();
  425. });
  426. it('stops loading state once all queries finish even if some fail', async function () {
  427. const firstQuery = MockApiClient.addMockResponse({
  428. statusCode: 500,
  429. url: '/organizations/org-slug/events/',
  430. body: {detail: 'it didnt work'},
  431. match: [MockApiClient.matchQuery({query: 'event.type:error'})],
  432. });
  433. const secondQuery = MockApiClient.addMockResponse({
  434. url: '/organizations/org-slug/events/',
  435. body: {
  436. meta: {title: 'string'},
  437. data: [{title: 'ValueError'}],
  438. },
  439. match: [MockApiClient.matchQuery({query: 'title:ValueError'})],
  440. });
  441. const widget = {
  442. title: 'SDK',
  443. interval: '5m',
  444. displayType: DisplayType.TABLE,
  445. queries: [
  446. {
  447. conditions: 'event.type:error',
  448. fields: ['sdk.name'],
  449. aggregates: [],
  450. columns: ['sdk.name'],
  451. name: 'sdk',
  452. orderby: '',
  453. },
  454. {
  455. conditions: 'title:ValueError',
  456. fields: ['sdk.name'],
  457. aggregates: [],
  458. columns: ['sdk.name'],
  459. name: 'title',
  460. orderby: '',
  461. },
  462. ],
  463. };
  464. let childProps: GenericWidgetQueriesChildrenProps | undefined;
  465. renderWithProviders(
  466. <WidgetQueries
  467. api={new MockApiClient()}
  468. widget={widget}
  469. organization={initialData.organization}
  470. selection={selection}
  471. >
  472. {props => {
  473. childProps = props;
  474. return <div data-test-id="child" />;
  475. }}
  476. </WidgetQueries>
  477. );
  478. // Child should be rendered and 2 requests should be sent.
  479. await screen.findByTestId('child');
  480. expect(firstQuery).toHaveBeenCalledTimes(1);
  481. expect(secondQuery).toHaveBeenCalledTimes(1);
  482. await waitFor(() => expect(childProps?.loading).toEqual(false));
  483. });
  484. it('sets bar charts to 1d interval', async function () {
  485. const errorMock = MockApiClient.addMockResponse({
  486. url: '/organizations/org-slug/events-stats/',
  487. body: [],
  488. match: [MockApiClient.matchQuery({interval: '1d'})],
  489. });
  490. const barWidget = {
  491. ...singleQueryWidget,
  492. displayType: DisplayType.BAR,
  493. // Should be ignored for bars.
  494. interval: '5m',
  495. };
  496. renderWithProviders(
  497. <WidgetQueries
  498. api={new MockApiClient()}
  499. widget={barWidget}
  500. organization={initialData.organization}
  501. selection={selection}
  502. >
  503. {() => <div data-test-id="child" />}
  504. </WidgetQueries>
  505. );
  506. // Child should be rendered and 1 requests should be sent.
  507. await screen.findByTestId('child');
  508. expect(errorMock).toHaveBeenCalledTimes(1);
  509. });
  510. it('returns timeseriesResults in the same order as widgetQuery', async function () {
  511. MockApiClient.clearMockResponses();
  512. const defaultMock = MockApiClient.addMockResponse({
  513. url: '/organizations/org-slug/events-stats/',
  514. method: 'GET',
  515. body: {
  516. data: [
  517. [
  518. 1000,
  519. [
  520. {
  521. count: 100,
  522. },
  523. ],
  524. ],
  525. ],
  526. start: 1000,
  527. end: 2000,
  528. },
  529. match: [MockApiClient.matchQuery({query: 'event.type:default'})],
  530. });
  531. const errorMock = MockApiClient.addMockResponse({
  532. url: '/organizations/org-slug/events-stats/',
  533. method: 'GET',
  534. body: {
  535. data: [
  536. [
  537. 1000,
  538. [
  539. {
  540. count: 200,
  541. },
  542. ],
  543. ],
  544. ],
  545. start: 1000,
  546. end: 2000,
  547. },
  548. match: [MockApiClient.matchQuery({query: 'event.type:error'})],
  549. });
  550. const barWidget = {
  551. ...multipleQueryWidget,
  552. displayType: DisplayType.BAR,
  553. // Should be ignored for bars.
  554. interval: '5m',
  555. };
  556. const child = jest.fn(() => <div data-test-id="child" />);
  557. renderWithProviders(
  558. <WidgetQueries
  559. api={new MockApiClient()}
  560. widget={barWidget}
  561. organization={initialData.organization}
  562. selection={selection}
  563. >
  564. {child}
  565. </WidgetQueries>
  566. );
  567. await screen.findByTestId('child');
  568. expect(defaultMock).toHaveBeenCalledTimes(1);
  569. expect(errorMock).toHaveBeenCalledTimes(1);
  570. await waitFor(() =>
  571. expect(child).toHaveBeenLastCalledWith(
  572. expect.objectContaining({
  573. timeseriesResults: [
  574. {data: [{name: 1000000, value: 200}], seriesName: 'errors : count()'},
  575. {data: [{name: 1000000, value: 100}], seriesName: 'default : count()'},
  576. ],
  577. })
  578. )
  579. );
  580. });
  581. it('calls events-stats with 4h interval when interval buckets would exceed 66', async function () {
  582. const eventsStatsMock = MockApiClient.addMockResponse({
  583. url: '/organizations/org-slug/events-stats/',
  584. body: [],
  585. });
  586. const areaWidget = {
  587. ...singleQueryWidget,
  588. displayType: DisplayType.AREA,
  589. interval: '5m',
  590. };
  591. renderWithProviders(
  592. <WidgetQueries
  593. api={new MockApiClient()}
  594. widget={areaWidget}
  595. organization={initialData.organization}
  596. selection={{
  597. ...selection,
  598. datetime: {
  599. period: '90d',
  600. start: null,
  601. end: null,
  602. utc: false,
  603. },
  604. }}
  605. >
  606. {() => <div data-test-id="child" />}
  607. </WidgetQueries>
  608. );
  609. // Child should be rendered and 1 requests should be sent.
  610. await screen.findByTestId('child');
  611. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  612. expect(eventsStatsMock).toHaveBeenCalledWith(
  613. '/organizations/org-slug/events-stats/',
  614. expect.objectContaining({query: expect.objectContaining({interval: '4h'})})
  615. );
  616. });
  617. it('does not re-query events and sets name in widgets', async function () {
  618. const eventsStatsMock = MockApiClient.addMockResponse({
  619. url: '/organizations/org-slug/events-stats/',
  620. body: EventsStatsFixture(),
  621. });
  622. const lineWidget = {
  623. ...singleQueryWidget,
  624. displayType: DisplayType.LINE,
  625. interval: '5m',
  626. };
  627. let childProps;
  628. const {rerender} = renderWithProviders(
  629. <WidgetQueries
  630. api={new MockApiClient()}
  631. widget={lineWidget}
  632. organization={initialData.organization}
  633. selection={selection}
  634. >
  635. {props => {
  636. childProps = props;
  637. return <div data-test-id="child" />;
  638. }}
  639. </WidgetQueries>
  640. );
  641. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  642. await waitFor(() => expect(childProps.loading).toEqual(false));
  643. // Simulate a re-render with a new query alias
  644. rerender(
  645. <MetricsResultsMetaProvider>
  646. <MEPSettingProvider forceTransactions={false}>
  647. <WidgetQueries
  648. api={new MockApiClient()}
  649. widget={{
  650. ...lineWidget,
  651. queries: [
  652. {
  653. conditions: 'event.type:error',
  654. fields: ['count()'],
  655. aggregates: ['count()'],
  656. columns: [],
  657. name: 'this query alias changed',
  658. orderby: '',
  659. },
  660. ],
  661. }}
  662. organization={initialData.organization}
  663. selection={selection}
  664. >
  665. {props => {
  666. childProps = props;
  667. return <div data-test-id="child" />;
  668. }}
  669. </WidgetQueries>
  670. </MEPSettingProvider>
  671. </MetricsResultsMetaProvider>
  672. );
  673. // Did not re-query
  674. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  675. expect(childProps.timeseriesResults[0].seriesName).toEqual(
  676. 'this query alias changed : count()'
  677. );
  678. });
  679. describe('multi-series grouped data', () => {
  680. const [START, END] = [1647399900, 1647399901];
  681. let mockCountData, mockCountUniqueData, mockRawResultData;
  682. beforeEach(() => {
  683. mockCountData = {
  684. start: START,
  685. end: END,
  686. data: [
  687. [START, [{'count()': 0}]],
  688. [END, [{'count()': 0}]],
  689. ],
  690. };
  691. mockCountUniqueData = {
  692. start: START,
  693. end: END,
  694. data: [
  695. [START, [{'count_unique()': 0}]],
  696. [END, [{'count_unique()': 0}]],
  697. ],
  698. };
  699. mockRawResultData = {
  700. local: {
  701. 'count()': mockCountData,
  702. 'count_unique()': mockCountUniqueData,
  703. order: 0,
  704. },
  705. prod: {
  706. 'count()': mockCountData,
  707. 'count_unique()': mockCountUniqueData,
  708. order: 1,
  709. },
  710. };
  711. });
  712. it('combines group name and aggregate names in grouped multi series data', () => {
  713. const actual = flattenMultiSeriesDataWithGrouping(mockRawResultData, '');
  714. expect(actual).toEqual([
  715. [
  716. 0,
  717. expect.objectContaining({
  718. seriesName: 'local : count()',
  719. data: expect.anything(),
  720. }),
  721. ],
  722. [
  723. 0,
  724. expect.objectContaining({
  725. seriesName: 'local : count_unique()',
  726. data: expect.anything(),
  727. }),
  728. ],
  729. [
  730. 1,
  731. expect.objectContaining({
  732. seriesName: 'prod : count()',
  733. data: expect.anything(),
  734. }),
  735. ],
  736. [
  737. 1,
  738. expect.objectContaining({
  739. seriesName: 'prod : count_unique()',
  740. data: expect.anything(),
  741. }),
  742. ],
  743. ]);
  744. });
  745. it('prefixes with a query alias when provided', () => {
  746. const actual = flattenMultiSeriesDataWithGrouping(mockRawResultData, 'Query 1');
  747. expect(actual).toEqual([
  748. [
  749. 0,
  750. expect.objectContaining({
  751. seriesName: 'Query 1 > local : count()',
  752. data: expect.anything(),
  753. }),
  754. ],
  755. [
  756. 0,
  757. expect.objectContaining({
  758. seriesName: 'Query 1 > local : count_unique()',
  759. data: expect.anything(),
  760. }),
  761. ],
  762. [
  763. 1,
  764. expect.objectContaining({
  765. seriesName: 'Query 1 > prod : count()',
  766. data: expect.anything(),
  767. }),
  768. ],
  769. [
  770. 1,
  771. expect.objectContaining({
  772. seriesName: 'Query 1 > prod : count_unique()',
  773. data: expect.anything(),
  774. }),
  775. ],
  776. ]);
  777. });
  778. });
  779. it('charts send metricsEnhanced requests', async function () {
  780. const {organization} = initialData;
  781. const mock = MockApiClient.addMockResponse({
  782. url: '/organizations/org-slug/events-stats/',
  783. body: {
  784. data: [
  785. [
  786. 1000,
  787. [
  788. {
  789. count: 100,
  790. },
  791. ],
  792. ],
  793. ],
  794. isMetricsData: false,
  795. start: 1000,
  796. end: 2000,
  797. },
  798. });
  799. const setIsMetricsMock = jest.fn();
  800. const children = jest.fn(() => <div />);
  801. renderWithProviders(
  802. <DashboardsMEPContext.Provider
  803. value={{
  804. isMetricsData: undefined,
  805. setIsMetricsData: setIsMetricsMock,
  806. }}
  807. >
  808. <WidgetQueries
  809. api={new MockApiClient()}
  810. widget={singleQueryWidget}
  811. organization={{
  812. ...organization,
  813. features: [...organization.features, 'dashboards-mep'],
  814. }}
  815. selection={selection}
  816. >
  817. {children}
  818. </WidgetQueries>
  819. </DashboardsMEPContext.Provider>
  820. );
  821. expect(mock).toHaveBeenCalledWith(
  822. '/organizations/org-slug/events-stats/',
  823. expect.objectContaining({
  824. query: expect.objectContaining({dataset: 'metricsEnhanced'}),
  825. })
  826. );
  827. await waitFor(() => {
  828. expect(setIsMetricsMock).toHaveBeenCalledWith(false);
  829. });
  830. });
  831. it('tables send metricsEnhanced requests', async function () {
  832. const {organization} = initialData;
  833. const mock = MockApiClient.addMockResponse({
  834. url: '/organizations/org-slug/events/',
  835. body: {
  836. meta: {title: 'string', isMetricsData: true},
  837. data: [{title: 'ValueError'}],
  838. },
  839. });
  840. const setIsMetricsMock = jest.fn();
  841. const children = jest.fn(() => <div />);
  842. renderWithProviders(
  843. <DashboardsMEPContext.Provider
  844. value={{
  845. isMetricsData: undefined,
  846. setIsMetricsData: setIsMetricsMock,
  847. }}
  848. >
  849. <WidgetQueries
  850. api={new MockApiClient()}
  851. widget={{...singleQueryWidget, displayType: DisplayType.TABLE}}
  852. organization={{
  853. ...organization,
  854. features: [...organization.features, 'dashboards-mep'],
  855. }}
  856. selection={selection}
  857. >
  858. {children}
  859. </WidgetQueries>
  860. </DashboardsMEPContext.Provider>
  861. );
  862. expect(mock).toHaveBeenCalledWith(
  863. '/organizations/org-slug/events/',
  864. expect.objectContaining({
  865. query: expect.objectContaining({dataset: 'metricsEnhanced'}),
  866. })
  867. );
  868. await waitFor(() => {
  869. expect(setIsMetricsMock).toHaveBeenCalledWith(true);
  870. });
  871. });
  872. it('does not inject equation aliases for top N requests', async function () {
  873. const testData = initializeOrg({
  874. organization: {
  875. ...OrganizationFixture(),
  876. },
  877. });
  878. const eventsStatsMock = MockApiClient.addMockResponse({
  879. url: '/organizations/org-slug/events-stats/',
  880. body: [],
  881. });
  882. const areaWidget = {
  883. title: 'Errors',
  884. displayType: DisplayType.AREA,
  885. interval: '5m',
  886. queries: [
  887. {
  888. conditions: 'event.type:error',
  889. fields: [],
  890. aggregates: ['count()', 'equation|count() * 2'],
  891. columns: ['project'],
  892. orderby: 'equation[0]',
  893. name: '',
  894. },
  895. ],
  896. };
  897. renderWithProviders(
  898. <WidgetQueries
  899. api={new MockApiClient()}
  900. widget={areaWidget}
  901. organization={testData.organization}
  902. selection={selection}
  903. >
  904. {() => <div data-test-id="child" />}
  905. </WidgetQueries>
  906. );
  907. // Child should be rendered and 1 requests should be sent.
  908. await screen.findByTestId('child');
  909. expect(eventsStatsMock).toHaveBeenCalledTimes(1);
  910. expect(eventsStatsMock).toHaveBeenCalledWith(
  911. '/organizations/org-slug/events-stats/',
  912. expect.objectContaining({
  913. query: expect.objectContaining({
  914. field: ['project', 'count()', 'equation|count() * 2'],
  915. orderby: 'equation[0]',
  916. }),
  917. })
  918. );
  919. });
  920. });