merge_request_spec.rb 96.2 KB
Newer Older
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
1 2
require 'spec_helper'

3
describe MergeRequest do
4
  include RepoHelpers
5
  include ProjectForksHelper
6
  include ReactiveCachingHelpers
7

8 9
  subject { create(:merge_request) }

Robert Speicher's avatar
Robert Speicher committed
10
  describe 'associations' do
11 12
    it { is_expected.to belong_to(:target_project).class_name('Project') }
    it { is_expected.to belong_to(:source_project).class_name('Project') }
13
    it { is_expected.to belong_to(:merge_user).class_name("User") }
14
    it { is_expected.to belong_to(:assignee) }
15
    it { is_expected.to have_many(:merge_request_diffs) }
16 17 18 19 20 21 22 23 24 25 26 27 28 29

    context 'for forks' do
      let!(:project) { create(:project) }
      let!(:fork) { fork_project(project) }
      let!(:merge_request) { create(:merge_request, target_project: project, source_project: fork) }

      it 'does not load another project due to inverse relationship' do
        expect(project.merge_requests.first.target_project.object_id).to eq(project.object_id)
      end

      it 'finds the associated merge request' do
        expect(project.merge_requests.find(merge_request.id)).to eq(merge_request)
      end
    end
Robert Speicher's avatar
Robert Speicher committed
30 31
  end

32
  describe '#squash_in_progress?' do
33 34 35
    let(:repo_path) do
      Gitlab::GitalyClient::StorageSettings.allow_disk_access do
        subject.source_project.repository.path
36
      end
37 38
    end
    let(:squash_path) { File.join(repo_path, "gitlab-worktree", "squash-#{subject.id}") }
39

40 41 42
    before do
      system(*%W(#{Gitlab.config.git.bin_path} -C #{repo_path} worktree add --detach #{squash_path} master))
    end
43

44 45 46
    it 'returns true when there is a current squash directory' do
      expect(subject.squash_in_progress?).to be_truthy
    end
47

48 49
    it 'returns false when there is no squash directory' do
      FileUtils.rm_rf(squash_path)
50

51 52
      expect(subject.squash_in_progress?).to be_falsey
    end
53

54 55 56
    it 'returns false when the squash directory has expired' do
      time = 20.minutes.ago.to_time
      File.utime(time, time, squash_path)
57

58
      expect(subject.squash_in_progress?).to be_falsey
59 60
    end

61 62
    it 'returns false when the source project has been removed' do
      allow(subject).to receive(:source_project).and_return(nil)
63

64
      expect(subject.squash_in_progress?).to be_falsey
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    end
  end

  describe '#squash?' do
    let(:merge_request) { build(:merge_request, squash: squash) }
    subject { merge_request.squash? }

    context 'disabled in database' do
      let(:squash) { false }

      it { is_expected.to be_falsy }
    end

    context 'enabled in database' do
      let(:squash) { true }

      it { is_expected.to be_truthy }
    end
  end

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
  describe '#default_squash_commit_message' do
    let(:project) { subject.project }

    def commit_collection(commit_hashes)
      raw_commits = commit_hashes.map { |raw| Commit.from_hash(raw, project) }

      CommitCollection.new(project, raw_commits)
    end

    it 'returns the oldest multiline commit message' do
      commits = commit_collection([
        { message: 'Singleline', parent_ids: [] },
        { message: "Second multiline\nCommit message", parent_ids: [] },
        { message: "First multiline\nCommit message", parent_ids: [] }
      ])

      expect(subject).to receive(:commits).and_return(commits)

      expect(subject.default_squash_commit_message).to eq("First multiline\nCommit message")
    end

    it 'returns the merge request title if there are no multiline commits' do
      commits = commit_collection([
        { message: 'Singleline', parent_ids: [] }
      ])

      expect(subject).to receive(:commits).and_return(commits)

      expect(subject.default_squash_commit_message).to eq(subject.title)
    end
  end

117 118 119 120 121 122 123
  describe 'modules' do
    subject { described_class }

    it { is_expected.to include_module(Issuable) }
    it { is_expected.to include_module(Referable) }
    it { is_expected.to include_module(Sortable) }
    it { is_expected.to include_module(Taskable) }
124 125 126 127

    it_behaves_like 'AtomicInternalId' do
      let(:internal_id_attribute) { :iid }
      let(:instance) { build(:merge_request) }
128
      let(:scope) { :target_project }
129 130 131
      let(:scope_attrs) { { project: instance.target_project } }
      let(:usage) { :merge_requests }
    end
132 133 134
  end

  describe 'validation' do
135 136
    it { is_expected.to validate_presence_of(:target_branch) }
    it { is_expected.to validate_presence_of(:source_branch) }
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
137

138
    context "Validation of merge user with Merge When Pipeline Succeeds" do
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
139 140 141 142 143
      it "allows user to be nil when the feature is disabled" do
        expect(subject).to be_valid
      end

      it "is invalid without merge user" do
144
        subject.merge_when_pipeline_succeeds = true
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
145 146 147 148
        expect(subject).not_to be_valid
      end

      it "is valid with merge user" do
149
        subject.merge_when_pipeline_succeeds = true
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
150 151 152 153 154
        subject.merge_user = build(:user)

        expect(subject).to be_valid
      end
    end
155 156 157

    context 'for forks' do
      let(:project) { create(:project) }
158 159
      let(:fork1) { fork_project(project) }
      let(:fork2) { fork_project(project) }
160 161 162 163 164 165 166 167

      it 'allows merge requests for sibling-forks' do
        subject.source_project = fork1
        subject.target_project = fork2

        expect(subject).to be_valid
      end
    end
168 169
  end

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  describe 'callbacks' do
    describe '#ensure_merge_request_metrics' do
      it 'creates metrics after saving' do
        merge_request = create(:merge_request)

        expect(merge_request.metrics).to be_persisted
        expect(MergeRequest::Metrics.count).to eq(1)
      end

      it 'does not duplicate metrics for a merge request' do
        merge_request = create(:merge_request)

        merge_request.mark_as_merged!

        expect(MergeRequest::Metrics.count).to eq(1)
      end
    end
  end

Robert Speicher's avatar
Robert Speicher committed
189
  describe 'respond to' do
190 191 192
    it { is_expected.to respond_to(:unchecked?) }
    it { is_expected.to respond_to(:can_be_merged?) }
    it { is_expected.to respond_to(:cannot_be_merged?) }
193
    it { is_expected.to respond_to(:merge_params) }
194
    it { is_expected.to respond_to(:merge_when_pipeline_succeeds) }
195
  end
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
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
  describe '.by_commit_sha' do
    subject(:by_commit_sha) { described_class.by_commit_sha(sha) }

    let!(:merge_request) { create(:merge_request, :with_diffs) }

    context 'with sha contained in latest merge request diff' do
      let(:sha) { 'b83d6e391c22777fca1ed3012fce84f633d7fed0' }

      it 'returns merge requests' do
        expect(by_commit_sha).to eq([merge_request])
      end
    end

    context 'with sha contained not in latest merge request diff' do
      let(:sha) { 'b83d6e391c22777fca1ed3012fce84f633d7fed0' }

      it 'returns empty requests' do
        latest_merge_request_diff = merge_request.merge_request_diffs.create
        latest_merge_request_diff.merge_request_diff_commits.where(sha: 'b83d6e391c22777fca1ed3012fce84f633d7fed0').delete_all

        expect(by_commit_sha).to be_empty
      end
    end

    context 'with sha not contained in' do
      let(:sha) { 'b83d6e3' }

      it 'returns empty result' do
        expect(by_commit_sha).to be_empty
      end
    end
  end

230 231 232 233 234 235
  describe '.in_projects' do
    it 'returns the merge requests for a set of projects' do
      expect(described_class.in_projects(Project.all)).to eq([subject])
    end
  end

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
  describe '.set_latest_merge_request_diff_ids!' do
    def create_merge_request_with_diffs(source_branch, diffs: 2)
      params = {
        target_project: project,
        target_branch: 'master',
        source_project: project,
        source_branch: source_branch
      }

      create(:merge_request, params).tap do |mr|
        diffs.times { mr.merge_request_diffs.create }
      end
    end

    let(:project) { create(:project) }

    it 'sets IDs for merge requests, whether they are already set or not' do
      merge_requests = [
        create_merge_request_with_diffs('feature'),
        create_merge_request_with_diffs('feature-conflict'),
        create_merge_request_with_diffs('wip', diffs: 0),
        create_merge_request_with_diffs('csv')
      ]

      merge_requests.take(2).each do |merge_request|
        merge_request.update_column(:latest_merge_request_diff_id, nil)
      end

      expected = merge_requests.map do |merge_request|
        merge_request.merge_request_diffs.maximum(:id)
      end

      expect { project.merge_requests.set_latest_merge_request_diff_ids! }
        .to change { merge_requests.map { |mr| mr.reload.latest_merge_request_diff_id } }.to(expected)
    end
  end

273
  describe '#target_branch_sha' do
274
    let(:project) { create(:project, :repository) }
275

276
    subject { create(:merge_request, source_project: project, target_project: project) }
277

278
    context 'when the target branch does not exist' do
279
      before do
280
        project.repository.rm_branch(subject.author, subject.target_branch)
281
        subject.clear_memoized_shas
282
      end
283 284

      it 'returns nil' do
285
        expect(subject.target_branch_sha).to be_nil
286 287
      end
    end
288 289 290 291 292 293

    it 'returns memoized value' do
      subject.target_branch_sha = '8ffb3c15a5475e59ae909384297fede4badcb4c7'

      expect(subject.target_branch_sha).to eq '8ffb3c15a5475e59ae909384297fede4badcb4c7'
    end
294 295
  end

296 297 298 299 300
  describe '#card_attributes' do
    it 'includes the author name' do
      allow(subject).to receive(:author).and_return(double(name: 'Robert'))
      allow(subject).to receive(:assignee).and_return(nil)

301 302
      expect(subject.card_attributes)
        .to eq({ 'Author' => 'Robert', 'Assignee' => nil })
303 304 305 306 307 308
    end

    it 'includes the assignee name' do
      allow(subject).to receive(:author).and_return(double(name: 'Robert'))
      allow(subject).to receive(:assignee).and_return(double(name: 'Douwe'))

309 310
      expect(subject.card_attributes)
        .to eq({ 'Author' => 'Robert', 'Assignee' => 'Douwe' })
311 312 313
    end
  end

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  describe '#assignee_ids' do
    it 'returns an array of the assigned user id' do
      subject.assignee_id = 123

      expect(subject.assignee_ids).to eq([123])
    end
  end

  describe '#assignee_ids=' do
    it 'sets assignee_id to the last id in the array' do
      subject.assignee_ids = [123, 456]

      expect(subject.assignee_id).to eq(456)
    end
  end

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  describe '#assignee_or_author?' do
    let(:user) { create(:user) }

    it 'returns true for a user that is assigned to a merge request' do
      subject.assignee = user

      expect(subject.assignee_or_author?(user)).to eq(true)
    end

    it 'returns true for a user that is the author of a merge request' do
      subject.author = user

      expect(subject.assignee_or_author?(user)).to eq(true)
    end

    it 'returns false for a user that is not the assignee or author' do
      expect(subject.assignee_or_author?(user)).to eq(false)
    end
  end

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
  describe '#visible_closing_issues_for' do
    let(:guest) { create(:user) }
    let(:developer) { create(:user) }
    let(:issue_1) { create(:issue, project: subject.source_project) }
    let(:issue_2) { create(:issue, project: subject.source_project) }
    let(:confidential_issue) { create(:issue, :confidential, project: subject.source_project) }

    before do
      subject.project.add_developer(subject.author)
      subject.target_branch = subject.project.default_branch
      commit = double('commit1', safe_message: "Fixes #{issue_1.to_reference} #{issue_2.to_reference} #{confidential_issue.to_reference}")
      allow(subject).to receive(:commits).and_return([commit])
    end

    it 'shows only allowed issues to guest' do
      subject.project.add_guest(guest)

      subject.cache_merge_request_closes_issues!

      expect(subject.visible_closing_issues_for(guest)).to match_array([issue_1, issue_2])
    end

    it 'shows only allowed issues to developer' do
      subject.project.add_developer(developer)

      subject.cache_merge_request_closes_issues!

      expect(subject.visible_closing_issues_for(developer)).to match_array([issue_1, confidential_issue, issue_2])
    end

    context 'when external issue tracker is enabled' do
      before do
        subject.project.has_external_issue_tracker = true
        subject.project.save!
      end

      it 'calls non #closes_issues to retrieve data' do
        expect(subject).to receive(:closes_issues)
        expect(subject).not_to receive(:cached_closes_issues)

        subject.visible_closing_issues_for
      end
    end
  end

395 396
  describe '#cache_merge_request_closes_issues!' do
    before do
397
      subject.project.add_developer(subject.author)
398 399 400 401 402 403 404 405
      subject.target_branch = subject.project.default_branch
    end

    it 'caches closed issues' do
      issue  = create :issue, project: subject.project
      commit = double('commit1', safe_message: "Fixes #{issue.to_reference}")
      allow(subject).to receive(:commits).and_return([commit])

406
      expect { subject.cache_merge_request_closes_issues!(subject.author) }.to change(subject.merge_requests_closing_issues, :count).by(1)
407 408
    end

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    it 'does not cache closed issues when merge request is closed' do
      issue  = create :issue, project: subject.project
      commit = double('commit1', safe_message: "Fixes #{issue.to_reference}")

      allow(subject).to receive(:commits).and_return([commit])
      allow(subject).to receive(:state).and_return("closed")

      expect { subject.cache_merge_request_closes_issues!(subject.author) }.not_to change(subject.merge_requests_closing_issues, :count)
    end

    it 'does not cache closed issues when merge request is merged' do
      issue  = create :issue, project: subject.project
      commit = double('commit1', safe_message: "Fixes #{issue.to_reference}")
      allow(subject).to receive(:commits).and_return([commit])
      allow(subject).to receive(:state).and_return("merged")

      expect { subject.cache_merge_request_closes_issues!(subject.author) }.not_to change(subject.merge_requests_closing_issues, :count)
    end

428 429 430 431
    context 'when both internal and external issue trackers are enabled' do
      before do
        subject.project.has_external_issue_tracker = true
        subject.project.save!
432
        create(:jira_service, project: subject.project)
433 434 435 436 437 438
      end

      it 'does not cache issues from external trackers' do
        issue  = ExternalIssue.new('JIRA-123', subject.project)
        commit = double('commit1', safe_message: "Fixes #{issue.to_reference}")
        allow(subject).to receive(:commits).and_return([commit])
439

440
        expect { subject.cache_merge_request_closes_issues!(subject.author) }.not_to raise_error
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
        expect { subject.cache_merge_request_closes_issues!(subject.author) }.not_to change(subject.merge_requests_closing_issues, :count)
      end

      it 'caches an internal issue' do
        issue  = create(:issue, project: subject.project)
        commit = double('commit1', safe_message: "Fixes #{issue.to_reference}")
        allow(subject).to receive(:commits).and_return([commit])

        expect { subject.cache_merge_request_closes_issues!(subject.author) }
          .to change(subject.merge_requests_closing_issues, :count).by(1)
      end
    end

    context 'when only external issue tracker enabled' do
      before do
        subject.project.has_external_issue_tracker = true
        subject.project.issues_enabled = false
        subject.project.save!
      end

      it 'does not cache issues from external trackers' do
        issue  = ExternalIssue.new('JIRA-123', subject.project)
        commit = double('commit1', safe_message: "Fixes #{issue.to_reference}")
        allow(subject).to receive(:commits).and_return([commit])

        expect { subject.cache_merge_request_closes_issues!(subject.author) }.not_to change(subject.merge_requests_closing_issues, :count)
      end

      it 'does not cache an internal issue' do
        issue  = create(:issue, project: subject.project)
        commit = double('commit1', safe_message: "Fixes #{issue.to_reference}")
        allow(subject).to receive(:commits).and_return([commit])

        expect { subject.cache_merge_request_closes_issues!(subject.author) }
          .not_to change(subject.merge_requests_closing_issues, :count)
      end
477 478 479
    end
  end

480
  describe '#source_branch_sha' do
481
    let(:last_branch_commit) { subject.source_project.repository.commit(Gitlab::Git::BRANCH_REF_PREFIX + subject.source_branch) }
482 483 484 485

    context 'with diffs' do
      subject { create(:merge_request, :with_diffs) }
      it 'returns the sha of the source branch last commit' do
486
        expect(subject.source_branch_sha).to eq(last_branch_commit.sha)
487 488 489
      end
    end

490 491 492
    context 'without diffs' do
      subject { create(:merge_request, :without_diffs) }
      it 'returns the sha of the source branch last commit' do
493
        expect(subject.source_branch_sha).to eq(last_branch_commit.sha)
494
      end
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

      context 'when there is a tag name matching the branch name' do
        let(:tag_name) { subject.source_branch }

        it 'returns the sha of the source branch last commit' do
          subject.source_project.repository.add_tag(subject.author,
                                                    tag_name,
                                                    subject.target_branch_sha,
                                                    'Add a tag')

          expect(subject.source_branch_sha).to eq(last_branch_commit.sha)

          subject.source_project.repository.rm_tag(subject.author, tag_name)
        end
      end
510 511
    end

512 513 514
    context 'when the merge request is being created' do
      subject { build(:merge_request, source_branch: nil, compare_commits: []) }
      it 'returns nil' do
515
        expect(subject.source_branch_sha).to be_nil
516 517
      end
    end
518 519 520 521 522 523

    it 'returns memoized value' do
      subject.source_branch_sha = '2e5d3239642f9161dcbbc4b70a211a68e5e45e2b'

      expect(subject.source_branch_sha).to eq '2e5d3239642f9161dcbbc4b70a211a68e5e45e2b'
    end
524 525
  end

526
  describe '#to_reference' do
527
    let(:project) { build(:project, name: 'sample-project') }
528 529
    let(:merge_request) { build(:merge_request, target_project: project, iid: 1) }

530
    it 'returns a String reference to the object' do
531
      expect(merge_request.to_reference).to eq "!1"
532 533 534
    end

    it 'supports a cross-project reference' do
535
      another_project = build(:project, name: 'another-project', namespace: project.namespace)
536
      expect(merge_request.to_reference(another_project)).to eq "sample-project!1"
537
    end
538 539

    it 'returns a String reference with the full path' do
540
      expect(merge_request.to_reference(full: true)).to eq(project.full_path + '!1')
541
    end
542
  end
543

544
  describe '#raw_diffs' do
545 546 547 548 549 550 551
    let(:merge_request) { build(:merge_request) }
    let(:options) { { paths: ['a/b', 'b/a', 'c/*'] } }

    context 'when there are MR diffs' do
      it 'delegates to the MR diffs' do
        merge_request.merge_request_diff = MergeRequestDiff.new

552
        expect(merge_request.merge_request_diff).to receive(:raw_diffs).with(options)
553

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
        merge_request.raw_diffs(options)
      end
    end

    context 'when there are no MR diffs' do
      it 'delegates to the compare object' do
        merge_request.compare = double(:compare)

        expect(merge_request.compare).to receive(:raw_diffs).with(options)

        merge_request.raw_diffs(options)
      end
    end
  end

569 570 571 572 573 574
  describe '#diffs' do
    let(:merge_request) { build(:merge_request) }
    let(:options) { { paths: ['a/b', 'b/a', 'c/*'] } }

    context 'when there are MR diffs' do
      it 'delegates to the MR diffs' do
575
        merge_request.save
576

577
        expect(merge_request.merge_request_diff).to receive(:raw_diffs).with(hash_including(options)).and_call_original
578

579
        merge_request.diffs(options).diff_files
580 581 582 583
      end
    end

    context 'when there are no MR diffs' do
584
      it 'delegates to the compare object, setting expanded: true' do
585 586
        merge_request.compare = double(:compare)

587
        expect(merge_request.compare).to receive(:diffs).with(options.merge(expanded: true))
588 589 590 591 592 593

        merge_request.diffs(options)
      end
    end
  end

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
  describe '#preload_discussions_diff_highlight' do
    let(:merge_request) { create(:merge_request) }

    context 'with commit diff note' do
      let(:other_merge_request) { create(:merge_request) }

      let!(:diff_note) do
        create(:diff_note_on_commit, project: merge_request.project)
      end

      let!(:other_mr_diff_note) do
        create(:diff_note_on_commit, project: other_merge_request.project)
      end

      it 'preloads diff highlighting' do
        expect_next_instance_of(Gitlab::DiscussionsDiff::FileCollection) do |collection|
          note_diff_file = diff_note.note_diff_file

          expect(collection)
            .to receive(:load_highlight)
            .with([note_diff_file.id]).and_call_original
        end

        merge_request.preload_discussions_diff_highlight
      end
    end

    context 'with merge request diff note' do
      let!(:unresolved_diff_note) do
        create(:diff_note_on_merge_request, project: merge_request.project, noteable: merge_request)
      end

      let!(:resolved_diff_note) do
        create(:diff_note_on_merge_request, :resolved, project: merge_request.project, noteable: merge_request)
      end

      it 'preloads diff highlighting' do
        expect_next_instance_of(Gitlab::DiscussionsDiff::FileCollection) do |collection|
          note_diff_file = unresolved_diff_note.note_diff_file

          expect(collection)
            .to receive(:load_highlight)
            .with([note_diff_file.id])
            .and_call_original
        end

        merge_request.preload_discussions_diff_highlight
      end
    end
  end

645 646 647 648 649 650
  describe '#diff_size' do
    let(:merge_request) do
      build(:merge_request, source_branch: 'expand-collapse-files', target_branch: 'master')
    end

    context 'when there are MR diffs' do
651
      it 'returns the correct count' do
652
        merge_request.save
653 654

        expect(merge_request.diff_size).to eq('105')
655 656
      end

657 658 659 660 661
      it 'returns the correct overflow count' do
        allow(Commit).to receive(:max_diff_options).and_return(max_files: 2)
        merge_request.save

        expect(merge_request.diff_size).to eq('2+')
662 663 664
      end

      it 'does not perform highlighting' do
665 666
        merge_request.save

667 668 669 670 671 672 673
        expect(Gitlab::Diff::Highlight).not_to receive(:new)

        merge_request.diff_size
      end
    end

    context 'when there are no MR diffs' do
674
      def set_compare(merge_request)
675 676 677 678 679 680 681 682 683 684
        merge_request.compare = CompareService.new(
          merge_request.source_project,
          merge_request.source_branch
        ).execute(
          merge_request.target_project,
          merge_request.target_branch
        )
      end

      it 'returns the correct count' do
685 686 687 688 689 690 691 692 693 694
        set_compare(merge_request)

        expect(merge_request.diff_size).to eq('105')
      end

      it 'returns the correct overflow count' do
        allow(Commit).to receive(:max_diff_options).and_return(max_files: 2)
        set_compare(merge_request)

        expect(merge_request.diff_size).to eq('2+')
695 696 697
      end

      it 'does not perform highlighting' do
698 699
        set_compare(merge_request)

700 701 702 703 704 705 706
        expect(Gitlab::Diff::Highlight).not_to receive(:new)

        merge_request.diff_size
      end
    end
  end

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  describe '#modified_paths' do
    let(:paths) { double(:paths) }
    subject(:merge_request) { build(:merge_request) }

    before do
      expect(diff).to receive(:modified_paths).and_return(paths)
    end

    context 'when past_merge_request_diff is specified' do
      let(:another_diff) { double(:merge_request_diff) }
      let(:diff) { another_diff }

      it 'returns affected file paths from specified past_merge_request_diff' do
        expect(merge_request.modified_paths(past_merge_request_diff: another_diff)).to eq(paths)
      end
    end

    context 'when compare is present' do
      let(:compare) { double(:compare) }
      let(:diff) { compare }

      it 'returns affected file paths from compare' do
        merge_request.compare = compare

        expect(merge_request.modified_paths).to eq(paths)
      end
    end

    context 'when no arguments provided' do
      let(:diff) { merge_request.merge_request_diff }
      subject(:merge_request) { create(:merge_request, source_branch: 'feature', target_branch: 'master') }

      it 'returns affected file paths for merge_request_diff' do
        expect(merge_request.modified_paths).to eq(paths)
      end
    end
  end

745
  describe "#related_notes" do
746
    let!(:merge_request) { create(:merge_request) }
747 748

    before do
749
      allow(merge_request).to receive(:commits) { [merge_request.source_project.repository.commit] }
750 751
      create(:note_on_commit, commit_id: merge_request.commits.first.id,
                              project: merge_request.project)
752
      create(:note, noteable: merge_request, project: merge_request.project)
753 754
    end

755
    it "includes notes for commits" do
756
      expect(merge_request.commits).not_to be_empty
757
      expect(merge_request.related_notes.count).to eq(2)
758
    end
759

760
    it "includes notes for commits from target project as well" do
761 762 763
      create(:note_on_commit, commit_id: merge_request.commits.first.id,
                              project: merge_request.target_project)

764
      expect(merge_request.commits).not_to be_empty
765
      expect(merge_request.related_notes.count).to eq(3)
766
    end
767
  end
768

769 770
  describe '#for_fork?' do
    it 'returns true if the merge request is for a fork' do
771 772
      subject.source_project = build_stubbed(:project, namespace: create(:group))
      subject.target_project = build_stubbed(:project, namespace: create(:group))
773

774
      expect(subject.for_fork?).to be_truthy
775
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
776

777
    it 'returns false if is not for a fork' do
778
      expect(subject.for_fork?).to be_falsey
779 780 781
    end
  end

782
  describe '#closes_issues' do
783 784
    let(:issue0) { create :issue, project: subject.project }
    let(:issue1) { create :issue, project: subject.project }
785 786 787 788

    let(:commit0) { double('commit0', safe_message: "Fixes #{issue0.to_reference}") }
    let(:commit1) { double('commit1', safe_message: "Fixes #{issue0.to_reference}") }
    let(:commit2) { double('commit2', safe_message: "Fixes #{issue1.to_reference}") }
789 790

    before do
791
      subject.project.add_developer(subject.author)
792
      allow(subject).to receive(:commits).and_return([commit0, commit1, commit2])
793 794
    end

795
    it 'accesses the set of issues that will be closed on acceptance' do
796 797
      allow(subject.project).to receive(:default_branch)
        .and_return(subject.target_branch)
798

799
      closed = subject.closes_issues
800

801 802
      expect(closed).to include(issue0, issue1)
    end
803

804 805 806
    it 'only lists issues as to be closed if it targets the default branch' do
      allow(subject.project).to receive(:default_branch).and_return('master')
      subject.target_branch = 'something-else'
807

808
      expect(subject.closes_issues).to be_empty
809
    end
810
  end
811

812
  describe '#issues_mentioned_but_not_closing' do
813 814 815 816
    let(:closing_issue) { create :issue, project: subject.project }
    let(:mentioned_issue) { create :issue, project: subject.project }

    let(:commit) { double('commit', safe_message: "Fixes #{closing_issue.to_reference}") }
817

818
    it 'detects issues mentioned in description but not closed' do
819
      subject.project.add_developer(subject.author)
820
      subject.description = "Is related to #{mentioned_issue.to_reference} and #{closing_issue.to_reference}"
821

822
      allow(subject).to receive(:commits).and_return([commit])
823 824
      allow(subject.project).to receive(:default_branch)
        .and_return(subject.target_branch)
825
      subject.cache_merge_request_closes_issues!
826

827
      expect(subject.issues_mentioned_but_not_closing(subject.author)).to match_array([mentioned_issue])
828
    end
829 830 831

    context 'when the project has an external issue tracker' do
      before do
832
        subject.project.add_developer(subject.author)
833 834 835 836 837 838 839 840 841 842
        commit = double(:commit, safe_message: 'Fixes TEST-3')

        create(:jira_service, project: subject.project)

        allow(subject).to receive(:commits).and_return([commit])
        allow(subject).to receive(:description).and_return('Is related to TEST-2 and TEST-3')
        allow(subject.project).to receive(:default_branch).and_return(subject.target_branch)
      end

      it 'detects issues mentioned in description but not closed' do
843 844
        subject.cache_merge_request_closes_issues!

845 846 847
        expect(subject.issues_mentioned_but_not_closing(subject.author).map(&:to_s)).to match_array(['TEST-2'])
      end
    end
848 849
  end

850
  describe "#work_in_progress?" do
851 852 853
    ['WIP ', 'WIP:', 'WIP: ', '[WIP]', '[WIP] ', ' [WIP] WIP [WIP] WIP: WIP '].each do |wip_prefix|
      it "detects the '#{wip_prefix}' prefix" do
        subject.title = "#{wip_prefix}#{subject.title}"
854
        expect(subject.work_in_progress?).to eq true
855
      end
856 857
    end

858 859
    it "doesn't detect WIP for words starting with WIP" do
      subject.title = "Wipwap #{subject.title}"
860
      expect(subject.work_in_progress?).to eq false
861 862
    end

863 864
    it "doesn't detect WIP for words containing with WIP" do
      subject.title = "WupWipwap #{subject.title}"
865
      expect(subject.work_in_progress?).to eq false
866 867
    end

868
    it "doesn't detect WIP by default" do
869
      expect(subject.work_in_progress?).to eq false
870 871 872
    end
  end

Thomas Balthazar's avatar
Thomas Balthazar committed
873
  describe "#wipless_title" do
874
    ['WIP ', 'WIP:', 'WIP: ', '[WIP]', '[WIP] ', '[WIP] WIP [WIP] WIP: WIP '].each do |wip_prefix|
Thomas Balthazar's avatar
Thomas Balthazar committed
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
      it "removes the '#{wip_prefix}' prefix" do
        wipless_title = subject.title
        subject.title = "#{wip_prefix}#{subject.title}"

        expect(subject.wipless_title).to eq wipless_title
      end

      it "is satisfies the #work_in_progress? method" do
        subject.title = "#{wip_prefix}#{subject.title}"
        subject.title = subject.wipless_title

        expect(subject.work_in_progress?).to eq false
      end
    end
  end

  describe "#wip_title" do
    it "adds the WIP: prefix to the title" do
      wip_title = "WIP: #{subject.title}"

      expect(subject.wip_title).to eq wip_title
896
    end
Thomas Balthazar's avatar
Thomas Balthazar committed
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

    it "does not add the WIP: prefix multiple times" do
      wip_title = "WIP: #{subject.title}"
      subject.title = subject.wip_title
      subject.title = subject.wip_title

      expect(subject.wip_title).to eq wip_title
    end

    it "is satisfies the #work_in_progress? method" do
      subject.title = subject.wip_title

      expect(subject.work_in_progress?).to eq true
    end
  end

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
913
  describe '#can_remove_source_branch?' do
914 915
    set(:user) { create(:user) }
    set(:merge_request) { create(:merge_request, :simple) }
916

917
    subject { merge_request }
918

919
    before do
920
      subject.source_project.add_maintainer(user)
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
921
    end
922

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
923
    it "can't be removed when its a protected branch" do
924
      allow(ProtectedBranch).to receive(:protected?).and_return(true)
925

926 927 928
      expect(subject.can_remove_source_branch?(user)).to be_falsey
    end

929
    it "can't remove a root ref" do
930
      subject.update(source_branch: 'master', target_branch: 'feature')
931 932 933 934

      expect(subject.can_remove_source_branch?(user)).to be_falsey
    end

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
935
    it "is unable to remove the source branch for a project the user cannot push to" do
936 937
      user2 = create(:user)

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
938 939 940
      expect(subject.can_remove_source_branch?(user2)).to be_falsey
    end

941
    it "can be removed if the last commit is the head of the source branch" do
942
      allow(subject).to receive(:source_branch_head).and_return(subject.diff_head_commit)
943

Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
944
      expect(subject.can_remove_source_branch?(user)).to be_truthy
945
    end
946 947

    it "cannot be removed if the last commit is not also the head of the source branch" do
948
      subject.clear_memoized_shas
949 950
      subject.source_branch = "lfs"

951 952
      expect(subject.can_remove_source_branch?(user)).to be_falsey
    end
953 954
  end

955
  describe '#default_merge_commit_message' do
956 957 958
    it 'includes merge information as the title' do
      request = build(:merge_request, source_branch: 'source', target_branch: 'target')

959
      expect(request.default_merge_commit_message)
960 961 962 963 964 965
        .to match("Merge branch 'source' into 'target'\n\n")
    end

    it 'includes its title in the body' do
      request = build(:merge_request, title: 'Remove all technical debt')

966
      expect(request.default_merge_commit_message)
967 968 969
        .to match("Remove all technical debt\n\n")
    end

970
    it 'includes its closed issues in the body' do
971
      issue = create(:issue, project: subject.project)
972

973
      subject.project.add_developer(subject.author)
974
      subject.description = "This issue Closes #{issue.to_reference}"
975 976
      allow(subject.project).to receive(:default_branch).and_return(subject.target_branch)
      subject.cache_merge_request_closes_issues!
977

978
      expect(subject.default_merge_commit_message)
979
        .to match("Closes #{issue.to_reference}")
980 981 982 983 984
    end

    it 'includes its reference in the body' do
      request = build_stubbed(:merge_request)

985
      expect(request.default_merge_commit_message)
986
        .to match("See merge request #{request.to_reference(full: true)}")
987 988 989 990 991
    end

    it 'excludes multiple linebreak runs when description is blank' do
      request = build(:merge_request, title: 'Title', description: nil)

992
      expect(request.default_merge_commit_message).not_to match("Title\n\n\n\n")
993
    end
994 995 996 997

    it 'includes its description in the body' do
      request = build(:merge_request, description: 'By removing all code')

998
      expect(request.default_merge_commit_message(include_description: true))
999 1000 1001 1002 1003 1004
        .to match("By removing all code\n\n")
    end

    it 'does not includes its description in the body' do
      request = build(:merge_request, description: 'By removing all code')

1005
      expect(request.default_merge_commit_message)
1006 1007
        .not_to match("By removing all code\n\n")
    end
1008 1009
  end

1010
  describe "#reset_merge_when_pipeline_succeeds" do
1011
    let(:merge_if_green) do
1012
      create :merge_request, merge_when_pipeline_succeeds: true, merge_user: create(:user),
1013 1014
                             merge_params: { "should_remove_source_branch" => "1", "commit_message" => "msg" }
    end
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
1015

1016
    it "sets the item to false" do
1017
      merge_if_green.reset_merge_when_pipeline_succeeds
1018 1019
      merge_if_green.reload

1020
      expect(merge_if_green.merge_when_pipeline_succeeds).to be_falsey
1021 1022
      expect(merge_if_green.merge_params["should_remove_source_branch"]).to be_nil
      expect(merge_if_green.merge_params["commit_message"]).to be_nil
1023 1024 1025
    end
  end

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  describe '#committers' do
    it 'returns all the committers of every commit in the merge request' do
      users = subject.commits.map(&:committer_email).uniq.map do |email|
        create(:user, email: email)
      end

      expect(subject.committers).to match_array(users)
    end

    it 'returns an empty array if no committer is associated with a user' do
      expect(subject.committers).to be_empty
    end
  end

  describe '#authors' do
    it 'returns a list with all the committers in the merge request and author' do
      users = subject.commits.map(&:committer_email).uniq.map do |email|
        create(:user, email: email)
      end

      expect(subject.authors).to match_array([subject.author, *users])
    end

    it 'returns only the author if no committer is associated with a user' do
      expect(subject.authors).to contain_exactly(subject.author)
    end
  end

1054
  describe '#hook_attrs' do
1055 1056 1057 1058 1059 1060 1061 1062
    it 'delegates to Gitlab::HookData::MergeRequestBuilder#build' do
      builder = double

      expect(Gitlab::HookData::MergeRequestBuilder)
        .to receive(:new).with(subject).and_return(builder)
      expect(builder).to receive(:build)

      subject.hook_attrs
1063
    end
1064 1065 1066
  end

  describe '#diverged_commits_count' do
1067
    let(:project) { create(:project, :repository) }
1068
    let(:forked_project) { fork_project(project, nil, repository: true) }
1069

1070
    context 'when the target branch does not exist anymore' do
1071 1072 1073 1074
      subject { create(:merge_request, source_project: project, target_project: project) }

      before do
        project.repository.raw_repository.delete_branch(subject.target_branch)
1075
        subject.clear_memoized_shas
1076
      end
1077 1078

      it 'does not crash' do
1079
        expect { subject.diverged_commits_count }.not_to raise_error
1080 1081 1082 1083 1084 1085 1086
      end

      it 'returns 0' do
        expect(subject.diverged_commits_count).to eq(0)
      end
    end

1087 1088 1089 1090
    context 'diverged on same repository' do
      subject(:merge_request_with_divergence) { create(:merge_request, :diverged, source_project: project, target_project: project) }

      it 'counts commits that are on target branch but not on source branch' do
1091
        expect(subject.diverged_commits_count).to eq(29)
1092 1093 1094 1095
      end
    end

    context 'diverged on fork' do
1096
      subject(:merge_request_fork_with_divergence) { create(:merge_request, :diverged, source_project: forked_project, target_project: project) }
1097 1098

      it 'counts commits that are on target branch but not on source branch' do
1099
        expect(subject.diverged_commits_count).to eq(29)
1100 1101 1102 1103
      end
    end

    context 'rebased on fork' do
1104
      subject(:merge_request_rebased) { create(:merge_request, :rebased, source_project: forked_project, target_project: project) }
1105 1106 1107 1108 1109 1110 1111

      it 'counts commits that are on target branch but not on source branch' do
        expect(subject.diverged_commits_count).to eq(0)
      end
    end

    describe 'caching' do
1112
      before do
1113 1114 1115 1116
        allow(Rails).to receive(:cache).and_return(ActiveSupport::Cache::MemoryStore.new)
      end

      it 'caches the output' do
1117 1118 1119
        expect(subject).to receive(:compute_diverged_commits_count)
          .once
          .and_return(2)
1120 1121 1122 1123 1124 1125

        subject.diverged_commits_count
        subject.diverged_commits_count
      end

      it 'invalidates the cache when the source sha changes' do
1126 1127 1128
        expect(subject).to receive(:compute_diverged_commits_count)
          .twice
          .and_return(2)
1129 1130

        subject.diverged_commits_count
1131
        allow(subject).to receive(:source_branch_sha).and_return('123abc')
1132 1133 1134 1135
        subject.diverged_commits_count
      end

      it 'invalidates the cache when the target sha changes' do
1136 1137 1138
        expect(subject).to receive(:compute_diverged_commits_count)
          .twice
          .and_return(2)
1139 1140

        subject.diverged_commits_count
1141
        allow(subject).to receive(:target_branch_sha).and_return('123abc')
1142 1143 1144
        subject.diverged_commits_count
      end
    end
1145 1146
  end

1147
  it_behaves_like 'an editable mentionable' do
1148
    subject { create(:merge_request, :simple) }
1149

1150
    let(:backref_text) { "merge request #{subject.to_reference}" }
1151
    let(:set_mentionable_text) { ->(txt) { subject.description = txt } }
1152
  end
Vinnie Okada's avatar
Vinnie Okada committed
1153 1154

  it_behaves_like 'a Taskable' do
1155
    subject { create :merge_request, :simple }
Vinnie Okada's avatar
Vinnie Okada committed
1156
  end
1157

1158
  describe '#commit_shas' do
1159
    before do
1160
      allow(subject.merge_request_diff).to receive(:commit_shas)
1161
        .and_return(['sha1'])
1162 1163
    end

1164
    it 'delegates to merge request diff' do
1165
      expect(subject.commit_shas).to eq ['sha1']
1166 1167 1168
    end
  end

1169
  context 'head pipeline' do
1170 1171 1172
    before do
      allow(subject).to receive(:diff_head_sha).and_return('lastsha')
    end
1173

1174 1175 1176
    describe '#head_pipeline' do
      it 'returns nil for MR without head_pipeline_id' do
        subject.update_attribute(:head_pipeline_id, nil)
1177

1178 1179
        expect(subject.head_pipeline).to be_nil
      end
1180 1181 1182 1183 1184 1185 1186 1187

      context 'when the source project does not exist' do
        it 'returns nil' do
          allow(subject).to receive(:source_project).and_return(nil)

          expect(subject.head_pipeline).to be_nil
        end
      end
1188 1189
    end

1190
    describe '#actual_head_pipeline' do
1191 1192 1193
      it 'returns nil for MR with old pipeline' do
        pipeline = create(:ci_empty_pipeline, sha: 'notlatestsha')
        subject.update_attribute(:head_pipeline_id, pipeline.id)
1194

1195
        expect(subject.actual_head_pipeline).to be_nil
1196
      end
1197

1198 1199 1200
      it 'returns the pipeline for MR with recent pipeline' do
        pipeline = create(:ci_empty_pipeline, sha: 'lastsha')
        subject.update_attribute(:head_pipeline_id, pipeline.id)
1201

1202 1203
        expect(subject.actual_head_pipeline).to eq(subject.head_pipeline)
        expect(subject.actual_head_pipeline).to eq(pipeline)
1204
      end
1205 1206 1207 1208 1209 1210

      it 'returns nil when source project does not exist' do
        allow(subject).to receive(:source_project).and_return(nil)

        expect(subject.actual_head_pipeline).to be_nil
      end
1211 1212
    end
  end
Yorick Peterse's avatar
Yorick Peterse committed
1213

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
  describe '#merge_pipeline' do
    it 'returns nil when not merged' do
      expect(subject.merge_pipeline).to be_nil
    end

    context 'when the MR is merged' do
      let(:sha)      { subject.target_project.commit.id }
      let(:pipeline) { create(:ci_empty_pipeline, sha: sha, ref: subject.target_branch, project: subject.target_project) }

      before do
        subject.mark_as_merged!
        subject.update_attribute(:merge_commit_sha, pipeline.sha)
      end

      it 'returns the post-merge pipeline' do
        expect(subject.merge_pipeline).to eq(pipeline)
      end
    end
  end

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
  describe '#has_ci?' do
    let(:merge_request) { build_stubbed(:merge_request) }

    context 'has ci' do
      it 'returns true if MR has head_pipeline_id and commits' do
        allow(merge_request).to receive_message_chain(:source_project, :ci_service) { nil }
        allow(merge_request).to receive(:head_pipeline_id) { double }
        allow(merge_request).to receive(:has_no_commits?) { false }

        expect(merge_request.has_ci?).to be(true)
      end

      it 'returns true if MR has any pipeline and commits' do
        allow(merge_request).to receive_message_chain(:source_project, :ci_service) { nil }
        allow(merge_request).to receive(:head_pipeline_id) { nil }
        allow(merge_request).to receive(:has_no_commits?) { false }
        allow(merge_request).to receive(:all_pipelines) { [double] }

        expect(merge_request.has_ci?).to be(true)
      end

      it 'returns true if MR has CI service and commits' do
        allow(merge_request).to receive_message_chain(:source_project, :ci_service) { double }
        allow(merge_request).to receive(:head_pipeline_id) { nil }
        allow(merge_request).to receive(:has_no_commits?) { false }
        allow(merge_request).to receive(:all_pipelines) { [] }

        expect(merge_request.has_ci?).to be(true)
      end
    end

    context 'has no ci' do
      it 'returns false if MR has no CI service nor pipeline, and no commits' do
        allow(merge_request).to receive_message_chain(:source_project, :ci_service) { nil }
        allow(merge_request).to receive(:head_pipeline_id) { nil }
        allow(merge_request).to receive(:all_pipelines) { [] }
        allow(merge_request).to receive(:has_no_commits?) { true }

        expect(merge_request.has_ci?).to be(false)
      end
    end
  end