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

3
describe Project do
4 5
  include ProjectForksHelper

6
  describe 'associations' do
7 8 9 10
    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
11
    it { is_expected.to have_many(:services) }
12 13 14 15 16
    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) }
17
    it { is_expected.to have_many(:users).through(:project_members) }
18 19 20 21
    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) }
22
    it { is_expected.to have_many(:deploy_keys) }
23 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(:forked_project_link) }
    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 57
    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(:gemnasium_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
58 59
    it { is_expected.to have_one(:last_event).class_name('Event') }
    it { is_expected.to have_one(:forked_from_project).through(:forked_project_link) }
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
60
    it { is_expected.to have_one(:auto_devops).class_name('ProjectAutoDevops') }
Kamil Trzcinski's avatar
Kamil Trzcinski committed
61
    it { is_expected.to have_many(:commit_statuses) }
62
    it { is_expected.to have_many(:pipelines) }
63
    it { is_expected.to have_many(:builds) }
64
    it { is_expected.to have_many(:build_trace_section_names)}
65 66 67 68
    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
69
    it { is_expected.to have_many(:pages_domains) }
70 71 72 73 74 75 76 77 78
    it { is_expected.to have_many(:labels).class_name('ProjectLabel') }
    it { is_expected.to have_many(:users_star_projects) }
    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) }
ubudzisz's avatar
ubudzisz committed
79
    it { is_expected.to have_many(:forks).through(:forked_project_links) }
Jan Provaznik's avatar
Jan Provaznik committed
80
    it { is_expected.to have_many(:uploads) }
81
    it { is_expected.to have_many(:pipeline_schedules) }
82
    it { is_expected.to have_many(:members_and_requesters) }
83
    it { is_expected.to have_many(:clusters) }
84
    it { is_expected.to have_many(:custom_attributes).class_name('ProjectCustomAttribute') }
85
    it { is_expected.to have_many(:project_badges).class_name('ProjectBadge') }
86
    it { is_expected.to have_many(:lfs_file_locks) }
87 88
    it { is_expected.to have_many(:project_deploy_tokens) }
    it { is_expected.to have_many(:deploy_tokens).through(:project_deploy_tokens) }
89

90 91
    context 'after initialized' do
      it "has a project_feature" do
92
        expect(described_class.new.project_feature).to be_present
93 94 95
      end
    end

96 97 98 99 100 101 102 103 104
    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

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    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

121 122 123 124
    context 'updating cd_cd_settings' do
      it 'does not raise an error' do
        project = create(:project)

James Lopez's avatar
James Lopez committed
125
        expect { project.update(ci_cd_settings: nil) }.not_to raise_exception
126 127 128
      end
    end

129
    describe '#members & #requesters' do
130
      let(:project) { create(:project, :public, :access_requestable) }
131 132 133 134
      let(:requester) { create(:user) }
      let(:developer) { create(:user) }
      before do
        project.request_access(requester)
135
        project.add_developer(developer)
136 137
      end

138 139
      it_behaves_like 'members and requesters associations' do
        let(:namespace) { project }
140 141
      end
    end
142 143 144 145 146

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

147
        expect { subject.boards.build }.to raise_error(Project::BoardLimitExceeded, 'Number of permitted boards exceeded')
148 149 150
        expect(subject.boards.size).to eq 1
      end
    end
gitlabhq's avatar
gitlabhq committed
151 152
  end

153 154 155 156 157 158 159 160
  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) }
161 162
  end

163
  describe 'validation' do
164
    let!(:project) { create(:project) }
165

166 167
    it { is_expected.to validate_presence_of(:name) }
    it { is_expected.to validate_uniqueness_of(:name).scoped_to(:namespace_id) }
168
    it { is_expected.to validate_length_of(:name).is_at_most(255) }
169
    it { is_expected.to validate_presence_of(:path) }
170 171
    it { is_expected.to validate_length_of(:path).is_at_most(255) }
    it { is_expected.to validate_length_of(:description).is_at_most(2000) }
172 173 174
    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) }
175
    it { is_expected.not_to allow_value('/test/foo').for(:ci_config_path) }
176 177
    it { is_expected.to validate_presence_of(:creator) }
    it { is_expected.to validate_presence_of(:namespace) }
178
    it { is_expected.to validate_presence_of(:repository_storage) }
179

180 181 182 183 184 185 186 187
    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

188
    it 'does not allow new projects beyond user limits' do
189
      project2 = build(:project)
190 191
      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
192
      expect(project2.errors[:limit_reached].first).to match(/Personal project creation is not allowed/)
193
    end
194 195 196

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

          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
206
        it 'has an error on the name attribute' do
207 208
          project_with_wiki_suffix = create(:project, path: 'foo.wiki')
          new_project = build_stubbed(:project, namespace_id: project_with_wiki_suffix.namespace_id, path: 'foo')
209 210 211 212 213 214

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

216
    context 'repository storages inclusion' do
217
      let(:project2) { build(:project, repository_storage: 'missing') }
218 219

      before do
220
        storages = { 'custom' => { 'path' => 'tmp/tests/custom_repositories' } }
221 222 223
        allow(Gitlab.config.repositories).to receive(:storages).and_return(storages)
      end

224
      it "does not allow repository storages that don't match a label in the configuration" do
225 226 227 228
        expect(project2).not_to be_valid
        expect(project2.errors[:repository_storage].first).to match(/is not included in the list/)
      end
    end
229

230
    it 'does not allow an invalid URI as import_url' do
231
      project2 = build(:project, import_url: 'invalid://')
James Lopez's avatar
James Lopez committed
232 233 234 235

      expect(project2).not_to be_valid
    end

236
    it 'does allow a valid URI as import_url' do
237
      project2 = build(:project, import_url: 'ssh://test@gitlab.com/project.git')
James Lopez's avatar
James Lopez committed
238

239 240
      expect(project2).to be_valid
    end
241

242
    it 'allows an empty URI' do
243
      project2 = build(:project, import_url: '')
244

245
      expect(project2).to be_valid
246 247 248
    end

    it 'does not produce import data on an empty URI' do
249
      project2 = build(:project, import_url: '')
250 251 252 253 254

      expect(project2.import_data).to be_nil
    end

    it 'does not produce import data on an invalid URI' do
255
      project2 = build(:project, import_url: 'test://')
256 257 258

      expect(project2.import_data).to be_nil
    end
259

260
    it "does not allow import_url pointing to localhost" do
261
      project2 = build(:project, import_url: 'http://localhost:9000/t.git')
262 263

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

267
    it "does not allow import_url with invalid ports" do
268
      project2 = build(:project, import_url: 'http://github.com:25/t.git')
269 270

      expect(project2).to be_invalid
271
      expect(project2.errors[:import_url].first).to include('Only allowed ports are 22, 80, 443')
272 273
    end

274 275 276 277 278 279 280
    it "does not allow import_url with invalid user" do
      project2 = build(:project, import_url: 'http://$user:password@github.com/t.git')

      expect(project2).to be_invalid
      expect(project2.errors[:import_url].first).to include('Username needs to start with an alphanumeric character')
    end

281 282
    describe 'project pending deletion' do
      let!(:project_pending_deletion) do
283
        create(:project,
284 285 286
               pending_delete: true)
      end
      let(:new_project) do
287
        build(:project,
288 289 290 291 292 293 294 295 296 297 298 299
              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
300 301 302

    describe 'path validation' do
      it 'allows paths reserved on the root namespace' do
303
        project = build(:project, path: 'api')
304 305 306 307 308

        expect(project).to be_valid
      end

      it 'rejects paths reserved on another level' do
309
        project = build(:project, path: 'tree')
310 311 312

        expect(project).not_to be_valid
      end
313 314 315

      it 'rejects nested paths' do
        parent = create(:group, :nested, path: 'environments')
316
        project = build(:project, path: 'folders', namespace: parent)
317 318 319

        expect(project).not_to be_valid
      end
320 321 322

      it 'allows a reserved group name' do
        parent = create(:group)
323
        project = build(:project, path: 'avatar', namespace: parent)
324 325 326

        expect(project).to be_valid
      end
327 328 329 330 331 332

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

        expect(project).to be_valid
      end
333
    end
gitlabhq's avatar
gitlabhq committed
334
  end
335

336
  describe 'project token' do
337
    it 'sets an random token if none provided' do
338
      project = FactoryBot.create(:project, runners_token: '')
Kamil Trzcinski's avatar
Kamil Trzcinski committed
339
      expect(project.runners_token).not_to eq('')
340 341
    end

ubudzisz's avatar
ubudzisz committed
342
    it 'does not set an random token if one provided' do
343
      project = FactoryBot.create(:project, runners_token: 'my-token')
Kamil Trzcinski's avatar
Kamil Trzcinski committed
344
      expect(project.runners_token).to eq('my-token')
345 346
    end
  end
gitlabhq's avatar
gitlabhq committed
347

348
  describe 'Respond to' do
349 350 351 352 353
    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) }
354
    it { is_expected.to respond_to(:full_path) }
gitlabhq's avatar
gitlabhq committed
355 356
  end

357
  describe 'delegation' do
358
    [:add_guest, :add_reporter, :add_developer, :add_maintainer, :add_user, :add_users].each do |method|
359 360 361 362 363
      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) }
364 365
  end

366
  describe '#to_reference' do
367
    let(:owner)     { create(:user, name: 'Gitlab') }
368
    let(:namespace) { create(:namespace, path: 'sample-namespace', owner: owner) }
369
    let(:project)   { create(:project, path: 'sample-project', namespace: namespace) }
370
    let(:group)     { create(:group, name: 'Group', path: 'sample-group') }
371

372
    context 'when nil argument' do
373 374 375 376 377
      it 'returns nil' do
        expect(project.to_reference).to be_nil
      end
    end

378
    context 'when full is true' do
379
      it 'returns complete path to the project' do
380 381 382
        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'
383 384 385 386 387 388 389 390 391 392
      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
393
      let(:another_namespace_project) { create(:project, name: 'another-project') }
394 395 396 397 398 399 400

      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
401
      let(:another_project) { create(:project, namespace: namespace) }
402

403
      it 'returns path to the project' do
404 405 406
        expect(project.to_reference(another_project)).to eq 'sample-project'
      end
    end
407

408 409
    context 'when different namespace / cross-project argument' do
      let(:another_namespace) { create(:namespace, path: 'another-namespace', owner: owner) }
410
      let(:another_project)   { create(:project, path: 'another-project', namespace: another_namespace) }
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

      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
428 429
      end
    end
430 431 432 433 434
  end

  describe '#to_human_reference' do
    let(:owner) { create(:user, name: 'Gitlab') }
    let(:namespace) { create(:namespace, name: 'Sample namespace', owner: owner) }
435
    let(:project) { create(:project, name: 'Sample project', namespace: namespace) }
436 437 438 439 440 441 442 443 444 445 446 447 448 449

    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
450
      let(:another_namespace_project) { create(:project, name: 'another-project') }
451 452 453 454 455 456 457

      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
458
      let(:another_project) { create(:project, namespace: namespace) }
459 460 461 462

      it 'returns name of the project' do
        expect(project.to_human_reference(another_project)).to eq 'Sample project'
      end
463 464 465
    end
  end

466
  describe '#merge_method' do
467 468 469 470 471 472 473
    using RSpec::Parameterized::TableSyntax

    where(:ff, :rebase, :method) do
      true  | true  | :ff
      true  | false | :ff
      false | true  | :rebase_merge
      false | false | :merge
474 475
    end

476 477 478 479 480 481
    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) }
482 483 484
    end
  end

485
  it 'returns valid url to repo' do
486
    project = described_class.new(path: 'somewhere')
487
    expect(project.url_to_repo).to eq(Gitlab.config.gitlab_shell.ssh_path_prefix + 'somewhere.git')
gitlabhq's avatar
gitlabhq committed
488 489
  end

Douwe Maan's avatar
Douwe Maan committed
490
  describe "#web_url" do
491
    let(:project) { create(:project, path: "somewhere") }
Douwe Maan's avatar
Douwe Maan committed
492 493

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

498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
  describe "#readme_url" do
    let(:project) { create(:project, :repository, path: "somewhere") }

    context 'with a non-existing repository' do
      it 'returns nil' do
        allow(project.repository).to receive(:tree).with(:head).and_return(nil)

        expect(project.readme_url).to be_nil
      end
    end

    context 'with an existing repository' do
      context 'when no README exists' do
        it 'returns nil' do
          allow_any_instance_of(Tree).to receive(:readme).and_return(nil)

          expect(project.readme_url).to be_nil
        end
      end

      context 'when a README exists' do
        it 'returns the README' do
          expect(project.readme_url).to eql("#{Gitlab.config.gitlab.url}/#{project.namespace.full_path}/somewhere/blob/master/README.md")
        end
      end
    end
  end

526
  describe "#new_issuable_address" do
527
    let(:project) { create(:project, path: "somewhere") }
528 529
    let(:user) { create(:user) }

530 531 532 533 534 535
    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
536
        address = "p+#{project.full_path}+#{user.incoming_email_token}@gl.ab"
537

538 539 540 541 542 543 544
        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)
545 546 547 548 549 550 551
      end
    end

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

553
      it 'returns nil' do
554 555 556 557 558
        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
559
      end
560 561 562
    end
  end

563
  describe 'last_activity methods' do
564 565
    let(:timestamp) { 2.hours.ago }
    # last_activity_at gets set to created_at upon creation
566
    let(:project) { create(:project, created_at: timestamp, updated_at: timestamp) }
gitlabhq's avatar
gitlabhq committed
567

568
    describe 'last_activity' do
569
      it 'alias last_activity to last_event' do
570
        last_event = create(:event, :closed, project: project)
571

572
        expect(project.last_activity).to eq(last_event)
573
      end
gitlabhq's avatar
gitlabhq committed
574 575
    end

576 577
    describe 'last_activity_date' do
      it 'returns the creation date of the project\'s last event if present' do
578
        new_event = create(:event, :closed, project: project, created_at: Time.now)
579

580
        project.reload
581
        expect(project.last_activity_at.to_i).to eq(new_event.created_at.to_i)
582
      end
583

584
      it 'returns the project\'s last update date if it has no events' do
585
        expect(project.last_activity_date).to eq(project.updated_at)
586
      end
587 588

      it 'returns the most recent timestamp' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
589 590 591
        project.update(updated_at: nil,
                       last_activity_at: timestamp,
                       last_repository_updated_at: timestamp - 1.hour)
592

593
        expect(project.last_activity_date).to be_like_time(timestamp)
594

Lin Jen-Shin's avatar
Lin Jen-Shin committed
595 596 597
        project.update(updated_at: timestamp,
                       last_activity_at: timestamp - 1.hour,
                       last_repository_updated_at: nil)
598

599
        expect(project.last_activity_date).to be_like_time(timestamp)
600
      end
601 602
    end
  end
603

604
  describe '#get_issue' do
605
    let(:project) { create(:project) }
606
    let!(:issue)  { create(:issue, project: project) }
607 608 609
    let(:user)    { create(:user) }

    before do
610
      project.add_developer(user)
611
    end
612 613 614

    context 'with default issues tracker' do
      it 'returns an issue' do
615
        expect(project.get_issue(issue.iid, user)).to eq issue
616 617
      end

618 619 620 621
      it 'returns count of open issues' do
        expect(project.open_issues_count).to eq(1)
      end

622
      it 'returns nil when no issue found' do
623 624 625 626 627 628
        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
629 630 631 632
      end
    end

    context 'with external issues tracker' do
633
      let!(:internal_issue) { create(:issue, project: project) }
634
      before do
635
        allow(project).to receive(:external_issue_tracker).and_return(true)
636 637
      end

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
      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
675 676 677 678 679
      end
    end
  end

  describe '#issue_exists?' do
680
    let(:project) { create(:project) }
681 682 683 684 685 686 687 688 689 690 691 692

    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

693
  describe '#to_param' do
694 695
    context 'with namespace' do
      before do
696
        @group = create(:group, name: 'gitlab')
697
        @project = create(:project, name: 'gitlabhq', namespace: @group)
698 699
      end

Vinnie Okada's avatar
Vinnie Okada committed
700
      it { expect(@project.to_param).to eq('gitlabhq') }
701
    end
702 703 704

    context 'with invalid path' do
      it 'returns previous path to keep project suitable for use in URLs when persisted' do
705
        project = create(:project, path: 'gitlab')
706 707 708 709 710 711 712
        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
713
        project = build(:project, path: 'gitlab')
714 715 716 717 718 719
        project.path = 'foo&bar'

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

722
  describe '#repository' do
723
    let(:project) { create(:project, :repository) }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
724

725
    it 'returns valid repo' do
726
      expect(project.repository).to be_kind_of(Repository)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
727 728
    end
  end
729

730
  describe '#default_issues_tracker?' do
731
    it "is true if used internal tracker" do
732
      project = build(:project)
733

734
      expect(project.default_issues_tracker?).to be_truthy
735 736
    end

737
    it "is false if used other tracker" do
738 739 740 741
      # NOTE: The current nature of this factory requires persistence
      project = create(:redmine_project)

      expect(project.default_issues_tracker?).to be_falsey
742 743 744
    end
  end

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
  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

763
  describe '#external_issue_tracker' do
764
    let(:project) { create(:project) }
765 766 767
    let(:ext_project) { create(:redmine_project) }

    context 'on existing projects with no value for has_external_issue_tracker' do
768
      before do
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
        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

798
  describe '#cache_has_external_issue_tracker' do
799
    let(:project) { create(:project, has_external_issue_tracker: nil) }
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817

    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
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

    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
856 857
  end

858
  describe '#has_wiki?' do
859 860 861
    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) }
862 863 864 865 866 867 868 869

    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

870
  describe '#external_wiki' do
871
    let(:project) { create(:project) }
872

873 874 875 876 877
    context 'with an active external wiki' do
      before do
        create(:service, project: project, type: 'ExternalWikiService', active: true)
        project.external_wiki
      end
878

879 880 881
      it 'sets :has_external_wiki as true' do
        expect(project.has_external_wiki).to be(true)
      end
882

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

886 887 888 889
        project.services.external_wikis.first.destroy

        expect(project.has_external_wiki).to be(false)
      end
890 891
    end

892 893 894 895
    context 'with an inactive external wiki' do
      before do
        create(:service, project: project, type: 'ExternalWikiService', active: false)
      end
896

897 898 899
      it 'sets :has_external_wiki as false' do
        expect(project.has_external_wiki).to be(false)
      end
900 901
    end

902 903 904 905
    context 'with no external wiki' do
      before do
        project.external_wiki
      end
906

907 908 909 910 911 912 913 914 915 916 917
      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
918 919 920
    end
  end

921 922
  describe '#star_count' do
    it 'counts stars from multiple users' do
923 924
      user1 = create(:user)
      user2 = create(:user)
925
      project = create(:project, :public)
Ciro Santilli's avatar
Ciro Santilli committed
926 927

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

Ciro Santilli's avatar
Ciro Santilli committed
929
      user1.toggle_star(project)
930 931
      expect(project.reload.star_count).to eq(1)

Ciro Santilli's avatar
Ciro Santilli committed
932
      user2.toggle_star(project)
933 934 935
      project.reload
      expect(project.reload.star_count).to eq(2)

Ciro Santilli's avatar
Ciro Santilli committed
936
      user1.toggle_star(project)
937 938 939
      project.reload
      expect(project.reload.star_count).to eq(1)

Ciro Santilli's avatar
Ciro Santilli committed
940
      user2.toggle_star(project)
941 942 943 944
      project.reload
      expect(project.reload.star_count).to eq(0)
    end

945
    it 'counts stars on the right project' do
946
      user = create(:user)
947 948
      project1 = create(:project, :public)
      project2 = create(:project, :public)
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975

      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
976 977
    end
  end
978

979
  describe '#avatar_type' do
980
    let(:project) { create(:project) }
981

982
    it 'is true if avatar is image' do
983
      project.update_attribute(:avatar, 'uploads/avatar.png')
984
      expect(project.avatar_type).to be_truthy
985 986
    end

987
    it 'is false if avatar is html page' do
988
      project.update_attribute(:avatar, 'uploads/avatar.html')
989
      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'])
990 991
    end
  end
sue445's avatar
sue445 committed
992

993
  describe '#avatar_url' do
sue445's avatar
sue445 committed
994 995
    subject { project.avatar_url }

996
    let(:project) { create(:project) }
sue445's avatar
sue445 committed
997

998
    context 'when avatar file is uploaded' do
999
      let(:project) { create(:project, :public, :with_avatar) }
sue445's avatar
sue445 committed
1000

1001
      it 'shows correct url' do
1002 1003
        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)
1004
      end
sue445's avatar
sue445 committed
1005 1006
    end

1007
    context 'when avatar file in git' do
sue445's avatar
sue445 committed
1008 1009 1010 1011
      before do
        allow(project).to receive(:avatar_in_git) { true }
      end

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

1014
      it { is_expected.to eq "http://#{Gitlab.config.gitlab.host}#{avatar_path}" }
sue445's avatar
sue445 committed
1015
    end
1016 1017

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

1020
      it { is_expected.to eq nil }
1021
    end
sue445's avatar
sue445 committed
1022
  end
1023

1024
  describe '#pipeline_for' do
1025
    let(:project) { create(:project, :repository) }
1026
    let!(:pipeline) { create_pipeline }
1027

1028 1029
    shared_examples 'giving the correct pipeline' do
      it { is_expected.to eq(pipeline) }
1030

1031 1032
      context 'return latest' do
        let!(:pipeline2) { create_pipeline }
1033

1034
        it { is_expected.to eq(pipeline2) }
1035
      end
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    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
1049

1050 1051 1052 1053 1054
    def create_pipeline
      create(:ci_pipeline,
             project: project,
             ref: 'master',
             sha: project.commit('master').sha)
1055
    end
1056
  end
1057

1058
  describe '#builds_enabled' do
1059
    let(:project) { create(:project) }
1060

1061 1062 1063
    subject { project.builds_enabled }

    it { expect(project.builds_enabled?).to be_truthy }
1064
  end
1065

1066
  describe '.with_shared_runners' do
1067
    subject { described_class.with_shared_runners }
1068 1069

    context 'when shared runners are enabled for project' do
1070
      let!(:project) { create(:project, shared_runners_enabled: true) }
1071 1072 1073 1074 1075 1076 1077

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

    context 'when shared runners are disabled for project' do
1078
      let!(:project) { create(:project, shared_runners_enabled: false) }
1079 1080 1081 1082 1083 1084 1085

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

1086
  describe '.cached_count', :use_clean_rails_memory_store_caching do
1087
    let(:group)     { create(:group, :public) }
1088 1089
    let!(:project1) { create(:project, :public, group: group) }
    let!(:project2) { create(:project, :public, group: group) }
1090 1091

    it 'returns total project count' do
1092
      expect(described_class).to receive(:count).once.and_call_original
1093 1094

      3.times do
1095
        expect(described_class.cached_count).to eq(2)
1096 1097 1098 1099
      end
    end
  end

1100
  describe '.trending' do
Felipe Artur's avatar
Felipe Artur committed
1101
    let(:group)    { create(:group, :public) }
1102 1103
    let(:project1) { create(:project, :public, group: group) }
    let(:project2) { create(:project, :public, group: group) }
1104 1105 1106 1107 1108 1109 1110 1111

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

      create(:note_on_commit, project: project2)

1112
      TrendingProject.refresh!
1113 1114
    end

1115
    subject { described_class.trending.to_a }
1116

1117 1118
    it 'sorts projects by the amount of notes in descending order' do
      expect(subject).to eq([project1, project2])
1119
    end
1120 1121 1122 1123 1124 1125 1126 1127

    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
1128
  end
1129

1130 1131 1132 1133
  describe '.starred_by' do
    it 'returns only projects starred by the given user' do
      user1 = create(:user)
      user2 = create(:user)
1134 1135 1136
      project1 = create(:project)
      project2 = create(:project)
      create(:project)
1137 1138 1139
      user1.toggle_star(project1)
      user2.toggle_star(project2)

1140
      expect(described_class.starred_by(user1)).to contain_exactly(project1)
1141 1142 1143
    end
  end

1144
  describe '.visible_to_user' do
1145
    let!(:project) { create(:project, :private) }
1146 1147 1148 1149 1150 1151
    let!(:user)    { create(:user) }

    subject { described_class.visible_to_user(user) }

    describe 'when a user has access to a project' do
      before do
1152
        project.add_user(user, Gitlab::Access::MAINTAINER)
1153 1154 1155 1156 1157 1158 1159 1160 1161
      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
1162

1163
  context 'repository storage by default' do
1164
    let(:project) { build(:project) }
1165 1166

    before do
1167
      storages = {
1168 1169
        'default' => Gitlab::GitalyClient::StorageSettings.new('path' => 'tmp/tests/repositories'),
        'picked'  => Gitlab::GitalyClient::StorageSettings.new('path' => 'tmp/tests/repositories')
1170
      }
1171 1172 1173
      allow(Gitlab.config.repositories).to receive(:storages).and_return(storages)
    end

1174 1175 1176 1177 1178
    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
1179 1180
  end

1181
  context 'shared runners by default' do
1182
    let(:project) { create(:project) }
1183 1184 1185 1186

    subject { project.shared_runners_enabled }

    context 'are enabled' do
1187 1188 1189
      before do
        stub_application_setting(shared_runners_enabled: true)
      end
1190 1191 1192 1193 1194

      it { is_expected.to be_truthy }
    end

    context 'are disabled' do
1195 1196 1197
      before do
        stub_application_setting(shared_runners_enabled: false)
      end
1198 1199 1200 1201 1202

      it { is_expected.to be_falsey }
    end
  end

1203
  describe '#any_runners?' do
1204
    context 'shared runners' do
1205
      let(:project) { create(:project, shared_runners_enabled: shared_runners_enabled) }
1206 1207
      let(:specific_runner) { create(:ci_runner, :project, projects: [project]) }
      let(:shared_runner) { create(:ci_runner, :instance) }
1208

1209 1210
      context 'for shared runners disabled' do
        let(:shared_runners_enabled) { false }
1211

1212 1213 1214
        it 'has no runners available' do
          expect(project.any_runners?).to be_falsey
        end
1215

1216
        it 'has a specific runner' do
1217
          specific_runner
1218

1219 1220 1221 1222 1223
          expect(project.any_runners?).to be_truthy
        end

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

1225 1226
          expect(project.any_runners?).to be_falsey
        end
1227

1228
        it 'checks the presence of specific runner' do
1229
          specific_runner
1230

1231 1232
          expect(project.any_runners? { |runner| runner == specific_runner }).to be_truthy
        end
1233 1234

        it 'returns false if match cannot be found' do
1235
          specific_runner
1236

1237 1238
          expect(project.any_runners? { false }).to be_falsey
        end
1239
      end
1240

1241 1242 1243 1244 1245
      context 'for shared runners enabled' do
        let(:shared_runners_enabled) { true }

        it 'has a shared runner' do
          shared_runner
1246

1247 1248 1249 1250 1251
          expect(project.any_runners?).to be_truthy
        end

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

1253 1254
          expect(project.any_runners? { |runner| runner == shared_runner }).to be_truthy
        end
1255 1256 1257

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

1259 1260
          expect(project.any_runners? { false }).to be_falsey
        end
1261 1262
      end
    end
1263

1264
    context 'group runners' do
1265 1266
      let(:project) { create(:project, group_runners_enabled: group_runners_enabled) }
      let(:group) { create(:group, projects: [project]) }
1267
      let(:group_runner) { create(:ci_runner, :group, groups: [group]) }
1268 1269 1270

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

1272 1273 1274 1275 1276 1277
        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
1278

1279 1280
          expect(project.any_runners?).to be_falsey
        end
1281 1282
      end

1283 1284 1285 1286 1287
      context 'for group runners enabled' do
        let(:group_runners_enabled) { true }

        it 'has a group runner' do
          group_runner
1288

1289 1290 1291 1292 1293
          expect(project.any_runners?).to be_truthy
        end

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

1295 1296
          expect(project.any_runners? { |runner| runner == group_runner }).to be_truthy
        end
1297 1298 1299

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

1301 1302
          expect(project.any_runners? { false }).to be_falsey
        end
1303 1304 1305
      end
    end
  end
1306

1307
  describe '#shared_runners' do
1308
    let!(:runner) { create(:ci_runner, :instance) }
1309 1310 1311 1312

    subject { project.shared_runners }

    context 'when shared runners are enabled for project' do
1313
      let!(:project) { create(:project, shared_runners_enabled: true) }
1314 1315 1316 1317 1318 1319 1320

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

    context 'when shared runners are disabled for project' do
1321
      let!(:project) { create(:project, shared_runners_enabled: false) }
1322 1323 1324 1325 1326 1327 1328

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

1329
  describe '#visibility_level_allowed?' do
1330
    let(:project) { create(:project, :internal) }
1331 1332 1333 1334 1335 1336 1337 1338

    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
1339 1340
      let(:project)        { create(:project, :internal) }
      let(:forked_project) { create(:project, forked_from_project: project) }
1341 1342 1343 1344 1345

      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
1346
  end
1347

1348
  describe '#pages_deployed?' do
1349
    let(:project) { create(:project) }
1350 1351 1352 1353

    subject { project.pages_deployed? }

    context 'if public folder does exist' do
1354 1355 1356
      before do
        allow(Dir).to receive(:exist?).with(project.public_pages_path).and_return(true)
      end
1357 1358 1359 1360 1361 1362 1363 1364 1365

      it { is_expected.to be_truthy }
    end

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

1366
  describe '#pages_url' do
1367 1368
    let(:group) { create(:group, name: group_name) }
    let(:project) { create(:project, namespace: group, name: project_name) }
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
    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") }
1390 1391 1392 1393
    end
  end

  describe '#pages_group_url' do
1394 1395
    let(:group) { create(:group, name: group_name) }
    let(:project) { create(:project, namespace: group, name: project_name) }
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    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}") }
1418 1419 1420
    end
  end

1421
  describe '.search' do
1422
    let(:project) { create(:project, description: 'kitten mittens') }
1423

1424 1425 1426
    it 'returns projects with a matching name' do
      expect(described_class.search(project.name)).to eq([project])
    end
1427

1428 1429 1430
    it 'returns projects with a partially matching name' do
      expect(described_class.search(project.name[0..2])).to eq([project])
    end
1431

1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
    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

1460
    describe 'with pending_delete project' do
1461
      let(:pending_delete_project) { create(:project, pending_delete: true) }
1462 1463 1464 1465 1466 1467 1468

      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
1469
  end
1470 1471

  describe '#expire_caches_before_rename' do
1472
    let(:project) { create(:project, :repository) }
1473 1474 1475 1476
    let(:repo)    { double(:repo, exists?: true) }
    let(:wiki)    { double(:wiki, exists?: true) }

    it 'expires the caches of the repository and wiki' do
1477 1478 1479
      allow(Repository).to receive(:new)
        .with('foo', project)
        .and_return(repo)
1480

1481 1482 1483
      allow(Repository).to receive(:new)
        .with('foo.wiki', project)
        .and_return(wiki)
1484

1485 1486
      expect(repo).to receive(:before_delete)
      expect(wiki).to receive(:before_delete)
1487 1488 1489 1490

      project.expire_caches_before_rename('foo')
    end
  end
1491 1492

  describe '.search_by_title' do
1493
    let(:project) { create(:project, name: 'kittens') }
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506

    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
1507 1508 1509 1510 1511

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

1512 1513
    let(:private_project)  { create(:project, :private, group: private_group) }
    let(:internal_project) { create(:project, :internal, group: internal_group) }
1514 1515 1516 1517 1518 1519 1520 1521 1522

    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
1523

1524
  describe '#create_repository' do
1525
    let(:project) { create(:project, :repository) }
1526 1527 1528 1529 1530 1531 1532 1533
    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
1534
        expect(shell).to receive(:create_repository)
1535
          .with(project.repository_storage, project.disk_path)
1536
          .and_return(true)
1537 1538 1539 1540 1541 1542 1543

        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
1544
        expect(shell).to receive(:create_repository)
1545
          .with(project.repository_storage, project.disk_path)
1546
          .and_return(false)
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557

        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)
1558
        expect(shell).not_to receive(:create_repository)
1559 1560 1561 1562 1563

        project.create_repository
      end
    end
  end
1564

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
  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)

1577
      allow(shell).to receive(:create_repository)
1578
        .with(project.repository_storage, project.disk_path)
1579 1580
        .and_return(true)

1581
      expect(project).to receive(:create_repository).with(force: true)
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

      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
1594 1595 1596 1597 1598 1599 1600

    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)

1601
      expect(shell).to receive(:create_repository)
1602
        .with(project.repository_storage, project.disk_path)
1603 1604 1605 1606
        .and_return(true)

      project.ensure_repository
    end
1607 1608
  end

1609
  describe '#container_registry_url' do
1610
    let(:project) { create(:project) }
1611

1612
    subject { project.container_registry_url }
1613

1614 1615 1616
    before do
      stub_container_registry_config(**registry_settings)
    end
1617 1618 1619

    context 'for enabled registry' do
      let(:registry_settings) do
1620 1621
        { enabled: true,
          host_port: 'example.com' }
1622 1623
      end

1624
      it { is_expected.not_to be_nil }
1625 1626 1627 1628
    end

    context 'for disabled registry' do
      let(:registry_settings) do
1629
        { enabled: false }
1630 1631 1632 1633 1634 1635
      end

      it { is_expected.to be_nil }
    end
  end

1636
  describe '#has_container_registry_tags?' do
1637
    let(:project) { create(:project) }
1638 1639

    context 'when container registry is enabled' do
1640 1641 1642
      before do
        stub_container_registry_config(enabled: true)
      end
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679

      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
1680 1681 1682
      before do
        stub_container_registry_config(enabled: false)
      end
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

      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

1700
  describe '#ci_config_path=' do
1701
    let(:project) { create(:project) }
1702 1703

    it 'sets nil' do
1704
      project.update!(ci_config_path: nil)
1705

1706
      expect(project.ci_config_path).to be_nil
1707 1708 1709
    end

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

1712
      expect(project.ci_config_path).to eq('foo/.gitlab_ci.yml')
1713 1714
    end

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

1718
      expect(project.ci_config_path).to eq('foo//.gitlab_ci.yml')
1719 1720 1721
    end
  end

1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
  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

1747
  describe 'Project import job' do
1748
    let(:project) { create(:project, import_url: generate(:url)) }
1749 1750

    before do
1751
      allow_any_instance_of(Gitlab::Shell).to receive(:import_repository)
1752
        .with(project.repository_storage, project.disk_path, project.import_url)
1753 1754
        .and_return(true)

1755
      # Works around https://github.com/rspec/rspec-mocks/issues/910
1756
      allow(described_class).to receive(:find).with(project.id).and_return(project)
1757 1758 1759
      expect(project.repository).to receive(:after_import)
        .and_call_original
      expect(project.wiki.repository).to receive(:after_import)
1760
        .and_call_original
1761 1762 1763 1764 1765
    end

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

1766
      expect { project.import_schedule }.to change { project.import_jid }
1767 1768 1769 1770
      expect(project.reload.import_status).to eq('finished')
    end
  end

1771 1772
  describe 'project import state transitions' do
    context 'state transition: [:started] => [:finished]' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1773
      let(:after_import_service) { spy(:after_import_service) }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1774
      let(:housekeeping_service) { spy(:housekeeping_service) }
1775 1776

      before do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1777 1778
        allow(Projects::AfterImportService)
          .to receive(:new) { after_import_service }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1779

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1780
        allow(after_import_service)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1781 1782 1783 1784
          .to receive(:execute) { housekeeping_service.execute }

        allow(Projects::HousekeepingService)
          .to receive(:new) { housekeeping_service }
1785 1786
      end

1787 1788
      it 'resets project import_error' do
        error_message = 'Some error'
1789
        mirror = create(:project_empty_repo, :import_started)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1790
        mirror.import_state.update(last_error: error_message)
1791 1792 1793 1794

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

1795 1796 1797 1798 1799
      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
1800
        expect(after_import_service).to have_received(:execute)
1801 1802 1803 1804
        expect(housekeeping_service).to have_received(:execute)
      end

      it 'does not perform housekeeping when project repository does not exist' do
1805
        project = create(:project, :import_started, import_type: :github)
1806 1807 1808 1809 1810 1811 1812

        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
1813
        project = create(:project, :import_started, import_type: nil)
1814 1815 1816 1817 1818 1819 1820 1821

        project.import_finish

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

1822
  describe '#latest_successful_builds_for' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1823
    def create_pipeline(status = 'success')
1824
      create(:ci_pipeline, project: project,
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1825
                           sha: project.commit.sha,
1826
                           ref: project.default_branch,
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1827
                           status: status)
1828 1829
    end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1830 1831 1832
    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
1833
             status: new_pipeline.status,
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1834
             name: name)
1835 1836
    end

1837
    let(:project) { create(:project, :repository) }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1838
    let(:pipeline) { create_pipeline }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1839 1840

    context 'with many builds' do
1841
      it 'gives the latest builds from latest pipeline' do
1842 1843
        pipeline1 = create_pipeline
        pipeline2 = create_pipeline
1844
        build1_p2 = create_build(pipeline2, 'test')
1845 1846
        create_build(pipeline1, 'test')
        create_build(pipeline1, 'test2')
1847
        build2_p2 = create_build(pipeline2, 'test2')
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1848 1849 1850

        latest_builds = project.latest_successful_builds_for

1851
        expect(latest_builds).to contain_exactly(build2_p2, build1_p2)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1852 1853
      end
    end
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1854

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1855
    context 'with succeeded pipeline' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1856
      let!(:build) { create_build }
1857

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1858
      context 'standalone pipeline' do
1859 1860 1861 1862 1863 1864 1865 1866
        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')
1867

1868 1869 1870
          expect(builds).to be_kind_of(ActiveRecord::Relation)
          expect(builds).to be_empty
        end
1871 1872
      end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1873
      context 'with some pending pipeline' do
1874
        before do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1875
          create_build(create_pipeline('pending'))
1876 1877
        end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1878 1879
        it 'gives the latest build from latest pipeline' do
          latest_build = project.latest_successful_builds_for
1880

Lin Jen-Shin's avatar
Lin Jen-Shin committed
1881
          expect(latest_build).to contain_exactly(build)
1882
        end
1883 1884 1885 1886 1887 1888
      end
    end

    context 'with pending pipeline' do
      before do
        pipeline.update(status: 'pending')
Lin Jen-Shin's avatar
Lin Jen-Shin committed
1889
        create_build(pipeline)
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
      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

1901
  describe '#add_import_job' do
1902 1903
    let(:import_jid) { '123' }

1904
    context 'forked' do
1905
      let(:forked_project_link) { create(:forked_project_link, :forked_to_empty_project) }
1906 1907 1908 1909
      let(:forked_from_project) { forked_project_link.forked_from_project }
      let(:project) { forked_project_link.forked_to_project }

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

1912
        expect(project.add_import_job).to eq(import_jid)
1913 1914 1915 1916 1917
      end
    end

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

1920 1921
        expect(RepositoryImportWorker).to receive(:perform_async).with(project.id).and_return(import_jid)
        expect(project.add_import_job).to eq(import_jid)
1922 1923 1924 1925
      end
    end
  end

Rémy Coutable's avatar
Rémy Coutable committed
1926
  describe '#gitlab_project_import?' do
1927
    subject(:project) { build(:project, import_type: 'gitlab_project') }
Rémy Coutable's avatar
Rémy Coutable committed
1928 1929 1930 1931 1932

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

  describe '#gitea_import?' do
1933
    subject(:project) { build(:project, import_type: 'gitea') }
Rémy Coutable's avatar
Rémy Coutable committed
1934 1935 1936 1937

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

1938
  describe '#has_remote_mirror?' do
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
    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
1951
      project.remote_mirrors.first.update(enabled: false)
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980

      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
1981
      project.remote_mirrors.first.update(enabled: false)
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014

      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

2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
  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

2030
  describe '#lfs_enabled?' do
2031
    let(:project) { create(:project) }
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 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 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091

    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

2092
  describe '#change_head' do
2093
    let(:project) { create(:project, :repository) }
2094

2095 2096 2097 2098 2099
    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

2100
    it 'calls the before_change_head and after_change_head methods' do
2101
      expect(project.repository).to receive(:before_change_head)
2102 2103
      expect(project.repository).to receive(:after_change_head)

2104 2105 2106
      project.change_head(project.default_branch)
    end

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

2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
      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
2123

2124
  context 'forks' do
2125 2126
    include ProjectForksHelper

2127 2128 2129 2130 2131
    let(:project) { create(:project, :public) }
    let!(:forked_project) { fork_project(project) }

    describe '#fork_network' do
      it 'includes a fork of the project' do
2132
        expect(project.fork_network.projects).to include(forked_project)
2133 2134 2135 2136 2137
      end

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

2138
        expect(project.fork_network.projects).to include(other_fork)
2139 2140 2141 2142 2143
      end

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

2144
        expect(forked_project.fork_network.projects).to include(other_fork)
2145 2146 2147
      end

      it 'includes the base project' do
2148
        expect(forked_project.fork_network.projects).to include(project.reload)
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
      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
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187

    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
2188 2189 2190 2191

      it 'returns nil if it is the root of the fork network' do
        expect(project.fork_source).to be_nil
      end
2192
    end
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210

    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
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226

    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
2227 2228
  end

2229
  describe '#pushes_since_gc' do
2230
    let(:project) { create(:project) }
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251

    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
2252
    let(:project) { create(:project) }
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265

    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
2266
    let(:project) { create(:project) }
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279

    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
2280

2281 2282
  describe '#deployment_variables' do
    context 'when project has no deployment service' do
2283
      let(:project) { create(:project) }
2284 2285 2286 2287 2288 2289 2290

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

    context 'when project has a deployment service' do
2291
      shared_examples 'same behavior between KubernetesService and Platform::Kubernetes' do
2292 2293
        it 'returns variables from this service' do
          expect(project.deployment_variables).to include(
2294
            { key: 'KUBE_TOKEN', value: project.deployment_platform.token, public: false }
2295 2296 2297 2298 2299 2300 2301
          )
        end
      end

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

2302
        it_behaves_like 'same behavior between KubernetesService and Platform::Kubernetes'
2303 2304 2305 2306 2307
      end

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

2309
        it_behaves_like 'same behavior between KubernetesService and Platform::Kubernetes'
2310 2311 2312 2313
      end
    end
  end

2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
  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

2336
  describe '#secret_variables_for' do
2337
    let(:project) { create(:project) }
2338 2339 2340 2341 2342 2343 2344 2345 2346

    let!(:secret_variable) do
      create(:ci_variable, value: 'secret', project: project)
    end

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

2347
    subject { project.reload.secret_variables_for(ref: 'ref') }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
2348 2349 2350 2351 2352

    before do
      stub_application_setting(
        default_branch_protection: Gitlab::Access::PROTECTION_NONE)
    end
2353 2354 2355

    shared_examples 'ref is protected' do
      it 'contains all the variables' do
2356
        is_expected.to contain_exactly(secret_variable, protected_variable)
2357 2358 2359 2360
      end
    end

    context 'when the ref is not protected' do
2361
      it 'contains only the secret variables' do
2362
        is_expected.to contain_exactly(secret_variable)
2363 2364 2365
      end
    end

2366 2367
    context 'when the ref is a protected branch' do
      before do
2368
        allow(project).to receive(:protected_for?).with('ref').and_return(true)
2369
      end
2370 2371 2372 2373 2374 2375

      it_behaves_like 'ref is protected'
    end

    context 'when the ref is a protected tag' do
      before do
2376
        allow(project).to receive(:protected_for?).with('ref').and_return(true)
2377 2378 2379
      end

      it_behaves_like 'ref is protected'
2380 2381 2382
    end
  end

2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
  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

2399
  describe '#protected_for?' do
2400
    let(:project) { create(:project) }
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416

    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
2417 2418
        allow(project).to receive(:repository).and_call_original
        allow(project).to receive_message_chain(:repository, :branch_exists?).and_return(true)
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
        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
2429 2430
        allow(project).to receive_message_chain(:repository, :branch_exists?).and_return(false)
        allow(project).to receive_message_chain(:repository, :tag_exists?).and_return(true)
2431 2432 2433 2434 2435 2436 2437 2438 2439
        create(:protected_tag, name: 'ref', project: project)
      end

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

2440
  describe '#update_project_statistics' do
2441
    let(:project) { create(:project) }
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459

    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

2460
  describe 'inside_path' do
2461 2462 2463
    let!(:project1) { create(:project, namespace: create(:namespace, path: 'name_pace')) }
    let!(:project2) { create(:project) }
    let!(:project3) { create(:project, namespace: create(:namespace, path: 'namespace')) }
2464
    let!(:path) { project1.namespace.full_path }
2465

2466
    it 'returns correct project' do
2467
      expect(described_class.inside_path(path)).to eq([project1])
2468
    end
2469 2470
  end

Douwe Maan's avatar
Douwe Maan committed
2471
  describe '#route_map_for' do
2472
    let(:project) { create(:project, :repository) }
Douwe Maan's avatar
Douwe Maan committed
2473 2474 2475 2476 2477 2478 2479 2480
    let(:route_map) do
      <<-MAP.strip_heredoc
      - source: /source/(.*)/
        public: '\\1'
      MAP
    end

    before do
2481
      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
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
    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
2509
    let(:project) { create(:project, :repository) }
Douwe Maan's avatar
Douwe Maan committed
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
    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

2547
  describe '#parent' do
2548
    let(:project) { create(:project) }
2549 2550 2551 2552

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

2553 2554 2555 2556 2557 2558
  describe '#parent_id' do
    let(:project) { create(:project) }

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

2559
  describe '#parent_changed?' do
2560
    let(:project) { create(:project) }
2561

2562 2563 2564
    before do
      project.namespace_id = 7
    end
2565 2566 2567 2568

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

2569 2570 2571
  def enable_lfs
    allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
  end
2572

2573
  describe '#pages_url' do
2574 2575
    let(:group) { create(:group, name: 'Group') }
    let(:nested_group) { create(:group, parent: group) }
2576 2577 2578 2579 2580 2581 2582 2583 2584
    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

2585
    context 'top-level group' do
2586
      let(:project) { create(:project, namespace: group, name: project_name) }
2587

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
      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
2599 2600
    end

2601
    context 'nested group' do
2602
      let(:project) { create(:project, namespace: nested_group, name: project_name) }
2603
      let(:expected_url) { "http://group.example.com/#{nested_group.path}/#{project.path}" }
2604

2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
      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
2616 2617
    end
  end
2618 2619

  describe '#http_url_to_repo' do
2620
    let(:project) { create(:project) }
2621

2622 2623 2624
    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('@')
2625 2626
    end
  end
2627 2628

  describe '#pipeline_status' do
2629
    let(:project) { create(:project, :repository) }
2630
    it 'builds a pipeline status' do
2631
      expect(project.pipeline_status).to be_a(Gitlab::Cache::Ci::ProjectPipelineStatus)
2632 2633 2634 2635 2636 2637
    end

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

  describe '#append_or_update_attribute' do
2640
    let(:project) { create(:project) }
2641 2642 2643 2644 2645

    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'

2646 2647
      expect { project.append_or_update_attribute(:merge_requests, [create(:merge_request)]) }
        .to raise_error(ActiveRecord::RecordNotSaved, error_message)
2648 2649 2650 2651 2652
    end

    it 'updates the project succesfully' do
      merge_request = create(:merge_request, target_project: project, source_project: project)

2653 2654
      expect { project.append_or_update_attribute(:merge_requests, [merge_request]) }
        .not_to raise_error
2655 2656
    end
  end
2657 2658 2659

  describe '#last_repository_updated_at' do
    it 'sets to created_at upon creation' do
2660
      project = create(:project, created_at: 2.hours.ago)
2661 2662 2663 2664

      expect(project.last_repository_updated_at.to_i).to eq(project.created_at.to_i)
    end
  end
2665 2666 2667 2668 2669

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

    let!(:private_project) do
2670
      create(:project, :private, creator: user, namespace: user.namespace)
2671 2672
    end

2673
    let!(:public_project) { create(:project, :public) }
2674 2675 2676

    context 'with a user' do
      let(:projects) do
2677
        described_class.all.public_or_visible_to_user(user)
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
      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
2691
        projects = described_class.all.public_or_visible_to_user
2692 2693 2694 2695 2696

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

2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
  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

2720
  describe '#remove_private_deploy_keys' do
2721
    let!(:project) { create(:project) }
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736

    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
2737
          another_project = create(:project)
2738 2739
          create(:deploy_keys_project, deploy_key: key, project: another_project)
        end
2740

2741 2742
        it 'does not remove the key' do
          project.remove_private_deploy_keys
2743

2744 2745 2746 2747 2748 2749 2750 2751
          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) }
2752

2753 2754
      it 'does not remove the key' do
        project.remove_private_deploy_keys
2755

2756 2757
        expect(project.deploy_keys).to include(key)
      end
2758 2759
    end
  end
2760

2761 2762
  describe '#remove_pages' do
    let(:project) { create(:project) }
2763
    let(:namespace) { project.namespace }
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
    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

2775 2776 2777 2778 2779 2780 2781 2782
    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

2783
    it 'is a no-op when there is no namespace' do
2784 2785
      project.namespace.delete
      project.reload
2786 2787 2788 2789 2790 2791

      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
2792 2793 2794 2795 2796 2797

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

      project.destroy
    end
2798 2799
  end

2800
  describe '#remove_export' do
2801
    let(:legacy_project) { create(:project, :legacy_storage, :with_export) }
2802 2803
    let(:project) { create(:project, :with_export) }

2804 2805 2806 2807
    before do
      stub_feature_flags(import_export_object_storage: false)
    end

2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
    it 'removes the exports directory for the project' do
      expect(File.exist?(project.export_path)).to be_truthy

      allow(FileUtils).to receive(:rm_rf).and_call_original
      expect(FileUtils).to receive(:rm_rf).with(project.export_path).and_call_original
      project.remove_exports

      expect(File.exist?(project.export_path)).to be_falsy
    end

2818 2819 2820
    it 'is a no-op on legacy projects when there is no namespace' do
      export_path = legacy_project.export_path

2821 2822
      legacy_project.namespace.delete
      legacy_project.reload
2823 2824 2825 2826 2827 2828 2829 2830 2831

      expect(FileUtils).not_to receive(:rm_rf).with(export_path)

      legacy_project.remove_exports

      expect(File.exist?(export_path)).to be_truthy
    end

    it 'runs on hashed storage projects when there is no namespace' do
2832
      export_path = project.export_path
2833

2834 2835
      project.namespace.delete
      legacy_project.reload
2836

2837 2838
      allow(FileUtils).to receive(:rm_rf).and_call_original
      expect(FileUtils).to receive(:rm_rf).with(export_path).and_call_original
2839 2840 2841

      project.remove_exports

2842
      expect(File.exist?(export_path)).to be_falsy
2843 2844 2845 2846 2847 2848 2849 2850 2851
    end

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

      project.destroy
    end
  end

2852 2853 2854 2855
  describe '#remove_exported_project_file' do
    let(:project) { create(:project, :with_export) }

    it 'removes the exported project file' do
2856 2857
      stub_feature_flags(import_export_object_storage: false)

2858 2859 2860 2861
      exported_file = project.export_project_path

      expect(File.exist?(exported_file)).to be_truthy

2862 2863
      allow(FileUtils).to receive(:rm_rf).and_call_original
      expect(FileUtils).to receive(:rm_rf).with(exported_file).and_call_original
2864 2865 2866 2867 2868 2869 2870

      project.remove_exported_project_file

      expect(File.exist?(exported_file)).to be_falsy
    end
  end

2871 2872 2873 2874
  describe '#forks_count' do
    it 'returns the number of forks' do
      project = build(:project)

Francisco Lopez's avatar
Francisco Lopez committed
2875
      expect_any_instance_of(Projects::ForksCountService).to receive(:count).and_return(1)
2876 2877 2878 2879

      expect(project.forks_count).to eq(1)
    end
  end
2880 2881

  context 'legacy storage' do
2882
    let(:project) { create(:project, :repository, :legacy_storage) }
2883
    let(:gitlab_shell) { Gitlab::Shell.new }
2884
    let(:project_storage) { project.send(:storage) }
2885

2886 2887 2888 2889
    before do
      allow(project).to receive(:gitlab_shell).and_return(gitlab_shell)
    end

2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
    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

2902
    describe '#ensure_storage_path_exists' do
2903
      it 'delegates to gitlab_shell to ensure namespace is created' do
2904
        expect(gitlab_shell).to receive(:add_namespace).with(project.repository_storage, project.base_dir)
2905

2906
        project.ensure_storage_path_exists
2907 2908 2909
      end
    end

2910 2911
    describe '#legacy_storage?' do
      it 'returns true when storage_version is nil' do
2912
        project = build(:project, storage_version: nil)
2913 2914 2915

        expect(project.legacy_storage?).to be_truthy
      end
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925

      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
2926
        expect(project.hashed_storage?(:repository)).to be_falsey
2927
      end
2928 2929
    end

2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
    describe '#rename_repo' do
      before do
        # Project#gitlab_shell returns a new instance of Gitlab::Shell on every
        # call. This makes testing a bit easier.
        allow(project).to receive(:gitlab_shell).and_return(gitlab_shell)
        allow(project).to receive(:previous_changes).and_return('path' => ['foo'])
      end

      it 'renames a repository' do
        stub_container_registry_config(enabled: false)

        expect(gitlab_shell).to receive(:mv_repository)
          .ordered
2943
          .with(project.repository_storage, "#{project.namespace.full_path}/foo", "#{project.full_path}")
2944 2945 2946 2947
          .and_return(true)

        expect(gitlab_shell).to receive(:mv_repository)
          .ordered
2948
          .with(project.repository_storage, "#{project.namespace.full_path}/foo.wiki", "#{project.full_path}.wiki")
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
          .and_return(true)

        expect_any_instance_of(SystemHooksService)
          .to receive(:execute_hooks_for)
            .with(project, :rename)

        expect_any_instance_of(Gitlab::UploadsTransfer)
          .to receive(:rename_project)
            .with('foo', project.path, project.namespace.full_path)

        expect(project).to receive(:expire_caches_before_rename)

        project.rename_repo
      end

      context 'container registry with images' do
        let(:container_repository) { create(:container_repository) }

        before do
          stub_container_registry_config(enabled: true)
          stub_container_registry_tags(repository: :any, tags: ['tag'])
          project.container_repositories << container_repository
        end

        subject { project.rename_repo }

2975
        it { expect { subject }.to raise_error(StandardError) }
2976
      end
2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000

      context 'gitlab pages' do
        before do
          expect(project_storage).to receive(:rename_repo) { true }
        end

        it 'moves pages folder to new location' do
          expect_any_instance_of(Gitlab::PagesTransfer).to receive(:rename_project)

          project.rename_repo
        end
      end

      context 'attachments' do
        before do
          expect(project_storage).to receive(:rename_repo) { true }
        end

        it 'moves uploads folder to new location' do
          expect_any_instance_of(Gitlab::UploadsTransfer).to receive(:rename_project)

          project.rename_repo
        end
      end
3001 3002 3003 3004 3005

      it 'updates project full path in .git/config' do
        allow(project_storage).to receive(:rename_repo).and_return(true)

        project.rename_repo
3006

3007
        expect(rugged_config['gitlab.fullpath']).to eq(project.full_path)
3008
      end
3009
    end
3010 3011 3012 3013 3014 3015

    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
3016 3017 3018 3019 3020 3021

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

3022
      it 'flags as read-only' do
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
        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
3048 3049 3050
  end

  context 'hashed storage' do
3051
    let(:project) { create(:project, :repository, skip_disk_validation: true) }
3052
    let(:gitlab_shell) { Gitlab::Shell.new }
3053
    let(:hash) { Digest::SHA2.hexdigest(project.id.to_s) }
3054 3055
    let(:hashed_prefix) { File.join('@hashed', hash[0..1], hash[2..3]) }
    let(:hashed_path) { File.join(hashed_prefix, hash) }
3056 3057

    before do
3058
      stub_application_setting(hashed_storage_enabled: true)
3059 3060
    end

3061 3062 3063 3064 3065 3066 3067
    describe '#legacy_storage?' do
      it 'returns false' do
        expect(project.legacy_storage?).to be_falsey
      end
    end

    describe '#hashed_storage?' do
3068 3069
      it 'returns true if rolled out' do
        expect(project.hashed_storage?(:attachments)).to be_truthy
3070 3071
      end

3072 3073
      it 'returns false when not rolled out yet' do
        project.storage_version = 1
3074

3075
        expect(project.hashed_storage?(:attachments)).to be_falsey
3076 3077 3078
      end
    end

3079 3080
    describe '#base_dir' do
      it 'returns base_dir based on hash of project id' do
3081
        expect(project.base_dir).to eq(hashed_prefix)
3082 3083 3084 3085
      end
    end

    describe '#disk_path' do
3086
      it 'returns disk_path based on hash of project id' do
3087 3088 3089 3090
        expect(project.disk_path).to eq(hashed_path)
      end
    end

3091
    describe '#ensure_storage_path_exists' do
3092
      it 'delegates to gitlab_shell to ensure namespace is created' do
3093 3094
        allow(project).to receive(:gitlab_shell).and_return(gitlab_shell)

3095
        expect(gitlab_shell).to receive(:add_namespace).with(project.repository_storage, hashed_prefix)
3096

3097
        project.ensure_storage_path_exists
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
      end
    end

    describe '#rename_repo' do
      before do
        # Project#gitlab_shell returns a new instance of Gitlab::Shell on every
        # call. This makes testing a bit easier.
        allow(project).to receive(:gitlab_shell).and_return(gitlab_shell)
        allow(project).to receive(:previous_changes).and_return('path' => ['foo'])
      end

      it 'renames a repository' do
        stub_container_registry_config(enabled: false)

        expect(gitlab_shell).not_to receive(:mv_repository)

        expect_any_instance_of(SystemHooksService)
          .to receive(:execute_hooks_for)
            .with(project, :rename)

        expect(project).to receive(:expire_caches_before_rename)

        project.rename_repo
      end

      context 'container registry with images' do
        let(:container_repository) { create(:container_repository) }

        before do
          stub_container_registry_config(enabled: true)
          stub_container_registry_tags(repository: :any, tags: ['tag'])
          project.container_repositories << container_repository
        end

        subject { project.rename_repo }

3134
        it { expect { subject }.to raise_error(StandardError) }
3135
      end
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152

      context 'gitlab pages' do
        it 'moves pages folder to new location' do
          expect_any_instance_of(Gitlab::PagesTransfer).to receive(:rename_project)

          project.rename_repo
        end
      end

      context 'attachments' do
        it 'keeps uploads folder location unchanged' do
          expect_any_instance_of(Gitlab::UploadsTransfer).not_to receive(:rename_project)

          project.rename_repo
        end

        context 'when not rolled out' do
3153
          let(:project) { create(:project, :repository, storage_version: 1, skip_disk_validation: true) }
3154 3155 3156 3157 3158 3159 3160 3161

          it 'moves pages folder to new location' do
            expect_any_instance_of(Gitlab::UploadsTransfer).to receive(:rename_project)

            project.rename_repo
          end
        end
      end
3162 3163 3164

      it 'updates project full path in .git/config' do
        project.rename_repo
3165

3166
        expect(rugged_config['gitlab.fullpath']).to eq(project.full_path)
3167
      end
3168
    end
3169 3170 3171 3172 3173 3174

    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
3175 3176 3177 3178 3179 3180

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

3181
      it 'does not flag as read-only' do
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
        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
3195
  end
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 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293

  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

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

      context 'when auto devops is enabled' do
        before do
          stub_application_setting(auto_devops_enabled: true)
        end

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

  describe '#auto_devops_enabled?' do
    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

      it 'auto devops is implicitly enabled' do
        expect(project.auto_devops).to be_nil
        expect(project).to be_auto_devops_enabled
      end

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

        it "auto devops is enabled" do
          expect(project).to be_auto_devops_enabled
        end
      end

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

        it "auto devops is disabled" do
          expect(project).not_to be_auto_devops_enabled
        end
      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.auto_devops).to be_nil
        expect(project).not_to be_auto_devops_enabled
      end

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

        it "auto devops is enabled" do
          expect(project).to be_auto_devops_enabled
        end
      end
    end
  end

3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337
  describe '#has_auto_devops_implicitly_disabled?' do
    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

      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
          create(:project_auto_devops, project: project)
        end

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

3338 3339 3340 3341 3342
  context '#auto_devops_variables' do
    set(:project) { create(:project) }

    subject { project.auto_devops_variables }

3343
    context 'when enabled in instance settings' do
3344 3345 3346 3347
      before do
        stub_application_setting(auto_devops_enabled: true)
      end

3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369
      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

    context 'when explicitely enabled' do
3370 3371 3372 3373 3374
      context 'when domain is empty' do
        before do
          create(:project_auto_devops, project: project, domain: nil)
        end

3375 3376
        it 'variables does not include AUTO_DEVOPS_DOMAIN' do
          is_expected.not_to include(domain_variable)
3377 3378 3379 3380 3381 3382 3383 3384
        end
      end

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

3385 3386
        it 'variables includes AUTO_DEVOPS_DOMAIN' do
          is_expected.to include(domain_variable)
3387 3388 3389
        end
      end
    end
3390 3391 3392 3393

    def domain_variable
      { key: 'AUTO_DEVOPS_DOMAIN', value: 'example.com', public: true }
    end
3394
  end
3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429

  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

3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
  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

3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
  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
3462 3463

  describe '#after_import' do
3464
    let(:project) { create(:project) }
3465 3466 3467

    it 'runs the correct hooks' do
      expect(project.repository).to receive(:after_import)
3468
      expect(project.wiki.repository).to receive(:after_import)
3469 3470 3471
      expect(project).to receive(:import_finish)
      expect(project).to receive(:update_project_counter_caches)
      expect(project).to receive(:remove_import_jid)
3472
      expect(project).to receive(:after_create_default_branch)
3473
      expect(project).to receive(:refresh_markdown_cache!)
3474 3475 3476

      project.after_import
    end
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 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513

    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)
3514 3515
        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])
3516 3517
      end
    end
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551
  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
3552 3553
        project = create(:project)
        create(:import_state, project: project, jid: '123')
3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579

        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
3580

3581 3582 3583 3584 3585 3586
  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

3587
      expect(rugged_config['gitlab.fullpath']).to eq project.full_path
3588 3589 3590 3591 3592
    end

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

3593
      expect { project.write_repository_config }.to change { rugged_config['gitlab.fullpath'] }.from('old/path').to(project.full_path)
3594 3595 3596 3597 3598 3599 3600 3601
    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
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614

  describe '#execute_hooks' do
    it 'executes the projects hooks with the specified scope' do
      hook1 = create(:project_hook, merge_requests_events: true, tag_push_events: false)
      hook2 = create(:project_hook, merge_requests_events: false, tag_push_events: true)
      project = create(:project, hooks: [hook1, hook2])

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

      project.execute_hooks({}, :tag_push_hooks)
    end

    it 'executes the system hooks with the specified scope' do
3615
      expect_any_instance_of(SystemHooksService).to receive(:execute_hooks).with({ data: 'data' }, :merge_request_hooks)
3616

3617 3618
      project = build(:project)
      project.execute_hooks({ data: 'data' }, :merge_request_hooks)
3619
    end
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636

    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
          project.execute_hooks({ data: 'data' }, :merge_request_hooks)
        end
      end.not_to raise_error # Sidekiq::Worker::EnqueueFromTransactionError
    end
3637
  end
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669

  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
3670

3671 3672
  context 'with cross project merge requests' do
    let(:user) { create(:user) }
3673 3674
    let(:target_project) { create(:project, :repository) }
    let(:project) { fork_project(target_project, nil, repository: true) }
3675 3676 3677 3678
    let!(:merge_request) do
      create(
        :merge_request,
        target_project: target_project,
3679
        target_branch: 'target-branch',
3680 3681
        source_project: project,
        source_branch: 'awesome-feature-1',
3682
        allow_collaboration: true
3683 3684 3685 3686
      )
    end

    before do
3687
      target_project.add_developer(user)
3688 3689
    end

3690 3691 3692 3693
    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
3694

3695 3696
      it 'does not include closed merge requests' do
        merge_request.close
3697

3698 3699 3700 3701 3702 3703
        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)
3704

3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
        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
3717 3718
    end

3719
    describe '#branch_allows_collaboration_push?' do
3720
      it 'allows access if the user can merge the merge request' do
3721
        expect(project.branch_allows_collaboration?(user, 'awesome-feature-1'))
3722 3723 3724
          .to be_truthy
      end

3725 3726 3727 3728 3729
      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

3730 3731 3732 3733
      it 'does not allow guest users access' do
        guest = create(:user)
        target_project.add_guest(guest)

3734
        expect(project.branch_allows_collaboration?(guest, 'awesome-feature-1'))
3735 3736 3737
          .to be_falsy
      end

3738
      it 'does not allow access to branches for which the merge request was closed' do
3739 3740
        create(:merge_request, :closed,
               target_project: target_project,
3741
               target_branch: 'target-branch',
3742 3743
               source_project: project,
               source_branch: 'rejected-feature-1',
3744
               allow_collaboration: true)
3745

3746
        expect(project.branch_allows_collaboration?(user, 'rejected-feature-1'))
3747 3748 3749
          .to be_falsy
      end

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

3753
        expect(project.branch_allows_collaboration?(user, 'awesome-feature-1'))
3754 3755 3756 3757
          .to be_falsy
      end

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

3760
        expect { 3.times { project.branch_allows_collaboration?(user, 'awesome-feature-1') } }
3761
          .not_to exceed_query_limit(control)
3762 3763 3764
      end

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

3768
          expect { 2.times { described_class.find(project.id).branch_allows_collaboration?(user, 'awesome-feature-1') } }
3769
            .not_to exceed_query_limit(control).with_threshold(2)
3770
        end
3771 3772 3773
      end
    end
  end
Rob Watson's avatar
Rob Watson committed
3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818

  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
3819

3820
  describe '#toggle_ci_cd_settings!' do
3821
    it 'toggles the value on #settings' do
3822
      project = create(:project, group_runners_enabled: false)
3823 3824 3825

      expect(project.group_runners_enabled).to be false

3826
      project.toggle_ci_cd_settings!(:group_runners_enabled)
3827 3828 3829 3830

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

3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851
  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

3852
    context 'when there is a gitlab deploy token associated but it is expired' do
3853 3854 3855 3856
      let!(:deploy_token) { create(:deploy_token, :gitlab_deploy_token, :expired, projects: [project]) }

      it { is_expected.to be_nil }
    end
3857

3858
    context 'when there is a deploy token associated with a different name' do
3859 3860 3861 3862
      let!(:deploy_token) { create(:deploy_token, projects: [project]) }

      it { is_expected.to be_nil }
    end
3863 3864 3865 3866 3867 3868 3869

    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
3870
  end
Jan Provaznik's avatar
Jan Provaznik committed
3871 3872 3873 3874 3875 3876 3877 3878

  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
3879

3880 3881 3882 3883 3884 3885 3886 3887 3888 3889
  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

3890 3891 3892 3893 3894
  def rugged_config
    Gitlab::GitalyClient::StorageSettings.allow_disk_access do
      project.repository.rugged.config
    end
  end
gitlabhq's avatar
gitlabhq committed
3895
end