summaryrefslogtreecommitdiff
path: root/spec/frontend/ide/services/index_spec.js
blob: 623dee387e5faf7eb239483d8bf0c8291f529ea2 (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
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import getIdeProject from 'ee_else_ce/ide/queries/get_ide_project.query.graphql';
import Api from '~/api';
import dismissUserCallout from '~/graphql_shared/mutations/dismiss_user_callout.mutation.graphql';
import services from '~/ide/services';
import { query, mutate } from '~/ide/services/gql';
import { HTTP_STATUS_OK } from '~/lib/utils/http_status';
import { escapeFileUrl } from '~/lib/utils/url_utility';
import ciConfig from '~/ci/pipeline_editor/graphql/queries/ci_config.query.graphql';
import { projectData } from '../mock_data';

jest.mock('~/api');
jest.mock('~/ide/services/gql');

const TEST_NAMESPACE = 'alice';
const TEST_PROJECT = 'wonderland';
const TEST_PROJECT_ID = `${TEST_NAMESPACE}/${TEST_PROJECT}`;
const TEST_BRANCH = 'main-patch-123';
const TEST_COMMIT_SHA = '123456789';
const TEST_FILE_PATH = 'README2.md';
const TEST_FILE_OLD_PATH = 'OLD_README2.md';
const TEST_FILE_PATH_SPECIAL = 'READM?ME/abc';
const TEST_FILE_CONTENTS = 'raw file content';

describe('IDE services', () => {
  describe('commit', () => {
    let payload;

    beforeEach(() => {
      payload = {
        branch: TEST_BRANCH,
        commit_message: 'Hello world',
        actions: [],
        start_sha: TEST_COMMIT_SHA,
      };

      Api.commitMultiple.mockReturnValue(Promise.resolve());
    });

    it('should commit', () => {
      services.commit(TEST_PROJECT_ID, payload);

      expect(Api.commitMultiple).toHaveBeenCalledWith(TEST_PROJECT_ID, payload);
    });
  });

  describe('getRawFileData', () => {
    it("resolves with a file's content if its a tempfile and it isn't renamed", () => {
      const file = {
        path: 'file',
        tempFile: true,
        content: 'content',
        raw: 'raw content',
      };

      return services.getRawFileData(file).then((raw) => {
        expect(raw).toBe('content');
      });
    });

    it('resolves with file.raw if the file is renamed', () => {
      const file = {
        path: 'file',
        tempFile: true,
        content: 'content',
        prevPath: 'old_path',
        raw: 'raw content',
      };

      return services.getRawFileData(file).then((raw) => {
        expect(raw).toBe('raw content');
      });
    });

    it('returns file.raw if it exists', () => {
      const file = {
        path: 'file',
        content: 'content',
        raw: 'raw content',
      };

      return services.getRawFileData(file).then((raw) => {
        expect(raw).toBe('raw content');
      });
    });

    it("returns file.raw if file.raw is empty but file.rawPath doesn't exist", () => {
      const file = {
        path: 'file',
        content: 'content',
        raw: '',
      };

      return services.getRawFileData(file).then((raw) => {
        expect(raw).toBe('');
      });
    });

    describe("if file.rawPath exists but file.raw doesn't exist", () => {
      let file;
      let mock;
      beforeEach(() => {
        file = {
          path: 'file',
          content: 'content',
          raw: '',
          rawPath: 'some_raw_path',
        };

        mock = new MockAdapter(axios);
        mock.onGet(file.rawPath).reply(HTTP_STATUS_OK, 'raw content');

        jest.spyOn(axios, 'get');
      });

      afterEach(() => {
        mock.restore();
      });

      it('sends a request to file.rawPath', () => {
        return services.getRawFileData(file).then((raw) => {
          expect(axios.get).toHaveBeenCalledWith(file.rawPath, {
            transformResponse: [expect.any(Function)],
          });
          expect(raw).toEqual('raw content');
        });
      });

      it('returns arraybuffer for binary files', () => {
        file.binary = true;

        return services.getRawFileData(file).then((raw) => {
          expect(axios.get).toHaveBeenCalledWith(file.rawPath, {
            transformResponse: [expect.any(Function)],
            responseType: 'arraybuffer',
          });
          expect(raw).toEqual('raw content');
        });
      });
    });
  });

  describe('getBaseRawFileData', () => {
    let file;
    let mock;

    beforeEach(() => {
      file = {
        mrChange: null,
        projectId: TEST_PROJECT_ID,
        path: TEST_FILE_PATH,
      };

      jest.spyOn(axios, 'get');

      mock = new MockAdapter(axios);
    });

    afterEach(() => {
      mock.restore();
    });

    it('gives back file.baseRaw for files with that property present', () => {
      file.baseRaw = TEST_FILE_CONTENTS;

      return services.getBaseRawFileData(file, TEST_PROJECT_ID, TEST_COMMIT_SHA).then((content) => {
        expect(content).toEqual(TEST_FILE_CONTENTS);
      });
    });

    it('gives back file.baseRaw for files for temp files', () => {
      file.tempFile = true;
      file.baseRaw = TEST_FILE_CONTENTS;

      return services.getBaseRawFileData(file, TEST_PROJECT_ID, TEST_COMMIT_SHA).then((content) => {
        expect(content).toEqual(TEST_FILE_CONTENTS);
      });
    });

    describe.each`
      relativeUrlRoot | filePath                  | isRenamed
      ${''}           | ${TEST_FILE_PATH}         | ${false}
      ${''}           | ${TEST_FILE_OLD_PATH}     | ${true}
      ${''}           | ${TEST_FILE_PATH_SPECIAL} | ${false}
      ${''}           | ${TEST_FILE_PATH_SPECIAL} | ${true}
      ${'gitlab'}     | ${TEST_FILE_OLD_PATH}     | ${true}
    `(
      'with relativeUrlRoot ($relativeUrlRoot) and filePath ($filePath) and isRenamed ($isRenamed)',
      ({ relativeUrlRoot, filePath, isRenamed }) => {
        beforeEach(() => {
          if (isRenamed) {
            file.mrChange = {
              renamed_file: true,
              old_path: filePath,
            };
          } else {
            file.path = filePath;
          }

          gon.relative_url_root = relativeUrlRoot;

          mock
            .onGet(
              `${relativeUrlRoot}/${TEST_PROJECT_ID}/-/raw/${TEST_COMMIT_SHA}/${escapeFileUrl(
                filePath,
              )}`,
            )
            .reply(HTTP_STATUS_OK, TEST_FILE_CONTENTS);
        });

        it('fetches file content', () =>
          services.getBaseRawFileData(file, TEST_PROJECT_ID, TEST_COMMIT_SHA).then((content) => {
            expect(content).toEqual(TEST_FILE_CONTENTS);
          }));
      },
    );
  });

  describe('getFiles', () => {
    let mock;
    let relativeUrlRoot;
    const TEST_RELATIVE_URL_ROOT = 'blah-blah';

    beforeEach(() => {
      jest.spyOn(axios, 'get');
      relativeUrlRoot = gon.relative_url_root;
      gon.relative_url_root = TEST_RELATIVE_URL_ROOT;

      mock = new MockAdapter(axios);

      mock
        .onGet(`${TEST_RELATIVE_URL_ROOT}/${TEST_PROJECT_ID}/-/files/${TEST_COMMIT_SHA}`)
        .reply(HTTP_STATUS_OK, [TEST_FILE_PATH]);
    });

    afterEach(() => {
      mock.restore();
      gon.relative_url_root = relativeUrlRoot;
    });

    it('initates the api call based on the passed path and commit hash', () => {
      return services.getFiles(TEST_PROJECT_ID, TEST_COMMIT_SHA).then(({ data }) => {
        expect(axios.get).toHaveBeenCalledWith(
          `${gon.relative_url_root}/${TEST_PROJECT_ID}/-/files/${TEST_COMMIT_SHA}`,
          expect.any(Object),
        );
        expect(data).toEqual([TEST_FILE_PATH]);
      });
    });
  });

  describe('pingUsage', () => {
    let mock;
    let relativeUrlRoot;
    const TEST_RELATIVE_URL_ROOT = 'blah-blah';

    beforeEach(() => {
      jest.spyOn(axios, 'post');
      relativeUrlRoot = gon.relative_url_root;
      gon.relative_url_root = TEST_RELATIVE_URL_ROOT;

      mock = new MockAdapter(axios);
    });

    afterEach(() => {
      mock.restore();
      gon.relative_url_root = relativeUrlRoot;
    });

    it('posts to usage endpoint', () => {
      const TEST_PROJECT_PATH = 'foo/bar';
      const axiosURL = `${TEST_RELATIVE_URL_ROOT}/${TEST_PROJECT_PATH}/service_ping/web_ide_pipelines_count`;

      mock.onPost(axiosURL).reply(HTTP_STATUS_OK);

      return services.pingUsage(TEST_PROJECT_PATH).then(() => {
        expect(axios.post).toHaveBeenCalledWith(axiosURL);
      });
    });
  });
  describe('getCiConfig', () => {
    const TEST_PROJECT_PATH = 'foo/bar';
    const TEST_CI_CONFIG = 'test config';

    it('queries with the given CI config and project', () => {
      const result = { data: { ciConfig: { test: 'data' } } };
      query.mockResolvedValue(result);
      return services.getCiConfig(TEST_PROJECT_PATH, TEST_CI_CONFIG).then((data) => {
        expect(data).toEqual(result.data.ciConfig);
        expect(query).toHaveBeenCalledWith({
          query: ciConfig,
          variables: { projectPath: TEST_PROJECT_PATH, content: TEST_CI_CONFIG },
        });
      });
    });
  });
  describe('dismissUserCallout', () => {
    it('mutates the callout to dismiss', () => {
      const result = { data: { callouts: { test: 'data' } } };
      mutate.mockResolvedValue(result);
      return services.dismissUserCallout('test').then((data) => {
        expect(data).toEqual(result.data);
        expect(mutate).toHaveBeenCalledWith({
          mutation: dismissUserCallout,
          variables: { input: { featureName: 'test' } },
        });
      });
    });
  });

  describe('getProjectPermissionsData', () => {
    const TEST_PROJECT_PATH = 'foo/bar';

    it('queries for the project permissions', () => {
      const result = { data: { project: projectData } };
      query.mockResolvedValue(result);

      return services.getProjectPermissionsData(TEST_PROJECT_PATH).then((data) => {
        expect(data).toEqual(result.data.project);
        expect(query).toHaveBeenCalledWith(
          expect.objectContaining({
            query: getIdeProject,
            variables: { projectPath: TEST_PROJECT_PATH },
          }),
        );
      });
    });

    it('converts the returned GraphQL id to the regular ID number', () => {
      const projectId = 2;
      const gqlProjectData = {
        id: `gid://gitlab/Project/${projectId}`,
        userPermissions: {
          bogus: true,
        },
      };

      query.mockResolvedValue({ data: { project: gqlProjectData } });
      return services.getProjectPermissionsData(TEST_PROJECT_PATH).then((data) => {
        expect(data.id).toBe(projectId);
      });
    });
  });
});