Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ci_variable_drawer_spec.js « components « ci_variable_list « ci « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 809d638a8ea426bc72dec324dc7badeec20ef288 (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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import { nextTick } from 'vue';
import {
  GlDrawer,
  GlFormCombobox,
  GlFormGroup,
  GlFormInput,
  GlFormSelect,
  GlLink,
  GlModal,
  GlSprintf,
} from '@gitlab/ui';
import { mountExtended, shallowMountExtended } from 'helpers/vue_test_utils_helper';
import { helpPagePath } from '~/helpers/help_page_helper';
import CiEnvironmentsDropdown from '~/ci/common/private/ci_environments_dropdown';
import CiVariableDrawer from '~/ci/ci_variable_list/components/ci_variable_drawer.vue';
import { awsTokenList } from '~/ci/ci_variable_list/components/ci_variable_autocomplete_tokens';
import {
  ADD_VARIABLE_ACTION,
  DRAWER_EVENT_LABEL,
  EDIT_VARIABLE_ACTION,
  EVENT_ACTION,
  variableOptions,
  projectString,
  variableTypes,
} from '~/ci/ci_variable_list/constants';
import { mockTracking } from 'helpers/tracking_helper';
import { mockVariablesWithScopes } from '../mocks';

describe('CI Variable Drawer', () => {
  let wrapper;
  let trackingSpy;

  const itif = (condition) => (condition ? it : it.skip);

  const mockProjectVariable = mockVariablesWithScopes(projectString)[0];
  const mockProjectVariableFileType = mockVariablesWithScopes(projectString)[1];
  const mockEnvScope = 'staging';
  const mockEnvironments = ['*', 'dev', 'staging', 'production'];

  // matches strings that contain at least 8 consecutive characters consisting of only
  // letters (both uppercase and lowercase), digits, or the specified special characters
  const maskableRegex = '^[a-zA-Z0-9_+=/@:.~-]{8,}$';

  // matches strings that consist of at least 8 or more non-whitespace characters
  const maskableRawRegex = '^\\S{8,}$';

  const defaultProps = {
    areEnvironmentsLoading: false,
    areScopedVariablesAvailable: true,
    environments: mockEnvironments,
    hideEnvironmentScope: false,
    selectedVariable: {},
    mode: ADD_VARIABLE_ACTION,
  };

  const defaultProvide = {
    isProtectedByDefault: true,
    environmentScopeLink: '/help/environments',
    maskableRawRegex,
    maskableRegex,
  };

  const createComponent = ({
    mountFn = shallowMountExtended,
    props = {},
    provide = {},
    stubs = {},
  } = {}) => {
    wrapper = mountFn(CiVariableDrawer, {
      propsData: {
        ...defaultProps,
        ...props,
      },
      provide: {
        ...defaultProvide,
        ...provide,
      },
      stubs,
    });
  };

  const findConfirmBtn = () => wrapper.findByTestId('ci-variable-confirm-button');
  const findConfirmDeleteModal = () => wrapper.findComponent(GlModal);
  const findDeleteBtn = () => wrapper.findByTestId('ci-variable-delete-button');
  const findDescriptionField = () => wrapper.findByTestId('ci-variable-description');
  const findDisabledEnvironmentScopeDropdown = () => wrapper.findComponent(GlFormInput);
  const findDrawer = () => wrapper.findComponent(GlDrawer);
  const findEnvironmentScopeDropdown = () => wrapper.findComponent(CiEnvironmentsDropdown);
  const findExpandedCheckbox = () => wrapper.findByTestId('ci-variable-expanded-checkbox');
  const findFlagsDocsLink = () => wrapper.findByTestId('ci-variable-flags-docs-link');
  const findKeyField = () => wrapper.findComponent(GlFormCombobox);
  const findMaskedCheckbox = () => wrapper.findByTestId('ci-variable-masked-checkbox');
  const findProtectedCheckbox = () => wrapper.findByTestId('ci-variable-protected-checkbox');
  const findValueField = () => wrapper.findByTestId('ci-variable-value');
  const findValueLabel = () => wrapper.findByTestId('ci-variable-value-label');
  const findTitle = () => findDrawer().find('h2');
  const findTypeDropdown = () => wrapper.findComponent(GlFormSelect);
  const findVariablesPrecedenceDocsLink = () =>
    wrapper.findByTestId('ci-variable-precedence-docs-link');

  describe('template', () => {
    beforeEach(() => {
      createComponent({ stubs: { GlFormGroup, GlLink, GlSprintf } });
    });

    it('renders docs link for variables precendece', () => {
      expect(findVariablesPrecedenceDocsLink().attributes('href')).toBe(
        helpPagePath('ci/variables/index', { anchor: 'cicd-variable-precedence' }),
      );
    });

    it('renders docs link for flags', () => {
      expect(findFlagsDocsLink().attributes('href')).toBe(
        helpPagePath('ci/variables/index', { anchor: 'define-a-cicd-variable-in-the-ui' }),
      );
    });

    it('value field is resizable', () => {
      expect(findValueField().props('noResize')).toBe(false);
    });
  });

  describe('validations', () => {
    describe('type dropdown', () => {
      beforeEach(() => {
        createComponent({ mountFn: mountExtended });
      });

      it('adds each type option as a dropdown item', () => {
        expect(findTypeDropdown().findAll('option')).toHaveLength(variableOptions.length);

        variableOptions.forEach((v) => {
          expect(findTypeDropdown().text()).toContain(v.text);
        });
      });

      it('is set to environment variable by default', () => {
        expect(findTypeDropdown().findAll('option').at(0).attributes('value')).toBe(
          variableTypes.envType,
        );
      });

      it('renders the selected variable type', () => {
        createComponent({
          mountFn: mountExtended,
          props: {
            areEnvironmentsLoading: true,
            selectedVariable: mockProjectVariableFileType,
          },
        });

        expect(findTypeDropdown().element.value).toBe(variableTypes.fileType);
      });
    });

    describe('environment scope dropdown', () => {
      it('passes correct props to the dropdown', () => {
        createComponent({
          props: {
            areEnvironmentsLoading: true,
            selectedVariable: { ...mockProjectVariable, environmentScope: mockEnvScope },
          },
          stubs: { CiEnvironmentsDropdown },
        });

        expect(findEnvironmentScopeDropdown().props()).toMatchObject({
          areEnvironmentsLoading: true,
          environments: mockEnvironments,
          selectedEnvironmentScope: mockEnvScope,
        });
      });

      it('hides environment scope dropdown when hideEnvironmentScope is true', () => {
        createComponent({
          props: { hideEnvironmentScope: true },
          stubs: { CiEnvironmentsDropdown },
        });

        expect(findEnvironmentScopeDropdown().exists()).toBe(false);
      });

      it('disables the environment scope dropdown when areScopedVariablesAvailable is false', () => {
        createComponent({
          mountFn: mountExtended,
          props: { areScopedVariablesAvailable: false },
        });

        expect(findEnvironmentScopeDropdown().exists()).toBe(false);
        expect(findDisabledEnvironmentScopeDropdown().attributes('readonly')).toBe('readonly');
      });
    });

    describe('protected flag', () => {
      beforeEach(() => {
        createComponent();
      });

      it('is true by default when isProtectedByDefault is true', () => {
        expect(findProtectedCheckbox().attributes('checked')).toBeDefined();
      });

      it('is not checked when isProtectedByDefault is false', () => {
        createComponent({ provide: { isProtectedByDefault: false } });

        expect(findProtectedCheckbox().attributes('checked')).toBeUndefined();
      });

      it('inherits value of selected variable when editing', () => {
        createComponent({
          props: {
            selectedVariable: mockProjectVariableFileType,
            mode: EDIT_VARIABLE_ACTION,
          },
        });

        expect(findProtectedCheckbox().attributes('checked')).toBeUndefined();
      });
    });

    describe('masked flag', () => {
      beforeEach(() => {
        createComponent();
      });

      it('is false by default', () => {
        expect(findMaskedCheckbox().attributes('checked')).toBeUndefined();
      });

      it('inherits value of selected variable when editing', () => {
        createComponent({
          props: {
            selectedVariable: mockProjectVariableFileType,
            mode: EDIT_VARIABLE_ACTION,
          },
        });

        expect(findMaskedCheckbox().attributes('checked')).toBeDefined();
      });
    });

    describe('expanded flag', () => {
      beforeEach(() => {
        createComponent();
      });

      it('is true by default when adding a variable', () => {
        expect(findExpandedCheckbox().attributes('checked')).toBeDefined();
      });

      it('inherits value of selected variable when editing', () => {
        createComponent({
          props: {
            selectedVariable: mockProjectVariableFileType,
            mode: EDIT_VARIABLE_ACTION,
          },
        });

        expect(findExpandedCheckbox().attributes('checked')).toBeUndefined();
      });

      it("sets the variable's raw value", async () => {
        await findKeyField().vm.$emit('input', 'NEW_VARIABLE');
        await findExpandedCheckbox().vm.$emit('change');
        await findConfirmBtn().vm.$emit('click');

        const sentRawValue = wrapper.emitted('add-variable')[0][0].raw;
        expect(sentRawValue).toBe(!defaultProps.raw);
      });

      it('shows help text when variable is not expanded (will be evaluated as raw)', async () => {
        expect(findExpandedCheckbox().attributes('checked')).toBeDefined();
        expect(findDrawer().text()).not.toContain(
          'Variable value will be evaluated as raw string.',
        );

        await findExpandedCheckbox().vm.$emit('change');

        expect(findExpandedCheckbox().attributes('checked')).toBeUndefined();
        expect(findDrawer().text()).toContain('Variable value will be evaluated as raw string.');
      });

      it('shows help text when variable is expanded and contains the $ character', async () => {
        expect(findDrawer().text()).not.toContain(
          'Unselect "Expand variable reference" if you want to use the variable value as a raw string.',
        );

        await findValueField().vm.$emit('input', '$NEW_VALUE');

        expect(findDrawer().text()).toContain(
          'Unselect "Expand variable reference" if you want to use the variable value as a raw string.',
        );
      });
    });

    describe('key', () => {
      beforeEach(() => {
        createComponent();
      });

      it('prompts AWS tokens as options', () => {
        expect(findKeyField().props('tokenList')).toBe(awsTokenList);
      });

      const keyFeedbackMessage = "A variable key can only contain letters, numbers, and '_'.";
      describe.each`
        key                      | feedbackMessage       | submitButtonDisabledState
        ${'validKey123'}         | ${''}                 | ${undefined}
        ${'VALID_KEY'}           | ${''}                 | ${undefined}
        ${''}                    | ${''}                 | ${'true'}
        ${'invalid!!key'}        | ${keyFeedbackMessage} | ${'true'}
        ${'key with whitespace'} | ${keyFeedbackMessage} | ${'true'}
        ${'multiline\nkey'}      | ${keyFeedbackMessage} | ${'true'}
      `('key validation', ({ key, feedbackMessage, submitButtonDisabledState }) => {
        it(`validates key ${key} correctly`, async () => {
          await findKeyField().vm.$emit('input', key);

          expect(findConfirmBtn().attributes('disabled')).toBe(submitButtonDisabledState);
          expect(wrapper.text()).toContain(feedbackMessage);
        });
      });
    });

    describe('value', () => {
      beforeEach(() => {
        createComponent();
      });

      it('can submit empty value', async () => {
        await findKeyField().vm.$emit('input', 'NEW_VARIABLE');

        // value is empty by default
        expect(findConfirmBtn().attributes('disabled')).toBeUndefined();
      });

      const invalidValues = {
        short: 'short',
        multiLine: 'multiline\nvalue',
        unsupportedChar: 'unsupported|char',
        twoUnsupportedChars: 'unsupported|chars!',
        threeUnsupportedChars: '%unsupported|chars!',
        shortAndMultiLine: 'sho\nrt',
        shortAndUnsupportedChar: 'short!',
        shortAndMultiLineAndUnsupportedChar: 'short\n!',
        multiLineAndUnsupportedChar: 'multiline\nvalue!',
      };
      const maskedValidationIssuesText = {
        short: 'The value must have at least 8 characters.',
        multiLine:
          'This value cannot be masked because it contains the following characters: whitespace characters.',
        unsupportedChar:
          'This value cannot be masked because it contains the following characters: |.',
        unsupportedDollarChar:
          'This value cannot be masked because it contains the following characters: $.',
        twoUnsupportedChars:
          'This value cannot be masked because it contains the following characters: |, !.',
        threeUnsupportedChars:
          'This value cannot be masked because it contains the following characters: %, |, !.',
        shortAndMultiLine:
          'This value cannot be masked because it contains the following characters: whitespace characters. The value must have at least 8 characters.',
        shortAndUnsupportedChar:
          'This value cannot be masked because it contains the following characters: !. The value must have at least 8 characters.',
        shortAndMultiLineAndUnsupportedChar:
          'This value cannot be masked because it contains the following characters: ! and whitespace characters. The value must have at least 8 characters.',
        multiLineAndUnsupportedChar:
          'This value cannot be masked because it contains the following characters: ! and whitespace characters.',
      };

      describe.each`
        value                                                | canSubmit | trackingErrorProperty | validationIssueKey
        ${'secretValue'}                                     | ${true}   | ${null}               | ${''}
        ${'~v@lid:symbols.'}                                 | ${true}   | ${null}               | ${''}
        ${invalidValues.short}                               | ${false}  | ${null}               | ${'short'}
        ${invalidValues.multiLine}                           | ${false}  | ${'\n'}               | ${'multiLine'}
        ${'dollar$ign'}                                      | ${false}  | ${'$'}                | ${'unsupportedDollarChar'}
        ${invalidValues.unsupportedChar}                     | ${false}  | ${'|'}                | ${'unsupportedChar'}
        ${invalidValues.twoUnsupportedChars}                 | ${false}  | ${'|!'}               | ${'twoUnsupportedChars'}
        ${invalidValues.threeUnsupportedChars}               | ${false}  | ${'%|!'}              | ${'threeUnsupportedChars'}
        ${invalidValues.shortAndMultiLine}                   | ${false}  | ${'\n'}               | ${'shortAndMultiLine'}
        ${invalidValues.shortAndUnsupportedChar}             | ${false}  | ${'!'}                | ${'shortAndUnsupportedChar'}
        ${invalidValues.shortAndMultiLineAndUnsupportedChar} | ${false}  | ${'\n!'}              | ${'shortAndMultiLineAndUnsupportedChar'}
        ${invalidValues.multiLineAndUnsupportedChar}         | ${false}  | ${'\n!'}              | ${'multiLineAndUnsupportedChar'}
      `(
        'masking requirements',
        ({ value, canSubmit, trackingErrorProperty, validationIssueKey }) => {
          beforeEach(() => {
            createComponent();

            trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);
            findKeyField().vm.$emit('input', 'NEW_VARIABLE');
            findValueField().vm.$emit('input', value);
            findMaskedCheckbox().vm.$emit('input', true);
          });

          itif(canSubmit)(`can submit when value is ${value}`, () => {
            /* eslint-disable jest/no-standalone-expect */
            expect(findValueLabel().attributes('invalid-feedback')).toBe('');
            expect(findConfirmBtn().attributes('disabled')).toBeUndefined();
            /* eslint-enable jest/no-standalone-expect */
          });

          itif(!canSubmit)(
            `shows validation errors and disables submit button when value is ${value}`,
            () => {
              const validationIssueText = maskedValidationIssuesText[validationIssueKey] || '';

              /* eslint-disable jest/no-standalone-expect */
              expect(findValueLabel().attributes('invalid-feedback')).toBe(validationIssueText);
              expect(findConfirmBtn().attributes('disabled')).toBeDefined();
              /* eslint-enable jest/no-standalone-expect */
            },
          );

          itif(trackingErrorProperty)(
            `sends the correct variable validation tracking event when value is ${value}`,
            () => {
              /* eslint-disable jest/no-standalone-expect */
              expect(trackingSpy).toHaveBeenCalledTimes(1);
              expect(trackingSpy).toHaveBeenCalledWith(undefined, EVENT_ACTION, {
                label: DRAWER_EVENT_LABEL,
                property: trackingErrorProperty,
              });
              /* eslint-enable jest/no-standalone-expect */
            },
          );

          itif(!trackingErrorProperty)(
            `does not send the the correct variable validation tracking event when value is ${value}`,
            () => {
              // eslint-disable-next-line jest/no-standalone-expect
              expect(trackingSpy).toHaveBeenCalledTimes(0);
            },
          );
        },
      );

      it('only sends the tracking event once', async () => {
        trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);
        await findKeyField().vm.$emit('input', 'NEW_VARIABLE');
        await findMaskedCheckbox().vm.$emit('input', true);

        expect(trackingSpy).toHaveBeenCalledTimes(0);

        await findValueField().vm.$emit('input', 'unsupported|char');

        expect(trackingSpy).toHaveBeenCalledTimes(1);

        await findValueField().vm.$emit('input', 'dollar$ign');

        expect(trackingSpy).toHaveBeenCalledTimes(1);
      });
    });
  });

  describe('drawer events', () => {
    it('emits `search-environment-scope` before mounting', () => {
      createComponent();

      expect(wrapper.emitted('search-environment-scope')).toHaveLength(1);
      expect(wrapper.emitted('search-environment-scope')).toEqual([['']]);
    });

    it('emits `close-form` when closing the drawer', async () => {
      createComponent();

      expect(wrapper.emitted('close-form')).toBeUndefined();

      await findDrawer().vm.$emit('close');

      expect(wrapper.emitted('close-form')).toHaveLength(1);
    });

    describe('when adding a variable', () => {
      beforeEach(() => {
        createComponent({ stubs: { GlDrawer } });
      });

      it('title and confirm button renders the correct text', () => {
        expect(findTitle().text()).toBe('Add variable');
        expect(findConfirmBtn().text()).toBe('Add variable');
      });

      it('does not render delete button', () => {
        expect(findDeleteBtn().exists()).toBe(false);
      });

      it('dispatches the add-variable event', async () => {
        await findDescriptionField().vm.$emit('input', 'NEW_DESCRIPTION');
        await findKeyField().vm.$emit('input', 'NEW_VARIABLE');
        await findProtectedCheckbox().vm.$emit('input', false);
        await findExpandedCheckbox().vm.$emit('input', true);
        await findMaskedCheckbox().vm.$emit('input', true);
        await findValueField().vm.$emit('input', 'NEW_VALUE');

        findConfirmBtn().vm.$emit('click');

        expect(wrapper.emitted('add-variable')).toEqual([
          [
            {
              environmentScope: '*',
              description: 'NEW_DESCRIPTION',
              key: 'NEW_VARIABLE',
              masked: true,
              protected: false,
              raw: false, // opposite of expanded
              value: 'NEW_VALUE',
              variableType: 'ENV_VAR',
            },
          ],
        ]);
      });
    });

    describe('when editing a variable', () => {
      beforeEach(() => {
        createComponent({
          props: { mode: EDIT_VARIABLE_ACTION, selectedVariable: mockProjectVariableFileType },
          stubs: { GlDrawer },
        });
      });

      it('title and confirm button renders the correct text', () => {
        expect(findTitle().text()).toBe('Edit variable');
        expect(findConfirmBtn().text()).toBe('Save changes');
      });

      it('dispatches the edit-variable event', async () => {
        await findValueField().vm.$emit('input', 'EDITED_VALUE');
        await findDescriptionField().vm.$emit('input', 'EDITED_DESCRIPTION');

        findConfirmBtn().vm.$emit('click');

        expect(wrapper.emitted('update-variable')).toEqual([
          [
            {
              ...mockProjectVariableFileType,
              description: 'EDITED_DESCRIPTION',
              value: 'EDITED_VALUE',
            },
          ],
        ]);
      });
    });

    describe('when deleting a variable', () => {
      beforeEach(() => {
        createComponent({
          mountFn: mountExtended,
          props: { mode: EDIT_VARIABLE_ACTION, selectedVariable: mockProjectVariableFileType },
        });
      });

      it('bubbles up the delete-variable event', async () => {
        findDeleteBtn().vm.$emit('click');

        await nextTick();

        findConfirmDeleteModal().vm.$emit('primary');

        expect(wrapper.emitted('delete-variable')).toEqual([[mockProjectVariableFileType]]);
      });
    });

    describe('environment scope events', () => {
      beforeEach(() => {
        createComponent({
          mountFn: mountExtended,
          props: {
            mode: EDIT_VARIABLE_ACTION,
            selectedVariable: mockProjectVariableFileType,
            areScopedVariablesAvailable: true,
            hideEnvironmentScope: false,
          },
        });
      });

      it('sets the environment scope', async () => {
        await findEnvironmentScopeDropdown().vm.$emit('select-environment', 'staging');
        await findConfirmBtn().vm.$emit('click');

        expect(wrapper.emitted('update-variable')).toEqual([
          [
            {
              ...mockProjectVariableFileType,
              environmentScope: 'staging',
            },
          ],
        ]);
      });

      it('bubbles up the search event', async () => {
        await findEnvironmentScopeDropdown().vm.$emit('search-environment-scope', 'staging');

        expect(wrapper.emitted('search-environment-scope')[1]).toEqual(['staging']);
      });
    });
  });
});