utils_spec.js 11.9 KB
Newer Older
1
import * as monitoringUtils from '~/monitoring/utils';
2
import * as urlUtils from '~/lib/utils/url_utility';
3
import { TEST_HOST } from 'jest/helpers/test_constants';
4
import {
5
  mockProjectDir,
6
  singleStatMetricsResult,
7
  anomalyMockGraphData,
8
  barMockData,
9
} from './mock_data';
10
import { metricsDashboardViewModel, graphData } from './fixture_data';
11

12
const mockPath = `${TEST_HOST}${mockProjectDir}/-/environments/29/metrics`;
13 14 15 16 17 18 19 20 21 22 23 24 25 26

const generatedLink = 'http://chart.link.com';

const chartTitle = 'Some metric chart';

const range = {
  start: '2019-01-01T00:00:00.000Z',
  end: '2019-01-10T00:00:00.000Z',
};

const rollingRange = {
  duration: { seconds: 120 },
};

27
describe('monitoring/utils', () => {
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  describe('trackGenerateLinkToChartEventOptions', () => {
    it('should return Cluster Monitoring options if located on Cluster Health Dashboard', () => {
      document.body.dataset.page = 'groups:clusters:show';

      expect(monitoringUtils.generateLinkToChartOptions(generatedLink)).toEqual({
        category: 'Cluster Monitoring',
        action: 'generate_link_to_cluster_metric_chart',
        label: 'Chart link',
        property: generatedLink,
      });
    });

    it('should return Incident Management event options if located on Metrics Dashboard', () => {
      document.body.dataset.page = 'metrics:show';

      expect(monitoringUtils.generateLinkToChartOptions(generatedLink)).toEqual({
        category: 'Incident Management::Embedded metrics',
        action: 'generate_link_to_metrics_chart',
        label: 'Chart link',
        property: generatedLink,
      });
    });
  });

  describe('trackDownloadCSVEvent', () => {
    it('should return Cluster Monitoring options if located on Cluster Health Dashboard', () => {
      document.body.dataset.page = 'groups:clusters:show';

      expect(monitoringUtils.downloadCSVOptions(chartTitle)).toEqual({
        category: 'Cluster Monitoring',
        action: 'download_csv_of_cluster_metric_chart',
        label: 'Chart title',
        property: chartTitle,
      });
    });

    it('should return Incident Management event options if located on Metrics Dashboard', () => {
      document.body.dataset.page = 'metriss:show';

      expect(monitoringUtils.downloadCSVOptions(chartTitle)).toEqual({
        category: 'Incident Management::Embedded metrics',
        action: 'download_csv_of_metrics_dashboard_chart',
        label: 'Chart title',
        property: chartTitle,
      });
    });
  });
75 76 77 78 79 80 81 82 83 84

  describe('graphDataValidatorForValues', () => {
    /*
     * When dealing with a metric using the query format, e.g.
     * query: 'max(go_memstats_alloc_bytes{job="prometheus"}) by (job) /1024/1024'
     * the validator will look for the `value` key instead of `values`
     */
    it('validates data with the query format', () => {
      const validGraphData = monitoringUtils.graphDataValidatorForValues(
        true,
85
        singleStatMetricsResult,
86 87 88 89 90 91 92 93 94 95 96
      );

      expect(validGraphData).toBe(true);
    });

    /*
     * When dealing with a metric using the query?range format, e.g.
     * query_range: 'avg(sum(container_memory_usage_bytes{container_name!="POD",pod_name=~"^%{ci_environment_slug}-(.*)",namespace="%{kube_namespace}"}) by (job)) without (job)  /1024/1024/1024',
     * the validator will look for the `values` key instead of `value`
     */
    it('validates data with the query_range format', () => {
97
      const validGraphData = monitoringUtils.graphDataValidatorForValues(false, graphData);
98 99 100 101 102 103 104 105 106 107

      expect(validGraphData).toBe(true);
    });
  });

  describe('graphDataValidatorForAnomalyValues', () => {
    let oneMetric;
    let threeMetrics;
    let fourMetrics;
    beforeEach(() => {
108
      oneMetric = singleStatMetricsResult;
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
      threeMetrics = anomalyMockGraphData;

      const metrics = [...threeMetrics.metrics];
      metrics.push(threeMetrics.metrics[0]);
      fourMetrics = {
        ...anomalyMockGraphData,
        metrics,
      };
    });
    /*
     * Anomaly charts can accept results for exactly 3 metrics,
     */
    it('validates passes with the right query format', () => {
      expect(monitoringUtils.graphDataValidatorForAnomalyValues(threeMetrics)).toBe(true);
    });

    it('validation fails for wrong format, 1 metric', () => {
      expect(monitoringUtils.graphDataValidatorForAnomalyValues(oneMetric)).toBe(false);
    });

    it('validation fails for wrong format, more than 3 metrics', () => {
      expect(monitoringUtils.graphDataValidatorForAnomalyValues(fourMetrics)).toBe(false);
    });
  });
133 134

  describe('timeRangeFromUrl', () => {
135 136 137
    beforeEach(() => {
      jest.spyOn(urlUtils, 'queryToObject');
    });
138

139 140 141 142 143
    afterEach(() => {
      urlUtils.queryToObject.mockRestore();
    });

    const { timeRangeFromUrl } = monitoringUtils;
144

145 146
    it('returns a fixed range when query contains `start` and `end` parameters are given', () => {
      urlUtils.queryToObject.mockReturnValueOnce(range);
147 148 149
      expect(timeRangeFromUrl()).toEqual(range);
    });

150
    it('returns a rolling range when query contains `duration_seconds` parameters are given', () => {
151 152
      const { seconds } = rollingRange.duration;

153
      urlUtils.queryToObject.mockReturnValueOnce({
154 155 156 157 158 159 160
        dashboard: '.gitlab/dashboard/my_dashboard.yml',
        duration_seconds: `${seconds}`,
      });

      expect(timeRangeFromUrl()).toEqual(rollingRange);
    });

161 162
    it('returns null when no time range parameters are given', () => {
      urlUtils.queryToObject.mockReturnValueOnce({
163 164 165
        dashboard: '.gitlab/dashboards/custom_dashboard.yml',
        param1: 'value1',
        param2: 'value2',
166
      });
167

168
      expect(timeRangeFromUrl()).toBe(null);
169 170 171 172 173 174
    });
  });

  describe('removeTimeRangeParams', () => {
    const { removeTimeRangeParams } = monitoringUtils;

175
    it('returns when query contains `start` and `end` parameters are given', () => {
176 177 178 179 180 181 182 183 184
      expect(removeTimeRangeParams(`${mockPath}?start=${range.start}&end=${range.end}`)).toEqual(
        mockPath,
      );
    });
  });

  describe('timeRangeToUrl', () => {
    const { timeRangeToUrl } = monitoringUtils;

185 186 187 188 189 190 191 192 193 194 195
    beforeEach(() => {
      jest.spyOn(urlUtils, 'mergeUrlParams');
      jest.spyOn(urlUtils, 'removeParams');
    });

    afterEach(() => {
      urlUtils.mergeUrlParams.mockRestore();
      urlUtils.removeParams.mockRestore();
    });

    it('returns a fixed range when query contains `start` and `end` parameters are given', () => {
196 197 198
      const toUrl = `${mockPath}?start=${range.start}&end=${range.end}`;
      const fromUrl = mockPath;

199 200
      urlUtils.removeParams.mockReturnValueOnce(fromUrl);
      urlUtils.mergeUrlParams.mockReturnValueOnce(toUrl);
201 202

      expect(timeRangeToUrl(range)).toEqual(toUrl);
203
      expect(urlUtils.mergeUrlParams).toHaveBeenCalledWith(range, fromUrl);
204 205
    });

206
    it('returns a rolling range when query contains `duration_seconds` parameters are given', () => {
207 208 209 210 211
      const { seconds } = rollingRange.duration;

      const toUrl = `${mockPath}?duration_seconds=${seconds}`;
      const fromUrl = mockPath;

212 213
      urlUtils.removeParams.mockReturnValueOnce(fromUrl);
      urlUtils.mergeUrlParams.mockReturnValueOnce(toUrl);
214 215

      expect(timeRangeToUrl(rollingRange)).toEqual(toUrl);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      expect(urlUtils.mergeUrlParams).toHaveBeenCalledWith(
        { duration_seconds: `${seconds}` },
        fromUrl,
      );
    });
  });

  describe('expandedPanelPayloadFromUrl', () => {
    const { expandedPanelPayloadFromUrl } = monitoringUtils;
    const [panelGroup] = metricsDashboardViewModel.panelGroups;
    const [panel] = panelGroup.panels;

    const { group } = panelGroup;
    const { title, y_label: yLabel } = panel;

    it('returns payload for a panel when query parameters are given', () => {
      const search = `?group=${group}&title=${title}&y_label=${yLabel}`;

      expect(expandedPanelPayloadFromUrl(metricsDashboardViewModel, search)).toEqual({
        group: panelGroup.group,
        panel,
      });
    });

    it('returns null when no parameters are given', () => {
      expect(expandedPanelPayloadFromUrl(metricsDashboardViewModel, '')).toBe(null);
    });

    it('throws an error when no group is provided', () => {
      const search = `?title=${panel.title}&y_label=${yLabel}`;
      expect(() => expandedPanelPayloadFromUrl(metricsDashboardViewModel, search)).toThrow();
    });

    it('throws an error when no title is provided', () => {
      const search = `?title=${title}&y_label=${yLabel}`;
      expect(() => expandedPanelPayloadFromUrl(metricsDashboardViewModel, search)).toThrow();
    });

    it('throws an error when no y_label group is provided', () => {
      const search = `?group=${group}&title=${title}`;
      expect(() => expandedPanelPayloadFromUrl(metricsDashboardViewModel, search)).toThrow();
    });

    test.each`
      group            | title            | yLabel             | missingField
      ${'NOT_A_GROUP'} | ${title}         | ${yLabel}          | ${'group'}
      ${group}         | ${'NOT_A_TITLE'} | ${yLabel}          | ${'title'}
      ${group}         | ${title}         | ${'NOT_A_Y_LABEL'} | ${'y_label'}
    `('throws an error when $missingField is incorrect', params => {
      const search = `?group=${params.group}&title=${params.title}&y_label=${params.yLabel}`;
      expect(() => expandedPanelPayloadFromUrl(metricsDashboardViewModel, search)).toThrow();
    });
  });

  describe('panelToUrl', () => {
    const { panelToUrl } = monitoringUtils;

    const dashboard = 'metrics.yml';
    const [panelGroup] = metricsDashboardViewModel.panelGroups;
    const [panel] = panelGroup.panels;

277 278
    const getUrlParams = url => urlUtils.queryToObject(url.split('?')[1]);

279
    it('returns URL for a panel when query parameters are given', () => {
280
      const params = getUrlParams(panelToUrl(dashboard, panelGroup.group, panel));
281 282 283 284 285 286 287 288 289

      expect(params).toEqual({
        dashboard,
        group: panelGroup.group,
        title: panel.title,
        y_label: panel.y_label,
      });
    });

290 291 292
    it('returns a dashboard only URL if group is missing', () => {
      const params = getUrlParams(panelToUrl(dashboard, null, panel));
      expect(params).toEqual({ dashboard: 'metrics.yml' });
293 294
    });

295 296 297
    it('returns a dashboard only URL if panel is missing', () => {
      const params = getUrlParams(panelToUrl(dashboard, panelGroup.group, null));
      expect(params).toEqual({ dashboard: 'metrics.yml' });
298 299
    });
  });
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

  describe('barChartsDataParser', () => {
    const singleMetricExpected = {
      SLA: [
        ['0.9935198135198128', 'api'],
        ['0.9975296513504401', 'git'],
        ['0.9994716394716395', 'registry'],
        ['0.9948251748251747', 'sidekiq'],
        ['0.9535664335664336', 'web'],
        ['0.9335664335664336', 'postgresql_database'],
      ],
    };

    const multipleMetricExpected = {
      ...singleMetricExpected,
      SLA_2: Object.values(singleMetricExpected)[0],
    };

    const barMockDataWithMultipleMetrics = {
      ...barMockData,
      metrics: [
        barMockData.metrics[0],
        {
          ...barMockData.metrics[0],
          label: 'SLA_2',
        },
      ],
    };

    [
      {
        input: { metrics: undefined },
        output: {},
        testCase: 'barChartsDataParser returns {} with undefined',
      },
      {
        input: { metrics: null },
        output: {},
        testCase: 'barChartsDataParser returns {} with null',
      },
      {
        input: { metrics: [] },
        output: {},
        testCase: 'barChartsDataParser returns {} with []',
      },
      {
        input: barMockData,
        output: singleMetricExpected,
        testCase: 'barChartsDataParser returns single series object with single metrics',
      },
      {
        input: barMockDataWithMultipleMetrics,
        output: multipleMetricExpected,
        testCase: 'barChartsDataParser returns multiple series object with multiple metrics',
      },
    ].forEach(({ input, output, testCase }) => {
      it(testCase, () => {
        expect(monitoringUtils.barChartsDataParser(input.metrics)).toEqual(
          expect.objectContaining(output),
        );
      });
    });
  });
363
});