project_spec.rb 121 KB
Newer Older
gitlabhq's avatar
gitlabhq committed
1 2
require 'spec_helper'

3
describe Project do
4
  include ProjectForksHelper
5
  include GitHelpers
6

7
  describe 'associations' do
8 9 10 11
    it { is_expected.to belong_to(:group) }
    it { is_expected.to belong_to(:namespace) }
    it { is_expected.to belong_to(:creator).class_name('User') }
    it { is_expected.to have_many(:users) }
ubudzisz's avatar
ubudzisz committed
12
    it { is_expected.to have_many(:services) }
13 14 15 16 17
    it { is_expected.to have_many(:events) }
    it { is_expected.to have_many(:merge_requests) }
    it { is_expected.to have_many(:issues) }
    it { is_expected.to have_many(:milestones) }
    it { is_expected.to have_many(:project_members).dependent(:delete_all) }
18
    it { is_expected.to have_many(:users).through(:project_members) }
19 20 21 22
    it { is_expected.to have_many(:requesters).dependent(:delete_all) }
    it { is_expected.to have_many(:notes) }
    it { is_expected.to have_many(:snippets).class_name('ProjectSnippet') }
    it { is_expected.to have_many(:deploy_keys_projects) }
23
    it { is_expected.to have_many(:deploy_keys) }
24 25 26 27 28
    it { is_expected.to have_many(:hooks) }
    it { is_expected.to have_many(:protected_branches) }
    it { is_expected.to have_one(:slack_service) }
    it { is_expected.to have_one(:microsoft_teams_service) }
    it { is_expected.to have_one(:mattermost_service) }
29
    it { is_expected.to have_one(:hangouts_chat_service) }
30
    it { is_expected.to have_one(:packagist_service) }
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
    it { is_expected.to have_one(:pushover_service) }
    it { is_expected.to have_one(:asana_service) }
    it { is_expected.to have_many(:boards) }
    it { is_expected.to have_one(:campfire_service) }
    it { is_expected.to have_one(:drone_ci_service) }
    it { is_expected.to have_one(:emails_on_push_service) }
    it { is_expected.to have_one(:pipelines_email_service) }
    it { is_expected.to have_one(:irker_service) }
    it { is_expected.to have_one(:pivotaltracker_service) }
    it { is_expected.to have_one(:hipchat_service) }
    it { is_expected.to have_one(:flowdock_service) }
    it { is_expected.to have_one(:assembla_service) }
    it { is_expected.to have_one(:slack_slash_commands_service) }
    it { is_expected.to have_one(:mattermost_slash_commands_service) }
    it { is_expected.to have_one(:buildkite_service) }
    it { is_expected.to have_one(:bamboo_service) }
    it { is_expected.to have_one(:teamcity_service) }
    it { is_expected.to have_one(:jira_service) }
    it { is_expected.to have_one(:redmine_service) }
    it { is_expected.to have_one(:custom_issue_tracker_service) }
    it { is_expected.to have_one(:bugzilla_service) }
    it { is_expected.to have_one(:gitlab_issue_tracker_service) }
    it { is_expected.to have_one(:external_wiki_service) }
    it { is_expected.to have_one(:project_feature) }
    it { is_expected.to have_one(:statistics).class_name('ProjectStatistics') }
    it { is_expected.to have_one(:import_data).class_name('ProjectImportData') }
ubudzisz's avatar
ubudzisz committed
57
    it { is_expected.to have_one(:last_event).class_name('Event') }
58
    it { is_expected.to have_one(:forked_from_project).through(:fork_network_member) }
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
59
    it { is_expected.to have_one(:auto_devops).class_name('ProjectAutoDevops') }
Kamil Trzcinski's avatar
Kamil Trzcinski committed
60
    it { is_expected.to have_many(:commit_statuses) }
61
    it { is_expected.to have_many(:pipelines) }
62
    it { is_expected.to have_many(:builds) }
63
    it { is_expected.to have_many(:build_trace_section_names)}
64 65 66 67
    it { is_expected.to have_many(:runner_projects) }
    it { is_expected.to have_many(:runners) }
    it { is_expected.to have_many(:variables) }
    it { is_expected.to have_many(:triggers) }
Kamil Trzcinski's avatar
Kamil Trzcinski committed
68
    it { is_expected.to have_many(:pages_domains) }
69 70
    it { is_expected.to have_many(:labels).class_name('ProjectLabel') }
    it { is_expected.to have_many(:users_star_projects) }
71
    it { is_expected.to have_many(:repository_languages) }
72 73 74 75 76 77 78
    it { is_expected.to have_many(:environments) }
    it { is_expected.to have_many(:deployments) }
    it { is_expected.to have_many(:todos) }
    it { is_expected.to have_many(:releases) }
    it { is_expected.to have_many(:lfs_objects_projects) }
    it { is_expected.to have_many(:project_group_links) }
    it { is_expected.to have_many(:notification_settings).dependent(:delete_all) }
79 80
    it { is_expected.to have_many(:forked_to_members).class_name('ForkNetworkMember') }
    it { is_expected.to have_many(:forks).through(:forked_to_members) }
Jan Provaznik's avatar
Jan Provaznik committed
81
    it { is_expected.to have_many(:uploads) }
82
    it { is_expected.to have_many(:pipeline_schedules) }
83
    it { is_expected.to have_many(:members_and_requesters) }
84
    it { is_expected.to have_many(:clusters) }
85
    it { is_expected.to have_many(:custom_attributes).class_name('ProjectCustomAttribute') }
86
    it { is_expected.to have_many(:project_badges).class_name('ProjectBadge') }
87
    it { is_expected.to have_many(:lfs_file_locks) }
88 89
    it { is_expected.to have_many(:project_deploy_tokens) }
    it { is_expected.to have_many(:deploy_tokens).through(:project_deploy_tokens) }
90

91 92 93 94
    it 'has an inverse relationship with merge requests' do
      expect(described_class.reflect_on_association(:merge_requests).has_inverse?).to eq(:target_project)
    end

95 96
    context 'after initialized' do
      it "has a project_feature" do
97
        expect(described_class.new.project_feature).to be_present
98 99 100
      end
    end

101 102 103 104 105 106 107 108 109
    context 'when creating a new project' do
      it 'automatically creates a CI/CD settings row' do
        project = create(:project)

        expect(project.ci_cd_settings).to be_an_instance_of(ProjectCiCdSetting)
        expect(project.ci_cd_settings).to be_persisted
      end
    end

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    context 'Site Statistics' do
      context 'when creating a new project' do
        it 'tracks project in SiteStatistic' do
          expect { create(:project) }.to change { SiteStatistic.fetch.repositories_count }.by(1)
        end
      end

      context 'when deleting a project' do
        it 'untracks project in SiteStatistic' do
          project = create(:project)

          expect { project.destroy }.to change { SiteStatistic.fetch.repositories_count }.by(-1)
        end
      end
    end

126 127 128 129
    context 'updating cd_cd_settings' do
      it 'does not raise an error' do
        project = create(:project)

James Lopez's avatar
James Lopez committed
130
        expect { project.update(ci_cd_settings: nil) }.not_to raise_exception
131 132 133
      end
    end

134
    describe '#members & #requesters' do
135
      let(:project) { create(:project, :public, :access_requestable) }
136 137 138 139
      let(:requester) { create(:user) }
      let(:developer) { create(:user) }
      before do
        project.request_access(requester)
140
        project.add_developer(developer)
141 142
      end

143 144
      it_behaves_like 'members and requesters associations' do
        let(:namespace) { project }
145 146
      end
    end
147 148 149 150 151

    describe '#boards' do
      it 'raises an error when attempting to add more than one board to the project' do
        subject.boards.build

152
        expect { subject.boards.build }.to raise_error(Project::BoardLimitExceeded, 'Number of permitted boards exceeded')
153 154 155
        expect(subject.boards.size).to eq 1
      end
    end
gitlabhq's avatar
gitlabhq committed
156 157
  end

158 159 160 161 162 163 164 165
  describe 'modules' do
    subject { described_class }

    it { is_expected.to include_module(Gitlab::ConfigHelper) }
    it { is_expected.to include_module(Gitlab::ShellAdapter) }
    it { is_expected.to include_module(Gitlab::VisibilityLevel) }
    it { is_expected.to include_module(Referable) }
    it { is_expected.to include_module(Sortable) }
166 167
  end

168
  describe 'validation' do
169
    let!(:project) { create(:project) }
170

171 172
    it { is_expected.to validate_presence_of(:name) }
    it { is_expected.to validate_uniqueness_of(:name).scoped_to(:namespace_id) }
173
    it { is_expected.to validate_length_of(:name).is_at_most(255) }
174
    it { is_expected.to validate_presence_of(:path) }
175 176
    it { is_expected.to validate_length_of(:path).is_at_most(255) }
    it { is_expected.to validate_length_of(:description).is_at_most(2000) }
177 178 179
    it { is_expected.to validate_length_of(:ci_config_path).is_at_most(255) }
    it { is_expected.to allow_value('').for(:ci_config_path) }
    it { is_expected.not_to allow_value('test/../foo').for(:ci_config_path) }
180
    it { is_expected.not_to allow_value('/test/foo').for(:ci_config_path) }
181 182
    it { is_expected.to validate_presence_of(:creator) }
    it { is_expected.to validate_presence_of(:namespace) }
183
    it { is_expected.to validate_presence_of(:repository_storage) }
184

185 186 187 188 189 190 191 192
    it 'validates build timeout constraints' do
      is_expected.to validate_numericality_of(:build_timeout)
        .only_integer
        .is_greater_than_or_equal_to(10.minutes)
        .is_less_than(1.month)
        .with_message('needs to be beetween 10 minutes and 1 month')
    end

193
    it 'does not allow new projects beyond user limits' do
194
      project2 = build(:project)
195 196
      allow(project2).to receive(:creator).and_return(double(can_create_project?: false, projects_limit: 0).as_null_object)
      expect(project2).not_to be_valid
Phil Hughes's avatar
Phil Hughes committed
197
      expect(project2.errors[:limit_reached].first).to match(/Personal project creation is not allowed/)
198
    end
199 200 201

    describe 'wiki path conflict' do
      context "when the new path has been used by the wiki of other Project" do
202
        it 'has an error on the name attribute' do
203
          new_project = build_stubbed(:project, namespace_id: project.namespace_id, path: "#{project.path}.wiki")
204 205 206 207 208 209 210

          expect(new_project).not_to be_valid
          expect(new_project.errors[:name].first).to eq('has already been taken')
        end
      end

      context "when the new wiki path has been used by the path of other Project" do
211
        it 'has an error on the name attribute' do
212 213
          project_with_wiki_suffix = create(:project, path: 'foo.wiki')
          new_project = build_stubbed(:project, namespace_id: project_with_wiki_suffix.namespace_id, path: 'foo')
214 215 216 217 218 219

          expect(new_project).not_to be_valid
          expect(new_project.errors[:name].first).to eq('has already been taken')
        end
      end
    end
220

221
    context 'repository storages inclusion' do
222
      let(:project2) { build(:project, repository_storage: 'missing') }
223 224

      before do
225
        storages = { 'custom' => { 'path' => 'tmp/tests/custom_repositories' } }
226 227 228
        allow(Gitlab.config.repositories).to receive(:storages).and_return(storages)
      end

229
      it "does not allow repository storages that don't match a label in the configuration" do
230 231 232 233
        expect(project2).not_to be_valid
        expect(project2.errors[:repository_storage].first).to match(/is not included in the list/)
      end
    end
234

235
    it 'does not allow an invalid URI as import_url' do
236
      project = build(:project, import_url: 'invalid://')
James Lopez's avatar
James Lopez committed
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251
      expect(project).not_to be_valid
    end

    it 'does allow a SSH URI as import_url for persisted projects' do
      project = create(:project)
      project.import_url = 'ssh://test@gitlab.com/project.git'

      expect(project).to be_valid
    end

    it 'does not allow a SSH URI as import_url for new projects' do
      project = build(:project, import_url: 'ssh://test@gitlab.com/project.git')

      expect(project).not_to be_valid
James Lopez's avatar
James Lopez committed
252 253
    end

254
    it 'does allow a valid URI as import_url' do
255
      project = build(:project, import_url: 'http://gitlab.com/project.git')
James Lopez's avatar
James Lopez committed
256

257
      expect(project).to be_valid
258
    end
259

260
    it 'allows an empty URI' do
261
      project = build(:project, import_url: '')
262

263
      expect(project).to be_valid
264 265 266
    end

    it 'does not produce import data on an empty URI' do
267
      project = build(:project, import_url: '')
268

269
      expect(project.import_data).to be_nil
270 271 272
    end

    it 'does not produce import data on an invalid URI' do
273
      project = build(:project, import_url: 'test://')
274

275
      expect(project.import_data).to be_nil
276
    end
277

278
    it "does not allow import_url pointing to localhost" do
279 280 281 282 283 284 285 286
      project = build(:project, import_url: 'http://localhost:9000/t.git')

      expect(project).to be_invalid
      expect(project.errors[:import_url].first).to include('Requests to localhost are not allowed')
    end

    it "does not allow import_url with invalid ports for new projects" do
      project = build(:project, import_url: 'http://github.com:25/t.git')
287

288 289
      expect(project).to be_invalid
      expect(project.errors[:import_url].first).to include('Only allowed ports are 80, 443')
290 291
    end

292 293 294
    it "does not allow import_url with invalid ports for persisted projects" do
      project = create(:project)
      project.import_url = 'http://github.com:25/t.git'
295

296 297
      expect(project).to be_invalid
      expect(project.errors[:import_url].first).to include('Only allowed ports are 22, 80, 443')
298 299
    end

300
    it "does not allow import_url with invalid user" do
301
      project = build(:project, import_url: 'http://$user:password@github.com/t.git')
302

303 304
      expect(project).to be_invalid
      expect(project.errors[:import_url].first).to include('Username needs to start with an alphanumeric character')
305 306
    end

307 308
    describe 'project pending deletion' do
      let!(:project_pending_deletion) do
309
        create(:project,
310 311 312
               pending_delete: true)
      end
      let(:new_project) do
313
        build(:project,
314 315 316 317 318 319 320 321 322 323 324 325
              name: project_pending_deletion.name,
              namespace: project_pending_deletion.namespace)
      end

      before do
        new_project.validate
      end

      it 'contains errors related to the project being deleted' do
        expect(new_project.errors.full_messages.first).to eq('The project is still being deleted. Please try again later.')
      end
    end
326 327 328

    describe 'path validation' do
      it 'allows paths reserved on the root namespace' do
329
        project = build(:project, path: 'api')
330 331 332 333 334

        expect(project).to be_valid
      end

      it 'rejects paths reserved on another level' do
335
        project = build(:project, path: 'tree')
336 337 338

        expect(project).not_to be_valid
      end
339 340 341

      it 'rejects nested paths' do
        parent = create(:group, :nested, path: 'environments')
342
        project = build(:project, path: 'folders', namespace: parent)
343 344 345

        expect(project).not_to be_valid
      end
346 347 348

      it 'allows a reserved group name' do
        parent = create(:group)
349
        project = build(:project, path: 'avatar', namespace: parent)
350 351 352

        expect(project).to be_valid
      end
353 354 355 356 357 358

      it 'allows a path ending in a period' do
        project = build(:project, path: 'foo.')

        expect(project).to be_valid
      end
359
    end
gitlabhq's avatar
gitlabhq committed
360
  end
361

362
  describe 'project token' do
363
    it 'sets an random token if none provided' do
364
      project = FactoryBot.create(:project, runners_token: '')
Kamil Trzcinski's avatar
Kamil Trzcinski committed
365
      expect(project.runners_token).not_to eq('')
366 367
    end

ubudzisz's avatar
ubudzisz committed
368
    it 'does not set an random token if one provided' do
369
      project = FactoryBot.create(:project, runners_token: 'my-token')
Kamil Trzcinski's avatar
Kamil Trzcinski committed
370
      expect(project.runners_token).to eq('my-token')
371 372
    end
  end
gitlabhq's avatar
gitlabhq committed
373

374
  describe 'Respond to' do
375 376 377 378 379
    it { is_expected.to respond_to(:url_to_repo) }
    it { is_expected.to respond_to(:repo_exists?) }
    it { is_expected.to respond_to(:execute_hooks) }
    it { is_expected.to respond_to(:owner) }
    it { is_expected.to respond_to(:path_with_namespace) }
380
    it { is_expected.to respond_to(:full_path) }
gitlabhq's avatar
gitlabhq committed
381 382
  end

383
  describe 'delegation' do
384
    [:add_guest, :add_reporter, :add_developer, :add_maintainer, :add_user, :add_users].each do |method|
385 386 387 388 389
      it { is_expected.to delegate_method(method).to(:team) }
    end

    it { is_expected.to delegate_method(:members).to(:team).with_prefix(true) }
    it { is_expected.to delegate_method(:name).to(:owner).with_prefix(true).with_arguments(allow_nil: true) }
390 391
  end

392 393 394 395 396 397 398 399 400
  describe '#to_reference_with_postfix' do
    it 'returns the full path with reference_postfix' do
      namespace = create(:namespace, path: 'sample-namespace')
      project = create(:project, path: 'sample-project', namespace: namespace)

      expect(project.to_reference_with_postfix).to eq 'sample-namespace/sample-project>'
    end
  end

401
  describe '#to_reference' do
402
    let(:owner)     { create(:user, name: 'Gitlab') }
403
    let(:namespace) { create(:namespace, path: 'sample-namespace', owner: owner) }
404
    let(:project)   { create(:project, path: 'sample-project', namespace: namespace) }
405
    let(:group)     { create(:group, name: 'Group', path: 'sample-group') }
406

407
    context 'when nil argument' do
408 409 410 411 412
      it 'returns nil' do
        expect(project.to_reference).to be_nil
      end
    end

413
    context 'when full is true' do
414
      it 'returns complete path to the project' do
415 416 417
        expect(project.to_reference(full: true)).to          eq 'sample-namespace/sample-project'
        expect(project.to_reference(project, full: true)).to eq 'sample-namespace/sample-project'
        expect(project.to_reference(group, full: true)).to   eq 'sample-namespace/sample-project'
418 419 420 421 422 423 424 425 426 427
      end
    end

    context 'when same project argument' do
      it 'returns nil' do
        expect(project.to_reference(project)).to be_nil
      end
    end

    context 'when cross namespace project argument' do
428
      let(:another_namespace_project) { create(:project, name: 'another-project') }
429 430 431 432 433 434 435

      it 'returns complete path to the project' do
        expect(project.to_reference(another_namespace_project)).to eq 'sample-namespace/sample-project'
      end
    end

    context 'when same namespace / cross-project argument' do
436
      let(:another_project) { create(:project, namespace: namespace) }
437

438
      it 'returns path to the project' do
439 440 441
        expect(project.to_reference(another_project)).to eq 'sample-project'
      end
    end
442

443 444
    context 'when different namespace / cross-project argument' do
      let(:another_namespace) { create(:namespace, path: 'another-namespace', owner: owner) }
445
      let(:another_project)   { create(:project, path: 'another-project', namespace: another_namespace) }
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

      it 'returns full path to the project' do
        expect(project.to_reference(another_project)).to eq 'sample-namespace/sample-project'
      end
    end

    context 'when argument is a namespace' do
      context 'with same project path' do
        it 'returns path to the project' do
          expect(project.to_reference(namespace)).to eq 'sample-project'
        end
      end

      context 'with different project path' do
        it 'returns full path to the project' do
          expect(project.to_reference(group)).to eq 'sample-namespace/sample-project'
        end
463 464
      end
    end
465 466 467 468 469
  end

  describe '#to_human_reference' do
    let(:owner) { create(:user, name: 'Gitlab') }
    let(:namespace) { create(:namespace, name: 'Sample namespace', owner: owner) }
470
    let(:project) { create(:project, name: 'Sample project', namespace: namespace) }
471 472 473 474 475 476 477 478 479 480 481 482 483 484

    context 'when nil argument' do
      it 'returns nil' do
        expect(project.to_human_reference).to be_nil
      end
    end

    context 'when same project argument' do
      it 'returns nil' do
        expect(project.to_human_reference(project)).to be_nil
      end
    end

    context 'when cross namespace project argument' do
485
      let(:another_namespace_project) { create(:project, name: 'another-project') }
486 487 488 489 490 491 492

      it 'returns complete name with namespace of the project' do
        expect(project.to_human_reference(another_namespace_project)).to eq 'Gitlab / Sample project'
      end
    end

    context 'when same namespace / cross-project argument' do
493
      let(:another_project) { create(:project, namespace: namespace) }
494 495 496 497

      it 'returns name of the project' do
        expect(project.to_human_reference(another_project)).to eq 'Sample project'
      end
498 499 500
    end
  end

501
  describe '#merge_method' do
502 503 504 505 506 507 508
    using RSpec::Parameterized::TableSyntax

    where(:ff, :rebase, :method) do
      true  | true  | :ff
      true  | false | :ff
      false | true  | :rebase_merge
      false | false | :merge
509 510
    end

511 512 513 514 515 516
    with_them do
      let(:project) { build(:project, merge_requests_rebase_enabled: rebase, merge_requests_ff_only_enabled: ff) }

      subject { project.merge_method }

      it { is_expected.to eq(method) }
517 518 519
    end
  end

520
  it 'returns valid url to repo' do
521
    project = described_class.new(path: 'somewhere')
522
    expect(project.url_to_repo).to eq(Gitlab.config.gitlab_shell.ssh_path_prefix + 'somewhere.git')
gitlabhq's avatar
gitlabhq committed
523 524
  end

Douwe Maan's avatar
Douwe Maan committed
525
  describe "#web_url" do
526
    let(:project) { create(:project, path: "somewhere") }
Douwe Maan's avatar
Douwe Maan committed
527 528

    it 'returns the full web URL for this repo' do
529
      expect(project.web_url).to eq("#{Gitlab.config.gitlab.url}/#{project.namespace.full_path}/somewhere")
Douwe Maan's avatar
Douwe Maan committed
530
    end
531 532
  end

533 534
  describe "#readme_url" do
    context 'with a non-existing repository' do
535
      let(:project) { create(:project) }
536

537
      it 'returns nil' do
538 539 540 541 542 543
        expect(project.readme_url).to be_nil
      end
    end

    context 'with an existing repository' do
      context 'when no README exists' do
544
        let(:project) { create(:project, :empty_repo) }
545

546
        it 'returns nil' do
547 548 549 550 551
          expect(project.readme_url).to be_nil
        end
      end

      context 'when a README exists' do
552 553
        let(:project) { create(:project, :repository) }

554
        it 'returns the README' do
555
          expect(project.readme_url).to eq("#{project.web_url}/blob/master/README.md")
556 557 558 559 560
        end
      end
    end
  end

561
  describe "#new_issuable_address" do
562
    let(:project) { create(:project, path: "somewhere") }
563 564
    let(:user) { create(:user) }

565 566 567 568 569 570
    context 'incoming email enabled' do
      before do
        stub_incoming_email_setting(enabled: true, address: "p+%{key}@gl.ab")
      end

      it 'returns the address to create a new issue' do
571
        address = "p+#{project.full_path}+#{user.incoming_email_token}@gl.ab"
572

573 574 575 576 577 578 579
        expect(project.new_issuable_address(user, 'issue')).to eq(address)
      end

      it 'returns the address to create a new merge request' do
        address = "p+#{project.full_path}+merge-request+#{user.incoming_email_token}@gl.ab"

        expect(project.new_issuable_address(user, 'merge_request')).to eq(address)
580 581 582 583 584 585 586
      end
    end

    context 'incoming email disabled' do
      before do
        stub_incoming_email_setting(enabled: false)
      end
587

588
      it 'returns nil' do
589 590 591 592 593
        expect(project.new_issuable_address(user, 'issue')).to be_nil
      end

      it 'returns nil' do
        expect(project.new_issuable_address(user, 'merge_request')).to be_nil
594
      end
595 596 597
    end
  end

598
  describe 'last_activity methods' do
599 600
    let(:timestamp) { 2.hours.ago }
    # last_activity_at gets set to created_at upon creation
601
    let(:project) { create(:project, created_at: timestamp, updated_at: timestamp) }
gitlabhq's avatar
gitlabhq committed
602

603
    describe 'last_activity' do
604
      it 'alias last_activity to last_event' do
605
        last_event = create(:event, :closed, project: project)
606

607
        expect(project.last_activity).to eq(last_event)
608
      end
gitlabhq's avatar
gitlabhq committed
609 610
    end

611 612
    describe 'last_activity_date' do
      it 'returns the creation date of the project\'s last event if present' do
613
        new_event = create(:event, :closed, project: project, created_at: Time.now)
614

615
        project.reload
616
        expect(project.last_activity_at.to_i).to eq(new_event.created_at.to_i)
617
      end
618

619
      it 'returns the project\'s last update date if it has no events' do
620
        expect(project.last_activity_date).to eq(project.updated_at)
621
      end
622 623

      it 'returns the most recent timestamp' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
624 625 626
        project.update(updated_at: nil,
                       last_activity_at: timestamp,
                       last_repository_updated_at: timestamp - 1.hour)
627

628
        expect(project.last_activity_date).to be_like_time(timestamp)
629

Lin Jen-Shin's avatar
Lin Jen-Shin committed
630 631 632
        project.update(updated_at: timestamp,
                       last_activity_at: timestamp - 1.hour,
                       last_repository_updated_at: nil)
633

634
        expect(project.last_activity_date).to be_like_time(timestamp)
635
      end
636 637
    end
  end
638

639
  describe '#get_issue' do
640
    let(:project) { create(:project) }
641
    let!(:issue)  { create(:issue, project: project) }
642 643 644
    let(:user)    { create(:user) }

    before do
645
      project.add_developer(user)
646
    end
647 648 649

    context 'with default issues tracker' do
      it 'returns an issue' do
650
        expect(project.get_issue(issue.iid, user)).to eq issue
651 652
      end

653 654 655 656
      it 'returns count of open issues' do
        expect(project.open_issues_count).to eq(1)
      end

657
      it 'returns nil when no issue found' do
658 659 660 661 662 663
        expect(project.get_issue(999, user)).to be_nil
      end

      it "returns nil when user doesn't have access" do
        user = create(:user)
        expect(project.get_issue(issue.iid, user)).to eq nil
664 665 666 667
      end
    end

    context 'with external issues tracker' do
668
      let!(:internal_issue) { create(:issue, project: project) }
669
      before do
670
        allow(project).to receive(:external_issue_tracker).and_return(true)
671 672
      end

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
      context 'when internal issues are enabled' do
        it 'returns interlan issue' do
          issue = project.get_issue(internal_issue.iid, user)

          expect(issue).to be_kind_of(Issue)
          expect(issue.iid).to eq(internal_issue.iid)
          expect(issue.project).to eq(project)
        end

        it 'returns an ExternalIssue when internal issue does not exists' do
          issue = project.get_issue('FOO-1234', user)

          expect(issue).to be_kind_of(ExternalIssue)
          expect(issue.iid).to eq('FOO-1234')
          expect(issue.project).to eq(project)
        end
      end

      context 'when internal issues are disabled' do
        before do
          project.issues_enabled = false
          project.save!
        end

        it 'returns always an External issues' do
          issue = project.get_issue(internal_issue.iid, user)
          expect(issue).to be_kind_of(ExternalIssue)
          expect(issue.iid).to eq(internal_issue.iid.to_s)
          expect(issue.project).to eq(project)
        end

        it 'returns an ExternalIssue when internal issue does not exists' do
          issue = project.get_issue('FOO-1234', user)
          expect(issue).to be_kind_of(ExternalIssue)
          expect(issue.iid).to eq('FOO-1234')
          expect(issue.project).to eq(project)
        end
710 711 712 713 714
      end
    end
  end

  describe '#issue_exists?' do
715
    let(:project) { create(:project) }
716 717 718 719 720 721 722 723 724 725 726 727

    it 'is truthy when issue exists' do
      expect(project).to receive(:get_issue).and_return(double)
      expect(project.issue_exists?(1)).to be_truthy
    end

    it 'is falsey when issue does not exist' do
      expect(project).to receive(:get_issue).and_return(nil)
      expect(project.issue_exists?(1)).to be_falsey
    end
  end

728
  describe '#to_param' do
729 730
    context 'with namespace' do
      before do
731
        @group = create(:group, name: 'gitlab')
732
        @project = create(:project, name: 'gitlabhq', namespace: @group)
733 734
      end

Vinnie Okada's avatar
Vinnie Okada committed
735
      it { expect(@project.to_param).to eq('gitlabhq') }
736
    end
737 738 739

    context 'with invalid path' do
      it 'returns previous path to keep project suitable for use in URLs when persisted' do
740
        project = create(:project, path: 'gitlab')
741 742 743 744 745 746 747
        project.path = 'foo&bar'

        expect(project).not_to be_valid
        expect(project.to_param).to eq 'gitlab'
      end

      it 'returns current path when new record' do
748
        project = build(:project, path: 'gitlab')
749 750 751 752 753 754
        project.path = 'foo&bar'

        expect(project).not_to be_valid
        expect(project.to_param).to eq 'foo&bar'
      end
    end
755
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
756

757
  describe '#repository' do
758
    let(:project) { create(:project, :repository) }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
759

760
    it 'returns valid repo' do
761
      expect(project.repository).to be_kind_of(Repository)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
762 763
    end
  end
764

765
  describe '#default_issues_tracker?' do
766
    it "is true if used internal tracker" do
767
      project = build(:project)
768

769
      expect(project.default_issues_tracker?).to be_truthy
770 771
    end

772
    it "is false if used other tracker" do
773 774 775 776
      # NOTE: The current nature of this factory requires persistence
      project = create(:redmine_project)

      expect(project.default_issues_tracker?).to be_falsey
777 778 779
    end
  end

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
  describe '#empty_repo?' do
    context 'when the repo does not exist' do
      let(:project) { build_stubbed(:project) }

      it 'returns true' do
        expect(project.empty_repo?).to be(true)
      end
    end

    context 'when the repo exists' do
      let(:project) { create(:project, :repository) }
      let(:empty_project) { create(:project, :empty_repo) }

      it { expect(empty_project.empty_repo?).to be(true) }
      it { expect(project.empty_repo?).to be(false) }
    end
  end

798
  describe '#external_issue_tracker' do
799
    let(:project) { create(:project) }
800 801 802
    let(:ext_project) { create(:redmine_project) }

    context 'on existing projects with no value for has_external_issue_tracker' do
803
      before do
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
        project.update_column(:has_external_issue_tracker, nil)
        ext_project.update_column(:has_external_issue_tracker, nil)
      end

      it 'updates the has_external_issue_tracker boolean' do
        expect do
          project.external_issue_tracker
        end.to change { project.reload.has_external_issue_tracker }.to(false)

        expect do
          ext_project.external_issue_tracker
        end.to change { ext_project.reload.has_external_issue_tracker }.to(true)
      end
    end

    it 'returns nil and does not query services when there is no external issue tracker' do
      expect(project).not_to receive(:services)

      expect(project.external_issue_tracker).to eq(nil)
    end

    it 'retrieves external_issue_tracker querying services and cache it when there is external issue tracker' do
      ext_project.reload # Factory returns a project with changed attributes
      expect(ext_project).to receive(:services).once.and_call_original

      2.times { expect(ext_project.external_issue_tracker).to be_a_kind_of(RedmineService) }
    end
  end

833
  describe '#cache_has_external_issue_tracker' do
834
    let(:project) { create(:project, has_external_issue_tracker: nil) }
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

    it 'stores true if there is any external_issue_tracker' do
      services = double(:service, external_issue_trackers: [RedmineService.new])
      expect(project).to receive(:services).and_return(services)

      expect do
        project.cache_has_external_issue_tracker
      end.to change { project.has_external_issue_tracker}.to(true)
    end

    it 'stores false if there is no external_issue_tracker' do
      services = double(:service, external_issue_trackers: [])
      expect(project).to receive(:services).and_return(services)

      expect do
        project.cache_has_external_issue_tracker
      end.to change { project.has_external_issue_tracker}.to(false)
    end
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890

    it 'does not cache data when in a read-only GitLab instance' do
      allow(Gitlab::Database).to receive(:read_only?) { true }

      expect do
        project.cache_has_external_issue_tracker
      end.not_to change { project.has_external_issue_tracker }
    end
  end

  describe '#cache_has_external_wiki' do
    let(:project) { create(:project, has_external_wiki: nil) }

    it 'stores true if there is any external_wikis' do
      services = double(:service, external_wikis: [ExternalWikiService.new])
      expect(project).to receive(:services).and_return(services)

      expect do
        project.cache_has_external_wiki
      end.to change { project.has_external_wiki}.to(true)
    end

    it 'stores false if there is no external_wikis' do
      services = double(:service, external_wikis: [])
      expect(project).to receive(:services).and_return(services)

      expect do
        project.cache_has_external_wiki
      end.to change { project.has_external_wiki}.to(false)
    end

    it 'does not cache data when in a read-only GitLab instance' do
      allow(Gitlab::Database).to receive(:read_only?) { true }

      expect do
        project.cache_has_external_wiki
      end.not_to change { project.has_external_wiki }
    end
891 892
  end

893
  describe '#has_wiki?' do
894 895 896
    let(:no_wiki_project)       { create(:project, :wiki_disabled, has_external_wiki: false) }
    let(:wiki_enabled_project)  { create(:project) }
    let(:external_wiki_project) { create(:project, has_external_wiki: true) }
897 898 899 900 901 902 903 904

    it 'returns true if project is wiki enabled or has external wiki' do
      expect(wiki_enabled_project).to have_wiki
      expect(external_wiki_project).to have_wiki
      expect(no_wiki_project).not_to have_wiki
    end
  end

905
  describe '#external_wiki' do
906
    let(:project) { create(:project) }
907

908 909 910 911 912
    context 'with an active external wiki' do
      before do
        create(:service, project: project, type: 'ExternalWikiService', active: true)
        project.external_wiki
      end
913

914 915 916
      it 'sets :has_external_wiki as true' do
        expect(project.has_external_wiki).to be(true)
      end
917

918 919
      it 'sets :has_external_wiki as false if an external wiki service is destroyed later' do
        expect(project.has_external_wiki).to be(true)
920

921 922 923 924
        project.services.external_wikis.first.destroy

        expect(project.has_external_wiki).to be(false)
      end
925 926
    end

927 928 929 930
    context 'with an inactive external wiki' do
      before do
        create(:service, project: project, type: 'ExternalWikiService', active: false)
      end
931

932 933 934
      it 'sets :has_external_wiki as false' do
        expect(project.has_external_wiki).to be(false)
      end
935 936
    end

937 938 939 940
    context 'with no external wiki' do
      before do
        project.external_wiki
      end
941

942 943 944 945 946 947 948 949 950 951 952
      it 'sets :has_external_wiki as false' do
        expect(project.has_external_wiki).to be(false)
      end

      it 'sets :has_external_wiki as true if an external wiki service is created later' do
        expect(project.has_external_wiki).to be(false)

        create(:service, project: project, type: 'ExternalWikiService', active: true)

        expect(project.has_external_wiki).to be(true)
      end
953 954 955
    end
  end

956 957
  describe '#star_count' do
    it 'counts stars from multiple users' do
958 959
      user1 = create(:user)
      user2 = create(:user)
960
      project = create(:project, :public)
Ciro Santilli's avatar
Ciro Santilli committed
961 962

      expect(project.star_count).to eq(0)
963

Ciro Santilli's avatar
Ciro Santilli committed
964
      user1.toggle_star(project)
965 966
      expect(project.reload.star_count).to eq(1)

Ciro Santilli's avatar
Ciro Santilli committed
967
      user2.toggle_star(project)
968 969 970
      project.reload
      expect(project.reload.star_count).to eq(2)

Ciro Santilli's avatar
Ciro Santilli committed
971
      user1.toggle_star(project)
972 973 974
      project.reload
      expect(project.reload.star_count).to eq(1)

Ciro Santilli's avatar
Ciro Santilli committed
975
      user2.toggle_star(project)
976 977 978 979
      project.reload
      expect(project.reload.star_count).to eq(0)
    end

980
    it 'counts stars on the right project' do
981
      user = create(:user)
982 983
      project1 = create(:project, :public)
      project2 = create(:project, :public)
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

      expect(project1.star_count).to eq(0)
      expect(project2.star_count).to eq(0)

      user.toggle_star(project1)
      project1.reload
      project2.reload
      expect(project1.star_count).to eq(1)
      expect(project2.star_count).to eq(0)

      user.toggle_star(project1)
      project1.reload
      project2.reload
      expect(project1.star_count).to eq(0)
      expect(project2.star_count).to eq(0)

      user.toggle_star(project2)
      project1.reload
      project2.reload
      expect(project1.star_count).to eq(0)
      expect(project2.star_count).to eq(1)

      user.toggle_star(project2)
      project1.reload
      project2.reload
      expect(project1.star_count).to eq(0)
      expect(project2.star_count).to eq(0)
Ciro Santilli's avatar
Ciro Santilli committed
1011 1012
    end
  end
1013

1014
  describe '#avatar_type' do
1015
    let(:project) { create(:project) }
1016

1017
    it 'is true if avatar is image' do
1018
      project.update_attribute(:avatar, 'uploads/avatar.png')
1019
      expect(project.avatar_type).to be_truthy
1020 1021
    end

1022
    it 'is false if avatar is html page' do
1023
      project.update_attribute(:avatar, 'uploads/avatar.html')
1024
      expect(project.avatar_type).to eq(['file format is not supported. Please try one of the following supported formats: png, jpg, jpeg, gif, bmp, tiff, ico'])
1025 1026
    end
  end
sue445's avatar
sue445 committed
1027

1028
  describe '#avatar_url' do
sue445's avatar
sue445 committed
1029 1030
    subject { project.avatar_url }

1031
    let(:project) { create(:project) }
sue445's avatar
sue445 committed
1032

1033
    context 'when avatar file is uploaded' do
1034
      let(:project) { create(:project, :public, :with_avatar) }
sue445's avatar
sue445 committed
1035

1036
      it 'shows correct url' do
1037 1038
        expect(project.avatar_url).to eq(project.avatar.url)
        expect(project.avatar_url(only_path: false)).to eq([Gitlab.config.gitlab.url, project.avatar.url].join)
1039
      end
sue445's avatar
sue445 committed
1040 1041
    end

1042
    context 'when avatar file in git' do
sue445's avatar
sue445 committed
1043 1044 1045 1046
      before do
        allow(project).to receive(:avatar_in_git) { true }
      end

1047
      let(:avatar_path) { "/#{project.full_path}/avatar" }
sue445's avatar
sue445 committed
1048

1049
      it { is_expected.to eq "http://#{Gitlab.config.gitlab.host}#{avatar_path}" }
sue445's avatar
sue445 committed
1050
    end
1051 1052

    context 'when git repo is empty' do
1053
      let(:project) { create(:project) }
1054

1055
      it { is_expected.to eq nil }
1056
    end
sue445's avatar
sue445 committed
1057
  end
1058

1059
  describe '#pipeline_for' do
1060
    let(:project) { create(:project, :repository) }
1061
    let!(:pipeline) { create_pipeline }
1062

1063 1064
    shared_examples 'giving the correct pipeline' do
      it { is_expected.to eq(pipeline) }
1065

1066 1067
      context 'return latest' do
        let!(:pipeline2) { create_pipeline }
1068

1069
        it { is_expected.to eq(pipeline2) }
1070
      end
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    end

    context 'with explicit sha' do
      subject { project.pipeline_for('master', pipeline.sha) }

      it_behaves_like 'giving the correct pipeline'
    end

    context 'with implicit sha' do
      subject { project.pipeline_for('master') }

      it_behaves_like 'giving the correct pipeline'
    end
1084

1085 1086 1087 1088 1089
    def create_pipeline
      create(:ci_pipeline,
             project: project,
             ref: 'master',
             sha: project.commit('master').sha)
1090
    end
1091
  end
1092

1093
  describe '#builds_enabled' do
1094
    let(:project) { create(:project) }
1095

1096 1097 1098
    subject { project.builds_enabled }

    it { expect(project.builds_enabled?).to be_truthy }
1099
  end
1100

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  describe '.sort_by_attribute' do
    it 'reorders the input relation by start count desc' do
      project1 = create(:project, star_count: 2)
      project2 = create(:project, star_count: 1)
      project3 = create(:project)

      projects = described_class.sort_by_attribute(:stars_desc)

      expect(projects).to eq([project1, project2, project3])
    end
  end

1113
  describe '.with_shared_runners' do
1114
    subject { described_class.with_shared_runners }
1115 1116

    context 'when shared runners are enabled for project' do
1117
      let!(:project) { create(:project, shared_runners_enabled: true) }
1118 1119 1120 1121 1122 1123 1124

      it "returns a project" do
        is_expected.to eq([project])
      end
    end

    context 'when shared runners are disabled for project' do
1125
      let!(:project) { create(:project, shared_runners_enabled: false) }
1126 1127 1128 1129 1130 1131 1132

      it "returns an empty array" do
        is_expected.to be_empty
      end
    end
  end

1133
  describe '.cached_count', :use_clean_rails_memory_store_caching do
1134
    let(:group)     { create(:group, :public) }
1135 1136
    let!(:project1) { create(:project, :public, group: group) }
    let!(:project2) { create(:project, :public, group: group) }
1137 1138

    it 'returns total project count' do
1139
      expect(described_class).to receive(:count).once.and_call_original
1140 1141

      3.times do
1142
        expect(described_class.cached_count).to eq(2)
1143 1144 1145 1146
      end
    end
  end

1147
  describe '.trending' do
Felipe Artur's avatar
Felipe Artur committed
1148
    let(:group)    { create(:group, :public) }
1149 1150
    let(:project1) { create(:project, :public, group: group) }
    let(:project2) { create(:project, :public, group: group) }
1151 1152 1153 1154 1155 1156 1157 1158

    before do
      2.times do
        create(:note_on_commit, project: project1)
      end

      create(:note_on_commit, project: project2)

1159
      TrendingProject.refresh!
1160 1161
    end

1162
    subject { described_class.trending.to_a }
1163

1164 1165
    it 'sorts projects by the amount of notes in descending order' do
      expect(subject).to eq([project1, project2])
1166
    end
1167 1168 1169 1170 1171 1172 1173 1174

    it 'does not take system notes into account' do
      10.times do
        create(:note_on_commit, project: project2, system: true)
      end

      expect(described_class.trending.to_a).to eq([project1, project2])
    end
1175
  end
1176

1177 1178 1179 1180
  describe '.starred_by' do
    it 'returns only projects starred by the given user' do
      user1 = create(:user)
      user2 = create(:user)
1181 1182 1183
      project1 = create(:project)
      project2 = create(:project)
      create(:project)
1184 1185 1186
      user1.toggle_star(project1)
      user2.toggle_star(project2)

1187
      expect(described_class.starred_by(user1)).to contain_exactly(project1)
1188 1189 1190
    end
  end

1191
  describe '.visible_to_user' do
1192
    let!(:project) { create(:project, :private) }
1193 1194 1195 1196 1197 1198
    let!(:user)    { create(:user) }

    subject { described_class.visible_to_user(user) }

    describe 'when a user has access to a project' do
      before do
1199
        project.add_user(user, Gitlab::Access::MAINTAINER)
1200 1201 1202 1203 1204 1205 1206 1207 1208
      end

      it { is_expected.to eq([project]) }
    end

    describe 'when a user does not have access to any projects' do
      it { is_expected.to eq([]) }
    end
  end
1209

1210
  context 'repository storage by default' do
1211
    let(:project) { build(:project) }
1212 1213

    before do
1214
      storages = {
1215 1216
        'default' => Gitlab::GitalyClient::StorageSettings.new('path' => 'tmp/tests/repositories'),
        'picked'  => Gitlab::GitalyClient::StorageSettings.new('path' => 'tmp/tests/repositories')
1217
      }
1218 1219 1220
      allow(Gitlab.config.repositories).to receive(:storages).and_return(storages)
    end

1221 1222 1223 1224 1225
    it 'picks storage from ApplicationSetting' do
      expect_any_instance_of(ApplicationSetting).to receive(:pick_repository_storage).and_return('picked')

      expect(project.repository_storage).to eq('picked')
    end
1226 1227
  end

1228
  context 'shared runners by default' do
1229
    let(:project) { create(:project) }
1230 1231 1232 1233

    subject { project.shared_runners_enabled }

    context 'are enabled' do
1234 1235 1236
      before do
        stub_application_setting(shared_runners_enabled: true)
      end
1237 1238 1239 1240 1241

      it { is_expected.to be_truthy }
    end

    context 'are disabled' do
1242 1243 1244
      before do
        stub_application_setting(shared_runners_enabled: false)
      end
1245 1246 1247 1248 1249

      it { is_expected.to be_falsey }
    end
  end

1250
  describe '#any_runners?' do
1251
    context 'shared runners' do
1252
      let(:project) { create(:project, shared_runners_enabled: shared_runners_enabled) }
1253 1254
      let(:specific_runner) { create(:ci_runner, :project, projects: [project]) }
      let(:shared_runner) { create(:ci_runner, :instance) }
1255

1256 1257
      context 'for shared runners disabled' do
        let(:shared_runners_enabled) { false }
1258

1259 1260 1261
        it 'has no runners available' do
          expect(project.any_runners?).to be_falsey
        end
1262

1263
        it 'has a specific runner' do
1264
          specific_runner
1265

1266 1267 1268 1269 1270
          expect(project.any_runners?).to be_truthy
        end

        it 'has a shared runner, but they are prohibited to use' do
          shared_runner
1271

1272 1273
          expect(project.any_runners?).to be_falsey
        end
1274

1275
        it 'checks the presence of specific runner' do
1276
          specific_runner
1277

1278 1279
          expect(project.any_runners? { |runner| runner == specific_runner }).to be_truthy
        end
1280 1281

        it 'returns false if match cannot be found' do
1282
          specific_runner
1283

1284 1285
          expect(project.any_runners? { false }).to be_falsey
        end
1286
      end
1287

1288 1289 1290 1291 1292
      context 'for shared runners enabled' do
        let(:shared_runners_enabled) { true }

        it 'has a shared runner' do
          shared_runner
1293

1294 1295 1296 1297 1298
          expect(project.any_runners?).to be_truthy
        end

        it 'checks the presence of shared runner' do
          shared_runner
1299

1300 1301
          expect(project.any_runners? { |runner| runner == shared_runner }).to be_truthy
        end
1302 1303 1304

        it 'returns false if match cannot be found' do
          shared_runner
1305

1306 1307
          expect(project.any_runners? { false }).to be_falsey
        end
1308 1309
      end
    end
1310

1311
    context 'group runners' do
1312 1313
      let(:project) { create(:project, group_runners_enabled: group_runners_enabled) }
      let(:group) { create(:group, projects: [project]) }
1314
      let(:group_runner) { create(:ci_runner, :group, groups: [group]) }
1315 1316 1317

      context 'for group runners disabled' do
        let(:group_runners_enabled) { false }
1318

1319 1320 1321 1322 1323 1324
        it 'has no runners available' do
          expect(project.any_runners?).to be_falsey
        end

        it 'has a group runner, but they are prohibited to use' do
          group_runner
1325

1326 1327
          expect(project.any_runners?).to be_falsey
        end
1328 1329
      end

1330 1331 1332 1333 1334
      context 'for group runners enabled' do
        let(:group_runners_enabled) { true }

        it 'has a group runner' do
          group_runner
1335

1336 1337 1338 1339 1340
          expect(project.any_runners?).to be_truthy
        end

        it 'checks the presence of group runner' do
          group_runner
1341

1342 1343
          expect(project.any_runners? { |runner| runner == group_runner }).to be_truthy
        end
1344 1345 1346

        it 'returns false if match cannot be found' do
          group_runner
1347

1348 1349
          expect(project.any_runners? { false }).to be_falsey
        end
1350 1351 1352
      end
    end
  end
1353

1354
  describe '#shared_runners' do
1355
    let!(:runner) { create(:ci_runner, :instance) }
1356 1357 1358 1359

    subject { project.shared_runners }

    context 'when shared runners are enabled for project' do
1360
      let!(:project) { create(:project, shared_runners_enabled: true) }
1361 1362 1363 1364 1365 1366 1367

      it "returns a list of shared runners" do
        is_expected.to eq([runner])
      end
    end

    context 'when shared runners are disabled for project' do
1368
      let!(:project) { create(:project, shared_runners_enabled: false) }
1369 1370 1371 1372 1373 1374 1375

      it "returns a empty list" do
        is_expected.to be_empty
      end
    end
  end

1376
  describe '#visibility_level_allowed?' do
1377
    let(:project) { create(:project, :internal) }
1378 1379 1380 1381 1382 1383 1384 1385

    context 'when checking on non-forked project' do
      it { expect(project.visibility_level_allowed?(Gitlab::VisibilityLevel::PRIVATE)).to be_truthy }
      it { expect(project.visibility_level_allowed?(Gitlab::VisibilityLevel::INTERNAL)).to be_truthy }
      it { expect(project.visibility_level_allowed?(Gitlab::VisibilityLevel::PUBLIC)).to be_truthy }
    end

    context 'when checking on forked project' do
1386
      let(:project)        { create(:project, :internal) }
1387
      let(:forked_project) { fork_project(project) }
1388 1389 1390 1391 1392

      it { expect(forked_project.visibility_level_allowed?(Gitlab::VisibilityLevel::PRIVATE)).to be_truthy }
      it { expect(forked_project.visibility_level_allowed?(Gitlab::VisibilityLevel::INTERNAL)).to be_truthy }
      it { expect(forked_project.visibility_level_allowed?(Gitlab::VisibilityLevel::PUBLIC)).to be_falsey }
    end
1393
  end
1394

1395
  describe '#pages_deployed?' do
1396
    let(:project) { create(:project) }
1397 1398 1399 1400

    subject { project.pages_deployed? }

    context 'if public folder does exist' do
1401 1402 1403
      before do
        allow(Dir).to receive(:exist?).with(project.public_pages_path).and_return(true)
      end
1404 1405 1406 1407 1408 1409 1410 1411 1412

      it { is_expected.to be_truthy }
    end

    context "if public folder doesn't exist" do
      it { is_expected.to be_falsey }
    end
  end

1413
  describe '#pages_url' do
1414 1415
    let(:group) { create(:group, name: group_name) }
    let(:project) { create(:project, namespace: group, name: project_name) }
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    let(:domain) { 'Example.com' }

    subject { project.pages_url }

    before do
      allow(Settings.pages).to receive(:host).and_return(domain)
      allow(Gitlab.config.pages).to receive(:url).and_return('http://example.com')
    end

    context 'group page' do
      let(:group_name) { 'Group' }
      let(:project_name) { 'group.example.com' }

      it { is_expected.to eq("http://group.example.com") }
    end

    context 'project page' do
      let(:group_name) { 'Group' }
      let(:project_name) { 'Project' }

      it { is_expected.to eq("http://group.example.com/project") }
1437 1438 1439 1440
    end
  end

  describe '#pages_group_url' do
1441 1442
    let(:group) { create(:group, name: group_name) }
    let(:project) { create(:project, namespace: group, name: project_name) }
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
    let(:domain) { 'Example.com' }
    let(:port) { 1234 }

    subject { project.pages_group_url }

    before do
      allow(Settings.pages).to receive(:host).and_return(domain)
      allow(Gitlab.config.pages).to receive(:url).and_return("http://example.com:#{port}")
    end

    context 'group page' do
      let(:group_name) { 'Group' }
      let(:project_name) { 'group.example.com' }

      it { is_expected.to eq("http://group.example.com:#{port}") }
    end

    context 'project page' do
      let(:group_name) { 'Group' }
      let(:project_name) { 'Project' }

      it { is_expected.to eq("http://group.example.com:#{port}") }
1465 1466 1467
    end
  end

1468
  describe '.search' do
1469
    let(:project) { create(:project, description: 'kitten mittens') }
1470

1471 1472 1473
    it 'returns projects with a matching name' do
      expect(described_class.search(project.name)).to eq([project])
    end
1474

1475 1476 1477
    it 'returns projects with a partially matching name' do
      expect(described_class.search(project.name[0..2])).to eq([project])
    end
1478

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
    it 'returns projects with a matching name regardless of the casing' do
      expect(described_class.search(project.name.upcase)).to eq([project])
    end

    it 'returns projects with a matching description' do
      expect(described_class.search(project.description)).to eq([project])
    end

    it 'returns projects with a partially matching description' do
      expect(described_class.search('kitten')).to eq([project])
    end

    it 'returns projects with a matching description regardless of the casing' do
      expect(described_class.search('KITTEN')).to eq([project])
    end

    it 'returns projects with a matching path' do
      expect(described_class.search(project.path)).to eq([project])
    end

    it 'returns projects with a partially matching path' do
      expect(described_class.search(project.path[0..2])).to eq([project])
    end

    it 'returns projects with a matching path regardless of the casing' do
      expect(described_class.search(project.path.upcase)).to eq([project])
    end

1507
    describe 'with pending_delete project' do
1508
      let(:pending_delete_project) { create(:project, pending_delete: true) }
1509 1510 1511 1512 1513 1514 1515

      it 'shows pending deletion project' do
        search_result = described_class.search(pending_delete_project.name)

        expect(search_result).to eq([pending_delete_project])
      end
    end
1516
  end
1517

1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
  describe '.optionally_search' do
    let(:project) { create(:project) }

    it 'searches for projects matching the query if one is given' do
      relation = described_class.optionally_search(project.name)

      expect(relation).to eq([project])
    end

    it 'returns the current relation if no search query is given' do
      relation = described_class.where(id: project.id)

      expect(relation.optionally_search).to eq(relation)
    end
  end

  describe '.paginate_in_descending_order_using_id' do
    let!(:project1) { create(:project) }
    let!(:project2) { create(:project) }

    it 'orders the relation in descending order' do
      expect(described_class.paginate_in_descending_order_using_id)
        .to eq([project2, project1])
    end

    it 'applies a limit to the relation' do
      expect(described_class.paginate_in_descending_order_using_id(limit: 1))
        .to eq([project2])
    end

    it 'limits projects by and ID when given' do
      expect(described_class.paginate_in_descending_order_using_id(before: project2.id))
        .to eq([project1])
    end
  end

  describe '.including_namespace_and_owner' do
    it 'eager loads the namespace and namespace owner' do
      create(:project)

      row = described_class.eager_load_namespace_and_owner.to_a.first
      recorder = ActiveRecord::QueryRecorder.new { row.namespace.owner }

      expect(recorder.count).to be_zero
    end
  end

1565
  describe '#expire_caches_before_rename' do
1566
    let(:project) { create(:project, :repository) }
1567 1568 1569 1570
    let(:repo)    { double(:repo, exists?: true) }
    let(:wiki)    { double(:wiki, exists?: true) }

    it 'expires the caches of the repository and wiki' do
1571 1572 1573
      allow(Repository).to receive(:new)
        .with('foo', project)
        .and_return(repo)
1574

1575 1576 1577
      allow(Repository).to receive(:new)
        .with('foo.wiki', project)
        .and_return(wiki)
1578

1579 1580
      expect(repo).to receive(:before_delete)
      expect(wiki).to receive(:before_delete)
1581 1582 1583 1584

      project.expire_caches_before_rename('foo')
    end
  end
1585 1586

  describe '.search_by_title' do
1587
    let(:project) { create(:project, name: 'kittens') }
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600

    it 'returns projects with a matching name' do
      expect(described_class.search_by_title(project.name)).to eq([project])
    end

    it 'returns projects with a partially matching name' do
      expect(described_class.search_by_title('kitten')).to eq([project])
    end

    it 'returns projects with a matching name regardless of the casing' do
      expect(described_class.search_by_title('KITTENS')).to eq([project])
    end
  end
1601 1602 1603 1604 1605

  context 'when checking projects from groups' do
    let(:private_group)    { create(:group, visibility_level: 0)  }
    let(:internal_group)   { create(:group, visibility_level: 10) }

1606 1607
    let(:private_project)  { create(:project, :private, group: private_group) }
    let(:internal_project) { create(:project, :internal, group: internal_group) }
1608 1609 1610 1611 1612 1613 1614 1615 1616

    context 'when group is private project can not be internal' do
      it { expect(private_project.visibility_level_allowed?(Gitlab::VisibilityLevel::INTERNAL)).to be_falsey }
    end

    context 'when group is internal project can not be public' do
      it { expect(internal_project.visibility_level_allowed?(Gitlab::VisibilityLevel::PUBLIC)).to be_falsey }
    end
  end
1617

1618
  describe '#create_repository' do
1619
    let(:project) { create(:project, :repository) }
1620 1621 1622 1623 1624 1625 1626 1627
    let(:shell) { Gitlab::Shell.new }

    before do
      allow(project).to receive(:gitlab_shell).and_return(shell)
    end

    context 'using a regular repository' do
      it 'creates the repository' do
1628
        expect(shell).to receive(:create_repository)
1629
          .with(project.repository_storage, project.disk_path)
1630
          .and_return(true)
1631 1632 1633 1634 1635 1636 1637

        expect(project.repository).to receive(:after_create)

        expect(project.create_repository).to eq(true)
      end

      it 'adds an error if the repository could not be created' do
1638
        expect(shell).to receive(:create_repository)
1639
          .with(project.repository_storage, project.disk_path)
1640
          .and_return(false)
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651

        expect(project.repository).not_to receive(:after_create)

        expect(project.create_repository).to eq(false)
        expect(project.errors).not_to be_empty
      end
    end

    context 'using a forked repository' do
      it 'does nothing' do
        expect(project).to receive(:forked?).and_return(true)
1652
        expect(shell).not_to receive(:create_repository)
1653 1654 1655 1656 1657

        project.create_repository
      end
    end
  end
1658

1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
  describe '#ensure_repository' do
    let(:project) { create(:project, :repository) }
    let(:shell) { Gitlab::Shell.new }

    before do
      allow(project).to receive(:gitlab_shell).and_return(shell)
    end

    it 'creates the repository if it not exist' do
      allow(project).to receive(:repository_exists?)
        .and_return(false)

1671
      allow(shell).to receive(:create_repository)
1672
        .with(project.repository_storage, project.disk_path)
1673 1674
        .and_return(true)

1675
      expect(project).to receive(:create_repository).with(force: true)
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687

      project.ensure_repository
    end

    it 'does not create the repository if it exists' do
      allow(project).to receive(:repository_exists?)
        .and_return(true)

      expect(project).not_to receive(:create_repository)

      project.ensure_repository
    end
1688 1689 1690 1691 1692 1693 1694

    it 'creates the repository if it is a fork' do
      expect(project).to receive(:forked?).and_return(true)

      allow(project).to receive(:repository_exists?)
        .and_return(false)

1695
      expect(shell).to receive(:create_repository)
1696
        .with(project.repository_storage, project.disk_path)
1697 1698 1699 1700
        .and_return(true)

      project.ensure_repository
    end
1701 1702
  end

1703
  describe '#container_registry_url' do
1704
    let(:project) { create(:project) }
1705

1706
    subject { project.container_registry_url }
1707

1708 1709 1710
    before do
      stub_container_registry_config(**registry_settings)
    end
1711 1712 1713

    context 'for enabled registry' do
      let(:registry_settings) do
1714 1715
        { enabled: true,
          host_port: 'example.com' }
1716 1717
      end

1718
      it { is_expected.not_to be_nil }
1719 1720 1721 1722
    end

    context 'for disabled registry' do
      let(:registry_settings) do
1723
        { enabled: false }
1724 1725 1726 1727 1728 1729
      end

      it { is_expected.to be_nil }
    end
  end

1730
  describe '#has_container_registry_tags?' do
1731
    let(:project) { create(:project) }
1732 1733

    context 'when container registry is enabled' do
1734 1735 1736
      before do
        stub_container_registry_config(enabled: true)
      end
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773

      context 'when tags are present for multi-level registries' do
        before do
          create(:container_repository, project: project, name: 'image')

          stub_container_registry_tags(repository: /image/,
                                       tags: %w[latest rc1])
        end

        it 'should have image tags' do
          expect(project).to have_container_registry_tags
        end
      end

      context 'when tags are present for root repository' do
        before do
          stub_container_registry_tags(repository: project.full_path,
                                       tags: %w[latest rc1 pre1])
        end

        it 'should have image tags' do
          expect(project).to have_container_registry_tags
        end
      end

      context 'when there are no tags at all' do
        before do
          stub_container_registry_tags(repository: :any, tags: [])
        end

        it 'should not have image tags' do
          expect(project).not_to have_container_registry_tags
        end
      end
    end

    context 'when container registry is disabled' do
1774 1775 1776
      before do
        stub_container_registry_config(enabled: false)
      end
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793

      it 'should not have image tags' do
        expect(project).not_to have_container_registry_tags
      end

      it 'should not check root repository tags' do
        expect(project).not_to receive(:full_path)
        expect(project).not_to have_container_registry_tags
      end

      it 'should iterate through container repositories' do
        expect(project).to receive(:container_repositories)
        expect(project).not_to have_container_registry_tags
      end
    end
  end

1794
  describe '#ci_config_path=' do
1795
    let(:project) { create(:project) }
1796 1797

    it 'sets nil' do
1798
      project.update!(ci_config_path: nil)
1799

1800
      expect(project.ci_config_path).to be_nil
1801 1802 1803
    end

    it 'sets a string' do
1804
      project.update!(ci_config_path: 'foo/.gitlab_ci.yml')
1805

1806
      expect(project.ci_config_path).to eq('foo/.gitlab_ci.yml')
1807 1808
    end

1809 1810
    it 'sets a string but removes all null characters' do
      project.update!(ci_config_path: "f\0oo/\0/.gitlab_ci.yml")
1811

1812
      expect(project.ci_config_path).to eq('foo//.gitlab_ci.yml')
1813 1814 1815
    end
  end

1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
  describe '#human_import_status_name' do
    context 'when import_state exists' do
      it 'returns the humanized status name' do
        project = create(:project)
        create(:import_state, :started, project: project)

        expect(project.human_import_status_name).to eq("started")
      end
    end

    context 'when import_state was not created yet' do
      let(:project) { create(:project, :import_started) }

      it 'ensures import_state is created and returns humanized status name' do
        expect do
          project.human_import_status_name
        end.to change { ProjectImportState.count }.from(0).to(1)
      end

      it 'returns humanized status name' do
        expect(project.human_import_status_name).to eq("started")
      end
    end
  end

1841
  describe 'Project import job' do
1842
    let(:project) { create(:project, import_url: generate(:url)) }
1843 1844

    before do
1845
      allow_any_instance_of(Gitlab::Shell).to receive(:import_repository)
1846
        .with(project.repository_storage, project.disk_path, project.import_url)
1847 1848
        .and_return(true)

1849
      # Works around https://github.com/rspec/rspec-mocks/issues/910
1850
      allow(described_class).to receive(:find).with(project.id).and_return(project)
1851 1852 1853
      expect(project.repository).to receive(:after_import)
        .and_call_original
      expect(project.wiki.repository).to receive(:after_import)
1854
        .and_call_original
1855 1856 1857 1858 1859
    end

    it 'imports a project' do
      expect_any_instance_of(RepositoryImportWorker).to receive(:perform).and_call_original

1860
      expect { project.import_schedule }.to change { project.import_jid }
1861 1862 1863 1864
      expect(project.reload.import_status).to eq('finished')
    end
  end

1865 1866
  describe 'project import state transitions' do
    context 'state transition: [:started] => [:finished]' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1867
      let(:after_import_service) { spy(:after_import_service) }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1868
      let(:housekeeping_service) { spy(:housekeeping_service) }
1869 1870

      before do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1871 1872
        allow(Projects::AfterImportService)
          .to receive(:new) { after_import_service }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1873

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1874
        allow(after_import_service)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1875 1876 1877 1878
          .to receive(:execute) { housekeeping_service.execute }

        allow(Projects::HousekeepingService)
          .to receive(:new) { housekeeping_service }
1879 1880
      end

1881 1882
      it 'resets project import_error' do
        error_message = 'Some error'
1883
        mirror = create(:project_empty_repo, :import_started)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1884
        mirror.import_state.update(last_error: error_message)
1885 1886 1887 1888

        expect { mirror.import_finish }.to change { mirror.import_error }.from(error_message).to(nil)
      end

1889 1890 1891 1892 1893
      it 'performs housekeeping when an import of a fresh project is completed' do
        project = create(:project_empty_repo, :import_started, import_type: :github)

        project.import_finish

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1894
        expect(after_import_service).to have_received(:execute)
1895 1896 1897 1898
        expect(housekeeping_service).to have_received(:execute)
      end

      it 'does not perform housekeeping when project repository does not exist' do
1899
        project = create(:project, :import_started, import_type: :github)
1900 1901 1902 1903 1904 1905 1906

        project.import_finish

        expect(housekeeping_service).not_to have_received(:execute)
      end

      it 'does not perform housekeeping when project does not have a valid import type' do
1907
        project = create(:project, :import_started, import_type: nil)
1908 1909 1910 1911 1912 1913 1914 1915

        project.import_finish

        expect(housekeeping_service).not_to have_received(:execute)
      end
    end
  end

1916
  describe '#latest_successful_builds_for' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1917
    def create_pipeline(status = 'success')
1918
      create(:ci_pipeline, project: project,
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1919
                           sha: project.commit.sha,
1920
                           ref: project.default_branch,
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1921
                           status: status)
1922 1923
    end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1924 1925 1926
    def create_build(new_pipeline = pipeline, name = 'test')
      create(:ci_build, :success, :artifacts,
             pipeline: new_pipeline,
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1927
             status: new_pipeline.status,
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1928
             name: name)
1929 1930
    end

1931
    let(:project) { create(:project, :repository) }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1932
    let(:pipeline) { create_pipeline }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1933 1934

    context 'with many builds' do
1935
      it 'gives the latest builds from latest pipeline' do
1936 1937
        pipeline1 = create_pipeline
        pipeline2 = create_pipeline
1938
        build1_p2 = create_build(pipeline2, 'test')
1939 1940
        create_build(pipeline1, 'test')
        create_build(pipeline1, 'test2')
1941
        build2_p2 = create_build(pipeline2, 'test2')
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1942 1943 1944

        latest_builds = project.latest_successful_builds_for

1945
        expect(latest_builds).to contain_exactly(build2_p2, build1_p2)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1946 1947
      end
    end
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1948

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1949
    context 'with succeeded pipeline' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1950
      let!(:build) { create_build }
1951

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1952
      context 'standalone pipeline' do
1953 1954 1955 1956 1957 1958 1959 1960
        it 'returns builds for ref for default_branch' do
          builds = project.latest_successful_builds_for

          expect(builds).to contain_exactly(build)
        end

        it 'returns empty relation if the build cannot be found' do
          builds = project.latest_successful_builds_for('TAIL')
1961

1962 1963 1964
          expect(builds).to be_kind_of(ActiveRecord::Relation)
          expect(builds).to be_empty
        end
1965 1966
      end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1967
      context 'with some pending pipeline' do
1968
        before do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1969
          create_build(create_pipeline('pending'))
1970 1971
        end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1972 1973
        it 'gives the latest build from latest pipeline' do
          latest_build = project.latest_successful_builds_for
1974

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1975
          expect(latest_build).to contain_exactly(build)
1976
        end
1977 1978 1979 1980 1981 1982
      end
    end

    context 'with pending pipeline' do
      before do
        pipeline.update(status: 'pending')
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1983
        create_build(pipeline)
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
      end

      it 'returns empty relation' do
        builds = project.latest_successful_builds_for

        expect(builds).to be_kind_of(ActiveRecord::Relation)
        expect(builds).to be_empty
      end
    end
  end

1995
  describe '#add_import_job' do
1996 1997
    let(:import_jid) { '123' }

1998
    context 'forked' do
1999 2000 2001 2002 2003 2004
      let(:forked_from_project) { create(:project, :repository) }
      let(:project) { create(:project) }

      before do
        fork_project(forked_from_project, nil, target_project: project)
      end
2005 2006

      it 'schedules a RepositoryForkWorker job' do
2007
        expect(RepositoryForkWorker).to receive(:perform_async).with(project.id).and_return(import_jid)
2008

2009
        expect(project.add_import_job).to eq(import_jid)
2010 2011 2012 2013 2014
      end
    end

    context 'not forked' do
      it 'schedules a RepositoryImportWorker job' do
2015
        project = create(:project, import_url: generate(:url))
2016

2017 2018
        expect(RepositoryImportWorker).to receive(:perform_async).with(project.id).and_return(import_jid)
        expect(project.add_import_job).to eq(import_jid)
2019 2020 2021 2022
      end
    end
  end

Rémy Coutable's avatar
Rémy Coutable committed
2023
  describe '#gitlab_project_import?' do
2024
    subject(:project) { build(:project, import_type: 'gitlab_project') }
Rémy Coutable's avatar
Rémy Coutable committed
2025 2026 2027 2028 2029

    it { expect(project.gitlab_project_import?).to be true }
  end

  describe '#gitea_import?' do
2030
    subject(:project) { build(:project, import_type: 'gitea') }
Rémy Coutable's avatar
Rémy Coutable committed
2031 2032 2033 2034

    it { expect(project.gitea_import?).to be true }
  end

2035
  describe '#has_remote_mirror?' do
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
    let(:project) { create(:project, :remote_mirror, :import_started) }
    subject { project.has_remote_mirror? }

    before do
      allow_any_instance_of(RemoteMirror).to receive(:refresh_remote)
    end

    it 'returns true when a remote mirror is enabled' do
      is_expected.to be_truthy
    end

    it 'returns false when remote mirror is disabled' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
2048
      project.remote_mirrors.first.update(enabled: false)
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077

      is_expected.to be_falsy
    end
  end

  describe '#update_remote_mirrors' do
    let(:project) { create(:project, :remote_mirror, :import_started) }
    delegate :update_remote_mirrors, to: :project

    before do
      allow_any_instance_of(RemoteMirror).to receive(:refresh_remote)
    end

    it 'syncs enabled remote mirror' do
      expect_any_instance_of(RemoteMirror).to receive(:sync)

      update_remote_mirrors
    end

    it 'does nothing when remote mirror is disabled globally and not overridden' do
      stub_application_setting(mirror_available: false)
      project.remote_mirror_available_overridden = false

      expect_any_instance_of(RemoteMirror).not_to receive(:sync)

      update_remote_mirrors
    end

    it 'does not sync disabled remote mirrors' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
2078
      project.remote_mirrors.first.update(enabled: false)
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111

      expect_any_instance_of(RemoteMirror).not_to receive(:sync)

      update_remote_mirrors
    end
  end

  describe '#remote_mirror_available?' do
    let(:project) { create(:project) }

    context 'when remote mirror global setting is enabled' do
      it 'returns true' do
        expect(project.remote_mirror_available?).to be(true)
      end
    end

    context 'when remote mirror global setting is disabled' do
      before do
        stub_application_setting(mirror_available: false)
      end

      it 'returns true when overridden' do
        project.remote_mirror_available_overridden = true

        expect(project.remote_mirror_available?).to be(true)
      end

      it 'returns false when not overridden' do
        expect(project.remote_mirror_available?).to be(false)
      end
    end
  end

2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
  describe '#ancestors_upto', :nested_groups do
    let(:parent) { create(:group) }
    let(:child) { create(:group, parent: parent) }
    let(:child2) { create(:group, parent: child) }
    let(:project) { create(:project, namespace: child2) }

    it 'returns all ancestors when no namespace is given' do
      expect(project.ancestors_upto).to contain_exactly(child2, child, parent)
    end

    it 'includes ancestors upto but excluding the given ancestor' do
      expect(project.ancestors_upto(parent)).to contain_exactly(child2, child)
    end
  end

2127
  describe '#lfs_enabled?' do
2128
    let(:project) { create(:project) }
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188

    shared_examples 'project overrides group' do
      it 'returns true when enabled in project' do
        project.update_attribute(:lfs_enabled, true)

        expect(project.lfs_enabled?).to be_truthy
      end

      it 'returns false when disabled in project' do
        project.update_attribute(:lfs_enabled, false)

        expect(project.lfs_enabled?).to be_falsey
      end

      it 'returns the value from the namespace, when no value is set in project' do
        expect(project.lfs_enabled?).to eq(project.namespace.lfs_enabled?)
      end
    end

    context 'LFS disabled in group' do
      before do
        project.namespace.update_attribute(:lfs_enabled, false)
        enable_lfs
      end

      it_behaves_like 'project overrides group'
    end

    context 'LFS enabled in group' do
      before do
        project.namespace.update_attribute(:lfs_enabled, true)
        enable_lfs
      end

      it_behaves_like 'project overrides group'
    end

    describe 'LFS disabled globally' do
      shared_examples 'it always returns false' do
        it do
          expect(project.lfs_enabled?).to be_falsey
          expect(project.namespace.lfs_enabled?).to be_falsey
        end
      end

      context 'when no values are set' do
        it_behaves_like 'it always returns false'
      end

      context 'when all values are set to true' do
        before do
          project.namespace.update_attribute(:lfs_enabled, true)
          project.update_attribute(:lfs_enabled, true)
        end

        it_behaves_like 'it always returns false'
      end
    end
  end

2189
  describe '#change_head' do
2190
    let(:project) { create(:project, :repository) }
2191

2192 2193 2194 2195 2196
    it 'returns error if branch does not exist' do
      expect(project.change_head('unexisted-branch')).to be false
      expect(project.errors.size).to eq(1)
    end

2197
    it 'calls the before_change_head and after_change_head methods' do
2198
      expect(project.repository).to receive(:before_change_head)
2199 2200
      expect(project.repository).to receive(:after_change_head)

2201 2202 2203
      project.change_head(project.default_branch)
    end

2204
    it 'creates the new reference with rugged' do
2205 2206
      expect(project.repository.raw_repository).to receive(:write_ref).with('HEAD', "refs/heads/#{project.default_branch}", shell: false)

2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
      project.change_head(project.default_branch)
    end

    it 'copies the gitattributes' do
      expect(project.repository).to receive(:copy_gitattributes).with(project.default_branch)
      project.change_head(project.default_branch)
    end

    it 'reloads the default branch' do
      expect(project).to receive(:reload_default_branch)
      project.change_head(project.default_branch)
    end
  end
2220

2221
  context 'forks' do
2222 2223
    include ProjectForksHelper

2224 2225 2226 2227 2228
    let(:project) { create(:project, :public) }
    let!(:forked_project) { fork_project(project) }

    describe '#fork_network' do
      it 'includes a fork of the project' do
2229
        expect(project.fork_network.projects).to include(forked_project)
2230 2231 2232 2233 2234
      end

      it 'includes a fork of a fork' do
        other_fork = fork_project(forked_project)

2235
        expect(project.fork_network.projects).to include(other_fork)
2236 2237 2238 2239 2240
      end

      it 'includes sibling forks' do
        other_fork = fork_project(project)

2241
        expect(forked_project.fork_network.projects).to include(other_fork)
2242 2243 2244
      end

      it 'includes the base project' do
2245
        expect(forked_project.fork_network.projects).to include(project.reload)
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
      end
    end

    describe '#in_fork_network_of?' do
      it 'is true for a real fork' do
        expect(forked_project.in_fork_network_of?(project)).to be_truthy
      end

      it 'is true for a fork of a fork', :postgresql do
        other_fork = fork_project(forked_project)

        expect(other_fork.in_fork_network_of?(project)).to be_truthy
      end

      it 'is true for sibling forks' do
        sibling = fork_project(project)

        expect(sibling.in_fork_network_of?(forked_project)).to be_truthy
      end

      it 'is false when another project is given' do
        other_project = build_stubbed(:project)

        expect(forked_project.in_fork_network_of?(other_project)).to be_falsy
      end
    end
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284

    describe '#fork_source' do
      let!(:second_fork) { fork_project(forked_project) }

      it 'returns the direct source if it exists' do
        expect(second_fork.fork_source).to eq(forked_project)
      end

      it 'returns the root of the fork network when the directs source was deleted' do
        forked_project.destroy

        expect(second_fork.fork_source).to eq(project)
      end
2285 2286 2287 2288

      it 'returns nil if it is the root of the fork network' do
        expect(project.fork_source).to be_nil
      end
2289
    end
2290

2291 2292 2293 2294 2295 2296
    describe '#forks' do
      it 'includes direct forks of the project' do
        expect(project.forks).to contain_exactly(forked_project)
      end
    end

2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
    describe '#lfs_storage_project' do
      it 'returns self for non-forks' do
        expect(project.lfs_storage_project).to eq project
      end

      it 'returns the fork network root for forks' do
        second_fork = fork_project(forked_project)

        expect(second_fork.lfs_storage_project).to eq project
      end

      it 'returns self when fork_source is nil' do
        expect(forked_project).to receive(:fork_source).and_return(nil)

        expect(forked_project.lfs_storage_project).to eq forked_project
      end
    end
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329

    describe '#all_lfs_objects' do
      let(:lfs_object) { create(:lfs_object) }

      before do
        project.lfs_objects << lfs_object
      end

      it 'returns the lfs object for a project' do
        expect(project.all_lfs_objects).to contain_exactly(lfs_object)
      end

      it 'returns the lfs object for a fork' do
        expect(forked_project.all_lfs_objects).to contain_exactly(lfs_object)
      end
    end
2330 2331
  end

2332
  describe '#pushes_since_gc' do
2333
    let(:project) { create(:project) }
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354

    after do
      project.reset_pushes_since_gc
    end

    context 'without any pushes' do
      it 'returns 0' do
        expect(project.pushes_since_gc).to eq(0)
      end
    end

    context 'with a number of pushes' do
      it 'returns the number of pushes' do
        3.times { project.increment_pushes_since_gc }

        expect(project.pushes_since_gc).to eq(3)
      end
    end
  end

  describe '#increment_pushes_since_gc' do
2355
    let(:project) { create(:project) }
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368

    after do
      project.reset_pushes_since_gc
    end

    it 'increments the number of pushes since the last GC' do
      3.times { project.increment_pushes_since_gc }

      expect(project.pushes_since_gc).to eq(3)
    end
  end

  describe '#reset_pushes_since_gc' do
2369
    let(:project) { create(:project) }
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382

    after do
      project.reset_pushes_since_gc
    end

    it 'resets the number of pushes since the last GC' do
      3.times { project.increment_pushes_since_gc }

      project.reset_pushes_since_gc

      expect(project.pushes_since_gc).to eq(0)
    end
  end
2383

2384 2385
  describe '#deployment_variables' do
    context 'when project has no deployment service' do
2386
      let(:project) { create(:project) }
2387 2388 2389 2390 2391 2392 2393

      it 'returns an empty array' do
        expect(project.deployment_variables).to eq []
      end
    end

    context 'when project has a deployment service' do
2394
      shared_examples 'same behavior between KubernetesService and Platform::Kubernetes' do
2395 2396
        it 'returns variables from this service' do
          expect(project.deployment_variables).to include(
2397
            { key: 'KUBE_TOKEN', value: project.deployment_platform.token, public: false }
2398 2399 2400 2401 2402 2403 2404
          )
        end
      end

      context 'when user configured kubernetes from Integration > Kubernetes' do
        let(:project) { create(:kubernetes_project) }

2405
        it_behaves_like 'same behavior between KubernetesService and Platform::Kubernetes'
2406 2407 2408 2409 2410
      end

      context 'when user configured kubernetes from CI/CD > Clusters' do
        let!(:cluster) { create(:cluster, :project, :provided_by_gcp) }
        let(:project) { cluster.project }
2411

2412
        it_behaves_like 'same behavior between KubernetesService and Platform::Kubernetes'
2413 2414 2415 2416
      end
    end
  end

2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
  describe '#default_environment' do
    let(:project) { create(:project) }

    it 'returns production environment when it exists' do
      production = create(:environment, name: "production", project: project)
      create(:environment, name: 'staging', project: project)

      expect(project.default_environment).to eq(production)
    end

    it 'returns first environment when no production environment exists' do
      create(:environment, name: 'staging', project: project)
      create(:environment, name: 'foo', project: project)

      expect(project.default_environment).to eq(project.environments.first)
    end

    it 'returns nil when no available environment exists' do
      expect(project.default_environment).to be_nil
    end
  end

2439
  describe '#ci_variables_for' do
2440
    let(:project) { create(:project) }
2441

2442
    let!(:ci_variable) do
2443 2444 2445 2446 2447 2448 2449
      create(:ci_variable, value: 'secret', project: project)
    end

    let!(:protected_variable) do
      create(:ci_variable, :protected, value: 'protected', project: project)
    end

2450
    subject { project.reload.ci_variables_for(ref: 'ref') }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
2451 2452 2453 2454 2455

    before do
      stub_application_setting(
        default_branch_protection: Gitlab::Access::PROTECTION_NONE)
    end
2456 2457 2458

    shared_examples 'ref is protected' do
      it 'contains all the variables' do
2459
        is_expected.to contain_exactly(ci_variable, protected_variable)
2460 2461 2462 2463
      end
    end

    context 'when the ref is not protected' do
2464 2465
      it 'contains only the CI variables' do
        is_expected.to contain_exactly(ci_variable)
2466 2467 2468
      end
    end

2469 2470
    context 'when the ref is a protected branch' do
      before do
2471
        allow(project).to receive(:protected_for?).with('ref').and_return(true)
2472
      end
2473 2474 2475 2476 2477 2478

      it_behaves_like 'ref is protected'
    end

    context 'when the ref is a protected tag' do
      before do
2479
        allow(project).to receive(:protected_for?).with('ref').and_return(true)
2480 2481 2482
      end

      it_behaves_like 'ref is protected'
2483 2484 2485
    end
  end

2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
  describe '#any_lfs_file_locks?', :request_store do
    set(:project) { create(:project) }

    it 'returns false when there are no LFS file locks' do
      expect(project.any_lfs_file_locks?).to be_falsey
    end

    it 'returns a cached true when there are LFS file locks' do
      create(:lfs_file_lock, project: project)

      expect(project.lfs_file_locks).to receive(:any?).once.and_call_original

      2.times { expect(project.any_lfs_file_locks?).to be_truthy }
    end
  end

2502
  describe '#protected_for?' do
2503
    let(:project) { create(:project) }
2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519

    subject { project.protected_for?('ref') }

    context 'when the ref is not protected' do
      before do
        stub_application_setting(
          default_branch_protection: Gitlab::Access::PROTECTION_NONE)
      end

      it 'returns false' do
        is_expected.to be_falsey
      end
    end

    context 'when the ref is a protected branch' do
      before do
2520 2521
        allow(project).to receive(:repository).and_call_original
        allow(project).to receive_message_chain(:repository, :branch_exists?).and_return(true)
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
        create(:protected_branch, name: 'ref', project: project)
      end

      it 'returns true' do
        is_expected.to be_truthy
      end
    end

    context 'when the ref is a protected tag' do
      before do
2532 2533
        allow(project).to receive_message_chain(:repository, :branch_exists?).and_return(false)
        allow(project).to receive_message_chain(:repository, :tag_exists?).and_return(true)
2534 2535 2536 2537 2538 2539 2540 2541 2542
        create(:protected_tag, name: 'ref', project: project)
      end

      it 'returns true' do
        is_expected.to be_truthy
      end
    end
  end

2543
  describe '#update_project_statistics' do
2544
    let(:project) { create(:project) }
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562

    it "is called after creation" do
      expect(project.statistics).to be_a ProjectStatistics
      expect(project.statistics).to be_persisted
    end

    it "copies the namespace_id" do
      expect(project.statistics.namespace_id).to eq project.namespace_id
    end

    it "updates the namespace_id when changed" do
      namespace = create(:namespace)
      project.update(namespace: namespace)

      expect(project.statistics.namespace_id).to eq namespace.id
    end
  end

2563
  describe 'inside_path' do
2564 2565 2566
    let!(:project1) { create(:project, namespace: create(:namespace, path: 'name_pace')) }
    let!(:project2) { create(:project) }
    let!(:project3) { create(:project, namespace: create(:namespace, path: 'namespace')) }
2567
    let!(:path) { project1.namespace.full_path }
2568

2569
    it 'returns correct project' do
2570
      expect(described_class.inside_path(path)).to eq([project1])
2571
    end
2572 2573
  end

Douwe Maan's avatar
Douwe Maan committed
2574
  describe '#route_map_for' do
2575
    let(:project) { create(:project, :repository) }
Douwe Maan's avatar
Douwe Maan committed
2576 2577 2578 2579 2580 2581 2582 2583
    let(:route_map) do
      <<-MAP.strip_heredoc
      - source: /source/(.*)/
        public: '\\1'
      MAP
    end

    before do
2584
      project.repository.create_file(User.last, '.gitlab/route-map.yml', route_map, message: 'Add .gitlab/route-map.yml', branch_name: 'master')
Douwe Maan's avatar
Douwe Maan committed
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
    end

    context 'when there is a .gitlab/route-map.yml at the commit' do
      context 'when the route map is valid' do
        it 'returns a route map' do
          map = project.route_map_for(project.commit.sha)
          expect(map).to be_a_kind_of(Gitlab::RouteMap)
        end
      end

      context 'when the route map is invalid' do
        let(:route_map) { 'INVALID' }

        it 'returns nil' do
          expect(project.route_map_for(project.commit.sha)).to be_nil
        end
      end
    end

    context 'when there is no .gitlab/route-map.yml at the commit' do
      it 'returns nil' do
        expect(project.route_map_for(project.commit.parent.sha)).to be_nil
      end
    end
  end

  describe '#public_path_for_source_path' do
2612
    let(:project) { create(:project, :repository) }
Douwe Maan's avatar
Douwe Maan committed
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
    let(:route_map) do
      Gitlab::RouteMap.new(<<-MAP.strip_heredoc)
        - source: /source/(.*)/
          public: '\\1'
      MAP
    end
    let(:sha) { project.commit.id }

    context 'when there is a route map' do
      before do
        allow(project).to receive(:route_map_for).with(sha).and_return(route_map)
      end

      context 'when the source path is mapped' do
        it 'returns the public path' do
          expect(project.public_path_for_source_path('source/file.html', sha)).to eq('file.html')
        end
      end

      context 'when the source path is not mapped' do
        it 'returns nil' do
          expect(project.public_path_for_source_path('file.html', sha)).to be_nil
        end
      end
    end

    context 'when there is no route map' do
      before do
        allow(project).to receive(:route_map_for).with(sha).and_return(nil)
      end

      it 'returns nil' do
        expect(project.public_path_for_source_path('source/file.html', sha)).to be_nil
      end
    end
  end

2650
  describe '#parent' do
2651
    let(:project) { create(:project) }
2652 2653 2654 2655

    it { expect(project.parent).to eq(project.namespace) }
  end

2656 2657 2658 2659 2660 2661
  describe '#parent_id' do
    let(:project) { create(:project) }

    it { expect(project.parent_id).to eq(project.namespace_id) }
  end

2662
  describe '#parent_changed?' do
2663
    let(:project) { create(:project) }
2664

2665 2666 2667
    before do
      project.namespace_id = 7
    end
2668 2669 2670 2671

    it { expect(project.parent_changed?).to be_truthy }
  end

2672 2673 2674
  def enable_lfs
    allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
  end
2675

2676
  describe '#pages_url' do
2677 2678
    let(:group) { create(:group, name: 'Group') }
    let(:nested_group) { create(:group, parent: group) }
2679 2680 2681 2682 2683 2684 2685 2686 2687
    let(:domain) { 'Example.com' }

    subject { project.pages_url }

    before do
      allow(Settings.pages).to receive(:host).and_return(domain)
      allow(Gitlab.config.pages).to receive(:url).and_return('http://example.com')
    end

2688
    context 'top-level group' do
2689
      let(:project) { create(:project, namespace: group, name: project_name) }
2690

2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
      context 'group page' do
        let(:project_name) { 'group.example.com' }

        it { is_expected.to eq("http://group.example.com") }
      end

      context 'project page' do
        let(:project_name) { 'Project' }

        it { is_expected.to eq("http://group.example.com/project") }
      end
2702 2703
    end

2704
    context 'nested group' do
2705
      let(:project) { create(:project, namespace: nested_group, name: project_name) }
2706
      let(:expected_url) { "http://group.example.com/#{nested_group.path}/#{project.path}" }
2707

2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
      context 'group page' do
        let(:project_name) { 'group.example.com' }

        it { is_expected.to eq(expected_url) }
      end

      context 'project page' do
        let(:project_name) { 'Project' }

        it { is_expected.to eq(expected_url) }
      end
2719 2720
    end
  end
2721 2722

  describe '#http_url_to_repo' do
2723
    let(:project) { create(:project) }
2724

2725 2726 2727
    it 'returns the url to the repo without a username' do
      expect(project.http_url_to_repo).to eq("#{project.web_url}.git")
      expect(project.http_url_to_repo).not_to include('@')
2728 2729
    end
  end
2730 2731

  describe '#pipeline_status' do
2732
    let(:project) { create(:project, :repository) }
2733
    it 'builds a pipeline status' do
2734
      expect(project.pipeline_status).to be_a(Gitlab::Cache::Ci::ProjectPipelineStatus)
2735 2736 2737 2738 2739 2740
    end

    it 'hase a loaded pipeline status' do
      expect(project.pipeline_status).to be_loaded
    end
  end
2741 2742

  describe '#append_or_update_attribute' do
2743
    let(:project) { create(:project) }
2744 2745 2746 2747 2748

    it 'shows full error updating an invalid MR' do
      error_message = 'Failed to replace merge_requests because one or more of the new records could not be saved.'\
                      ' Validate fork Source project is not a fork of the target project'

2749 2750
      expect { project.append_or_update_attribute(:merge_requests, [create(:merge_request)]) }
        .to raise_error(ActiveRecord::RecordNotSaved, error_message)
2751 2752
    end

2753
    it 'updates the project successfully' do
2754 2755
      merge_request = create(:merge_request, target_project: project, source_project: project)

2756 2757
      expect { project.append_or_update_attribute(:merge_requests, [merge_request]) }
        .not_to raise_error
2758 2759
    end
  end
2760 2761 2762

  describe '#last_repository_updated_at' do
    it 'sets to created_at upon creation' do
2763
      project = create(:project, created_at: 2.hours.ago)
2764 2765 2766 2767

      expect(project.last_repository_updated_at.to_i).to eq(project.created_at.to_i)
    end
  end
2768 2769 2770 2771 2772

  describe '.public_or_visible_to_user' do
    let!(:user) { create(:user) }

    let!(:private_project) do
2773
      create(:project, :private, creator: user, namespace: user.namespace)
2774 2775
    end

2776
    let!(:public_project) { create(:project, :public) }
2777 2778 2779

    context 'with a user' do
      let(:projects) do
2780
        described_class.all.public_or_visible_to_user(user)
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
      end

      it 'includes projects the user has access to' do
        expect(projects).to include(private_project)
      end

      it 'includes projects the user can see' do
        expect(projects).to include(public_project)
      end
    end

    context 'without a user' do
      it 'only includes public projects' do
2794
        projects = described_class.all.public_or_visible_to_user
2795 2796 2797 2798 2799

        expect(projects).to eq([public_project])
      end
    end
  end
2800

2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
  describe '#pages_available?' do
    let(:project) { create(:project, group: group) }

    subject { project.pages_available? }

    before do
      allow(Gitlab.config.pages).to receive(:enabled).and_return(true)
    end

    context 'when the project is in a top level namespace' do
      let(:group) { create(:group) }

      it { is_expected.to be(true) }
    end

    context 'when the project is in a subgroup' do
      let(:group) { create(:group, :nested) }

      it { is_expected.to be(false) }
    end
  end

2823
  describe '#remove_private_deploy_keys' do
2824
    let!(:project) { create(:project) }
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839

    context 'for a private deploy key' do
      let!(:key) { create(:deploy_key, public: false) }
      let!(:deploy_keys_project) { create(:deploy_keys_project, deploy_key: key, project: project) }

      context 'when the key is not linked to another project' do
        it 'removes the key' do
          project.remove_private_deploy_keys

          expect(project.deploy_keys).not_to include(key)
        end
      end

      context 'when the key is linked to another project' do
        before do
2840
          another_project = create(:project)
2841 2842
          create(:deploy_keys_project, deploy_key: key, project: another_project)
        end
2843

2844 2845
        it 'does not remove the key' do
          project.remove_private_deploy_keys
2846

2847 2848 2849 2850 2851 2852 2853 2854
          expect(project.deploy_keys).to include(key)
        end
      end
    end

    context 'for a public deploy key' do
      let!(:key) { create(:deploy_key, public: true) }
      let!(:deploy_keys_project) { create(:deploy_keys_project, deploy_key: key, project: project) }
2855

2856 2857
      it 'does not remove the key' do
        project.remove_private_deploy_keys
2858

2859 2860
        expect(project.deploy_keys).to include(key)
      end
2861 2862
    end
  end
2863

2864 2865
  describe '#remove_pages' do
    let(:project) { create(:project) }
2866
    let(:namespace) { project.namespace }
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877
    let(:pages_path) { project.pages_path }

    around do |example|
      FileUtils.mkdir_p(pages_path)
      begin
        example.run
      ensure
        FileUtils.rm_rf(pages_path)
      end
    end

2878 2879 2880 2881 2882 2883 2884 2885
    it 'removes the pages directory' do
      expect_any_instance_of(Projects::UpdatePagesConfigurationService).to receive(:execute)
      expect_any_instance_of(Gitlab::PagesTransfer).to receive(:rename_project).and_return(true)
      expect(PagesWorker).to receive(:perform_in).with(5.minutes, :remove, namespace.full_path, anything)

      project.remove_pages
    end

2886
    it 'is a no-op when there is no namespace' do
2887 2888
      project.namespace.delete
      project.reload
2889 2890 2891 2892 2893 2894

      expect_any_instance_of(Projects::UpdatePagesConfigurationService).not_to receive(:execute)
      expect_any_instance_of(Gitlab::PagesTransfer).not_to receive(:rename_project)

      project.remove_pages
    end
2895 2896 2897 2898 2899 2900

    it 'is run when the project is destroyed' do
      expect(project).to receive(:remove_pages).and_call_original

      project.destroy
    end
2901 2902
  end

2903
  describe '#remove_export' do
2904 2905
    let(:project) { create(:project, :with_export) }

2906
    it 'removes the export' do
2907 2908
      project.remove_exports

2909
      expect(project.export_file_exists?).to be_falsey
2910 2911 2912
    end
  end

2913 2914 2915 2916
  describe '#forks_count' do
    it 'returns the number of forks' do
      project = build(:project)

Francisco Lopez's avatar
Francisco Lopez committed
2917
      expect_any_instance_of(Projects::ForksCountService).to receive(:count).and_return(1)
2918 2919 2920 2921

      expect(project.forks_count).to eq(1)
    end
  end
2922 2923

  context 'legacy storage' do
2924
    let(:project) { create(:project, :repository, :legacy_storage) }
2925
    let(:gitlab_shell) { Gitlab::Shell.new }
2926
    let(:project_storage) { project.send(:storage) }
2927

2928 2929 2930 2931
    before do
      allow(project).to receive(:gitlab_shell).and_return(gitlab_shell)
    end

2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
    describe '#base_dir' do
      it 'returns base_dir based on namespace only' do
        expect(project.base_dir).to eq(project.namespace.full_path)
      end
    end

    describe '#disk_path' do
      it 'returns disk_path based on namespace and project path' do
        expect(project.disk_path).to eq("#{project.namespace.full_path}/#{project.path}")
      end
    end

2944
    describe '#ensure_storage_path_exists' do
2945
      it 'delegates to gitlab_shell to ensure namespace is created' do
2946
        expect(gitlab_shell).to receive(:add_namespace).with(project.repository_storage, project.base_dir)
2947

2948
        project.ensure_storage_path_exists
2949 2950 2951
      end
    end

2952 2953
    describe '#legacy_storage?' do
      it 'returns true when storage_version is nil' do
2954
        project = build(:project, storage_version: nil)
2955 2956 2957

        expect(project.legacy_storage?).to be_truthy
      end
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967

      it 'returns true when the storage_version is 0' do
        project = build(:project, storage_version: 0)

        expect(project.legacy_storage?).to be_truthy
      end
    end

    describe '#hashed_storage?' do
      it 'returns false' do
2968
        expect(project.hashed_storage?(:repository)).to be_falsey
2969
      end
2970 2971
    end

2972 2973 2974 2975 2976
    describe '#pages_path' do
      it 'returns a path where pages are stored' do
        expect(project.pages_path).to eq(File.join(Settings.pages.path, project.namespace.full_path, project.path))
      end
    end
2977 2978 2979 2980 2981 2982

    describe '#migrate_to_hashed_storage!' do
      it 'returns true' do
        expect(project.migrate_to_hashed_storage!).to be_truthy
      end

2983
      it 'flags as read-only' do
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
        expect { project.migrate_to_hashed_storage! }.to change { project.repository_read_only }.to(true)
      end

      it 'schedules ProjectMigrateHashedStorageWorker with delayed start when the project repo is in use' do
        Gitlab::ReferenceCounter.new(project.gl_repository(is_wiki: false)).increase

        expect(ProjectMigrateHashedStorageWorker).to receive(:perform_in)

        project.migrate_to_hashed_storage!
      end

      it 'schedules ProjectMigrateHashedStorageWorker with delayed start when the wiki repo is in use' do
        Gitlab::ReferenceCounter.new(project.gl_repository(is_wiki: true)).increase

        expect(ProjectMigrateHashedStorageWorker).to receive(:perform_in)

        project.migrate_to_hashed_storage!
      end

      it 'schedules ProjectMigrateHashedStorageWorker' do
        expect(ProjectMigrateHashedStorageWorker).to receive(:perform_async).with(project.id)

        project.migrate_to_hashed_storage!
      end
    end
3009 3010 3011
  end

  context 'hashed storage' do
3012
    let(:project) { create(:project, :repository, skip_disk_validation: true) }
3013
    let(:gitlab_shell) { Gitlab::Shell.new }
3014
    let(:hash) { Digest::SHA2.hexdigest(project.id.to_s) }
3015 3016
    let(:hashed_prefix) { File.join('@hashed', hash[0..1], hash[2..3]) }
    let(:hashed_path) { File.join(hashed_prefix, hash) }
3017 3018

    before do
3019
      stub_application_setting(hashed_storage_enabled: true)
3020 3021
    end

3022 3023 3024 3025 3026 3027 3028
    describe '#legacy_storage?' do
      it 'returns false' do
        expect(project.legacy_storage?).to be_falsey
      end
    end

    describe '#hashed_storage?' do
3029 3030
      it 'returns true if rolled out' do
        expect(project.hashed_storage?(:attachments)).to be_truthy
3031 3032
      end

3033 3034
      it 'returns false when not rolled out yet' do
        project.storage_version = 1
3035

3036
        expect(project.hashed_storage?(:attachments)).to be_falsey
3037 3038 3039
      end
    end

3040 3041
    describe '#base_dir' do
      it 'returns base_dir based on hash of project id' do
3042
        expect(project.base_dir).to eq(hashed_prefix)
3043 3044 3045 3046
      end
    end

    describe '#disk_path' do
3047
      it 'returns disk_path based on hash of project id' do
3048 3049 3050 3051
        expect(project.disk_path).to eq(hashed_path)
      end
    end

3052
    describe '#ensure_storage_path_exists' do
3053
      it 'delegates to gitlab_shell to ensure namespace is created' do
3054 3055
        allow(project).to receive(:gitlab_shell).and_return(gitlab_shell)

3056
        expect(gitlab_shell).to receive(:add_namespace).with(project.repository_storage, hashed_prefix)
3057

3058
        project.ensure_storage_path_exists
3059 3060 3061
      end
    end

3062 3063 3064 3065 3066
    describe '#pages_path' do
      it 'returns a path where pages are stored' do
        expect(project.pages_path).to eq(File.join(Settings.pages.path, project.namespace.full_path, project.path))
      end
    end
3067 3068 3069 3070 3071 3072

    describe '#migrate_to_hashed_storage!' do
      it 'returns nil' do
        expect(project.migrate_to_hashed_storage!).to be_nil
      end

3073
      it 'does not flag as read-only' do
3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086
        expect { project.migrate_to_hashed_storage! }.not_to change { project.repository_read_only }
      end
    end
  end

  describe '#gl_repository' do
    let(:project) { create(:project) }

    it 'delegates to Gitlab::GlRepository.gl_repository' do
      expect(Gitlab::GlRepository).to receive(:gl_repository).with(project, true)

      project.gl_repository(is_wiki: true)
    end
3087
  end
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111

  describe '#has_ci?' do
    set(:project) { create(:project) }
    let(:repository) { double }

    before do
      expect(project).to receive(:repository) { repository }
    end

    context 'when has .gitlab-ci.yml' do
      before do
        expect(repository).to receive(:gitlab_ci_yml) { 'content' }
      end

      it "CI is available" do
        expect(project).to have_ci
      end
    end

    context 'when there is no .gitlab-ci.yml' do
      before do
        expect(repository).to receive(:gitlab_ci_yml) { nil }
      end

3112 3113
      it "CI is available" do
        expect(project).to have_ci
3114 3115
      end

3116
      context 'when auto devops is disabled' do
3117
        before do
3118
          stub_application_setting(auto_devops_enabled: false)
3119 3120
        end

3121 3122
        it "CI is not available" do
          expect(project).not_to have_ci
3123 3124 3125 3126 3127 3128
        end
      end
    end
  end

  describe '#auto_devops_enabled?' do
3129 3130 3131 3132 3133
    before do
      allow(Feature).to receive(:enabled?).and_call_original
      Feature.get(:force_autodevops_on_by_default).enable_percentage_of_actors(0)
    end

3134 3135 3136 3137 3138 3139 3140 3141 3142
    set(:project) { create(:project) }

    subject { project.auto_devops_enabled? }

    context 'when enabled in settings' do
      before do
        stub_application_setting(auto_devops_enabled: true)
      end

3143
      it { is_expected.to be_truthy }
3144 3145 3146 3147 3148 3149

      context 'when explicitly enabled' do
        before do
          create(:project_auto_devops, project: project)
        end

3150
        it { is_expected.to be_truthy }
3151 3152 3153 3154 3155 3156 3157
      end

      context 'when explicitly disabled' do
        before do
          create(:project_auto_devops, project: project, enabled: false)
        end

3158
        it { is_expected.to be_falsey }
3159 3160 3161 3162 3163 3164 3165 3166
      end
    end

    context 'when disabled in settings' do
      before do
        stub_application_setting(auto_devops_enabled: false)
      end

3167
      it { is_expected.to be_falsey }
3168 3169 3170 3171 3172 3173

      context 'when explicitly enabled' do
        before do
          create(:project_auto_devops, project: project)
        end

3174 3175 3176 3177 3178 3179
        it { is_expected.to be_truthy }
      end

      context 'when force_autodevops_on_by_default is enabled for the project' do
        before do
          Feature.get(:force_autodevops_on_by_default).enable_percentage_of_actors(100)
3180
        end
3181 3182

        it { is_expected.to be_truthy }
3183 3184 3185 3186
      end
    end
  end

3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
  describe '#has_auto_devops_implicitly_enabled?' do
    set(:project) { create(:project) }

    context 'when disabled in settings' do
      before do
        stub_application_setting(auto_devops_enabled: false)
      end

      it 'does not have auto devops implicitly disabled' do
        expect(project).not_to have_auto_devops_implicitly_enabled
      end
    end

    context 'when enabled in settings' do
      before do
        stub_application_setting(auto_devops_enabled: true)
      end

      it 'auto devops is implicitly disabled' do
        expect(project).to have_auto_devops_implicitly_enabled
      end

      context 'when explicitly disabled' do
        before do
          create(:project_auto_devops, project: project, enabled: false)
        end

        it 'does not have auto devops implicitly disabled' do
          expect(project).not_to have_auto_devops_implicitly_enabled
        end
      end

      context 'when explicitly enabled' do
        before do
          create(:project_auto_devops, project: project, enabled: true)
        end

        it 'does not have auto devops implicitly disabled' do
          expect(project).not_to have_auto_devops_implicitly_enabled
        end
      end
    end
  end

3231
  describe '#has_auto_devops_implicitly_disabled?' do
3232 3233 3234 3235 3236
    before do
      allow(Feature).to receive(:enabled?).and_call_original
      Feature.get(:force_autodevops_on_by_default).enable_percentage_of_actors(0)
    end

3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
    set(:project) { create(:project) }

    context 'when enabled in settings' do
      before do
        stub_application_setting(auto_devops_enabled: true)
      end

      it 'does not have auto devops implicitly disabled' do
        expect(project).not_to have_auto_devops_implicitly_disabled
      end
    end

    context 'when disabled in settings' do
      before do
        stub_application_setting(auto_devops_enabled: false)
      end

      it 'auto devops is implicitly disabled' do
        expect(project).to have_auto_devops_implicitly_disabled
      end

3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
      context 'when force_autodevops_on_by_default is enabled for the project' do
        before do
          Feature.get(:force_autodevops_on_by_default).enable_percentage_of_actors(100)
        end

        it 'does not have auto devops implicitly disabled' do
          expect(project).not_to have_auto_devops_implicitly_disabled
        end
      end

3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
      context 'when explicitly disabled' do
        before do
          create(:project_auto_devops, project: project, enabled: false)
        end

        it 'does not have auto devops implicitly disabled' do
          expect(project).not_to have_auto_devops_implicitly_disabled
        end
      end

      context 'when explicitly enabled' do
        before do
3280
          create(:project_auto_devops, project: project, enabled: true)
3281 3282 3283 3284 3285 3286 3287 3288 3289
        end

        it 'does not have auto devops implicitly disabled' do
          expect(project).not_to have_auto_devops_implicitly_disabled
        end
      end
    end
  end

3290 3291 3292 3293 3294
  context '#auto_devops_variables' do
    set(:project) { create(:project) }

    subject { project.auto_devops_variables }

3295
    context 'when enabled in instance settings' do
3296 3297 3298 3299
      before do
        stub_application_setting(auto_devops_enabled: true)
      end

3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
      context 'when domain is empty' do
        before do
          stub_application_setting(auto_devops_domain: nil)
        end

        it 'variables does not include AUTO_DEVOPS_DOMAIN' do
          is_expected.not_to include(domain_variable)
        end
      end

      context 'when domain is configured' do
        before do
          stub_application_setting(auto_devops_domain: 'example.com')
        end

        it 'variables includes AUTO_DEVOPS_DOMAIN' do
          is_expected.to include(domain_variable)
        end
      end
    end

3321
    context 'when explicitly enabled' do
3322 3323 3324 3325 3326
      context 'when domain is empty' do
        before do
          create(:project_auto_devops, project: project, domain: nil)
        end

3327 3328
        it 'variables does not include AUTO_DEVOPS_DOMAIN' do
          is_expected.not_to include(domain_variable)
3329 3330 3331 3332 3333 3334 3335 3336
        end
      end

      context 'when domain is configured' do
        before do
          create(:project_auto_devops, project: project, domain: 'example.com')
        end

3337 3338
        it 'variables includes AUTO_DEVOPS_DOMAIN' do
          is_expected.to include(domain_variable)
3339 3340 3341
        end
      end
    end
3342 3343 3344 3345

    def domain_variable
      { key: 'AUTO_DEVOPS_DOMAIN', value: 'example.com', public: true }
    end
3346
  end
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381

  describe '#latest_successful_builds_for' do
    let(:project) { build(:project) }

    before do
      allow(project).to receive(:default_branch).and_return('master')
    end

    context 'without a ref' do
      it 'returns a pipeline for the default branch' do
        expect(project)
          .to receive(:latest_successful_pipeline_for_default_branch)

        project.latest_successful_pipeline_for
      end
    end

    context 'with the ref set to the default branch' do
      it 'returns a pipeline for the default branch' do
        expect(project)
          .to receive(:latest_successful_pipeline_for_default_branch)

        project.latest_successful_pipeline_for(project.default_branch)
      end
    end

    context 'with a ref that is not the default branch' do
      it 'returns the latest successful pipeline for the given ref' do
        expect(project.pipelines).to receive(:latest_successful_for).with('foo')

        project.latest_successful_pipeline_for('foo')
      end
    end
  end

3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
  describe '#check_repository_path_availability' do
    let(:project) { build(:project) }

    it 'skips gitlab-shell exists?' do
      project.skip_disk_validation = true

      expect(project.gitlab_shell).not_to receive(:exists?)
      expect(project.check_repository_path_availability).to be_truthy
    end
  end

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
  describe '#latest_successful_pipeline_for_default_branch' do
    let(:project) { build(:project) }

    before do
      allow(project).to receive(:default_branch).and_return('master')
    end

    it 'memoizes and returns the latest successful pipeline for the default branch' do
      pipeline = double(:pipeline)

      expect(project.pipelines).to receive(:latest_successful_for)
        .with(project.default_branch)
        .and_return(pipeline)
        .once

      2.times do
        expect(project.latest_successful_pipeline_for_default_branch)
          .to eq(pipeline)
      end
    end
  end
3414 3415

  describe '#after_import' do
3416
    let(:project) { create(:project) }
3417 3418 3419

    it 'runs the correct hooks' do
      expect(project.repository).to receive(:after_import)
3420
      expect(project.wiki.repository).to receive(:after_import)
3421 3422 3423
      expect(project).to receive(:import_finish)
      expect(project).to receive(:update_project_counter_caches)
      expect(project).to receive(:remove_import_jid)
3424
      expect(project).to receive(:after_create_default_branch)
3425
      expect(project).to receive(:refresh_markdown_cache!)
3426 3427 3428

      project.after_import
    end
3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465

    context 'branch protection' do
      let(:project) { create(:project, :repository) }

      it 'does not protect when branch protection is disabled' do
        stub_application_setting(default_branch_protection: Gitlab::Access::PROTECTION_NONE)

        project.after_import

        expect(project.protected_branches).to be_empty
      end

      it "gives developer access to push when branch protection is set to 'developers can push'" do
        stub_application_setting(default_branch_protection: Gitlab::Access::PROTECTION_DEV_CAN_PUSH)

        project.after_import

        expect(project.protected_branches).not_to be_empty
        expect(project.default_branch).to eq(project.protected_branches.first.name)
        expect(project.protected_branches.first.push_access_levels.map(&:access_level)).to eq([Gitlab::Access::DEVELOPER])
      end

      it "gives developer access to merge when branch protection is set to 'developers can merge'" do
        stub_application_setting(default_branch_protection: Gitlab::Access::PROTECTION_DEV_CAN_MERGE)

        project.after_import

        expect(project.protected_branches).not_to be_empty
        expect(project.default_branch).to eq(project.protected_branches.first.name)
        expect(project.protected_branches.first.merge_access_levels.map(&:access_level)).to eq([Gitlab::Access::DEVELOPER])
      end

      it 'protects default branch' do
        project.after_import

        expect(project.protected_branches).not_to be_empty
        expect(project.default_branch).to eq(project.protected_branches.first.name)
3466 3467
        expect(project.protected_branches.first.push_access_levels.map(&:access_level)).to eq([Gitlab::Access::MAINTAINER])
        expect(project.protected_branches.first.merge_access_levels.map(&:access_level)).to eq([Gitlab::Access::MAINTAINER])
3468 3469
      end
    end
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
  end

  describe '#update_project_counter_caches' do
    let(:project) { create(:project) }

    it 'updates all project counter caches' do
      expect_any_instance_of(Projects::OpenIssuesCountService)
        .to receive(:refresh_cache)
        .and_call_original

      expect_any_instance_of(Projects::OpenMergeRequestsCountService)
        .to receive(:refresh_cache)
        .and_call_original

      project.update_project_counter_caches
    end
  end

  describe '#remove_import_jid', :clean_gitlab_redis_cache do
    let(:project) {  }

    context 'without an import JID' do
      it 'does nothing' do
        project = create(:project)

        expect(Gitlab::SidekiqStatus)
          .not_to receive(:unset)

        project.remove_import_jid
      end
    end

    context 'with an import JID' do
      it 'unsets the import JID' do
3504 3505
        project = create(:project)
        create(:import_state, project: project, jid: '123')
3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531

        expect(Gitlab::SidekiqStatus)
          .to receive(:unset)
          .with('123')
          .and_call_original

        project.remove_import_jid

        expect(project.import_jid).to be_nil
      end
    end
  end

  describe '#wiki_repository_exists?' do
    it 'returns true when the wiki repository exists' do
      project = create(:project, :wiki_repo)

      expect(project.wiki_repository_exists?).to eq(true)
    end

    it 'returns false when the wiki repository does not exist' do
      project = create(:project)

      expect(project.wiki_repository_exists?).to eq(false)
    end
  end
3532

3533 3534 3535 3536 3537 3538
  describe '#write_repository_config' do
    set(:project) { create(:project, :repository) }

    it 'writes full path in .git/config when key is missing' do
      project.write_repository_config

3539
      expect(rugged_config['gitlab.fullpath']).to eq project.full_path
3540 3541 3542 3543 3544
    end

    it 'updates full path in .git/config when key is present' do
      project.write_repository_config(gl_full_path: 'old/path')

3545
      expect { project.write_repository_config }.to change { rugged_config['gitlab.fullpath'] }.from('old/path').to(project.full_path)
3546 3547 3548 3549 3550 3551 3552 3553
    end

    it 'does not raise an error with an empty repository' do
      project = create(:project_empty_repo)

      expect { project.write_repository_config }.not_to raise_error
    end
  end
3554 3555

  describe '#execute_hooks' do
3556
    let(:data) { { ref: 'refs/heads/master', data: 'data' } }
3557
    it 'executes active projects hooks with the specified scope' do
3558 3559 3560 3561
      hook = create(:project_hook, merge_requests_events: false, push_events: true)
      expect(ProjectHook).to receive(:select_active)
        .with(:push_hooks, data)
        .and_return([hook])
3562
      project = create(:project, hooks: [hook])
3563 3564 3565

      expect_any_instance_of(ProjectHook).to receive(:async_execute).once

3566
      project.execute_hooks(data, :push_hooks)
3567 3568 3569
    end

    it 'does not execute project hooks that dont match the specified scope' do
3570
      hook = create(:project_hook, merge_requests_events: true, push_events: false)
3571 3572 3573 3574
      project = create(:project, hooks: [hook])

      expect_any_instance_of(ProjectHook).not_to receive(:async_execute).once

3575
      project.execute_hooks(data, :push_hooks)
3576 3577
    end

3578
    it 'does not execute project hooks which are not active' do
3579 3580 3581 3582
      hook = create(:project_hook, push_events: true)
      expect(ProjectHook).to receive(:select_active)
        .with(:push_hooks, data)
        .and_return([])
3583 3584 3585 3586
      project = create(:project, hooks: [hook])

      expect_any_instance_of(ProjectHook).not_to receive(:async_execute).once

3587
      project.execute_hooks(data, :push_hooks)
3588 3589 3590
    end

    it 'executes the system hooks with the specified scope' do
3591
      expect_any_instance_of(SystemHooksService).to receive(:execute_hooks).with(data, :merge_request_hooks)
3592

3593
      project = build(:project)
3594
      project.execute_hooks(data, :merge_request_hooks)
3595
    end
3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608

    it 'executes the system hooks when inside a transaction' do
      allow_any_instance_of(WebHookService).to receive(:execute)

      create(:system_hook, merge_requests_events: true)

      project = build(:project)

      # Ideally, we'd test that `WebHookWorker.jobs.size` increased by 1,
      # but since the entire spec run takes place in a transaction, we never
      # actually get to the `after_commit` hook that queues these jobs.
      expect do
        project.transaction do
3609
          project.execute_hooks(data, :merge_request_hooks)
3610 3611 3612
        end
      end.not_to raise_error # Sidekiq::Worker::EnqueueFromTransactionError
    end
3613
  end
3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645

  describe '#badges' do
    let(:project_group) { create(:group) }
    let(:project) {  create(:project, path: 'avatar', namespace: project_group) }

    before do
      create_list(:project_badge, 2, project: project)
      create(:group_badge, group: project_group)
    end

    it 'returns the project and the project group badges' do
      create(:group_badge, group: create(:group))

      expect(Badge.count).to eq 4
      expect(project.badges.count).to eq 3
    end

    if Group.supports_nested_groups?
      context 'with nested_groups' do
        let(:parent_group) { create(:group) }

        before do
          create_list(:group_badge, 2, group: project_group)
          project_group.update(parent: parent_group)
        end

        it 'returns the project and the project nested groups badges' do
          expect(project.badges.count).to eq 5
        end
      end
    end
  end
3646

3647 3648
  context 'with cross project merge requests' do
    let(:user) { create(:user) }
3649 3650
    let(:target_project) { create(:project, :repository) }
    let(:project) { fork_project(target_project, nil, repository: true) }
3651 3652 3653 3654
    let!(:merge_request) do
      create(
        :merge_request,
        target_project: target_project,
3655
        target_branch: 'target-branch',
3656 3657
        source_project: project,
        source_branch: 'awesome-feature-1',
3658
        allow_collaboration: true
3659 3660 3661 3662
      )
    end

    before do
3663
      target_project.add_developer(user)
3664 3665
    end

3666 3667 3668 3669
    describe '#merge_requests_allowing_push_to_user' do
      it 'returns open merge requests for which the user has developer access to the target project' do
        expect(project.merge_requests_allowing_push_to_user(user)).to include(merge_request)
      end
3670

3671 3672
      it 'does not include closed merge requests' do
        merge_request.close
3673

3674 3675 3676 3677 3678 3679
        expect(project.merge_requests_allowing_push_to_user(user)).to be_empty
      end

      it 'does not include merge requests for guest users' do
        guest = create(:user)
        target_project.add_guest(guest)
3680

3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692
        expect(project.merge_requests_allowing_push_to_user(guest)).to be_empty
      end

      it 'does not include the merge request for other users' do
        other_user = create(:user)

        expect(project.merge_requests_allowing_push_to_user(other_user)).to be_empty
      end

      it 'is empty when no user is passed' do
        expect(project.merge_requests_allowing_push_to_user(nil)).to be_empty
      end
3693 3694
    end

3695
    describe '#branch_allows_collaboration_push?' do
3696
      it 'allows access if the user can merge the merge request' do
3697
        expect(project.branch_allows_collaboration?(user, 'awesome-feature-1'))
3698 3699 3700
          .to be_truthy
      end

3701 3702 3703 3704 3705
      it 'allows access when there are merge requests open but no branch name is given' do
        expect(project.branch_allows_collaboration?(user, nil))
          .to be_truthy
      end

3706 3707 3708 3709
      it 'does not allow guest users access' do
        guest = create(:user)
        target_project.add_guest(guest)

3710
        expect(project.branch_allows_collaboration?(guest, 'awesome-feature-1'))
3711 3712 3713
          .to be_falsy
      end

3714
      it 'does not allow access to branches for which the merge request was closed' do
3715 3716
        create(:merge_request, :closed,
               target_project: target_project,
3717
               target_branch: 'target-branch',
3718 3719
               source_project: project,
               source_branch: 'rejected-feature-1',
3720
               allow_collaboration: true)
3721

3722
        expect(project.branch_allows_collaboration?(user, 'rejected-feature-1'))
3723 3724 3725
          .to be_falsy
      end

3726
      it 'does not allow access if the user cannot merge the merge request' do
3727
        create(:protected_branch, :maintainers_can_push, project: target_project, name: 'target-branch')
3728

3729
        expect(project.branch_allows_collaboration?(user, 'awesome-feature-1'))
3730 3731 3732 3733
          .to be_falsy
      end

      it 'caches the result' do
3734
        control = ActiveRecord::QueryRecorder.new { project.branch_allows_collaboration?(user, 'awesome-feature-1') }
3735

3736
        expect { 3.times { project.branch_allows_collaboration?(user, 'awesome-feature-1') } }
3737
          .not_to exceed_query_limit(control)
3738 3739 3740
      end

      context 'when the requeststore is active', :request_store do
3741
        it 'only queries per project across instances' do
3742
          control = ActiveRecord::QueryRecorder.new { project.branch_allows_collaboration?(user, 'awesome-feature-1') }
3743

3744
          expect { 2.times { described_class.find(project.id).branch_allows_collaboration?(user, 'awesome-feature-1') } }
3745
            .not_to exceed_query_limit(control).with_threshold(2)
3746
        end
3747 3748 3749
      end
    end
  end
Rob Watson's avatar
Rob Watson committed
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794

  describe "#pages_https_only?" do
    subject { build(:project) }

    context "when HTTPS pages are disabled" do
      it { is_expected.not_to be_pages_https_only }
    end

    context "when HTTPS pages are enabled", :https_pages_enabled do
      it { is_expected.to be_pages_https_only }
    end
  end

  describe "#pages_https_only? validation", :https_pages_enabled do
    subject(:project) do
      # set-up dirty object:
      create(:project, pages_https_only: false).tap do |p|
        p.pages_https_only = true
      end
    end

    context "when no domains are associated" do
      it { is_expected.to be_valid }
    end

    context "when domains including keys and certificates are associated" do
      before do
        allow(project)
          .to receive(:pages_domains)
          .and_return([instance_double(PagesDomain, https?: true)])
      end

      it { is_expected.to be_valid }
    end

    context "when domains including no keys or certificates are associated" do
      before do
        allow(project)
          .to receive(:pages_domains)
          .and_return([instance_double(PagesDomain, https?: false)])
      end

      it { is_expected.not_to be_valid }
    end
  end
3795

3796
  describe '#toggle_ci_cd_settings!' do
3797
    it 'toggles the value on #settings' do
3798
      project = create(:project, group_runners_enabled: false)
3799 3800 3801

      expect(project.group_runners_enabled).to be false

3802
      project.toggle_ci_cd_settings!(:group_runners_enabled)
3803 3804 3805 3806

      expect(project.group_runners_enabled).to be true
    end
  end
3807

3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827
  describe '#gitlab_deploy_token' do
    let(:project) { create(:project) }

    subject { project.gitlab_deploy_token }

    context 'when there is a gitlab deploy token associated' do
      let!(:deploy_token) { create(:deploy_token, :gitlab_deploy_token, projects: [project]) }

      it { is_expected.to eq(deploy_token) }
    end

    context 'when there is no a gitlab deploy token associated' do
      it { is_expected.to be_nil }
    end

    context 'when there is a gitlab deploy token associated but is has been revoked' do
      let!(:deploy_token) { create(:deploy_token, :gitlab_deploy_token, :revoked, projects: [project]) }
      it { is_expected.to be_nil }
    end

3828
    context 'when there is a gitlab deploy token associated but it is expired' do
3829 3830 3831 3832
      let!(:deploy_token) { create(:deploy_token, :gitlab_deploy_token, :expired, projects: [project]) }

      it { is_expected.to be_nil }
    end
3833

3834
    context 'when there is a deploy token associated with a different name' do
3835 3836 3837 3838
      let!(:deploy_token) { create(:deploy_token, projects: [project]) }

      it { is_expected.to be_nil }
    end
3839 3840 3841 3842 3843 3844 3845

    context 'when there is a deploy token associated to a different project' do
      let(:project_2) { create(:project) }
      let!(:deploy_token) { create(:deploy_token, projects: [project_2]) }

      it { is_expected.to be_nil }
    end
3846
  end
Jan Provaznik's avatar
Jan Provaznik committed
3847 3848 3849 3850 3851 3852 3853 3854

  context 'with uploads' do
    it_behaves_like 'model with mounted uploader', true do
      let(:model_object) { create(:project, :with_avatar) }
      let(:upload_attribute) { :avatar }
      let(:uploader_class) { AttachmentUploader }
    end
  end
3855

3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
  context '#commits_by' do
    let(:project) { create(:project, :repository) }
    let(:commits) { project.repository.commits('HEAD', limit: 3).commits }
    let(:commit_shas) { commits.map(&:id) }

    it 'retrieves several commits from the repository by oid' do
      expect(project.commits_by(oids: commit_shas)).to eq commits
    end
  end

3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
  context '#members_among' do
    let(:users) { create_list(:user, 3) }
    set(:group) { create(:group) }
    set(:project) { create(:project, namespace: group) }

    before do
      project.add_guest(users.first)
      project.group.add_maintainer(users.last)
    end

    context 'when users is an Array' do
      it 'returns project members among the users' do
        expect(project.members_among(users)).to eq([users.first, users.last])
      end

      it 'maintains input order' do
        expect(project.members_among(users.reverse)).to eq([users.last, users.first])
      end

      it 'returns empty array if users is empty' do
        result = project.members_among([])

        expect(result).to be_empty
      end
    end

    context 'when users is a relation' do
      it 'returns project members among the users' do
        result = project.members_among(User.where(id: users.map(&:id)))

        expect(result).to be_a(ActiveRecord::Relation)
        expect(result).to eq([users.first, users.last])
      end

      it 'returns empty relation if users is empty' do
        result = project.members_among(User.none)

        expect(result).to be_a(ActiveRecord::Relation)
        expect(result).to be_empty
      end
    end
3907
  end
3908

3909 3910
  describe "#find_or_initialize_services" do
    subject { build(:project) }
3911

3912 3913 3914
    it 'returns only enabled services' do
      allow(Service).to receive(:available_services_names).and_return(%w(prometheus pushover))
      allow(subject).to receive(:disabled_services).and_return(%w(prometheus))
3915

3916
      services = subject.find_or_initialize_services
3917

3918 3919 3920 3921
      expect(services.count).to eq 1
      expect(services).to include(PushoverService)
    end
  end
3922

3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939
  describe "#find_or_initialize_service" do
    subject { build(:project) }

    it 'avoids N+1 database queries' do
      allow(Service).to receive(:available_services_names).and_return(%w(prometheus pushover))

      control_count = ActiveRecord::QueryRecorder.new { subject.find_or_initialize_service('prometheus') }.count

      allow(Service).to receive(:available_services_names).and_call_original

      expect { subject.find_or_initialize_service('prometheus') }.not_to exceed_query_limit(control_count)
    end

    it 'returns nil if service is disabled' do
      allow(subject).to receive(:disabled_services).and_return(%w(prometheus))

      expect(subject.find_or_initialize_service('prometheus')).to be_nil
3940
    end
3941 3942
  end

3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
  describe '.find_without_deleted' do
    it 'returns nil if the project is about to be removed' do
      project = create(:project, pending_delete: true)

      expect(described_class.find_without_deleted(project.id)).to be_nil
    end

    it 'returns a project when it is not about to be removed' do
      project = create(:project)

      expect(described_class.find_without_deleted(project.id)).to eq(project)
    end
  end

  describe '.for_group' do
    it 'returns the projects for a given group' do
      group = create(:group)
      project = create(:project, namespace: group)

      expect(described_class.for_group(group)).to eq([project])
    end
  end

3966
  def rugged_config
3967
    rugged_repo(project.repository).config
3968
  end
gitlabhq's avatar
gitlabhq committed
3969
end