summaryrefslogtreecommitdiff
path: root/spec/services/suggestions/apply_service_spec.rb
blob: bdbcb0fdb0748452d378d682da48505fb0c55879 (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
# frozen_string_literal: true

require 'spec_helper'

describe Suggestions::ApplyService do
  include ProjectForksHelper

  def build_position(args = {})
    default_args = { old_path: "files/ruby/popen.rb",
                     new_path: "files/ruby/popen.rb",
                     old_line: nil,
                     new_line: 9,
                     diff_refs: merge_request.diff_refs }

    Gitlab::Diff::Position.new(default_args.merge(args))
  end

  shared_examples 'successfully creates commit and updates suggestion' do
    def apply(suggestion)
      result = subject.execute(suggestion)
      expect(result[:status]).to eq(:success)
    end

    it 'updates the file with the new contents' do
      apply(suggestion)

      blob = project.repository.blob_at_branch(merge_request.source_branch,
                                               position.new_path)

      expect(blob.data).to eq(expected_content)
    end

    it 'updates suggestion applied and commit_id columns' do
      expect { apply(suggestion) }
        .to change(suggestion, :applied)
        .from(false).to(true)
        .and change(suggestion, :commit_id)
        .from(nil)
    end

    it 'created commit has users email and name' do
      apply(suggestion)

      commit = project.repository.commit

      expect(user.commit_email).not_to eq(user.email)
      expect(commit.author_email).to eq(user.commit_email)
      expect(commit.committer_email).to eq(user.commit_email)
      expect(commit.author_name).to eq(user.name)
    end
  end

  let(:project) { create(:project, :repository) }
  let(:user) { create(:user, :commit_email) }

  let(:position) { build_position }

  let(:diff_note) do
    create(:diff_note_on_merge_request, noteable: merge_request, position: position, project: project)
  end

  let(:suggestion) do
    create(:suggestion, :content_from_repo, note: diff_note,
                                            to_content: "      raise RuntimeError, 'Explosion'\n      # explosion?\n")
  end

  subject { described_class.new(user) }

  context 'patch is appliable' do
    let(:expected_content) do
      <<-CONTENT.strip_heredoc
          require 'fileutils'
          require 'open3'

          module Popen
            extend self

            def popen(cmd, path=nil)
              unless cmd.is_a?(Array)
                raise RuntimeError, 'Explosion'
                # explosion?
              end

              path ||= Dir.pwd

              vars = {
                "PWD" => path
              }

              options = {
                chdir: path
              }

              unless File.directory?(path)
                FileUtils.mkdir_p(path)
              end

              @cmd_output = ""
              @cmd_status = 0

              Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
                @cmd_output << stdout.read
                @cmd_output << stderr.read
                @cmd_status = wait_thr.value.exitstatus
              end

              return @cmd_output, @cmd_status
            end
          end
      CONTENT
    end

    context 'non-fork project' do
      let(:merge_request) do
        create(:merge_request, source_project: project,
                               target_project: project)
      end

      before do
        project.add_maintainer(user)
      end

      it_behaves_like 'successfully creates commit and updates suggestion'

      context 'when it fails to apply because the file was changed' do
        it 'returns error message' do
          service = instance_double(Files::UpdateService)

          expect(Files::UpdateService).to receive(:new)
            .and_return(service)

          allow(service).to receive(:execute)
            .and_raise(Files::UpdateService::FileChangedError)

          result = subject.execute(suggestion)

          expect(result).to eq(message: 'The file has been changed', status: :error)
        end
      end

      context 'when HEAD from position is different from source branch HEAD on repo' do
        it 'returns error message' do
          allow(suggestion).to receive(:appliable?) { true }
          allow(suggestion.position).to receive(:head_sha) { 'old-sha' }
          allow(suggestion.noteable).to receive(:source_branch_sha) { 'new-sha' }

          result = subject.execute(suggestion)

          expect(result).to eq(message: 'The file has been changed', status: :error)
        end
      end

      context 'multiple suggestions applied' do
        let(:expected_content) do
          <<-CONTENT.strip_heredoc
              require 'fileutils'
              require 'open3'

              module Popen
                extend self


                def popen(cmd, path=nil)
                  unless cmd.is_a?(Array)
                    # v1 change
                  end

                  path ||= Dir.pwd
                  # v1 change
                  vars = {
                    "PWD" => path
                  }

                  options = {
                    chdir: path
                  }
                  # v2 change
                  unless File.directory?(path)
                    FileUtils.mkdir_p(path)
                  end

                  @cmd_output = ""
                  # v2 change

                  Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
                    @cmd_output << stdout.read
                    @cmd_output << stderr.read
                    @cmd_status = wait_thr.value.exitstatus
                  end

                  return @cmd_output, @cmd_status
                end
              end
          CONTENT
        end

        def create_suggestion(diff, old_line: nil, new_line: nil, from_content:, to_content:, path:)
          position = Gitlab::Diff::Position.new(old_path: path,
                                                new_path: path,
                                                old_line: old_line,
                                                new_line: new_line,
                                                diff_refs: diff.diff_refs)

          suggestion_note = create(:diff_note_on_merge_request, noteable: merge_request,
                                                                original_position: position,
                                                                position: position,
                                                                project: project)
          create(:suggestion, note: suggestion_note,
                              from_content: from_content,
                              to_content: to_content)
        end

        def apply_suggestion(suggestion)
          suggestion.reload
          merge_request.reload
          merge_request.clear_memoized_shas

          result = subject.execute(suggestion)
          expect(result[:status]).to eq(:success)

          refresh = MergeRequests::RefreshService.new(project, user)
          refresh.execute(merge_request.diff_head_sha,
                          suggestion.commit_id,
                          merge_request.source_branch_ref)

          result
        end

        def fetch_raw_diff(suggestion)
          project.reload.commit(suggestion.commit_id).diffs.diff_files.first.diff.diff
        end

        it 'applies multiple suggestions in subsequent versions correctly' do
          diff = merge_request.merge_request_diff
          path = 'files/ruby/popen.rb'

          suggestion_1_changes = { old_line: nil,
                                   new_line: 13,
                                   from_content: "\n",
                                   to_content: "# v1 change\n",
                                   path: path }

          suggestion_2_changes = { old_line: 24,
                                   new_line: 31,
                                   from_content: "      @cmd_output << stderr.read\n",
                                   to_content: "# v2 change\n",
                                   path: path }

          suggestion_1 = create_suggestion(diff, suggestion_1_changes)
          suggestion_2 = create_suggestion(diff, suggestion_2_changes)

          apply_suggestion(suggestion_1)

          suggestion_1_diff = fetch_raw_diff(suggestion_1)

          # rubocop: disable Layout/TrailingWhitespace
          expected_suggestion_1_diff = <<-CONTENT.strip_heredoc
            @@ -10,7 +10,7 @@ module Popen
                 end
             
                 path ||= Dir.pwd
            -
            +# v1 change
                 vars = {
                   "PWD" => path
                 }
          CONTENT
          # rubocop: enable Layout/TrailingWhitespace

          apply_suggestion(suggestion_2)

          suggestion_2_diff = fetch_raw_diff(suggestion_2)

          # rubocop: disable Layout/TrailingWhitespace
          expected_suggestion_2_diff = <<-CONTENT.strip_heredoc
            @@ -28,7 +28,7 @@ module Popen
             
                 Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
                   @cmd_output << stdout.read
            -      @cmd_output << stderr.read
            +# v2 change
                   @cmd_status = wait_thr.value.exitstatus
                 end
          CONTENT
          # rubocop: enable Layout/TrailingWhitespace

          expect(suggestion_1_diff.strip).to eq(expected_suggestion_1_diff.strip)
          expect(suggestion_2_diff.strip).to eq(expected_suggestion_2_diff.strip)
        end
      end

      context 'multi-line suggestion' do
        let(:expected_content) do
          <<~CONTENT
            require 'fileutils'
            require 'open3'

            module Popen
              extend self

            # multi
            # line

                vars = {
                  "PWD" => path
                }

                options = {
                  chdir: path
                }

                unless File.directory?(path)
                  FileUtils.mkdir_p(path)
                end

                @cmd_output = ""
                @cmd_status = 0

                Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
                  @cmd_output << stdout.read
                  @cmd_output << stderr.read
                  @cmd_status = wait_thr.value.exitstatus
                end

                return @cmd_output, @cmd_status
              end
            end
          CONTENT
        end

        let(:suggestion) do
          create(:suggestion, :content_from_repo, note: diff_note,
                                                  lines_above: 2,
                                                  lines_below: 3,
                                                  to_content: "# multi\n# line\n")
        end

        it_behaves_like 'successfully creates commit and updates suggestion'
      end

      context 'remove an empty line suggestion' do
        let(:expected_content) do
          <<~CONTENT
            require 'fileutils'
            require 'open3'

            module Popen
              extend self

              def popen(cmd, path=nil)
                unless cmd.is_a?(Array)
                  raise RuntimeError, "System commands must be given as an array of strings"
                end

                path ||= Dir.pwd
                vars = {
                  "PWD" => path
                }

                options = {
                  chdir: path
                }

                unless File.directory?(path)
                  FileUtils.mkdir_p(path)
                end

                @cmd_output = ""
                @cmd_status = 0

                Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
                  @cmd_output << stdout.read
                  @cmd_output << stderr.read
                  @cmd_status = wait_thr.value.exitstatus
                end

                return @cmd_output, @cmd_status
              end
            end
          CONTENT
        end

        let(:position) { build_position(new_line: 13) }
        let(:suggestion) do
          create(:suggestion, :content_from_repo, note: diff_note, to_content: "")
        end

        it_behaves_like 'successfully creates commit and updates suggestion'
      end
    end

    context 'fork-project' do
      let(:project) { create(:project, :public, :repository) }

      let(:forked_project) do
        fork_project_with_submodules(project, user, repository: project.repository)
      end

      let(:merge_request) do
        create(:merge_request,
               source_branch: 'conflict-resolvable-fork', source_project: forked_project,
               target_branch: 'conflict-start', target_project: project)
      end

      let!(:diff_note) do
        create(:diff_note_on_merge_request, noteable: merge_request, position: position, project: project)
      end

      before do
        project.add_maintainer(user)
      end

      it 'updates file in the source project' do
        expect(Files::UpdateService).to receive(:new)
          .with(merge_request.source_project, user, anything)
          .and_call_original

        subject.execute(suggestion)
      end
    end
  end

  context 'no permission' do
    let(:merge_request) do
      create(:merge_request, source_project: project,
                             target_project: project)
    end

    let(:diff_note) do
      create(:diff_note_on_merge_request, noteable: merge_request,
                                          position: position,
                                          project: project)
    end

    context 'user cannot write in project repo' do
      before do
        project.add_reporter(user)
      end

      it 'returns error' do
        result = subject.execute(suggestion)

        expect(result).to eq(message: "You are not allowed to push into this branch",
                             status: :error)
      end
    end
  end

  context 'patch is not appliable' do
    let(:merge_request) do
      create(:merge_request, source_project: project,
                             target_project: project)
    end

    let(:diff_note) do
      create(:diff_note_on_merge_request, noteable: merge_request,
                                          position: position,
                                          project: project)
    end

    before do
      project.add_maintainer(user)
    end

    context 'diff file was not found' do
      it 'returns error message' do
        expect(suggestion.note).to receive(:latest_diff_file) { nil }

        result = subject.execute(suggestion)

        expect(result).to eq(message: 'Suggestion is not appliable',
                             status: :error)
      end
    end

    context 'suggestion is eligible to be outdated' do
      it 'returns error message' do
        expect(suggestion).to receive(:outdated?) { true }

        result = subject.execute(suggestion)

        expect(result).to eq(message: 'Suggestion is not appliable',
                             status: :error)
      end
    end

    context 'suggestion was already applied' do
      it 'returns success status' do
        result = subject.execute(suggestion)

        expect(result[:status]).to eq(:success)
      end
    end

    context 'note is outdated' do
      before do
        allow(diff_note).to receive(:active?) { false }
      end

      it 'returns error message' do
        result = subject.execute(suggestion)

        expect(result).to eq(message: 'Suggestion is not appliable',
                             status: :error)
      end
    end

    context 'suggestion was already applied' do
      before do
        suggestion.update!(applied: true, commit_id: 'sha')
      end

      it 'returns error message' do
        result = subject.execute(suggestion)

        expect(result).to eq(message: 'Suggestion is not appliable',
                             status: :error)
      end
    end
  end
end