summaryrefslogtreecommitdiff
path: root/spec/frontend/ci/runner/admin_runners/admin_runners_app_spec.js
blob: 6fc6c0b608586fb39a02a0ec7fba2532640ad4cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
import Vue, { nextTick } from 'vue';
import { GlToast, GlLink } from '@gitlab/ui';
import VueApollo from 'vue-apollo';
import createMockApollo from 'helpers/mock_apollo_helper';
import setWindowLocation from 'helpers/set_window_location_helper';
import {
  extendedWrapper,
  shallowMountExtended,
  mountExtended,
} from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import { createAlert } from '~/alert';
import { s__ } from '~/locale';
import { getIdFromGraphQLId } from '~/graphql_shared/utils';
import { updateHistory } from '~/lib/utils/url_utility';

import { upgradeStatusTokenConfig } from 'ee_else_ce/ci/runner/components/search_tokens/upgrade_status_token_config';
import { createLocalState } from '~/ci/runner/graphql/list/local_state';
import AdminRunnersApp from '~/ci/runner/admin_runners/admin_runners_app.vue';
import RunnerTypeTabs from '~/ci/runner/components/runner_type_tabs.vue';
import RunnerFilteredSearchBar from '~/ci/runner/components/runner_filtered_search_bar.vue';
import RunnerList from '~/ci/runner/components/runner_list.vue';
import RunnerListEmptyState from '~/ci/runner/components/runner_list_empty_state.vue';
import RunnerStats from '~/ci/runner/components/stat/runner_stats.vue';
import RunnerActionsCell from '~/ci/runner/components/cells/runner_actions_cell.vue';
import RegistrationDropdown from '~/ci/runner/components/registration/registration_dropdown.vue';
import RunnerPagination from '~/ci/runner/components/runner_pagination.vue';
import RunnerJobStatusBadge from '~/ci/runner/components/runner_job_status_badge.vue';

import {
  ADMIN_FILTERED_SEARCH_NAMESPACE,
  CREATED_ASC,
  CREATED_DESC,
  DEFAULT_SORT,
  I18N_STATUS_ONLINE,
  I18N_STATUS_OFFLINE,
  I18N_STATUS_STALE,
  I18N_INSTANCE_TYPE,
  I18N_GROUP_TYPE,
  I18N_PROJECT_TYPE,
  INSTANCE_TYPE,
  JOBS_ROUTE_PATH,
  PARAM_KEY_PAUSED,
  PARAM_KEY_STATUS,
  PARAM_KEY_TAG,
  STATUS_ONLINE,
  DEFAULT_MEMBERSHIP,
  RUNNER_PAGE_SIZE,
} from '~/ci/runner/constants';
import allRunnersQuery from 'ee_else_ce/ci/runner/graphql/list/all_runners.query.graphql';
import allRunnersCountQuery from 'ee_else_ce/ci/runner/graphql/list/all_runners_count.query.graphql';
import { captureException } from '~/ci/runner/sentry_utils';

import {
  allRunnersData,
  runnersCountData,
  allRunnersDataPaginated,
  onlineContactTimeoutSecs,
  staleTimeoutSecs,
  mockRegistrationToken,
  newRunnerPath,
  emptyPageInfo,
  emptyStateSvgPath,
  emptyStateFilteredSvgPath,
} from '../mock_data';

const mockRunners = allRunnersData.data.runners.nodes;
const mockRunnersCount = runnersCountData.data.runners.count;

const mockRunnersHandler = jest.fn();
const mockRunnersCountHandler = jest.fn();

jest.mock('~/alert');
jest.mock('~/ci/runner/sentry_utils');
jest.mock('~/lib/utils/url_utility', () => ({
  ...jest.requireActual('~/lib/utils/url_utility'),
  updateHistory: jest.fn(),
}));

Vue.use(VueApollo);
Vue.use(GlToast);

const STATUS_COUNT_QUERIES = 3;
const TAB_COUNT_QUERIES = 4;
const COUNT_QUERIES = TAB_COUNT_QUERIES + STATUS_COUNT_QUERIES;

describe('AdminRunnersApp', () => {
  let wrapper;
  let showToast;

  const findRunnerStats = () => wrapper.findComponent(RunnerStats);
  const findRunnerActionsCell = () => wrapper.findComponent(RunnerActionsCell);
  const findRegistrationDropdown = () => wrapper.findComponent(RegistrationDropdown);
  const findRunnerTypeTabs = () => wrapper.findComponent(RunnerTypeTabs);
  const findRunnerList = () => wrapper.findComponent(RunnerList);
  const findRunnerListEmptyState = () => wrapper.findComponent(RunnerListEmptyState);
  const findRunnerPagination = () => extendedWrapper(wrapper.findComponent(RunnerPagination));
  const findRunnerPaginationNext = () => findRunnerPagination().findByText(s__('Pagination|Next'));
  const findRunnerFilteredSearchBar = () => wrapper.findComponent(RunnerFilteredSearchBar);

  const createComponent = ({
    props = {},
    mountFn = shallowMountExtended,
    provide,
    ...options
  } = {}) => {
    const { cacheConfig, localMutations } = createLocalState();

    const handlers = [
      [allRunnersQuery, mockRunnersHandler],
      [allRunnersCountQuery, mockRunnersCountHandler],
    ];

    wrapper = mountFn(AdminRunnersApp, {
      apolloProvider: createMockApollo(handlers, {}, cacheConfig),
      propsData: {
        registrationToken: mockRegistrationToken,
        newRunnerPath,
        ...props,
      },
      provide: {
        localMutations,
        onlineContactTimeoutSecs,
        staleTimeoutSecs,
        emptyStateSvgPath,
        emptyStateFilteredSvgPath,
        ...provide,
      },
      ...options,
    });

    showToast = jest.spyOn(wrapper.vm.$root.$toast, 'show');

    return waitForPromises();
  };

  beforeEach(() => {
    mockRunnersHandler.mockResolvedValue(allRunnersData);
    mockRunnersCountHandler.mockResolvedValue(runnersCountData);
  });

  afterEach(() => {
    mockRunnersHandler.mockReset();
    mockRunnersCountHandler.mockReset();
    showToast.mockReset();
  });

  it('shows the runner setup instructions', () => {
    createComponent();

    expect(findRegistrationDropdown().props('registrationToken')).toBe(mockRegistrationToken);
    expect(findRegistrationDropdown().props('type')).toBe(INSTANCE_TYPE);
  });

  describe('shows total runner counts', () => {
    beforeEach(async () => {
      await createComponent({ mountFn: mountExtended });
    });

    it('fetches counts', () => {
      expect(mockRunnersCountHandler).toHaveBeenCalledTimes(COUNT_QUERIES);
    });

    it('shows the runner tabs', () => {
      const tabs = findRunnerTypeTabs().text();
      expect(tabs).toMatchInterpolatedText(
        `All ${mockRunnersCount} ${I18N_INSTANCE_TYPE} ${mockRunnersCount} ${I18N_GROUP_TYPE} ${mockRunnersCount} ${I18N_PROJECT_TYPE} ${mockRunnersCount}`,
      );
    });

    it('shows the total', () => {
      expect(findRunnerStats().text()).toContain(`${I18N_STATUS_ONLINE} ${mockRunnersCount}`);
      expect(findRunnerStats().text()).toContain(`${I18N_STATUS_OFFLINE} ${mockRunnersCount}`);
      expect(findRunnerStats().text()).toContain(`${I18N_STATUS_STALE} ${mockRunnersCount}`);
    });
  });

  describe('does not show total runner counts when total is 0', () => {
    beforeEach(async () => {
      mockRunnersCountHandler.mockResolvedValue({
        data: {
          runners: {
            count: 0,
            ...runnersCountData.runners,
          },
        },
      });

      await createComponent({ mountFn: mountExtended });
    });

    it('fetches only tab counts', () => {
      expect(mockRunnersCountHandler).toHaveBeenCalledTimes(TAB_COUNT_QUERIES);
    });

    it('does not shows counters', () => {
      expect(findRunnerStats().text()).toBe('');
    });
  });

  it('shows the runners list', async () => {
    await createComponent();

    expect(mockRunnersHandler).toHaveBeenCalledTimes(1);
    expect(findRunnerList().props('runners')).toEqual(mockRunners);
  });

  it('runner item links to the runner admin page', async () => {
    await createComponent({ mountFn: mountExtended });

    const { id, shortSha, adminUrl } = mockRunners[0];
    const numericId = getIdFromGraphQLId(id);

    const runnerLink = wrapper.find('tr [data-testid="td-summary"]').findComponent(GlLink);

    expect(runnerLink.text()).toBe(`#${numericId} (${shortSha})`);
    expect(runnerLink.attributes('href')).toBe(adminUrl);
  });

  it('renders runner actions for each runner', async () => {
    await createComponent({ mountFn: mountExtended });

    const runnerActions = wrapper
      .find('tr [data-testid="td-actions"]')
      .findComponent(RunnerActionsCell);
    const runner = mockRunners[0];

    expect(runnerActions.props()).toEqual({
      runner,
      editUrl: runner.editAdminUrl,
    });
  });

  it('requests the runners with no filters', async () => {
    await createComponent();

    expect(mockRunnersHandler).toHaveBeenLastCalledWith({
      status: undefined,
      type: undefined,
      membership: DEFAULT_MEMBERSHIP,
      sort: DEFAULT_SORT,
      first: RUNNER_PAGE_SIZE,
    });
  });

  it('sets tokens in the filtered search', () => {
    createComponent();

    expect(findRunnerFilteredSearchBar().props('tokens')).toEqual([
      expect.objectContaining({
        type: PARAM_KEY_PAUSED,
        options: expect.any(Array),
      }),
      expect.objectContaining({
        type: PARAM_KEY_STATUS,
        options: expect.any(Array),
      }),
      expect.objectContaining({
        type: PARAM_KEY_TAG,
        recentSuggestionsStorageKey: `${ADMIN_FILTERED_SEARCH_NAMESPACE}-recent-tags`,
      }),
      upgradeStatusTokenConfig,
    ]);
  });

  describe('Single runner row', () => {
    const { id: graphqlId, shortSha, adminUrl } = mockRunners[0];
    const id = getIdFromGraphQLId(graphqlId);

    beforeEach(async () => {
      mockRunnersCountHandler.mockClear();

      await createComponent({ mountFn: mountExtended });
    });

    it('Links to the runner page', () => {
      const runnerLink = wrapper.find('tr [data-testid="td-summary"]').findComponent(GlLink);

      expect(runnerLink.text()).toBe(`#${id} (${shortSha})`);
      expect(runnerLink.attributes('href')).toBe(adminUrl);
    });

    it('Shows job status and links to jobs', () => {
      const badge = wrapper
        .find('tr [data-testid="td-status"]')
        .findComponent(RunnerJobStatusBadge);

      expect(badge.props('jobStatus')).toBe(mockRunners[0].jobExecutionStatus);
      expect(badge.attributes('href')).toBe(`${adminUrl}#${JOBS_ROUTE_PATH}`);
    });

    it('When runner is paused or unpaused, some data is refetched', () => {
      expect(mockRunnersCountHandler).toHaveBeenCalledTimes(COUNT_QUERIES);

      findRunnerActionsCell().vm.$emit('toggledPaused');

      expect(mockRunnersCountHandler).toHaveBeenCalledTimes(COUNT_QUERIES * 2);
      expect(showToast).toHaveBeenCalledTimes(0);
    });

    it('When runner is deleted, data is refetched and a toast message is shown', () => {
      findRunnerActionsCell().vm.$emit('deleted', { message: 'Runner deleted' });

      expect(showToast).toHaveBeenCalledTimes(1);
      expect(showToast).toHaveBeenCalledWith('Runner deleted');
    });
  });

  describe('when a filter is preselected', () => {
    beforeEach(async () => {
      setWindowLocation(`?status[]=${STATUS_ONLINE}&runner_type[]=${INSTANCE_TYPE}&paused[]=true`);

      await createComponent({ mountFn: mountExtended });
    });

    it('sets the filters in the search bar', () => {
      expect(findRunnerFilteredSearchBar().props('value')).toEqual({
        runnerType: INSTANCE_TYPE,
        membership: DEFAULT_MEMBERSHIP,
        filters: [
          { type: PARAM_KEY_STATUS, value: { data: STATUS_ONLINE, operator: '=' } },
          { type: PARAM_KEY_PAUSED, value: { data: 'true', operator: '=' } },
        ],
        sort: DEFAULT_SORT,
        pagination: {},
      });
    });

    it('requests the runners with filter parameters', () => {
      expect(mockRunnersHandler).toHaveBeenLastCalledWith({
        status: STATUS_ONLINE,
        type: INSTANCE_TYPE,
        membership: DEFAULT_MEMBERSHIP,
        paused: true,
        sort: DEFAULT_SORT,
        first: RUNNER_PAGE_SIZE,
      });
    });

    it('fetches count results for requested status', () => {
      expect(mockRunnersCountHandler).toHaveBeenCalledWith({
        type: INSTANCE_TYPE,
        membership: DEFAULT_MEMBERSHIP,
        status: STATUS_ONLINE,
        paused: true,
      });
    });
  });

  describe('when a filter is selected by the user', () => {
    beforeEach(async () => {
      await createComponent({ mountFn: mountExtended });

      findRunnerFilteredSearchBar().vm.$emit('input', {
        runnerType: null,
        membership: DEFAULT_MEMBERSHIP,
        filters: [{ type: PARAM_KEY_STATUS, value: { data: STATUS_ONLINE, operator: '=' } }],
        sort: CREATED_ASC,
      });

      await nextTick();
    });

    it('updates the browser url', () => {
      expect(updateHistory).toHaveBeenLastCalledWith({
        title: expect.any(String),
        url: expect.stringContaining('?status[]=ONLINE&sort=CREATED_ASC'),
      });
    });

    it('requests the runners with filters', () => {
      expect(mockRunnersHandler).toHaveBeenLastCalledWith({
        status: STATUS_ONLINE,
        membership: DEFAULT_MEMBERSHIP,
        sort: CREATED_ASC,
        first: RUNNER_PAGE_SIZE,
      });
    });

    it('fetches count results for requested status', () => {
      expect(mockRunnersCountHandler).toHaveBeenCalledWith({
        status: STATUS_ONLINE,
        membership: DEFAULT_MEMBERSHIP,
      });
    });
  });

  it('when runners have not loaded, shows a loading state', () => {
    createComponent();
    expect(findRunnerList().props('loading')).toBe(true);
    expect(findRunnerPagination().attributes('disabled')).toBeDefined();
  });

  describe('Bulk delete', () => {
    describe('Before runners are deleted', () => {
      beforeEach(async () => {
        await createComponent({ mountFn: mountExtended });
      });

      it('runner list is checkable', () => {
        expect(findRunnerList().props('checkable')).toBe(true);
      });
    });

    describe('When runners are deleted', () => {
      beforeEach(async () => {
        await createComponent({ mountFn: mountExtended });
      });

      it('count data is refetched', () => {
        expect(mockRunnersCountHandler).toHaveBeenCalledTimes(COUNT_QUERIES);

        findRunnerList().vm.$emit('deleted', { message: 'Runners deleted' });

        expect(mockRunnersCountHandler).toHaveBeenCalledTimes(COUNT_QUERIES * 2);
      });

      it('toast is shown', () => {
        expect(showToast).toHaveBeenCalledTimes(0);

        findRunnerList().vm.$emit('deleted', { message: 'Runners deleted' });

        expect(showToast).toHaveBeenCalledTimes(1);
        expect(showToast).toHaveBeenCalledWith('Runners deleted');
      });
    });
  });

  describe('when no runners are found', () => {
    beforeEach(async () => {
      mockRunnersHandler.mockResolvedValue({
        data: {
          runners: {
            nodes: [],
            pageInfo: emptyPageInfo,
          },
        },
      });

      await createComponent();
    });

    it('shows no errors', () => {
      expect(createAlert).not.toHaveBeenCalled();
    });

    it('shows an empty state', () => {
      expect(findRunnerListEmptyState().props()).toEqual({
        newRunnerPath,
        isSearchFiltered: false,
        filteredSvgPath: emptyStateFilteredSvgPath,
        registrationToken: mockRegistrationToken,
        svgPath: emptyStateSvgPath,
      });
    });

    describe('when a filter is selected by the user', () => {
      beforeEach(async () => {
        findRunnerFilteredSearchBar().vm.$emit('input', {
          runnerType: null,
          membership: DEFAULT_MEMBERSHIP,
          filters: [{ type: PARAM_KEY_STATUS, value: { data: STATUS_ONLINE, operator: '=' } }],
          sort: CREATED_ASC,
        });
        await waitForPromises();
      });

      it('shows an empty state for a filtered search', () => {
        expect(findRunnerListEmptyState().props('isSearchFiltered')).toBe(true);
      });
    });
  });

  describe('when runners query fails', () => {
    beforeEach(async () => {
      mockRunnersHandler.mockRejectedValue(new Error('Error!'));
      await createComponent();
    });

    it('error is shown to the user', () => {
      expect(createAlert).toHaveBeenCalledTimes(1);
    });

    it('error is reported to sentry', () => {
      expect(captureException).toHaveBeenCalledWith({
        error: new Error('Error!'),
        component: 'AdminRunnersApp',
      });
    });
  });

  describe('Pagination', () => {
    const { pageInfo } = allRunnersDataPaginated.data.runners;

    beforeEach(async () => {
      mockRunnersHandler.mockResolvedValue(allRunnersDataPaginated);

      await createComponent({ mountFn: mountExtended });
    });

    it('passes the page info', () => {
      expect(findRunnerPagination().props('pageInfo')).toEqual(pageInfo);
    });

    it('navigates to the next page', async () => {
      await findRunnerPaginationNext().trigger('click');

      expect(mockRunnersHandler).toHaveBeenLastCalledWith({
        membership: DEFAULT_MEMBERSHIP,
        sort: CREATED_DESC,
        first: RUNNER_PAGE_SIZE,
        after: pageInfo.endCursor,
      });
    });
  });
});