diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2020-07-20 12:26:25 +0000 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2020-07-20 12:26:25 +0000 |
commit | a09983ae35713f5a2bbb100981116d31ce99826e (patch) | |
tree | 2ee2af7bd104d57086db360a7e6d8c9d5d43667a /spec/lib | |
parent | 18c5ab32b738c0b6ecb4d0df3994000482f34bd8 (diff) | |
download | gitlab-ce-a09983ae35713f5a2bbb100981116d31ce99826e.tar.gz |
Add latest changes from gitlab-org/gitlab@13-2-stable-ee
Diffstat (limited to 'spec/lib')
1451 files changed, 11450 insertions, 3726 deletions
diff --git a/spec/lib/after_commit_queue_spec.rb b/spec/lib/after_commit_queue_spec.rb index 8e9dfd90338..ca383808bfc 100644 --- a/spec/lib/after_commit_queue_spec.rb +++ b/spec/lib/after_commit_queue_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe AfterCommitQueue do +RSpec.describe AfterCommitQueue do it 'runs after transaction is committed' do called = false test_proc = proc { called = true } diff --git a/spec/lib/api/api_spec.rb b/spec/lib/api/api_spec.rb index c83d068ca50..cf08eaa7653 100644 --- a/spec/lib/api/api_spec.rb +++ b/spec/lib/api/api_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::API do +RSpec.describe API::API do describe '.prefix' do it 'has a prefix defined' do expect(described_class.prefix).to eq :api diff --git a/spec/lib/api/entities/branch_spec.rb b/spec/lib/api/entities/branch_spec.rb index 604f56c0cb2..e07b431964c 100644 --- a/spec/lib/api/entities/branch_spec.rb +++ b/spec/lib/api/entities/branch_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::Branch do +RSpec.describe API::Entities::Branch do describe '#as_json' do subject { entity.as_json } diff --git a/spec/lib/api/entities/deploy_key_spec.rb b/spec/lib/api/entities/deploy_key_spec.rb index 704dabae63b..6427d6eac8f 100644 --- a/spec/lib/api/entities/deploy_key_spec.rb +++ b/spec/lib/api/entities/deploy_key_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::DeployKey do +RSpec.describe API::Entities::DeployKey do describe '#as_json' do subject { entity.as_json } diff --git a/spec/lib/api/entities/deploy_keys_project_spec.rb b/spec/lib/api/entities/deploy_keys_project_spec.rb index a357467d7ce..57ffdc55736 100644 --- a/spec/lib/api/entities/deploy_keys_project_spec.rb +++ b/spec/lib/api/entities/deploy_keys_project_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::DeployKeysProject do +RSpec.describe API::Entities::DeployKeysProject do describe '#as_json' do subject { entity.as_json } diff --git a/spec/lib/api/entities/design_management/design_spec.rb b/spec/lib/api/entities/design_management/design_spec.rb index 50ca3b43c6a..fe449e3e9bc 100644 --- a/spec/lib/api/entities/design_management/design_spec.rb +++ b/spec/lib/api/entities/design_management/design_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::DesignManagement::Design do +RSpec.describe API::Entities::DesignManagement::Design do let_it_be(:design) { create(:design) } let(:entity) { described_class.new(design, request: double) } diff --git a/spec/lib/api/entities/job_request/image_spec.rb b/spec/lib/api/entities/job_request/image_spec.rb index 092c181ae9c..f13eab6a752 100644 --- a/spec/lib/api/entities/job_request/image_spec.rb +++ b/spec/lib/api/entities/job_request/image_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::JobRequest::Image do +RSpec.describe API::Entities::JobRequest::Image do let(:ports) { [{ number: 80, protocol: 'http', name: 'name' }]} let(:image) { double(name: 'image_name', entrypoint: ['foo'], ports: ports)} let(:entity) { described_class.new(image) } diff --git a/spec/lib/api/entities/job_request/port_spec.rb b/spec/lib/api/entities/job_request/port_spec.rb index 40ab4cd6231..4820c4a691b 100644 --- a/spec/lib/api/entities/job_request/port_spec.rb +++ b/spec/lib/api/entities/job_request/port_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::API::Entities::JobRequest::Port do +RSpec.describe ::API::Entities::JobRequest::Port do let(:port) { double(number: 80, protocol: 'http', name: 'name')} let(:entity) { described_class.new(port) } diff --git a/spec/lib/api/entities/merge_request_approvals_spec.rb b/spec/lib/api/entities/merge_request_approvals_spec.rb new file mode 100644 index 00000000000..cbbb037100a --- /dev/null +++ b/spec/lib/api/entities/merge_request_approvals_spec.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Entities::MergeRequestApprovals do + let(:user) { create(:user) } + let(:merge_request) { create(:merge_request) } + + subject { described_class.new(merge_request, current_user: user).as_json } + + before do + merge_request.project.add_developer(user) + end + + it 'serializes an approved merge request' do + create(:approval, merge_request: merge_request, user: user) + + is_expected.to eq({ + user_has_approved: true, + user_can_approve: false, + approved: true, + approved_by: [{ + user: API::Entities::UserBasic.new(user).as_json + }] + }) + end + + it 'serializes a merge request that is not approved' do + is_expected.to eq({ + user_has_approved: false, + user_can_approve: true, + approved: false, + approved_by: [] + }) + end +end diff --git a/spec/lib/api/entities/merge_request_basic_spec.rb b/spec/lib/api/entities/merge_request_basic_spec.rb new file mode 100644 index 00000000000..715fcf4bcdb --- /dev/null +++ b/spec/lib/api/entities/merge_request_basic_spec.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ::API::Entities::MergeRequestBasic do + let_it_be(:user) { create(:user) } + let_it_be(:project) { create(:project, :public) } + let_it_be(:merge_request) { create(:merge_request) } + let_it_be(:labels) { create_list(:label, 3) } + let_it_be(:merge_requests) { create_list(:labeled_merge_request, 10, :unique_branches, :with_diffs, labels: labels) } + + # This mimics the behavior of the `Grape::Entity` serializer + def present(obj) + described_class.new(obj).presented + end + + context "with :with_api_entity_associations scope" do + let(:scope) { MergeRequest.with_api_entity_associations } + + it "avoids N+1 queries" do + query = scope.find(merge_request.id) + + control = ActiveRecord::QueryRecorder.new do + present(query).to_json + end + + # stub the `head_commit_sha` as it will trigger a + # backward compatibility query that is out-of-scope + # for this test whenever it is `nil` + allow_any_instance_of(MergeRequestDiff).to receive(:head_commit_sha).and_return(Gitlab::Git::BLANK_SHA) + + query = scope.all + batch = ActiveRecord::QueryRecorder.new do + entities = query.map(&method(:present)) + + entities.to_json + end + + # The current threshold is 3 query per entity maximum. + expect(batch.count).to be_within(3 * query.count).of(control.count) + end + end +end diff --git a/spec/lib/api/entities/nuget/dependency_group_spec.rb b/spec/lib/api/entities/nuget/dependency_group_spec.rb new file mode 100644 index 00000000000..5a649be846b --- /dev/null +++ b/spec/lib/api/entities/nuget/dependency_group_spec.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Entities::Nuget::DependencyGroup do + let(:dependency_group) do + { + id: 'http://gitlab.com/Sandbox.App/1.0.0.json#dependencygroup', + type: 'PackageDependencyGroup', + target_framework: 'fwk test', + dependencies: [ + { + id: 'http://gitlab.com/Sandbox.App/1.0.0.json#dependency', + type: 'PackageDependency', + name: 'Dependency', + range: '2.0.0' + } + ] + } + end + + let(:expected) do + { + '@id': 'http://gitlab.com/Sandbox.App/1.0.0.json#dependencygroup', + '@type': 'PackageDependencyGroup', + 'targetFramework': 'fwk test', + 'dependencies': [ + { + '@id': 'http://gitlab.com/Sandbox.App/1.0.0.json#dependency', + '@type': 'PackageDependency', + 'id': 'Dependency', + 'range': '2.0.0' + } + ] + } + end + let(:entity) { described_class.new(dependency_group) } + + subject { entity.as_json } + + it { is_expected.to eq(expected) } + + context 'dependency group without target framework' do + let(:dependency_group_with_no_target_framework) { dependency_group.tap { |dg| dg[:target_framework] = nil } } + let(:expected_no_target_framework) { expected.except(:targetFramework) } + let(:entity) { described_class.new(dependency_group_with_no_target_framework) } + + it { is_expected.to eq(expected_no_target_framework) } + end +end diff --git a/spec/lib/api/entities/nuget/dependency_spec.rb b/spec/lib/api/entities/nuget/dependency_spec.rb new file mode 100644 index 00000000000..13897cc91f0 --- /dev/null +++ b/spec/lib/api/entities/nuget/dependency_spec.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Entities::Nuget::Dependency do + let(:dependency) do + { + id: 'http://gitlab.com/Sandbox.App/1.0.0.json#dependency', + type: 'PackageDependency', + name: 'Dependency', + range: '2.0.0' + } + end + + let(:expected) do + { + '@id': 'http://gitlab.com/Sandbox.App/1.0.0.json#dependency', + '@type': 'PackageDependency', + 'id': 'Dependency', + 'range': '2.0.0' + } + end + let(:entity) { described_class.new(dependency) } + + subject { entity.as_json } + + it { is_expected.to eq(expected) } +end diff --git a/spec/lib/api/entities/nuget/metadatum_spec.rb b/spec/lib/api/entities/nuget/metadatum_spec.rb new file mode 100644 index 00000000000..fe94ea3a69a --- /dev/null +++ b/spec/lib/api/entities/nuget/metadatum_spec.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Entities::Nuget::Metadatum do + let(:metadatum) do + { + project_url: 'http://sandbox.com/project', + license_url: 'http://sandbox.com/license', + icon_url: 'http://sandbox.com/icon' + } + end + let(:expected) do + { + 'projectUrl': 'http://sandbox.com/project', + 'licenseUrl': 'http://sandbox.com/license', + 'iconUrl': 'http://sandbox.com/icon' + } + end + let(:entity) { described_class.new(metadatum) } + + subject { entity.as_json } + + it { is_expected.to eq(expected) } + + %i[project_url license_url icon_url].each do |optional_field| + context "metadatum without #{optional_field}" do + let(:metadatum_without_a_field) { metadatum.except(optional_field) } + let(:expected_without_a_field) { expected.except(optional_field.to_s.camelize(:lower).to_sym) } + let(:entity) { described_class.new(metadatum_without_a_field) } + + it { is_expected.to eq(expected_without_a_field) } + end + end +end diff --git a/spec/lib/api/entities/nuget/package_metadata_catalog_entry_spec.rb b/spec/lib/api/entities/nuget/package_metadata_catalog_entry_spec.rb new file mode 100644 index 00000000000..c422b51bf3b --- /dev/null +++ b/spec/lib/api/entities/nuget/package_metadata_catalog_entry_spec.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Entities::Nuget::PackageMetadataCatalogEntry do + let(:entry) do + { + json_url: 'http://sandbox.com/json/package', + authors: 'Authors', + dependency_groups: [], + package_name: 'PackageTest', + package_version: '1.2.3', + tags: 'tag1 tag2 tag3', + archive_url: 'http://sandbox.com/archive/package', + summary: 'Summary', + metadatum: { + project_url: 'http://sandbox.com/project', + license_url: 'http://sandbox.com/license', + icon_url: 'http://sandbox.com/icon' + } + } + end + + let(:expected) do + { + '@id': 'http://sandbox.com/json/package', + 'id': 'PackageTest', + 'version': '1.2.3', + 'authors': 'Authors', + 'dependencyGroups': [], + 'tags': 'tag1 tag2 tag3', + 'packageContent': 'http://sandbox.com/archive/package', + 'summary': 'Summary', + 'projectUrl': 'http://sandbox.com/project', + 'licenseUrl': 'http://sandbox.com/license', + 'iconUrl': 'http://sandbox.com/icon' + } + end + + subject { described_class.new(entry).as_json } + + it { is_expected.to eq(expected) } +end diff --git a/spec/lib/api/entities/nuget/search_result_spec.rb b/spec/lib/api/entities/nuget/search_result_spec.rb new file mode 100644 index 00000000000..2a760c70224 --- /dev/null +++ b/spec/lib/api/entities/nuget/search_result_spec.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Entities::Nuget::SearchResult do + let(:search_result) do + { + type: 'Package', + authors: 'Author', + name: 'PackageTest', + version: '1.2.3', + versions: [ + { + json_url: 'http://sandbox.com/json/package', + downloads: 100, + version: '1.2.3' + } + ], + summary: 'Summary', + total_downloads: 100, + verified: true, + tags: 'tag1 tag2 tag3', + metadatum: { + project_url: 'http://sandbox.com/project', + license_url: 'http://sandbox.com/license', + icon_url: 'http://sandbox.com/icon' + } + } + end + let(:expected) do + { + '@type': 'Package', + 'authors': 'Author', + 'id': 'PackageTest', + 'title': 'PackageTest', + 'summary': 'Summary', + 'totalDownloads': 100, + 'verified': true, + 'version': '1.2.3', + 'tags': 'tag1 tag2 tag3', + 'projectUrl': 'http://sandbox.com/project', + 'licenseUrl': 'http://sandbox.com/license', + 'iconUrl': 'http://sandbox.com/icon', + 'versions': [ + { + '@id': 'http://sandbox.com/json/package', + 'downloads': 100, + 'version': '1.2.3' + } + ] + } + end + + subject { described_class.new(search_result).as_json } + + it { is_expected.to eq(expected) } +end diff --git a/spec/lib/api/entities/project_import_failed_relation_spec.rb b/spec/lib/api/entities/project_import_failed_relation_spec.rb index f8330713480..51a684c4564 100644 --- a/spec/lib/api/entities/project_import_failed_relation_spec.rb +++ b/spec/lib/api/entities/project_import_failed_relation_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::ProjectImportFailedRelation do +RSpec.describe API::Entities::ProjectImportFailedRelation do describe '#as_json' do subject { entity.as_json } diff --git a/spec/lib/api/entities/project_import_status_spec.rb b/spec/lib/api/entities/project_import_status_spec.rb index a800d703496..5eda613a6a6 100644 --- a/spec/lib/api/entities/project_import_status_spec.rb +++ b/spec/lib/api/entities/project_import_status_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::ProjectImportStatus do +RSpec.describe API::Entities::ProjectImportStatus do describe '#as_json' do subject { entity.as_json } diff --git a/spec/lib/api/entities/project_repository_storage_move_spec.rb b/spec/lib/api/entities/project_repository_storage_move_spec.rb index 1c38c8231d4..b0102dc376a 100644 --- a/spec/lib/api/entities/project_repository_storage_move_spec.rb +++ b/spec/lib/api/entities/project_repository_storage_move_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::ProjectRepositoryStorageMove do +RSpec.describe API::Entities::ProjectRepositoryStorageMove do describe '#as_json' do subject { entity.as_json } diff --git a/spec/lib/api/entities/release_spec.rb b/spec/lib/api/entities/release_spec.rb index fa9e1e74f9b..d57c283c1f4 100644 --- a/spec/lib/api/entities/release_spec.rb +++ b/spec/lib/api/entities/release_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::Release do +RSpec.describe API::Entities::Release do let_it_be(:project) { create(:project) } let(:release) { create(:release, project: project) } let(:evidence) { release.evidences.first } diff --git a/spec/lib/api/entities/snippet_spec.rb b/spec/lib/api/entities/snippet_spec.rb index dada0942e49..bcb8c364392 100644 --- a/spec/lib/api/entities/snippet_spec.rb +++ b/spec/lib/api/entities/snippet_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::API::Entities::Snippet do +RSpec.describe ::API::Entities::Snippet do let_it_be(:user) { create(:user) } let_it_be(:personal_snippet) { create(:personal_snippet, :repository, author: user ) } let_it_be(:project_snippet) { create(:project_snippet, :repository, author: user) } @@ -21,6 +21,16 @@ describe ::API::Entities::Snippet do it { expect(subject[:visibility]).to eq snippet.visibility } it { expect(subject).to include(:author) } + context 'with snippet_multiple_files feature disabled' do + before do + stub_feature_flags(snippet_multiple_files: false) + end + + it 'does not return files' do + expect(subject).not_to include(:files) + end + end + describe 'file_name' do it 'returns attribute from repository' do expect(subject[:file_name]).to eq snippet.blobs.first.path @@ -62,6 +72,49 @@ describe ::API::Entities::Snippet do end end end + + describe 'files' do + let(:blob) { snippet.blobs.first } + let(:ref) { blob.repository.root_ref } + + context 'when repository does not exist' do + it 'does not include the files attribute' do + allow(snippet).to receive(:repository_exists?).and_return(false) + + expect(subject).not_to include(:files) + end + end + + shared_examples 'snippet files' do + let(:file) { subject[:files].first } + + it 'returns all snippet files' do + expect(subject[:files].count).to eq snippet.blobs.count + end + + it 'has the file path' do + expect(file[:path]).to eq blob.path + end + + it 'has the raw url' do + expect(file[:raw_url]).to match(raw_url) + end + end + + context 'with PersonalSnippet' do + it_behaves_like 'snippet files' do + let(:snippet) { personal_snippet } + let(:raw_url) { "/-/snippets/#{snippet.id}/raw/#{ref}/#{blob.path}" } + end + end + + context 'with ProjectSnippet' do + it_behaves_like 'snippet files' do + let(:snippet) { project_snippet } + let(:raw_url) { "#{snippet.project.full_path}/-/snippets/#{snippet.id}/raw/#{ref}/#{blob.path}" } + end + end + end end context 'with PersonalSnippet' do diff --git a/spec/lib/api/entities/ssh_key_spec.rb b/spec/lib/api/entities/ssh_key_spec.rb index 25a0fecfb75..768ad416fbe 100644 --- a/spec/lib/api/entities/ssh_key_spec.rb +++ b/spec/lib/api/entities/ssh_key_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::SSHKey do +RSpec.describe API::Entities::SSHKey do describe '#as_json' do subject { entity.as_json } diff --git a/spec/lib/api/entities/user_spec.rb b/spec/lib/api/entities/user_spec.rb index 20524b197e0..99ffe0eb925 100644 --- a/spec/lib/api/entities/user_spec.rb +++ b/spec/lib/api/entities/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Entities::User do +RSpec.describe API::Entities::User do let(:user) { create(:user) } let(:current_user) { create(:user) } diff --git a/spec/lib/api/helpers/common_helpers_spec.rb b/spec/lib/api/helpers/common_helpers_spec.rb new file mode 100644 index 00000000000..5162d2f1000 --- /dev/null +++ b/spec/lib/api/helpers/common_helpers_spec.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Helpers::CommonHelpers do + include Rack::Test::Methods + + subject do + Class.new(Grape::API) do + helpers API::Helpers::CommonHelpers + + before do + coerce_nil_params_to_array! + end + + params do + requires :id, type: String + optional :array, type: Array, coerce_with: ::API::Validations::Types::CommaSeparatedToArray.coerce + optional :array_of_strings, type: Array[String], coerce_with: ::API::Validations::Types::CommaSeparatedToArray.coerce + optional :array_of_ints, type: Array[Integer], coerce_with: ::API::Validations::Types::CommaSeparatedToIntegerArray.coerce + end + get ":id" do + params.to_json + end + end + end + + def app + subject + end + + describe '.coerce_nil_params_to_array!' do + let(:json_response) { Gitlab::Json.parse(last_response.body) } + + it 'converts all nil parameters to empty arrays' do + get '/test?array=&array_of_strings=&array_of_ints=' + + expect(json_response['array']).to eq([]) + expect(json_response['array_of_strings']).to eq([]) + expect(json_response['array_of_ints']).to eq([]) + end + + it 'leaves non-nil parameters alone' do + get '/test?array=&array_of_strings=test,me&array_of_ints=1,2' + + expect(json_response['array']).to eq([]) + expect(json_response['array_of_strings']).to eq(%w(test me)) + expect(json_response['array_of_ints']).to eq([1, 2]) + end + end +end diff --git a/spec/lib/api/helpers/graphql_helpers_spec.rb b/spec/lib/api/helpers/graphql_helpers_spec.rb index c775ba6d5e8..678f4f8a3e3 100644 --- a/spec/lib/api/helpers/graphql_helpers_spec.rb +++ b/spec/lib/api/helpers/graphql_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Helpers::GraphqlHelpers do +RSpec.describe API::Helpers::GraphqlHelpers do describe 'run_graphql!' do let(:query) { '{ metadata { version } }' } diff --git a/spec/lib/api/helpers/label_helpers_spec.rb b/spec/lib/api/helpers/label_helpers_spec.rb index 138e9a22d70..007cb3248e2 100644 --- a/spec/lib/api/helpers/label_helpers_spec.rb +++ b/spec/lib/api/helpers/label_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Helpers::LabelHelpers do +RSpec.describe API::Helpers::LabelHelpers do describe 'create_service_params' do let(:label_helper) do Class.new do diff --git a/spec/lib/api/helpers/packages/dependency_proxy_helpers_spec.rb b/spec/lib/api/helpers/packages/dependency_proxy_helpers_spec.rb new file mode 100644 index 00000000000..ccf96bcbad6 --- /dev/null +++ b/spec/lib/api/helpers/packages/dependency_proxy_helpers_spec.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Helpers::Packages::DependencyProxyHelpers do + let_it_be(:helper) { Class.new.include(described_class).new } + + describe 'redirect_registry_request' do + using RSpec::Parameterized::TableSyntax + + let(:options) { {} } + + subject { helper.redirect_registry_request(forward_to_registry, package_type, options) { helper.fallback } } + + shared_examples 'executing fallback' do + it 'redirects to package registry' do + expect(helper).to receive(:registry_url).never + expect(helper).to receive(:redirect).never + expect(helper).to receive(:fallback).once + + subject + end + end + + shared_examples 'executing redirect' do + it 'redirects to package registry' do + expect(helper).to receive(:registry_url).once + expect(helper).to receive(:redirect).once + expect(helper).to receive(:fallback).never + + subject + end + end + + context 'with npm packages' do + let(:package_type) { :npm } + + where(:application_setting, :forward_to_registry, :example_name) do + true | true | 'executing redirect' + true | false | 'executing fallback' + false | true | 'executing fallback' + false | false | 'executing fallback' + end + + with_them do + before do + stub_application_setting(npm_package_requests_forwarding: application_setting) + end + + it_behaves_like params[:example_name] + end + end + + context 'with non-forwardable packages' do + let(:forward_to_registry) { true } + + before do + stub_application_setting(npm_package_requests_forwarding: true) + end + + Packages::Package.package_types.keys.without('npm').each do |pkg_type| + context "#{pkg_type}" do + let(:package_type) { pkg_type } + + it 'raises an error' do + expect { subject }.to raise_error(ArgumentError, "Can't build registry_url for package_type #{package_type}") + end + end + end + end + end +end diff --git a/spec/lib/api/helpers/packages_helpers_spec.rb b/spec/lib/api/helpers/packages_helpers_spec.rb new file mode 100644 index 00000000000..0c51e25bad9 --- /dev/null +++ b/spec/lib/api/helpers/packages_helpers_spec.rb @@ -0,0 +1,104 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Helpers::PackagesHelpers do + let_it_be(:helper) { Class.new.include(described_class).new } + let_it_be(:project) { create(:project) } + + describe 'authorize_packages_access!' do + subject { helper.authorize_packages_access!(project) } + + it 'authorizes packages access' do + expect(helper).to receive(:require_packages_enabled!) + expect(helper).to receive(:authorize_read_package!).with(project) + + expect(subject).to eq nil + end + end + + %i[read_package create_package destroy_package].each do |action| + describe "authorize_#{action}!" do + subject { helper.send("authorize_#{action}!", project) } + + it 'calls authorize!' do + expect(helper).to receive(:authorize!).with(action, project) + + expect(subject).to eq nil + end + end + end + + describe 'require_packages_enabled!' do + let(:packages_enabled) { true } + + subject { helper.require_packages_enabled! } + + before do + allow(::Gitlab.config.packages).to receive(:enabled).and_return(packages_enabled) + end + + context 'with packages enabled' do + it "doesn't call not_found!" do + expect(helper).to receive(:not_found!).never + + expect(subject).to eq nil + end + end + + context 'with package disabled' do + let(:packages_enabled) { false } + + it 'calls not_found!' do + expect(helper).to receive(:not_found!).once + + subject + end + end + end + + describe '#authorize_workhorse!' do + let_it_be(:headers) { {} } + + subject { helper.authorize_workhorse!(subject: project) } + + before do + allow(helper).to receive(:headers).and_return(headers) + end + + it 'authorizes workhorse' do + expect(helper).to receive(:authorize_upload!).with(project) + expect(helper).to receive(:status).with(200) + expect(helper).to receive(:content_type).with(Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE) + expect(Gitlab::Workhorse).to receive(:verify_api_request!).with(headers) + expect(::Packages::PackageFileUploader).to receive(:workhorse_authorize).with(has_length: true) + + expect(subject).to eq nil + end + + context 'without length' do + subject { helper.authorize_workhorse!(subject: project, has_length: false) } + + it 'authorizes workhorse' do + expect(helper).to receive(:authorize_upload!).with(project) + expect(helper).to receive(:status).with(200) + expect(helper).to receive(:content_type).with(Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE) + expect(Gitlab::Workhorse).to receive(:verify_api_request!).with(headers) + expect(::Packages::PackageFileUploader).to receive(:workhorse_authorize).with(has_length: false, maximum_size: ::API::Helpers::PackagesHelpers::MAX_PACKAGE_FILE_SIZE) + + expect(subject).to eq nil + end + end + end + + describe '#authorize_upload!' do + subject { helper.authorize_upload!(project) } + + it 'authorizes the upload' do + expect(helper).to receive(:authorize_create_package!).with(project) + expect(helper).to receive(:require_gitlab_workhorse!) + + expect(subject).to eq nil + end + end +end diff --git a/spec/lib/api/helpers/packages_manager_clients_helpers_spec.rb b/spec/lib/api/helpers/packages_manager_clients_helpers_spec.rb new file mode 100644 index 00000000000..80be5f7d10a --- /dev/null +++ b/spec/lib/api/helpers/packages_manager_clients_helpers_spec.rb @@ -0,0 +1,154 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe API::Helpers::PackagesManagerClientsHelpers do + let_it_be(:personal_access_token) { create(:personal_access_token) } + let_it_be(:username) { personal_access_token.user.username } + let_it_be(:helper) { Class.new.include(described_class).new } + let(:password) { personal_access_token.token } + + describe '#find_personal_access_token_from_http_basic_auth' do + let(:headers) { { Authorization: basic_http_auth(username, password) } } + + subject { helper.find_personal_access_token_from_http_basic_auth } + + before do + allow(helper).to receive(:headers).and_return(headers&.with_indifferent_access) + end + + context 'with a valid Authorization header' do + it { is_expected.to eq personal_access_token } + end + + context 'with an invalid Authorization header' do + where(:headers) do + [ + [{ Authorization: 'Invalid' }], + [{}], + [nil] + ] + end + + with_them do + it { is_expected.to be nil } + end + end + + context 'with an unknown Authorization header' do + let(:password) { 'Unknown' } + + it { is_expected.to be nil } + end + end + + describe '#find_job_from_http_basic_auth' do + let_it_be(:user) { personal_access_token.user } + + let(:job) { create(:ci_build, user: user) } + let(:password) { job.token } + let(:headers) { { Authorization: basic_http_auth(username, password) } } + + subject { helper.find_job_from_http_basic_auth } + + before do + allow(helper).to receive(:headers).and_return(headers&.with_indifferent_access) + end + + context 'with a valid Authorization header' do + it { is_expected.to eq job } + end + + context 'with an invalid Authorization header' do + where(:headers) do + [ + [{ Authorization: 'Invalid' }], + [{}], + [nil] + ] + end + + with_them do + it { is_expected.to be nil } + end + end + + context 'with an unknown Authorization header' do + let(:password) { 'Unknown' } + + it { is_expected.to be nil } + end + end + + describe '#find_deploy_token_from_http_basic_auth' do + let_it_be(:deploy_token) { create(:deploy_token) } + let(:token) { deploy_token.token } + let(:headers) { { Authorization: basic_http_auth(deploy_token.username, token) } } + + subject { helper.find_deploy_token_from_http_basic_auth } + + before do + allow(helper).to receive(:headers).and_return(headers&.with_indifferent_access) + end + + context 'with a valid Authorization header' do + it { is_expected.to eq deploy_token } + end + + context 'with an invalid Authorization header' do + where(:headers) do + [ + [{ Authorization: 'Invalid' }], + [{}], + [nil] + ] + end + + with_them do + it { is_expected.to be nil } + end + end + + context 'with an invalid token' do + let(:token) { 'Unknown' } + + it { is_expected.to be nil } + end + end + + describe '#uploaded_package_file' do + let_it_be(:params) { {} } + + subject { helper.uploaded_package_file } + + before do + allow(helper).to receive(:params).and_return(params) + end + + context 'with valid uploaded package file' do + let_it_be(:uploaded_file) { Object.new } + + before do + allow(UploadedFile).to receive(:from_params).and_return(uploaded_file) + end + + it { is_expected.to be uploaded_file } + end + + context 'with invalid uploaded package file' do + before do + allow(UploadedFile).to receive(:from_params).and_return(nil) + end + + it 'fails with bad_request!' do + expect(helper).to receive(:bad_request!) + + expect(subject).to be nil + end + end + end + + def basic_http_auth(username, password) + ActionController::HttpAuthentication::Basic.encode_credentials(username, password) + end +end diff --git a/spec/lib/api/helpers/pagination_spec.rb b/spec/lib/api/helpers/pagination_spec.rb index 796c753d6c4..a008c1adeac 100644 --- a/spec/lib/api/helpers/pagination_spec.rb +++ b/spec/lib/api/helpers/pagination_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Helpers::Pagination do +RSpec.describe API::Helpers::Pagination do subject { Class.new.include(described_class).new } let(:paginator) { double('paginator') } diff --git a/spec/lib/api/helpers/pagination_strategies_spec.rb b/spec/lib/api/helpers/pagination_strategies_spec.rb index eaa71159714..e8a4243b407 100644 --- a/spec/lib/api/helpers/pagination_strategies_spec.rb +++ b/spec/lib/api/helpers/pagination_strategies_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Helpers::PaginationStrategies do +RSpec.describe API::Helpers::PaginationStrategies do subject { Class.new.include(described_class).new } let(:expected_result) { double("result") } diff --git a/spec/lib/api/helpers/related_resources_helpers_spec.rb b/spec/lib/api/helpers/related_resources_helpers_spec.rb index eeeb22abd10..a0dc69536b4 100644 --- a/spec/lib/api/helpers/related_resources_helpers_spec.rb +++ b/spec/lib/api/helpers/related_resources_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Helpers::RelatedResourcesHelpers do +RSpec.describe API::Helpers::RelatedResourcesHelpers do subject(:helpers) do Class.new.include(described_class).new end diff --git a/spec/lib/api/helpers/version_spec.rb b/spec/lib/api/helpers/version_spec.rb index a9f33962537..a87a3c5a026 100644 --- a/spec/lib/api/helpers/version_spec.rb +++ b/spec/lib/api/helpers/version_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Helpers::Version do +RSpec.describe API::Helpers::Version do describe '.new' do it 'is possible to initialize it with existing API version' do expect(described_class.new('v4').to_s).to eq 'v4' diff --git a/spec/lib/api/helpers_spec.rb b/spec/lib/api/helpers_spec.rb index 3595d06a184..8cba1e0794a 100644 --- a/spec/lib/api/helpers_spec.rb +++ b/spec/lib/api/helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Helpers do +RSpec.describe API::Helpers do subject { Class.new.include(described_class).new } describe '#find_project' do diff --git a/spec/lib/api/support/git_access_actor_spec.rb b/spec/lib/api/support/git_access_actor_spec.rb index 69637947c79..70753856419 100644 --- a/spec/lib/api/support/git_access_actor_spec.rb +++ b/spec/lib/api/support/git_access_actor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Support::GitAccessActor do +RSpec.describe API::Support::GitAccessActor do let(:user) { nil } let(:key) { nil } diff --git a/spec/lib/api/validations/validators/absence_spec.rb b/spec/lib/api/validations/validators/absence_spec.rb index 31120979d4f..bfecaf4e243 100644 --- a/spec/lib/api/validations/validators/absence_spec.rb +++ b/spec/lib/api/validations/validators/absence_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::Absence do +RSpec.describe API::Validations::Validators::Absence do include ApiValidatorsHelpers subject do diff --git a/spec/lib/api/validations/validators/array_none_any_spec.rb b/spec/lib/api/validations/validators/array_none_any_spec.rb index 03f1c63b117..833adea6554 100644 --- a/spec/lib/api/validations/validators/array_none_any_spec.rb +++ b/spec/lib/api/validations/validators/array_none_any_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::ArrayNoneAny do +RSpec.describe API::Validations::Validators::ArrayNoneAny do include ApiValidatorsHelpers subject do diff --git a/spec/lib/api/validations/validators/file_path_spec.rb b/spec/lib/api/validations/validators/file_path_spec.rb index 8679f102d23..2c79260b8d5 100644 --- a/spec/lib/api/validations/validators/file_path_spec.rb +++ b/spec/lib/api/validations/validators/file_path_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::FilePath do +RSpec.describe API::Validations::Validators::FilePath do include ApiValidatorsHelpers subject do diff --git a/spec/lib/api/validations/validators/git_ref_spec.rb b/spec/lib/api/validations/validators/git_ref_spec.rb index 84de6272fe1..0d2d9e8f39a 100644 --- a/spec/lib/api/validations/validators/git_ref_spec.rb +++ b/spec/lib/api/validations/validators/git_ref_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::GitRef do +RSpec.describe API::Validations::Validators::GitRef do include ApiValidatorsHelpers subject do diff --git a/spec/lib/api/validations/validators/git_sha_spec.rb b/spec/lib/api/validations/validators/git_sha_spec.rb index 39c2fe1dcf9..ae6be52a4c7 100644 --- a/spec/lib/api/validations/validators/git_sha_spec.rb +++ b/spec/lib/api/validations/validators/git_sha_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::GitSha do +RSpec.describe API::Validations::Validators::GitSha do include ApiValidatorsHelpers let(:sha) { RepoHelpers.sample_commit.id } diff --git a/spec/lib/api/validations/validators/integer_none_any_spec.rb b/spec/lib/api/validations/validators/integer_none_any_spec.rb index a42f69fd96e..33fa7688d18 100644 --- a/spec/lib/api/validations/validators/integer_none_any_spec.rb +++ b/spec/lib/api/validations/validators/integer_none_any_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::IntegerNoneAny do +RSpec.describe API::Validations::Validators::IntegerNoneAny do include ApiValidatorsHelpers subject do diff --git a/spec/lib/api/validations/validators/limit_spec.rb b/spec/lib/api/validations/validators/limit_spec.rb index 600f74e1fb2..d71dde470cc 100644 --- a/spec/lib/api/validations/validators/limit_spec.rb +++ b/spec/lib/api/validations/validators/limit_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::Limit do +RSpec.describe API::Validations::Validators::Limit do include ApiValidatorsHelpers subject do diff --git a/spec/lib/api/validations/validators/untrusted_regexp_spec.rb b/spec/lib/api/validations/validators/untrusted_regexp_spec.rb index 491bf94fd79..def67c94de0 100644 --- a/spec/lib/api/validations/validators/untrusted_regexp_spec.rb +++ b/spec/lib/api/validations/validators/untrusted_regexp_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe API::Validations::Validators::UntrustedRegexp do +RSpec.describe API::Validations::Validators::UntrustedRegexp do include ApiValidatorsHelpers subject do diff --git a/spec/lib/backup/files_spec.rb b/spec/lib/backup/files_spec.rb index b75f3bafeef..a7374b82ce0 100644 --- a/spec/lib/backup/files_spec.rb +++ b/spec/lib/backup/files_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Backup::Files do +RSpec.describe Backup::Files do let(:progress) { StringIO.new } let!(:project) { create(:project) } diff --git a/spec/lib/backup/manager_spec.rb b/spec/lib/backup/manager_spec.rb index b86e92d5969..38a5c30506b 100644 --- a/spec/lib/backup/manager_spec.rb +++ b/spec/lib/backup/manager_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Backup::Manager do +RSpec.describe Backup::Manager do include StubENV let(:progress) { StringIO.new } diff --git a/spec/lib/backup/repository_spec.rb b/spec/lib/backup/repository_spec.rb index e0afa256581..c073a45bf68 100644 --- a/spec/lib/backup/repository_spec.rb +++ b/spec/lib/backup/repository_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Backup::Repository do +RSpec.describe Backup::Repository do let(:progress) { StringIO.new } let!(:project) { create(:project, :wiki_repo) } diff --git a/spec/lib/backup/uploads_spec.rb b/spec/lib/backup/uploads_spec.rb index 1f49baeff69..7c2d715b580 100644 --- a/spec/lib/backup/uploads_spec.rb +++ b/spec/lib/backup/uploads_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Backup::Uploads do +RSpec.describe Backup::Uploads do let(:progress) { StringIO.new } subject(:backup) { described_class.new(progress) } diff --git a/spec/lib/banzai/color_parser_spec.rb b/spec/lib/banzai/color_parser_spec.rb index d9202ce77db..95b3955d8fe 100644 --- a/spec/lib/banzai/color_parser_spec.rb +++ b/spec/lib/banzai/color_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ColorParser do +RSpec.describe Banzai::ColorParser do describe '.parse' do context 'HEX format' do [ diff --git a/spec/lib/banzai/commit_renderer_spec.rb b/spec/lib/banzai/commit_renderer_spec.rb index e5a16b167be..a10dd6eb3a2 100644 --- a/spec/lib/banzai/commit_renderer_spec.rb +++ b/spec/lib/banzai/commit_renderer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::CommitRenderer do +RSpec.describe Banzai::CommitRenderer do describe '.render', :clean_gitlab_redis_cache do it 'renders a commit description and title' do user = build(:user) diff --git a/spec/lib/banzai/cross_project_reference_spec.rb b/spec/lib/banzai/cross_project_reference_spec.rb index cf41af7e7a1..95b78ceb5d5 100644 --- a/spec/lib/banzai/cross_project_reference_spec.rb +++ b/spec/lib/banzai/cross_project_reference_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::CrossProjectReference do +RSpec.describe Banzai::CrossProjectReference do let(:including_class) { Class.new.include(described_class).new } before do diff --git a/spec/lib/banzai/filter/absolute_link_filter_spec.rb b/spec/lib/banzai/filter/absolute_link_filter_spec.rb index b61bd496dba..2cb70850dca 100644 --- a/spec/lib/banzai/filter/absolute_link_filter_spec.rb +++ b/spec/lib/banzai/filter/absolute_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::AbsoluteLinkFilter do +RSpec.describe Banzai::Filter::AbsoluteLinkFilter do def filter(doc, context = {}) described_class.call(doc, context) end diff --git a/spec/lib/banzai/filter/abstract_reference_filter_spec.rb b/spec/lib/banzai/filter/abstract_reference_filter_spec.rb index 6890a70518b..797f1c8d52f 100644 --- a/spec/lib/banzai/filter/abstract_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/abstract_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::AbstractReferenceFilter do +RSpec.describe Banzai::Filter::AbstractReferenceFilter do let_it_be(:project) { create(:project) } let(:doc) { Nokogiri::HTML.fragment('') } diff --git a/spec/lib/banzai/filter/ascii_doc_post_processing_filter_spec.rb b/spec/lib/banzai/filter/ascii_doc_post_processing_filter_spec.rb index bd06dae26ba..334d5c59828 100644 --- a/spec/lib/banzai/filter/ascii_doc_post_processing_filter_spec.rb +++ b/spec/lib/banzai/filter/ascii_doc_post_processing_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::AsciiDocPostProcessingFilter do +RSpec.describe Banzai::Filter::AsciiDocPostProcessingFilter do include FilterSpecHelper it "adds class for elements with data-math-style" do diff --git a/spec/lib/banzai/filter/asset_proxy_filter_spec.rb b/spec/lib/banzai/filter/asset_proxy_filter_spec.rb index ff2346fe1ba..2a4ee28130b 100644 --- a/spec/lib/banzai/filter/asset_proxy_filter_spec.rb +++ b/spec/lib/banzai/filter/asset_proxy_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::AssetProxyFilter do +RSpec.describe Banzai::Filter::AssetProxyFilter do include FilterSpecHelper def image(path) diff --git a/spec/lib/banzai/filter/audio_link_filter_spec.rb b/spec/lib/banzai/filter/audio_link_filter_spec.rb index a8459137169..4198a50e980 100644 --- a/spec/lib/banzai/filter/audio_link_filter_spec.rb +++ b/spec/lib/banzai/filter/audio_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::AudioLinkFilter do +RSpec.describe Banzai::Filter::AudioLinkFilter do def filter(doc, contexts = {}) contexts.reverse_merge!({ project: project diff --git a/spec/lib/banzai/filter/autolink_filter_spec.rb b/spec/lib/banzai/filter/autolink_filter_spec.rb index be6192f9ead..ba15860f3c9 100644 --- a/spec/lib/banzai/filter/autolink_filter_spec.rb +++ b/spec/lib/banzai/filter/autolink_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::AutolinkFilter do +RSpec.describe Banzai::Filter::AutolinkFilter do include FilterSpecHelper let(:link) { 'http://about.gitlab.com/' } diff --git a/spec/lib/banzai/filter/blockquote_fence_filter_spec.rb b/spec/lib/banzai/filter/blockquote_fence_filter_spec.rb index 8e955ec3b6b..e736943914b 100644 --- a/spec/lib/banzai/filter/blockquote_fence_filter_spec.rb +++ b/spec/lib/banzai/filter/blockquote_fence_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::BlockquoteFenceFilter do +RSpec.describe Banzai::Filter::BlockquoteFenceFilter do include FilterSpecHelper it 'converts blockquote fences to blockquote lines' do diff --git a/spec/lib/banzai/filter/broadcast_message_placeholders_filter_spec.rb b/spec/lib/banzai/filter/broadcast_message_placeholders_filter_spec.rb index 1a90abc12d9..a2d35eaa6b6 100644 --- a/spec/lib/banzai/filter/broadcast_message_placeholders_filter_spec.rb +++ b/spec/lib/banzai/filter/broadcast_message_placeholders_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::BroadcastMessagePlaceholdersFilter do +RSpec.describe Banzai::Filter::BroadcastMessagePlaceholdersFilter do include FilterSpecHelper subject { filter(text, current_user: user, broadcast_message_placeholders: true).to_html } diff --git a/spec/lib/banzai/filter/broadcast_message_sanitization_filter_spec.rb b/spec/lib/banzai/filter/broadcast_message_sanitization_filter_spec.rb index 317ac7ef854..1f65268bd3c 100644 --- a/spec/lib/banzai/filter/broadcast_message_sanitization_filter_spec.rb +++ b/spec/lib/banzai/filter/broadcast_message_sanitization_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::BroadcastMessageSanitizationFilter do +RSpec.describe Banzai::Filter::BroadcastMessageSanitizationFilter do include FilterSpecHelper it_behaves_like 'default whitelist' diff --git a/spec/lib/banzai/filter/color_filter_spec.rb b/spec/lib/banzai/filter/color_filter_spec.rb index f8931d37b99..dced3671323 100644 --- a/spec/lib/banzai/filter/color_filter_spec.rb +++ b/spec/lib/banzai/filter/color_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::ColorFilter, lib: true do +RSpec.describe Banzai::Filter::ColorFilter, lib: true do include FilterSpecHelper let(:color) { '#F00' } diff --git a/spec/lib/banzai/filter/commit_range_reference_filter_spec.rb b/spec/lib/banzai/filter/commit_range_reference_filter_spec.rb index 5cfb0e6e6f7..f04d3212437 100644 --- a/spec/lib/banzai/filter/commit_range_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/commit_range_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::CommitRangeReferenceFilter do +RSpec.describe Banzai::Filter::CommitRangeReferenceFilter do include FilterSpecHelper let(:project) { create(:project, :public, :repository) } diff --git a/spec/lib/banzai/filter/commit_reference_filter_spec.rb b/spec/lib/banzai/filter/commit_reference_filter_spec.rb index 63ec597a0ba..925fd031d95 100644 --- a/spec/lib/banzai/filter/commit_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/commit_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::CommitReferenceFilter do +RSpec.describe Banzai::Filter::CommitReferenceFilter do include FilterSpecHelper let(:project) { create(:project, :public, :repository) } diff --git a/spec/lib/banzai/filter/commit_trailers_filter_spec.rb b/spec/lib/banzai/filter/commit_trailers_filter_spec.rb index 192d00805e0..03a6cc34962 100644 --- a/spec/lib/banzai/filter/commit_trailers_filter_spec.rb +++ b/spec/lib/banzai/filter/commit_trailers_filter_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'ffaker' -describe Banzai::Filter::CommitTrailersFilter do +RSpec.describe Banzai::Filter::CommitTrailersFilter do include FilterSpecHelper include CommitTrailersSpecHelper diff --git a/spec/lib/banzai/filter/design_reference_filter_spec.rb b/spec/lib/banzai/filter/design_reference_filter_spec.rb index 8a6c2e3b3f9..1b558754932 100644 --- a/spec/lib/banzai/filter/design_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/design_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::DesignReferenceFilter do +RSpec.describe Banzai::Filter::DesignReferenceFilter do include FilterSpecHelper include DesignManagementTestHelpers diff --git a/spec/lib/banzai/filter/emoji_filter_spec.rb b/spec/lib/banzai/filter/emoji_filter_spec.rb index 4e163668a28..d78763b6939 100644 --- a/spec/lib/banzai/filter/emoji_filter_spec.rb +++ b/spec/lib/banzai/filter/emoji_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::EmojiFilter do +RSpec.describe Banzai::Filter::EmojiFilter do include FilterSpecHelper it 'replaces supported name emoji' do diff --git a/spec/lib/banzai/filter/external_issue_reference_filter_spec.rb b/spec/lib/banzai/filter/external_issue_reference_filter_spec.rb index a70c820f97a..7d8fb183dbb 100644 --- a/spec/lib/banzai/filter/external_issue_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/external_issue_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::ExternalIssueReferenceFilter do +RSpec.describe Banzai::Filter::ExternalIssueReferenceFilter do include FilterSpecHelper shared_examples_for "external issue tracker" do diff --git a/spec/lib/banzai/filter/external_link_filter_spec.rb b/spec/lib/banzai/filter/external_link_filter_spec.rb index 4b2500b31f7..630730dfc1a 100644 --- a/spec/lib/banzai/filter/external_link_filter_spec.rb +++ b/spec/lib/banzai/filter/external_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -shared_examples 'an external link with rel attribute' do +RSpec.shared_examples 'an external link with rel attribute' do it 'adds rel="nofollow" to external links' do expect(doc.at_css('a')).to have_attribute('rel') expect(doc.at_css('a')['rel']).to include 'nofollow' @@ -19,7 +19,7 @@ shared_examples 'an external link with rel attribute' do end end -describe Banzai::Filter::ExternalLinkFilter do +RSpec.describe Banzai::Filter::ExternalLinkFilter do include FilterSpecHelper it 'ignores elements without an href attribute' do diff --git a/spec/lib/banzai/filter/footnote_filter_spec.rb b/spec/lib/banzai/filter/footnote_filter_spec.rb index c6dcb4e46fd..01b7319fab1 100644 --- a/spec/lib/banzai/filter/footnote_filter_spec.rb +++ b/spec/lib/banzai/filter/footnote_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::FootnoteFilter do +RSpec.describe Banzai::Filter::FootnoteFilter do include FilterSpecHelper # first[^1] and second[^second] diff --git a/spec/lib/banzai/filter/front_matter_filter_spec.rb b/spec/lib/banzai/filter/front_matter_filter_spec.rb index 1b5b1770615..3f966c94dd3 100644 --- a/spec/lib/banzai/filter/front_matter_filter_spec.rb +++ b/spec/lib/banzai/filter/front_matter_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::FrontMatterFilter do +RSpec.describe Banzai::Filter::FrontMatterFilter do include FilterSpecHelper it 'allows for `encoding:` before the front matter' do diff --git a/spec/lib/banzai/filter/gollum_tags_filter_spec.rb b/spec/lib/banzai/filter/gollum_tags_filter_spec.rb index 00d8b871224..2576dd1bf07 100644 --- a/spec/lib/banzai/filter/gollum_tags_filter_spec.rb +++ b/spec/lib/banzai/filter/gollum_tags_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::GollumTagsFilter do +RSpec.describe Banzai::Filter::GollumTagsFilter do include FilterSpecHelper let(:project) { create(:project) } diff --git a/spec/lib/banzai/filter/html_entity_filter_spec.rb b/spec/lib/banzai/filter/html_entity_filter_spec.rb index 6017380725d..d88fa21cde7 100644 --- a/spec/lib/banzai/filter/html_entity_filter_spec.rb +++ b/spec/lib/banzai/filter/html_entity_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::HtmlEntityFilter do +RSpec.describe Banzai::Filter::HtmlEntityFilter do include FilterSpecHelper let(:unescaped) { 'foo <strike attr="foo">&&&</strike>' } diff --git a/spec/lib/banzai/filter/image_lazy_load_filter_spec.rb b/spec/lib/banzai/filter/image_lazy_load_filter_spec.rb index 6475fd14ce4..9f5aa558f24 100644 --- a/spec/lib/banzai/filter/image_lazy_load_filter_spec.rb +++ b/spec/lib/banzai/filter/image_lazy_load_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::ImageLazyLoadFilter do +RSpec.describe Banzai::Filter::ImageLazyLoadFilter do include FilterSpecHelper def image(path) diff --git a/spec/lib/banzai/filter/image_link_filter_spec.rb b/spec/lib/banzai/filter/image_link_filter_spec.rb index 011e3a1e2da..5c04f6b2b3e 100644 --- a/spec/lib/banzai/filter/image_link_filter_spec.rb +++ b/spec/lib/banzai/filter/image_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::ImageLinkFilter do +RSpec.describe Banzai::Filter::ImageLinkFilter do include FilterSpecHelper def image(path) diff --git a/spec/lib/banzai/filter/inline_cluster_metrics_filter_spec.rb b/spec/lib/banzai/filter/inline_cluster_metrics_filter_spec.rb new file mode 100644 index 00000000000..fe048daa601 --- /dev/null +++ b/spec/lib/banzai/filter/inline_cluster_metrics_filter_spec.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Banzai::Filter::InlineClusterMetricsFilter do + include FilterSpecHelper + + let!(:cluster) { create(:cluster) } + let!(:project) { create(:project) } + let(:params) { [project.namespace.path, project.path, cluster.id] } + let(:query_params) { { group: 'Food metrics', title: 'Pizza Consumption', y_label: 'Slice Count' } } + let(:trigger_url) { urls.namespace_project_cluster_url(*params, **query_params) } + let(:dashboard_url) do + urls.metrics_dashboard_namespace_project_cluster_url( + *params, + **{ + embedded: 'true', + cluster_type: 'project', + format: :json + }.merge(query_params) + ) + end + + it_behaves_like 'a metrics embed filter' +end diff --git a/spec/lib/banzai/filter/inline_diff_filter_spec.rb b/spec/lib/banzai/filter/inline_diff_filter_spec.rb index c09065fb746..1ef00139db2 100644 --- a/spec/lib/banzai/filter/inline_diff_filter_spec.rb +++ b/spec/lib/banzai/filter/inline_diff_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::InlineDiffFilter do +RSpec.describe Banzai::Filter::InlineDiffFilter do include FilterSpecHelper it 'adds inline diff span tags for deletions when using square brackets' do diff --git a/spec/lib/banzai/filter/inline_grafana_metrics_filter_spec.rb b/spec/lib/banzai/filter/inline_grafana_metrics_filter_spec.rb index 28bf5bd3e92..8bdb24ab08c 100644 --- a/spec/lib/banzai/filter/inline_grafana_metrics_filter_spec.rb +++ b/spec/lib/banzai/filter/inline_grafana_metrics_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::InlineGrafanaMetricsFilter do +RSpec.describe Banzai::Filter::InlineGrafanaMetricsFilter do include FilterSpecHelper let_it_be(:project) { create(:project) } diff --git a/spec/lib/banzai/filter/inline_metrics_filter_spec.rb b/spec/lib/banzai/filter/inline_metrics_filter_spec.rb index 1546a5e88ed..9b0b95b9da2 100644 --- a/spec/lib/banzai/filter/inline_metrics_filter_spec.rb +++ b/spec/lib/banzai/filter/inline_metrics_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::InlineMetricsFilter do +RSpec.describe Banzai::Filter::InlineMetricsFilter do include FilterSpecHelper let(:params) { ['foo', 'bar', 12] } diff --git a/spec/lib/banzai/filter/inline_metrics_redactor_filter_spec.rb b/spec/lib/banzai/filter/inline_metrics_redactor_filter_spec.rb index 9d8cd729958..cafcaef8ae2 100644 --- a/spec/lib/banzai/filter/inline_metrics_redactor_filter_spec.rb +++ b/spec/lib/banzai/filter/inline_metrics_redactor_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::InlineMetricsRedactorFilter do +RSpec.describe Banzai::Filter::InlineMetricsRedactorFilter do include FilterSpecHelper let_it_be(:project) { create(:project) } @@ -29,6 +29,26 @@ describe Banzai::Filter::InlineMetricsRedactorFilter do it_behaves_like 'retains the embed placeholder when applicable' end + context 'for a cluster metric embed' do + let_it_be(:cluster) { create(:cluster, :provided_by_gcp, :project, projects: [project]) } + let(:params) { [project.namespace.path, project.path, cluster.id] } + let(:query_params) { { group: 'Cluster Health', title: 'CPU Usage', y_label: 'CPU (cores)' } } + let(:url) { urls.metrics_dashboard_namespace_project_cluster_url(*params, **query_params) } + + context 'with user who can read cluster' do + it_behaves_like 'redacts the embed placeholder' + it_behaves_like 'retains the embed placeholder when applicable' + end + + context 'without user who can read cluster' do + let(:doc) { filter(input, current_user: create(:user)) } + + it 'redacts the embed placeholder' do + expect(doc.to_s).to be_empty + end + end + end + context 'the user has requisite permissions' do let(:user) { create(:user) } let(:doc) { filter(input, current_user: user) } diff --git a/spec/lib/banzai/filter/issuable_state_filter_spec.rb b/spec/lib/banzai/filter/issuable_state_filter_spec.rb index 5950b6878ef..a3851fd7cca 100644 --- a/spec/lib/banzai/filter/issuable_state_filter_spec.rb +++ b/spec/lib/banzai/filter/issuable_state_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::IssuableStateFilter do +RSpec.describe Banzai::Filter::IssuableStateFilter do include ActionView::Helpers::UrlHelper include FilterSpecHelper diff --git a/spec/lib/banzai/filter/issue_reference_filter_spec.rb b/spec/lib/banzai/filter/issue_reference_filter_spec.rb index 603da2b4421..98955d5cde9 100644 --- a/spec/lib/banzai/filter/issue_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/issue_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::IssueReferenceFilter do +RSpec.describe Banzai::Filter::IssueReferenceFilter do include FilterSpecHelper include DesignManagementTestHelpers diff --git a/spec/lib/banzai/filter/jira_import/adf_to_commonmark_filter_spec.rb b/spec/lib/banzai/filter/jira_import/adf_to_commonmark_filter_spec.rb new file mode 100644 index 00000000000..287b5774048 --- /dev/null +++ b/spec/lib/banzai/filter/jira_import/adf_to_commonmark_filter_spec.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Banzai::Filter::JiraImport::AdfToCommonmarkFilter do + include FilterSpecHelper + + let_it_be(:fixtures_path) { 'lib/kramdown/atlassian_document_format' } + + it 'renders a complex document' do + source = fixture_file(File.join(fixtures_path, 'complex_document.json')) + target = fixture_file(File.join(fixtures_path, 'complex_document.md')) + + expect(filter(source)).to eq target + end + + it 'renders original source when it is invalid JSON' do + source = fixture_file(File.join(fixtures_path, 'invalid_json.json')) + + expect(filter(source)).to eq "Invalid Atlassian Document Format JSON\n\n#{source}" + end + + it 'renders original source when missing document node' do + source = fixture_file(File.join(fixtures_path, 'invalid_no_doc.json')) + + expect(filter(source)).to eq "Invalid Atlassian Document Format JSON\n\n#{source}" + end +end diff --git a/spec/lib/banzai/filter/label_reference_filter_spec.rb b/spec/lib/banzai/filter/label_reference_filter_spec.rb index 0b697ab2040..dadf98d9b76 100644 --- a/spec/lib/banzai/filter/label_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/label_reference_filter_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'html/pipeline' -describe Banzai::Filter::LabelReferenceFilter do +RSpec.describe Banzai::Filter::LabelReferenceFilter do include FilterSpecHelper let(:project) { create(:project, :public, name: 'sample-project') } diff --git a/spec/lib/banzai/filter/markdown_filter_spec.rb b/spec/lib/banzai/filter/markdown_filter_spec.rb index d0a43564903..8d01a651651 100644 --- a/spec/lib/banzai/filter/markdown_filter_spec.rb +++ b/spec/lib/banzai/filter/markdown_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::MarkdownFilter do +RSpec.describe Banzai::Filter::MarkdownFilter do include FilterSpecHelper describe 'markdown engine from context' do diff --git a/spec/lib/banzai/filter/math_filter_spec.rb b/spec/lib/banzai/filter/math_filter_spec.rb index c8fd92edcdf..9f6688f4f7d 100644 --- a/spec/lib/banzai/filter/math_filter_spec.rb +++ b/spec/lib/banzai/filter/math_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::MathFilter do +RSpec.describe Banzai::Filter::MathFilter do include FilterSpecHelper it 'leaves regular inline code unchanged' do diff --git a/spec/lib/banzai/filter/merge_request_reference_filter_spec.rb b/spec/lib/banzai/filter/merge_request_reference_filter_spec.rb index 12ee952b10e..f24fcf98b1f 100644 --- a/spec/lib/banzai/filter/merge_request_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/merge_request_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::MergeRequestReferenceFilter do +RSpec.describe Banzai::Filter::MergeRequestReferenceFilter do include FilterSpecHelper let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/filter/mermaid_filter_spec.rb b/spec/lib/banzai/filter/mermaid_filter_spec.rb index ae6725cc14c..c9bfcffe98f 100644 --- a/spec/lib/banzai/filter/mermaid_filter_spec.rb +++ b/spec/lib/banzai/filter/mermaid_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::MermaidFilter do +RSpec.describe Banzai::Filter::MermaidFilter do include FilterSpecHelper it 'adds `js-render-mermaid` class to the `code` tag' do diff --git a/spec/lib/banzai/filter/milestone_reference_filter_spec.rb b/spec/lib/banzai/filter/milestone_reference_filter_spec.rb index 0c8413adcba..62b1711ee57 100644 --- a/spec/lib/banzai/filter/milestone_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/milestone_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::MilestoneReferenceFilter do +RSpec.describe Banzai::Filter::MilestoneReferenceFilter do include FilterSpecHelper let(:parent_group) { create(:group, :public) } diff --git a/spec/lib/banzai/filter/output_safety_spec.rb b/spec/lib/banzai/filter/output_safety_spec.rb index 5ffe591c9a4..5b7b7298411 100644 --- a/spec/lib/banzai/filter/output_safety_spec.rb +++ b/spec/lib/banzai/filter/output_safety_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::OutputSafety do +RSpec.describe Banzai::Filter::OutputSafety do subject do Class.new do include Banzai::Filter::OutputSafety diff --git a/spec/lib/banzai/filter/plantuml_filter_spec.rb b/spec/lib/banzai/filter/plantuml_filter_spec.rb index abe525ac47a..5ad94c74514 100644 --- a/spec/lib/banzai/filter/plantuml_filter_spec.rb +++ b/spec/lib/banzai/filter/plantuml_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::PlantumlFilter do +RSpec.describe Banzai::Filter::PlantumlFilter do include FilterSpecHelper it 'replaces plantuml pre tag with img tag' do diff --git a/spec/lib/banzai/filter/project_reference_filter_spec.rb b/spec/lib/banzai/filter/project_reference_filter_spec.rb index a054b79ec03..ac7a90a5893 100644 --- a/spec/lib/banzai/filter/project_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/project_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::ProjectReferenceFilter do +RSpec.describe Banzai::Filter::ProjectReferenceFilter do include FilterSpecHelper def invalidate_reference(reference) diff --git a/spec/lib/banzai/filter/reference_filter_spec.rb b/spec/lib/banzai/filter/reference_filter_spec.rb index d889b0b832d..d5978db13c0 100644 --- a/spec/lib/banzai/filter/reference_filter_spec.rb +++ b/spec/lib/banzai/filter/reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::ReferenceFilter do +RSpec.describe Banzai::Filter::ReferenceFilter do let(:project) { build_stubbed(:project) } describe '#each_node' do @@ -44,4 +44,249 @@ describe Banzai::Filter::ReferenceFilter do expect(filter.nodes).to eq([document.children[0]]) end end + + RSpec.shared_context 'document nodes' do + let(:document) { Nokogiri::HTML.fragment('<p data-sourcepos="1:1-1:18"></p>') } + let(:nodes) { [] } + let(:filter) { described_class.new(document, project: project) } + let(:ref_pattern) { nil } + let(:href_link) { nil } + + before do + nodes.each do |node| + document.children.first.add_child(node) + end + end + end + + RSpec.shared_context 'new nodes' do + let(:nodes) { [{ value: "1" }, { value: "2" }, { value: "3" }] } + let(:expected_nodes) { [{ value: "1.1" }, { value: "1.2" }, { value: "1.3" }, { value: "2.1" }, { value: "2.2" }, { value: "2.3" }, { value: "3.1" }, { value: "3.2" }, { value: "3.3" }] } + let(:new_nodes) do + { + 0 => [{ value: "1.1" }, { value: "1.2" }, { value: "1.3" }], + 2 => [{ value: "3.1" }, { value: "3.2" }, { value: "3.3" }], + 1 => [{ value: "2.1" }, { value: "2.2" }, { value: "2.3" }] + } + end + end + + RSpec.shared_examples 'replaces text' do |method_name, index| + let(:args) { [filter.nodes[index], index, ref_pattern || href_link].compact } + + context 'when content didnt change' do + it 'does not replace link node with html' do + filter.send(method_name, *args) do + existing_content + end + + expect(filter).not_to receive(:replace_text_with_html) + end + end + + context 'when link node has changed' do + let(:html) { %(text <a href="reference_url" class="gfm gfm-user" title="reference">Reference</a>) } + + it 'replaces reference node' do + filter.send(method_name, *args) do + html + end + + expect(document.css('a').length).to eq 1 + end + + it 'calls replace_and_update_new_nodes' do + expect(filter).to receive(:replace_and_update_new_nodes).with(filter.nodes[index], index, html) + + filter.send(method_name, *args) do + html + end + end + + it 'stores filtered new nodes' do + filter.send(method_name, *args) do + html + end + + expect(filter.instance_variable_get(:@new_nodes)).to eq({ index => [filter.each_node.to_a[index]] }) + end + + context "with update_nodes_for_banzai_reference_filter feature flag disabled" do + before do + stub_feature_flags(update_nodes_for_banzai_reference_filter: false) + end + + it 'does not call replace_and_update_new_nodes' do + expect(filter).not_to receive(:replace_and_update_new_nodes).with(filter.nodes[index], index, html) + + filter.send(method_name, *args) do + html + end + end + end + end + end + + RSpec.shared_examples 'replaces document node' do |method_name| + context 'when parent has only one node' do + let(:nodes) { [node] } + + it_behaves_like 'replaces text', method_name, 0 + end + + context 'when parent has multiple nodes' do + let(:node1) { Nokogiri::HTML.fragment('<span>span text</span>') } + let(:node2) { Nokogiri::HTML.fragment('<span>text</span>') } + + context 'when pattern matches in the first node' do + let(:nodes) { [node, node1, node2] } + + it_behaves_like 'replaces text', method_name, 0 + end + + context 'when pattern matches in the middle node' do + let(:nodes) { [node1, node, node2] } + + it_behaves_like 'replaces text', method_name, 1 + end + + context 'when pattern matches in the last node' do + let(:nodes) { [node1, node2, node] } + + it_behaves_like 'replaces text', method_name, 2 + end + end + end + + describe '#replace_text_when_pattern_matches' do + include_context 'document nodes' + let(:node) { Nokogiri::HTML.fragment('text @reference') } + + let(:ref_pattern) { %r{(?<!\w)@(?<user>[a-zA-Z0-9_\-\.]*)}x } + + context 'when node has no reference pattern' do + let(:node) { Nokogiri::HTML.fragment('random text') } + let(:nodes) { [node] } + + it 'skips node' do + expect { |b| filter.replace_text_when_pattern_matches(filter.nodes[0], 0, ref_pattern, &b) }.not_to yield_control + end + end + + it_behaves_like 'replaces document node', :replace_text_when_pattern_matches do + let(:existing_content) { node.to_html } + end + end + + describe '#replace_link_node_with_text' do + include_context 'document nodes' + let(:node) { Nokogiri::HTML.fragment('<a>end text</a>') } + + it_behaves_like 'replaces document node', :replace_link_node_with_text do + let(:existing_content) { node.text } + end + end + + describe '#replace_link_node_with_href' do + include_context 'document nodes' + let(:node) { Nokogiri::HTML.fragment('<a href="link">end text</a>') } + let(:href_link) { CGI.unescape(node.attr('href').to_s) } + + it_behaves_like 'replaces document node', :replace_link_node_with_href do + let(:existing_content) { href_link } + end + end + + describe "#call_and_update_nodes" do + context "with update_nodes_for_banzai_reference_filter feature flag enabled" do + include_context 'new nodes' + let(:document) { Nokogiri::HTML.fragment('<a href="foo">foo</a>') } + let(:filter) { described_class.new(document, project: project) } + + before do + stub_feature_flags(update_nodes_for_banzai_reference_filter: true) + end + + it "updates all new nodes", :aggregate_failures do + filter.instance_variable_set('@nodes', nodes) + + expect(filter).to receive(:call) { filter.instance_variable_set('@new_nodes', new_nodes) } + expect(filter).to receive(:with_update_nodes).and_call_original + expect(filter).to receive(:update_nodes!).and_call_original + + filter.call_and_update_nodes + + expect(filter.result[:reference_filter_nodes]).to eq(expected_nodes) + end + end + + context "with update_nodes_for_banzai_reference_filter feature flag disabled" do + include_context 'new nodes' + + before do + stub_feature_flags(update_nodes_for_banzai_reference_filter: false) + end + + it "does not change nodes", :aggregate_failures do + document = Nokogiri::HTML.fragment('<a href="foo">foo</a>') + filter = described_class.new(document, project: project) + filter.instance_variable_set('@nodes', nodes) + + expect(filter).to receive(:call) { filter.instance_variable_set('@new_nodes', new_nodes) } + expect(filter).not_to receive(:with_update_nodes) + expect(filter).not_to receive(:update_nodes!) + + filter.call_and_update_nodes + + expect(filter.nodes).to eq(nodes) + expect(filter.result[:reference_filter_nodes]).to be nil + end + end + end + + describe ".call" do + include_context 'new nodes' + + let(:document) { Nokogiri::HTML.fragment('<a href="foo">foo</a>') } + + let(:result) { { reference_filter_nodes: nodes } } + + before do + stub_feature_flags(update_nodes_for_banzai_reference_filter: true) + end + + it "updates all nodes", :aggregate_failures do + expect_next_instance_of(described_class) do |filter| + expect(filter).to receive(:call_and_update_nodes).and_call_original + expect(filter).to receive(:with_update_nodes).and_call_original + expect(filter).to receive(:call) { filter.instance_variable_set('@new_nodes', new_nodes) } + expect(filter).to receive(:update_nodes!).and_call_original + end + + described_class.call(document, { project: project }, result) + + expect(result[:reference_filter_nodes]).to eq(expected_nodes) + end + + context "with update_nodes_for_banzai_reference_filter feature flag disabled" do + let(:result) { {} } + + before do + stub_feature_flags(update_nodes_for_banzai_reference_filter: false) + end + + it "updates all nodes", :aggregate_failures do + expect_next_instance_of(described_class) do |filter| + expect(filter).to receive(:call_and_update_nodes).and_call_original + expect(filter).not_to receive(:with_update_nodes) + expect(filter).to receive(:call) { filter.instance_variable_set('@new_nodes', new_nodes) } + expect(filter).not_to receive(:update_nodes!) + end + + described_class.call(document, { project: project }, result) + + expect(result[:reference_filter_nodes]).to be nil + end + end + end end diff --git a/spec/lib/banzai/filter/reference_redactor_filter_spec.rb b/spec/lib/banzai/filter/reference_redactor_filter_spec.rb index 956bc85e53f..ac1cabb34cc 100644 --- a/spec/lib/banzai/filter/reference_redactor_filter_spec.rb +++ b/spec/lib/banzai/filter/reference_redactor_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::ReferenceRedactorFilter do +RSpec.describe Banzai::Filter::ReferenceRedactorFilter do include ActionView::Helpers::UrlHelper include FilterSpecHelper diff --git a/spec/lib/banzai/filter/repository_link_filter_spec.rb b/spec/lib/banzai/filter/repository_link_filter_spec.rb index 81f93f885f7..815053aac2f 100644 --- a/spec/lib/banzai/filter/repository_link_filter_spec.rb +++ b/spec/lib/banzai/filter/repository_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::RepositoryLinkFilter do +RSpec.describe Banzai::Filter::RepositoryLinkFilter do include GitHelpers include RepoHelpers diff --git a/spec/lib/banzai/filter/sanitization_filter_spec.rb b/spec/lib/banzai/filter/sanitization_filter_spec.rb index 607dc3fda47..09dcd5518ff 100644 --- a/spec/lib/banzai/filter/sanitization_filter_spec.rb +++ b/spec/lib/banzai/filter/sanitization_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::SanitizationFilter do +RSpec.describe Banzai::Filter::SanitizationFilter do include FilterSpecHelper it_behaves_like 'default whitelist' diff --git a/spec/lib/banzai/filter/snippet_reference_filter_spec.rb b/spec/lib/banzai/filter/snippet_reference_filter_spec.rb index 62ce12406a2..f23fbc5be88 100644 --- a/spec/lib/banzai/filter/snippet_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/snippet_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::SnippetReferenceFilter do +RSpec.describe Banzai::Filter::SnippetReferenceFilter do include FilterSpecHelper let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/filter/spaced_link_filter_spec.rb b/spec/lib/banzai/filter/spaced_link_filter_spec.rb index 98c38813144..2c64657d69d 100644 --- a/spec/lib/banzai/filter/spaced_link_filter_spec.rb +++ b/spec/lib/banzai/filter/spaced_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::SpacedLinkFilter do +RSpec.describe Banzai::Filter::SpacedLinkFilter do include FilterSpecHelper let(:link) { '[example](page slug)' } diff --git a/spec/lib/banzai/filter/suggestion_filter_spec.rb b/spec/lib/banzai/filter/suggestion_filter_spec.rb index 9c4650b73de..7d6092e21e9 100644 --- a/spec/lib/banzai/filter/suggestion_filter_spec.rb +++ b/spec/lib/banzai/filter/suggestion_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::SuggestionFilter do +RSpec.describe Banzai::Filter::SuggestionFilter do include FilterSpecHelper let(:input) { %(<pre class="code highlight js-syntax-highlight suggestion"><code>foo\n</code></pre>) } diff --git a/spec/lib/banzai/filter/syntax_highlight_filter_spec.rb b/spec/lib/banzai/filter/syntax_highlight_filter_spec.rb index 5a844fb61e3..a2875fad421 100644 --- a/spec/lib/banzai/filter/syntax_highlight_filter_spec.rb +++ b/spec/lib/banzai/filter/syntax_highlight_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::SyntaxHighlightFilter do +RSpec.describe Banzai::Filter::SyntaxHighlightFilter do include FilterSpecHelper shared_examples "XSS prevention" do |lang| diff --git a/spec/lib/banzai/filter/table_of_contents_filter_spec.rb b/spec/lib/banzai/filter/table_of_contents_filter_spec.rb index 05ef77c811a..2d17855707f 100644 --- a/spec/lib/banzai/filter/table_of_contents_filter_spec.rb +++ b/spec/lib/banzai/filter/table_of_contents_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::TableOfContentsFilter do +RSpec.describe Banzai::Filter::TableOfContentsFilter do include FilterSpecHelper def header(level, text) diff --git a/spec/lib/banzai/filter/table_of_contents_tag_filter_spec.rb b/spec/lib/banzai/filter/table_of_contents_tag_filter_spec.rb index 20f32d7347d..56f36af5066 100644 --- a/spec/lib/banzai/filter/table_of_contents_tag_filter_spec.rb +++ b/spec/lib/banzai/filter/table_of_contents_tag_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::TableOfContentsTagFilter do +RSpec.describe Banzai::Filter::TableOfContentsTagFilter do include FilterSpecHelper context 'table of contents' do diff --git a/spec/lib/banzai/filter/upload_link_filter_spec.rb b/spec/lib/banzai/filter/upload_link_filter_spec.rb index 8844ad78306..0f8c773c68d 100644 --- a/spec/lib/banzai/filter/upload_link_filter_spec.rb +++ b/spec/lib/banzai/filter/upload_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::UploadLinkFilter do +RSpec.describe Banzai::Filter::UploadLinkFilter do def filter(doc, contexts = {}) contexts.reverse_merge!( project: project, diff --git a/spec/lib/banzai/filter/user_reference_filter_spec.rb b/spec/lib/banzai/filter/user_reference_filter_spec.rb index cd6b68343b5..d8de3e5cc11 100644 --- a/spec/lib/banzai/filter/user_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/user_reference_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::UserReferenceFilter do +RSpec.describe Banzai::Filter::UserReferenceFilter do include FilterSpecHelper def get_reference(user) diff --git a/spec/lib/banzai/filter/video_link_filter_spec.rb b/spec/lib/banzai/filter/video_link_filter_spec.rb index c324c36fe4d..32fbc6b687f 100644 --- a/spec/lib/banzai/filter/video_link_filter_spec.rb +++ b/spec/lib/banzai/filter/video_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::VideoLinkFilter do +RSpec.describe Banzai::Filter::VideoLinkFilter do def filter(doc, contexts = {}) contexts.reverse_merge!({ project: project diff --git a/spec/lib/banzai/filter/wiki_link_filter_spec.rb b/spec/lib/banzai/filter/wiki_link_filter_spec.rb index 827f38ef717..7a4464a2604 100644 --- a/spec/lib/banzai/filter/wiki_link_filter_spec.rb +++ b/spec/lib/banzai/filter/wiki_link_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Filter::WikiLinkFilter do +RSpec.describe Banzai::Filter::WikiLinkFilter do include FilterSpecHelper let(:namespace) { build_stubbed(:namespace, name: "wiki_link_ns") } diff --git a/spec/lib/banzai/filter_array_spec.rb b/spec/lib/banzai/filter_array_spec.rb index bed41a80d29..47bc5633300 100644 --- a/spec/lib/banzai/filter_array_spec.rb +++ b/spec/lib/banzai/filter_array_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::FilterArray do +RSpec.describe Banzai::FilterArray do describe '#insert_after' do it 'inserts an element after a provided element' do filters = described_class.new(%w(a b c)) diff --git a/spec/lib/banzai/issuable_extractor_spec.rb b/spec/lib/banzai/issuable_extractor_spec.rb index 7fa6048c1c6..c4ee7160e12 100644 --- a/spec/lib/banzai/issuable_extractor_spec.rb +++ b/spec/lib/banzai/issuable_extractor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::IssuableExtractor do +RSpec.describe Banzai::IssuableExtractor do let(:project) { create(:project) } let(:user) { create(:user) } let(:extractor) { described_class.new(Banzai::RenderContext.new(project, user)) } diff --git a/spec/lib/banzai/object_renderer_spec.rb b/spec/lib/banzai/object_renderer_spec.rb index aef11775e60..f8d7acd3148 100644 --- a/spec/lib/banzai/object_renderer_spec.rb +++ b/spec/lib/banzai/object_renderer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ObjectRenderer do +RSpec.describe Banzai::ObjectRenderer do let(:project) { create(:project, :repository) } let(:user) { project.owner } let(:renderer) do diff --git a/spec/lib/banzai/pipeline/broadcast_message_pipeline_spec.rb b/spec/lib/banzai/pipeline/broadcast_message_pipeline_spec.rb index 9832b132b58..41a91c56f3b 100644 --- a/spec/lib/banzai/pipeline/broadcast_message_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/broadcast_message_pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline::BroadcastMessagePipeline do +RSpec.describe Banzai::Pipeline::BroadcastMessagePipeline do before do stub_commonmark_sourcepos_disabled end diff --git a/spec/lib/banzai/pipeline/description_pipeline_spec.rb b/spec/lib/banzai/pipeline/description_pipeline_spec.rb index 6778a273bba..82d4f883e0d 100644 --- a/spec/lib/banzai/pipeline/description_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/description_pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline::DescriptionPipeline do +RSpec.describe Banzai::Pipeline::DescriptionPipeline do let_it_be(:project) { create(:project) } def parse(html) diff --git a/spec/lib/banzai/pipeline/email_pipeline_spec.rb b/spec/lib/banzai/pipeline/email_pipeline_spec.rb index 77186861225..c7a0b9fefa1 100644 --- a/spec/lib/banzai/pipeline/email_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/email_pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline::EmailPipeline do +RSpec.describe Banzai::Pipeline::EmailPipeline do describe '.filters' do it 'returns the expected type' do expect(described_class.filters).to be_kind_of(Banzai::FilterArray) diff --git a/spec/lib/banzai/pipeline/emoji_pipeline_spec.rb b/spec/lib/banzai/pipeline/emoji_pipeline_spec.rb index 744df3e0b96..6de9d65f1b2 100644 --- a/spec/lib/banzai/pipeline/emoji_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/emoji_pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline::EmojiPipeline do +RSpec.describe Banzai::Pipeline::EmojiPipeline do def parse(text) described_class.to_html(text, {}) end diff --git a/spec/lib/banzai/pipeline/full_pipeline_spec.rb b/spec/lib/banzai/pipeline/full_pipeline_spec.rb index b4047e369fb..0127ac11c81 100644 --- a/spec/lib/banzai/pipeline/full_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/full_pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline::FullPipeline do +RSpec.describe Banzai::Pipeline::FullPipeline do describe 'References' do let(:project) { create(:project, :public) } let(:issue) { create(:issue, project: project) } diff --git a/spec/lib/banzai/pipeline/gfm_pipeline_spec.rb b/spec/lib/banzai/pipeline/gfm_pipeline_spec.rb index 448422b15e3..beb760637b0 100644 --- a/spec/lib/banzai/pipeline/gfm_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/gfm_pipeline_spec.rb @@ -2,12 +2,63 @@ require 'spec_helper' -describe Banzai::Pipeline::GfmPipeline do +RSpec.describe Banzai::Pipeline::GfmPipeline do describe 'integration between parsing regular and external issue references' do let(:project) { create(:redmine_project, :public) } context 'when internal issue tracker is enabled' do context 'when shorthand pattern #ISSUE_ID is used' do + it 'links an internal issues and keep updated nodes in result[:reference_filter_nodes]', :aggregate_failures do + issue = create(:issue, project: project) + markdown = "text #{issue.to_reference(project, full: true)}" + + result = described_class.call(markdown, project: project) + link = result[:output].css('a').first + text = result[:output].children.first + + expect(link['href']).to eq(Gitlab::Routing.url_helpers.project_issue_path(project, issue)) + expect(result[:reference_filter_nodes]).to eq([text]) + end + end + + it 'executes :each_node only once for first reference filter', :aggregate_failures do + issue = create(:issue, project: project) + markdown = "text #{issue.to_reference(project, full: true)}" + + expect_any_instance_of(Banzai::Filter::ReferenceFilter).to receive(:each_node).once + + described_class.call(markdown, project: project) + end + + context "with update_nodes_for_banzai_reference_filter feature flag disabled" do + before do + stub_feature_flags(update_nodes_for_banzai_reference_filter: false) + end + + context 'when shorthand pattern #ISSUE_ID is used' do + it 'links an internal issues and doesnt store nodes in result[:reference_filter_nodes]', :aggregate_failures do + issue = create(:issue, project: project) + markdown = "text #{issue.to_reference(project, full: true)}" + result = described_class.call(markdown, project: project) + link = result[:output].css('a').first + + expect(link['href']).to eq(Gitlab::Routing.url_helpers.project_issue_path(project, issue)) + expect(result[:reference_filter_nodes]).to eq nil + end + end + + it 'execute :each_node for each reference_filter', :aggregate_failures do + issue = create(:issue, project: project) + markdown = "text #{issue.to_reference(project, full: true)}" + described_class.reference_filters do |reference_filter| + expect_any_instance_of(reference_filter).to receive(:each_node).once + end + + described_class.call(markdown, project: project) + end + end + + context 'when shorthand pattern #ISSUE_ID is used' do it 'links an internal issue if it exists' do issue = create(:issue, project: project) markdown = issue.to_reference(project, full: true) diff --git a/spec/lib/banzai/pipeline/jira_import/adf_commonmark_pipeline_spec.rb b/spec/lib/banzai/pipeline/jira_import/adf_commonmark_pipeline_spec.rb new file mode 100644 index 00000000000..d8841a9753e --- /dev/null +++ b/spec/lib/banzai/pipeline/jira_import/adf_commonmark_pipeline_spec.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Banzai::Pipeline::JiraImport::AdfCommonmarkPipeline do + let_it_be(:fixtures_path) { 'lib/kramdown/atlassian_document_format' } + + it 'converts text in Atlassian Document Format ' do + source = fixture_file(File.join(fixtures_path, 'paragraph.json')) + target = fixture_file(File.join(fixtures_path, 'paragraph.md')) + output = described_class.call(source, {})[:output] + + expect(output).to eq target + end +end diff --git a/spec/lib/banzai/pipeline/post_process_pipeline_spec.rb b/spec/lib/banzai/pipeline/post_process_pipeline_spec.rb index ab72354edcf..d9f45769550 100644 --- a/spec/lib/banzai/pipeline/post_process_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/post_process_pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline::PostProcessPipeline do +RSpec.describe Banzai::Pipeline::PostProcessPipeline do context 'when a document only has upload links' do it 'does not make any Gitaly calls', :request_store do markdown = <<-MARKDOWN.strip_heredoc diff --git a/spec/lib/banzai/pipeline/wiki_pipeline_spec.rb b/spec/lib/banzai/pipeline/wiki_pipeline_spec.rb index b2c24284eb9..4af782c7d73 100644 --- a/spec/lib/banzai/pipeline/wiki_pipeline_spec.rb +++ b/spec/lib/banzai/pipeline/wiki_pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline::WikiPipeline do +RSpec.describe Banzai::Pipeline::WikiPipeline do let_it_be(:namespace) { create(:namespace, name: "wiki_link_ns") } let_it_be(:project) { create(:project, :public, name: "wiki_link_project", namespace: namespace) } let_it_be(:wiki) { ProjectWiki.new(project, double(:user)) } diff --git a/spec/lib/banzai/pipeline_spec.rb b/spec/lib/banzai/pipeline_spec.rb index eeff7287ff5..7d4df2ca5ce 100644 --- a/spec/lib/banzai/pipeline_spec.rb +++ b/spec/lib/banzai/pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Pipeline do +RSpec.describe Banzai::Pipeline do describe '.[]' do subject { described_class[name] } diff --git a/spec/lib/banzai/querying_spec.rb b/spec/lib/banzai/querying_spec.rb index b7a235b0558..b76f6ec533c 100644 --- a/spec/lib/banzai/querying_spec.rb +++ b/spec/lib/banzai/querying_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Querying do +RSpec.describe Banzai::Querying do describe '.css' do it 'optimizes queries for elements with classes' do document = double(:document) diff --git a/spec/lib/banzai/reference_parser/base_parser_spec.rb b/spec/lib/banzai/reference_parser/base_parser_spec.rb index b1002c1db25..0eea51262ba 100644 --- a/spec/lib/banzai/reference_parser/base_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/base_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::BaseParser do +RSpec.describe Banzai::ReferenceParser::BaseParser do include ReferenceParserHelpers let(:user) { create(:user) } diff --git a/spec/lib/banzai/reference_parser/commit_parser_spec.rb b/spec/lib/banzai/reference_parser/commit_parser_spec.rb index 7f7c750fe74..612ce6b93f1 100644 --- a/spec/lib/banzai/reference_parser/commit_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/commit_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::CommitParser do +RSpec.describe Banzai::ReferenceParser::CommitParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/commit_range_parser_spec.rb b/spec/lib/banzai/reference_parser/commit_range_parser_spec.rb index 78b337466aa..2f64aef4fb7 100644 --- a/spec/lib/banzai/reference_parser/commit_range_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/commit_range_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::CommitRangeParser do +RSpec.describe Banzai::ReferenceParser::CommitRangeParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/design_parser_spec.rb b/spec/lib/banzai/reference_parser/design_parser_spec.rb index 76708acf887..92d3a4aaad2 100644 --- a/spec/lib/banzai/reference_parser/design_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/design_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::DesignParser do +RSpec.describe Banzai::ReferenceParser::DesignParser do include ReferenceParserHelpers include DesignManagementTestHelpers diff --git a/spec/lib/banzai/reference_parser/external_issue_parser_spec.rb b/spec/lib/banzai/reference_parser/external_issue_parser_spec.rb index 9343d52e44b..5f92eb42e74 100644 --- a/spec/lib/banzai/reference_parser/external_issue_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/external_issue_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::ExternalIssueParser do +RSpec.describe Banzai::ReferenceParser::ExternalIssueParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/issue_parser_spec.rb b/spec/lib/banzai/reference_parser/issue_parser_spec.rb index ac321aca5e9..76f13e7b3aa 100644 --- a/spec/lib/banzai/reference_parser/issue_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/issue_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::IssueParser do +RSpec.describe Banzai::ReferenceParser::IssueParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/label_parser_spec.rb b/spec/lib/banzai/reference_parser/label_parser_spec.rb index 8b66a891e69..8f287e15b37 100644 --- a/spec/lib/banzai/reference_parser/label_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/label_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::LabelParser do +RSpec.describe Banzai::ReferenceParser::LabelParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/mentioned_group_parser_spec.rb b/spec/lib/banzai/reference_parser/mentioned_group_parser_spec.rb index 8346ba93f88..4610da7cbe6 100644 --- a/spec/lib/banzai/reference_parser/mentioned_group_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/mentioned_group_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::MentionedGroupParser do +RSpec.describe Banzai::ReferenceParser::MentionedGroupParser do include ReferenceParserHelpers let(:group) { create(:group, :private) } diff --git a/spec/lib/banzai/reference_parser/mentioned_project_parser_spec.rb b/spec/lib/banzai/reference_parser/mentioned_project_parser_spec.rb index b99c02351d0..7eb58ee40d3 100644 --- a/spec/lib/banzai/reference_parser/mentioned_project_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/mentioned_project_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::MentionedProjectParser do +RSpec.describe Banzai::ReferenceParser::MentionedProjectParser do include ReferenceParserHelpers let(:group) { create(:group, :private) } diff --git a/spec/lib/banzai/reference_parser/mentioned_user_parser_spec.rb b/spec/lib/banzai/reference_parser/mentioned_user_parser_spec.rb index b10e5d19828..4be07866db1 100644 --- a/spec/lib/banzai/reference_parser/mentioned_user_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/mentioned_user_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::MentionedUserParser do +RSpec.describe Banzai::ReferenceParser::MentionedUserParser do include ReferenceParserHelpers let(:group) { create(:group, :private) } diff --git a/spec/lib/banzai/reference_parser/merge_request_parser_spec.rb b/spec/lib/banzai/reference_parser/merge_request_parser_spec.rb index cb65893aea0..32a9f09c3f6 100644 --- a/spec/lib/banzai/reference_parser/merge_request_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/merge_request_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::MergeRequestParser do +RSpec.describe Banzai::ReferenceParser::MergeRequestParser do include ReferenceParserHelpers let(:user) { create(:user) } diff --git a/spec/lib/banzai/reference_parser/milestone_parser_spec.rb b/spec/lib/banzai/reference_parser/milestone_parser_spec.rb index 25ba41dd8a0..95f71154e38 100644 --- a/spec/lib/banzai/reference_parser/milestone_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/milestone_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::MilestoneParser do +RSpec.describe Banzai::ReferenceParser::MilestoneParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/project_parser_spec.rb b/spec/lib/banzai/reference_parser/project_parser_spec.rb index e87fa3e8767..6358a04f12a 100644 --- a/spec/lib/banzai/reference_parser/project_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/project_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::ProjectParser do +RSpec.describe Banzai::ReferenceParser::ProjectParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/snippet_parser_spec.rb b/spec/lib/banzai/reference_parser/snippet_parser_spec.rb index 6581ed0d7c3..cdc660b4f4a 100644 --- a/spec/lib/banzai/reference_parser/snippet_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/snippet_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::SnippetParser do +RSpec.describe Banzai::ReferenceParser::SnippetParser do include ReferenceParserHelpers let(:project) { create(:project, :public) } diff --git a/spec/lib/banzai/reference_parser/user_parser_spec.rb b/spec/lib/banzai/reference_parser/user_parser_spec.rb index 71d2e1de3b6..d4f4339cf17 100644 --- a/spec/lib/banzai/reference_parser/user_parser_spec.rb +++ b/spec/lib/banzai/reference_parser/user_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceParser::UserParser do +RSpec.describe Banzai::ReferenceParser::UserParser do include ReferenceParserHelpers let(:group) { create(:group) } diff --git a/spec/lib/banzai/reference_redactor_spec.rb b/spec/lib/banzai/reference_redactor_spec.rb index 0dec6395fb3..de774267b81 100644 --- a/spec/lib/banzai/reference_redactor_spec.rb +++ b/spec/lib/banzai/reference_redactor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::ReferenceRedactor do +RSpec.describe Banzai::ReferenceRedactor do let(:user) { create(:user) } let(:project) { build(:project) } let(:redactor) { described_class.new(Banzai::RenderContext.new(project, user)) } diff --git a/spec/lib/banzai/render_context_spec.rb b/spec/lib/banzai/render_context_spec.rb index ad17db11613..c4b609b936e 100644 --- a/spec/lib/banzai/render_context_spec.rb +++ b/spec/lib/banzai/render_context_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::RenderContext do +RSpec.describe Banzai::RenderContext do let(:document) { Nokogiri::HTML.fragment('<p>hello</p>') } describe '#project_for_node' do diff --git a/spec/lib/banzai/renderer_spec.rb b/spec/lib/banzai/renderer_spec.rb index b540a76face..52bf3087875 100644 --- a/spec/lib/banzai/renderer_spec.rb +++ b/spec/lib/banzai/renderer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Banzai::Renderer do +RSpec.describe Banzai::Renderer do let(:renderer) { described_class } def fake_object(fresh:) diff --git a/spec/lib/bitbucket/collection_spec.rb b/spec/lib/bitbucket/collection_spec.rb index 5946be71565..349274585c4 100644 --- a/spec/lib/bitbucket/collection_spec.rb +++ b/spec/lib/bitbucket/collection_spec.rb @@ -17,7 +17,7 @@ class TestPaginator end end -describe Bitbucket::Collection do +RSpec.describe Bitbucket::Collection do it "iterates paginator" do collection = described_class.new(TestPaginator.new) diff --git a/spec/lib/bitbucket/connection_spec.rb b/spec/lib/bitbucket/connection_spec.rb index 5aca93767dc..bed44b94f44 100644 --- a/spec/lib/bitbucket/connection_spec.rb +++ b/spec/lib/bitbucket/connection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Connection do +RSpec.describe Bitbucket::Connection do before do allow_next_instance_of(described_class) do |instance| allow(instance).to receive(:provider).and_return(double(app_id: '', app_secret: '')) diff --git a/spec/lib/bitbucket/page_spec.rb b/spec/lib/bitbucket/page_spec.rb index 6301dd56faf..1d599007d9e 100644 --- a/spec/lib/bitbucket/page_spec.rb +++ b/spec/lib/bitbucket/page_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Page do +RSpec.describe Bitbucket::Page do let(:response) { { 'values' => [{ 'username' => 'Ben' }], 'pagelen' => 2, 'next' => '' } } before do diff --git a/spec/lib/bitbucket/paginator_spec.rb b/spec/lib/bitbucket/paginator_spec.rb index a1effa14000..e74af8a264b 100644 --- a/spec/lib/bitbucket/paginator_spec.rb +++ b/spec/lib/bitbucket/paginator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Paginator do +RSpec.describe Bitbucket::Paginator do let(:last_page) { double(:page, next?: false, items: ['item_2']) } let(:first_page) { double(:page, next?: true, next: last_page, items: ['item_1']) } diff --git a/spec/lib/bitbucket/representation/comment_spec.rb b/spec/lib/bitbucket/representation/comment_spec.rb index 1874296df8c..f6766ab685b 100644 --- a/spec/lib/bitbucket/representation/comment_spec.rb +++ b/spec/lib/bitbucket/representation/comment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Representation::Comment do +RSpec.describe Bitbucket::Representation::Comment do describe '#author' do it { expect(described_class.new('user' => { 'nickname' => 'Ben' }).author).to eq('Ben') } it { expect(described_class.new({}).author).to be_nil } diff --git a/spec/lib/bitbucket/representation/issue_spec.rb b/spec/lib/bitbucket/representation/issue_spec.rb index 655b9b78b47..8c27086546f 100644 --- a/spec/lib/bitbucket/representation/issue_spec.rb +++ b/spec/lib/bitbucket/representation/issue_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Representation::Issue do +RSpec.describe Bitbucket::Representation::Issue do describe '#iid' do it { expect(described_class.new('id' => 1).iid).to eq(1) } end diff --git a/spec/lib/bitbucket/representation/pull_request_comment_spec.rb b/spec/lib/bitbucket/representation/pull_request_comment_spec.rb index 151055f510f..cdab683492f 100644 --- a/spec/lib/bitbucket/representation/pull_request_comment_spec.rb +++ b/spec/lib/bitbucket/representation/pull_request_comment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Representation::PullRequestComment do +RSpec.describe Bitbucket::Representation::PullRequestComment do describe '#iid' do it { expect(described_class.new('id' => 1).iid).to eq(1) } end diff --git a/spec/lib/bitbucket/representation/pull_request_spec.rb b/spec/lib/bitbucket/representation/pull_request_spec.rb index 6a9df0e5099..6f05d03aa0a 100644 --- a/spec/lib/bitbucket/representation/pull_request_spec.rb +++ b/spec/lib/bitbucket/representation/pull_request_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Representation::PullRequest do +RSpec.describe Bitbucket::Representation::PullRequest do describe '#iid' do it { expect(described_class.new('id' => 1).iid).to eq(1) } end diff --git a/spec/lib/bitbucket/representation/repo_spec.rb b/spec/lib/bitbucket/representation/repo_spec.rb index a272695e681..a779a153f25 100644 --- a/spec/lib/bitbucket/representation/repo_spec.rb +++ b/spec/lib/bitbucket/representation/repo_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Representation::Repo do +RSpec.describe Bitbucket::Representation::Repo do describe '#has_wiki?' do it { expect(described_class.new({ 'has_wiki' => false }).has_wiki?).to be_falsey } it { expect(described_class.new({ 'has_wiki' => true }).has_wiki?).to be_truthy } diff --git a/spec/lib/bitbucket/representation/user_spec.rb b/spec/lib/bitbucket/representation/user_spec.rb index 0169887a24c..e1f6c724da8 100644 --- a/spec/lib/bitbucket/representation/user_spec.rb +++ b/spec/lib/bitbucket/representation/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Bitbucket::Representation::User do +RSpec.describe Bitbucket::Representation::User do describe '#username' do it 'returns correct value' do user = described_class.new('username' => 'Ben') diff --git a/spec/lib/bitbucket_server/client_spec.rb b/spec/lib/bitbucket_server/client_spec.rb index aa0217856ee..9dcd1500aab 100644 --- a/spec/lib/bitbucket_server/client_spec.rb +++ b/spec/lib/bitbucket_server/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Client do +RSpec.describe BitbucketServer::Client do let(:base_uri) { 'https://test:7990/stash/' } let(:options) { { base_uri: base_uri, user: 'bitbucket', password: 'mypassword' } } let(:project) { 'SOME-PROJECT' } diff --git a/spec/lib/bitbucket_server/collection_spec.rb b/spec/lib/bitbucket_server/collection_spec.rb index ddd02bac88a..1a47a30c74b 100644 --- a/spec/lib/bitbucket_server/collection_spec.rb +++ b/spec/lib/bitbucket_server/collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Collection do +RSpec.describe BitbucketServer::Collection do let(:connection) { instance_double(BitbucketServer::Connection) } let(:page) { 1 } let(:paginator) { BitbucketServer::Paginator.new(connection, 'http://more-data', :pull_request, page_offset: page) } diff --git a/spec/lib/bitbucket_server/connection_spec.rb b/spec/lib/bitbucket_server/connection_spec.rb index 3a7fe4e7321..873eded58d7 100644 --- a/spec/lib/bitbucket_server/connection_spec.rb +++ b/spec/lib/bitbucket_server/connection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Connection do +RSpec.describe BitbucketServer::Connection do let(:options) { { base_uri: 'https://test:7990', user: 'bitbucket', password: 'mypassword' } } let(:payload) { { 'test' => 1 } } let(:headers) { { "Content-Type" => "application/json" } } diff --git a/spec/lib/bitbucket_server/page_spec.rb b/spec/lib/bitbucket_server/page_spec.rb index 2da1d0995ca..2d4e946e590 100644 --- a/spec/lib/bitbucket_server/page_spec.rb +++ b/spec/lib/bitbucket_server/page_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Page do +RSpec.describe BitbucketServer::Page do let(:response) { { 'values' => [{ 'description' => 'Test' }], 'isLastPage' => false, 'nextPageStart' => 2 } } before do diff --git a/spec/lib/bitbucket_server/paginator_spec.rb b/spec/lib/bitbucket_server/paginator_spec.rb index e01cbeb4270..66bf5bf3f02 100644 --- a/spec/lib/bitbucket_server/paginator_spec.rb +++ b/spec/lib/bitbucket_server/paginator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Paginator do +RSpec.describe BitbucketServer::Paginator do let(:last_page) { double(:page, next?: false, items: ['item_2']) } let(:first_page) { double(:page, next?: true, next: last_page, items: ['item_1']) } let(:connection) { instance_double(BitbucketServer::Connection) } diff --git a/spec/lib/bitbucket_server/representation/activity_spec.rb b/spec/lib/bitbucket_server/representation/activity_spec.rb index 6988e77ad25..0b7e4542cbe 100644 --- a/spec/lib/bitbucket_server/representation/activity_spec.rb +++ b/spec/lib/bitbucket_server/representation/activity_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Representation::Activity do +RSpec.describe BitbucketServer::Representation::Activity do let(:activities) { Gitlab::Json.parse(fixture_file('importers/bitbucket_server/activities.json'))['values'] } let(:inline_comment) { activities.first } let(:comment) { activities[3] } diff --git a/spec/lib/bitbucket_server/representation/comment_spec.rb b/spec/lib/bitbucket_server/representation/comment_spec.rb index ecaf6a843ae..b568789bd97 100644 --- a/spec/lib/bitbucket_server/representation/comment_spec.rb +++ b/spec/lib/bitbucket_server/representation/comment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Representation::Comment do +RSpec.describe BitbucketServer::Representation::Comment do let(:activities) { Gitlab::Json.parse(fixture_file('importers/bitbucket_server/activities.json'))['values'] } let(:comment) { activities.first } diff --git a/spec/lib/bitbucket_server/representation/pull_request_comment_spec.rb b/spec/lib/bitbucket_server/representation/pull_request_comment_spec.rb index aa3eddf305a..01e56263a5e 100644 --- a/spec/lib/bitbucket_server/representation/pull_request_comment_spec.rb +++ b/spec/lib/bitbucket_server/representation/pull_request_comment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Representation::PullRequestComment do +RSpec.describe BitbucketServer::Representation::PullRequestComment do let(:activities) { Gitlab::Json.parse(fixture_file('importers/bitbucket_server/activities.json'))['values'] } let(:comment) { activities.second } diff --git a/spec/lib/bitbucket_server/representation/pull_request_spec.rb b/spec/lib/bitbucket_server/representation/pull_request_spec.rb index 7e72da05cb1..a05d98f0d4a 100644 --- a/spec/lib/bitbucket_server/representation/pull_request_spec.rb +++ b/spec/lib/bitbucket_server/representation/pull_request_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Representation::PullRequest do +RSpec.describe BitbucketServer::Representation::PullRequest do let(:sample_data) { Gitlab::Json.parse(fixture_file('importers/bitbucket_server/pull_request.json')) } subject { described_class.new(sample_data) } diff --git a/spec/lib/bitbucket_server/representation/repo_spec.rb b/spec/lib/bitbucket_server/representation/repo_spec.rb index 429b6d36c59..7a773f47ca5 100644 --- a/spec/lib/bitbucket_server/representation/repo_spec.rb +++ b/spec/lib/bitbucket_server/representation/repo_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe BitbucketServer::Representation::Repo do +RSpec.describe BitbucketServer::Representation::Repo do let(:sample_data) do <<~DATA { diff --git a/spec/lib/constraints/admin_constrainer_spec.rb b/spec/lib/constraints/admin_constrainer_spec.rb index da178f9e71a..3efe683177c 100644 --- a/spec/lib/constraints/admin_constrainer_spec.rb +++ b/spec/lib/constraints/admin_constrainer_spec.rb @@ -2,7 +2,7 @@ # require 'spec_helper' -describe Constraints::AdminConstrainer, :do_not_mock_admin_mode do +RSpec.describe Constraints::AdminConstrainer, :do_not_mock_admin_mode do let(:user) { create(:user) } let(:session) { {} } diff --git a/spec/lib/constraints/feature_constrainer_spec.rb b/spec/lib/constraints/feature_constrainer_spec.rb index 7665d5b3547..c98dc694186 100644 --- a/spec/lib/constraints/feature_constrainer_spec.rb +++ b/spec/lib/constraints/feature_constrainer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Constraints::FeatureConstrainer do +RSpec.describe Constraints::FeatureConstrainer do describe '#matches' do it 'calls Feature.enabled? with the correct arguments' do gate = stub_feature_flag_gate("an object") diff --git a/spec/lib/constraints/group_url_constrainer_spec.rb b/spec/lib/constraints/group_url_constrainer_spec.rb index 573de331898..45a5b3afd81 100644 --- a/spec/lib/constraints/group_url_constrainer_spec.rb +++ b/spec/lib/constraints/group_url_constrainer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Constraints::GroupUrlConstrainer do +RSpec.describe Constraints::GroupUrlConstrainer do let!(:group) { create(:group, path: 'gitlab') } describe '#matches?' do diff --git a/spec/lib/constraints/project_url_constrainer_spec.rb b/spec/lib/constraints/project_url_constrainer_spec.rb index 963e1d5b8e0..1e8aac8479d 100644 --- a/spec/lib/constraints/project_url_constrainer_spec.rb +++ b/spec/lib/constraints/project_url_constrainer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Constraints::ProjectUrlConstrainer do +RSpec.describe Constraints::ProjectUrlConstrainer do let!(:project) { create(:project) } let!(:namespace) { project.namespace } diff --git a/spec/lib/constraints/user_url_constrainer_spec.rb b/spec/lib/constraints/user_url_constrainer_spec.rb index 4f665def3bf..1b68e966585 100644 --- a/spec/lib/constraints/user_url_constrainer_spec.rb +++ b/spec/lib/constraints/user_url_constrainer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Constraints::UserUrlConstrainer do +RSpec.describe Constraints::UserUrlConstrainer do let!(:user) { create(:user, username: 'dz') } describe '#matches?' do diff --git a/spec/lib/container_registry/blob_spec.rb b/spec/lib/container_registry/blob_spec.rb index be7be2f3719..676adc74be2 100644 --- a/spec/lib/container_registry/blob_spec.rb +++ b/spec/lib/container_registry/blob_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ContainerRegistry::Blob do +RSpec.describe ContainerRegistry::Blob do let(:group) { create(:group, name: 'group') } let(:project) { create(:project, path: 'test', group: group) } diff --git a/spec/lib/container_registry/client_spec.rb b/spec/lib/container_registry/client_spec.rb index 18bcff65f41..de92ca5eeec 100644 --- a/spec/lib/container_registry/client_spec.rb +++ b/spec/lib/container_registry/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ContainerRegistry::Client do +RSpec.describe ContainerRegistry::Client do let(:token) { '12345' } let(:options) { { token: token } } let(:client) { described_class.new("http://container-registry", options) } diff --git a/spec/lib/container_registry/path_spec.rb b/spec/lib/container_registry/path_spec.rb index 8c671b4d56d..aa6876225b5 100644 --- a/spec/lib/container_registry/path_spec.rb +++ b/spec/lib/container_registry/path_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ContainerRegistry::Path do +RSpec.describe ContainerRegistry::Path do subject { described_class.new(path) } describe '#components' do diff --git a/spec/lib/container_registry/registry_spec.rb b/spec/lib/container_registry/registry_spec.rb index e509566fae8..d6e2b17f53b 100644 --- a/spec/lib/container_registry/registry_spec.rb +++ b/spec/lib/container_registry/registry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ContainerRegistry::Registry do +RSpec.describe ContainerRegistry::Registry do let(:path) { nil } let(:registry) { described_class.new('http://example.com', path: path) } diff --git a/spec/lib/container_registry/tag_spec.rb b/spec/lib/container_registry/tag_spec.rb index 085c73caa97..d696b61ac9d 100644 --- a/spec/lib/container_registry/tag_spec.rb +++ b/spec/lib/container_registry/tag_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ContainerRegistry::Tag do +RSpec.describe ContainerRegistry::Tag do let(:group) { create(:group, name: 'group') } let(:project) { create(:project, path: 'test', group: group) } diff --git a/spec/lib/csv_builder_spec.rb b/spec/lib/csv_builder_spec.rb index 0d5e2b81b16..546be3ba6f7 100644 --- a/spec/lib/csv_builder_spec.rb +++ b/spec/lib/csv_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe CsvBuilder do +RSpec.describe CsvBuilder do let(:object) { double(question: :answer) } let(:fake_relation) { FakeRelation.new([object]) } let(:subject) { described_class.new(fake_relation, 'Q & A' => :question, 'Reversed' => -> (o) { o.question.to_s.reverse }) } diff --git a/spec/lib/declarative_policy/overrides_spec.rb b/spec/lib/declarative_policy/overrides_spec.rb new file mode 100644 index 00000000000..84dc8f7ac71 --- /dev/null +++ b/spec/lib/declarative_policy/overrides_spec.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +require 'fast_spec_helper' +require_dependency 'rspec-parameterized' + +RSpec.describe 'DeclarativePolicy overrides' do + let(:foo_policy) do + Class.new(DeclarativePolicy::Base) do + condition(:foo_prop_cond) { @subject.foo_prop } + + rule { foo_prop_cond }.policy do + enable :common_ability + enable :foo_prop_ability + end + end + end + + let(:bar_policy) do + Class.new(DeclarativePolicy::Base) do + delegate { @subject.foo } + + overrides :common_ability + + condition(:bar_prop_cond) { @subject.bar_prop } + + rule { bar_prop_cond }.policy do + enable :common_ability + enable :bar_prop_ability + end + + rule { bar_prop_cond & can?(:foo_prop_ability) }.policy do + enable :combined_ability + end + end + end + + before do + stub_const('Foo', Struct.new(:foo_prop)) + stub_const('FooPolicy', foo_policy) + stub_const('Bar', Struct.new(:foo, :bar_prop)) + stub_const('BarPolicy', bar_policy) + end + + where(:foo_prop, :bar_prop) do + [ + [true, true], + [true, false], + [false, true], + [false, false] + ] + end + + with_them do + let(:foo) { Foo.new(foo_prop) } + let(:bar) { Bar.new(foo, bar_prop) } + + it 'determines the correct bar_prop_ability (non-delegated) permissions for bar' do + policy = DeclarativePolicy.policy_for(nil, bar) + expect(policy.allowed?(:bar_prop_ability)).to eq(bar_prop) + end + + it 'determines the correct foo_prop (non-overridden) permissions for bar' do + policy = DeclarativePolicy.policy_for(nil, bar) + expect(policy.allowed?(:foo_prop_ability)).to eq(foo_prop) + end + + it 'determines the correct common_ability (overridden) permissions for bar' do + policy = DeclarativePolicy.policy_for(nil, bar) + expect(policy.allowed?(:common_ability)).to eq(bar_prop) + end + + it 'determines the correct common_ability permissions for foo' do + policy = DeclarativePolicy.policy_for(nil, foo) + expect(policy.allowed?(:common_ability)).to eq(foo_prop) + end + + it 'allows combinations of overridden and inherited values' do + policy = DeclarativePolicy.policy_for(nil, bar) + expect(policy.allowed?(:combined_ability)).to eq(foo_prop && bar_prop) + end + end +end diff --git a/spec/lib/declarative_policy_spec.rb b/spec/lib/declarative_policy_spec.rb index 5fdb3c27738..fc21bd43f48 100644 --- a/spec/lib/declarative_policy_spec.rb +++ b/spec/lib/declarative_policy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe DeclarativePolicy do +RSpec.describe DeclarativePolicy do describe '.class_for' do it 'uses declarative_policy_class if present' do instance = Gitlab::ErrorTracking::ErrorEvent.new diff --git a/spec/lib/event_filter_spec.rb b/spec/lib/event_filter_spec.rb index da6e1f9458f..bab48796b8c 100644 --- a/spec/lib/event_filter_spec.rb +++ b/spec/lib/event_filter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe EventFilter do +RSpec.describe EventFilter do describe '#filter' do it 'returns "all" if given filter is nil' do expect(described_class.new(nil).filter).to eq(described_class::ALL) @@ -30,6 +30,7 @@ describe EventFilter do let_it_be(:left_event) { create(:event, :left, project: public_project, target: public_project) } let_it_be(:wiki_page_event) { create(:wiki_page_event) } let_it_be(:wiki_page_update_event) { create(:wiki_page_event, :updated) } + let_it_be(:design_event) { create(:design_event) } let(:filtered_events) { described_class.new(filter).apply_filter(Event.all) } @@ -79,15 +80,13 @@ describe EventFilter do it 'returns all events' do expect(filtered_events).to eq(Event.all) end + end - context 'the :wiki_events filter is disabled' do - before do - stub_feature_flags(wiki_events: false) - end + context 'with the "design" filter' do + let(:filter) { described_class::DESIGNS } - it 'does not return wiki events' do - expect(filtered_events).to eq(Event.not_wiki_page) - end + it 'returns only design events' do + expect(filtered_events).to contain_exactly(design_event) end end @@ -97,16 +96,6 @@ describe EventFilter do it 'returns only wiki page events' do expect(filtered_events).to contain_exactly(wiki_page_event, wiki_page_update_event) end - - context 'the :wiki_events filter is disabled' do - before do - stub_feature_flags(wiki_events: false) - end - - it 'does not return wiki events' do - expect(filtered_events).not_to include(wiki_page_event, wiki_page_update_event) - end - end end context 'with an unknown filter' do @@ -115,16 +104,6 @@ describe EventFilter do it 'returns all events' do expect(filtered_events).to eq(Event.all) end - - context 'the :wiki_events filter is disabled' do - before do - stub_feature_flags(wiki_events: false) - end - - it 'does not return wiki events' do - expect(filtered_events).to eq(Event.not_wiki_page) - end - end end context 'with a nil filter' do @@ -133,16 +112,6 @@ describe EventFilter do it 'returns all events' do expect(filtered_events).to eq(Event.all) end - - context 'the :wiki_events filter is disabled' do - before do - stub_feature_flags(wiki_events: false) - end - - it 'does not return wiki events' do - expect(filtered_events).to eq(Event.not_wiki_page) - end - end end end diff --git a/spec/lib/expand_variables_spec.rb b/spec/lib/expand_variables_spec.rb index 1b8ec2b1979..4a5b70ff248 100644 --- a/spec/lib/expand_variables_spec.rb +++ b/spec/lib/expand_variables_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ExpandVariables do +RSpec.describe ExpandVariables do describe '#expand' do context 'table tests' do using RSpec::Parameterized::TableSyntax diff --git a/spec/lib/extracts_path_spec.rb b/spec/lib/extracts_path_spec.rb index a56768a1a88..dbb3aa8797e 100644 --- a/spec/lib/extracts_path_spec.rb +++ b/spec/lib/extracts_path_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ExtractsPath do +RSpec.describe ExtractsPath do include described_class include RepoHelpers include Gitlab::Routing diff --git a/spec/lib/extracts_ref_spec.rb b/spec/lib/extracts_ref_spec.rb index 1867f639711..ca2f1fd7dc1 100644 --- a/spec/lib/extracts_ref_spec.rb +++ b/spec/lib/extracts_ref_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ExtractsRef do +RSpec.describe ExtractsRef do include described_class include RepoHelpers diff --git a/spec/lib/feature/definition_spec.rb b/spec/lib/feature/definition_spec.rb new file mode 100644 index 00000000000..49224cf4279 --- /dev/null +++ b/spec/lib/feature/definition_spec.rb @@ -0,0 +1,209 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Feature::Definition do + let(:attributes) do + { name: 'feature_flag', + type: 'development', + default_enabled: true } + end + + let(:path) { File.join('development', 'feature_flag.yml') } + let(:definition) { described_class.new(path, attributes) } + let(:yaml_content) { attributes.deep_stringify_keys.to_yaml } + + describe '#key' do + subject { definition.key } + + it 'returns a symbol from name' do + is_expected.to eq(:feature_flag) + end + end + + describe '#validate!' do + using RSpec::Parameterized::TableSyntax + + where(:param, :value, :result) do + :name | nil | /Feature flag is missing name/ + :path | nil | /Feature flag 'feature_flag' is missing path/ + :type | nil | /Feature flag 'feature_flag' is missing type/ + :type | 'invalid' | /Feature flag 'feature_flag' type 'invalid' is invalid/ + :path | 'development/invalid.yml' | /Feature flag 'feature_flag' has an invalid path/ + :path | 'invalid/feature_flag.yml' | /Feature flag 'feature_flag' has an invalid type/ + :default_enabled | nil | /Feature flag 'feature_flag' is missing default_enabled/ + end + + with_them do + let(:params) { attributes.merge(path: path) } + + before do + params[param] = value + end + + it do + expect do + described_class.new( + params[:path], params.except(:path) + ).validate! + end.to raise_error(result) + end + end + end + + describe '#valid_usage!' do + context 'validates type' do + it 'raises exception for invalid type' do + expect { definition.valid_usage!(type_in_code: :invalid, default_enabled_in_code: false) } + .to raise_error(/The `type:` of `feature_flag` is not equal to config/) + end + end + + context 'validates default enabled' do + it 'raises exception for different value' do + expect { definition.valid_usage!(type_in_code: :development, default_enabled_in_code: false) } + .to raise_error(/The `default_enabled:` of `feature_flag` is not equal to config/) + end + end + end + + describe '.paths' do + it 'returns at least one path' do + expect(described_class.paths).not_to be_empty + end + end + + describe '.load_from_file' do + it 'properly loads a definition from file' do + expect(File).to receive(:read).with(path) { yaml_content } + + expect(described_class.send(:load_from_file, path).attributes) + .to eq(definition.attributes) + end + + context 'for missing file' do + let(:path) { 'missing/feature-flag/file.yml' } + + it 'raises exception' do + expect do + described_class.send(:load_from_file, path) + end.to raise_error(/Invalid definition for/) + end + end + + context 'for invalid definition' do + it 'raises exception' do + expect(File).to receive(:read).with(path) { '{}' } + + expect do + described_class.send(:load_from_file, path) + end.to raise_error(/Feature flag is missing name/) + end + end + end + + describe '.load_all!' do + let(:store1) { Dir.mktmpdir('path1') } + let(:store2) { Dir.mktmpdir('path2') } + + before do + allow(described_class).to receive(:paths).and_return( + [ + File.join(store1, '**', '*.yml'), + File.join(store2, '**', '*.yml') + ] + ) + end + + it "when there's no feature flags a list of definitions is empty" do + expect(described_class.load_all!).to be_empty + end + + it "when there's a single feature flag it properly loads them" do + write_feature_flag(store1, path, yaml_content) + + expect(described_class.load_all!).to be_one + end + + it "when the same feature flag is stored multiple times raises exception" do + write_feature_flag(store1, path, yaml_content) + write_feature_flag(store2, path, yaml_content) + + expect { described_class.load_all! } + .to raise_error(/Feature flag 'feature_flag' is already defined/) + end + + it "when one of the YAMLs is invalid it does raise exception" do + write_feature_flag(store1, path, '{}') + + expect { described_class.load_all! } + .to raise_error(/Feature flag is missing name/) + end + + after do + FileUtils.rm_rf(store1) + FileUtils.rm_rf(store2) + end + + def write_feature_flag(store, path, content) + path = File.join(store, path) + dir = File.dirname(path) + FileUtils.mkdir_p(dir) + File.write(path, content) + end + end + + describe '.valid_usage!' do + before do + allow(described_class).to receive(:definitions) do + { definition.key => definition } + end + end + + context 'when a known feature flag is used' do + it 'validates it usage' do + expect(definition).to receive(:valid_usage!) + + described_class.valid_usage!(:feature_flag, type: :development, default_enabled: false) + end + end + + context 'when an unknown feature flag is used' do + context 'for a type that is required to have all feature flags registered' do + before do + stub_const('Feature::Shared::TYPES', { + development: { optional: false } + }) + end + + it 'raises exception' do + expect do + described_class.valid_usage!(:unknown_feature_flag, type: :development, default_enabled: false) + end.to raise_error(/Missing feature definition for `unknown_feature_flag`/) + end + end + + context 'for a type that is optional' do + before do + stub_const('Feature::Shared::TYPES', { + development: { optional: true } + }) + end + + it 'does not raise exception' do + expect do + described_class.valid_usage!(:unknown_feature_flag, type: :development, default_enabled: false) + end.not_to raise_error + end + end + + context 'for an unknown type' do + it 'raises exception' do + expect do + described_class.valid_usage!(:unknown_feature_flag, type: :unknown_type, default_enabled: false) + end.to raise_error(/Unknown feature flag type used: `unknown_type`/) + end + end + end + end +end diff --git a/spec/lib/feature/gitaly_spec.rb b/spec/lib/feature/gitaly_spec.rb index 6654b7627cd..a2181a63335 100644 --- a/spec/lib/feature/gitaly_spec.rb +++ b/spec/lib/feature/gitaly_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Feature::Gitaly do +RSpec.describe Feature::Gitaly do let(:feature_flag) { "mep_mep" } describe ".enabled?" do diff --git a/spec/lib/feature_spec.rb b/spec/lib/feature_spec.rb index 37f8d3ad47d..acd7d97ac85 100644 --- a/spec/lib/feature_spec.rb +++ b/spec/lib/feature_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Feature, stub_feature_flags: false do +RSpec.describe Feature, stub_feature_flags: false do before do # reset Flipper AR-engine Feature.reset @@ -21,66 +21,29 @@ describe Feature, stub_feature_flags: false do end describe '.persisted_names' do - context 'when FF_LEGACY_PERSISTED_NAMES=false' do - before do - stub_env('FF_LEGACY_PERSISTED_NAMES', 'false') - end - - it 'returns the names of the persisted features' do - Feature.enable('foo') - - expect(described_class.persisted_names).to contain_exactly('foo') - end - - it 'returns an empty Array when no features are presisted' do - expect(described_class.persisted_names).to be_empty - end - - it 'caches the feature names when request store is active', - :request_store, :use_clean_rails_memory_store_caching do - Feature.enable('foo') + it 'returns the names of the persisted features' do + Feature.enable('foo') - expect(Gitlab::ProcessMemoryCache.cache_backend) - .to receive(:fetch) - .once - .with('flipper/v1/features', expires_in: 1.minute) - .and_call_original + expect(described_class.persisted_names).to contain_exactly('foo') + end - 2.times do - expect(described_class.persisted_names).to contain_exactly('foo') - end - end + it 'returns an empty Array when no features are presisted' do + expect(described_class.persisted_names).to be_empty end - context 'when FF_LEGACY_PERSISTED_NAMES=true' do - before do - stub_env('FF_LEGACY_PERSISTED_NAMES', 'true') - end + it 'caches the feature names when request store is active', + :request_store, :use_clean_rails_memory_store_caching do + Feature.enable('foo') - it 'returns the names of the persisted features' do - Feature.enable('foo') + expect(Gitlab::ProcessMemoryCache.cache_backend) + .to receive(:fetch) + .once + .with('flipper/v1/features', expires_in: 1.minute) + .and_call_original + 2.times do expect(described_class.persisted_names).to contain_exactly('foo') end - - it 'returns an empty Array when no features are presisted' do - expect(described_class.persisted_names).to be_empty - end - - it 'caches the feature names when request store is active', - :request_store, :use_clean_rails_memory_store_caching do - Feature.enable('foo') - - expect(Gitlab::ProcessMemoryCache.cache_backend) - .to receive(:fetch) - .once - .with('flipper:persisted_names', expires_in: 1.minute) - .and_call_original - - 2.times do - expect(described_class.persisted_names).to contain_exactly('foo') - end - end end it 'fetches all flags once in a single query', :request_store do @@ -279,6 +242,36 @@ describe Feature, stub_feature_flags: false do end end end + + context 'validates usage of feature flag with YAML definition' do + let(:definition) do + Feature::Definition.new('development/my_feature_flag.yml', + name: 'my_feature_flag', + type: 'development', + default_enabled: false + ).tap(&:validate!) + end + + before do + allow(Feature::Definition).to receive(:definitions) do + { definition.key => definition } + end + end + + it 'when usage is correct' do + expect { described_class.enabled?(:my_feature_flag) }.not_to raise_error + end + + it 'when invalid type is used' do + expect { described_class.enabled?(:my_feature_flag, type: :licensed) } + .to raise_error(/The `type:` of/) + end + + it 'when invalid default_enabled is used' do + expect { described_class.enabled?(:my_feature_flag, default_enabled: true) } + .to raise_error(/The `default_enabled:` of/) + end + end end describe '.disable?' do diff --git a/spec/lib/file_size_validator_spec.rb b/spec/lib/file_size_validator_spec.rb index 87376a98c60..c5cb7d6eb30 100644 --- a/spec/lib/file_size_validator_spec.rb +++ b/spec/lib/file_size_validator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe FileSizeValidator do +RSpec.describe FileSizeValidator do let(:validator) { described_class.new(options) } let(:note) { create(:note) } let(:attachment) { AttachmentUploader.new(note) } diff --git a/spec/lib/forever_spec.rb b/spec/lib/forever_spec.rb index 9f17308241b..6f6b3055df5 100644 --- a/spec/lib/forever_spec.rb +++ b/spec/lib/forever_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Forever do +RSpec.describe Forever do describe '.date' do subject { described_class.date } diff --git a/spec/lib/gitaly/server_spec.rb b/spec/lib/gitaly/server_spec.rb index 390855b30ad..83df4b28757 100644 --- a/spec/lib/gitaly/server_spec.rb +++ b/spec/lib/gitaly/server_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitaly::Server do +RSpec.describe Gitaly::Server do let(:server) { described_class.new('default') } describe '.all' do diff --git a/spec/lib/gitlab/access/branch_protection_spec.rb b/spec/lib/gitlab/access/branch_protection_spec.rb index e4b763357c4..9b736a30c7e 100644 --- a/spec/lib/gitlab/access/branch_protection_spec.rb +++ b/spec/lib/gitlab/access/branch_protection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Access::BranchProtection do +RSpec.describe Gitlab::Access::BranchProtection do describe '#any?' do using RSpec::Parameterized::TableSyntax diff --git a/spec/lib/gitlab/alert_management/alert_params_spec.rb b/spec/lib/gitlab/alert_management/alert_params_spec.rb index 284af421f05..393838ab042 100644 --- a/spec/lib/gitlab/alert_management/alert_params_spec.rb +++ b/spec/lib/gitlab/alert_management/alert_params_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AlertManagement::AlertParams do +RSpec.describe Gitlab::AlertManagement::AlertParams do let_it_be(:project) { create(:project, :repository, :private) } describe '.from_generic_alert' do @@ -88,7 +88,9 @@ describe Gitlab::AlertManagement::AlertParams do payload: payload, started_at: parsed_alert.starts_at, ended_at: parsed_alert.ends_at, - fingerprint: parsed_alert.gitlab_fingerprint + fingerprint: parsed_alert.gitlab_fingerprint, + environment: parsed_alert.environment, + prometheus_alert: parsed_alert.gitlab_alert ) end end diff --git a/spec/lib/gitlab/alert_management/alert_status_counts_spec.rb b/spec/lib/gitlab/alert_management/alert_status_counts_spec.rb index 728cbf11cda..4e471a8eac0 100644 --- a/spec/lib/gitlab/alert_management/alert_status_counts_spec.rb +++ b/spec/lib/gitlab/alert_management/alert_status_counts_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AlertManagement::AlertStatusCounts do +RSpec.describe Gitlab::AlertManagement::AlertStatusCounts do let_it_be(:current_user) { create(:user) } let_it_be(:project) { create(:project) } let_it_be(:alert_1) { create(:alert_management_alert, :resolved, project: project) } diff --git a/spec/lib/gitlab/alert_management/fingerprint_spec.rb b/spec/lib/gitlab/alert_management/fingerprint_spec.rb index 7865d667f71..8a933963f6a 100644 --- a/spec/lib/gitlab/alert_management/fingerprint_spec.rb +++ b/spec/lib/gitlab/alert_management/fingerprint_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AlertManagement::Fingerprint do +RSpec.describe Gitlab::AlertManagement::Fingerprint do using RSpec::Parameterized::TableSyntax let_it_be(:alert) { create(:alert_management_alert) } @@ -13,34 +13,62 @@ describe Gitlab::AlertManagement::Fingerprint do context 'when data is an array' do let(:data) { [1, 'fingerprint', 'given'] } - it 'flattens the array' do - expect_next_instance_of(described_class) do |obj| - expect(obj).to receive(:flatten_array) - end - - subject - end - it 'returns the hashed fingerprint' do expected_fingerprint = Digest::SHA1.hexdigest(data.flatten.map!(&:to_s).join) expect(subject).to eq(expected_fingerprint) end - end - context 'when data is a non-array type' do - where(:data) do - [ - 111, - 'fingerprint', - :fingerprint, - true, - { test: true } - ] + context 'with a variety of data' do + where(:data) do + [ + 111, + 'fingerprint', + :fingerprint, + true + ] + end + + with_them do + it 'performs like a hashed fingerprint' do + expect(subject).to eq(Digest::SHA1.hexdigest(data.to_s)) + end + end end + end - with_them do + context 'when data is a hash' do + let(:data) { { test: true } } + + shared_examples 'fingerprinted Hash' do it 'performs like a hashed fingerprint' do - expect(subject).to eq(Digest::SHA1.hexdigest(data.to_s)) + flattened_hash = Gitlab::Utils::SafeInlineHash.merge_keys!(data).sort.to_s + expect(subject).to eq(Digest::SHA1.hexdigest(flattened_hash)) + end + end + + it_behaves_like 'fingerprinted Hash' + + context 'hashes with different order' do + it 'calculates the same result' do + data = { test: true, another_test: 1 } + data_hash = described_class.generate(data) + + reverse_data = { another_test: 1, test: true } + reverse_data_hash = described_class.generate(reverse_data) + + expect(data_hash).to eq(reverse_data_hash) + end + end + + context 'hash is too large' do + before do + expect_next_instance_of(Gitlab::Utils::SafeInlineHash) do |obj| + expect(obj).to receive(:valid?).and_return(false) + end + end + + it 'raises an error' do + expect { subject }.to raise_error(ArgumentError) end end end diff --git a/spec/lib/gitlab/alerting/alert_spec.rb b/spec/lib/gitlab/alerting/alert_spec.rb index d582ff6f32a..9663e6af0d2 100644 --- a/spec/lib/gitlab/alerting/alert_spec.rb +++ b/spec/lib/gitlab/alerting/alert_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Alerting::Alert do +RSpec.describe Gitlab::Alerting::Alert do let_it_be(:project) { create(:project) } let(:alert) { build(:alerting_alert, project: project, payload: payload) } diff --git a/spec/lib/gitlab/alerting/notification_payload_parser_spec.rb b/spec/lib/gitlab/alerting/notification_payload_parser_spec.rb index 889efae9585..0489108b159 100644 --- a/spec/lib/gitlab/alerting/notification_payload_parser_spec.rb +++ b/spec/lib/gitlab/alerting/notification_payload_parser_spec.rb @@ -2,7 +2,9 @@ require 'spec_helper' -describe Gitlab::Alerting::NotificationPayloadParser do +RSpec.describe Gitlab::Alerting::NotificationPayloadParser do + let_it_be(:project) { build(:project) } + describe '.call' do let(:starts_at) { Time.current.change(usec: 0) } let(:payload) do @@ -17,7 +19,7 @@ describe Gitlab::Alerting::NotificationPayloadParser do } end - subject { described_class.call(payload) } + subject { described_class.call(payload, project) } it 'returns Prometheus-like payload' do is_expected.to eq( diff --git a/spec/lib/gitlab/allowable_spec.rb b/spec/lib/gitlab/allowable_spec.rb index 4905cc4c3db..0535384be6e 100644 --- a/spec/lib/gitlab/allowable_spec.rb +++ b/spec/lib/gitlab/allowable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Allowable do +RSpec.describe Gitlab::Allowable do subject do Class.new.include(described_class).new end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/base_query_builder_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/base_query_builder_spec.rb index 250e2f16aec..80d3f82b404 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/base_query_builder_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/base_query_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::BaseQueryBuilder do +RSpec.describe Gitlab::Analytics::CycleAnalytics::BaseQueryBuilder do let_it_be(:project) { create(:project, :empty_repo) } let_it_be(:mr1) { create(:merge_request, target_project: project, source_project: project, allow_broken: true, created_at: 3.months.ago) } let_it_be(:mr2) { create(:merge_request, target_project: project, source_project: project, allow_broken: true, created_at: 1.month.ago) } diff --git a/spec/lib/gitlab/analytics/cycle_analytics/median_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/median_spec.rb index 92ecec350ae..c1ea000eb7b 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/median_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/median_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::Median do +RSpec.describe Gitlab::Analytics::CycleAnalytics::Median do let_it_be(:project) { create(:project, :repository) } let(:query) { Project.joins(merge_requests: :metrics) } diff --git a/spec/lib/gitlab/analytics/cycle_analytics/records_fetcher_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/records_fetcher_spec.rb index e3429b0ca57..b8f9dde4291 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/records_fetcher_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/records_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::RecordsFetcher do +RSpec.describe Gitlab::Analytics::CycleAnalytics::RecordsFetcher do around do |example| Timecop.freeze { example.run } end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/code_stage_start_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/code_stage_start_spec.rb index 29c8d548754..fe390289ef6 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/code_stage_start_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/code_stage_start_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::CodeStageStart do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::CodeStageStart do let(:subject) { described_class.new({}) } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_created_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_created_spec.rb index efdef91c5a2..5cc6b05407f 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_created_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_created_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::IssueCreated do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::IssueCreated do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_first_mentioned_in_commit_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_first_mentioned_in_commit_spec.rb index 50883e1c1e2..715ad5a8e7d 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_first_mentioned_in_commit_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_first_mentioned_in_commit_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::IssueFirstMentionedInCommit do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::IssueFirstMentionedInCommit do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_stage_end_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_stage_end_spec.rb index 85062db370a..56241194f36 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_stage_end_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/issue_stage_end_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::IssueStageEnd do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::IssueStageEnd do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_created_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_created_spec.rb index 7858b810661..f3202eab5bb 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_created_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_created_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestCreated do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestCreated do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_first_deployed_to_production_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_first_deployed_to_production_spec.rb index ba9d8be5a2c..03b0ccfae43 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_first_deployed_to_production_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_first_deployed_to_production_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestFirstDeployedToProduction do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestFirstDeployedToProduction do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_finished_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_finished_spec.rb index 8e83e10ef96..b0c003e6f2a 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_finished_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_finished_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestLastBuildFinished do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestLastBuildFinished do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_started_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_started_spec.rb index 9f6b430a320..8f9aaf6f463 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_started_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_last_build_started_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestLastBuildStarted do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestLastBuildStarted do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_merged_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_merged_spec.rb index ce2aa0a60db..f1d2ca9f36e 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_merged_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/merge_request_merged_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestMerged do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::MergeRequestMerged do it_behaves_like 'cycle analytics event' end diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/plan_stage_start_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/plan_stage_start_spec.rb index cb63139f0a8..3248af524bd 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/plan_stage_start_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/plan_stage_start_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::PlanStageStart do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::PlanStageStart do let(:subject) { described_class.new({}) } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/stage_event_spec.rb b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/stage_event_spec.rb index b05faf5d813..6fc658ecade 100644 --- a/spec/lib/gitlab/analytics/cycle_analytics/stage_events/stage_event_spec.rb +++ b/spec/lib/gitlab/analytics/cycle_analytics/stage_events/stage_event_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Analytics::CycleAnalytics::StageEvents::StageEvent do +RSpec.describe Gitlab::Analytics::CycleAnalytics::StageEvents::StageEvent do let(:instance) { described_class.new({}) } it { expect(described_class).to respond_to(:name) } diff --git a/spec/lib/gitlab/analytics/unique_visits_spec.rb b/spec/lib/gitlab/analytics/unique_visits_spec.rb new file mode 100644 index 00000000000..ff3623a3a71 --- /dev/null +++ b/spec/lib/gitlab/analytics/unique_visits_spec.rb @@ -0,0 +1,62 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Analytics::UniqueVisits, :clean_gitlab_redis_shared_state do + let(:unique_visits) { Gitlab::Analytics::UniqueVisits.new } + let(:target1_id) { 'g_analytics_contribution' } + let(:target2_id) { 'g_analytics_insights' } + let(:target3_id) { 'g_analytics_issues' } + let(:visitor1_id) { 'dfb9d2d2-f56c-4c77-8aeb-6cddc4a1f857' } + let(:visitor2_id) { '1dd9afb2-a3ee-4de1-8ae3-a405579c8584' } + + around do |example| + # We need to freeze to a reference time + # because visits are grouped by the week number in the year + # Without freezing the time, the test may behave inconsistently + # depending on which day of the week test is run. + reference_time = Time.utc(2020, 6, 1) + Timecop.freeze(reference_time) { example.run } + end + + describe '#track_visit' do + it 'tracks the unique weekly visits for targets' do + unique_visits.track_visit(visitor1_id, target1_id, 7.days.ago) + unique_visits.track_visit(visitor1_id, target1_id, 7.days.ago) + unique_visits.track_visit(visitor2_id, target1_id, 7.days.ago) + + unique_visits.track_visit(visitor2_id, target2_id, 7.days.ago) + unique_visits.track_visit(visitor1_id, target2_id, 8.days.ago) + unique_visits.track_visit(visitor1_id, target2_id, 15.days.ago) + + expect(unique_visits.weekly_unique_visits_for_target(target1_id)).to eq(2) + expect(unique_visits.weekly_unique_visits_for_target(target2_id)).to eq(1) + + expect(unique_visits.weekly_unique_visits_for_target(target2_id, week_of: 15.days.ago)).to eq(1) + + expect(unique_visits.weekly_unique_visits_for_target(target3_id)).to eq(0) + + expect(unique_visits.weekly_unique_visits_for_any_target).to eq(2) + expect(unique_visits.weekly_unique_visits_for_any_target(week_of: 15.days.ago)).to eq(1) + expect(unique_visits.weekly_unique_visits_for_any_target(week_of: 30.days.ago)).to eq(0) + end + + it 'sets the keys in Redis to expire automatically after 28 days' do + unique_visits.track_visit(visitor1_id, target1_id) + + Gitlab::Redis::SharedState.with do |redis| + redis.scan_each(match: "#{target1_id}-*").each do |key| + expect(redis.ttl(key)).to be_within(5.seconds).of(28.days) + end + end + end + + it 'raises an error if an invalid target id is given' do + invalid_target_id = "x_invalid" + + expect do + unique_visits.track_visit(visitor1_id, invalid_target_id) + end.to raise_error("Invalid target id #{invalid_target_id}") + end + end +end diff --git a/spec/lib/gitlab/anonymous_session_spec.rb b/spec/lib/gitlab/anonymous_session_spec.rb index 94daa0f2470..0f0795cd9fc 100644 --- a/spec/lib/gitlab/anonymous_session_spec.rb +++ b/spec/lib/gitlab/anonymous_session_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AnonymousSession, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::AnonymousSession, :clean_gitlab_redis_shared_state do let(:default_session_id) { '6919a6f1bb119dd7396fadc38fd18d0d' } let(:additional_session_id) { '7919a6f1bb119dd7396fadc38fd18d0d' } diff --git a/spec/lib/gitlab/app_json_logger_spec.rb b/spec/lib/gitlab/app_json_logger_spec.rb index d11456236cc..89dce969522 100644 --- a/spec/lib/gitlab/app_json_logger_spec.rb +++ b/spec/lib/gitlab/app_json_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AppJsonLogger do +RSpec.describe Gitlab::AppJsonLogger do subject { described_class.new('/dev/null') } let(:hash_message) { { 'message' => 'Message', 'project_id' => '123' } } diff --git a/spec/lib/gitlab/app_logger_spec.rb b/spec/lib/gitlab/app_logger_spec.rb index 132a10b9409..166b1fda268 100644 --- a/spec/lib/gitlab/app_logger_spec.rb +++ b/spec/lib/gitlab/app_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AppLogger do +RSpec.describe Gitlab::AppLogger do subject { described_class } it 'builds a Gitlab::Logger object twice' do diff --git a/spec/lib/gitlab/app_text_logger_spec.rb b/spec/lib/gitlab/app_text_logger_spec.rb index c84b986ce40..04c2e946640 100644 --- a/spec/lib/gitlab/app_text_logger_spec.rb +++ b/spec/lib/gitlab/app_text_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AppTextLogger do +RSpec.describe Gitlab::AppTextLogger do subject { described_class.new('/dev/null') } let(:hash_message) { { message: 'Message', project_id: 123 } } diff --git a/spec/lib/gitlab/application_context_spec.rb b/spec/lib/gitlab/application_context_spec.rb index 3be967ac8a4..88f865adea7 100644 --- a/spec/lib/gitlab/application_context_spec.rb +++ b/spec/lib/gitlab/application_context_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ApplicationContext do +RSpec.describe Gitlab::ApplicationContext do describe '.with_context' do it 'yields the block' do expect { |b| described_class.with_context({}, &b) }.to yield_control diff --git a/spec/lib/gitlab/application_rate_limiter_spec.rb b/spec/lib/gitlab/application_rate_limiter_spec.rb index f1a0163d91c..14a7e25a2e8 100644 --- a/spec/lib/gitlab/application_rate_limiter_spec.rb +++ b/spec/lib/gitlab/application_rate_limiter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ApplicationRateLimiter, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::ApplicationRateLimiter, :clean_gitlab_redis_cache do let(:redis) { double('redis') } let(:user) { create(:user) } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/asciidoc/include_processor_spec.rb b/spec/lib/gitlab/asciidoc/include_processor_spec.rb index 2781319567c..067dcefb525 100644 --- a/spec/lib/gitlab/asciidoc/include_processor_spec.rb +++ b/spec/lib/gitlab/asciidoc/include_processor_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'nokogiri' -describe Gitlab::Asciidoc::IncludeProcessor do +RSpec.describe Gitlab::Asciidoc::IncludeProcessor do let_it_be(:project) { create(:project, :repository) } let(:processor_context) do diff --git a/spec/lib/gitlab/asciidoc_spec.rb b/spec/lib/gitlab/asciidoc_spec.rb index 24528d79fa8..40a4ab3e173 100644 --- a/spec/lib/gitlab/asciidoc_spec.rb +++ b/spec/lib/gitlab/asciidoc_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' require 'nokogiri' module Gitlab - describe Asciidoc do + RSpec.describe Asciidoc do include FakeBlobHelpers before do diff --git a/spec/lib/gitlab/asset_proxy_spec.rb b/spec/lib/gitlab/asset_proxy_spec.rb index e406917a5a4..73b101c0dd8 100644 --- a/spec/lib/gitlab/asset_proxy_spec.rb +++ b/spec/lib/gitlab/asset_proxy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AssetProxy do +RSpec.describe Gitlab::AssetProxy do context 'when asset proxy is disabled' do before do stub_asset_proxy_setting(enabled: false) diff --git a/spec/lib/gitlab/auth/activity_spec.rb b/spec/lib/gitlab/auth/activity_spec.rb index e03fafe3826..cbc42c46470 100644 --- a/spec/lib/gitlab/auth/activity_spec.rb +++ b/spec/lib/gitlab/auth/activity_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Auth::Activity do +RSpec.describe Gitlab::Auth::Activity do describe '.each_counter' do it 'has all static counters defined' do described_class.each_counter do |counter| diff --git a/spec/lib/gitlab/auth/auth_finders_spec.rb b/spec/lib/gitlab/auth/auth_finders_spec.rb index 2aef206c7fd..d0f5d0a9b35 100644 --- a/spec/lib/gitlab/auth/auth_finders_spec.rb +++ b/spec/lib/gitlab/auth/auth_finders_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::AuthFinders do +RSpec.describe Gitlab::Auth::AuthFinders do include described_class include HttpBasicAuthHelpers @@ -26,6 +26,63 @@ describe Gitlab::Auth::AuthFinders do env.merge!(basic_auth_header(username, password)) end + shared_examples 'find user from job token' do + context 'when route is allowed to be authenticated' do + let(:route_authentication_setting) { { job_token_allowed: true } } + + it "returns an Unauthorized exception for an invalid token" do + set_token('invalid token') + + expect { subject }.to raise_error(Gitlab::Auth::UnauthorizedError) + end + + it "return user if token is valid" do + set_token(job.token) + + expect(subject).to eq(user) + expect(@current_authenticated_job).to eq job + end + end + end + + describe '#find_user_from_bearer_token' do + let(:job) { create(:ci_build, user: user) } + + subject { find_user_from_bearer_token } + + context 'when the token is passed as an oauth token' do + def set_token(token) + env['HTTP_AUTHORIZATION'] = "Bearer #{token}" + end + + context 'with a job token' do + it_behaves_like 'find user from job token' + end + + context 'with oauth token' do + let(:application) { Doorkeeper::Application.create!(name: 'MyApp', redirect_uri: 'https://app.com', owner: user) } + let(:token) { Doorkeeper::AccessToken.create!(application_id: application.id, resource_owner_id: user.id, scopes: 'api').token } + + before do + set_token(token) + end + + it { is_expected.to eq user } + end + end + + context 'with a personal access token' do + let(:pat) { create(:personal_access_token, user: user) } + let(:token) { pat.token } + + before do + env[described_class::PRIVATE_TOKEN_HEADER] = pat.token + end + + it { is_expected.to eq user } + end + end + describe '#find_user_from_warden' do context 'with CSRF token' do before do @@ -522,8 +579,24 @@ describe Gitlab::Auth::AuthFinders do end describe '#validate_access_token!' do + subject { validate_access_token! } + let(:personal_access_token) { create(:personal_access_token, user: user) } + context 'with a job token' do + let(:route_authentication_setting) { { job_token_allowed: true } } + let(:job) { create(:ci_build, user: user) } + + before do + env['HTTP_AUTHORIZATION'] = "Bearer #{job.token}" + find_user_from_bearer_token + end + + it 'does not raise an error' do + expect { subject }.not_to raise_error + end + end + it 'returns nil if no access_token present' do expect(validate_access_token!).to be_nil end diff --git a/spec/lib/gitlab/auth/blocked_user_tracker_spec.rb b/spec/lib/gitlab/auth/blocked_user_tracker_spec.rb index 52849f8c172..76775db3a4a 100644 --- a/spec/lib/gitlab/auth/blocked_user_tracker_spec.rb +++ b/spec/lib/gitlab/auth/blocked_user_tracker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::BlockedUserTracker do +RSpec.describe Gitlab::Auth::BlockedUserTracker do describe '#log_blocked_user_activity!' do context 'when user is not blocked' do it 'does not log blocked user activity' do diff --git a/spec/lib/gitlab/auth/current_user_mode_spec.rb b/spec/lib/gitlab/auth/current_user_mode_spec.rb index 26e44fa7cc8..60b403780c0 100644 --- a/spec/lib/gitlab/auth/current_user_mode_spec.rb +++ b/spec/lib/gitlab/auth/current_user_mode_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::CurrentUserMode, :do_not_mock_admin_mode, :request_store do +RSpec.describe Gitlab::Auth::CurrentUserMode, :do_not_mock_admin_mode, :request_store do let(:user) { build_stubbed(:user) } subject { described_class.new(user) } diff --git a/spec/lib/gitlab/auth/ip_rate_limiter_spec.rb b/spec/lib/gitlab/auth/ip_rate_limiter_spec.rb index aea1b2921b6..3d782272d7e 100644 --- a/spec/lib/gitlab/auth/ip_rate_limiter_spec.rb +++ b/spec/lib/gitlab/auth/ip_rate_limiter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::IpRateLimiter, :use_clean_rails_memory_store_caching do +RSpec.describe Gitlab::Auth::IpRateLimiter, :use_clean_rails_memory_store_caching do let(:ip) { '10.2.2.3' } let(:whitelist) { ['127.0.0.1'] } let(:options) do diff --git a/spec/lib/gitlab/auth/key_status_checker_spec.rb b/spec/lib/gitlab/auth/key_status_checker_spec.rb index b1a540eae81..e8ac0d7c394 100644 --- a/spec/lib/gitlab/auth/key_status_checker_spec.rb +++ b/spec/lib/gitlab/auth/key_status_checker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::KeyStatusChecker do +RSpec.describe Gitlab::Auth::KeyStatusChecker do let_it_be(:never_expires_key) { build(:personal_key, expires_at: nil) } let_it_be(:expired_key) { build(:personal_key, expires_at: 3.days.ago) } let_it_be(:expiring_soon_key) { build(:personal_key, expires_at: 3.days.from_now) } diff --git a/spec/lib/gitlab/auth/ldap/access_spec.rb b/spec/lib/gitlab/auth/ldap/access_spec.rb index 2f691429541..9e269f84b7e 100644 --- a/spec/lib/gitlab/auth/ldap/access_spec.rb +++ b/spec/lib/gitlab/auth/ldap/access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::Access do +RSpec.describe Gitlab::Auth::Ldap::Access do include LdapHelpers let(:user) { create(:omniauth_user) } diff --git a/spec/lib/gitlab/auth/ldap/adapter_spec.rb b/spec/lib/gitlab/auth/ldap/adapter_spec.rb index 34853acdd0f..78970378b7f 100644 --- a/spec/lib/gitlab/auth/ldap/adapter_spec.rb +++ b/spec/lib/gitlab/auth/ldap/adapter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::Adapter do +RSpec.describe Gitlab::Auth::Ldap::Adapter do include LdapHelpers let(:ldap) { double(:ldap) } diff --git a/spec/lib/gitlab/auth/ldap/auth_hash_spec.rb b/spec/lib/gitlab/auth/ldap/auth_hash_spec.rb index 7bc92d0abea..9dff7f7b3dc 100644 --- a/spec/lib/gitlab/auth/ldap/auth_hash_spec.rb +++ b/spec/lib/gitlab/auth/ldap/auth_hash_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::AuthHash do +RSpec.describe Gitlab::Auth::Ldap::AuthHash do include LdapHelpers let(:auth_hash) do diff --git a/spec/lib/gitlab/auth/ldap/authentication_spec.rb b/spec/lib/gitlab/auth/ldap/authentication_spec.rb index 1f8b1474539..42a893417d8 100644 --- a/spec/lib/gitlab/auth/ldap/authentication_spec.rb +++ b/spec/lib/gitlab/auth/ldap/authentication_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::Authentication do +RSpec.describe Gitlab::Auth::Ldap::Authentication do let(:dn) { 'uid=John Smith, ou=People, dc=example, dc=com' } let(:user) { create(:omniauth_user, extern_uid: Gitlab::Auth::Ldap::Person.normalize_dn(dn)) } let(:login) { 'john' } diff --git a/spec/lib/gitlab/auth/ldap/config_spec.rb b/spec/lib/gitlab/auth/ldap/config_spec.rb index 124f072ebe6..4287596af8f 100644 --- a/spec/lib/gitlab/auth/ldap/config_spec.rb +++ b/spec/lib/gitlab/auth/ldap/config_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::Config do +RSpec.describe Gitlab::Auth::Ldap::Config do include LdapHelpers let(:config) { described_class.new('ldapmain') } diff --git a/spec/lib/gitlab/auth/ldap/dn_spec.rb b/spec/lib/gitlab/auth/ldap/dn_spec.rb index 7aaffa52ae4..e89f764b040 100644 --- a/spec/lib/gitlab/auth/ldap/dn_spec.rb +++ b/spec/lib/gitlab/auth/ldap/dn_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::DN do +RSpec.describe Gitlab::Auth::Ldap::DN do using RSpec::Parameterized::TableSyntax describe '#normalize_value' do diff --git a/spec/lib/gitlab/auth/ldap/person_spec.rb b/spec/lib/gitlab/auth/ldap/person_spec.rb index 403a48d40ef..6857b561370 100644 --- a/spec/lib/gitlab/auth/ldap/person_spec.rb +++ b/spec/lib/gitlab/auth/ldap/person_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::Person do +RSpec.describe Gitlab::Auth::Ldap::Person do include LdapHelpers let(:entry) { ldap_user_entry('john.doe') } diff --git a/spec/lib/gitlab/auth/ldap/user_spec.rb b/spec/lib/gitlab/auth/ldap/user_spec.rb index 867633e54df..7ca2878e583 100644 --- a/spec/lib/gitlab/auth/ldap/user_spec.rb +++ b/spec/lib/gitlab/auth/ldap/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Ldap::User do +RSpec.describe Gitlab::Auth::Ldap::User do include LdapHelpers let(:ldap_user) { described_class.new(auth_hash) } diff --git a/spec/lib/gitlab/auth/o_auth/auth_hash_spec.rb b/spec/lib/gitlab/auth/o_auth/auth_hash_spec.rb index a2d9e27ea5b..7a60acca95b 100644 --- a/spec/lib/gitlab/auth/o_auth/auth_hash_spec.rb +++ b/spec/lib/gitlab/auth/o_auth/auth_hash_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::OAuth::AuthHash do +RSpec.describe Gitlab::Auth::OAuth::AuthHash do let(:provider) { 'ldap'.freeze } let(:auth_hash) do described_class.new( diff --git a/spec/lib/gitlab/auth/o_auth/identity_linker_spec.rb b/spec/lib/gitlab/auth/o_auth/identity_linker_spec.rb index 45c1baa4089..8014fbe1687 100644 --- a/spec/lib/gitlab/auth/o_auth/identity_linker_spec.rb +++ b/spec/lib/gitlab/auth/o_auth/identity_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::OAuth::IdentityLinker do +RSpec.describe Gitlab::Auth::OAuth::IdentityLinker do let(:user) { create(:user) } let(:provider) { 'twitter' } let(:uid) { user.email } diff --git a/spec/lib/gitlab/auth/o_auth/provider_spec.rb b/spec/lib/gitlab/auth/o_auth/provider_spec.rb index 8b0d4d786cd..658a9976cc2 100644 --- a/spec/lib/gitlab/auth/o_auth/provider_spec.rb +++ b/spec/lib/gitlab/auth/o_auth/provider_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::OAuth::Provider do +RSpec.describe Gitlab::Auth::OAuth::Provider do describe '.enabled?' do before do allow(described_class).to receive(:providers).and_return([:ldapmain, :google_oauth2]) diff --git a/spec/lib/gitlab/auth/o_auth/user_spec.rb b/spec/lib/gitlab/auth/o_auth/user_spec.rb index 62b83ff8b88..ad04fddc675 100644 --- a/spec/lib/gitlab/auth/o_auth/user_spec.rb +++ b/spec/lib/gitlab/auth/o_auth/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::OAuth::User do +RSpec.describe Gitlab::Auth::OAuth::User do include LdapHelpers let(:oauth_user) { described_class.new(auth_hash) } diff --git a/spec/lib/gitlab/auth/request_authenticator_spec.rb b/spec/lib/gitlab/auth/request_authenticator_spec.rb index 87c96803c3a..32d64519e2c 100644 --- a/spec/lib/gitlab/auth/request_authenticator_spec.rb +++ b/spec/lib/gitlab/auth/request_authenticator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::RequestAuthenticator do +RSpec.describe Gitlab::Auth::RequestAuthenticator do let(:env) do { 'rack.input' => '', diff --git a/spec/lib/gitlab/auth/saml/auth_hash_spec.rb b/spec/lib/gitlab/auth/saml/auth_hash_spec.rb index 8b88c16f317..f1fad946f35 100644 --- a/spec/lib/gitlab/auth/saml/auth_hash_spec.rb +++ b/spec/lib/gitlab/auth/saml/auth_hash_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Saml::AuthHash do +RSpec.describe Gitlab::Auth::Saml::AuthHash do include LoginHelpers let(:raw_info_attr) { { 'groups' => %w(Developers Freelancers) } } diff --git a/spec/lib/gitlab/auth/saml/identity_linker_spec.rb b/spec/lib/gitlab/auth/saml/identity_linker_spec.rb index 7912c8fb4b1..743163ad315 100644 --- a/spec/lib/gitlab/auth/saml/identity_linker_spec.rb +++ b/spec/lib/gitlab/auth/saml/identity_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Saml::IdentityLinker do +RSpec.describe Gitlab::Auth::Saml::IdentityLinker do let(:user) { create(:user) } let(:provider) { 'saml' } let(:uid) { user.email } diff --git a/spec/lib/gitlab/auth/saml/origin_validator_spec.rb b/spec/lib/gitlab/auth/saml/origin_validator_spec.rb index ae120b328ab..f13140cdcba 100644 --- a/spec/lib/gitlab/auth/saml/origin_validator_spec.rb +++ b/spec/lib/gitlab/auth/saml/origin_validator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Saml::OriginValidator do +RSpec.describe Gitlab::Auth::Saml::OriginValidator do let(:session) { instance_double(ActionDispatch::Request::Session) } subject { described_class.new(session) } diff --git a/spec/lib/gitlab/auth/saml/user_spec.rb b/spec/lib/gitlab/auth/saml/user_spec.rb index 55d2f22b923..7f8346f0486 100644 --- a/spec/lib/gitlab/auth/saml/user_spec.rb +++ b/spec/lib/gitlab/auth/saml/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::Saml::User do +RSpec.describe Gitlab::Auth::Saml::User do include LdapHelpers include LoginHelpers diff --git a/spec/lib/gitlab/auth/unique_ips_limiter_spec.rb b/spec/lib/gitlab/auth/unique_ips_limiter_spec.rb index ebf7de9c701..a08055ab852 100644 --- a/spec/lib/gitlab/auth/unique_ips_limiter_spec.rb +++ b/spec/lib/gitlab/auth/unique_ips_limiter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::UniqueIpsLimiter, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::Auth::UniqueIpsLimiter, :clean_gitlab_redis_shared_state do include_context 'unique ips sign in limit' let(:user) { create(:user) } diff --git a/spec/lib/gitlab/auth/user_access_denied_reason_spec.rb b/spec/lib/gitlab/auth/user_access_denied_reason_spec.rb index 7045105a2c7..a2a0eb5428a 100644 --- a/spec/lib/gitlab/auth/user_access_denied_reason_spec.rb +++ b/spec/lib/gitlab/auth/user_access_denied_reason_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth::UserAccessDeniedReason do +RSpec.describe Gitlab::Auth::UserAccessDeniedReason do include TermsHelper let(:user) { build(:user) } diff --git a/spec/lib/gitlab/auth_spec.rb b/spec/lib/gitlab/auth_spec.rb index 870f02b6933..0b391c8cba9 100644 --- a/spec/lib/gitlab/auth_spec.rb +++ b/spec/lib/gitlab/auth_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Auth, :use_clean_rails_memory_store_caching do +RSpec.describe Gitlab::Auth, :use_clean_rails_memory_store_caching do let_it_be(:project) { create(:project) } let(:gl_auth) { described_class } @@ -172,7 +172,7 @@ describe Gitlab::Auth, :use_clean_rails_memory_store_caching do end end - (HasStatus::AVAILABLE_STATUSES - ['running']).each do |build_status| + (Ci::HasStatus::AVAILABLE_STATUSES - ['running']).each do |build_status| context "for #{build_status} build" do let!(:build) { create(:ci_build, status: build_status) } let(:project) { build.project } diff --git a/spec/lib/gitlab/authorized_keys_spec.rb b/spec/lib/gitlab/authorized_keys_spec.rb index d89eb9ef114..1053ae2e325 100644 --- a/spec/lib/gitlab/authorized_keys_spec.rb +++ b/spec/lib/gitlab/authorized_keys_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::AuthorizedKeys do +RSpec.describe Gitlab::AuthorizedKeys do let(:logger) { double('logger').as_null_object } subject(:authorized_keys) { described_class.new(logger) } diff --git a/spec/lib/gitlab/background_migration/add_merge_request_diff_commits_count_spec.rb b/spec/lib/gitlab/background_migration/add_merge_request_diff_commits_count_spec.rb index b77c67b120f..1e72b249c19 100644 --- a/spec/lib/gitlab/background_migration/add_merge_request_diff_commits_count_spec.rb +++ b/spec/lib/gitlab/background_migration/add_merge_request_diff_commits_count_spec.rb @@ -2,13 +2,15 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::AddMergeRequestDiffCommitsCount, schema: 20180105212544 do +RSpec.describe Gitlab::BackgroundMigration::AddMergeRequestDiffCommitsCount do + let(:namespaces_table) { table(:namespaces) } let(:projects_table) { table(:projects) } let(:merge_requests_table) { table(:merge_requests) } let(:merge_request_diffs_table) { table(:merge_request_diffs) } let(:merge_request_diff_commits_table) { table(:merge_request_diff_commits) } - let(:project) { projects_table.create!(name: 'gitlab', path: 'gitlab-org/gitlab-ce') } + let(:namespace) { namespaces_table.create!(name: 'gitlab-org', path: 'gitlab-org') } + let(:project) { projects_table.create!(name: 'gitlab', path: 'gitlab-org/gitlab-ce', namespace_id: namespace.id) } let(:merge_request) do merge_requests_table.create!(target_project_id: project.id, target_branch: 'master', diff --git a/spec/lib/gitlab/background_migration/archive_legacy_traces_spec.rb b/spec/lib/gitlab/background_migration/archive_legacy_traces_spec.rb index 5c8dcb38511..7991ad69007 100644 --- a/spec/lib/gitlab/background_migration/archive_legacy_traces_spec.rb +++ b/spec/lib/gitlab/background_migration/archive_legacy_traces_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::ArchiveLegacyTraces, schema: 20180529152628 do +RSpec.describe Gitlab::BackgroundMigration::ArchiveLegacyTraces do include TraceHelpers let(:namespaces) { table(:namespaces) } diff --git a/spec/lib/gitlab/background_migration/backfill_deployment_clusters_from_deployments_spec.rb b/spec/lib/gitlab/background_migration/backfill_deployment_clusters_from_deployments_spec.rb index fdabc8e8f7c..2be9c03e5bd 100644 --- a/spec/lib/gitlab/background_migration/backfill_deployment_clusters_from_deployments_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_deployment_clusters_from_deployments_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillDeploymentClustersFromDeployments, :migration, schema: 20200227140242 do +RSpec.describe Gitlab::BackgroundMigration::BackfillDeploymentClustersFromDeployments, :migration, schema: 20200227140242 do subject { described_class.new } describe '#perform' do diff --git a/spec/lib/gitlab/background_migration/backfill_environment_id_deployment_merge_requests_spec.rb b/spec/lib/gitlab/background_migration/backfill_environment_id_deployment_merge_requests_spec.rb index 34ac70071bb..550bdc484c9 100644 --- a/spec/lib/gitlab/background_migration/backfill_environment_id_deployment_merge_requests_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_environment_id_deployment_merge_requests_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillEnvironmentIdDeploymentMergeRequests, schema: 20200312134637 do +RSpec.describe Gitlab::BackgroundMigration::BackfillEnvironmentIdDeploymentMergeRequests, schema: 20200312134637 do let(:environments) { table(:environments) } let(:merge_requests) { table(:merge_requests) } let(:deployments) { table(:deployments) } diff --git a/spec/lib/gitlab/background_migration/backfill_hashed_project_repositories_spec.rb b/spec/lib/gitlab/background_migration/backfill_hashed_project_repositories_spec.rb index f64c3ccc058..79b344ea6fa 100644 --- a/spec/lib/gitlab/background_migration/backfill_hashed_project_repositories_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_hashed_project_repositories_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillHashedProjectRepositories, schema: 20181130102132 do +RSpec.describe Gitlab::BackgroundMigration::BackfillHashedProjectRepositories do it_behaves_like 'backfill migration for project repositories', :hashed end diff --git a/spec/lib/gitlab/background_migration/backfill_legacy_project_repositories_spec.rb b/spec/lib/gitlab/background_migration/backfill_legacy_project_repositories_spec.rb index 806d044ab40..c4013d002b2 100644 --- a/spec/lib/gitlab/background_migration/backfill_legacy_project_repositories_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_legacy_project_repositories_spec.rb @@ -2,6 +2,6 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillLegacyProjectRepositories, schema: 20181212171634 do +RSpec.describe Gitlab::BackgroundMigration::BackfillLegacyProjectRepositories do it_behaves_like 'backfill migration for project repositories', :legacy end diff --git a/spec/lib/gitlab/background_migration/backfill_namespace_settings_spec.rb b/spec/lib/gitlab/background_migration/backfill_namespace_settings_spec.rb new file mode 100644 index 00000000000..43e76a2952e --- /dev/null +++ b/spec/lib/gitlab/background_migration/backfill_namespace_settings_spec.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::BackgroundMigration::BackfillNamespaceSettings, schema: 20200703125016 do + let(:namespaces) { table(:namespaces) } + let(:namespace_settings) { table(:namespace_settings) } + let(:namespace) { table(:namespaces).create!(name: 'user', path: 'user') } + + subject { described_class.new } + + describe '#perform' do + it 'creates settings for all projects in range' do + namespaces.create!(id: 5, name: 'test1', path: 'test1') + namespaces.create!(id: 7, name: 'test2', path: 'test2') + namespaces.create!(id: 8, name: 'test3', path: 'test3') + + subject.perform(5, 7) + + expect(namespace_settings.all.pluck(:namespace_id)).to contain_exactly(5, 7) + end + end +end diff --git a/spec/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config_spec.rb b/spec/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config_spec.rb index 44f5c3380a1..1b2e1ed0c1a 100644 --- a/spec/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillProjectFullpathInRepoConfig, schema: 20181010133639 do +RSpec.describe Gitlab::BackgroundMigration::BackfillProjectFullpathInRepoConfig do let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:group) { namespaces.create!(name: 'foo', path: 'foo') } diff --git a/spec/lib/gitlab/background_migration/backfill_project_repositories_spec.rb b/spec/lib/gitlab/background_migration/backfill_project_repositories_spec.rb index cfaef1578a9..8a8edc1af29 100644 --- a/spec/lib/gitlab/background_migration/backfill_project_repositories_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_project_repositories_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' # rubocop:disable RSpec/FactoriesInMigrationSpecs -describe Gitlab::BackgroundMigration::BackfillProjectRepositories do +RSpec.describe Gitlab::BackgroundMigration::BackfillProjectRepositories do let(:group) { create(:group, name: 'foo', path: 'foo') } describe described_class::ShardFinder do diff --git a/spec/lib/gitlab/background_migration/backfill_project_settings_spec.rb b/spec/lib/gitlab/background_migration/backfill_project_settings_spec.rb index a2b4e003d82..4e7a3a33f7e 100644 --- a/spec/lib/gitlab/background_migration/backfill_project_settings_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_project_settings_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillProjectSettings, schema: 20200114113341 do +RSpec.describe Gitlab::BackgroundMigration::BackfillProjectSettings, schema: 20200114113341 do let(:projects) { table(:projects) } let(:project_settings) { table(:project_settings) } let(:namespace) { table(:namespaces).create(name: 'user', path: 'user') } diff --git a/spec/lib/gitlab/background_migration/backfill_push_rules_id_in_projects_spec.rb b/spec/lib/gitlab/background_migration/backfill_push_rules_id_in_projects_spec.rb index f150ed4bd2e..39b49d008d4 100644 --- a/spec/lib/gitlab/background_migration/backfill_push_rules_id_in_projects_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_push_rules_id_in_projects_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillPushRulesIdInProjects, :migration, schema: 2020_03_25_162730 do +RSpec.describe Gitlab::BackgroundMigration::BackfillPushRulesIdInProjects, :migration, schema: 2020_03_25_162730 do let(:push_rules) { table(:push_rules) } let(:projects) { table(:projects) } let(:project_settings) { table(:project_settings) } diff --git a/spec/lib/gitlab/background_migration/backfill_snippet_repositories_spec.rb b/spec/lib/gitlab/background_migration/backfill_snippet_repositories_spec.rb index 27ae60eb278..ec2fd3cc4e0 100644 --- a/spec/lib/gitlab/background_migration/backfill_snippet_repositories_spec.rb +++ b/spec/lib/gitlab/background_migration/backfill_snippet_repositories_spec.rb @@ -2,14 +2,13 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::BackfillSnippetRepositories, :migration, schema: 2020_04_20_094444 do +RSpec.describe Gitlab::BackgroundMigration::BackfillSnippetRepositories, :migration, schema: 2020_04_20_094444 do let(:gitlab_shell) { Gitlab::Shell.new } let(:users) { table(:users) } let(:snippets) { table(:snippets) } let(:snippet_repositories) { table(:snippet_repositories) } let(:user_state) { 'active' } - let(:ghost) { false } let(:user_type) { nil } let(:user_name) { 'Test' } @@ -20,13 +19,20 @@ describe Gitlab::BackgroundMigration::BackfillSnippetRepositories, :migration, s username: 'test', name: user_name, state: user_state, - ghost: ghost, last_activity_on: 1.minute.ago, user_type: user_type, confirmed_at: 1.day.ago) end - let(:migration_bot) { User.migration_bot } + let!(:migration_bot) do + users.create(id: 100, + email: "noreply+gitlab-migration-bot%s@#{Settings.gitlab.host}", + user_type: HasUserType::USER_TYPES[:migration_bot], + name: 'GitLab Migration Bot', + projects_limit: 10, + username: 'bot') + end + let!(:snippet_with_repo) { snippets.create(id: 1, type: 'PersonalSnippet', author_id: user.id, file_name: file_name, content: content) } let!(:snippet_with_empty_repo) { snippets.create(id: 2, type: 'PersonalSnippet', author_id: user.id, file_name: file_name, content: content) } let!(:snippet_without_repo) { snippets.create(id: 3, type: 'PersonalSnippet', author_id: user.id, file_name: file_name, content: content) } @@ -113,8 +119,7 @@ describe Gitlab::BackgroundMigration::BackfillSnippetRepositories, :migration, s end context 'when user is a ghost' do - let(:ghost) { true } - let(:user_type) { 'ghost' } + let(:user_type) { HasUserType::USER_TYPES[:ghost] } it_behaves_like 'migration_bot user commits files' end @@ -255,7 +260,6 @@ describe Gitlab::BackgroundMigration::BackfillSnippetRepositories, :migration, s username: 'test2', name: 'Test2', state: user_state, - ghost: ghost, last_activity_on: 1.minute.ago, user_type: user_type, confirmed_at: 1.day.ago) diff --git a/spec/lib/gitlab/background_migration/cleanup_concurrent_schema_change_spec.rb b/spec/lib/gitlab/background_migration/cleanup_concurrent_schema_change_spec.rb new file mode 100644 index 00000000000..2931b5e6dd3 --- /dev/null +++ b/spec/lib/gitlab/background_migration/cleanup_concurrent_schema_change_spec.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true +require 'spec_helper' + +RSpec.describe Gitlab::BackgroundMigration::CleanupConcurrentSchemaChange do + describe '#perform' do + it 'new column does not exist' do + expect(subject).to receive(:column_exists?).with(:issues, :closed_at_timestamp).and_return(false) + expect(subject).not_to receive(:column_exists?).with(:issues, :closed_at) + expect(subject).not_to receive(:define_model_for) + + expect(subject.perform(:issues, :closed_at, :closed_at_timestamp)).to be_nil + end + + it 'old column does not exist' do + expect(subject).to receive(:column_exists?).with(:issues, :closed_at_timestamp).and_return(true) + expect(subject).to receive(:column_exists?).with(:issues, :closed_at).and_return(false) + expect(subject).not_to receive(:define_model_for) + + expect(subject.perform(:issues, :closed_at, :closed_at_timestamp)).to be_nil + end + + it 'has both old and new columns' do + expect(subject).to receive(:column_exists?).twice.and_return(true) + + expect { subject.perform('issues', :closed_at, :created_at) }.to raise_error(NotImplementedError) + end + end +end diff --git a/spec/lib/gitlab/background_migration/digest_column_spec.rb b/spec/lib/gitlab/background_migration/digest_column_spec.rb deleted file mode 100644 index 0c76ebe9c66..00000000000 --- a/spec/lib/gitlab/background_migration/digest_column_spec.rb +++ /dev/null @@ -1,46 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' - -describe Gitlab::BackgroundMigration::DigestColumn, schema: 20180913142237 do - let(:personal_access_tokens) { table(:personal_access_tokens) } - let(:users) { table(:users) } - - subject { described_class.new } - - describe '#perform' do - context 'token is not yet hashed' do - before do - users.create(id: 1, email: 'user@example.com', projects_limit: 10) - personal_access_tokens.create!(id: 1, user_id: 1, name: 'pat-01', token: 'token-01') - end - - it 'saves token digest' do - expect { subject.perform(PersonalAccessToken, :token, :token_digest, 1, 2) }.to( - change { PersonalAccessToken.find(1).token_digest }.from(nil).to(Gitlab::CryptoHelper.sha256('token-01'))) - end - - it 'erases token' do - expect { subject.perform(PersonalAccessToken, :token, :token_digest, 1, 2) }.to( - change { PersonalAccessToken.find(1).read_attribute(:token) }.from('token-01').to(nil)) - end - end - - context 'token is already hashed' do - before do - users.create(id: 1, email: 'user@example.com', projects_limit: 10) - personal_access_tokens.create!(id: 1, user_id: 1, name: 'pat-01', token_digest: 'token-digest-01') - end - - it 'does not change existing token digest' do - expect { subject.perform(PersonalAccessToken, :token, :token_digest, 1, 2) }.not_to( - change { PersonalAccessToken.find(1).token_digest }) - end - - it 'leaves token empty' do - expect { subject.perform(PersonalAccessToken, :token, :token_digest, 1, 2) }.not_to( - change { PersonalAccessToken.find(1).read_attribute(:token) }.from(nil)) - end - end - end -end diff --git a/spec/lib/gitlab/background_migration/encrypt_columns_spec.rb b/spec/lib/gitlab/background_migration/encrypt_columns_spec.rb deleted file mode 100644 index 6d3ccde7df2..00000000000 --- a/spec/lib/gitlab/background_migration/encrypt_columns_spec.rb +++ /dev/null @@ -1,96 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' - -describe Gitlab::BackgroundMigration::EncryptColumns, schema: 20180910115836 do - let(:model) { Gitlab::BackgroundMigration::Models::EncryptColumns::WebHook } - let(:web_hooks) { table(:web_hooks) } - - let(:plaintext_attrs) do - { - 'encrypted_token' => nil, - 'encrypted_url' => nil, - 'token' => 'secret', - 'url' => 'http://example.com?access_token=secret' - } - end - - let(:encrypted_attrs) do - { - 'encrypted_token' => be_present, - 'encrypted_url' => be_present, - 'token' => nil, - 'url' => nil - } - end - - describe '#perform' do - it 'encrypts columns for the specified range' do - hooks = web_hooks.create([plaintext_attrs] * 5).sort_by(&:id) - - # Encrypt all but the first and last rows - subject.perform(model, [:token, :url], hooks[1].id, hooks[3].id) - - hooks = web_hooks.where(id: hooks.map(&:id)).order(:id) - - aggregate_failures do - expect(hooks[0]).to have_attributes(plaintext_attrs) - expect(hooks[1]).to have_attributes(encrypted_attrs) - expect(hooks[2]).to have_attributes(encrypted_attrs) - expect(hooks[3]).to have_attributes(encrypted_attrs) - expect(hooks[4]).to have_attributes(plaintext_attrs) - end - end - - it 'acquires an exclusive lock for the update' do - relation = double('relation', each: nil) - - expect(model).to receive(:where) { relation } - expect(relation).to receive(:lock) { relation } - - subject.perform(model, [:token, :url], 1, 1) - end - - it 'skips already-encrypted columns' do - values = { - 'encrypted_token' => 'known encrypted token', - 'encrypted_url' => 'known encrypted url', - 'token' => 'token', - 'url' => 'url' - } - - hook = web_hooks.create(values) - - subject.perform(model, [:token, :url], hook.id, hook.id) - - hook.reload - - expect(hook).to have_attributes(values) - end - - it 'reloads the model column information' do - expect(model).to receive(:reset_column_information).and_call_original - expect(model).to receive(:define_attribute_methods).and_call_original - - subject.perform(model, [:token, :url], 1, 1) - end - - it 'fails if a source column is not present' do - columns = model.columns.reject { |c| c.name == 'url' } - allow(model).to receive(:columns) { columns } - - expect do - subject.perform(model, [:token, :url], 1, 1) - end.to raise_error(/source column: url is missing/) - end - - it 'fails if a destination column is not present' do - columns = model.columns.reject { |c| c.name == 'encrypted_url' } - allow(model).to receive(:columns) { columns } - - expect do - subject.perform(model, [:token, :url], 1, 1) - end.to raise_error(/destination column: encrypted_url is missing/) - end - end -end diff --git a/spec/lib/gitlab/background_migration/encrypt_runners_tokens_spec.rb b/spec/lib/gitlab/background_migration/encrypt_runners_tokens_spec.rb deleted file mode 100644 index 89262788d9b..00000000000 --- a/spec/lib/gitlab/background_migration/encrypt_runners_tokens_spec.rb +++ /dev/null @@ -1,79 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' - -describe Gitlab::BackgroundMigration::EncryptRunnersTokens, schema: 20181121111200 do - let(:settings) { table(:application_settings) } - let(:namespaces) { table(:namespaces) } - let(:projects) { table(:projects) } - let(:runners) { table(:ci_runners) } - - context 'when migrating application settings' do - before do - settings.create!(id: 1, runners_registration_token: 'plain-text-token1') - end - - it 'migrates runners registration tokens' do - migrate!(:settings, 1, 1) - - encrypted_token = settings.first.runners_registration_token_encrypted - decrypted_token = ::Gitlab::CryptoHelper.aes256_gcm_decrypt(encrypted_token) - - expect(decrypted_token).to eq 'plain-text-token1' - expect(settings.first.runners_registration_token).to eq 'plain-text-token1' - end - end - - context 'when migrating namespaces' do - before do - namespaces.create!(id: 11, name: 'gitlab', path: 'gitlab-org', runners_token: 'my-token1') - namespaces.create!(id: 12, name: 'gitlab', path: 'gitlab-org', runners_token: 'my-token2') - namespaces.create!(id: 22, name: 'gitlab', path: 'gitlab-org', runners_token: 'my-token3') - end - - it 'migrates runners registration tokens' do - migrate!(:namespace, 11, 22) - - expect(namespaces.all.reload).to all( - have_attributes(runners_token: be_a(String), runners_token_encrypted: be_a(String)) - ) - end - end - - context 'when migrating projects' do - before do - namespaces.create!(id: 11, name: 'gitlab', path: 'gitlab-org') - projects.create!(id: 111, namespace_id: 11, name: 'gitlab', path: 'gitlab-ce', runners_token: 'my-token1') - projects.create!(id: 114, namespace_id: 11, name: 'gitlab', path: 'gitlab-ce', runners_token: 'my-token2') - projects.create!(id: 116, namespace_id: 11, name: 'gitlab', path: 'gitlab-ce', runners_token: 'my-token3') - end - - it 'migrates runners registration tokens' do - migrate!(:project, 111, 116) - - expect(projects.all.reload).to all( - have_attributes(runners_token: be_a(String), runners_token_encrypted: be_a(String)) - ) - end - end - - context 'when migrating runners' do - before do - runners.create!(id: 201, runner_type: 1, token: 'plain-text-token1') - runners.create!(id: 202, runner_type: 1, token: 'plain-text-token2') - runners.create!(id: 203, runner_type: 1, token: 'plain-text-token3') - end - - it 'migrates runners communication tokens' do - migrate!(:runner, 201, 203) - - expect(runners.all.reload).to all( - have_attributes(token: be_a(String), token_encrypted: be_a(String)) - ) - end - end - - def migrate!(model, from, to) - subject.perform(model, from, to) - end -end diff --git a/spec/lib/gitlab/background_migration/fix_cross_project_label_links_spec.rb b/spec/lib/gitlab/background_migration/fix_cross_project_label_links_spec.rb index cc4ce023f04..8e3ace083fc 100644 --- a/spec/lib/gitlab/background_migration/fix_cross_project_label_links_spec.rb +++ b/spec/lib/gitlab/background_migration/fix_cross_project_label_links_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::FixCrossProjectLabelLinks, schema: 20180702120647 do +RSpec.describe Gitlab::BackgroundMigration::FixCrossProjectLabelLinks do let(:namespaces_table) { table(:namespaces) } let(:projects_table) { table(:projects) } let(:issues_table) { table(:issues) } diff --git a/spec/lib/gitlab/background_migration/fix_projects_without_project_feature_spec.rb b/spec/lib/gitlab/background_migration/fix_projects_without_project_feature_spec.rb index 056ddd7adf9..e2175c41513 100644 --- a/spec/lib/gitlab/background_migration/fix_projects_without_project_feature_spec.rb +++ b/spec/lib/gitlab/background_migration/fix_projects_without_project_feature_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::FixProjectsWithoutProjectFeature, schema: 2020_01_27_111840 do +RSpec.describe Gitlab::BackgroundMigration::FixProjectsWithoutProjectFeature, schema: 2020_01_27_111840 do let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:project_features) { table(:project_features) } diff --git a/spec/lib/gitlab/background_migration/fix_projects_without_prometheus_service_spec.rb b/spec/lib/gitlab/background_migration/fix_projects_without_prometheus_service_spec.rb index 3c3e37df200..fe2b206ea74 100644 --- a/spec/lib/gitlab/background_migration/fix_projects_without_prometheus_service_spec.rb +++ b/spec/lib/gitlab/background_migration/fix_projects_without_prometheus_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::FixProjectsWithoutPrometheusService, :migration, schema: 2020_02_20_115023 do +RSpec.describe Gitlab::BackgroundMigration::FixProjectsWithoutPrometheusService, :migration, schema: 2020_02_20_115023 do def service_params_for(project_id, params = {}) { project_id: project_id, diff --git a/spec/lib/gitlab/background_migration/fix_promoted_epics_discussion_ids_spec.rb b/spec/lib/gitlab/background_migration/fix_promoted_epics_discussion_ids_spec.rb index 141a0af6c29..452fc962c7b 100644 --- a/spec/lib/gitlab/background_migration/fix_promoted_epics_discussion_ids_spec.rb +++ b/spec/lib/gitlab/background_migration/fix_promoted_epics_discussion_ids_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::FixPromotedEpicsDiscussionIds, schema: 20190715193142 do +RSpec.describe Gitlab::BackgroundMigration::FixPromotedEpicsDiscussionIds, schema: 20190715193142 do let(:namespaces) { table(:namespaces) } let(:users) { table(:users) } let(:epics) { table(:epics) } diff --git a/spec/lib/gitlab/background_migration/fix_user_namespace_names_spec.rb b/spec/lib/gitlab/background_migration/fix_user_namespace_names_spec.rb index 52760cdd115..7768411828c 100644 --- a/spec/lib/gitlab/background_migration/fix_user_namespace_names_spec.rb +++ b/spec/lib/gitlab/background_migration/fix_user_namespace_names_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::FixUserNamespaceNames, schema: 20190620112608 do +RSpec.describe Gitlab::BackgroundMigration::FixUserNamespaceNames, schema: 20190620112608 do let(:namespaces) { table(:namespaces) } let(:users) { table(:users) } let(:user) { users.create(name: "The user's full name", projects_limit: 10, username: 'not-null', email: '1') } diff --git a/spec/lib/gitlab/background_migration/fix_user_project_route_names_spec.rb b/spec/lib/gitlab/background_migration/fix_user_project_route_names_spec.rb index 0fb7eea2bd7..4c04043ebd0 100644 --- a/spec/lib/gitlab/background_migration/fix_user_project_route_names_spec.rb +++ b/spec/lib/gitlab/background_migration/fix_user_project_route_names_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::FixUserProjectRouteNames, schema: 20190620112608 do +RSpec.describe Gitlab::BackgroundMigration::FixUserProjectRouteNames, schema: 20190620112608 do let(:namespaces) { table(:namespaces) } let(:users) { table(:users) } let(:routes) { table(:routes) } diff --git a/spec/lib/gitlab/background_migration/legacy_upload_mover_spec.rb b/spec/lib/gitlab/background_migration/legacy_upload_mover_spec.rb index 850ef48d44a..bf793e7c537 100644 --- a/spec/lib/gitlab/background_migration/legacy_upload_mover_spec.rb +++ b/spec/lib/gitlab/background_migration/legacy_upload_mover_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' # rubocop: disable RSpec/FactoriesInMigrationSpecs -describe Gitlab::BackgroundMigration::LegacyUploadMover do +RSpec.describe Gitlab::BackgroundMigration::LegacyUploadMover do let(:test_dir) { FileUploader.options['storage_path'] } let(:filename) { 'image.png' } diff --git a/spec/lib/gitlab/background_migration/legacy_uploads_migrator_spec.rb b/spec/lib/gitlab/background_migration/legacy_uploads_migrator_spec.rb index 85187d039c1..66a1787b2cb 100644 --- a/spec/lib/gitlab/background_migration/legacy_uploads_migrator_spec.rb +++ b/spec/lib/gitlab/background_migration/legacy_uploads_migrator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' # rubocop: disable RSpec/FactoriesInMigrationSpecs -describe Gitlab::BackgroundMigration::LegacyUploadsMigrator do +RSpec.describe Gitlab::BackgroundMigration::LegacyUploadsMigrator do let(:test_dir) { FileUploader.options['storage_path'] } let!(:hashed_project) { create(:project) } diff --git a/spec/lib/gitlab/background_migration/link_lfs_objects_projects_spec.rb b/spec/lib/gitlab/background_migration/link_lfs_objects_projects_spec.rb index 5700cac2e0f..dda4f5a3a36 100644 --- a/spec/lib/gitlab/background_migration/link_lfs_objects_projects_spec.rb +++ b/spec/lib/gitlab/background_migration/link_lfs_objects_projects_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::LinkLfsObjectsProjects, :migration, schema: 2020_03_10_075115 do +RSpec.describe Gitlab::BackgroundMigration::LinkLfsObjectsProjects, :migration, schema: 2020_03_10_075115 do let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:fork_networks) { table(:fork_networks) } diff --git a/spec/lib/gitlab/background_migration/mailers/unconfirm_mailer_spec.rb b/spec/lib/gitlab/background_migration/mailers/unconfirm_mailer_spec.rb new file mode 100644 index 00000000000..f430009989b --- /dev/null +++ b/spec/lib/gitlab/background_migration/mailers/unconfirm_mailer_spec.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::BackgroundMigration::Mailers::UnconfirmMailer do + let(:user) { User.new(id: 1111) } + let(:subject) { described_class.unconfirm_notification_email(user) } + + it 'contains abuse report url' do + expect(subject.body.encoded).to include(Rails.application.routes.url_helpers.new_abuse_report_url(user_id: user.id)) + end +end diff --git a/spec/lib/gitlab/background_migration/merge_request_assignees_migration_progress_check_spec.rb b/spec/lib/gitlab/background_migration/merge_request_assignees_migration_progress_check_spec.rb index 9dd97b58014..a3840e3a22e 100644 --- a/spec/lib/gitlab/background_migration/merge_request_assignees_migration_progress_check_spec.rb +++ b/spec/lib/gitlab/background_migration/merge_request_assignees_migration_progress_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MergeRequestAssigneesMigrationProgressCheck do +RSpec.describe Gitlab::BackgroundMigration::MergeRequestAssigneesMigrationProgressCheck do context 'rescheduling' do context 'when there are ongoing and no dead jobs' do it 'reschedules check' do diff --git a/spec/lib/gitlab/background_migration/migrate_build_stage_spec.rb b/spec/lib/gitlab/background_migration/migrate_build_stage_spec.rb index adf358f5320..65d45ec694f 100644 --- a/spec/lib/gitlab/background_migration/migrate_build_stage_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_build_stage_spec.rb @@ -2,7 +2,8 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MigrateBuildStage, schema: 20180212101928 do +RSpec.describe Gitlab::BackgroundMigration::MigrateBuildStage do + let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:pipelines) { table(:ci_pipelines) } let(:stages) { table(:ci_stages) } @@ -22,7 +23,8 @@ describe Gitlab::BackgroundMigration::MigrateBuildStage, schema: 20180212101928 end before do - projects.create!(id: 123, name: 'gitlab', path: 'gitlab-ce') + namespace = namespaces.create!(name: 'gitlab-org', path: 'gitlab-org') + projects.create!(id: 123, name: 'gitlab', path: 'gitlab-ce', namespace_id: namespace.id) pipelines.create!(id: 1, project_id: 123, ref: 'master', sha: 'adf43c3a') jobs.create!(id: 1, commit_id: 1, project_id: 123, @@ -53,7 +55,7 @@ describe Gitlab::BackgroundMigration::MigrateBuildStage, schema: 20180212101928 statuses[:pending]] end - it 'recovers from unique constraint violation only twice', :quarantine do + it 'recovers from unique constraint violation only twice', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/28128' do allow(described_class::Migratable::Stage) .to receive(:find_by).and_return(nil) diff --git a/spec/lib/gitlab/background_migration/migrate_fingerprint_sha256_within_keys_spec.rb b/spec/lib/gitlab/background_migration/migrate_fingerprint_sha256_within_keys_spec.rb index 79a8cd926a7..c58b2d609e9 100644 --- a/spec/lib/gitlab/background_migration/migrate_fingerprint_sha256_within_keys_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_fingerprint_sha256_within_keys_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MigrateFingerprintSha256WithinKeys, schema: 20200106071113 do +RSpec.describe Gitlab::BackgroundMigration::MigrateFingerprintSha256WithinKeys, schema: 20200106071113 do subject(:fingerprint_migrator) { described_class.new } let(:key_table) { table(:keys) } diff --git a/spec/lib/gitlab/background_migration/migrate_issue_trackers_sensitive_data_spec.rb b/spec/lib/gitlab/background_migration/migrate_issue_trackers_sensitive_data_spec.rb index 4411dca3fd9..d53f79c61c1 100644 --- a/spec/lib/gitlab/background_migration/migrate_issue_trackers_sensitive_data_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_issue_trackers_sensitive_data_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::BackgroundMigration::MigrateIssueTrackersSensitiveData, schema: 20200130145430 do +RSpec.describe Gitlab::BackgroundMigration::MigrateIssueTrackersSensitiveData, schema: 20200130145430 do let(:services) { table(:services) } before do diff --git a/spec/lib/gitlab/background_migration/migrate_legacy_artifacts_spec.rb b/spec/lib/gitlab/background_migration/migrate_legacy_artifacts_spec.rb index 5f2a27acd9b..08f2b2a043e 100644 --- a/spec/lib/gitlab/background_migration/migrate_legacy_artifacts_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_legacy_artifacts_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MigrateLegacyArtifacts, schema: 20180816161409 do +RSpec.describe Gitlab::BackgroundMigration::MigrateLegacyArtifacts do let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:pipelines) { table(:ci_pipelines) } diff --git a/spec/lib/gitlab/background_migration/migrate_null_private_profile_to_false_spec.rb b/spec/lib/gitlab/background_migration/migrate_null_private_profile_to_false_spec.rb index ff88d2a5d00..6ff1157cb86 100644 --- a/spec/lib/gitlab/background_migration/migrate_null_private_profile_to_false_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_null_private_profile_to_false_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MigrateNullPrivateProfileToFalse, schema: 20190620105427 do +RSpec.describe Gitlab::BackgroundMigration::MigrateNullPrivateProfileToFalse, schema: 20190620105427 do let(:users) { table(:users) } it 'correctly migrates nil private_profile to false' do diff --git a/spec/lib/gitlab/background_migration/migrate_pages_metadata_spec.rb b/spec/lib/gitlab/background_migration/migrate_pages_metadata_spec.rb index 10a1d4ee1b9..906a6a747c9 100644 --- a/spec/lib/gitlab/background_migration/migrate_pages_metadata_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_pages_metadata_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MigratePagesMetadata, schema: 20190919040324 do +RSpec.describe Gitlab::BackgroundMigration::MigratePagesMetadata, schema: 20190919040324 do let(:projects) { table(:projects) } subject(:migrate_pages_metadata) { described_class.new } diff --git a/spec/lib/gitlab/background_migration/migrate_stage_index_spec.rb b/spec/lib/gitlab/background_migration/migrate_stage_index_spec.rb index 437be125cf0..81874ff7982 100644 --- a/spec/lib/gitlab/background_migration/migrate_stage_index_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_stage_index_spec.rb @@ -2,35 +2,33 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MigrateStageIndex, schema: 20180420080616 do +RSpec.describe Gitlab::BackgroundMigration::MigrateStageIndex do let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:pipelines) { table(:ci_pipelines) } let(:stages) { table(:ci_stages) } let(:jobs) { table(:ci_builds) } + let(:namespace) { namespaces.create(name: 'gitlab-org', path: 'gitlab-org') } + let(:project) { projects.create!(namespace_id: namespace.id, name: 'gitlab', path: 'gitlab') } + let(:pipeline) { pipelines.create!(project_id: project.id, ref: 'master', sha: 'adf43c3a') } + let(:stage1) { stages.create(project_id: project.id, pipeline_id: pipeline.id, name: 'build') } + let(:stage2) { stages.create(project_id: project.id, pipeline_id: pipeline.id, name: 'test') } before do - namespaces.create(id: 10, name: 'gitlab-org', path: 'gitlab-org') - projects.create!(id: 11, namespace_id: 10, name: 'gitlab', path: 'gitlab') - pipelines.create!(id: 12, project_id: 11, ref: 'master', sha: 'adf43c3a') - - stages.create(id: 100, project_id: 11, pipeline_id: 12, name: 'build') - stages.create(id: 101, project_id: 11, pipeline_id: 12, name: 'test') - - jobs.create!(id: 121, commit_id: 12, project_id: 11, - stage_idx: 2, stage_id: 100) - jobs.create!(id: 122, commit_id: 12, project_id: 11, - stage_idx: 2, stage_id: 100) - jobs.create!(id: 123, commit_id: 12, project_id: 11, - stage_idx: 10, stage_id: 100) - jobs.create!(id: 124, commit_id: 12, project_id: 11, - stage_idx: 3, stage_id: 101) + jobs.create!(commit_id: pipeline.id, project_id: project.id, + stage_idx: 2, stage_id: stage1.id) + jobs.create!(commit_id: pipeline.id, project_id: project.id, + stage_idx: 2, stage_id: stage1.id) + jobs.create!(commit_id: pipeline.id, project_id: project.id, + stage_idx: 10, stage_id: stage1.id) + jobs.create!(commit_id: pipeline.id, project_id: project.id, + stage_idx: 3, stage_id: stage2.id) end it 'correctly migrates stages indices' do expect(stages.all.pluck(:position)).to all(be_nil) - described_class.new.perform(100, 101) + described_class.new.perform(stage1.id, stage2.id) expect(stages.all.order(:id).pluck(:position)).to eq [2, 3] end diff --git a/spec/lib/gitlab/background_migration/migrate_users_bio_to_user_details_spec.rb b/spec/lib/gitlab/background_migration/migrate_users_bio_to_user_details_spec.rb index 8603eb73bd5..db3cbe7ccdc 100644 --- a/spec/lib/gitlab/background_migration/migrate_users_bio_to_user_details_spec.rb +++ b/spec/lib/gitlab/background_migration/migrate_users_bio_to_user_details_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::MigrateUsersBioToUserDetails, :migration, schema: 20200323074147 do +RSpec.describe Gitlab::BackgroundMigration::MigrateUsersBioToUserDetails, :migration, schema: 20200323074147 do let(:users) { table(:users) } let(:user_details) do diff --git a/spec/lib/gitlab/background_migration/populate_canonical_emails_spec.rb b/spec/lib/gitlab/background_migration/populate_canonical_emails_spec.rb index 37ddb8b569d..ee0024e8526 100644 --- a/spec/lib/gitlab/background_migration/populate_canonical_emails_spec.rb +++ b/spec/lib/gitlab/background_migration/populate_canonical_emails_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::PopulateCanonicalEmails, :migration, schema: 20200312053852 do +RSpec.describe Gitlab::BackgroundMigration::PopulateCanonicalEmails, :migration, schema: 20200312053852 do let(:migration) { described_class.new } let_it_be(:users_table) { table(:users) } diff --git a/spec/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table_spec.rb b/spec/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table_spec.rb index d445858b8e8..73faca54b52 100644 --- a/spec/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table_spec.rb +++ b/spec/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::PopulateClusterKubernetesNamespaceTable, schema: 20181022173835 do +RSpec.describe Gitlab::BackgroundMigration::PopulateClusterKubernetesNamespaceTable do include MigrationHelpers::ClusterHelpers let(:migration) { described_class.new } diff --git a/spec/lib/gitlab/background_migration/populate_merge_request_assignees_table_spec.rb b/spec/lib/gitlab/background_migration/populate_merge_request_assignees_table_spec.rb index e65b3549de0..1e5773ee16b 100644 --- a/spec/lib/gitlab/background_migration/populate_merge_request_assignees_table_spec.rb +++ b/spec/lib/gitlab/background_migration/populate_merge_request_assignees_table_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::PopulateMergeRequestAssigneesTable, schema: 20190315191339 do +RSpec.describe Gitlab::BackgroundMigration::PopulateMergeRequestAssigneesTable, schema: 20190315191339 do let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:users) { table(:users) } diff --git a/spec/lib/gitlab/background_migration/populate_project_snippet_statistics_spec.rb b/spec/lib/gitlab/background_migration/populate_project_snippet_statistics_spec.rb new file mode 100644 index 00000000000..897f5e81372 --- /dev/null +++ b/spec/lib/gitlab/background_migration/populate_project_snippet_statistics_spec.rb @@ -0,0 +1,224 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::BackgroundMigration::PopulateProjectSnippetStatistics do + let(:file_name) { 'file_name.rb' } + let(:content) { 'content' } + let(:snippets) { table(:snippets) } + let(:snippet_repositories) { table(:snippet_repositories) } + let(:users) { table(:users) } + let(:namespaces) { table(:namespaces) } + let(:snippet_statistics) { table(:snippet_statistics) } + let(:project_statistics) { table(:project_statistics) } + let(:projects) { table(:projects) } + let(:namespace_statistics) { table(:namespace_root_storage_statistics) } + let(:routes) { table(:routes) } + let(:repo_size) { 123456 } + let(:expected_repo_size) { repo_size.megabytes } + + let(:user) { users.create!(id: 1, email: 'test@example.com', projects_limit: 100, username: 'test') } + let(:group) { namespaces.create!(id: 10, type: 'Group', name: 'group1', path: 'group1') } + let(:user_namespace) { namespaces.create!(id: 20, name: 'user', path: 'user', owner_id: user.id) } + + let(:project1) { create_project(1, 'test', group) } + let(:project2) { create_project(2, 'test1', user_namespace) } + let(:project3) { create_project(3, 'test2', group) } + + let!(:project_stats1) { create_project_statistics(project1) } + let!(:project_stats2) { create_project_statistics(project2) } + let!(:project_stats3) { create_project_statistics(project3) } + + let(:ids) { snippets.pluck(:id) } + let(:migration) { described_class.new } + + subject do + migration.perform(ids) + + project_stats1.reload if project_stats1.persisted? + project_stats2.reload if project_stats2.persisted? + project_stats3.reload if project_stats3.persisted? + end + + before do + allow_any_instance_of(Repository).to receive(:size).and_return(repo_size) + end + + after do + snippets.all.each { |s| raw_repository(s).remove } + end + + context 'with existing user and group snippets' do + let!(:snippet1) { create_snippet(1, project1) } + let!(:snippet2) { create_snippet(2, project1) } + let!(:snippet3) { create_snippet(3, project2) } + let!(:snippet4) { create_snippet(4, project2) } + let!(:snippet5) { create_snippet(5, project3) } + + before do + create_snippet_statistics(2, 0) + create_snippet_statistics(4, 123) + end + + it 'creates/updates all snippet_statistics' do + expect(snippet_statistics.count).to eq 2 + + subject + + expect(snippet_statistics.count).to eq 5 + + snippet_statistics.all.each do |stat| + expect(stat.repository_size).to eq expected_repo_size + end + end + + it 'updates associated snippet project statistics' do + expect(project_stats1.snippets_size).to be_nil + expect(project_stats2.snippets_size).to be_nil + + subject + + snippets_size = snippet_statistics.where(snippet_id: [snippet1.id, snippet2.id]).sum(:repository_size) + expect(project_stats1.snippets_size).to eq snippets_size + + snippets_size = snippet_statistics.where(snippet_id: [snippet3.id, snippet4.id]).sum(:repository_size) + expect(project_stats2.snippets_size).to eq snippets_size + + snippets_size = snippet_statistics.where(snippet_id: snippet5.id).sum(:repository_size) + expect(project_stats3.snippets_size).to eq snippets_size + end + + it 'forces the project statistics refresh' do + expect(migration).to receive(:update_project_statistics).exactly(3).times + + subject + end + + it 'creates/updates the associated namespace statistics' do + expect(migration).to receive(:update_namespace_statistics).twice.and_call_original + + subject + + expect(namespace_statistics.find_by(namespace_id: group.id).snippets_size).to eq project_stats1.snippets_size + project_stats3.snippets_size + expect(namespace_statistics.find_by(namespace_id: user_namespace.id).snippets_size).to eq project_stats2.snippets_size + end + + context 'when the project statistics does not exists' do + it 'does not raise any error' do + project_stats3.delete + + subject + + expect(namespace_statistics.find_by(namespace_id: group.id).snippets_size).to eq project_stats1.snippets_size + expect(namespace_statistics.find_by(namespace_id: user_namespace.id).snippets_size).to eq project_stats2.snippets_size + end + end + + context 'when an error is raised when updating a project statistics' do + it 'logs the error and continue execution' do + expect(migration).to receive(:update_project_statistics).with(Project.find(project1.id)).and_raise('Error') + expect(migration).to receive(:update_project_statistics).with(Project.find(project2.id)).and_call_original + expect(migration).to receive(:update_project_statistics).with(Project.find(project3.id)).and_call_original + + expect_next_instance_of(Gitlab::BackgroundMigration::Logger) do |instance| + expect(instance).to receive(:error).with(message: /Error updating statistics for project #{project1.id}/).once + end + + subject + + expect(project_stats2.snippets_size).not_to be_nil + expect(project_stats3.snippets_size).not_to be_nil + end + end + + context 'when an error is raised when updating a namespace statistics' do + it 'logs the error and continue execution' do + expect(migration).to receive(:update_namespace_statistics).with(Group.find(group.id)).and_raise('Error') + expect(migration).to receive(:update_namespace_statistics).with(Namespace.find(user_namespace.id)).and_call_original + + expect_next_instance_of(Gitlab::BackgroundMigration::Logger) do |instance| + expect(instance).to receive(:error).with(message: /Error updating statistics for namespace/).once + end + + subject + + expect(namespace_statistics.find_by(namespace_id: user_namespace.id).snippets_size).to eq project_stats2.snippets_size + end + end + end + + context 'when project snippet is in a subgroup' do + let(:subgroup) { namespaces.create!(id: 30, type: 'Group', name: 'subgroup', path: 'subgroup', parent_id: group.id) } + let(:project1) { create_project(1, 'test', subgroup, "#{group.path}/#{subgroup.path}/test") } + let!(:snippet1) { create_snippet(1, project1) } + + it 'updates the root namespace statistics' do + subject + + expect(snippet_statistics.count).to eq 1 + expect(project_stats1.snippets_size).to eq snippet_statistics.first.repository_size + expect(namespace_statistics.find_by(namespace_id: subgroup.id)).to be_nil + expect(namespace_statistics.find_by(namespace_id: group.id).snippets_size).to eq project_stats1.snippets_size + end + end + + context 'when a snippet repository is empty' do + let!(:snippet1) { create_snippet(1, project1, with_repo: false) } + let!(:snippet2) { create_snippet(2, project1) } + + it 'logs error and continues execution' do + expect_next_instance_of(Gitlab::BackgroundMigration::Logger) do |instance| + expect(instance).to receive(:error).with(message: /Invalid snippet repository/).once + end + + subject + + expect(snippet_statistics.find_by(snippet_id: snippet1.id)).to be_nil + expect(project_stats1.snippets_size).to eq snippet_statistics.find(snippet2.id).repository_size + end + end + + def create_snippet(id, project, with_repo: true) + snippets.create!(id: id, type: 'ProjectSnippet', project_id: project.id, author_id: user.id, file_name: file_name, content: content).tap do |snippet| + if with_repo + allow(snippet).to receive(:disk_path).and_return(disk_path(snippet)) + + TestEnv.copy_repo(snippet, + bare_repo: TestEnv.factory_repo_path_bare, + refs: TestEnv::BRANCH_SHA) + + raw_repository(snippet).create_repository + end + end + end + + def create_project(id, name, namespace, path = nil) + projects.create!(id: id, name: name, path: name.downcase.gsub(/\s/, '_'), namespace_id: namespace.id).tap do |project| + path ||= "#{namespace.path}/#{project.path}" + routes.create!(id: id, source_type: 'Project', source_id: project.id, path: path) + end + end + + def create_snippet_statistics(snippet_id, repository_size = 0) + snippet_statistics.create!(snippet_id: snippet_id, repository_size: repository_size) + end + + def create_project_statistics(project, snippets_size = nil) + project_statistics.create!(id: project.id, project_id: project.id, namespace_id: project.namespace_id, snippets_size: snippets_size) + end + + def raw_repository(snippet) + Gitlab::Git::Repository.new('default', + "#{disk_path(snippet)}.git", + Gitlab::GlRepository::SNIPPET.identifier_for_container(snippet), + "@snippets/#{snippet.id}") + end + + def hashed_repository(snippet) + Storage::Hashed.new(snippet, prefix: '@snippets') + end + + def disk_path(snippet) + hashed_repository(snippet).disk_path + end +end diff --git a/spec/lib/gitlab/background_migration/populate_untracked_uploads_dependencies/untracked_file_spec.rb b/spec/lib/gitlab/background_migration/populate_untracked_uploads_dependencies/untracked_file_spec.rb index 0250ebd7759..6a25e8e2784 100644 --- a/spec/lib/gitlab/background_migration/populate_untracked_uploads_dependencies/untracked_file_spec.rb +++ b/spec/lib/gitlab/background_migration/populate_untracked_uploads_dependencies/untracked_file_spec.rb @@ -2,8 +2,7 @@ require 'spec_helper' -# Rollback DB to 10.5 (later than this was originally written for) because it still needs to work. -describe Gitlab::BackgroundMigration::PopulateUntrackedUploadsDependencies::UntrackedFile, schema: 20180208183958 do +RSpec.describe Gitlab::BackgroundMigration::PopulateUntrackedUploadsDependencies::UntrackedFile do include MigrationsHelpers::TrackUntrackedUploadsHelpers let!(:appearances) { table(:appearances) } diff --git a/spec/lib/gitlab/background_migration/populate_untracked_uploads_spec.rb b/spec/lib/gitlab/background_migration/populate_untracked_uploads_spec.rb index 44cec112bfd..787cc54e79a 100644 --- a/spec/lib/gitlab/background_migration/populate_untracked_uploads_spec.rb +++ b/spec/lib/gitlab/background_migration/populate_untracked_uploads_spec.rb @@ -2,8 +2,7 @@ require 'spec_helper' -# Rollback DB to 10.5 (later than this was originally written for) because it still needs to work. -describe Gitlab::BackgroundMigration::PopulateUntrackedUploads, schema: 20180208183958 do +RSpec.describe Gitlab::BackgroundMigration::PopulateUntrackedUploads do include MigrationsHelpers::TrackUntrackedUploadsHelpers subject { described_class.new } diff --git a/spec/lib/gitlab/background_migration/populate_user_highest_roles_table_spec.rb b/spec/lib/gitlab/background_migration/populate_user_highest_roles_table_spec.rb index be661d5b83e..f0b0f77280e 100644 --- a/spec/lib/gitlab/background_migration/populate_user_highest_roles_table_spec.rb +++ b/spec/lib/gitlab/background_migration/populate_user_highest_roles_table_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::PopulateUserHighestRolesTable, schema: 20200311130802 do +RSpec.describe Gitlab::BackgroundMigration::PopulateUserHighestRolesTable, schema: 20200311130802 do let(:members) { table(:members) } let(:users) { table(:users) } let(:user_highest_roles) { table(:user_highest_roles) } diff --git a/spec/lib/gitlab/background_migration/prepare_untracked_uploads_spec.rb b/spec/lib/gitlab/background_migration/prepare_untracked_uploads_spec.rb index 9daf35d0311..9b01407dc8b 100644 --- a/spec/lib/gitlab/background_migration/prepare_untracked_uploads_spec.rb +++ b/spec/lib/gitlab/background_migration/prepare_untracked_uploads_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' # Rollback DB to 10.5 (later than this was originally written for) because it still needs to work. -describe Gitlab::BackgroundMigration::PrepareUntrackedUploads, schema: 20180208183958 do +RSpec.describe Gitlab::BackgroundMigration::PrepareUntrackedUploads do include MigrationsHelpers::TrackUntrackedUploadsHelpers let!(:untracked_files_for_uploads) { table(:untracked_files_for_uploads) } diff --git a/spec/lib/gitlab/background_migration/recalculate_project_authorizations_spec.rb b/spec/lib/gitlab/background_migration/recalculate_project_authorizations_spec.rb index ba87312e2bf..33e1f31d1f1 100644 --- a/spec/lib/gitlab/background_migration/recalculate_project_authorizations_spec.rb +++ b/spec/lib/gitlab/background_migration/recalculate_project_authorizations_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::RecalculateProjectAuthorizations, schema: 20200204113223 do +RSpec.describe Gitlab::BackgroundMigration::RecalculateProjectAuthorizations, schema: 20200204113223 do let(:users_table) { table(:users) } let(:namespaces_table) { table(:namespaces) } let(:projects_table) { table(:projects) } diff --git a/spec/lib/gitlab/background_migration/recalculate_project_authorizations_with_min_max_user_id_spec.rb b/spec/lib/gitlab/background_migration/recalculate_project_authorizations_with_min_max_user_id_spec.rb index edb46efad7c..c1ba1607b89 100644 --- a/spec/lib/gitlab/background_migration/recalculate_project_authorizations_with_min_max_user_id_spec.rb +++ b/spec/lib/gitlab/background_migration/recalculate_project_authorizations_with_min_max_user_id_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::RecalculateProjectAuthorizationsWithMinMaxUserId, schema: 20200204113224 do +RSpec.describe Gitlab::BackgroundMigration::RecalculateProjectAuthorizationsWithMinMaxUserId, schema: 20200204113224 do let(:users_table) { table(:users) } let(:min) { 1 } let(:max) { 5 } diff --git a/spec/lib/gitlab/background_migration/remove_restricted_todos_spec.rb b/spec/lib/gitlab/background_migration/remove_restricted_todos_spec.rb index 3de24f577ab..7019d5d4212 100644 --- a/spec/lib/gitlab/background_migration/remove_restricted_todos_spec.rb +++ b/spec/lib/gitlab/background_migration/remove_restricted_todos_spec.rb @@ -2,7 +2,8 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::RemoveRestrictedTodos, schema: 20180704204006 do +RSpec.describe Gitlab::BackgroundMigration::RemoveRestrictedTodos do + let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:users) { table(:users) } let(:todos) { table(:todos) } @@ -18,8 +19,9 @@ describe Gitlab::BackgroundMigration::RemoveRestrictedTodos, schema: 20180704204 users.create(id: 2, email: 'reporter@example.com', projects_limit: 10) users.create(id: 3, email: 'guest@example.com', projects_limit: 10) - projects.create!(id: 1, name: 'project-1', path: 'project-1', visibility_level: 0, namespace_id: 1) - projects.create!(id: 2, name: 'project-2', path: 'project-2', visibility_level: 0, namespace_id: 1) + namespace = namespaces.create(name: 'gitlab-org', path: 'gitlab-org') + projects.create!(id: 1, name: 'project-1', path: 'project-1', visibility_level: 0, namespace_id: namespace.id) + projects.create!(id: 2, name: 'project-2', path: 'project-2', visibility_level: 0, namespace_id: namespace.id) issues.create(id: 1, project_id: 1) issues.create(id: 2, project_id: 2) @@ -92,7 +94,7 @@ describe Gitlab::BackgroundMigration::RemoveRestrictedTodos, schema: 20180704204 context 'when issues are restricted to project members' do before do - project_features.create(issues_access_level: 10, project_id: 2) + project_features.create(issues_access_level: 10, pages_access_level: 10, project_id: 2) end it 'removes non members issue todos' do @@ -102,7 +104,7 @@ describe Gitlab::BackgroundMigration::RemoveRestrictedTodos, schema: 20180704204 context 'when merge requests are restricted to project members' do before do - project_features.create(merge_requests_access_level: 10, project_id: 2) + project_features.create(merge_requests_access_level: 10, pages_access_level: 10, project_id: 2) end it 'removes non members issue todos' do @@ -112,7 +114,7 @@ describe Gitlab::BackgroundMigration::RemoveRestrictedTodos, schema: 20180704204 context 'when repository and merge requests are restricted to project members' do before do - project_features.create(repository_access_level: 10, merge_requests_access_level: 10, project_id: 2) + project_features.create(repository_access_level: 10, merge_requests_access_level: 10, pages_access_level: 10, project_id: 2) end it 'removes non members commit and merge requests todos' do diff --git a/spec/lib/gitlab/background_migration/reset_merge_status_spec.rb b/spec/lib/gitlab/background_migration/reset_merge_status_spec.rb index e057aea6bb3..43fc0fb3691 100644 --- a/spec/lib/gitlab/background_migration/reset_merge_status_spec.rb +++ b/spec/lib/gitlab/background_migration/reset_merge_status_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::ResetMergeStatus do +RSpec.describe Gitlab::BackgroundMigration::ResetMergeStatus do let(:namespaces) { table(:namespaces) } let(:projects) { table(:projects) } let(:namespace) { namespaces.create(name: 'gitlab', path: 'gitlab-org') } diff --git a/spec/lib/gitlab/background_migration/schedule_calculate_wiki_sizes_spec.rb b/spec/lib/gitlab/background_migration/schedule_calculate_wiki_sizes_spec.rb deleted file mode 100644 index 387e3343ede..00000000000 --- a/spec/lib/gitlab/background_migration/schedule_calculate_wiki_sizes_spec.rb +++ /dev/null @@ -1,64 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' -require Rails.root.join('db', 'post_migrate', '20190527194900_schedule_calculate_wiki_sizes.rb') - -describe ScheduleCalculateWikiSizes do - let(:migration_class) { Gitlab::BackgroundMigration::CalculateWikiSizes } - let(:migration_name) { migration_class.to_s.demodulize } - - let(:namespaces) { table(:namespaces) } - let(:projects) { table(:projects) } - let(:project_statistics) { table(:project_statistics) } - - context 'when missing wiki sizes exist' do - before do - namespaces.create!(id: 1, name: 'wiki-migration', path: 'wiki-migration') - projects.create!(id: 1, name: 'wiki-project-1', path: 'wiki-project-1', namespace_id: 1) - projects.create!(id: 2, name: 'wiki-project-2', path: 'wiki-project-2', namespace_id: 1) - projects.create!(id: 3, name: 'wiki-project-3', path: 'wiki-project-3', namespace_id: 1) - project_statistics.create!(id: 1, project_id: 1, namespace_id: 1, wiki_size: 1000) - project_statistics.create!(id: 2, project_id: 2, namespace_id: 1, wiki_size: nil) - project_statistics.create!(id: 3, project_id: 3, namespace_id: 1, wiki_size: nil) - end - - it 'schedules a background migration' do - Sidekiq::Testing.fake! do - Timecop.freeze do - migrate! - - expect(migration_name).to be_scheduled_delayed_migration(5.minutes, 2, 3) - expect(BackgroundMigrationWorker.jobs.size).to eq 1 - end - end - end - - it 'calculates missing wiki sizes', :sidekiq_might_not_need_inline do - expect(project_statistics.find_by(id: 2).wiki_size).to be_nil - expect(project_statistics.find_by(id: 3).wiki_size).to be_nil - - migrate! - - expect(project_statistics.find_by(id: 2).wiki_size).not_to be_nil - expect(project_statistics.find_by(id: 3).wiki_size).not_to be_nil - end - end - - context 'when missing wiki sizes do not exist' do - before do - namespaces.create!(id: 1, name: 'wiki-migration', path: 'wiki-migration') - projects.create!(id: 1, name: 'wiki-project-1', path: 'wiki-project-1', namespace_id: 1) - project_statistics.create!(id: 1, project_id: 1, namespace_id: 1, wiki_size: 1000) - end - - it 'does not schedule a background migration' do - Sidekiq::Testing.fake! do - Timecop.freeze do - migrate! - - expect(BackgroundMigrationWorker.jobs.size).to eq 0 - end - end - end - end -end diff --git a/spec/lib/gitlab/background_migration/set_confidential_note_events_on_services_spec.rb b/spec/lib/gitlab/background_migration/set_confidential_note_events_on_services_spec.rb index 5ce4a322e51..364edf3ed2a 100644 --- a/spec/lib/gitlab/background_migration/set_confidential_note_events_on_services_spec.rb +++ b/spec/lib/gitlab/background_migration/set_confidential_note_events_on_services_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::SetConfidentialNoteEventsOnServices, schema: 20180122154930 do +RSpec.describe Gitlab::BackgroundMigration::SetConfidentialNoteEventsOnServices do let(:services) { table(:services) } describe '#perform' do diff --git a/spec/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks_spec.rb b/spec/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks_spec.rb index 08f1f543f5d..28b06ac3ba3 100644 --- a/spec/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks_spec.rb +++ b/spec/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::SetConfidentialNoteEventsOnWebhooks, schema: 20180104131052 do +RSpec.describe Gitlab::BackgroundMigration::SetConfidentialNoteEventsOnWebhooks do let(:web_hooks) { table(:web_hooks) } describe '#perform' do diff --git a/spec/lib/gitlab/background_migration/update_existing_subgroup_to_match_visibility_level_of_parent_spec.rb b/spec/lib/gitlab/background_migration/update_existing_subgroup_to_match_visibility_level_of_parent_spec.rb index 70397ae1e30..6c0a1d3a5b0 100644 --- a/spec/lib/gitlab/background_migration/update_existing_subgroup_to_match_visibility_level_of_parent_spec.rb +++ b/spec/lib/gitlab/background_migration/update_existing_subgroup_to_match_visibility_level_of_parent_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration::UpdateExistingSubgroupToMatchVisibilityLevelOfParent, schema: 2020_01_10_121314 do +RSpec.describe Gitlab::BackgroundMigration::UpdateExistingSubgroupToMatchVisibilityLevelOfParent, schema: 2020_01_10_121314 do include MigrationHelpers::NamespacesHelpers context 'private visibility level' do diff --git a/spec/lib/gitlab/background_migration/user_mentions/create_resource_user_mention_spec.rb b/spec/lib/gitlab/background_migration/user_mentions/create_resource_user_mention_spec.rb index d4f52a11ce7..08a4bbe38ac 100644 --- a/spec/lib/gitlab/background_migration/user_mentions/create_resource_user_mention_spec.rb +++ b/spec/lib/gitlab/background_migration/user_mentions/create_resource_user_mention_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' require './db/post_migrate/20200128134110_migrate_commit_notes_mentions_to_db' require './db/post_migrate/20200211155539_migrate_merge_request_mentions_to_db' -describe Gitlab::BackgroundMigration::UserMentions::CreateResourceUserMention, schema: 20200211155539 do +RSpec.describe Gitlab::BackgroundMigration::UserMentions::CreateResourceUserMention, schema: 20200211155539 do include MigrationsHelpers context 'when migrating data' do diff --git a/spec/lib/gitlab/background_migration/wrongfully_confirmed_email_unconfirmer_spec.rb b/spec/lib/gitlab/background_migration/wrongfully_confirmed_email_unconfirmer_spec.rb new file mode 100644 index 00000000000..c9928edb8e8 --- /dev/null +++ b/spec/lib/gitlab/background_migration/wrongfully_confirmed_email_unconfirmer_spec.rb @@ -0,0 +1,123 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::BackgroundMigration::WrongfullyConfirmedEmailUnconfirmer, schema: 20200615111857 do + let(:users) { table(:users) } + let(:emails) { table(:emails) } + let(:confirmed_at_2_days_ago) { 2.days.ago } + let(:confirmed_at_3_days_ago) { 3.days.ago } + let(:one_year_ago) { 1.year.ago } + + let!(:user_needs_migration_1) { users.create!(name: 'user1', email: 'test1@test.com', state: 'active', projects_limit: 1, confirmed_at: confirmed_at_2_days_ago, confirmation_sent_at: one_year_ago) } + let!(:user_needs_migration_2) { users.create!(name: 'user2', email: 'test2@test.com', unconfirmed_email: 'unconfirmed@test.com', state: 'active', projects_limit: 1, confirmed_at: confirmed_at_3_days_ago, confirmation_sent_at: one_year_ago) } + let!(:user_does_not_need_migration) { users.create!(name: 'user3', email: 'test3@test.com', state: 'active', projects_limit: 1) } + let!(:inactive_user) { users.create!(name: 'user4', email: 'test4@test.com', state: 'blocked', projects_limit: 1, confirmed_at: confirmed_at_3_days_ago, confirmation_sent_at: one_year_ago) } + let!(:alert_bot_user) { users.create!(name: 'user5', email: 'test5@test.com', state: 'active', user_type: 2, projects_limit: 1, confirmed_at: confirmed_at_3_days_ago, confirmation_sent_at: one_year_ago) } + + let!(:bad_email_1) { emails.create!(user_id: user_needs_migration_1.id, email: 'other1@test.com', confirmed_at: confirmed_at_2_days_ago, confirmation_sent_at: one_year_ago) } + let!(:bad_email_2) { emails.create!(user_id: user_needs_migration_2.id, email: 'other2@test.com', confirmed_at: confirmed_at_3_days_ago, confirmation_sent_at: one_year_ago) } + let!(:bad_email_3_inactive_user) { emails.create!(user_id: inactive_user.id, email: 'other-inactive@test.com', confirmed_at: confirmed_at_3_days_ago, confirmation_sent_at: one_year_ago) } + let!(:bad_email_4_bot_user) { emails.create!(user_id: alert_bot_user.id, email: 'other-bot@test.com', confirmed_at: confirmed_at_3_days_ago, confirmation_sent_at: one_year_ago) } + + let!(:good_email_1) { emails.create!(user_id: user_needs_migration_2.id, email: 'other3@test.com', confirmed_at: confirmed_at_2_days_ago, confirmation_sent_at: one_year_ago) } + let!(:good_email_2) { emails.create!(user_id: user_needs_migration_2.id, email: 'other4@test.com', confirmed_at: nil) } + let!(:good_email_3) { emails.create!(user_id: user_does_not_need_migration.id, email: 'other5@test.com', confirmed_at: confirmed_at_2_days_ago, confirmation_sent_at: one_year_ago) } + + subject do + email_ids = [bad_email_1, bad_email_2, good_email_1, good_email_2, good_email_3].map(&:id) + + described_class.new.perform(email_ids.min, email_ids.max) + end + + it 'does not change irrelevant email records' do + subject + + expect(good_email_1.reload.confirmed_at).to be_within(1.second).of(confirmed_at_2_days_ago) + expect(good_email_2.reload.confirmed_at).to be_nil + expect(good_email_3.reload.confirmed_at).to be_within(1.second).of(confirmed_at_2_days_ago) + + expect(bad_email_3_inactive_user.reload.confirmed_at).to be_within(1.second).of(confirmed_at_3_days_ago) + expect(bad_email_4_bot_user.reload.confirmed_at).to be_within(1.second).of(confirmed_at_3_days_ago) + + expect(good_email_1.reload.confirmation_sent_at).to be_within(1.second).of(one_year_ago) + expect(good_email_2.reload.confirmation_sent_at).to be_nil + expect(good_email_3.reload.confirmation_sent_at).to be_within(1.second).of(one_year_ago) + + expect(bad_email_3_inactive_user.reload.confirmation_sent_at).to be_within(1.second).of(one_year_ago) + expect(bad_email_4_bot_user.reload.confirmation_sent_at).to be_within(1.second).of(one_year_ago) + end + + it 'clears the `unconfirmed_email` field' do + subject + + user_needs_migration_2.reload + expect(user_needs_migration_2.unconfirmed_email).to be_nil + end + + it 'does not change irrelevant user records' do + subject + + expect(user_does_not_need_migration.reload.confirmed_at).to be_nil + expect(inactive_user.reload.confirmed_at).to be_within(1.second).of(confirmed_at_3_days_ago) + expect(alert_bot_user.reload.confirmed_at).to be_within(1.second).of(confirmed_at_3_days_ago) + + expect(user_does_not_need_migration.reload.confirmation_sent_at).to be_nil + expect(inactive_user.reload.confirmation_sent_at).to be_within(1.second).of(one_year_ago) + expect(alert_bot_user.reload.confirmation_sent_at).to be_within(1.second).of(one_year_ago) + end + + it 'updates confirmation_sent_at column' do + subject + + expect(user_needs_migration_1.reload.confirmation_sent_at).to be_within(1.minute).of(Time.now) + expect(user_needs_migration_2.reload.confirmation_sent_at).to be_within(1.minute).of(Time.now) + + expect(bad_email_1.reload.confirmation_sent_at).to be_within(1.minute).of(Time.now) + expect(bad_email_2.reload.confirmation_sent_at).to be_within(1.minute).of(Time.now) + end + + it 'unconfirms bad email records' do + subject + + expect(bad_email_1.reload.confirmed_at).to be_nil + expect(bad_email_2.reload.confirmed_at).to be_nil + + expect(bad_email_1.reload.confirmation_token).not_to be_nil + expect(bad_email_2.reload.confirmation_token).not_to be_nil + end + + it 'unconfirms user records' do + subject + + expect(user_needs_migration_1.reload.confirmed_at).to be_nil + expect(user_needs_migration_2.reload.confirmed_at).to be_nil + + expect(user_needs_migration_1.reload.confirmation_token).not_to be_nil + expect(user_needs_migration_2.reload.confirmation_token).not_to be_nil + end + + context 'enqueued jobs' do + let(:user_1) { User.find(user_needs_migration_1.id) } + let(:user_2) { User.find(user_needs_migration_2.id) } + + let(:email_1) { Email.find(bad_email_1.id) } + let(:email_2) { Email.find(bad_email_2.id) } + + it 'enqueues the email confirmation and the unconfirm notification mailer jobs' do + allow(DeviseMailer).to receive(:confirmation_instructions).and_call_original + allow(Gitlab::BackgroundMigration::Mailers::UnconfirmMailer).to receive(:unconfirm_notification_email).and_call_original + + subject + + expect(DeviseMailer).to have_received(:confirmation_instructions).with(email_1, email_1.confirmation_token) + expect(DeviseMailer).to have_received(:confirmation_instructions).with(email_2, email_2.confirmation_token) + + expect(Gitlab::BackgroundMigration::Mailers::UnconfirmMailer).to have_received(:unconfirm_notification_email).with(user_1) + expect(DeviseMailer).to have_received(:confirmation_instructions).with(user_1, user_1.confirmation_token) + + expect(Gitlab::BackgroundMigration::Mailers::UnconfirmMailer).to have_received(:unconfirm_notification_email).with(user_2) + expect(DeviseMailer).to have_received(:confirmation_instructions).with(user_2, user_2.confirmation_token) + end + end +end diff --git a/spec/lib/gitlab/background_migration_spec.rb b/spec/lib/gitlab/background_migration_spec.rb index 71959f54b38..b110fa484ff 100644 --- a/spec/lib/gitlab/background_migration_spec.rb +++ b/spec/lib/gitlab/background_migration_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BackgroundMigration do +RSpec.describe Gitlab::BackgroundMigration do describe '.queue' do it 'returns background migration worker queue' do expect(described_class.queue) @@ -47,6 +47,25 @@ describe Gitlab::BackgroundMigration do described_class.steal('Bar') end + + context 'when a custom predicate is given' do + it 'steals jobs that match the predicate' do + expect(queue[0]).to receive(:delete).and_return(true) + + expect(described_class).to receive(:perform) + .with('Foo', [10, 20]) + + described_class.steal('Foo') { |(arg1, arg2)| arg1 == 10 && arg2 == 20 } + end + + it 'does not steal jobs that do not match the predicate' do + expect(described_class).not_to receive(:perform) + + expect(queue[0]).not_to receive(:delete) + + described_class.steal('Foo') { |(arg1, _)| arg1 == 5 } + end + end end context 'when one of the jobs raises an error' do diff --git a/spec/lib/gitlab/backtrace_cleaner_spec.rb b/spec/lib/gitlab/backtrace_cleaner_spec.rb index f3aded9faad..51d99bf5f74 100644 --- a/spec/lib/gitlab/backtrace_cleaner_spec.rb +++ b/spec/lib/gitlab/backtrace_cleaner_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BacktraceCleaner do +RSpec.describe Gitlab::BacktraceCleaner do describe '.clean_backtrace' do it 'uses the Rails backtrace cleaner' do backtrace = [] diff --git a/spec/lib/gitlab/badge/coverage/metadata_spec.rb b/spec/lib/gitlab/badge/coverage/metadata_spec.rb index 2b87508bdef..725ae03ad74 100644 --- a/spec/lib/gitlab/badge/coverage/metadata_spec.rb +++ b/spec/lib/gitlab/badge/coverage/metadata_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'lib/gitlab/badge/shared/metadata' -describe Gitlab::Badge::Coverage::Metadata do +RSpec.describe Gitlab::Badge::Coverage::Metadata do let(:badge) do double(project: create(:project), ref: 'feature', job: 'test') end diff --git a/spec/lib/gitlab/badge/coverage/report_spec.rb b/spec/lib/gitlab/badge/coverage/report_spec.rb index 284ca53a996..9c4dfcbfd54 100644 --- a/spec/lib/gitlab/badge/coverage/report_spec.rb +++ b/spec/lib/gitlab/badge/coverage/report_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Badge::Coverage::Report do +RSpec.describe Gitlab::Badge::Coverage::Report do let(:project) { create(:project, :repository) } let(:job_name) { nil } diff --git a/spec/lib/gitlab/badge/coverage/template_spec.rb b/spec/lib/gitlab/badge/coverage/template_spec.rb index 3940b37830e..5a0adfd8e59 100644 --- a/spec/lib/gitlab/badge/coverage/template_spec.rb +++ b/spec/lib/gitlab/badge/coverage/template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Badge::Coverage::Template do +RSpec.describe Gitlab::Badge::Coverage::Template do let(:badge) { double(entity: 'coverage', status: 90.00, customization: {}) } let(:template) { described_class.new(badge) } diff --git a/spec/lib/gitlab/badge/pipeline/metadata_spec.rb b/spec/lib/gitlab/badge/pipeline/metadata_spec.rb index b096803f921..c8ed0c8ea29 100644 --- a/spec/lib/gitlab/badge/pipeline/metadata_spec.rb +++ b/spec/lib/gitlab/badge/pipeline/metadata_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'lib/gitlab/badge/shared/metadata' -describe Gitlab::Badge::Pipeline::Metadata do +RSpec.describe Gitlab::Badge::Pipeline::Metadata do let(:badge) { double(project: create(:project), ref: 'feature') } let(:metadata) { described_class.new(badge) } diff --git a/spec/lib/gitlab/badge/pipeline/status_spec.rb b/spec/lib/gitlab/badge/pipeline/status_spec.rb index ab8d1f0ec5b..fcc0d4030fd 100644 --- a/spec/lib/gitlab/badge/pipeline/status_spec.rb +++ b/spec/lib/gitlab/badge/pipeline/status_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Badge::Pipeline::Status do +RSpec.describe Gitlab::Badge::Pipeline::Status do let(:project) { create(:project, :repository) } let(:sha) { project.commit.sha } let(:branch) { 'master' } diff --git a/spec/lib/gitlab/badge/pipeline/template_spec.rb b/spec/lib/gitlab/badge/pipeline/template_spec.rb index 751a5d6645e..2f0d0782369 100644 --- a/spec/lib/gitlab/badge/pipeline/template_spec.rb +++ b/spec/lib/gitlab/badge/pipeline/template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Badge::Pipeline::Template do +RSpec.describe Gitlab::Badge::Pipeline::Template do let(:badge) { double(entity: 'pipeline', status: 'success', customization: {}) } let(:template) { described_class.new(badge) } diff --git a/spec/lib/gitlab/badge/shared/metadata.rb b/spec/lib/gitlab/badge/shared/metadata.rb index 809fa54db02..c99a65bb2f4 100644 --- a/spec/lib/gitlab/badge/shared/metadata.rb +++ b/spec/lib/gitlab/badge/shared/metadata.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -shared_examples 'badge metadata' do +RSpec.shared_examples 'badge metadata' do describe '#to_html' do let(:html) { Nokogiri::HTML.parse(metadata.to_html) } let(:a_href) { html.at('a') } diff --git a/spec/lib/gitlab/bare_repository_import/importer_spec.rb b/spec/lib/gitlab/bare_repository_import/importer_spec.rb index 75a23d4f49e..e09430a858c 100644 --- a/spec/lib/gitlab/bare_repository_import/importer_spec.rb +++ b/spec/lib/gitlab/bare_repository_import/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BareRepositoryImport::Importer, :seed_helper do +RSpec.describe Gitlab::BareRepositoryImport::Importer, :seed_helper do let!(:admin) { create(:admin) } let!(:base_dir) { Dir.mktmpdir + '/' } let(:bare_repository) { Gitlab::BareRepositoryImport::Repository.new(base_dir, File.join(base_dir, "#{project_path}.git")) } diff --git a/spec/lib/gitlab/bare_repository_import/repository_spec.rb b/spec/lib/gitlab/bare_repository_import/repository_spec.rb index d2ecb1869fc..bf115046744 100644 --- a/spec/lib/gitlab/bare_repository_import/repository_spec.rb +++ b/spec/lib/gitlab/bare_repository_import/repository_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::BareRepositoryImport::Repository do +RSpec.describe ::Gitlab::BareRepositoryImport::Repository do context 'legacy storage' do subject { described_class.new('/full/path/', '/full/path/to/repo.git') } diff --git a/spec/lib/gitlab/batch_pop_queueing_spec.rb b/spec/lib/gitlab/batch_pop_queueing_spec.rb index 28984d52024..41efc5417e4 100644 --- a/spec/lib/gitlab/batch_pop_queueing_spec.rb +++ b/spec/lib/gitlab/batch_pop_queueing_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BatchPopQueueing do +RSpec.describe Gitlab::BatchPopQueueing do include ExclusiveLeaseHelpers using RSpec::Parameterized::TableSyntax diff --git a/spec/lib/gitlab/batch_worker_context_spec.rb b/spec/lib/gitlab/batch_worker_context_spec.rb index 0ba30287ae5..31641f7449e 100644 --- a/spec/lib/gitlab/batch_worker_context_spec.rb +++ b/spec/lib/gitlab/batch_worker_context_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BatchWorkerContext do +RSpec.describe Gitlab::BatchWorkerContext do subject(:batch_context) do described_class.new( %w(hello world), diff --git a/spec/lib/gitlab/bitbucket_import/importer_spec.rb b/spec/lib/gitlab/bitbucket_import/importer_spec.rb index 137d0fd4f9e..08b7bafddf0 100644 --- a/spec/lib/gitlab/bitbucket_import/importer_spec.rb +++ b/spec/lib/gitlab/bitbucket_import/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BitbucketImport::Importer do +RSpec.describe Gitlab::BitbucketImport::Importer do include ImportSpecHelper before do @@ -226,8 +226,8 @@ describe Gitlab::BitbucketImport::Importer do it 'counts imported pull requests' do expect(Gitlab::Metrics).to receive(:counter).with( - :bitbucket_importer_imported_pull_requests, - 'The number of imported Bitbucket pull requests' + :bitbucket_importer_imported_merge_requests_total, + 'The number of imported merge (pull) requests' ) expect(counter).to receive(:increment) @@ -369,8 +369,8 @@ describe Gitlab::BitbucketImport::Importer do it 'counts imported issues' do expect(Gitlab::Metrics).to receive(:counter).with( - :bitbucket_importer_imported_issues, - 'The number of imported Bitbucket issues' + :bitbucket_importer_imported_issues_total, + 'The number of imported issues' ) expect(counter).to receive(:increment) @@ -389,23 +389,27 @@ describe Gitlab::BitbucketImport::Importer do allow(subject).to receive(:import_issues) allow(subject).to receive(:import_pull_requests) - allow(Gitlab::Metrics).to receive(:counter) { counter } - allow(Gitlab::Metrics).to receive(:histogram) { histogram } + allow(Gitlab::Metrics).to receive(:counter).and_return(counter) + allow(Gitlab::Metrics).to receive(:histogram).and_return(histogram) + allow(histogram).to receive(:observe) + allow(counter).to receive(:increment) end it 'counts and measures duration of imported projects' do expect(Gitlab::Metrics).to receive(:counter).with( - :bitbucket_importer_imported_projects, - 'The number of imported Bitbucket projects' + :bitbucket_importer_imported_projects_total, + 'The number of imported projects' ) expect(Gitlab::Metrics).to receive(:histogram).with( :bitbucket_importer_total_duration_seconds, - 'Total time spent importing Bitbucket projects, in seconds' + 'Total time spent importing projects, in seconds', + {}, + Gitlab::Import::Metrics::IMPORT_DURATION_BUCKETS ) expect(counter).to receive(:increment) - expect(histogram).to receive(:observe).with({ importer: described_class::IMPORTER }, anything) + expect(histogram).to receive(:observe).with({ importer: :bitbucket_importer }, anything) subject.execute end diff --git a/spec/lib/gitlab/bitbucket_import/project_creator_spec.rb b/spec/lib/gitlab/bitbucket_import/project_creator_spec.rb index 0dd8547a925..236e04a041b 100644 --- a/spec/lib/gitlab/bitbucket_import/project_creator_spec.rb +++ b/spec/lib/gitlab/bitbucket_import/project_creator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BitbucketImport::ProjectCreator do +RSpec.describe Gitlab::BitbucketImport::ProjectCreator do let(:user) { create(:user) } let(:repo) do diff --git a/spec/lib/gitlab/bitbucket_import/wiki_formatter_spec.rb b/spec/lib/gitlab/bitbucket_import/wiki_formatter_spec.rb index 7b5c7847f2d..4c285d31979 100644 --- a/spec/lib/gitlab/bitbucket_import/wiki_formatter_spec.rb +++ b/spec/lib/gitlab/bitbucket_import/wiki_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BitbucketImport::WikiFormatter do +RSpec.describe Gitlab::BitbucketImport::WikiFormatter do let(:project) do create(:project, namespace: create(:namespace, path: 'gitlabhq'), diff --git a/spec/lib/gitlab/bitbucket_server_import/importer_spec.rb b/spec/lib/gitlab/bitbucket_server_import/importer_spec.rb index cf39d2cb753..5eb27c51f9e 100644 --- a/spec/lib/gitlab/bitbucket_server_import/importer_spec.rb +++ b/spec/lib/gitlab/bitbucket_server_import/importer_spec.rb @@ -2,10 +2,13 @@ require 'spec_helper' -describe Gitlab::BitbucketServerImport::Importer do +RSpec.describe Gitlab::BitbucketServerImport::Importer do include ImportSpecHelper - let(:project) { create(:project, :repository, import_url: 'http://my-bitbucket') } + let(:import_url) { 'http://my-bitbucket' } + let(:user) { 'bitbucket' } + let(:password) { 'test' } + let(:project) { create(:project, :repository, import_url: import_url) } let(:now) { Time.now.utc.change(usec: 0) } let(:project_key) { 'TEST' } let(:repo_slug) { 'rouge' } @@ -16,7 +19,7 @@ describe Gitlab::BitbucketServerImport::Importer do before do data = project.create_or_update_import_data( data: { project_key: project_key, repo_slug: repo_slug }, - credentials: { base_uri: 'http://my-bitbucket', user: 'bitbucket', password: 'test' } + credentials: { base_uri: import_url, user: user, password: password } ) data.save project.save @@ -125,6 +128,48 @@ describe Gitlab::BitbucketServerImport::Importer do expect(note.updated_at).to eq(@pr_note.created_at) end + context 'metrics' do + let(:histogram) { double(:histogram) } + let(:counter) { double('counter', increment: true) } + + before do + allow(Gitlab::Metrics).to receive(:counter) { counter } + allow(Gitlab::Metrics).to receive(:histogram) { histogram } + allow(subject.client).to receive(:activities).and_return([@merge_event]) + end + + it 'counts and measures duration of imported projects' do + expect(Gitlab::Metrics).to receive(:counter).with( + :bitbucket_server_importer_imported_projects_total, + 'The number of imported projects' + ) + + expect(Gitlab::Metrics).to receive(:histogram).with( + :bitbucket_server_importer_total_duration_seconds, + 'Total time spent importing projects, in seconds', + {}, + Gitlab::Import::Metrics::IMPORT_DURATION_BUCKETS + ) + + expect(counter).to receive(:increment) + expect(histogram).to receive(:observe).with({ importer: :bitbucket_server_importer }, anything) + + subject.execute + end + + it 'counts imported pull requests' do + expect(Gitlab::Metrics).to receive(:counter).with( + :bitbucket_server_importer_imported_merge_requests_total, + 'The number of imported merge (pull) requests' + ) + + expect(counter).to receive(:increment) + allow(histogram).to receive(:observe).with({ importer: :bitbucket_server_importer }, anything) + + subject.execute + end + end + it 'imports threaded discussions' do reply = instance_double( BitbucketServer::Representation::PullRequestComment, diff --git a/spec/lib/gitlab/blame_spec.rb b/spec/lib/gitlab/blame_spec.rb index e1afd5b25bb..e22399723ac 100644 --- a/spec/lib/gitlab/blame_spec.rb +++ b/spec/lib/gitlab/blame_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Blame do +RSpec.describe Gitlab::Blame do let(:project) { create(:project, :repository) } let(:path) { 'files/ruby/popen.rb' } let(:commit) { project.commit('master') } diff --git a/spec/lib/gitlab/blob_helper_spec.rb b/spec/lib/gitlab/blob_helper_spec.rb index e057385b35f..65fa5bf0120 100644 --- a/spec/lib/gitlab/blob_helper_spec.rb +++ b/spec/lib/gitlab/blob_helper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BlobHelper do +RSpec.describe Gitlab::BlobHelper do include FakeBlobHelpers let(:project) { create(:project) } diff --git a/spec/lib/gitlab/branch_push_merge_commit_analyzer_spec.rb b/spec/lib/gitlab/branch_push_merge_commit_analyzer_spec.rb index a27f14cd621..f09f38a6127 100644 --- a/spec/lib/gitlab/branch_push_merge_commit_analyzer_spec.rb +++ b/spec/lib/gitlab/branch_push_merge_commit_analyzer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BranchPushMergeCommitAnalyzer do +RSpec.describe Gitlab::BranchPushMergeCommitAnalyzer do let(:project) { create(:project, :repository) } let(:oldrev) { 'merge-commit-analyze-before' } let(:newrev) { 'merge-commit-analyze-after' } diff --git a/spec/lib/gitlab/build_access_spec.rb b/spec/lib/gitlab/build_access_spec.rb index b7af8ace5b5..c6248f94772 100644 --- a/spec/lib/gitlab/build_access_spec.rb +++ b/spec/lib/gitlab/build_access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::BuildAccess do +RSpec.describe Gitlab::BuildAccess do let(:user) { create(:user) } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/cache/ci/project_pipeline_status_spec.rb b/spec/lib/gitlab/cache/ci/project_pipeline_status_spec.rb index fc9266f75fb..8d625cab1d8 100644 --- a/spec/lib/gitlab/cache/ci/project_pipeline_status_spec.rb +++ b/spec/lib/gitlab/cache/ci/project_pipeline_status_spec.rb @@ -2,8 +2,8 @@ require 'spec_helper' -describe Gitlab::Cache::Ci::ProjectPipelineStatus, :clean_gitlab_redis_cache do - let!(:project) { create(:project, :repository) } +RSpec.describe Gitlab::Cache::Ci::ProjectPipelineStatus, :clean_gitlab_redis_cache do + let_it_be(:project) { create(:project, :repository) } let(:pipeline_status) { described_class.new(project) } let(:cache_key) { pipeline_status.cache_key } @@ -77,6 +77,62 @@ describe Gitlab::Cache::Ci::ProjectPipelineStatus, :clean_gitlab_redis_cache do end describe '#load_status' do + describe 'gitaly call counts', :request_store do + context 'not cached' do + before do + expect(pipeline_status).not_to be_has_cache + end + + context 'ci_pipeline_status_omit_commit_sha_in_cache_key is enabled' do + before do + stub_feature_flags(ci_pipeline_status_omit_commit_sha_in_cache_key: project) + end + + it 'makes a Gitaly call' do + expect { pipeline_status.load_status }.to change { Gitlab::GitalyClient.get_request_count }.by(1) + end + end + + context 'ci_pipeline_status_omit_commit_sha_in_cache_key is disabled' do + before do + stub_feature_flags(ci_pipeline_status_omit_commit_sha_in_cache_key: false) + end + + it 'makes a Gitaly calls' do + expect { pipeline_status.load_status }.to change { Gitlab::GitalyClient.get_request_count }.by(1) + end + end + end + + context 'cached' do + before do + described_class.load_in_batch_for_projects([project]) + + expect(pipeline_status).to be_has_cache + end + + context 'ci_pipeline_status_omit_commit_sha_in_cache_key is enabled' do + before do + stub_feature_flags(ci_pipeline_status_omit_commit_sha_in_cache_key: project) + end + + it 'makes no Gitaly calls' do + expect { pipeline_status.load_status }.to change { Gitlab::GitalyClient.get_request_count }.by(0) + end + end + + context 'ci_pipeline_status_omit_commit_sha_in_cache_key is disabled' do + before do + stub_feature_flags(ci_pipeline_status_omit_commit_sha_in_cache_key: false) + end + + it 'makes a Gitaly calls' do + expect { pipeline_status.load_status }.to change { Gitlab::GitalyClient.get_request_count }.by(1) + end + end + end + end + it 'loads the status from the cache when there is one' do expect(pipeline_status).to receive(:has_cache?).and_return(true) expect(pipeline_status).to receive(:load_from_cache) diff --git a/spec/lib/gitlab/cache/import/caching_spec.rb b/spec/lib/gitlab/cache/import/caching_spec.rb index 7b4308d32ae..d6911dad9d4 100644 --- a/spec/lib/gitlab/cache/import/caching_spec.rb +++ b/spec/lib/gitlab/cache/import/caching_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cache::Import::Caching, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::Cache::Import::Caching, :clean_gitlab_redis_cache do describe '.read' do it 'reads a value from the cache' do described_class.write('foo', 'bar') diff --git a/spec/lib/gitlab/cache/request_cache_spec.rb b/spec/lib/gitlab/cache/request_cache_spec.rb index 70a7f090d0a..57aee525ddd 100644 --- a/spec/lib/gitlab/cache/request_cache_spec.rb +++ b/spec/lib/gitlab/cache/request_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cache::RequestCache do +RSpec.describe Gitlab::Cache::RequestCache do let(:klass) do Class.new do extend Gitlab::Cache::RequestCache diff --git a/spec/lib/gitlab/changes_list_spec.rb b/spec/lib/gitlab/changes_list_spec.rb index 911450f3a8b..8292764f561 100644 --- a/spec/lib/gitlab/changes_list_spec.rb +++ b/spec/lib/gitlab/changes_list_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::ChangesList do +RSpec.describe Gitlab::ChangesList do let(:valid_changes_string) { "\n000000 570e7b2 refs/heads/my_branch\nd14d6c 6fd24d refs/heads/master" } let(:invalid_changes) { 1 } diff --git a/spec/lib/gitlab/chat/command_spec.rb b/spec/lib/gitlab/chat/command_spec.rb index f7f344bf786..89c693daaa0 100644 --- a/spec/lib/gitlab/chat/command_spec.rb +++ b/spec/lib/gitlab/chat/command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Chat::Command do +RSpec.describe Gitlab::Chat::Command do let(:chat_name) { create(:chat_name) } let(:command) do diff --git a/spec/lib/gitlab/chat/output_spec.rb b/spec/lib/gitlab/chat/output_spec.rb index b179f9e9d0a..38e17c39fad 100644 --- a/spec/lib/gitlab/chat/output_spec.rb +++ b/spec/lib/gitlab/chat/output_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Chat::Output do +RSpec.describe Gitlab::Chat::Output do let(:build) do create(:ci_build, pipeline: create(:ci_pipeline, source: :chat)) end diff --git a/spec/lib/gitlab/chat/responder/base_spec.rb b/spec/lib/gitlab/chat/responder/base_spec.rb index 7fa9bad9d38..667228cbab4 100644 --- a/spec/lib/gitlab/chat/responder/base_spec.rb +++ b/spec/lib/gitlab/chat/responder/base_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Chat::Responder::Base do +RSpec.describe Gitlab::Chat::Responder::Base do let(:project) { double(:project) } let(:pipeline) { double(:pipeline, project: project) } let(:build) { double(:build, pipeline: pipeline) } diff --git a/spec/lib/gitlab/chat/responder/mattermost_spec.rb b/spec/lib/gitlab/chat/responder/mattermost_spec.rb index f3480dfef06..ca5f83d760a 100644 --- a/spec/lib/gitlab/chat/responder/mattermost_spec.rb +++ b/spec/lib/gitlab/chat/responder/mattermost_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Chat::Responder::Mattermost do +RSpec.describe Gitlab::Chat::Responder::Mattermost do let(:chat_name) { create(:chat_name, chat_id: 'U123') } let(:pipeline) do diff --git a/spec/lib/gitlab/chat/responder/slack_spec.rb b/spec/lib/gitlab/chat/responder/slack_spec.rb index a1553232b32..4801a1c6b66 100644 --- a/spec/lib/gitlab/chat/responder/slack_spec.rb +++ b/spec/lib/gitlab/chat/responder/slack_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Chat::Responder::Slack do +RSpec.describe Gitlab::Chat::Responder::Slack do let(:chat_name) { create(:chat_name, chat_id: 'U123') } let(:pipeline) do diff --git a/spec/lib/gitlab/chat/responder_spec.rb b/spec/lib/gitlab/chat/responder_spec.rb index 9893689cba9..6603dbe8d52 100644 --- a/spec/lib/gitlab/chat/responder_spec.rb +++ b/spec/lib/gitlab/chat/responder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Chat::Responder do +RSpec.describe Gitlab::Chat::Responder do describe '.responder_for' do context 'using a regular build' do it 'returns nil' do diff --git a/spec/lib/gitlab/chat_name_token_spec.rb b/spec/lib/gitlab/chat_name_token_spec.rb index b2d4a466021..906c02d54db 100644 --- a/spec/lib/gitlab/chat_name_token_spec.rb +++ b/spec/lib/gitlab/chat_name_token_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ChatNameToken do +RSpec.describe Gitlab::ChatNameToken do context 'when using unknown token' do let(:token) { } diff --git a/spec/lib/gitlab/chat_spec.rb b/spec/lib/gitlab/chat_spec.rb index be606fe6db1..a9df35ace98 100644 --- a/spec/lib/gitlab/chat_spec.rb +++ b/spec/lib/gitlab/chat_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Chat, :use_clean_rails_memory_store_caching do +RSpec.describe Gitlab::Chat, :use_clean_rails_memory_store_caching do describe '.available?' do it 'returns true when the chatops feature is available' do stub_feature_flags(chatops: true) diff --git a/spec/lib/gitlab/checks/branch_check_spec.rb b/spec/lib/gitlab/checks/branch_check_spec.rb index fd7eaa1603f..92452727017 100644 --- a/spec/lib/gitlab/checks/branch_check_spec.rb +++ b/spec/lib/gitlab/checks/branch_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::BranchCheck do +RSpec.describe Gitlab::Checks::BranchCheck do include_context 'change access checks context' describe '#validate!' do diff --git a/spec/lib/gitlab/checks/change_access_spec.rb b/spec/lib/gitlab/checks/change_access_spec.rb index dfc8c59fd74..87936d19239 100644 --- a/spec/lib/gitlab/checks/change_access_spec.rb +++ b/spec/lib/gitlab/checks/change_access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::ChangeAccess do +RSpec.describe Gitlab::Checks::ChangeAccess do describe '#exec' do include_context 'change access checks context' diff --git a/spec/lib/gitlab/checks/diff_check_spec.rb b/spec/lib/gitlab/checks/diff_check_spec.rb index 467b4ed3a21..2cca0aed9c6 100644 --- a/spec/lib/gitlab/checks/diff_check_spec.rb +++ b/spec/lib/gitlab/checks/diff_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::DiffCheck do +RSpec.describe Gitlab::Checks::DiffCheck do include_context 'change access checks context' describe '#validate!' do diff --git a/spec/lib/gitlab/checks/force_push_spec.rb b/spec/lib/gitlab/checks/force_push_spec.rb index 334dd8635a3..49e02fe5cec 100644 --- a/spec/lib/gitlab/checks/force_push_spec.rb +++ b/spec/lib/gitlab/checks/force_push_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::ForcePush do +RSpec.describe Gitlab::Checks::ForcePush do let_it_be(:project) { create(:project, :repository) } describe '.force_push?' do diff --git a/spec/lib/gitlab/checks/lfs_check_spec.rb b/spec/lib/gitlab/checks/lfs_check_spec.rb index c86481d1abe..713858e0e35 100644 --- a/spec/lib/gitlab/checks/lfs_check_spec.rb +++ b/spec/lib/gitlab/checks/lfs_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::LfsCheck do +RSpec.describe Gitlab::Checks::LfsCheck do include_context 'change access checks context' let(:blob_object) { project.repository.blob_at_branch('lfs', 'files/lfs/lfs_object.iso') } diff --git a/spec/lib/gitlab/checks/lfs_integrity_spec.rb b/spec/lib/gitlab/checks/lfs_integrity_spec.rb index 505f117034e..8fec702790c 100644 --- a/spec/lib/gitlab/checks/lfs_integrity_spec.rb +++ b/spec/lib/gitlab/checks/lfs_integrity_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::LfsIntegrity do +RSpec.describe Gitlab::Checks::LfsIntegrity do include ProjectForksHelper let!(:time_left) { 50 } diff --git a/spec/lib/gitlab/checks/project_created_spec.rb b/spec/lib/gitlab/checks/project_created_spec.rb index bbc97155374..f099f19b061 100644 --- a/spec/lib/gitlab/checks/project_created_spec.rb +++ b/spec/lib/gitlab/checks/project_created_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::ProjectCreated, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::Checks::ProjectCreated, :clean_gitlab_redis_shared_state do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, :repository, namespace: user.namespace) } let(:protocol) { 'http' } diff --git a/spec/lib/gitlab/checks/project_moved_spec.rb b/spec/lib/gitlab/checks/project_moved_spec.rb index 1d1d6211088..e15fa90443b 100644 --- a/spec/lib/gitlab/checks/project_moved_spec.rb +++ b/spec/lib/gitlab/checks/project_moved_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::ProjectMoved, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::Checks::ProjectMoved, :clean_gitlab_redis_shared_state do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, :repository, :wiki_repo, namespace: user.namespace) } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/checks/push_check_spec.rb b/spec/lib/gitlab/checks/push_check_spec.rb index 857d71732fe..45ab13cf0cf 100644 --- a/spec/lib/gitlab/checks/push_check_spec.rb +++ b/spec/lib/gitlab/checks/push_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::PushCheck do +RSpec.describe Gitlab::Checks::PushCheck do include_context 'change access checks context' describe '#validate!' do diff --git a/spec/lib/gitlab/checks/push_file_count_check_spec.rb b/spec/lib/gitlab/checks/push_file_count_check_spec.rb index e05102a9ce8..e05070e8f35 100644 --- a/spec/lib/gitlab/checks/push_file_count_check_spec.rb +++ b/spec/lib/gitlab/checks/push_file_count_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::PushFileCountCheck do +RSpec.describe Gitlab::Checks::PushFileCountCheck do let(:snippet) { create(:personal_snippet, :repository) } let(:changes) { { oldrev: oldrev, newrev: newrev, ref: ref } } let(:timeout) { Gitlab::GitAccess::INTERNAL_TIMEOUT } diff --git a/spec/lib/gitlab/checks/snippet_check_spec.rb b/spec/lib/gitlab/checks/snippet_check_spec.rb index 3eee5ccfc0a..2c027486bc9 100644 --- a/spec/lib/gitlab/checks/snippet_check_spec.rb +++ b/spec/lib/gitlab/checks/snippet_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::SnippetCheck do +RSpec.describe Gitlab::Checks::SnippetCheck do include_context 'change access checks context' let(:snippet) { create(:personal_snippet, :repository) } diff --git a/spec/lib/gitlab/checks/tag_check_spec.rb b/spec/lib/gitlab/checks/tag_check_spec.rb index 0c94171646e..e2e7d9c9648 100644 --- a/spec/lib/gitlab/checks/tag_check_spec.rb +++ b/spec/lib/gitlab/checks/tag_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::TagCheck do +RSpec.describe Gitlab::Checks::TagCheck do include_context 'change access checks context' describe '#validate!' do diff --git a/spec/lib/gitlab/checks/timed_logger_spec.rb b/spec/lib/gitlab/checks/timed_logger_spec.rb index 0ed3940c038..6c488212eca 100644 --- a/spec/lib/gitlab/checks/timed_logger_spec.rb +++ b/spec/lib/gitlab/checks/timed_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Checks::TimedLogger do +RSpec.describe Gitlab::Checks::TimedLogger do let!(:timeout) { 50.seconds } let!(:start) { Time.now } let!(:ref) { "bar" } diff --git a/spec/lib/gitlab/ci/ansi2html_spec.rb b/spec/lib/gitlab/ci/ansi2html_spec.rb index ee789995bc2..f29a39e4e66 100644 --- a/spec/lib/gitlab/ci/ansi2html_spec.rb +++ b/spec/lib/gitlab/ci/ansi2html_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Ansi2html do +RSpec.describe Gitlab::Ci::Ansi2html do subject { described_class } it "prints non-ansi as-is" do diff --git a/spec/lib/gitlab/ci/ansi2json/line_spec.rb b/spec/lib/gitlab/ci/ansi2json/line_spec.rb index 4b5c3f9489e..8b1cd812a70 100644 --- a/spec/lib/gitlab/ci/ansi2json/line_spec.rb +++ b/spec/lib/gitlab/ci/ansi2json/line_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Ansi2json::Line do +RSpec.describe Gitlab::Ci::Ansi2json::Line do let(:offset) { 0 } let(:style) { Gitlab::Ci::Ansi2json::Style.new } diff --git a/spec/lib/gitlab/ci/ansi2json/parser_spec.rb b/spec/lib/gitlab/ci/ansi2json/parser_spec.rb index e161e74c1ff..cf93ebe0721 100644 --- a/spec/lib/gitlab/ci/ansi2json/parser_spec.rb +++ b/spec/lib/gitlab/ci/ansi2json/parser_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' # The rest of the specs for this class are covered in style_spec.rb -describe Gitlab::Ci::Ansi2json::Parser do +RSpec.describe Gitlab::Ci::Ansi2json::Parser do subject { described_class } describe 'bold?' do diff --git a/spec/lib/gitlab/ci/ansi2json/result_spec.rb b/spec/lib/gitlab/ci/ansi2json/result_spec.rb index 5b7b5481400..31c0da95f0a 100644 --- a/spec/lib/gitlab/ci/ansi2json/result_spec.rb +++ b/spec/lib/gitlab/ci/ansi2json/result_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Ansi2json::Result do +RSpec.describe Gitlab::Ci::Ansi2json::Result do let(:stream) { StringIO.new('hello') } let(:state) { Gitlab::Ci::Ansi2json::State.new(nil, stream.size) } let(:offset) { 0 } diff --git a/spec/lib/gitlab/ci/ansi2json/style_spec.rb b/spec/lib/gitlab/ci/ansi2json/style_spec.rb index ad05aa03e83..d27a642ecf3 100644 --- a/spec/lib/gitlab/ci/ansi2json/style_spec.rb +++ b/spec/lib/gitlab/ci/ansi2json/style_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Ansi2json::Style do +RSpec.describe Gitlab::Ci::Ansi2json::Style do describe '#set?' do subject { described_class.new(params).set? } diff --git a/spec/lib/gitlab/ci/ansi2json_spec.rb b/spec/lib/gitlab/ci/ansi2json_spec.rb index 124379fa321..cb6949fddc2 100644 --- a/spec/lib/gitlab/ci/ansi2json_spec.rb +++ b/spec/lib/gitlab/ci/ansi2json_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Ansi2json do +RSpec.describe Gitlab::Ci::Ansi2json do subject { described_class } describe 'lines' do diff --git a/spec/lib/gitlab/ci/artifact_file_reader_spec.rb b/spec/lib/gitlab/ci/artifact_file_reader_spec.rb index 04017b9ae3e..e982f0eb015 100644 --- a/spec/lib/gitlab/ci/artifact_file_reader_spec.rb +++ b/spec/lib/gitlab/ci/artifact_file_reader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::ArtifactFileReader do +RSpec.describe Gitlab::Ci::ArtifactFileReader do let(:job) { create(:ci_build) } let(:path) { 'generated.yml' } # included in the ci_build_artifacts.zip diff --git a/spec/lib/gitlab/ci/build/artifacts/adapters/gzip_stream_spec.rb b/spec/lib/gitlab/ci/build/artifacts/adapters/gzip_stream_spec.rb index cec3e70bb9f..98f909a0ed0 100644 --- a/spec/lib/gitlab/ci/build/artifacts/adapters/gzip_stream_spec.rb +++ b/spec/lib/gitlab/ci/build/artifacts/adapters/gzip_stream_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Artifacts::Adapters::GzipStream do +RSpec.describe Gitlab::Ci::Build::Artifacts::Adapters::GzipStream do describe '#initialize' do context 'when stream is passed' do let(:stream) { File.open(expand_fixture_path('junit/junit.xml.gz'), 'rb') } diff --git a/spec/lib/gitlab/ci/build/artifacts/adapters/raw_stream_spec.rb b/spec/lib/gitlab/ci/build/artifacts/adapters/raw_stream_spec.rb index 66a234232e1..badff972e60 100644 --- a/spec/lib/gitlab/ci/build/artifacts/adapters/raw_stream_spec.rb +++ b/spec/lib/gitlab/ci/build/artifacts/adapters/raw_stream_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Artifacts::Adapters::RawStream do +RSpec.describe Gitlab::Ci::Build::Artifacts::Adapters::RawStream do describe '#initialize' do context 'when stream is passed' do let(:stream) { File.open(expand_fixture_path('junit/junit.xml'), 'rb') } diff --git a/spec/lib/gitlab/ci/build/artifacts/metadata/entry_spec.rb b/spec/lib/gitlab/ci/build/artifacts/metadata/entry_spec.rb index 7a413a7aeac..c8ace28108b 100644 --- a/spec/lib/gitlab/ci/build/artifacts/metadata/entry_spec.rb +++ b/spec/lib/gitlab/ci/build/artifacts/metadata/entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Artifacts::Metadata::Entry do +RSpec.describe Gitlab::Ci::Build::Artifacts::Metadata::Entry do let(:entries) do { 'path/' => {}, 'path/dir_1/' => {}, diff --git a/spec/lib/gitlab/ci/build/artifacts/metadata_spec.rb b/spec/lib/gitlab/ci/build/artifacts/metadata_spec.rb index bfa65c66b33..77b8aa1d591 100644 --- a/spec/lib/gitlab/ci/build/artifacts/metadata_spec.rb +++ b/spec/lib/gitlab/ci/build/artifacts/metadata_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Artifacts::Metadata do +RSpec.describe Gitlab::Ci::Build::Artifacts::Metadata do def metadata(path = '', **opts) described_class.new(metadata_file_stream, path, **opts) end diff --git a/spec/lib/gitlab/ci/build/artifacts/path_spec.rb b/spec/lib/gitlab/ci/build/artifacts/path_spec.rb index 7bbef0f5197..27b7dac2ae4 100644 --- a/spec/lib/gitlab/ci/build/artifacts/path_spec.rb +++ b/spec/lib/gitlab/ci/build/artifacts/path_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Artifacts::Path do +RSpec.describe Gitlab::Ci::Build::Artifacts::Path do describe '#valid?' do context 'when path contains a zero character' do it 'is not valid' do diff --git a/spec/lib/gitlab/ci/build/context/build_spec.rb b/spec/lib/gitlab/ci/build/context/build_spec.rb index 1b73b9a083d..61ca8e759b5 100644 --- a/spec/lib/gitlab/ci/build/context/build_spec.rb +++ b/spec/lib/gitlab/ci/build/context/build_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Context::Build do +RSpec.describe Gitlab::Ci::Build::Context::Build do let(:pipeline) { create(:ci_pipeline) } let(:seed_attributes) { { 'name' => 'some-job' } } diff --git a/spec/lib/gitlab/ci/build/context/global_spec.rb b/spec/lib/gitlab/ci/build/context/global_spec.rb index 65cc41ed3f9..7394708f9b6 100644 --- a/spec/lib/gitlab/ci/build/context/global_spec.rb +++ b/spec/lib/gitlab/ci/build/context/global_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Context::Global do +RSpec.describe Gitlab::Ci::Build::Context::Global do let(:pipeline) { create(:ci_pipeline) } let(:yaml_variables) { {} } diff --git a/spec/lib/gitlab/ci/build/credentials/factory_spec.rb b/spec/lib/gitlab/ci/build/credentials/factory_spec.rb index 159f89f4985..613d360f78d 100644 --- a/spec/lib/gitlab/ci/build/credentials/factory_spec.rb +++ b/spec/lib/gitlab/ci/build/credentials/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Credentials::Factory do +RSpec.describe Gitlab::Ci::Build::Credentials::Factory do let(:build) { create(:ci_build, name: 'spinach', stage: 'test', stage_idx: 0) } subject { described_class.new(build).create! } diff --git a/spec/lib/gitlab/ci/build/credentials/registry_spec.rb b/spec/lib/gitlab/ci/build/credentials/registry_spec.rb index 552580dcbbe..c0a76973f60 100644 --- a/spec/lib/gitlab/ci/build/credentials/registry_spec.rb +++ b/spec/lib/gitlab/ci/build/credentials/registry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Credentials::Registry do +RSpec.describe Gitlab::Ci::Build::Credentials::Registry do let(:build) { create(:ci_build, name: 'spinach', stage: 'test', stage_idx: 0) } let(:registry_url) { 'registry.example.com:5005' } diff --git a/spec/lib/gitlab/ci/build/image_spec.rb b/spec/lib/gitlab/ci/build/image_spec.rb index 4f7cfc9783a..71cd57d317c 100644 --- a/spec/lib/gitlab/ci/build/image_spec.rb +++ b/spec/lib/gitlab/ci/build/image_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Image do +RSpec.describe Gitlab::Ci::Build::Image do let(:job) { create(:ci_build, :no_options) } describe '#from_image' do diff --git a/spec/lib/gitlab/ci/build/policy/changes_spec.rb b/spec/lib/gitlab/ci/build/policy/changes_spec.rb index 07f52605929..016730e01cd 100644 --- a/spec/lib/gitlab/ci/build/policy/changes_spec.rb +++ b/spec/lib/gitlab/ci/build/policy/changes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Policy::Changes do +RSpec.describe Gitlab::Ci::Build::Policy::Changes do let_it_be(:project) { create(:project) } describe '#satisfied_by?' do diff --git a/spec/lib/gitlab/ci/build/policy/kubernetes_spec.rb b/spec/lib/gitlab/ci/build/policy/kubernetes_spec.rb index 6d96bdc30c7..81c0b76b453 100644 --- a/spec/lib/gitlab/ci/build/policy/kubernetes_spec.rb +++ b/spec/lib/gitlab/ci/build/policy/kubernetes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Policy::Kubernetes do +RSpec.describe Gitlab::Ci::Build::Policy::Kubernetes do let(:pipeline) { create(:ci_pipeline, project: project) } context 'when kubernetes service is active' do diff --git a/spec/lib/gitlab/ci/build/policy/refs_spec.rb b/spec/lib/gitlab/ci/build/policy/refs_spec.rb index c32fdc5c72e..7fd51102d71 100644 --- a/spec/lib/gitlab/ci/build/policy/refs_spec.rb +++ b/spec/lib/gitlab/ci/build/policy/refs_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Policy::Refs do +RSpec.describe Gitlab::Ci::Build::Policy::Refs do describe '#satisfied_by?' do context 'when matching ref' do let(:pipeline) { build_stubbed(:ci_pipeline, ref: 'master') } diff --git a/spec/lib/gitlab/ci/build/policy/variables_spec.rb b/spec/lib/gitlab/ci/build/policy/variables_spec.rb index 0e75726b81c..f692aa6146e 100644 --- a/spec/lib/gitlab/ci/build/policy/variables_spec.rb +++ b/spec/lib/gitlab/ci/build/policy/variables_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Policy::Variables do +RSpec.describe Gitlab::Ci::Build::Policy::Variables do let_it_be(:project) { create(:project) } let(:pipeline) do diff --git a/spec/lib/gitlab/ci/build/policy_spec.rb b/spec/lib/gitlab/ci/build/policy_spec.rb index 80d7b2e9dc8..b85b093fd03 100644 --- a/spec/lib/gitlab/ci/build/policy_spec.rb +++ b/spec/lib/gitlab/ci/build/policy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Policy do +RSpec.describe Gitlab::Ci::Build::Policy do let(:policy) { spy('policy specification') } before do diff --git a/spec/lib/gitlab/ci/build/port_spec.rb b/spec/lib/gitlab/ci/build/port_spec.rb index 1413780dfa6..480418e0851 100644 --- a/spec/lib/gitlab/ci/build/port_spec.rb +++ b/spec/lib/gitlab/ci/build/port_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Port do +RSpec.describe Gitlab::Ci::Build::Port do subject { described_class.new(port) } context 'when port is defined as an integer' do diff --git a/spec/lib/gitlab/ci/build/prerequisite/factory_spec.rb b/spec/lib/gitlab/ci/build/prerequisite/factory_spec.rb index 5187f99a441..a38ade4bfa5 100644 --- a/spec/lib/gitlab/ci/build/prerequisite/factory_spec.rb +++ b/spec/lib/gitlab/ci/build/prerequisite/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Prerequisite::Factory do +RSpec.describe Gitlab::Ci::Build::Prerequisite::Factory do let(:build) { create(:ci_build) } describe '.for_build' do diff --git a/spec/lib/gitlab/ci/build/prerequisite/kubernetes_namespace_spec.rb b/spec/lib/gitlab/ci/build/prerequisite/kubernetes_namespace_spec.rb index 66240380edd..94c14cfa479 100644 --- a/spec/lib/gitlab/ci/build/prerequisite/kubernetes_namespace_spec.rb +++ b/spec/lib/gitlab/ci/build/prerequisite/kubernetes_namespace_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Prerequisite::KubernetesNamespace do +RSpec.describe Gitlab::Ci::Build::Prerequisite::KubernetesNamespace do describe '#unmet?' do let(:build) { create(:ci_build) } diff --git a/spec/lib/gitlab/ci/build/releaser_spec.rb b/spec/lib/gitlab/ci/build/releaser_spec.rb index 2f7bca777dd..fa5e90674a6 100644 --- a/spec/lib/gitlab/ci/build/releaser_spec.rb +++ b/spec/lib/gitlab/ci/build/releaser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Releaser do +RSpec.describe Gitlab::Ci::Build::Releaser do subject { described_class.new(config: config[:release]).script } describe '#script' do @@ -13,13 +13,15 @@ describe Gitlab::Ci::Build::Releaser do name: 'Release $CI_COMMIT_SHA', description: 'Created using the release-cli $EXTRA_DESCRIPTION', tag_name: 'release-$CI_COMMIT_SHA', - ref: '$CI_COMMIT_SHA' + ref: '$CI_COMMIT_SHA', + milestones: %w[m1 m2 m3], + released_at: '2020-07-15T08:00:00Z' } } end it 'generates the script' do - expect(subject).to eq('release-cli create --name "Release $CI_COMMIT_SHA" --description "Created using the release-cli $EXTRA_DESCRIPTION" --tag-name "release-$CI_COMMIT_SHA" --ref "$CI_COMMIT_SHA"') + expect(subject).to eq(['release-cli create --name "Release $CI_COMMIT_SHA" --description "Created using the release-cli $EXTRA_DESCRIPTION" --tag-name "release-$CI_COMMIT_SHA" --ref "$CI_COMMIT_SHA" --released-at "2020-07-15T08:00:00Z" --milestone "m1" --milestone "m2" --milestone "m3"']) end end @@ -27,10 +29,12 @@ describe Gitlab::Ci::Build::Releaser do using RSpec::Parameterized::TableSyntax where(:node_name, :node_value, :result) do - 'name' | 'Release $CI_COMMIT_SHA' | 'release-cli create --name "Release $CI_COMMIT_SHA"' - 'description' | 'Release-cli $EXTRA_DESCRIPTION' | 'release-cli create --description "Release-cli $EXTRA_DESCRIPTION"' - 'tag_name' | 'release-$CI_COMMIT_SHA' | 'release-cli create --tag-name "release-$CI_COMMIT_SHA"' - 'ref' | '$CI_COMMIT_SHA' | 'release-cli create --ref "$CI_COMMIT_SHA"' + :name | 'Release $CI_COMMIT_SHA' | 'release-cli create --name "Release $CI_COMMIT_SHA"' + :description | 'Release-cli $EXTRA_DESCRIPTION' | 'release-cli create --description "Release-cli $EXTRA_DESCRIPTION"' + :tag_name | 'release-$CI_COMMIT_SHA' | 'release-cli create --tag-name "release-$CI_COMMIT_SHA"' + :ref | '$CI_COMMIT_SHA' | 'release-cli create --ref "$CI_COMMIT_SHA"' + :milestones | %w[m1 m2 m3] | 'release-cli create --milestone "m1" --milestone "m2" --milestone "m3"' + :released_at | '2020-07-15T08:00:00Z' | 'release-cli create --released-at "2020-07-15T08:00:00Z"' end with_them do @@ -43,7 +47,7 @@ describe Gitlab::Ci::Build::Releaser do end it 'generates the script' do - expect(subject).to eq(result) + expect(subject).to eq([result]) end end end diff --git a/spec/lib/gitlab/ci/build/rules/rule/clause/changes_spec.rb b/spec/lib/gitlab/ci/build/rules/rule/clause/changes_spec.rb index 076de3646b0..cf52f601006 100644 --- a/spec/lib/gitlab/ci/build/rules/rule/clause/changes_spec.rb +++ b/spec/lib/gitlab/ci/build/rules/rule/clause/changes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Rules::Rule::Clause::Changes do +RSpec.describe Gitlab::Ci::Build::Rules::Rule::Clause::Changes do describe '#satisfied_by?' do it_behaves_like 'a glob matching rule' do let(:pipeline) { build(:ci_pipeline) } diff --git a/spec/lib/gitlab/ci/build/rules/rule/clause/exists_spec.rb b/spec/lib/gitlab/ci/build/rules/rule/clause/exists_spec.rb index 10843a1435a..86dd5569a96 100644 --- a/spec/lib/gitlab/ci/build/rules/rule/clause/exists_spec.rb +++ b/spec/lib/gitlab/ci/build/rules/rule/clause/exists_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Rules::Rule::Clause::Exists do +RSpec.describe Gitlab::Ci::Build::Rules::Rule::Clause::Exists do describe '#satisfied_by?' do let(:pipeline) { build(:ci_pipeline, project: project, sha: project.repository.head_commit.sha) } diff --git a/spec/lib/gitlab/ci/build/rules/rule_spec.rb b/spec/lib/gitlab/ci/build/rules/rule_spec.rb index 04cdaa9d0ae..5694cd5d0a0 100644 --- a/spec/lib/gitlab/ci/build/rules/rule_spec.rb +++ b/spec/lib/gitlab/ci/build/rules/rule_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Rules::Rule do +RSpec.describe Gitlab::Ci::Build::Rules::Rule do let(:seed) do double('build seed', to_resource: ci_build, diff --git a/spec/lib/gitlab/ci/build/rules_spec.rb b/spec/lib/gitlab/ci/build/rules_spec.rb index 31a9fa055e1..cbeae33fbcf 100644 --- a/spec/lib/gitlab/ci/build/rules_spec.rb +++ b/spec/lib/gitlab/ci/build/rules_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Rules do +RSpec.describe Gitlab::Ci::Build::Rules do let(:pipeline) { create(:ci_pipeline) } let(:ci_build) { build(:ci_build, pipeline: pipeline) } diff --git a/spec/lib/gitlab/ci/build/step_spec.rb b/spec/lib/gitlab/ci/build/step_spec.rb index 1cebda2cc7e..4b8f68b9fa8 100644 --- a/spec/lib/gitlab/ci/build/step_spec.rb +++ b/spec/lib/gitlab/ci/build/step_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Build::Step do +RSpec.describe Gitlab::Ci::Build::Step do describe '#from_commands' do subject { described_class.from_commands(job) } @@ -62,7 +62,7 @@ describe Gitlab::Ci::Build::Step do let(:job) { create(:ci_build, :release_options) } it 'returns the release-cli command line' do - expect(subject.script).to eq("release-cli create --name \"Release $CI_COMMIT_SHA\" --description \"Created using the release-cli $EXTRA_DESCRIPTION\" --tag-name \"release-$CI_COMMIT_SHA\" --ref \"$CI_COMMIT_SHA\"") + expect(subject.script).to eq(["release-cli create --name \"Release $CI_COMMIT_SHA\" --description \"Created using the release-cli $EXTRA_DESCRIPTION\" --tag-name \"release-$CI_COMMIT_SHA\" --ref \"$CI_COMMIT_SHA\""]) end end diff --git a/spec/lib/gitlab/ci/charts_spec.rb b/spec/lib/gitlab/ci/charts_spec.rb index cfb7a3f72fa..e00e5ed3920 100644 --- a/spec/lib/gitlab/ci/charts_spec.rb +++ b/spec/lib/gitlab/ci/charts_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Charts do +RSpec.describe Gitlab::Ci::Charts do context "yearchart" do let(:project) { create(:project) } let(:chart) { Gitlab::Ci::Charts::YearChart.new(project) } diff --git a/spec/lib/gitlab/ci/config/edge_stages_injector_spec.rb b/spec/lib/gitlab/ci/config/edge_stages_injector_spec.rb index 042f9b591b6..52ea925c1c4 100644 --- a/spec/lib/gitlab/ci/config/edge_stages_injector_spec.rb +++ b/spec/lib/gitlab/ci/config/edge_stages_injector_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Config::EdgeStagesInjector do +RSpec.describe Gitlab::Ci::Config::EdgeStagesInjector do describe '#call' do subject { described_class.new(config).to_hash } diff --git a/spec/lib/gitlab/ci/config/entry/artifacts_spec.rb b/spec/lib/gitlab/ci/config/entry/artifacts_spec.rb index 8cfd07df777..028dcd3e1e6 100644 --- a/spec/lib/gitlab/ci/config/entry/artifacts_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/artifacts_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Artifacts do +RSpec.describe Gitlab::Ci::Config::Entry::Artifacts do let(:entry) { described_class.new(config) } describe 'validation' do diff --git a/spec/lib/gitlab/ci/config/entry/bridge_spec.rb b/spec/lib/gitlab/ci/config/entry/bridge_spec.rb index d08ce30618d..f33176c3da3 100644 --- a/spec/lib/gitlab/ci/config/entry/bridge_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/bridge_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Bridge do +RSpec.describe Gitlab::Ci::Config::Entry::Bridge do subject { described_class.new(config, name: :my_bridge) } it_behaves_like 'with inheritable CI config' do diff --git a/spec/lib/gitlab/ci/config/entry/cache_spec.rb b/spec/lib/gitlab/ci/config/entry/cache_spec.rb index f7b14360af3..3501812b76e 100644 --- a/spec/lib/gitlab/ci/config/entry/cache_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Cache do +RSpec.describe Gitlab::Ci::Config::Entry::Cache do subject(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/commands_spec.rb b/spec/lib/gitlab/ci/config/entry/commands_spec.rb index 8e7f9ab9706..439799fe973 100644 --- a/spec/lib/gitlab/ci/config/entry/commands_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/commands_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Commands do +RSpec.describe Gitlab::Ci::Config::Entry::Commands do let(:entry) { described_class.new(config) } context 'when entry config value is an array of strings' do diff --git a/spec/lib/gitlab/ci/config/entry/coverage_spec.rb b/spec/lib/gitlab/ci/config/entry/coverage_spec.rb index 877e3ec6216..c4353e822ae 100644 --- a/spec/lib/gitlab/ci/config/entry/coverage_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/coverage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Coverage do +RSpec.describe Gitlab::Ci::Config::Entry::Coverage do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/default_spec.rb b/spec/lib/gitlab/ci/config/entry/default_spec.rb index 23c62bbf92a..6e46d02a96e 100644 --- a/spec/lib/gitlab/ci/config/entry/default_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/default_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Default do +RSpec.describe Gitlab::Ci::Config::Entry::Default do let(:entry) { described_class.new(config) } it_behaves_like 'with inheritable CI config' do diff --git a/spec/lib/gitlab/ci/config/entry/environment_spec.rb b/spec/lib/gitlab/ci/config/entry/environment_spec.rb index 8c21d5342cc..0c18a7fb71e 100644 --- a/spec/lib/gitlab/ci/config/entry/environment_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/environment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Environment do +RSpec.describe Gitlab::Ci::Config::Entry::Environment do let(:entry) { described_class.new(config) } before do @@ -102,6 +102,17 @@ describe Gitlab::Ci::Config::Entry::Environment do end end + context 'when prepare action is used' do + let(:config) do + { name: 'production', + action: 'prepare' } + end + + it 'is valid' do + expect(entry).to be_valid + end + end + context 'when wrong action type is used' do let(:config) do { name: 'production', @@ -137,7 +148,7 @@ describe Gitlab::Ci::Config::Entry::Environment do describe '#errors' do it 'contains error about invalid action' do expect(entry.errors) - .to include 'environment action should be start or stop' + .to include 'environment action should be start, stop or prepare' end end end diff --git a/spec/lib/gitlab/ci/config/entry/files_spec.rb b/spec/lib/gitlab/ci/config/entry/files_spec.rb index 2bebbd7b198..6a101d80c7d 100644 --- a/spec/lib/gitlab/ci/config/entry/files_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/files_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Files do +RSpec.describe Gitlab::Ci::Config::Entry::Files do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/hidden_spec.rb b/spec/lib/gitlab/ci/config/entry/hidden_spec.rb index 40b73352676..090ef67f39d 100644 --- a/spec/lib/gitlab/ci/config/entry/hidden_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/hidden_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Hidden do +RSpec.describe Gitlab::Ci::Config::Entry::Hidden do describe '.matching?' do subject { described_class.matching?(name, {}) } diff --git a/spec/lib/gitlab/ci/config/entry/image_spec.rb b/spec/lib/gitlab/ci/config/entry/image_spec.rb index de3e887a6ed..c3d91057328 100644 --- a/spec/lib/gitlab/ci/config/entry/image_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/image_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Image do +RSpec.describe Gitlab::Ci::Config::Entry::Image do let(:entry) { described_class.new(config) } context 'when configuration is a string' do diff --git a/spec/lib/gitlab/ci/config/entry/include_spec.rb b/spec/lib/gitlab/ci/config/entry/include_spec.rb index bab11f26fa1..3e816f70c03 100644 --- a/spec/lib/gitlab/ci/config/entry/include_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/include_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::Ci::Config::Entry::Include do +RSpec.describe ::Gitlab::Ci::Config::Entry::Include do subject(:include_entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/inherit/default_spec.rb b/spec/lib/gitlab/ci/config/entry/inherit/default_spec.rb index 073f93ce542..7cd9b0acb99 100644 --- a/spec/lib/gitlab/ci/config/entry/inherit/default_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/inherit/default_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::Ci::Config::Entry::Inherit::Default do +RSpec.describe ::Gitlab::Ci::Config::Entry::Inherit::Default do using RSpec::Parameterized::TableSyntax subject { described_class.new(config) } diff --git a/spec/lib/gitlab/ci/config/entry/inherit/variables_spec.rb b/spec/lib/gitlab/ci/config/entry/inherit/variables_spec.rb index 06deed11c15..b1a8fbcdbe0 100644 --- a/spec/lib/gitlab/ci/config/entry/inherit/variables_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/inherit/variables_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::Ci::Config::Entry::Inherit::Variables do +RSpec.describe ::Gitlab::Ci::Config::Entry::Inherit::Variables do using RSpec::Parameterized::TableSyntax subject { described_class.new(config) } diff --git a/spec/lib/gitlab/ci/config/entry/job_spec.rb b/spec/lib/gitlab/ci/config/entry/job_spec.rb index b6279485426..180c52ee1ab 100644 --- a/spec/lib/gitlab/ci/config/entry/job_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/job_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Job do +RSpec.describe Gitlab::Ci::Config::Entry::Job do let(:entry) { described_class.new(config, name: :rspec) } it_behaves_like 'with inheritable CI config' do @@ -33,7 +33,7 @@ describe Gitlab::Ci::Config::Entry::Job do inherit] end - it { is_expected.to match_array result } + it { is_expected.to include(*result) } end end diff --git a/spec/lib/gitlab/ci/config/entry/jobs_spec.rb b/spec/lib/gitlab/ci/config/entry/jobs_spec.rb index 203342ab620..8561bd330b7 100644 --- a/spec/lib/gitlab/ci/config/entry/jobs_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/jobs_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Jobs do +RSpec.describe Gitlab::Ci::Config::Entry::Jobs do let(:entry) { described_class.new(config) } let(:config) do diff --git a/spec/lib/gitlab/ci/config/entry/key_spec.rb b/spec/lib/gitlab/ci/config/entry/key_spec.rb index 327607e2266..4ee1ffb29ad 100644 --- a/spec/lib/gitlab/ci/config/entry/key_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/key_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Key do +RSpec.describe Gitlab::Ci::Config::Entry::Key do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/kubernetes_spec.rb b/spec/lib/gitlab/ci/config/entry/kubernetes_spec.rb index 468e83ec506..53809d2d549 100644 --- a/spec/lib/gitlab/ci/config/entry/kubernetes_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/kubernetes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Kubernetes do +RSpec.describe Gitlab::Ci::Config::Entry::Kubernetes do subject { described_class.new(config) } describe 'attributes' do diff --git a/spec/lib/gitlab/ci/config/entry/need_spec.rb b/spec/lib/gitlab/ci/config/entry/need_spec.rb index 92b71c5f6cc..5a826bf8282 100644 --- a/spec/lib/gitlab/ci/config/entry/need_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/need_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::Ci::Config::Entry::Need do +RSpec.describe ::Gitlab::Ci::Config::Entry::Need do subject(:need) { described_class.new(config) } shared_examples 'job type' do diff --git a/spec/lib/gitlab/ci/config/entry/needs_spec.rb b/spec/lib/gitlab/ci/config/entry/needs_spec.rb index b8b84b5efd2..f3b9d0c3c84 100644 --- a/spec/lib/gitlab/ci/config/entry/needs_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/needs_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::Ci::Config::Entry::Needs do +RSpec.describe ::Gitlab::Ci::Config::Entry::Needs do subject(:needs) { described_class.new(config) } before do diff --git a/spec/lib/gitlab/ci/config/entry/paths_spec.rb b/spec/lib/gitlab/ci/config/entry/paths_spec.rb index 221d5ae5863..dd4e7befc46 100644 --- a/spec/lib/gitlab/ci/config/entry/paths_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/paths_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Paths do +RSpec.describe Gitlab::Ci::Config::Entry::Paths do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/policy_spec.rb b/spec/lib/gitlab/ci/config/entry/policy_spec.rb index a606eb303e7..46800055dd9 100644 --- a/spec/lib/gitlab/ci/config/entry/policy_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/policy_spec.rb @@ -4,7 +4,7 @@ require 'fast_spec_helper' require 'support/helpers/stub_feature_flags' require_dependency 'active_model' -describe Gitlab::Ci::Config::Entry::Policy do +RSpec.describe Gitlab::Ci::Config::Entry::Policy do let(:entry) { described_class.new(config) } context 'when using simplified policy' do diff --git a/spec/lib/gitlab/ci/config/entry/port_spec.rb b/spec/lib/gitlab/ci/config/entry/port_spec.rb index 5f8f294334e..e2840c07f6b 100644 --- a/spec/lib/gitlab/ci/config/entry/port_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/port_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Port do +RSpec.describe Gitlab::Ci::Config::Entry::Port do let(:entry) { described_class.new(config) } before do diff --git a/spec/lib/gitlab/ci/config/entry/ports_spec.rb b/spec/lib/gitlab/ci/config/entry/ports_spec.rb index 2063bd1d86c..f738c4ee875 100644 --- a/spec/lib/gitlab/ci/config/entry/ports_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/ports_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Ports do +RSpec.describe Gitlab::Ci::Config::Entry::Ports do let(:entry) { described_class.new(config) } before do diff --git a/spec/lib/gitlab/ci/config/entry/prefix_spec.rb b/spec/lib/gitlab/ci/config/entry/prefix_spec.rb index 8132a674488..b337747f5d6 100644 --- a/spec/lib/gitlab/ci/config/entry/prefix_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/prefix_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Prefix do +RSpec.describe Gitlab::Ci::Config::Entry::Prefix do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/processable_spec.rb b/spec/lib/gitlab/ci/config/entry/processable_spec.rb index 8447a29c772..fdf6008f89f 100644 --- a/spec/lib/gitlab/ci/config/entry/processable_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/processable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Processable do +RSpec.describe Gitlab::Ci::Config::Entry::Processable do let(:node_class) do Class.new(::Gitlab::Config::Entry::Node) do include Gitlab::Ci::Config::Entry::Processable @@ -231,6 +231,12 @@ describe Gitlab::Ci::Config::Entry::Processable do end context 'when workflow rules is used' do + let(:workflow) { double('workflow', 'has_rules?' => true) } + + before do + entry.compose!(deps) + end + context 'when rules are used' do let(:config) { { script: 'ls', cache: { key: 'test' }, rules: [] } } @@ -239,11 +245,11 @@ describe Gitlab::Ci::Config::Entry::Processable do end end - context 'when rules are not used' do + context 'when rules are not used and only is defined' do let(:config) { { script: 'ls', cache: { key: 'test' }, only: [] } } - it 'does not define only' do - expect(entry).not_to be_only_defined + it 'keeps only entry' do + expect(entry).to be_only_defined end end end diff --git a/spec/lib/gitlab/ci/config/entry/release/assets/link_spec.rb b/spec/lib/gitlab/ci/config/entry/release/assets/link_spec.rb index 0e346de3d9e..bc320258412 100644 --- a/spec/lib/gitlab/ci/config/entry/release/assets/link_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/release/assets/link_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Release::Assets::Link do +RSpec.describe Gitlab::Ci::Config::Entry::Release::Assets::Link do let(:entry) { described_class.new(config) } describe 'validation' do diff --git a/spec/lib/gitlab/ci/config/entry/release/assets/links_spec.rb b/spec/lib/gitlab/ci/config/entry/release/assets/links_spec.rb index d12e8d966ab..440745d9eb3 100644 --- a/spec/lib/gitlab/ci/config/entry/release/assets/links_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/release/assets/links_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Release::Assets::Links do +RSpec.describe Gitlab::Ci::Config::Entry::Release::Assets::Links do let(:entry) { described_class.new(config) } describe 'validation' do diff --git a/spec/lib/gitlab/ci/config/entry/release/assets_spec.rb b/spec/lib/gitlab/ci/config/entry/release/assets_spec.rb index 08ad5764eaa..3d44d7d9903 100644 --- a/spec/lib/gitlab/ci/config/entry/release/assets_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/release/assets_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Release::Assets do +RSpec.describe Gitlab::Ci::Config::Entry::Release::Assets do let(:entry) { described_class.new(config) } describe 'validation' do diff --git a/spec/lib/gitlab/ci/config/entry/release_spec.rb b/spec/lib/gitlab/ci/config/entry/release_spec.rb index 500897569e9..e5155f91be4 100644 --- a/spec/lib/gitlab/ci/config/entry/release_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/release_spec.rb @@ -2,24 +2,35 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Release do +RSpec.describe Gitlab::Ci::Config::Entry::Release do let(:entry) { described_class.new(config) } + shared_examples_for 'a valid entry' do + describe '#value' do + it 'returns release configuration' do + expect(entry.value).to eq config + end + end + + describe '#valid?' do + it 'is valid' do + expect(entry).to be_valid + end + end + end + + shared_examples_for 'reports error' do |message| + it 'reports error' do + expect(entry.errors) + .to include message + end + end + describe 'validation' do context 'when entry config value is correct' do let(:config) { { tag_name: 'v0.06', description: "./release_changelog.txt" } } - describe '#value' do - it 'returns release configuration' do - expect(entry.value).to eq config - end - end - - describe '#valid?' do - it 'is valid' do - expect(entry).to be_valid - end - end + it_behaves_like 'a valid entry' end context "when value includes 'assets' keyword" do @@ -36,38 +47,144 @@ describe Gitlab::Ci::Config::Entry::Release do } end - describe '#value' do - it 'returns release configuration' do - expect(entry.value).to eq config - end + it_behaves_like 'a valid entry' + end + + context "when value includes 'name' keyword" do + let(:config) do + { + tag_name: 'v0.06', + description: "./release_changelog.txt", + name: "Release $CI_TAG_NAME" + } end - describe '#valid?' do - it 'is valid' do - expect(entry).to be_valid - end + it_behaves_like 'a valid entry' + end + + context "when value includes 'ref' keyword" do + let(:config) do + { + tag_name: 'v0.06', + description: "./release_changelog.txt", + name: "Release $CI_TAG_NAME", + ref: 'b3235930aa443112e639f941c69c578912189bdd' + } end + + it_behaves_like 'a valid entry' end - context "when value includes 'name' keyword" do + context "when value includes 'released_at' keyword" do let(:config) do { tag_name: 'v0.06', description: "./release_changelog.txt", - name: "Release $CI_TAG_NAME" + name: "Release $CI_TAG_NAME", + released_at: '2019-03-15T08:00:00Z' } end - describe '#value' do - it 'returns release configuration' do - expect(entry.value).to eq config - end + it_behaves_like 'a valid entry' + end + + context "when value includes 'milestones' keyword" do + let(:config) do + { + tag_name: 'v0.06', + description: "./release_changelog.txt", + name: "Release $CI_TAG_NAME", + milestones: milestones + } end - describe '#valid?' do - it 'is valid' do - expect(entry).to be_valid - end + context 'for an array of milestones' do + let(:milestones) { %w[m1 m2 m3] } + + it_behaves_like 'a valid entry' + end + + context 'for a single milestone' do + let(:milestones) { 'm1' } + + it_behaves_like 'a valid entry' + end + end + + context "when value includes 'ref' keyword" do + let(:config) do + { + tag_name: 'v0.06', + description: "./release_changelog.txt", + name: "Release $CI_TAG_NAME", + ref: ref + } + end + + context "when 'ref' is a full commit SHA" do + let(:ref) { 'b3235930aa443112e639f941c69c578912189bdd' } + + it_behaves_like 'a valid entry' + end + + context "when 'ref' is a short commit SHA" do + let(:ref) { 'b3235930'} + + it_behaves_like 'a valid entry' + end + + context "when 'ref' is a branch name" do + let(:ref) { 'fix/123-branch-name'} + + it_behaves_like 'a valid entry' + end + + context "when 'ref' is a semantic versioning tag" do + let(:ref) { 'v1.2.3'} + + it_behaves_like 'a valid entry' + end + + context "when 'ref' is a semantic versioning tag rc" do + let(:ref) { 'v1.2.3-rc'} + + it_behaves_like 'a valid entry' + end + end + + context "when value includes 'released_at' keyword" do + let(:config) do + { + tag_name: 'v0.06', + description: "./release_changelog.txt", + name: "Release $CI_TAG_NAME", + released_at: '2019-03-15T08:00:00Z' + } + end + + it_behaves_like 'a valid entry' + end + + context "when value includes 'milestones' keyword" do + let(:config) do + { + tag_name: 'v0.06', + description: "./release_changelog.txt", + name: "Release $CI_TAG_NAME", + milestones: milestones + } + end + + context 'for an array of milestones' do + let(:milestones) { %w[m1 m2 m3] } + + it_behaves_like 'a valid entry' + end + + context 'for a single milestone' do + let(:milestones) { 'm1' } + + it_behaves_like 'a valid entry' end end @@ -76,37 +193,43 @@ describe Gitlab::Ci::Config::Entry::Release do context 'when value of attribute is invalid' do let(:config) { { description: 10 } } - it 'reports error' do - expect(entry.errors) - .to include 'release description should be a string' - end + it_behaves_like 'reports error', 'release description should be a string' end context 'when release description is missing' do let(:config) { { tag_name: 'v0.06' } } - it 'reports error' do - expect(entry.errors) - .to include "release description can't be blank" - end + it_behaves_like 'reports error', "release description can't be blank" end context 'when release tag_name is missing' do let(:config) { { description: "./release_changelog.txt" } } - it 'reports error' do - expect(entry.errors) - .to include "release tag name can't be blank" - end + it_behaves_like 'reports error', "release tag name can't be blank" end context 'when there is an unknown key present' do let(:config) { { test: 100 } } - it 'reports error' do - expect(entry.errors) - .to include 'release config contains unknown keys: test' - end + it_behaves_like 'reports error', 'release config contains unknown keys: test' + end + + context 'when `released_at` is not a valid date' do + let(:config) { { released_at: 'ABC123' } } + + it_behaves_like 'reports error', 'release released at must be a valid datetime' + end + + context 'when `ref` is not valid' do + let(:config) { { ref: 'invalid\branch' } } + + it_behaves_like 'reports error', 'release ref must be a valid ref' + end + + context 'when `milestones` is not an array of strings' do + let(:config) { { milestones: [1, 2, 3] } } + + it_behaves_like 'reports error', 'release milestones should be an array of strings or a string' end end end diff --git a/spec/lib/gitlab/ci/config/entry/reports_spec.rb b/spec/lib/gitlab/ci/config/entry/reports_spec.rb index 2c12a88dedb..98105ebcd55 100644 --- a/spec/lib/gitlab/ci/config/entry/reports_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/reports_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Reports do +RSpec.describe Gitlab::Ci::Config::Entry::Reports do let(:entry) { described_class.new(config) } describe 'validates ALLOWED_KEYS' do @@ -44,6 +44,9 @@ describe Gitlab::Ci::Config::Entry::Reports do :license_management | 'gl-license-management-report.json' :license_scanning | 'gl-license-scanning-report.json' :performance | 'performance.json' + :browser_performance | 'browser-performance.json' + :browser_performance | 'performance.json' + :load_performance | 'load-performance.json' :lsif | 'lsif.json' :dotenv | 'build.dotenv' :cobertura | 'cobertura-coverage.xml' diff --git a/spec/lib/gitlab/ci/config/entry/retry_spec.rb b/spec/lib/gitlab/ci/config/entry/retry_spec.rb index 67253c71f6b..b38387a437e 100644 --- a/spec/lib/gitlab/ci/config/entry/retry_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/retry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Retry do +RSpec.describe Gitlab::Ci::Config::Entry::Retry do let(:entry) { described_class.new(config) } shared_context 'when retry value is a numeric', :numeric do diff --git a/spec/lib/gitlab/ci/config/entry/root_spec.rb b/spec/lib/gitlab/ci/config/entry/root_spec.rb index ba2dbf72fba..140b3c4f55b 100644 --- a/spec/lib/gitlab/ci/config/entry/root_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/root_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Root do +RSpec.describe Gitlab::Ci::Config::Entry::Root do let(:root) { described_class.new(hash) } describe '.nodes' do diff --git a/spec/lib/gitlab/ci/config/entry/rules/rule_spec.rb b/spec/lib/gitlab/ci/config/entry/rules/rule_spec.rb index 20db5f02fc7..4a43e6c9a86 100644 --- a/spec/lib/gitlab/ci/config/entry/rules/rule_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/rules/rule_spec.rb @@ -5,7 +5,7 @@ require 'gitlab_chronic_duration' require 'support/helpers/stub_feature_flags' require_dependency 'active_model' -describe Gitlab::Ci::Config::Entry::Rules::Rule do +RSpec.describe Gitlab::Ci::Config::Entry::Rules::Rule do let(:factory) do Gitlab::Config::Entry::Factory.new(described_class) .metadata(metadata) diff --git a/spec/lib/gitlab/ci/config/entry/rules_spec.rb b/spec/lib/gitlab/ci/config/entry/rules_spec.rb index 3c050801023..7d26365e7b3 100644 --- a/spec/lib/gitlab/ci/config/entry/rules_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/rules_spec.rb @@ -4,7 +4,7 @@ require 'fast_spec_helper' require 'support/helpers/stub_feature_flags' require_dependency 'active_model' -describe Gitlab::Ci::Config::Entry::Rules do +RSpec.describe Gitlab::Ci::Config::Entry::Rules do let(:factory) do Gitlab::Config::Entry::Factory.new(described_class) .metadata(metadata) diff --git a/spec/lib/gitlab/ci/config/entry/script_spec.rb b/spec/lib/gitlab/ci/config/entry/script_spec.rb index 57dc20ea628..1ddf7881e81 100644 --- a/spec/lib/gitlab/ci/config/entry/script_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/script_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Script do +RSpec.describe Gitlab::Ci::Config::Entry::Script do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/service_spec.rb b/spec/lib/gitlab/ci/config/entry/service_spec.rb index 66cca100688..9fbc14c19b9 100644 --- a/spec/lib/gitlab/ci/config/entry/service_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Service do +RSpec.describe Gitlab::Ci::Config::Entry::Service do let(:entry) { described_class.new(config) } before do diff --git a/spec/lib/gitlab/ci/config/entry/services_spec.rb b/spec/lib/gitlab/ci/config/entry/services_spec.rb index 764f783b083..e4f8a348d21 100644 --- a/spec/lib/gitlab/ci/config/entry/services_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/services_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Services do +RSpec.describe Gitlab::Ci::Config::Entry::Services do let(:entry) { described_class.new(config) } before do diff --git a/spec/lib/gitlab/ci/config/entry/stage_spec.rb b/spec/lib/gitlab/ci/config/entry/stage_spec.rb index 574fa00575a..2a105fb978e 100644 --- a/spec/lib/gitlab/ci/config/entry/stage_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Stage do +RSpec.describe Gitlab::Ci::Config::Entry::Stage do let(:stage) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/stages_spec.rb b/spec/lib/gitlab/ci/config/entry/stages_spec.rb index 3e6ff8eca28..1dd11bb03f8 100644 --- a/spec/lib/gitlab/ci/config/entry/stages_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/stages_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Stages do +RSpec.describe Gitlab::Ci::Config::Entry::Stages do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/trigger_spec.rb b/spec/lib/gitlab/ci/config/entry/trigger_spec.rb index dfd9807583c..5b4289741f3 100644 --- a/spec/lib/gitlab/ci/config/entry/trigger_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/trigger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Trigger do +RSpec.describe Gitlab::Ci::Config::Entry::Trigger do subject { described_class.new(config) } context 'when trigger config is a non-empty string' do diff --git a/spec/lib/gitlab/ci/config/entry/variables_spec.rb b/spec/lib/gitlab/ci/config/entry/variables_spec.rb index 1320b366367..d6391092f63 100644 --- a/spec/lib/gitlab/ci/config/entry/variables_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/variables_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Variables do +RSpec.describe Gitlab::Ci::Config::Entry::Variables do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/ci/config/entry/workflow_spec.rb b/spec/lib/gitlab/ci/config/entry/workflow_spec.rb index f2832b94bf0..3d19832e13d 100644 --- a/spec/lib/gitlab/ci/config/entry/workflow_spec.rb +++ b/spec/lib/gitlab/ci/config/entry/workflow_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::Entry::Workflow do +RSpec.describe Gitlab::Ci::Config::Entry::Workflow do let(:factory) { Gitlab::Config::Entry::Factory.new(described_class).value(rules_hash) } let(:config) { factory.create! } diff --git a/spec/lib/gitlab/ci/config/extendable/entry_spec.rb b/spec/lib/gitlab/ci/config/extendable/entry_spec.rb index e00104e3c68..69aa3bab77a 100644 --- a/spec/lib/gitlab/ci/config/extendable/entry_spec.rb +++ b/spec/lib/gitlab/ci/config/extendable/entry_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Config::Extendable::Entry do +RSpec.describe Gitlab::Ci::Config::Extendable::Entry do describe '.new' do context 'when entry key is not included in the context hash' do it 'raises error' do diff --git a/spec/lib/gitlab/ci/config/extendable_spec.rb b/spec/lib/gitlab/ci/config/extendable_spec.rb index 874b224067b..481f55d790e 100644 --- a/spec/lib/gitlab/ci/config/extendable_spec.rb +++ b/spec/lib/gitlab/ci/config/extendable_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Config::Extendable do +RSpec.describe Gitlab::Ci::Config::Extendable do subject { described_class.new(hash) } describe '#each' do diff --git a/spec/lib/gitlab/ci/config/external/context_spec.rb b/spec/lib/gitlab/ci/config/external/context_spec.rb index 610646ca85a..4b9adf7e87b 100644 --- a/spec/lib/gitlab/ci/config/external/context_spec.rb +++ b/spec/lib/gitlab/ci/config/external/context_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Config::External::Context do +RSpec.describe Gitlab::Ci::Config::External::Context do let(:project) { double('Project') } let(:user) { double('User') } let(:sha) { '12345' } diff --git a/spec/lib/gitlab/ci/config/external/file/artifact_spec.rb b/spec/lib/gitlab/ci/config/external/file/artifact_spec.rb index a8eb13c47bc..8dd92c5b5fd 100644 --- a/spec/lib/gitlab/ci/config/external/file/artifact_spec.rb +++ b/spec/lib/gitlab/ci/config/external/file/artifact_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::File::Artifact do +RSpec.describe Gitlab::Ci::Config::External::File::Artifact do let(:parent_pipeline) { create(:ci_pipeline) } let(:context) do Gitlab::Ci::Config::External::Context.new(parent_pipeline: parent_pipeline) diff --git a/spec/lib/gitlab/ci/config/external/file/base_spec.rb b/spec/lib/gitlab/ci/config/external/file/base_spec.rb index d472d6527e2..445edb253fd 100644 --- a/spec/lib/gitlab/ci/config/external/file/base_spec.rb +++ b/spec/lib/gitlab/ci/config/external/file/base_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::File::Base do +RSpec.describe Gitlab::Ci::Config::External::File::Base do let(:context_params) { { sha: 'HEAD' } } let(:context) { Gitlab::Ci::Config::External::Context.new(**context_params) } diff --git a/spec/lib/gitlab/ci/config/external/file/local_spec.rb b/spec/lib/gitlab/ci/config/external/file/local_spec.rb index c9851239859..993a07568de 100644 --- a/spec/lib/gitlab/ci/config/external/file/local_spec.rb +++ b/spec/lib/gitlab/ci/config/external/file/local_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::File::Local do +RSpec.describe Gitlab::Ci::Config::External::File::Local do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } let(:sha) { '12345' } diff --git a/spec/lib/gitlab/ci/config/external/file/project_spec.rb b/spec/lib/gitlab/ci/config/external/file/project_spec.rb index 4d8f0dbc861..a5e4e27df6f 100644 --- a/spec/lib/gitlab/ci/config/external/file/project_spec.rb +++ b/spec/lib/gitlab/ci/config/external/file/project_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::File::Project do +RSpec.describe Gitlab::Ci::Config::External::File::Project do let_it_be(:context_project) { create(:project) } let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/ci/config/external/file/remote_spec.rb b/spec/lib/gitlab/ci/config/external/file/remote_spec.rb index a23cce9b757..ab60ac215ba 100644 --- a/spec/lib/gitlab/ci/config/external/file/remote_spec.rb +++ b/spec/lib/gitlab/ci/config/external/file/remote_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::File::Remote do +RSpec.describe Gitlab::Ci::Config::External::File::Remote do include StubRequests let(:context_params) { { sha: '12345' } } diff --git a/spec/lib/gitlab/ci/config/external/file/template_spec.rb b/spec/lib/gitlab/ci/config/external/file/template_spec.rb index 7ea5aadac52..ad1d93a64a1 100644 --- a/spec/lib/gitlab/ci/config/external/file/template_spec.rb +++ b/spec/lib/gitlab/ci/config/external/file/template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::File::Template do +RSpec.describe Gitlab::Ci::Config::External::File::Template do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let(:context_params) { { project: project, sha: '12345', user: user } } diff --git a/spec/lib/gitlab/ci/config/external/mapper_spec.rb b/spec/lib/gitlab/ci/config/external/mapper_spec.rb index fa358f36527..bf14d8d6b34 100644 --- a/spec/lib/gitlab/ci/config/external/mapper_spec.rb +++ b/spec/lib/gitlab/ci/config/external/mapper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::Mapper do +RSpec.describe Gitlab::Ci::Config::External::Mapper do include StubRequests let_it_be(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/ci/config/external/processor_spec.rb b/spec/lib/gitlab/ci/config/external/processor_spec.rb index 45f646660a7..b2cf36b2597 100644 --- a/spec/lib/gitlab/ci/config/external/processor_spec.rb +++ b/spec/lib/gitlab/ci/config/external/processor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config::External::Processor do +RSpec.describe Gitlab::Ci::Config::External::Processor do include StubRequests let_it_be(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/ci/config/normalizer_spec.rb b/spec/lib/gitlab/ci/config/normalizer_spec.rb index db62fb7524d..d3d165ba00f 100644 --- a/spec/lib/gitlab/ci/config/normalizer_spec.rb +++ b/spec/lib/gitlab/ci/config/normalizer_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Config::Normalizer do +RSpec.describe Gitlab::Ci::Config::Normalizer do let(:job_name) { :rspec } let(:job_config) { { script: 'rspec', parallel: 5, name: 'rspec' } } let(:config) { { job_name => job_config } } diff --git a/spec/lib/gitlab/ci/config_spec.rb b/spec/lib/gitlab/ci/config_spec.rb index 3b65dbe11ec..18be9558829 100644 --- a/spec/lib/gitlab/ci/config_spec.rb +++ b/spec/lib/gitlab/ci/config_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Config do +RSpec.describe Gitlab::Ci::Config do include StubRequests let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/ci/cron_parser_spec.rb b/spec/lib/gitlab/ci/cron_parser_spec.rb index 8f9f3d7fa37..f724825a9cc 100644 --- a/spec/lib/gitlab/ci/cron_parser_spec.rb +++ b/spec/lib/gitlab/ci/cron_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::CronParser do +RSpec.describe Gitlab::Ci::CronParser do shared_examples_for "returns time in the future" do it { is_expected.to be > Time.now } end diff --git a/spec/lib/gitlab/ci/jwt_spec.rb b/spec/lib/gitlab/ci/jwt_spec.rb index f2897708b08..a15f3310dab 100644 --- a/spec/lib/gitlab/ci/jwt_spec.rb +++ b/spec/lib/gitlab/ci/jwt_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Jwt do +RSpec.describe Gitlab::Ci::Jwt do let(:namespace) { build_stubbed(:namespace) } let(:project) { build_stubbed(:project, namespace: namespace) } let(:user) { build_stubbed(:user) } diff --git a/spec/lib/gitlab/ci/mask_secret_spec.rb b/spec/lib/gitlab/ci/mask_secret_spec.rb index 6607aaae399..7b2d6b58518 100644 --- a/spec/lib/gitlab/ci/mask_secret_spec.rb +++ b/spec/lib/gitlab/ci/mask_secret_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::MaskSecret do +RSpec.describe Gitlab::Ci::MaskSecret do subject { described_class } describe '#mask' do diff --git a/spec/lib/gitlab/ci/parsers/accessibility/pa11y_spec.rb b/spec/lib/gitlab/ci/parsers/accessibility/pa11y_spec.rb index 4d87e3b201a..b3edf452f36 100644 --- a/spec/lib/gitlab/ci/parsers/accessibility/pa11y_spec.rb +++ b/spec/lib/gitlab/ci/parsers/accessibility/pa11y_spec.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true -require 'fast_spec_helper' +require 'spec_helper' -describe Gitlab::Ci::Parsers::Accessibility::Pa11y do +RSpec.describe Gitlab::Ci::Parsers::Accessibility::Pa11y do describe '#parse!' do subject { described_class.new.parse!(pa11y, accessibility_report) } @@ -108,7 +108,7 @@ describe Gitlab::Ci::Parsers::Accessibility::Pa11y do it "sets error_message" do expect { subject }.not_to raise_error - expect(accessibility_report.error_message).to include('Pa11y parsing failed') + expect(accessibility_report.error_message).to include('JSON parsing failed') expect(accessibility_report.errors_count).to eq(0) expect(accessibility_report.passes_count).to eq(0) expect(accessibility_report.scans_count).to eq(0) diff --git a/spec/lib/gitlab/ci/parsers/coverage/cobertura_spec.rb b/spec/lib/gitlab/ci/parsers/coverage/cobertura_spec.rb index e97544683db..08a3fbd7867 100644 --- a/spec/lib/gitlab/ci/parsers/coverage/cobertura_spec.rb +++ b/spec/lib/gitlab/ci/parsers/coverage/cobertura_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Parsers::Coverage::Cobertura do +RSpec.describe Gitlab::Ci::Parsers::Coverage::Cobertura do describe '#parse!' do subject { described_class.new.parse!(cobertura, coverage_report) } diff --git a/spec/lib/gitlab/ci/parsers/terraform/tfplan_spec.rb b/spec/lib/gitlab/ci/parsers/terraform/tfplan_spec.rb index fec27c0f31a..f487fccdab7 100644 --- a/spec/lib/gitlab/ci/parsers/terraform/tfplan_spec.rb +++ b/spec/lib/gitlab/ci/parsers/terraform/tfplan_spec.rb @@ -2,39 +2,86 @@ require 'spec_helper' -describe Gitlab::Ci::Parsers::Terraform::Tfplan do +RSpec.describe Gitlab::Ci::Parsers::Terraform::Tfplan do describe '#parse!' do - let_it_be(:artifact) { create(:ci_job_artifact, :terraform) } + let(:artifact) { create(:ci_job_artifact, :terraform) } let(:reports) { Gitlab::Ci::Reports::TerraformReports.new } context 'when data is invalid' do - context 'when there is no data' do - it 'raises an error' do - plan = '{}' + context 'when data is not a JSON file' do + it 'reports an invalid_json_format error' do + plan = 'Not a JSON file' + + expect { subject.parse!(plan, reports, artifact: artifact) }.not_to raise_error + + reports.plans.each do |key, hash_value| + expect(hash_value.keys).to match_array(%w[job_id job_name job_path tf_report_error]) + end - expect { subject.parse!(plan, reports, artifact: artifact) }.to raise_error( - described_class::TfplanParserError + expect(reports.plans).to match( + a_hash_including( + artifact.job.id.to_s => a_hash_including( + 'tf_report_error' => :invalid_json_format + ) + ) ) end end - context 'when data is not a JSON file' do - it 'raises an error' do - plan = { 'create' => 0, 'update' => 1, 'delete' => 0 }.to_s + context 'when JSON is missing a required key' do + it 'reports an invalid_json_keys error' do + plan = '{ "wrong_key": 1 }' + + expect { subject.parse!(plan, reports, artifact: artifact) }.not_to raise_error + + reports.plans.each do |key, hash_value| + expect(hash_value.keys).to match_array(%w[job_id job_name job_path tf_report_error]) + end - expect { subject.parse!(plan, reports, artifact: artifact) }.to raise_error( - described_class::TfplanParserError + expect(reports.plans).to match( + a_hash_including( + artifact.job.id.to_s => a_hash_including( + 'tf_report_error' => :missing_json_keys + ) + ) ) end end - context 'when JSON is missing a required key' do - it 'raises an error' do - plan = '{ "wrong_key": 1 }' + context 'when artifact is invalid' do + it 'reports an :unknown_error' do + expect { subject.parse!('{}', reports, artifact: nil) }.not_to raise_error + + reports.plans.each do |key, hash_value| + expect(hash_value.keys).to match_array(%w[tf_report_error]) + end + + expect(reports.plans).to match( + a_hash_including( + 'failed_tf_plan' => a_hash_including( + 'tf_report_error' => :unknown_error + ) + ) + ) + end + end + + context 'when job is invalid' do + it 'reports an :unknown_error' do + artifact.job_id = nil + expect { subject.parse!('{}', reports, artifact: artifact) }.not_to raise_error - expect { subject.parse!(plan, reports, artifact: artifact) }.to raise_error( - described_class::TfplanParserError + reports.plans.each do |key, hash_value| + expect(hash_value.keys).to match_array(%w[tf_report_error]) + end + + expect(reports.plans).to match( + a_hash_including( + 'failed_tf_plan' => a_hash_including( + 'tf_report_error' => :unknown_error + ) + ) ) end end @@ -47,7 +94,7 @@ describe Gitlab::Ci::Parsers::Terraform::Tfplan do expect { subject.parse!(plan, reports, artifact: artifact) }.not_to raise_error reports.plans.each do |key, hash_value| - expect(hash_value.keys).to match_array(%w[create delete job_name job_path update]) + expect(hash_value.keys).to match_array(%w[create delete job_id job_name job_path update]) end expect(reports.plans).to match( @@ -68,7 +115,7 @@ describe Gitlab::Ci::Parsers::Terraform::Tfplan do expect { subject.parse!(plan, reports, artifact: artifact) }.not_to raise_error reports.plans.each do |key, hash_value| - expect(hash_value.keys).to match_array(%w[create delete job_name job_path update]) + expect(hash_value.keys).to match_array(%w[create delete job_id job_name job_path update]) end expect(reports.plans).to match( diff --git a/spec/lib/gitlab/ci/parsers/test/junit_spec.rb b/spec/lib/gitlab/ci/parsers/test/junit_spec.rb index 7b7ace02bba..1f497dea2bf 100644 --- a/spec/lib/gitlab/ci/parsers/test/junit_spec.rb +++ b/spec/lib/gitlab/ci/parsers/test/junit_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Parsers::Test::Junit do +RSpec.describe Gitlab::Ci::Parsers::Test::Junit do describe '#parse!' do subject { described_class.new.parse!(junit, test_suite, args) } diff --git a/spec/lib/gitlab/ci/parsers_spec.rb b/spec/lib/gitlab/ci/parsers_spec.rb index 0a266e7a206..db9a5775d9f 100644 --- a/spec/lib/gitlab/ci/parsers_spec.rb +++ b/spec/lib/gitlab/ci/parsers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Parsers do +RSpec.describe Gitlab::Ci::Parsers do describe '.fabricate!' do subject { described_class.fabricate!(file_type) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/build/associations_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/build/associations_spec.rb index 542a2462b59..5fa414f5bd1 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/build/associations_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/build/associations_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Build::Associations do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Build::Associations do let(:project) { create(:project, :repository) } let(:user) { create(:user, developer_projects: [project]) } let(:pipeline) { Ci::Pipeline.new } diff --git a/spec/lib/gitlab/ci/pipeline/chain/build_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/build_spec.rb index 094563bd979..6da565a2bf6 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/build_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/build_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Build do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Build do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user, developer_projects: [project]) } let(:pipeline) { Ci::Pipeline.new } diff --git a/spec/lib/gitlab/ci/pipeline/chain/command_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/command_spec.rb index 56707f4e6e4..bc2012e83bd 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/command_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Command do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Command do let_it_be(:project) { create(:project, :repository) } describe '#initialize' do @@ -270,4 +270,29 @@ describe Gitlab::Ci::Pipeline::Chain::Command do it { is_expected. to eq(true) } end end + + describe '#dangling_build?' do + let(:project) { create(:project, :repository) } + let(:command) { described_class.new(project: project, source: source) } + + subject { command.dangling_build? } + + context 'when source is :webide' do + let(:source) { :webide } + + it { is_expected.to eq(true) } + end + + context 'when source is :ondemand_dast_scan' do + let(:source) { :ondemand_dast_scan } + + it { is_expected.to eq(true) } + end + + context 'when source something else' do + let(:source) { :web } + + it { is_expected.to eq(false) } + end + end end diff --git a/spec/lib/gitlab/ci/pipeline/chain/config/content_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/config/content_spec.rb index fc95bb602c2..42ec9ab6f5d 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/config/content_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/config/content_spec.rb @@ -2,10 +2,12 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Config::Content do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Config::Content do let(:project) { create(:project, ci_config_path: ci_config_path) } let(:pipeline) { build(:ci_pipeline, project: project) } - let(:command) { Gitlab::Ci::Pipeline::Chain::Command.new(project: project) } + let(:content) { nil } + let(:source) { :push } + let(:command) { Gitlab::Ci::Pipeline::Chain::Command.new(project: project, content: content, source: source) } subject { described_class.new(pipeline, command) } @@ -141,6 +143,26 @@ describe Gitlab::Ci::Pipeline::Chain::Config::Content do end end + context 'when config is passed as a parameter' do + let(:source) { :ondemand_dast_scan } + let(:ci_config_path) { nil } + let(:content) do + <<~EOY + --- + stages: + - dast + EOY + end + + it 'uses the parameter content' do + subject.perform! + + expect(pipeline.config_source).to eq 'parameter_source' + expect(pipeline.pipeline_config.content).to eq(content) + expect(command.config_content).to eq(content) + end + end + context 'when config is not defined anywhere' do let(:ci_config_path) { nil } diff --git a/spec/lib/gitlab/ci/pipeline/chain/create_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/create_spec.rb index f18ad05a704..d60ecc80a6e 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/create_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/create_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Create do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Create do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/evaluate_workflow_rules_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/evaluate_workflow_rules_spec.rb index 7b76adaf683..4ae51ac8bf9 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/evaluate_workflow_rules_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/evaluate_workflow_rules_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::EvaluateWorkflowRules do +RSpec.describe Gitlab::Ci::Pipeline::Chain::EvaluateWorkflowRules do let(:project) { create(:project) } let(:user) { create(:user) } let(:pipeline) { build(:ci_pipeline, project: project) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/populate_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/populate_spec.rb index 6dab5679e60..8c02121857a 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/populate_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/populate_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Populate do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Populate do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/remove_unwanted_chat_jobs_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/remove_unwanted_chat_jobs_spec.rb index 92eadf5548c..8b9de16ce5f 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/remove_unwanted_chat_jobs_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/remove_unwanted_chat_jobs_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::Ci::Pipeline::Chain::RemoveUnwantedChatJobs do +RSpec.describe ::Gitlab::Ci::Pipeline::Chain::RemoveUnwantedChatJobs do let(:project) { create(:project) } let(:pipeline) do diff --git a/spec/lib/gitlab/ci/pipeline/chain/seed_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/seed_spec.rb index 1e1d5c2a724..f83cd49d780 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/seed_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/seed_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Seed do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Seed do let(:project) { create(:project, :repository) } let(:user) { create(:user, developer_projects: [project]) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/sequence_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/sequence_spec.rb index ea04862ed74..5d20b1b8fda 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/sequence_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/sequence_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Sequence do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Sequence do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/skip_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/skip_spec.rb index 55d6d35340e..e4768f2ef0d 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/skip_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/skip_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Skip do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Skip do let_it_be(:project, reload: true) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:pipeline, reload: true) { create(:ci_pipeline, project: project) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/validate/abilities_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/validate/abilities_spec.rb index 8bf8bdf08ff..ae3270cb9b2 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/validate/abilities_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/validate/abilities_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Validate::Abilities do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Validate::Abilities do let_it_be(:project, reload: true) { create(:project, :repository) } let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/validate/external_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/validate/external_spec.rb index 9a2cf014007..931c62701ce 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/validate/external_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/validate/external_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Validate::External do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Validate::External do let(:project) { create(:project) } let(:user) { create(:user) } let(:pipeline) { build(:ci_empty_pipeline, user: user, project: project) } diff --git a/spec/lib/gitlab/ci/pipeline/chain/validate/repository_spec.rb b/spec/lib/gitlab/ci/pipeline/chain/validate/repository_spec.rb index 83271007ab0..1dc2e0a1822 100644 --- a/spec/lib/gitlab/ci/pipeline/chain/validate/repository_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/chain/validate/repository_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Chain::Validate::Repository do +RSpec.describe Gitlab::Ci::Pipeline::Chain::Validate::Repository do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } let(:pipeline) { build_stubbed(:ci_pipeline) } diff --git a/spec/lib/gitlab/ci/pipeline/duration_spec.rb b/spec/lib/gitlab/ci/pipeline/duration_spec.rb index a4984092f35..e0b4928d7f7 100644 --- a/spec/lib/gitlab/ci/pipeline/duration_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/duration_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Duration do +RSpec.describe Gitlab::Ci::Pipeline::Duration do let(:calculated_duration) { calculate(data) } shared_examples 'calculating duration' do diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/and_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/and_spec.rb index 847d613dba3..6601537a2d3 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/and_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/and_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::And do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::And do let(:left) { double('left', evaluate: nil) } let(:right) { double('right', evaluate: nil) } diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/equals_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/equals_spec.rb index 0e13681a4cf..2bed47f0a87 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/equals_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/equals_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::Equals do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::Equals do let(:left) { double('left') } let(:right) { double('right') } diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/matches_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/matches_spec.rb index a527783ffac..efcea0b0e09 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/matches_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/matches_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require_dependency 're2' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::Matches do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::Matches do let(:left) { double('left') } let(:right) { double('right') } diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_equals_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_equals_spec.rb index a3a48f83b27..a81e1713ef0 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_equals_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_equals_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::NotEquals do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::NotEquals do let(:left) { double('left') } let(:right) { double('right') } diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_matches_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_matches_spec.rb index fb4238ecaf3..f44fe19f86d 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_matches_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/not_matches_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require_dependency 're2' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::NotMatches do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::NotMatches do let(:left) { double('left') } let(:right) { double('right') } diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/null_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/null_spec.rb index 7013c6bacbb..49686d1a9bd 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/null_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/null_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::Null do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::Null do describe '.build' do it 'creates a new instance of the token' do expect(described_class.build('null')) diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/or_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/or_spec.rb index 15505ebc82b..7fe445975eb 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/or_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/or_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::Or do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::Or do let(:left) { double('left', evaluate: nil) } let(:right) { double('right', evaluate: nil) } diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/pattern_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/pattern_spec.rb index 2cc25a07417..1a56a91c471 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/pattern_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/pattern_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::Pattern do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::Pattern do describe '.build' do it 'creates a new instance of the token' do expect(described_class.build('/.*/')) diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/string_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/string_spec.rb index 2a6b90d127f..c6d0d2534a5 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/string_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/string_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::String do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::String do describe '.build' do it 'creates a new instance of the token' do expect(described_class.build('"my string"')) diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexeme/variable_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexeme/variable_spec.rb index 29e26930249..115674edc48 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexeme/variable_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexeme/variable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Lexeme::Variable do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexeme::Variable do describe '.build' do it 'creates a new instance of the token' do expect(described_class.build('$VARIABLE')) diff --git a/spec/lib/gitlab/ci/pipeline/expression/lexer_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/lexer_spec.rb index 2b0cee2d6f2..61c6ced4dac 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/lexer_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/lexer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Lexer do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Lexer do let(:token_class) do Gitlab::Ci::Pipeline::Expression::Token end diff --git a/spec/lib/gitlab/ci/pipeline/expression/parser_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/parser_spec.rb index 10adfa18af6..1704cabfd2e 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/parser_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/parser_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Parser do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Parser do describe '#tree' do context 'when using two operators' do it 'returns a reverse descent parse tree' do diff --git a/spec/lib/gitlab/ci/pipeline/expression/statement_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/statement_spec.rb index 79ee4d07e3a..642d6816030 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/statement_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/statement_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::Ci::Pipeline::Expression::Statement do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Statement do subject do described_class.new(text, variables) end diff --git a/spec/lib/gitlab/ci/pipeline/expression/token_spec.rb b/spec/lib/gitlab/ci/pipeline/expression/token_spec.rb index aa807cecb72..137e38d2ead 100644 --- a/spec/lib/gitlab/ci/pipeline/expression/token_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/expression/token_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Ci::Pipeline::Expression::Token do +RSpec.describe Gitlab::Ci::Pipeline::Expression::Token do let(:value) { '$VARIABLE' } let(:lexeme) { Gitlab::Ci::Pipeline::Expression::Lexeme::Variable } diff --git a/spec/lib/gitlab/ci/pipeline/preloader_spec.rb b/spec/lib/gitlab/ci/pipeline/preloader_spec.rb index 40dfd893465..ae423fa04f9 100644 --- a/spec/lib/gitlab/ci/pipeline/preloader_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/preloader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Preloader do +RSpec.describe Gitlab::Ci::Pipeline::Preloader do let(:stage) { double(:stage) } let(:commit) { double(:commit) } @@ -28,8 +28,9 @@ describe Gitlab::Ci::Pipeline::Preloader do end end - it 'preloads commit authors and number of warnings' do + it 'preloads commit authors, number of warnings and ref commits' do expect(commit).to receive(:lazy_author) + expect(pipeline).to receive(:lazy_ref_commit) expect(pipeline).to receive(:number_of_warnings) expect(stage).to receive(:number_of_warnings) @@ -38,6 +39,7 @@ describe Gitlab::Ci::Pipeline::Preloader do it 'returns original collection' do allow(commit).to receive(:lazy_author) + allow(pipeline).to receive(:lazy_ref_commit) allow(pipeline).to receive(:number_of_warnings) allow(stage).to receive(:number_of_warnings) diff --git a/spec/lib/gitlab/ci/pipeline/seed/build/cache_spec.rb b/spec/lib/gitlab/ci/pipeline/seed/build/cache_spec.rb index f5b43b5aeab..74c014b6408 100644 --- a/spec/lib/gitlab/ci/pipeline/seed/build/cache_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/seed/build/cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Seed::Build::Cache do +RSpec.describe Gitlab::Ci::Pipeline::Seed::Build::Cache do let_it_be(:project) { create(:project, :repository) } let_it_be(:head_sha) { project.repository.head_commit.id } let_it_be(:pipeline) { create(:ci_pipeline, project: project, sha: head_sha) } @@ -134,7 +134,7 @@ describe Gitlab::Ci::Pipeline::Seed::Build::Cache do it_behaves_like 'foo/bar directory key' end - context 'with directories ending in slash star', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/222356' do + context 'with directories ending in slash star' do let(:files) { ['foo/bar/*'] } it_behaves_like 'foo/bar directory key' diff --git a/spec/lib/gitlab/ci/pipeline/seed/build/resource_group_spec.rb b/spec/lib/gitlab/ci/pipeline/seed/build/resource_group_spec.rb index bf6985156d3..8fcc242ba5f 100644 --- a/spec/lib/gitlab/ci/pipeline/seed/build/resource_group_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/seed/build/resource_group_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Seed::Build::ResourceGroup do +RSpec.describe Gitlab::Ci::Pipeline::Seed::Build::ResourceGroup do let_it_be(:project) { create(:project) } let(:job) { build(:ci_build, project: project) } let(:seed) { described_class.new(job, resource_group_key) } diff --git a/spec/lib/gitlab/ci/pipeline/seed/build_spec.rb b/spec/lib/gitlab/ci/pipeline/seed/build_spec.rb index 01f65939da7..2dea554fe56 100644 --- a/spec/lib/gitlab/ci/pipeline/seed/build_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/seed/build_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Seed::Build do +RSpec.describe Gitlab::Ci::Pipeline::Seed::Build do let(:project) { create(:project, :repository) } let(:head_sha) { project.repository.head_commit.id } let(:pipeline) { create(:ci_empty_pipeline, project: project, sha: head_sha) } diff --git a/spec/lib/gitlab/ci/pipeline/seed/deployment_spec.rb b/spec/lib/gitlab/ci/pipeline/seed/deployment_spec.rb index ceb3cb28bc9..1f38c7aec63 100644 --- a/spec/lib/gitlab/ci/pipeline/seed/deployment_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/seed/deployment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Seed::Deployment do +RSpec.describe Gitlab::Ci::Pipeline::Seed::Deployment do let_it_be(:project, refind: true) { create(:project, :repository) } let(:pipeline) do create(:ci_pipeline, project: project, @@ -102,6 +102,19 @@ describe Gitlab::Ci::Pipeline::Seed::Deployment do end end + context 'when job has environment attribute with prepare action' do + let(:attributes) do + { + environment: 'production', + options: { environment: { name: 'production', action: 'prepare' } } + } + end + + it 'returns nothing' do + is_expected.to be_nil + end + end + context 'when job does not have environment attribute' do let(:attributes) { { name: 'test' } } diff --git a/spec/lib/gitlab/ci/pipeline/seed/environment_spec.rb b/spec/lib/gitlab/ci/pipeline/seed/environment_spec.rb index 4c0464e5e7c..0c8a0de2f34 100644 --- a/spec/lib/gitlab/ci/pipeline/seed/environment_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/seed/environment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Seed::Environment do +RSpec.describe Gitlab::Ci::Pipeline::Seed::Environment do let_it_be(:project) { create(:project) } let(:job) { build(:ci_build, project: project) } let(:seed) { described_class.new(job) } diff --git a/spec/lib/gitlab/ci/pipeline/seed/stage_spec.rb b/spec/lib/gitlab/ci/pipeline/seed/stage_spec.rb index 875fd457bd0..4b9db9fa6c6 100644 --- a/spec/lib/gitlab/ci/pipeline/seed/stage_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/seed/stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Pipeline::Seed::Stage do +RSpec.describe Gitlab::Ci::Pipeline::Seed::Stage do let(:project) { create(:project, :repository) } let(:pipeline) { create(:ci_empty_pipeline, project: project) } let(:previous_stages) { [] } diff --git a/spec/lib/gitlab/ci/reports/accessibility_reports_comparer_spec.rb b/spec/lib/gitlab/ci/reports/accessibility_reports_comparer_spec.rb index 31a330f46b1..240ede790e0 100644 --- a/spec/lib/gitlab/ci/reports/accessibility_reports_comparer_spec.rb +++ b/spec/lib/gitlab/ci/reports/accessibility_reports_comparer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::AccessibilityReportsComparer do +RSpec.describe Gitlab::Ci::Reports::AccessibilityReportsComparer do let(:comparer) { described_class.new(base_reports, head_reports) } let(:base_reports) { Gitlab::Ci::Reports::AccessibilityReports.new } let(:head_reports) { Gitlab::Ci::Reports::AccessibilityReports.new } diff --git a/spec/lib/gitlab/ci/reports/accessibility_reports_spec.rb b/spec/lib/gitlab/ci/reports/accessibility_reports_spec.rb index 0dc13b464b1..8c35b2a34cf 100644 --- a/spec/lib/gitlab/ci/reports/accessibility_reports_spec.rb +++ b/spec/lib/gitlab/ci/reports/accessibility_reports_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::AccessibilityReports do +RSpec.describe Gitlab::Ci::Reports::AccessibilityReports do let(:accessibility_report) { described_class.new } let(:url) { 'https://gitlab.com' } let(:data) do diff --git a/spec/lib/gitlab/ci/reports/coverage_reports_spec.rb b/spec/lib/gitlab/ci/reports/coverage_reports_spec.rb index 7cf43ceab32..41ebae863ee 100644 --- a/spec/lib/gitlab/ci/reports/coverage_reports_spec.rb +++ b/spec/lib/gitlab/ci/reports/coverage_reports_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::CoverageReports do +RSpec.describe Gitlab::Ci::Reports::CoverageReports do let(:coverage_report) { described_class.new } it { expect(coverage_report.files).to eq({}) } diff --git a/spec/lib/gitlab/ci/reports/terraform_reports_spec.rb b/spec/lib/gitlab/ci/reports/terraform_reports_spec.rb index bfab30543ed..5e94fe2bb3d 100644 --- a/spec/lib/gitlab/ci/reports/terraform_reports_spec.rb +++ b/spec/lib/gitlab/ci/reports/terraform_reports_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::TerraformReports do +RSpec.describe Gitlab::Ci::Reports::TerraformReports do it 'initializes plans with and empty hash' do expect(subject.plans).to eq({}) end diff --git a/spec/lib/gitlab/ci/reports/test_case_spec.rb b/spec/lib/gitlab/ci/reports/test_case_spec.rb index b5883867983..8882defbd9e 100644 --- a/spec/lib/gitlab/ci/reports/test_case_spec.rb +++ b/spec/lib/gitlab/ci/reports/test_case_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::TestCase do +RSpec.describe Gitlab::Ci::Reports::TestCase do describe '#initialize' do let(:test_case) { described_class.new(params)} diff --git a/spec/lib/gitlab/ci/reports/test_report_summary_spec.rb b/spec/lib/gitlab/ci/reports/test_report_summary_spec.rb new file mode 100644 index 00000000000..70d82851125 --- /dev/null +++ b/spec/lib/gitlab/ci/reports/test_report_summary_spec.rb @@ -0,0 +1,90 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Ci::Reports::TestReportSummary do + let(:build_report_result_1) { build(:ci_build_report_result) } + let(:build_report_result_2) { build(:ci_build_report_result, :with_junit_success) } + let(:test_report_summary) { described_class.new([build_report_result_1, build_report_result_2]) } + + describe '#total' do + subject { test_report_summary.total } + + context 'when test report summary has several build report results' do + it 'returns test suite summary object' do + expect(subject).to be_a_kind_of(Gitlab::Ci::Reports::TestSuiteSummary) + end + end + end + + describe '#total_time' do + subject { test_report_summary.total_time } + + context 'when test report summary has several build report results' do + it 'returns the total' do + expect(subject).to eq(0.84) + end + end + end + + describe '#total_count' do + subject { test_report_summary.total_count } + + context 'when test report summary has several build report results' do + it 'returns the total count' do + expect(subject).to eq(4) + end + end + end + + describe '#success_count' do + subject { test_report_summary.success_count } + + context 'when test suite summary has several build report results' do + it 'returns the total success' do + expect(subject).to eq(2) + end + end + end + + describe '#failed_count' do + subject { test_report_summary.failed_count } + + context 'when test suite summary has several build report results' do + it 'returns the total failed' do + expect(subject).to eq(0) + end + end + end + + describe '#error_count' do + subject { test_report_summary.error_count } + + context 'when test suite summary has several build report results' do + it 'returns the total errored' do + expect(subject).to eq(2) + end + end + end + + describe '#skipped_count' do + subject { test_report_summary.skipped_count } + + context 'when test suite summary has several build report results' do + it 'returns the total skipped' do + expect(subject).to eq(0) + end + end + end + + describe '#test_suites' do + subject { test_report_summary.test_suites } + + context 'when test report summary has several build report results' do + it 'returns test suites grouped by name' do + expect(subject.keys).to eq(["rspec"]) + expect(subject.keys.size).to eq(1) + end + end + end +end diff --git a/spec/lib/gitlab/ci/reports/test_reports_comparer_spec.rb b/spec/lib/gitlab/ci/reports/test_reports_comparer_spec.rb index d731afe1fff..3483dddca3a 100644 --- a/spec/lib/gitlab/ci/reports/test_reports_comparer_spec.rb +++ b/spec/lib/gitlab/ci/reports/test_reports_comparer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::TestReportsComparer do +RSpec.describe Gitlab::Ci::Reports::TestReportsComparer do include TestReportsHelper let(:comparer) { described_class.new(base_reports, head_reports) } diff --git a/spec/lib/gitlab/ci/reports/test_reports_spec.rb b/spec/lib/gitlab/ci/reports/test_reports_spec.rb index e51728496e1..502859852f2 100644 --- a/spec/lib/gitlab/ci/reports/test_reports_spec.rb +++ b/spec/lib/gitlab/ci/reports/test_reports_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::TestReports do +RSpec.describe Gitlab::Ci::Reports::TestReports do include TestReportsHelper let(:test_reports) { described_class.new } diff --git a/spec/lib/gitlab/ci/reports/test_suite_comparer_spec.rb b/spec/lib/gitlab/ci/reports/test_suite_comparer_spec.rb index 2d2179a690b..6bb6771678a 100644 --- a/spec/lib/gitlab/ci/reports/test_suite_comparer_spec.rb +++ b/spec/lib/gitlab/ci/reports/test_suite_comparer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::TestSuiteComparer do +RSpec.describe Gitlab::Ci::Reports::TestSuiteComparer do include TestReportsHelper let(:comparer) { described_class.new(name, base_suite, head_suite) } diff --git a/spec/lib/gitlab/ci/reports/test_suite_spec.rb b/spec/lib/gitlab/ci/reports/test_suite_spec.rb index e0b2593353a..c4c4d2c3704 100644 --- a/spec/lib/gitlab/ci/reports/test_suite_spec.rb +++ b/spec/lib/gitlab/ci/reports/test_suite_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Reports::TestSuite do +RSpec.describe Gitlab::Ci::Reports::TestSuite do include TestReportsHelper let(:test_suite) { described_class.new('Rspec') } @@ -139,6 +139,41 @@ describe Gitlab::Ci::Reports::TestSuite do end end + describe '#+' do + let(:test_suite_2) { described_class.new('Rspec') } + + subject { test_suite + test_suite_2 } + + context 'when adding multiple suites together' do + before do + test_suite.add_test_case(test_case_success) + test_suite.add_test_case(test_case_failed) + end + + it 'returns a new test suite' do + expect(subject).to be_an_instance_of(described_class) + end + + it 'returns the suite name' do + expect(subject.name).to eq('Rspec') + end + + it 'returns the sum for total_time' do + expect(subject.total_time).to eq(3.33) + end + + it 'merges tests cases hash', :aggregate_failures do + test_suite_2.add_test_case(create_test_case_java_success) + + failed_keys = test_suite.test_cases['failed'].keys + success_keys = test_suite.test_cases['success'].keys + test_suite_2.test_cases['success'].keys + + expect(subject.test_cases['failed'].keys).to contain_exactly(*failed_keys) + expect(subject.test_cases['success'].keys).to contain_exactly(*success_keys) + end + end + end + Gitlab::Ci::Reports::TestCase::STATUS_TYPES.each do |status_type| describe "##{status_type}" do subject { test_suite.public_send("#{status_type}") } diff --git a/spec/lib/gitlab/ci/reports/test_suite_summary_spec.rb b/spec/lib/gitlab/ci/reports/test_suite_summary_spec.rb new file mode 100644 index 00000000000..12c96acdcf3 --- /dev/null +++ b/spec/lib/gitlab/ci/reports/test_suite_summary_spec.rb @@ -0,0 +1,89 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Ci::Reports::TestSuiteSummary do + let(:build_report_result_1) { build(:ci_build_report_result) } + let(:build_report_result_2) { build(:ci_build_report_result, :with_junit_success) } + let(:test_suite_summary) { described_class.new([build_report_result_1, build_report_result_2]) } + + describe '#name' do + subject { test_suite_summary.name } + + context 'when test suite summary has several build report results' do + it 'returns the suite name' do + expect(subject).to eq("rspec") + end + end + end + + describe '#build_ids' do + subject { test_suite_summary.build_ids } + + context 'when test suite summary has several build report results' do + it 'returns the build ids' do + expect(subject).to contain_exactly(build_report_result_1.build_id, build_report_result_2.build_id) + end + end + end + + describe '#total_time' do + subject { test_suite_summary.total_time } + + context 'when test suite summary has several build report results' do + it 'returns the total time' do + expect(subject).to eq(0.84) + end + end + end + + describe '#success_count' do + subject { test_suite_summary.success_count } + + context 'when test suite summary has several build report results' do + it 'returns the total success' do + expect(subject).to eq(2) + end + end + end + + describe '#failed_count' do + subject { test_suite_summary.failed_count } + + context 'when test suite summary has several build report results' do + it 'returns the total failed' do + expect(subject).to eq(0) + end + end + end + + describe '#error_count' do + subject { test_suite_summary.error_count } + + context 'when test suite summary has several build report results' do + it 'returns the total errored' do + expect(subject).to eq(2) + end + end + end + + describe '#skipped_count' do + subject { test_suite_summary.skipped_count } + + context 'when test suite summary has several build report results' do + it 'returns the total skipped' do + expect(subject).to eq(0) + end + end + end + + describe '#total_count' do + subject { test_suite_summary.total_count } + + context 'when test suite summary has several build report results' do + it 'returns the total count' do + expect(subject).to eq(4) + end + end + end +end diff --git a/spec/lib/gitlab/ci/status/bridge/factory_spec.rb b/spec/lib/gitlab/ci/status/bridge/factory_spec.rb index 6c67864855d..021b777a0ff 100644 --- a/spec/lib/gitlab/ci/status/bridge/factory_spec.rb +++ b/spec/lib/gitlab/ci/status/bridge/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Bridge::Factory do +RSpec.describe Gitlab::Ci::Status::Bridge::Factory do let(:user) { create(:user) } let(:project) { bridge.project } let(:status) { factory.fabricate! } diff --git a/spec/lib/gitlab/ci/status/build/action_spec.rb b/spec/lib/gitlab/ci/status/build/action_spec.rb index 3aae7e18d6d..de237183feb 100644 --- a/spec/lib/gitlab/ci/status/build/action_spec.rb +++ b/spec/lib/gitlab/ci/status/build/action_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Action do +RSpec.describe Gitlab::Ci::Status::Build::Action do let(:status) { double('core status') } let(:user) { double('user') } diff --git a/spec/lib/gitlab/ci/status/build/cancelable_spec.rb b/spec/lib/gitlab/ci/status/build/cancelable_spec.rb index 3841dae91c7..95920518793 100644 --- a/spec/lib/gitlab/ci/status/build/cancelable_spec.rb +++ b/spec/lib/gitlab/ci/status/build/cancelable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Cancelable do +RSpec.describe Gitlab::Ci::Status::Build::Cancelable do let(:status) { double('core status') } let(:user) { double('user') } diff --git a/spec/lib/gitlab/ci/status/build/canceled_spec.rb b/spec/lib/gitlab/ci/status/build/canceled_spec.rb index 4b43c78f1a7..e30a2211c8f 100644 --- a/spec/lib/gitlab/ci/status/build/canceled_spec.rb +++ b/spec/lib/gitlab/ci/status/build/canceled_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Canceled do +RSpec.describe Gitlab::Ci::Status::Build::Canceled do let(:user) { create(:user) } subject do diff --git a/spec/lib/gitlab/ci/status/build/common_spec.rb b/spec/lib/gitlab/ci/status/build/common_spec.rb index 5114540708f..924ee5ee1a4 100644 --- a/spec/lib/gitlab/ci/status/build/common_spec.rb +++ b/spec/lib/gitlab/ci/status/build/common_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Common do +RSpec.describe Gitlab::Ci::Status::Build::Common do let(:user) { create(:user) } let(:build) { create(:ci_build) } let(:project) { build.project } diff --git a/spec/lib/gitlab/ci/status/build/created_spec.rb b/spec/lib/gitlab/ci/status/build/created_spec.rb index 6e3aa442810..49468674140 100644 --- a/spec/lib/gitlab/ci/status/build/created_spec.rb +++ b/spec/lib/gitlab/ci/status/build/created_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Created do +RSpec.describe Gitlab::Ci::Status::Build::Created do let(:user) { create(:user) } subject do diff --git a/spec/lib/gitlab/ci/status/build/erased_spec.rb b/spec/lib/gitlab/ci/status/build/erased_spec.rb index af9c296da0c..75467cc6b31 100644 --- a/spec/lib/gitlab/ci/status/build/erased_spec.rb +++ b/spec/lib/gitlab/ci/status/build/erased_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Erased do +RSpec.describe Gitlab::Ci::Status::Build::Erased do let(:user) { create(:user) } subject do diff --git a/spec/lib/gitlab/ci/status/build/factory_spec.rb b/spec/lib/gitlab/ci/status/build/factory_spec.rb index 11be17bfc53..21eca97331e 100644 --- a/spec/lib/gitlab/ci/status/build/factory_spec.rb +++ b/spec/lib/gitlab/ci/status/build/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Factory do +RSpec.describe Gitlab::Ci::Status::Build::Factory do let(:user) { create(:user) } let(:project) { build.project } let(:status) { factory.fabricate! } diff --git a/spec/lib/gitlab/ci/status/build/failed_allowed_spec.rb b/spec/lib/gitlab/ci/status/build/failed_allowed_spec.rb index 01500689619..0ff7c3796c0 100644 --- a/spec/lib/gitlab/ci/status/build/failed_allowed_spec.rb +++ b/spec/lib/gitlab/ci/status/build/failed_allowed_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::FailedAllowed do +RSpec.describe Gitlab::Ci::Status::Build::FailedAllowed do let(:status) { double('core status') } let(:user) { double('user') } let(:build) { create(:ci_build, :failed, :allowed_to_fail) } diff --git a/spec/lib/gitlab/ci/status/build/failed_spec.rb b/spec/lib/gitlab/ci/status/build/failed_spec.rb index 78f5214ca81..1d5069fe180 100644 --- a/spec/lib/gitlab/ci/status/build/failed_spec.rb +++ b/spec/lib/gitlab/ci/status/build/failed_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Failed do +RSpec.describe Gitlab::Ci::Status::Build::Failed do let(:build) { create(:ci_build, :script_failure) } let(:status) { double('core status') } let(:user) { double('user') } diff --git a/spec/lib/gitlab/ci/status/build/manual_spec.rb b/spec/lib/gitlab/ci/status/build/manual_spec.rb index bffe2c10d12..78193055139 100644 --- a/spec/lib/gitlab/ci/status/build/manual_spec.rb +++ b/spec/lib/gitlab/ci/status/build/manual_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Manual do +RSpec.describe Gitlab::Ci::Status::Build::Manual do let(:user) { create(:user) } subject do diff --git a/spec/lib/gitlab/ci/status/build/pending_spec.rb b/spec/lib/gitlab/ci/status/build/pending_spec.rb index 64d57954c15..7b695d33877 100644 --- a/spec/lib/gitlab/ci/status/build/pending_spec.rb +++ b/spec/lib/gitlab/ci/status/build/pending_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Pending do +RSpec.describe Gitlab::Ci::Status::Build::Pending do let(:user) { create(:user) } subject do diff --git a/spec/lib/gitlab/ci/status/build/play_spec.rb b/spec/lib/gitlab/ci/status/build/play_spec.rb index bb12a900b55..bb406623d2f 100644 --- a/spec/lib/gitlab/ci/status/build/play_spec.rb +++ b/spec/lib/gitlab/ci/status/build/play_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Play do +RSpec.describe Gitlab::Ci::Status::Build::Play do let(:user) { create(:user) } let(:project) { create(:project, :stubbed_repository) } let(:build) { create(:ci_build, :manual, project: project) } diff --git a/spec/lib/gitlab/ci/status/build/preparing_spec.rb b/spec/lib/gitlab/ci/status/build/preparing_spec.rb index 4d8945845ba..5bb18ac3799 100644 --- a/spec/lib/gitlab/ci/status/build/preparing_spec.rb +++ b/spec/lib/gitlab/ci/status/build/preparing_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Preparing do +RSpec.describe Gitlab::Ci::Status::Build::Preparing do subject do described_class.new(double('subject')) end diff --git a/spec/lib/gitlab/ci/status/build/retried_spec.rb b/spec/lib/gitlab/ci/status/build/retried_spec.rb index fce497d40a1..522228f0a1d 100644 --- a/spec/lib/gitlab/ci/status/build/retried_spec.rb +++ b/spec/lib/gitlab/ci/status/build/retried_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Retried do +RSpec.describe Gitlab::Ci::Status::Build::Retried do let(:build) { create(:ci_build, :retried) } let(:status) { double('core status') } let(:user) { double('user') } diff --git a/spec/lib/gitlab/ci/status/build/retryable_spec.rb b/spec/lib/gitlab/ci/status/build/retryable_spec.rb index 5b0ae315927..cb1cf85169d 100644 --- a/spec/lib/gitlab/ci/status/build/retryable_spec.rb +++ b/spec/lib/gitlab/ci/status/build/retryable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Retryable do +RSpec.describe Gitlab::Ci::Status::Build::Retryable do let(:status) { double('core status') } let(:user) { double('user') } diff --git a/spec/lib/gitlab/ci/status/build/scheduled_spec.rb b/spec/lib/gitlab/ci/status/build/scheduled_spec.rb index 8f87da10815..b0cd1ac4dc5 100644 --- a/spec/lib/gitlab/ci/status/build/scheduled_spec.rb +++ b/spec/lib/gitlab/ci/status/build/scheduled_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Scheduled do +RSpec.describe Gitlab::Ci::Status::Build::Scheduled do let(:user) { create(:user) } let(:project) { create(:project, :stubbed_repository) } let(:build) { create(:ci_build, :scheduled, project: project) } diff --git a/spec/lib/gitlab/ci/status/build/skipped_spec.rb b/spec/lib/gitlab/ci/status/build/skipped_spec.rb index 7ce5142da78..0b998a52a57 100644 --- a/spec/lib/gitlab/ci/status/build/skipped_spec.rb +++ b/spec/lib/gitlab/ci/status/build/skipped_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Skipped do +RSpec.describe Gitlab::Ci::Status::Build::Skipped do let(:user) { create(:user) } subject do diff --git a/spec/lib/gitlab/ci/status/build/stop_spec.rb b/spec/lib/gitlab/ci/status/build/stop_spec.rb index d3e98400a53..7376afe0e83 100644 --- a/spec/lib/gitlab/ci/status/build/stop_spec.rb +++ b/spec/lib/gitlab/ci/status/build/stop_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Stop do +RSpec.describe Gitlab::Ci::Status::Build::Stop do let(:status) { double('core status') } let(:user) { double('user') } diff --git a/spec/lib/gitlab/ci/status/build/unschedule_spec.rb b/spec/lib/gitlab/ci/status/build/unschedule_spec.rb index c18fc3252b4..74002c7d0d7 100644 --- a/spec/lib/gitlab/ci/status/build/unschedule_spec.rb +++ b/spec/lib/gitlab/ci/status/build/unschedule_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Build::Unschedule do +RSpec.describe Gitlab::Ci::Status::Build::Unschedule do let(:status) { double('core status') } let(:user) { double('user') } diff --git a/spec/lib/gitlab/ci/status/canceled_spec.rb b/spec/lib/gitlab/ci/status/canceled_spec.rb index 6cfcea4fdde..a35efae5c57 100644 --- a/spec/lib/gitlab/ci/status/canceled_spec.rb +++ b/spec/lib/gitlab/ci/status/canceled_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Canceled do +RSpec.describe Gitlab::Ci::Status::Canceled do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/composite_spec.rb b/spec/lib/gitlab/ci/status/composite_spec.rb index 8a226b382b0..47bbc4169b6 100644 --- a/spec/lib/gitlab/ci/status/composite_spec.rb +++ b/spec/lib/gitlab/ci/status/composite_spec.rb @@ -2,15 +2,15 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Composite do +RSpec.describe Gitlab::Ci::Status::Composite do let_it_be(:pipeline) { create(:ci_pipeline) } before_all do - @statuses = HasStatus::STATUSES_ENUM.map do |status, idx| + @statuses = Ci::HasStatus::STATUSES_ENUM.map do |status, idx| [status, create(:ci_build, pipeline: pipeline, status: status, importing: true)] end.to_h - @statuses_with_allow_failure = HasStatus::STATUSES_ENUM.map do |status, idx| + @statuses_with_allow_failure = Ci::HasStatus::STATUSES_ENUM.map do |status, idx| [status, create(:ci_build, pipeline: pipeline, status: status, allow_failure: true, importing: true)] end.to_h end @@ -26,7 +26,7 @@ describe Gitlab::Ci::Status::Composite do end shared_examples 'validate all combinations' do |perms| - HasStatus::STATUSES_ENUM.keys.combination(perms).each do |statuses| + Ci::HasStatus::STATUSES_ENUM.keys.combination(perms).each do |statuses| context "with #{statuses.join(",")}" do it_behaves_like 'compares composite with SQL status' do let(:all_statuses) do @@ -38,7 +38,7 @@ describe Gitlab::Ci::Status::Composite do end end - HasStatus::STATUSES_ENUM.each do |allow_failure_status, _| + Ci::HasStatus::STATUSES_ENUM.each do |allow_failure_status, _| context "and allow_failure #{allow_failure_status}" do it_behaves_like 'compares composite with SQL status' do let(:all_statuses) do diff --git a/spec/lib/gitlab/ci/status/created_spec.rb b/spec/lib/gitlab/ci/status/created_spec.rb index aeb41e9cfc3..1ddced923f6 100644 --- a/spec/lib/gitlab/ci/status/created_spec.rb +++ b/spec/lib/gitlab/ci/status/created_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Created do +RSpec.describe Gitlab::Ci::Status::Created do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/extended_spec.rb b/spec/lib/gitlab/ci/status/extended_spec.rb index 8accfc4a2f9..3e1004754ba 100644 --- a/spec/lib/gitlab/ci/status/extended_spec.rb +++ b/spec/lib/gitlab/ci/status/extended_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Extended do +RSpec.describe Gitlab::Ci::Status::Extended do it 'requires subclass to implement matcher' do expect { described_class.matches?(double, double) } .to raise_error(NotImplementedError) diff --git a/spec/lib/gitlab/ci/status/external/common_spec.rb b/spec/lib/gitlab/ci/status/external/common_spec.rb index 983522fa2d6..6de08ce9281 100644 --- a/spec/lib/gitlab/ci/status/external/common_spec.rb +++ b/spec/lib/gitlab/ci/status/external/common_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::External::Common do +RSpec.describe Gitlab::Ci::Status::External::Common do let(:user) { create(:user) } let(:project) { external_status.project } let(:external_target_url) { 'http://example.gitlab.com/status' } diff --git a/spec/lib/gitlab/ci/status/external/factory_spec.rb b/spec/lib/gitlab/ci/status/external/factory_spec.rb index 9c11e42fc5a..a31a11cd14a 100644 --- a/spec/lib/gitlab/ci/status/external/factory_spec.rb +++ b/spec/lib/gitlab/ci/status/external/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::External::Factory do +RSpec.describe Gitlab::Ci::Status::External::Factory do let(:user) { create(:user) } let(:project) { resource.project } let(:status) { factory.fabricate! } @@ -14,7 +14,7 @@ describe Gitlab::Ci::Status::External::Factory do end context 'when external status has a simple core status' do - HasStatus::AVAILABLE_STATUSES.each do |simple_status| + Ci::HasStatus::AVAILABLE_STATUSES.each do |simple_status| context "when core status is #{simple_status}" do let(:resource) do create(:generic_commit_status, status: simple_status, diff --git a/spec/lib/gitlab/ci/status/factory_spec.rb b/spec/lib/gitlab/ci/status/factory_spec.rb index 219eb53d9df..641cb0183d3 100644 --- a/spec/lib/gitlab/ci/status/factory_spec.rb +++ b/spec/lib/gitlab/ci/status/factory_spec.rb @@ -2,13 +2,13 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Factory do +RSpec.describe Gitlab::Ci::Status::Factory do let(:user) { create(:user) } let(:fabricated_status) { factory.fabricate! } let(:factory) { described_class.new(resource, user) } context 'when object has a core status' do - HasStatus::AVAILABLE_STATUSES.each do |simple_status| + Ci::HasStatus::AVAILABLE_STATUSES.each do |simple_status| context "when simple core status is #{simple_status}" do let(:resource) { double('resource', status: simple_status) } diff --git a/spec/lib/gitlab/ci/status/failed_spec.rb b/spec/lib/gitlab/ci/status/failed_spec.rb index 5c7393fc8cf..e8bd728b740 100644 --- a/spec/lib/gitlab/ci/status/failed_spec.rb +++ b/spec/lib/gitlab/ci/status/failed_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Failed do +RSpec.describe Gitlab::Ci::Status::Failed do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/group/common_spec.rb b/spec/lib/gitlab/ci/status/group/common_spec.rb index 35fff30ea9d..2bfd816e45d 100644 --- a/spec/lib/gitlab/ci/status/group/common_spec.rb +++ b/spec/lib/gitlab/ci/status/group/common_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Group::Common do +RSpec.describe Gitlab::Ci::Status::Group::Common do subject do Gitlab::Ci::Status::Core.new(double, double) .extend(described_class) diff --git a/spec/lib/gitlab/ci/status/group/factory_spec.rb b/spec/lib/gitlab/ci/status/group/factory_spec.rb index be76a1d5a65..6267b26aa78 100644 --- a/spec/lib/gitlab/ci/status/group/factory_spec.rb +++ b/spec/lib/gitlab/ci/status/group/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Group::Factory do +RSpec.describe Gitlab::Ci::Status::Group::Factory do it 'inherits from the core factory' do expect(described_class) .to be < Gitlab::Ci::Status::Factory diff --git a/spec/lib/gitlab/ci/status/manual_spec.rb b/spec/lib/gitlab/ci/status/manual_spec.rb index 0839452ec22..a9203438898 100644 --- a/spec/lib/gitlab/ci/status/manual_spec.rb +++ b/spec/lib/gitlab/ci/status/manual_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Manual do +RSpec.describe Gitlab::Ci::Status::Manual do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/pending_spec.rb b/spec/lib/gitlab/ci/status/pending_spec.rb index 5f830e5bb56..0e47b19d9c1 100644 --- a/spec/lib/gitlab/ci/status/pending_spec.rb +++ b/spec/lib/gitlab/ci/status/pending_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Pending do +RSpec.describe Gitlab::Ci::Status::Pending do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/pipeline/blocked_spec.rb b/spec/lib/gitlab/ci/status/pipeline/blocked_spec.rb index 664915ba552..8fd974972e4 100644 --- a/spec/lib/gitlab/ci/status/pipeline/blocked_spec.rb +++ b/spec/lib/gitlab/ci/status/pipeline/blocked_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Pipeline::Blocked do +RSpec.describe Gitlab::Ci::Status::Pipeline::Blocked do let(:pipeline) { double('pipeline') } subject do diff --git a/spec/lib/gitlab/ci/status/pipeline/common_spec.rb b/spec/lib/gitlab/ci/status/pipeline/common_spec.rb index d3251d138b8..575acc48a61 100644 --- a/spec/lib/gitlab/ci/status/pipeline/common_spec.rb +++ b/spec/lib/gitlab/ci/status/pipeline/common_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Pipeline::Common do +RSpec.describe Gitlab::Ci::Status::Pipeline::Common do let(:user) { create(:user) } let(:project) { create(:project, :private) } let(:pipeline) { create(:ci_pipeline, project: project) } diff --git a/spec/lib/gitlab/ci/status/pipeline/delayed_spec.rb b/spec/lib/gitlab/ci/status/pipeline/delayed_spec.rb index aba403de712..1302c2069ff 100644 --- a/spec/lib/gitlab/ci/status/pipeline/delayed_spec.rb +++ b/spec/lib/gitlab/ci/status/pipeline/delayed_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Pipeline::Delayed do +RSpec.describe Gitlab::Ci::Status::Pipeline::Delayed do let(:pipeline) { double('pipeline') } subject do diff --git a/spec/lib/gitlab/ci/status/pipeline/factory_spec.rb b/spec/lib/gitlab/ci/status/pipeline/factory_spec.rb index 838154759cb..a6f23180860 100644 --- a/spec/lib/gitlab/ci/status/pipeline/factory_spec.rb +++ b/spec/lib/gitlab/ci/status/pipeline/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Pipeline::Factory do +RSpec.describe Gitlab::Ci::Status::Pipeline::Factory do let(:user) { create(:user) } let(:project) { pipeline.project } let(:status) { factory.fabricate! } @@ -13,7 +13,7 @@ describe Gitlab::Ci::Status::Pipeline::Factory do end context 'when pipeline has a core status' do - (HasStatus::AVAILABLE_STATUSES - HasStatus::BLOCKED_STATUS).each do |simple_status| + (Ci::HasStatus::AVAILABLE_STATUSES - Ci::HasStatus::BLOCKED_STATUS).each do |simple_status| context "when core status is #{simple_status}" do let(:pipeline) { create(:ci_pipeline, status: simple_status) } diff --git a/spec/lib/gitlab/ci/status/preparing_spec.rb b/spec/lib/gitlab/ci/status/preparing_spec.rb index 33f6bab8d65..6d33eb77560 100644 --- a/spec/lib/gitlab/ci/status/preparing_spec.rb +++ b/spec/lib/gitlab/ci/status/preparing_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Preparing do +RSpec.describe Gitlab::Ci::Status::Preparing do subject do described_class.new(double('subject'), nil) end diff --git a/spec/lib/gitlab/ci/status/running_spec.rb b/spec/lib/gitlab/ci/status/running_spec.rb index 75ff58c5c98..fbc7bfd81b3 100644 --- a/spec/lib/gitlab/ci/status/running_spec.rb +++ b/spec/lib/gitlab/ci/status/running_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Running do +RSpec.describe Gitlab::Ci::Status::Running do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/scheduled_spec.rb b/spec/lib/gitlab/ci/status/scheduled_spec.rb index a0374e1a87b..4a1dae937ca 100644 --- a/spec/lib/gitlab/ci/status/scheduled_spec.rb +++ b/spec/lib/gitlab/ci/status/scheduled_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Scheduled do +RSpec.describe Gitlab::Ci::Status::Scheduled do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/skipped_spec.rb b/spec/lib/gitlab/ci/status/skipped_spec.rb index 7f68d4a2fa9..f402bbe5221 100644 --- a/spec/lib/gitlab/ci/status/skipped_spec.rb +++ b/spec/lib/gitlab/ci/status/skipped_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Skipped do +RSpec.describe Gitlab::Ci::Status::Skipped do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/stage/common_spec.rb b/spec/lib/gitlab/ci/status/stage/common_spec.rb index 26ff0e901fd..bbd2ce6c83b 100644 --- a/spec/lib/gitlab/ci/status/stage/common_spec.rb +++ b/spec/lib/gitlab/ci/status/stage/common_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Stage::Common do +RSpec.describe Gitlab::Ci::Status::Stage::Common do let(:user) { create(:user) } let(:project) { create(:project) } let(:pipeline) { create(:ci_empty_pipeline, project: project) } diff --git a/spec/lib/gitlab/ci/status/stage/factory_spec.rb b/spec/lib/gitlab/ci/status/stage/factory_spec.rb index 317756ea13c..e0f5531f370 100644 --- a/spec/lib/gitlab/ci/status/stage/factory_spec.rb +++ b/spec/lib/gitlab/ci/status/stage/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Stage::Factory do +RSpec.describe Gitlab::Ci::Status::Stage::Factory do let(:user) { create(:user) } let(:project) { create(:project) } let(:pipeline) { create(:ci_empty_pipeline, project: project) } @@ -24,7 +24,7 @@ describe Gitlab::Ci::Status::Stage::Factory do end context 'when stage has a core status' do - (HasStatus::AVAILABLE_STATUSES - %w(manual skipped scheduled)).each do |core_status| + (Ci::HasStatus::AVAILABLE_STATUSES - %w(manual skipped scheduled)).each do |core_status| context "when core status is #{core_status}" do before do create(:ci_build, pipeline: pipeline, stage: 'test', status: core_status) @@ -68,7 +68,7 @@ describe Gitlab::Ci::Status::Stage::Factory do end context 'when stage has manual builds' do - (HasStatus::BLOCKED_STATUS + ['skipped']).each do |core_status| + (Ci::HasStatus::BLOCKED_STATUS + ['skipped']).each do |core_status| context "when status is #{core_status}" do before do create(:ci_build, pipeline: pipeline, stage: 'test', status: core_status) diff --git a/spec/lib/gitlab/ci/status/stage/play_manual_spec.rb b/spec/lib/gitlab/ci/status/stage/play_manual_spec.rb index bdcbfed918f..25b79ff2099 100644 --- a/spec/lib/gitlab/ci/status/stage/play_manual_spec.rb +++ b/spec/lib/gitlab/ci/status/stage/play_manual_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Stage::PlayManual do +RSpec.describe Gitlab::Ci::Status::Stage::PlayManual do let(:stage) { double('stage') } let(:play_manual) { described_class.new(stage) } diff --git a/spec/lib/gitlab/ci/status/success_spec.rb b/spec/lib/gitlab/ci/status/success_spec.rb index d4b3a9f12cc..2d1c50448d4 100644 --- a/spec/lib/gitlab/ci/status/success_spec.rb +++ b/spec/lib/gitlab/ci/status/success_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::Success do +RSpec.describe Gitlab::Ci::Status::Success do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/status/success_warning_spec.rb b/spec/lib/gitlab/ci/status/success_warning_spec.rb index af952011e21..86b826ad272 100644 --- a/spec/lib/gitlab/ci/status/success_warning_spec.rb +++ b/spec/lib/gitlab/ci/status/success_warning_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::SuccessWarning do +RSpec.describe Gitlab::Ci::Status::SuccessWarning do let(:status) { double('status') } subject do diff --git a/spec/lib/gitlab/ci/status/waiting_for_resource_spec.rb b/spec/lib/gitlab/ci/status/waiting_for_resource_spec.rb index ed00dac8560..de18198c6c2 100644 --- a/spec/lib/gitlab/ci/status/waiting_for_resource_spec.rb +++ b/spec/lib/gitlab/ci/status/waiting_for_resource_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Status::WaitingForResource do +RSpec.describe Gitlab::Ci::Status::WaitingForResource do subject do described_class.new(double('subject'), double('user')) end diff --git a/spec/lib/gitlab/ci/templates/Jobs/build_gitlab_ci_yaml_spec.rb b/spec/lib/gitlab/ci/templates/Jobs/build_gitlab_ci_yaml_spec.rb index b2a9e3f5cf4..4f8faa5ddb1 100644 --- a/spec/lib/gitlab/ci/templates/Jobs/build_gitlab_ci_yaml_spec.rb +++ b/spec/lib/gitlab/ci/templates/Jobs/build_gitlab_ci_yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Jobs/Build.gitlab-ci.yml' do +RSpec.describe 'Jobs/Build.gitlab-ci.yml' do subject(:template) { Gitlab::Template::GitlabCiYmlTemplate.find('Jobs/Build') } describe 'the created pipeline' do diff --git a/spec/lib/gitlab/ci/templates/Jobs/code_quality_gitlab_ci_yaml_spec.rb b/spec/lib/gitlab/ci/templates/Jobs/code_quality_gitlab_ci_yaml_spec.rb index 9c5b2fd5099..e685ad3b46e 100644 --- a/spec/lib/gitlab/ci/templates/Jobs/code_quality_gitlab_ci_yaml_spec.rb +++ b/spec/lib/gitlab/ci/templates/Jobs/code_quality_gitlab_ci_yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Jobs/Code-Quality.gitlab-ci.yml' do +RSpec.describe 'Jobs/Code-Quality.gitlab-ci.yml' do subject(:template) { Gitlab::Template::GitlabCiYmlTemplate.find('Jobs/Code-Quality') } describe 'the created pipeline' do diff --git a/spec/lib/gitlab/ci/templates/Jobs/deploy_gitlab_ci_yaml_spec.rb b/spec/lib/gitlab/ci/templates/Jobs/deploy_gitlab_ci_yaml_spec.rb index a6ae23c85d3..ea9bd5bd02c 100644 --- a/spec/lib/gitlab/ci/templates/Jobs/deploy_gitlab_ci_yaml_spec.rb +++ b/spec/lib/gitlab/ci/templates/Jobs/deploy_gitlab_ci_yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Jobs/Deploy.gitlab-ci.yml' do +RSpec.describe 'Jobs/Deploy.gitlab-ci.yml' do subject(:template) do <<~YAML stages: diff --git a/spec/lib/gitlab/ci/templates/Jobs/test_gitlab_ci_yaml_spec.rb b/spec/lib/gitlab/ci/templates/Jobs/test_gitlab_ci_yaml_spec.rb index 2186bf038eb..f475785be98 100644 --- a/spec/lib/gitlab/ci/templates/Jobs/test_gitlab_ci_yaml_spec.rb +++ b/spec/lib/gitlab/ci/templates/Jobs/test_gitlab_ci_yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Jobs/Test.gitlab-ci.yml' do +RSpec.describe 'Jobs/Test.gitlab-ci.yml' do subject(:template) { Gitlab::Template::GitlabCiYmlTemplate.find('Jobs/Test') } describe 'the created pipeline' do diff --git a/spec/lib/gitlab/ci/templates/Jobs/browser_performance_testing_gitlab_ci_yaml_spec.rb b/spec/lib/gitlab/ci/templates/Verify/load_performance_testing_gitlab_ci_yaml_spec.rb index 54c3500b0a0..9711df55226 100644 --- a/spec/lib/gitlab/ci/templates/Jobs/browser_performance_testing_gitlab_ci_yaml_spec.rb +++ b/spec/lib/gitlab/ci/templates/Verify/load_performance_testing_gitlab_ci_yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Jobs/Browser-Performance-Testing.gitlab-ci.yml' do +RSpec.describe 'Verify/Load-Performance-Testing.gitlab-ci.yml' do subject(:template) do <<~YAML stages: @@ -10,7 +10,7 @@ describe 'Jobs/Browser-Performance-Testing.gitlab-ci.yml' do - performance include: - - template: 'Jobs/Browser-Performance-Testing.gitlab-ci.yml' + - template: 'Verify/Load-Performance-Testing.gitlab-ci.yml' placeholder: script: @@ -20,11 +20,7 @@ describe 'Jobs/Browser-Performance-Testing.gitlab-ci.yml' do describe 'the created pipeline' do let(:user) { create(:admin) } - let(:project) do - create(:project, :repository, variables: [ - build(:ci_variable, key: 'CI_KUBERNETES_ACTIVE', value: 'true') - ]) - end + let(:project) { create(:project, :repository) } let(:default_branch) { 'master' } let(:pipeline_ref) { default_branch } @@ -43,32 +39,26 @@ describe 'Jobs/Browser-Performance-Testing.gitlab-ci.yml' do expect(pipeline.errors).to be_empty end - shared_examples_for 'performance job on tag or branch' do + shared_examples_for 'load_performance job on tag or branch' do it 'by default' do - expect(build_names).to include('performance') - end - - it 'when PERFORMANCE_DISABLED' do - create(:ci_variable, project: project, key: 'PERFORMANCE_DISABLED', value: '1') - - expect(build_names).not_to include('performance') + expect(build_names).to include('load_performance') end end context 'on master' do - it_behaves_like 'performance job on tag or branch' + it_behaves_like 'load_performance job on tag or branch' end context 'on another branch' do let(:pipeline_ref) { 'feature' } - it_behaves_like 'performance job on tag or branch' + it_behaves_like 'load_performance job on tag or branch' end context 'on tag' do let(:pipeline_ref) { 'v1.0.0' } - it_behaves_like 'performance job on tag or branch' + it_behaves_like 'load_performance job on tag or branch' end context 'on merge request' do diff --git a/spec/lib/gitlab/ci/templates/auto_devops_gitlab_ci_yaml_spec.rb b/spec/lib/gitlab/ci/templates/auto_devops_gitlab_ci_yaml_spec.rb index af6ec25b9d6..4d90e7ca9e6 100644 --- a/spec/lib/gitlab/ci/templates/auto_devops_gitlab_ci_yaml_spec.rb +++ b/spec/lib/gitlab/ci/templates/auto_devops_gitlab_ci_yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Auto-DevOps.gitlab-ci.yml' do +RSpec.describe 'Auto-DevOps.gitlab-ci.yml' do subject(:template) { Gitlab::Template::GitlabCiYmlTemplate.find('Auto-DevOps') } describe 'the created pipeline' do @@ -37,6 +37,7 @@ describe 'Auto-DevOps.gitlab-ci.yml' do context 'when the project is set for deployment to AWS' do let(:platform_value) { 'ECS' } + let(:review_prod_build_names) { build_names.select {|n| n.include?('review') || n.include?('production')} } before do create(:ci_variable, project: project, key: 'AUTO_DEVOPS_PLATFORM_TARGET', value: platform_value) @@ -67,8 +68,15 @@ describe 'Auto-DevOps.gitlab-ci.yml' do end it 'creates an ECS deployment job for production only' do - expect(build_names).not_to include('review_ecs') - expect(build_names).to include('production_ecs') + expect(review_prod_build_names).to contain_exactly('production_ecs') + end + + context 'with FARGATE as a launch type' do + let(:platform_value) { 'FARGATE' } + + it 'creates a FARGATE deployment job for production only' do + expect(review_prod_build_names).to contain_exactly('production_fargate') + end end context 'and we are not on the default branch' do @@ -79,15 +87,22 @@ describe 'Auto-DevOps.gitlab-ci.yml' do project.repository.create_branch(pipeline_branch) end - it_behaves_like 'no ECS job when AUTO_DEVOPS_PLATFORM_TARGET is not present' do - let(:job_name) { 'review_ecs' } + %w(review_ecs review_fargate).each do |job| + it_behaves_like 'no ECS job when AUTO_DEVOPS_PLATFORM_TARGET is not present' do + let(:job_name) { job } + end end it 'creates an ECS deployment job for review only' do - expect(build_names).to include('review_ecs') - expect(build_names).not_to include('production_ecs') - expect(build_names).not_to include('review') - expect(build_names).not_to include('production') + expect(review_prod_build_names).to contain_exactly('review_ecs') + end + + context 'with FARGATE as a launch type' do + let(:platform_value) { 'FARGATE' } + + it 'creates an FARGATE deployment job for review only' do + expect(review_prod_build_names).to contain_exactly('review_fargate') + end end end @@ -190,6 +205,7 @@ describe 'Auto-DevOps.gitlab-ci.yml' do 'Buildpack' | { 'README.md' => '' } | { 'BUILDPACK_URL' => 'http://example.com' } | %w(build test) | %w() 'Explicit set' | { 'README.md' => '' } | { 'AUTO_DEVOPS_EXPLICITLY_ENABLED' => '1' } | %w(build test) | %w() 'Explicit unset' | { 'README.md' => '' } | { 'AUTO_DEVOPS_EXPLICITLY_ENABLED' => '0' } | %w() | %w(build test) + 'DOCKERFILE_PATH' | { 'README.md' => '' } | { 'DOCKERFILE_PATH' => 'Docker.file' } | %w(build test) | %w() 'Dockerfile' | { 'Dockerfile' => '' } | {} | %w(build test) | %w() 'Clojure' | { 'project.clj' => '' } | {} | %w(build test) | %w() 'Go modules' | { 'go.mod' => '' } | {} | %w(build test) | %w() diff --git a/spec/lib/gitlab/ci/templates/managed_cluster_applications_gitlab_ci_yaml_spec.rb b/spec/lib/gitlab/ci/templates/managed_cluster_applications_gitlab_ci_yaml_spec.rb index 2a6314755ef..0e458e01a2c 100644 --- a/spec/lib/gitlab/ci/templates/managed_cluster_applications_gitlab_ci_yaml_spec.rb +++ b/spec/lib/gitlab/ci/templates/managed_cluster_applications_gitlab_ci_yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Managed-Cluster-Applications.gitlab-ci.yml' do +RSpec.describe 'Managed-Cluster-Applications.gitlab-ci.yml' do subject(:template) { Gitlab::Template::GitlabCiYmlTemplate.find('Managed-Cluster-Applications') } describe 'the created pipeline' do diff --git a/spec/lib/gitlab/ci/templates/templates_spec.rb b/spec/lib/gitlab/ci/templates/templates_spec.rb index bc3d5b89220..def4d1b3bf6 100644 --- a/spec/lib/gitlab/ci/templates/templates_spec.rb +++ b/spec/lib/gitlab/ci/templates/templates_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'CI YML Templates' do +RSpec.describe 'CI YML Templates' do subject { Gitlab::Ci::YamlProcessor.new(content) } let(:all_templates) { Gitlab::Template::GitlabCiYmlTemplate.all.map(&:full_name) } diff --git a/spec/lib/gitlab/ci/trace/chunked_io_spec.rb b/spec/lib/gitlab/ci/trace/chunked_io_spec.rb index 92b3e5562a9..a2903391c6f 100644 --- a/spec/lib/gitlab/ci/trace/chunked_io_spec.rb +++ b/spec/lib/gitlab/ci/trace/chunked_io_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Trace::ChunkedIO, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::Ci::Trace::ChunkedIO, :clean_gitlab_redis_cache do include ChunkedIOHelpers let_it_be(:build) { create(:ci_build, :running) } diff --git a/spec/lib/gitlab/ci/trace/section_parser_spec.rb b/spec/lib/gitlab/ci/trace/section_parser_spec.rb index 24ce4d34411..b6bb52a5c06 100644 --- a/spec/lib/gitlab/ci/trace/section_parser_spec.rb +++ b/spec/lib/gitlab/ci/trace/section_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Trace::SectionParser do +RSpec.describe Gitlab::Ci::Trace::SectionParser do def lines_with_pos(text) pos = 0 StringIO.new(text).each_line do |line| diff --git a/spec/lib/gitlab/ci/trace/stream_spec.rb b/spec/lib/gitlab/ci/trace/stream_spec.rb index ea79073840d..568c10bbac2 100644 --- a/spec/lib/gitlab/ci/trace/stream_spec.rb +++ b/spec/lib/gitlab/ci/trace/stream_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Trace::Stream, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::Ci::Trace::Stream, :clean_gitlab_redis_cache do let_it_be(:build) { create(:ci_build, :running) } before do diff --git a/spec/lib/gitlab/ci/trace_spec.rb b/spec/lib/gitlab/ci/trace_spec.rb index 574c2b73722..85edf27d3e7 100644 --- a/spec/lib/gitlab/ci/trace_spec.rb +++ b/spec/lib/gitlab/ci/trace_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Trace, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::Ci::Trace, :clean_gitlab_redis_shared_state do let(:build) { create(:ci_build) } let(:trace) { described_class.new(build) } diff --git a/spec/lib/gitlab/ci/variables/collection/item_spec.rb b/spec/lib/gitlab/ci/variables/collection/item_spec.rb index 1bdca753cd3..eba2f29836d 100644 --- a/spec/lib/gitlab/ci/variables/collection/item_spec.rb +++ b/spec/lib/gitlab/ci/variables/collection/item_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Variables::Collection::Item do +RSpec.describe Gitlab::Ci::Variables::Collection::Item do let(:variable_key) { 'VAR' } let(:variable_value) { 'something' } let(:expected_value) { variable_value } diff --git a/spec/lib/gitlab/ci/variables/collection_spec.rb b/spec/lib/gitlab/ci/variables/collection_spec.rb index 59b9f7d4fb9..ac84313ad9f 100644 --- a/spec/lib/gitlab/ci/variables/collection_spec.rb +++ b/spec/lib/gitlab/ci/variables/collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Ci::Variables::Collection do +RSpec.describe Gitlab::Ci::Variables::Collection do describe '.new' do it 'can be initialized with an array' do variable = { key: 'VAR', value: 'value', public: true, masked: false } diff --git a/spec/lib/gitlab/ci/yaml_processor_spec.rb b/spec/lib/gitlab/ci/yaml_processor_spec.rb index 1668149d8f5..5c6d748d66c 100644 --- a/spec/lib/gitlab/ci/yaml_processor_spec.rb +++ b/spec/lib/gitlab/ci/yaml_processor_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' module Gitlab module Ci - describe YamlProcessor do + RSpec.describe YamlProcessor do include StubRequests subject { described_class.new(config, user: nil) } @@ -435,6 +435,153 @@ module Gitlab end end + describe '#warnings' do + before do + stub_feature_flags(ci_raise_job_rules_without_workflow_rules_warning: true) + end + + context 'when a warning is raised in a given entry' do + let(:config) do + <<-EOYML + rspec: + script: rspec + rules: + - if: '$VAR == "value"' + EOYML + end + + it 'is propagated all the way up to the processor' do + expect(subject.warnings).to contain_exactly('jobs:rspec uses `rules` without defining `workflow:rules`') + end + end + + context 'when a warning is raised together with errors' do + let(:config) do + <<-EOYML + rspec: + script: rspec + rules: + - if: '$VAR == "value"' + invalid: + script: echo + artifacts: + - wrong_key: value + EOYML + end + + it 'is propagated all the way up into the raised exception' do + expect { subject }.to raise_error do |error| + expect(error).to be_a(described_class::ValidationError) + expect(error.message).to eq('jobs:invalid:artifacts config should be a hash') + expect(error.warnings).to contain_exactly('jobs:rspec uses `rules` without defining `workflow:rules`') + end + end + end + + context 'when error is raised before composing the config' do + let(:config) do + <<-EOYML + include: unknown/file.yml + rspec: + script: rspec + rules: + - if: '$VAR == "value"' + EOYML + end + + it 'raises an exception with empty warnings array' do + expect { subject }.to raise_error do |error| + expect(error).to be_a(described_class::ValidationError) + expect(error.message).to eq('Local file `unknown/file.yml` does not have project!') + expect(error.warnings).to be_empty + end + end + end + + context 'when error is raised after composing the config with warnings' do + shared_examples 'has warnings and expected error' do |error_message| + it 'raises an exception including warnings' do + expect { subject }.to raise_error do |error| + expect(error).to be_a(described_class::ValidationError) + expect(error.message).to match(error_message) + expect(error.warnings).to be_present + end + end + end + + context 'when stage does not exist' do + let(:config) do + <<-EOYML + rspec: + stage: custom_stage + script: rspec + rules: + - if: '$VAR == "value"' + EOYML + end + + it_behaves_like 'has warnings and expected error', /rspec job: chosen stage does not exist/ + end + + context 'job dependency does not exist' do + let(:config) do + <<-EOYML + build: + stage: build + script: echo + rules: + - if: '$VAR == "value"' + test: + stage: test + script: echo + needs: [unknown_job] + EOYML + end + + it_behaves_like 'has warnings and expected error', /test job: undefined need: unknown_job/ + end + + context 'job dependency defined in later stage' do + let(:config) do + <<-EOYML + build: + stage: build + script: echo + needs: [test] + rules: + - if: '$VAR == "value"' + test: + stage: test + script: echo + EOYML + end + + it_behaves_like 'has warnings and expected error', /build job: need test is not defined in prior stages/ + end + end + + context 'when feature flag is disabled' do + before do + stub_feature_flags(ci_raise_job_rules_without_workflow_rules_warning: false) + end + + context 'job rules used without workflow rules' do + let(:config) do + <<-EOYML + rspec: + script: rspec + rules: + - if: '$VAR == "value"' + EOYML + end + + it 'does not raise the warning' do + expect(subject.warnings).to be_empty + end + end + end + end + describe 'only / except policies validations' do context 'when `only` has an invalid value' do let(:config) { { rspec: { script: "rspec", type: "test", only: only } } } @@ -1397,6 +1544,9 @@ module Gitlab tag_name: "$CI_COMMIT_TAG", name: "Release $CI_TAG_NAME", description: "./release_changelog.txt", + ref: 'b3235930aa443112e639f941c69c578912189bdd', + released_at: '2019-03-15T08:00:00Z', + milestones: %w[m1 m2 m3], assets: { links: [ { @@ -2514,7 +2664,7 @@ module Gitlab it 'returns errors and empty configuration' do expect(subject.valid?).to eq(false) expect(subject.errors).to eq(['Invalid configuration format']) - expect(subject.content).to be_blank + expect(subject.config).to be_blank end end @@ -2524,7 +2674,7 @@ module Gitlab it 'returns errors and empty configuration' do expect(subject.valid?).to eq(false) expect(subject.errors).to eq(['jobs:rspec:tags config should be an array of strings']) - expect(subject.content).to be_blank + expect(subject.config).to be_blank end end @@ -2536,7 +2686,7 @@ module Gitlab expect(subject.errors).to contain_exactly( 'jobs:rspec config contains unknown keys: bad_tags', 'jobs:rspec rules should be an array of hashes') - expect(subject.content).to be_blank + expect(subject.config).to be_blank end end @@ -2546,7 +2696,7 @@ module Gitlab it 'returns errors and empty configuration' do expect(subject.valid?).to eq(false) expect(subject.errors).to eq(['Please provide content of .gitlab-ci.yml']) - expect(subject.content).to be_blank + expect(subject.config).to be_blank end end @@ -2556,7 +2706,7 @@ module Gitlab it 'returns errors and empty configuration' do expect(subject.valid?).to eq(false) expect(subject.errors).to eq(['Unknown alias: bad_alias']) - expect(subject.content).to be_blank + expect(subject.config).to be_blank end end @@ -2566,7 +2716,7 @@ module Gitlab it 'returns errors and empty configuration' do expect(subject.valid?).to eq(true) expect(subject.errors).to be_empty - expect(subject.content).to be_present + expect(subject.config).to be_present end end end diff --git a/spec/lib/gitlab/ci_access_spec.rb b/spec/lib/gitlab/ci_access_spec.rb index 3c68d209eb6..9b573c6eb7a 100644 --- a/spec/lib/gitlab/ci_access_spec.rb +++ b/spec/lib/gitlab/ci_access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CiAccess do +RSpec.describe Gitlab::CiAccess do let(:access) { described_class.new } describe '#can_do_action?' do diff --git a/spec/lib/gitlab/class_attributes_spec.rb b/spec/lib/gitlab/class_attributes_spec.rb new file mode 100644 index 00000000000..f8766f20495 --- /dev/null +++ b/spec/lib/gitlab/class_attributes_spec.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true +require 'fast_spec_helper' + +RSpec.describe Gitlab::ClassAttributes do + let(:klass) do + Class.new do + include Gitlab::ClassAttributes + + def self.get_attribute(name) + get_class_attribute(name) + end + + def self.set_attribute(name, value) + class_attributes[name] = value + end + end + end + + let(:subclass) { Class.new(klass) } + + describe ".get_class_attribute" do + it "returns values set on the class" do + klass.set_attribute(:foo, :bar) + + expect(klass.get_attribute(:foo)).to eq(:bar) + end + + it "returns values set on a superclass" do + klass.set_attribute(:foo, :bar) + + expect(subclass.get_attribute(:foo)).to eq(:bar) + end + + it "returns values from the subclass over attributes from a superclass" do + klass.set_attribute(:foo, :baz) + subclass.set_attribute(:foo, :bar) + + expect(subclass.get_attribute(:foo)).to eq(:bar) + end + end +end diff --git a/spec/lib/gitlab/cleanup/orphan_job_artifact_files_batch_spec.rb b/spec/lib/gitlab/cleanup/orphan_job_artifact_files_batch_spec.rb index 4d8edfeac80..d03d4f64a0f 100644 --- a/spec/lib/gitlab/cleanup/orphan_job_artifact_files_batch_spec.rb +++ b/spec/lib/gitlab/cleanup/orphan_job_artifact_files_batch_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cleanup::OrphanJobArtifactFilesBatch do +RSpec.describe Gitlab::Cleanup::OrphanJobArtifactFilesBatch do let(:batch_size) { 10 } let(:dry_run) { true } diff --git a/spec/lib/gitlab/cleanup/orphan_job_artifact_files_spec.rb b/spec/lib/gitlab/cleanup/orphan_job_artifact_files_spec.rb index 966c4c8b2fb..8a7425a4156 100644 --- a/spec/lib/gitlab/cleanup/orphan_job_artifact_files_spec.rb +++ b/spec/lib/gitlab/cleanup/orphan_job_artifact_files_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cleanup::OrphanJobArtifactFiles do +RSpec.describe Gitlab::Cleanup::OrphanJobArtifactFiles do let(:null_logger) { Logger.new('/dev/null') } subject(:cleanup) { described_class.new(logger: null_logger) } diff --git a/spec/lib/gitlab/cleanup/orphan_lfs_file_references_spec.rb b/spec/lib/gitlab/cleanup/orphan_lfs_file_references_spec.rb index 01cc0b30784..47b2cf5dc4a 100644 --- a/spec/lib/gitlab/cleanup/orphan_lfs_file_references_spec.rb +++ b/spec/lib/gitlab/cleanup/orphan_lfs_file_references_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cleanup::OrphanLfsFileReferences do +RSpec.describe Gitlab::Cleanup::OrphanLfsFileReferences do let(:null_logger) { Logger.new('/dev/null') } let(:project) { create(:project, :repository, lfs_enabled: true) } let(:lfs_object) { create(:lfs_object) } diff --git a/spec/lib/gitlab/cleanup/project_uploads_spec.rb b/spec/lib/gitlab/cleanup/project_uploads_spec.rb index d1e3a73686e..05d744d95e2 100644 --- a/spec/lib/gitlab/cleanup/project_uploads_spec.rb +++ b/spec/lib/gitlab/cleanup/project_uploads_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cleanup::ProjectUploads do +RSpec.describe Gitlab::Cleanup::ProjectUploads do subject { described_class.new(logger: logger) } let(:logger) { double(:logger) } diff --git a/spec/lib/gitlab/cleanup/remote_uploads_spec.rb b/spec/lib/gitlab/cleanup/remote_uploads_spec.rb index 35642cd6e50..1752608f844 100644 --- a/spec/lib/gitlab/cleanup/remote_uploads_spec.rb +++ b/spec/lib/gitlab/cleanup/remote_uploads_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Cleanup::RemoteUploads do +RSpec.describe Gitlab::Cleanup::RemoteUploads do context 'when object_storage is enabled' do let(:connection) { double } let(:directory) { double } diff --git a/spec/lib/gitlab/closing_issue_extractor_spec.rb b/spec/lib/gitlab/closing_issue_extractor_spec.rb index 4e1bf2840dc..f2bc6390032 100644 --- a/spec/lib/gitlab/closing_issue_extractor_spec.rb +++ b/spec/lib/gitlab/closing_issue_extractor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ClosingIssueExtractor do +RSpec.describe Gitlab::ClosingIssueExtractor do let(:project) { create(:project) } let(:project2) { create(:project) } let(:forked_project) { Projects::ForkService.new(project, project2.creator).execute } diff --git a/spec/lib/gitlab/cluster/mixins/puma_cluster_spec.rb b/spec/lib/gitlab/cluster/mixins/puma_cluster_spec.rb index 864529a6bf6..5b69b34d04b 100644 --- a/spec/lib/gitlab/cluster/mixins/puma_cluster_spec.rb +++ b/spec/lib/gitlab/cluster/mixins/puma_cluster_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' # For easier debugging set `PUMA_DEBUG=1` -describe Gitlab::Cluster::Mixins::PumaCluster do +RSpec.describe Gitlab::Cluster::Mixins::PumaCluster do before do stub_const('PUMA_STARTUP_TIMEOUT', 30) end diff --git a/spec/lib/gitlab/cluster/mixins/unicorn_http_server_spec.rb b/spec/lib/gitlab/cluster/mixins/unicorn_http_server_spec.rb index 3965eb722a0..0aaca0a79c2 100644 --- a/spec/lib/gitlab/cluster/mixins/unicorn_http_server_spec.rb +++ b/spec/lib/gitlab/cluster/mixins/unicorn_http_server_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' # For easier debugging set `UNICORN_DEBUG=1` -describe Gitlab::Cluster::Mixins::UnicornHttpServer do +RSpec.describe Gitlab::Cluster::Mixins::UnicornHttpServer do before do stub_const('UNICORN_STARTUP_TIMEOUT', 30) end diff --git a/spec/lib/gitlab/cluster/puma_worker_killer_observer_spec.rb b/spec/lib/gitlab/cluster/puma_worker_killer_observer_spec.rb index 6ed9dda08d7..948de161235 100644 --- a/spec/lib/gitlab/cluster/puma_worker_killer_observer_spec.rb +++ b/spec/lib/gitlab/cluster/puma_worker_killer_observer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cluster::PumaWorkerKillerObserver do +RSpec.describe Gitlab::Cluster::PumaWorkerKillerObserver do let(:counter) { Gitlab::Metrics::NullMetric.instance } before do diff --git a/spec/lib/gitlab/cluster/rack_timeout_observer_spec.rb b/spec/lib/gitlab/cluster/rack_timeout_observer_spec.rb index 68e5435450c..05df4089075 100644 --- a/spec/lib/gitlab/cluster/rack_timeout_observer_spec.rb +++ b/spec/lib/gitlab/cluster/rack_timeout_observer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Cluster::RackTimeoutObserver do +RSpec.describe Gitlab::Cluster::RackTimeoutObserver do let(:counter) { Gitlab::Metrics::NullMetric.instance } before do diff --git a/spec/lib/gitlab/code_navigation_path_spec.rb b/spec/lib/gitlab/code_navigation_path_spec.rb index 07d4dfba622..4dc864b158d 100644 --- a/spec/lib/gitlab/code_navigation_path_spec.rb +++ b/spec/lib/gitlab/code_navigation_path_spec.rb @@ -2,10 +2,10 @@ require 'spec_helper' -describe Gitlab::CodeNavigationPath do +RSpec.describe Gitlab::CodeNavigationPath do context 'when there is an artifact with code navigation data' do let_it_be(:project) { create(:project, :repository) } - let_it_be(:sha) { project.repository.commits('master', limit: 5).last.id } + let_it_be(:sha) { project.repository.commits('master', limit: Gitlab::CodeNavigationPath::LATEST_COMMITS_LIMIT).last.id } let_it_be(:pipeline) { create(:ci_pipeline, project: project, sha: sha) } let_it_be(:job) { create(:ci_build, pipeline: pipeline) } let_it_be(:artifact) { create(:ci_job_artifact, :lsif, job: job) } diff --git a/spec/lib/gitlab/color_schemes_spec.rb b/spec/lib/gitlab/color_schemes_spec.rb index ba5573f6901..fd9fccc2bf7 100644 --- a/spec/lib/gitlab/color_schemes_spec.rb +++ b/spec/lib/gitlab/color_schemes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ColorSchemes do +RSpec.describe Gitlab::ColorSchemes do describe '.body_classes' do it 'returns a space-separated list of class names' do css = described_class.body_classes diff --git a/spec/lib/gitlab/conan_token_spec.rb b/spec/lib/gitlab/conan_token_spec.rb new file mode 100644 index 00000000000..b17f2eaa8d8 --- /dev/null +++ b/spec/lib/gitlab/conan_token_spec.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true +require 'spec_helper' + +RSpec.describe Gitlab::ConanToken do + let(:base_secret) { SecureRandom.base64(64) } + + let(:jwt_secret) do + OpenSSL::HMAC.hexdigest( + OpenSSL::Digest::SHA256.new, + base_secret, + described_class::HMAC_KEY + ) + end + + before do + allow(Settings).to receive(:attr_encrypted_db_key_base).and_return(base_secret) + end + + def build_jwt(access_token_id:, user_id:, expire_time: nil) + JSONWebToken::HMACToken.new(jwt_secret).tap do |jwt| + jwt['access_token'] = access_token_id + jwt['user_id'] = user_id || user_id + jwt.expire_time = expire_time || jwt.issued_at + 1.hour + end + end + + describe '.from_personal_access_token' do + it 'sets access token id and user id' do + access_token = double(id: 123, user_id: 456) + + token = described_class.from_personal_access_token(access_token) + + expect(token.access_token_id).to eq(123) + expect(token.user_id).to eq(456) + end + end + + describe '.from_job' do + it 'sets access token id and user id' do + user = double(id: 456) + job = double(token: 123, user: user) + + token = described_class.from_job(job) + + expect(token.access_token_id).to eq(123) + expect(token.user_id).to eq(456) + end + end + + describe '.from_deploy_token' do + it 'sets access token id and user id' do + deploy_token = double(token: '123', username: 'bob') + + token = described_class.from_deploy_token(deploy_token) + + expect(token.access_token_id).to eq('123') + expect(token.user_id).to eq('bob') + end + end + + describe '.decode' do + it 'sets access token id and user id' do + jwt = build_jwt(access_token_id: 123, user_id: 456) + + token = described_class.decode(jwt.encoded) + + expect(token.access_token_id).to eq(123) + expect(token.user_id).to eq(456) + end + + it 'returns nil for invalid JWT' do + expect(described_class.decode('invalid-jwt')).to be_nil + end + + it 'returns nil for expired JWT' do + jwt = build_jwt(access_token_id: 123, + user_id: 456, + expire_time: Time.zone.now - 2.hours) + + expect(described_class.decode(jwt.encoded)).to be_nil + end + end + + describe '#to_jwt' do + it 'returns the encoded JWT' do + allow(SecureRandom).to receive(:uuid).and_return('u-u-i-d') + + Timecop.freeze do + jwt = build_jwt(access_token_id: 123, user_id: 456) + + token = described_class.new(access_token_id: 123, user_id: 456) + + expect(token.to_jwt).to eq(jwt.encoded) + end + end + end +end diff --git a/spec/lib/gitlab/config/entry/attributable_spec.rb b/spec/lib/gitlab/config/entry/attributable_spec.rb index 64a4670f483..1e7880ed898 100644 --- a/spec/lib/gitlab/config/entry/attributable_spec.rb +++ b/spec/lib/gitlab/config/entry/attributable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Attributable do +RSpec.describe Gitlab::Config::Entry::Attributable do let(:node) do Class.new do include Gitlab::Config::Entry::Attributable diff --git a/spec/lib/gitlab/config/entry/boolean_spec.rb b/spec/lib/gitlab/config/entry/boolean_spec.rb index 0b8b720dd80..86cd92e22d7 100644 --- a/spec/lib/gitlab/config/entry/boolean_spec.rb +++ b/spec/lib/gitlab/config/entry/boolean_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Boolean do +RSpec.describe Gitlab::Config::Entry::Boolean do let(:entry) { described_class.new(config) } describe 'validations' do diff --git a/spec/lib/gitlab/config/entry/configurable_spec.rb b/spec/lib/gitlab/config/entry/configurable_spec.rb index 8c3a4490d08..c72efa66024 100644 --- a/spec/lib/gitlab/config/entry/configurable_spec.rb +++ b/spec/lib/gitlab/config/entry/configurable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Configurable do +RSpec.describe Gitlab::Config::Entry::Configurable do let(:entry) do Class.new(Gitlab::Config::Entry::Node) do include Gitlab::Config::Entry::Configurable diff --git a/spec/lib/gitlab/config/entry/factory_spec.rb b/spec/lib/gitlab/config/entry/factory_spec.rb index 81ca5f2cba1..a00c45169ef 100644 --- a/spec/lib/gitlab/config/entry/factory_spec.rb +++ b/spec/lib/gitlab/config/entry/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Factory do +RSpec.describe Gitlab::Config::Entry::Factory do describe '#create!' do before do stub_const('Script', Class.new(Gitlab::Config::Entry::Node)) diff --git a/spec/lib/gitlab/config/entry/simplifiable_spec.rb b/spec/lib/gitlab/config/entry/simplifiable_spec.rb index 5c208cab449..2011587a342 100644 --- a/spec/lib/gitlab/config/entry/simplifiable_spec.rb +++ b/spec/lib/gitlab/config/entry/simplifiable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Simplifiable do +RSpec.describe Gitlab::Config::Entry::Simplifiable do describe '.strategy' do let(:entry) do Class.new(described_class) do diff --git a/spec/lib/gitlab/config/entry/undefined_spec.rb b/spec/lib/gitlab/config/entry/undefined_spec.rb index 83c3a6aec72..36faabd8e31 100644 --- a/spec/lib/gitlab/config/entry/undefined_spec.rb +++ b/spec/lib/gitlab/config/entry/undefined_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Undefined do +RSpec.describe Gitlab::Config::Entry::Undefined do let(:entry) { described_class.new } describe '#leaf?' do diff --git a/spec/lib/gitlab/config/entry/unspecified_spec.rb b/spec/lib/gitlab/config/entry/unspecified_spec.rb index 32c52594ecf..35ba992f62a 100644 --- a/spec/lib/gitlab/config/entry/unspecified_spec.rb +++ b/spec/lib/gitlab/config/entry/unspecified_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Unspecified do +RSpec.describe Gitlab::Config::Entry::Unspecified do let(:unspecified) { described_class.new(entry) } let(:entry) { spy('Entry') } diff --git a/spec/lib/gitlab/config/entry/validatable_spec.rb b/spec/lib/gitlab/config/entry/validatable_spec.rb index 925db3594ba..5e66de60367 100644 --- a/spec/lib/gitlab/config/entry/validatable_spec.rb +++ b/spec/lib/gitlab/config/entry/validatable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Validatable do +RSpec.describe Gitlab::Config::Entry::Validatable do let(:entry) do Class.new(Gitlab::Config::Entry::Node) do include Gitlab::Config::Entry::Validatable diff --git a/spec/lib/gitlab/config/entry/validator_spec.rb b/spec/lib/gitlab/config/entry/validator_spec.rb index 7bf350912df..d41f7f794ec 100644 --- a/spec/lib/gitlab/config/entry/validator_spec.rb +++ b/spec/lib/gitlab/config/entry/validator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Entry::Validator do +RSpec.describe Gitlab::Config::Entry::Validator do let(:validator) { Class.new(described_class) } let(:validator_instance) { validator.new(node) } let(:node) { spy('node') } diff --git a/spec/lib/gitlab/config/loader/yaml_spec.rb b/spec/lib/gitlab/config/loader/yaml_spec.rb index 623fe927233..731ee12d7f4 100644 --- a/spec/lib/gitlab/config/loader/yaml_spec.rb +++ b/spec/lib/gitlab/config/loader/yaml_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Config::Loader::Yaml do +RSpec.describe Gitlab::Config::Loader::Yaml do let(:loader) { described_class.new(yml) } let(:yml) do diff --git a/spec/lib/gitlab/config_checker/external_database_checker_spec.rb b/spec/lib/gitlab/config_checker/external_database_checker_spec.rb index d86d132c237..316696bc584 100644 --- a/spec/lib/gitlab/config_checker/external_database_checker_spec.rb +++ b/spec/lib/gitlab/config_checker/external_database_checker_spec.rb @@ -2,55 +2,58 @@ require 'spec_helper' -describe Gitlab::ConfigChecker::ExternalDatabaseChecker do +RSpec.describe Gitlab::ConfigChecker::ExternalDatabaseChecker do describe '#check' do subject { described_class.check } - context 'database version is not deprecated' do + let_it_be(:deprecation_warning) { "Please upgrade" } + let_it_be(:upcoming_deprecation_warning) { "Please consider upgrading" } + + context 'when database meets minimum version and there is no upcoming deprecation' do before do - allow(described_class).to receive(:db_version_deprecated?).and_return(false) + allow(Gitlab::Database).to receive(:postgresql_minimum_supported_version?).and_return(true) + allow(Gitlab::Database).to receive(:postgresql_upcoming_deprecation?).and_return(false) end it { is_expected.to be_empty } end - context 'database version is deprecated' do + context 'when database does not meet minimum version and there is no upcoming deprecation' do before do - allow(described_class).to receive(:db_version_deprecated?).and_return(true) - end - - let(:notice_deprecated_database) do - { - type: 'warning', - message: _('Note that PostgreSQL 11 will become the minimum required PostgreSQL version in GitLab 13.0 (May 2020). '\ - 'PostgreSQL 9.6 and PostgreSQL 10 will no longer be supported in GitLab 13.0. '\ - 'Please consider upgrading your PostgreSQL version (%{db_version}) soon.') % { db_version: Gitlab::Database.version.to_s } - } + allow(Gitlab::Database).to receive(:postgresql_minimum_supported_version?).and_return(false) + allow(Gitlab::Database).to receive(:postgresql_upcoming_deprecation?).and_return(false) end - it 'reports deprecated database notices' do - is_expected.to contain_exactly(notice_deprecated_database) + it 'only returns notice about deprecated database version' do + is_expected.to include(a_hash_including(message: include(deprecation_warning))) + is_expected.not_to include(a_hash_including(message: include(upcoming_deprecation_warning))) end end - end - describe '#db_version_deprecated' do - subject { described_class.db_version_deprecated? } - - context 'database version is not deprecated' do + context 'when database meets minimum version and there is an upcoming deprecation' do before do - allow(Gitlab::Database).to receive(:version).and_return(11) + allow(Gitlab::Database).to receive(:postgresql_minimum_supported_version?).and_return(true) + allow(Gitlab::Database).to receive(:postgresql_upcoming_deprecation?).and_return(true) end - it { is_expected.to be false } + it 'only returns notice about an upcoming deprecation' do + is_expected.to include(a_hash_including(message: include(upcoming_deprecation_warning))) + is_expected.not_to include(a_hash_including(message: include(deprecation_warning))) + end end - context 'database version is deprecated' do + context 'when database does not meet minimum version and there is an upcoming deprecation' do before do - allow(Gitlab::Database).to receive(:version).and_return(10) + allow(Gitlab::Database).to receive(:postgresql_minimum_supported_version?).and_return(false) + allow(Gitlab::Database).to receive(:postgresql_upcoming_deprecation?).and_return(true) end - it { is_expected.to be true } + it 'returns notice about deprecated database version and an upcoming deprecation' do + is_expected.to include( + a_hash_including(message: include(deprecation_warning)), + a_hash_including(message: include(upcoming_deprecation_warning)) + ) + end end end end diff --git a/spec/lib/gitlab/config_checker/puma_rugged_checker_spec.rb b/spec/lib/gitlab/config_checker/puma_rugged_checker_spec.rb index badfd56d571..afee3c5536e 100644 --- a/spec/lib/gitlab/config_checker/puma_rugged_checker_spec.rb +++ b/spec/lib/gitlab/config_checker/puma_rugged_checker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ConfigChecker::PumaRuggedChecker do +RSpec.describe Gitlab::ConfigChecker::PumaRuggedChecker do describe '#check' do subject { described_class.check } diff --git a/spec/lib/gitlab/conflict/file_collection_spec.rb b/spec/lib/gitlab/conflict/file_collection_spec.rb index f3cdb1a9e59..6da7f8d530d 100644 --- a/spec/lib/gitlab/conflict/file_collection_spec.rb +++ b/spec/lib/gitlab/conflict/file_collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Conflict::FileCollection do +RSpec.describe Gitlab::Conflict::FileCollection do let(:merge_request) { create(:merge_request, source_branch: 'conflict-resolvable', target_branch: 'conflict-start') } let(:file_collection) { described_class.new(merge_request) } diff --git a/spec/lib/gitlab/conflict/file_spec.rb b/spec/lib/gitlab/conflict/file_spec.rb index 966648bcc5a..b54fe40bb5f 100644 --- a/spec/lib/gitlab/conflict/file_spec.rb +++ b/spec/lib/gitlab/conflict/file_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Conflict::File do +RSpec.describe Gitlab::Conflict::File do include GitHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/content_security_policy/config_loader_spec.rb b/spec/lib/gitlab/content_security_policy/config_loader_spec.rb index bbbbf91bd44..a94fd6acd32 100644 --- a/spec/lib/gitlab/content_security_policy/config_loader_spec.rb +++ b/spec/lib/gitlab/content_security_policy/config_loader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ContentSecurityPolicy::ConfigLoader do +RSpec.describe Gitlab::ContentSecurityPolicy::ConfigLoader do let(:policy) { ActionDispatch::ContentSecurityPolicy.new } let(:csp_config) do { diff --git a/spec/lib/gitlab/contributions_calendar_spec.rb b/spec/lib/gitlab/contributions_calendar_spec.rb index 97742a3e815..67b2ea7a1d4 100644 --- a/spec/lib/gitlab/contributions_calendar_spec.rb +++ b/spec/lib/gitlab/contributions_calendar_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ContributionsCalendar do +RSpec.describe Gitlab::ContributionsCalendar do let(:contributor) { create(:user) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/cross_project_access/check_collection_spec.rb b/spec/lib/gitlab/cross_project_access/check_collection_spec.rb index 1aa5480b670..178188f5555 100644 --- a/spec/lib/gitlab/cross_project_access/check_collection_spec.rb +++ b/spec/lib/gitlab/cross_project_access/check_collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CrossProjectAccess::CheckCollection do +RSpec.describe Gitlab::CrossProjectAccess::CheckCollection do subject(:collection) { described_class.new } describe '#add_collection' do diff --git a/spec/lib/gitlab/cross_project_access/check_info_spec.rb b/spec/lib/gitlab/cross_project_access/check_info_spec.rb index 7d2471b6327..5327030daf0 100644 --- a/spec/lib/gitlab/cross_project_access/check_info_spec.rb +++ b/spec/lib/gitlab/cross_project_access/check_info_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CrossProjectAccess::CheckInfo do +RSpec.describe Gitlab::CrossProjectAccess::CheckInfo do let(:dummy_controller) { double } before do diff --git a/spec/lib/gitlab/cross_project_access/class_methods_spec.rb b/spec/lib/gitlab/cross_project_access/class_methods_spec.rb index 17d265542dd..cc2c431fc07 100644 --- a/spec/lib/gitlab/cross_project_access/class_methods_spec.rb +++ b/spec/lib/gitlab/cross_project_access/class_methods_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CrossProjectAccess::ClassMethods do +RSpec.describe Gitlab::CrossProjectAccess::ClassMethods do let(:dummy_class) do Class.new do extend Gitlab::CrossProjectAccess::ClassMethods diff --git a/spec/lib/gitlab/cross_project_access_spec.rb b/spec/lib/gitlab/cross_project_access_spec.rb index ce18d207413..fb72b85f161 100644 --- a/spec/lib/gitlab/cross_project_access_spec.rb +++ b/spec/lib/gitlab/cross_project_access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CrossProjectAccess do +RSpec.describe Gitlab::CrossProjectAccess do let(:super_class) { Class.new } let(:descendant_class) { Class.new(super_class) } let(:current_instance) { described_class.new } diff --git a/spec/lib/gitlab/crypto_helper_spec.rb b/spec/lib/gitlab/crypto_helper_spec.rb index 71bbeccb17b..c07089d8ef0 100644 --- a/spec/lib/gitlab/crypto_helper_spec.rb +++ b/spec/lib/gitlab/crypto_helper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CryptoHelper do +RSpec.describe Gitlab::CryptoHelper do describe '.sha256' do it 'generates SHA256 digest Base46 encoded' do digest = described_class.sha256('some-value') diff --git a/spec/lib/gitlab/current_settings_spec.rb b/spec/lib/gitlab/current_settings_spec.rb index bfd9980ee9c..fd4e8bc1cd0 100644 --- a/spec/lib/gitlab/current_settings_spec.rb +++ b/spec/lib/gitlab/current_settings_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CurrentSettings do +RSpec.describe Gitlab::CurrentSettings do before do stub_env('IN_MEMORY_APPLICATION_SETTINGS', 'false') end diff --git a/spec/lib/gitlab/cycle_analytics/base_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/base_event_fetcher_spec.rb index 3eea791d61a..056c1b5bc9f 100644 --- a/spec/lib/gitlab/cycle_analytics/base_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/base_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::BaseEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::BaseEventFetcher do let(:max_events) { 2 } let(:project) { create(:project, :repository) } let(:user) { create(:user, :admin) } diff --git a/spec/lib/gitlab/cycle_analytics/code_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/code_event_fetcher_spec.rb index 326a41a3af7..a1a173abe57 100644 --- a/spec/lib/gitlab/cycle_analytics/code_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/code_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::CodeEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::CodeEventFetcher do let(:stage_name) { :code } it_behaves_like 'default query config' do diff --git a/spec/lib/gitlab/cycle_analytics/code_stage_spec.rb b/spec/lib/gitlab/cycle_analytics/code_stage_spec.rb index 9a4193b09f5..afab19de2ab 100644 --- a/spec/lib/gitlab/cycle_analytics/code_stage_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/code_stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::CodeStage do +RSpec.describe Gitlab::CycleAnalytics::CodeStage do let(:stage_name) { :code } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/cycle_analytics/events_spec.rb b/spec/lib/gitlab/cycle_analytics/events_spec.rb index 9eee7e89062..246003cde84 100644 --- a/spec/lib/gitlab/cycle_analytics/events_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/events_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'cycle analytics events' do +RSpec.describe 'cycle analytics events' do let(:project) { create(:project, :repository) } let(:from_date) { 10.days.ago } let(:user) { create(:user, :admin) } diff --git a/spec/lib/gitlab/cycle_analytics/issue_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/issue_event_fetcher_spec.rb index a72e2952782..7a49ee53e8f 100644 --- a/spec/lib/gitlab/cycle_analytics/issue_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/issue_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::IssueEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::IssueEventFetcher do let(:stage_name) { :issue } it_behaves_like 'default query config' diff --git a/spec/lib/gitlab/cycle_analytics/issue_stage_spec.rb b/spec/lib/gitlab/cycle_analytics/issue_stage_spec.rb index 021d31bf160..9ec71e6ed72 100644 --- a/spec/lib/gitlab/cycle_analytics/issue_stage_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/issue_stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::IssueStage do +RSpec.describe Gitlab::CycleAnalytics::IssueStage do let(:stage_name) { :issue } let(:project) { create(:project) } let(:issue_1) { create(:issue, project: project, created_at: 90.minutes.ago) } diff --git a/spec/lib/gitlab/cycle_analytics/permissions_spec.rb b/spec/lib/gitlab/cycle_analytics/permissions_spec.rb index 2896e973a43..3fd48993e5f 100644 --- a/spec/lib/gitlab/cycle_analytics/permissions_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/permissions_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::Permissions do +RSpec.describe Gitlab::CycleAnalytics::Permissions do let(:project) { create(:project, public_builds: false) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/cycle_analytics/plan_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/plan_event_fetcher_spec.rb index 587f185b970..bc14a772d34 100644 --- a/spec/lib/gitlab/cycle_analytics/plan_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/plan_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::PlanEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::PlanEventFetcher do let(:stage_name) { :plan } it_behaves_like 'default query config' do diff --git a/spec/lib/gitlab/cycle_analytics/plan_stage_spec.rb b/spec/lib/gitlab/cycle_analytics/plan_stage_spec.rb index e391fa6b999..66d00edacb7 100644 --- a/spec/lib/gitlab/cycle_analytics/plan_stage_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/plan_stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::PlanStage do +RSpec.describe Gitlab::CycleAnalytics::PlanStage do let(:stage_name) { :plan } let(:project) { create(:project) } let!(:issue_1) { create(:issue, project: project, created_at: 90.minutes.ago) } diff --git a/spec/lib/gitlab/cycle_analytics/production_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/production_event_fetcher_spec.rb index aeca72e8c91..86b07a95cbb 100644 --- a/spec/lib/gitlab/cycle_analytics/production_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/production_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::ProductionEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::ProductionEventFetcher do let(:stage_name) { :production } it_behaves_like 'default query config' diff --git a/spec/lib/gitlab/cycle_analytics/production_stage_spec.rb b/spec/lib/gitlab/cycle_analytics/production_stage_spec.rb index aeeae291e2e..73b17194f72 100644 --- a/spec/lib/gitlab/cycle_analytics/production_stage_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/production_stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::ProductionStage do +RSpec.describe Gitlab::CycleAnalytics::ProductionStage do let(:stage_name) { 'Total' } it_behaves_like 'base stage' diff --git a/spec/lib/gitlab/cycle_analytics/review_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/review_event_fetcher_spec.rb index 3eb62b45e6f..fe13cc6b065 100644 --- a/spec/lib/gitlab/cycle_analytics/review_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/review_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::ReviewEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::ReviewEventFetcher do let(:stage_name) { :review } it_behaves_like 'default query config' diff --git a/spec/lib/gitlab/cycle_analytics/review_stage_spec.rb b/spec/lib/gitlab/cycle_analytics/review_stage_spec.rb index 14100ee6f73..cdd1cca6837 100644 --- a/spec/lib/gitlab/cycle_analytics/review_stage_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/review_stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::ReviewStage do +RSpec.describe Gitlab::CycleAnalytics::ReviewStage do let(:stage_name) { :review } let(:project) { create(:project) } let(:issue_1) { create(:issue, project: project, created_at: 90.minutes.ago) } diff --git a/spec/lib/gitlab/cycle_analytics/stage_summary_spec.rb b/spec/lib/gitlab/cycle_analytics/stage_summary_spec.rb index ccc99017e37..9ece24074e7 100644 --- a/spec/lib/gitlab/cycle_analytics/stage_summary_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/stage_summary_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::StageSummary do +RSpec.describe Gitlab::CycleAnalytics::StageSummary do let(:project) { create(:project, :repository) } let(:options) { { from: 1.day.ago, current_user: user } } let(:user) { create(:user, :admin) } diff --git a/spec/lib/gitlab/cycle_analytics/staging_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/staging_event_fetcher_spec.rb index 525f1608a70..bdf1b99c4c9 100644 --- a/spec/lib/gitlab/cycle_analytics/staging_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/staging_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::StagingEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::StagingEventFetcher do let(:stage_name) { :staging } it_behaves_like 'default query config' do diff --git a/spec/lib/gitlab/cycle_analytics/staging_stage_spec.rb b/spec/lib/gitlab/cycle_analytics/staging_stage_spec.rb index 930892edd31..69e42adb139 100644 --- a/spec/lib/gitlab/cycle_analytics/staging_stage_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/staging_stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::StagingStage do +RSpec.describe Gitlab::CycleAnalytics::StagingStage do let(:stage_name) { :staging } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/cycle_analytics/summary/value_spec.rb b/spec/lib/gitlab/cycle_analytics/summary/value_spec.rb index d9bdfa92a04..c955b288500 100644 --- a/spec/lib/gitlab/cycle_analytics/summary/value_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/summary/value_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::Summary::Value do +RSpec.describe Gitlab::CycleAnalytics::Summary::Value do describe Gitlab::CycleAnalytics::Summary::Value::None do it 'returns `-`' do expect(described_class.new.to_s).to eq('-') diff --git a/spec/lib/gitlab/cycle_analytics/test_event_fetcher_spec.rb b/spec/lib/gitlab/cycle_analytics/test_event_fetcher_spec.rb index d550f083600..1277385d0b4 100644 --- a/spec/lib/gitlab/cycle_analytics/test_event_fetcher_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/test_event_fetcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::TestEventFetcher do +RSpec.describe Gitlab::CycleAnalytics::TestEventFetcher do let(:stage_name) { :test } it_behaves_like 'default query config' do diff --git a/spec/lib/gitlab/cycle_analytics/test_stage_spec.rb b/spec/lib/gitlab/cycle_analytics/test_stage_spec.rb index 56e90520e72..9a207d32167 100644 --- a/spec/lib/gitlab/cycle_analytics/test_stage_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/test_stage_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::TestStage do +RSpec.describe Gitlab::CycleAnalytics::TestStage do let(:stage_name) { :test } let(:project) { create(:project) } let(:stage_options) { { from: 2.days.ago, current_user: project.creator, project: project } } diff --git a/spec/lib/gitlab/cycle_analytics/updater_spec.rb b/spec/lib/gitlab/cycle_analytics/updater_spec.rb index 67f386f9144..f7095cffc19 100644 --- a/spec/lib/gitlab/cycle_analytics/updater_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/updater_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::Updater do +RSpec.describe Gitlab::CycleAnalytics::Updater do describe 'updates authors' do let(:user) { create(:user) } let(:events) { [{ 'author_id' => user.id }] } diff --git a/spec/lib/gitlab/cycle_analytics/usage_data_spec.rb b/spec/lib/gitlab/cycle_analytics/usage_data_spec.rb index 41ce9355708..9ebdacb16de 100644 --- a/spec/lib/gitlab/cycle_analytics/usage_data_spec.rb +++ b/spec/lib/gitlab/cycle_analytics/usage_data_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::CycleAnalytics::UsageData do +RSpec.describe Gitlab::CycleAnalytics::UsageData do describe '#to_json' do before do # Since git commits only have second precision, round up to the diff --git a/spec/lib/gitlab/daemon_spec.rb b/spec/lib/gitlab/daemon_spec.rb index cf1f089c577..075a1e414c7 100644 --- a/spec/lib/gitlab/daemon_spec.rb +++ b/spec/lib/gitlab/daemon_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Daemon do +RSpec.describe Gitlab::Daemon do subject { described_class.new } before do diff --git a/spec/lib/gitlab/danger/changelog_spec.rb b/spec/lib/gitlab/danger/changelog_spec.rb index 130a4708cec..f5954cd8c1e 100644 --- a/spec/lib/gitlab/danger/changelog_spec.rb +++ b/spec/lib/gitlab/danger/changelog_spec.rb @@ -1,13 +1,11 @@ # frozen_string_literal: true require 'fast_spec_helper' -require 'rspec-parameterized' require_relative 'danger_spec_helper' require 'gitlab/danger/changelog' -describe Gitlab::Danger::Changelog do - using RSpec::Parameterized::TableSyntax +RSpec.describe Gitlab::Danger::Changelog do include DangerSpecHelper let(:added_files) { nil } @@ -26,34 +24,36 @@ describe Gitlab::Danger::Changelog do subject(:changelog) { fake_danger.new(git: fake_git, gitlab: fake_gitlab, helper: fake_helper) } describe '#needed?' do - subject { changelog.needed? } + let(:category_with_changelog) { :backend } + let(:label_with_changelog) { 'frontend' } + let(:category_without_changelog) { Gitlab::Danger::Changelog::NO_CHANGELOG_CATEGORIES.first } + let(:label_without_changelog) { Gitlab::Danger::Changelog::NO_CHANGELOG_LABELS.first } - where(:categories, :labels) do - { backend: nil } | %w[backend backstage] - { frontend: nil, docs: nil } | ['ci-build'] - { engineering_productivity: nil, none: nil } | ['meta'] - end + subject { changelog.needed? } - with_them do - let(:changes_by_category) { categories } - let(:mr_labels) { labels } + context 'when MR contains only categories requiring no changelog' do + let(:changes_by_category) { { category_without_changelog => nil } } + let(:mr_labels) { [] } - it "is falsy when categories and labels require no changelog" do + it 'is falsey' do is_expected.to be_falsy end end - where(:categories, :labels) do - { frontend: nil, docs: nil } | ['database::review pending', 'feature'] - { backend: nil } | ['backend', 'technical debt'] - { engineering_productivity: nil, none: nil } | ['frontend'] + context 'when MR contains a label that require no changelog' do + let(:changes_by_category) { { category_with_changelog => nil } } + let(:mr_labels) { [label_with_changelog, label_without_changelog] } + + it 'is falsey' do + is_expected.to be_falsy + end end - with_them do - let(:changes_by_category) { categories } - let(:mr_labels) { labels } + context 'when MR contains a category that require changelog and a category that require no changelog' do + let(:changes_by_category) { { category_with_changelog => nil, category_without_changelog => nil } } + let(:mr_labels) { [] } - it "is truthy when categories and labels require a changelog" do + it 'is truthy' do is_expected.to be_truthy end end diff --git a/spec/lib/gitlab/danger/commit_linter_spec.rb b/spec/lib/gitlab/danger/commit_linter_spec.rb index e57ccd12fa5..06bec6f793d 100644 --- a/spec/lib/gitlab/danger/commit_linter_spec.rb +++ b/spec/lib/gitlab/danger/commit_linter_spec.rb @@ -6,7 +6,7 @@ require_relative 'danger_spec_helper' require 'gitlab/danger/commit_linter' -describe Gitlab::Danger::CommitLinter do +RSpec.describe Gitlab::Danger::CommitLinter do using RSpec::Parameterized::TableSyntax let(:total_files_changed) { 2 } @@ -156,7 +156,7 @@ describe Gitlab::Danger::CommitLinter do context 'when subject is a WIP' do let(:final_message) { 'A B C' } # commit message with prefix will be over max length. commit message without prefix will be of maximum size - let(:commit_message) { described_class::WIP_PREFIX + final_message + 'D' * (described_class::WARN_SUBJECT_LENGTH - final_message.size) } + let(:commit_message) { described_class::WIP_PREFIX + final_message + 'D' * (described_class::MAX_LINE_LENGTH - final_message.size) } it 'does not have any problems' do commit_linter.lint @@ -176,16 +176,6 @@ describe Gitlab::Danger::CommitLinter do end end - context 'when subject is above warning' do - let(:commit_message) { 'A B ' + 'C' * described_class::WARN_SUBJECT_LENGTH } - - it 'adds a problem' do - expect(commit_linter).to receive(:add_problem).with(:subject_above_warning, described_class::DEFAULT_SUBJECT_DESCRIPTION) - - commit_linter.lint - end - end - context 'when subject starts with lowercase' do let(:commit_message) { 'a B C' } diff --git a/spec/lib/gitlab/danger/emoji_checker_spec.rb b/spec/lib/gitlab/danger/emoji_checker_spec.rb index 0cdc18ce626..6092c751e1c 100644 --- a/spec/lib/gitlab/danger/emoji_checker_spec.rb +++ b/spec/lib/gitlab/danger/emoji_checker_spec.rb @@ -5,7 +5,7 @@ require 'rspec-parameterized' require 'gitlab/danger/emoji_checker' -describe Gitlab::Danger::EmojiChecker do +RSpec.describe Gitlab::Danger::EmojiChecker do using RSpec::Parameterized::TableSyntax describe '#includes_text_emoji?' do diff --git a/spec/lib/gitlab/danger/helper_spec.rb b/spec/lib/gitlab/danger/helper_spec.rb index 809064a540c..e73742b5911 100644 --- a/spec/lib/gitlab/danger/helper_spec.rb +++ b/spec/lib/gitlab/danger/helper_spec.rb @@ -6,7 +6,7 @@ require_relative 'danger_spec_helper' require 'gitlab/danger/helper' -describe Gitlab::Danger::Helper do +RSpec.describe Gitlab::Danger::Helper do using RSpec::Parameterized::TableSyntax include DangerSpecHelper @@ -165,125 +165,152 @@ describe Gitlab::Danger::Helper do end end - describe '#category_for_file' do - where(:path, :expected_category) do - 'doc/foo' | :none - 'CONTRIBUTING.md' | :none - 'LICENSE' | :none - 'MAINTENANCE.md' | :none - 'PHILOSOPHY.md' | :none - 'PROCESS.md' | :none - 'README.md' | :none - - 'ee/doc/foo' | :unknown - 'ee/README' | :unknown - - 'app/assets/foo' | :frontend - 'app/views/foo' | :frontend - 'public/foo' | :frontend - 'scripts/frontend/foo' | :frontend - 'spec/javascripts/foo' | :frontend - 'spec/frontend/bar' | :frontend - 'vendor/assets/foo' | :frontend - 'babel.config.js' | :frontend - 'jest.config.js' | :frontend - 'package.json' | :frontend - 'yarn.lock' | :frontend - 'config/foo.js' | :frontend - 'config/deep/foo.js' | :frontend - - 'ee/app/assets/foo' | :frontend - 'ee/app/views/foo' | :frontend - 'ee/spec/javascripts/foo' | :frontend - 'ee/spec/frontend/bar' | :frontend - - 'app/models/foo' | :backend - 'bin/foo' | :backend - 'config/foo' | :backend - 'lib/foo' | :backend - 'rubocop/foo' | :backend - 'spec/foo' | :backend - 'spec/foo/bar' | :backend - - 'ee/app/foo' | :backend - 'ee/bin/foo' | :backend - 'ee/spec/foo' | :backend - 'ee/spec/foo/bar' | :backend - - 'generator_templates/foo' | :backend - 'vendor/languages.yml' | :backend - 'vendor/licenses.csv' | :backend - 'file_hooks/examples/' | :backend - - 'Gemfile' | :backend - 'Gemfile.lock' | :backend - 'Rakefile' | :backend - 'FOO_VERSION' | :backend - - 'Dangerfile' | :engineering_productivity - 'danger/commit_messages/Dangerfile' | :engineering_productivity - 'ee/danger/commit_messages/Dangerfile' | :engineering_productivity - 'danger/commit_messages/' | :engineering_productivity - 'ee/danger/commit_messages/' | :engineering_productivity - '.gitlab-ci.yml' | :engineering_productivity - '.gitlab/ci/cng.gitlab-ci.yml' | :engineering_productivity - '.gitlab/ci/ee-specific-checks.gitlab-ci.yml' | :engineering_productivity - 'scripts/foo' | :engineering_productivity - 'lib/gitlab/danger/foo' | :engineering_productivity - 'ee/lib/gitlab/danger/foo' | :engineering_productivity - '.overcommit.yml.example' | :engineering_productivity - '.editorconfig' | :engineering_productivity - 'tooling/overcommit/foo' | :engineering_productivity - '.codeclimate.yml' | :engineering_productivity - - 'lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml' | :backend - - 'ee/FOO_VERSION' | :unknown - - 'db/schema.rb' | :database - 'db/structure.sql' | :database - 'db/migrate/foo' | :database - 'db/post_migrate/foo' | :database - 'ee/db/migrate/foo' | :database - 'ee/db/post_migrate/foo' | :database - 'ee/db/geo/migrate/foo' | :database - 'ee/db/geo/post_migrate/foo' | :database - 'app/models/project_authorization.rb' | :database - 'app/services/users/refresh_authorized_projects_service.rb' | :database - 'lib/gitlab/background_migration.rb' | :database - 'lib/gitlab/background_migration/foo' | :database - 'ee/lib/gitlab/background_migration/foo' | :database - 'lib/gitlab/database.rb' | :database - 'lib/gitlab/database/foo' | :database - 'ee/lib/gitlab/database/foo' | :database - 'lib/gitlab/github_import.rb' | :database - 'lib/gitlab/github_import/foo' | :database - 'lib/gitlab/sql/foo' | :database - 'rubocop/cop/migration/foo' | :database - - 'db/fixtures/foo.rb' | :backend - 'ee/db/fixtures/foo.rb' | :backend - - 'qa/foo' | :qa - 'ee/qa/foo' | :qa - - 'changelogs/foo' | :none - 'ee/changelogs/foo' | :none - 'locale/gitlab.pot' | :none - - 'FOO' | :unknown - 'foo' | :unknown - - 'foo/bar.rb' | :backend - 'foo/bar.js' | :frontend - 'foo/bar.txt' | :none - 'foo/bar.md' | :none + describe '#categories_for_file' do + before do + allow(fake_git).to receive(:diff_for_file).with('usage_data.rb') { double(:diff, patch: "+ count(User.active)") } + end + + where(:path, :expected_categories) do + 'usage_data.rb' | [:database, :backend] + 'doc/foo.md' | [:docs] + 'CONTRIBUTING.md' | [:docs] + 'LICENSE' | [:docs] + 'MAINTENANCE.md' | [:docs] + 'PHILOSOPHY.md' | [:docs] + 'PROCESS.md' | [:docs] + 'README.md' | [:docs] + + 'ee/doc/foo' | [:unknown] + 'ee/README' | [:unknown] + + 'app/assets/foo' | [:frontend] + 'app/views/foo' | [:frontend] + 'public/foo' | [:frontend] + 'scripts/frontend/foo' | [:frontend] + 'spec/javascripts/foo' | [:frontend] + 'spec/frontend/bar' | [:frontend] + 'vendor/assets/foo' | [:frontend] + 'babel.config.js' | [:frontend] + 'jest.config.js' | [:frontend] + 'package.json' | [:frontend] + 'yarn.lock' | [:frontend] + 'config/foo.js' | [:frontend] + 'config/deep/foo.js' | [:frontend] + + 'ee/app/assets/foo' | [:frontend] + 'ee/app/views/foo' | [:frontend] + 'ee/spec/javascripts/foo' | [:frontend] + 'ee/spec/frontend/bar' | [:frontend] + + '.gitlab/ci/frontend.gitlab-ci.yml' | %i[frontend engineering_productivity] + + 'app/models/foo' | [:backend] + 'bin/foo' | [:backend] + 'config/foo' | [:backend] + 'lib/foo' | [:backend] + 'rubocop/foo' | [:backend] + 'spec/foo' | [:backend] + 'spec/foo/bar' | [:backend] + + 'ee/app/foo' | [:backend] + 'ee/bin/foo' | [:backend] + 'ee/spec/foo' | [:backend] + 'ee/spec/foo/bar' | [:backend] + + 'generator_templates/foo' | [:backend] + 'vendor/languages.yml' | [:backend] + 'vendor/licenses.csv' | [:backend] + 'file_hooks/examples/' | [:backend] + + 'Gemfile' | [:backend] + 'Gemfile.lock' | [:backend] + 'Rakefile' | [:backend] + 'FOO_VERSION' | [:backend] + + 'Dangerfile' | [:engineering_productivity] + 'danger/commit_messages/Dangerfile' | [:engineering_productivity] + 'ee/danger/commit_messages/Dangerfile' | [:engineering_productivity] + 'danger/commit_messages/' | [:engineering_productivity] + 'ee/danger/commit_messages/' | [:engineering_productivity] + '.gitlab-ci.yml' | [:engineering_productivity] + '.gitlab/ci/cng.gitlab-ci.yml' | [:engineering_productivity] + '.gitlab/ci/ee-specific-checks.gitlab-ci.yml' | [:engineering_productivity] + 'scripts/foo' | [:engineering_productivity] + 'lib/gitlab/danger/foo' | [:engineering_productivity] + 'ee/lib/gitlab/danger/foo' | [:engineering_productivity] + '.overcommit.yml.example' | [:engineering_productivity] + '.editorconfig' | [:engineering_productivity] + 'tooling/overcommit/foo' | [:engineering_productivity] + '.codeclimate.yml' | [:engineering_productivity] + + 'lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml' | [:backend] + + 'ee/FOO_VERSION' | [:unknown] + + 'db/schema.rb' | [:database] + 'db/structure.sql' | [:database] + 'db/migrate/foo' | [:database] + 'db/post_migrate/foo' | [:database] + 'ee/db/migrate/foo' | [:database] + 'ee/db/post_migrate/foo' | [:database] + 'ee/db/geo/migrate/foo' | [:database] + 'ee/db/geo/post_migrate/foo' | [:database] + 'app/models/project_authorization.rb' | [:database] + 'app/services/users/refresh_authorized_projects_service.rb' | [:database] + 'lib/gitlab/background_migration.rb' | [:database] + 'lib/gitlab/background_migration/foo' | [:database] + 'ee/lib/gitlab/background_migration/foo' | [:database] + 'lib/gitlab/database.rb' | [:database] + 'lib/gitlab/database/foo' | [:database] + 'ee/lib/gitlab/database/foo' | [:database] + 'lib/gitlab/github_import.rb' | [:database] + 'lib/gitlab/github_import/foo' | [:database] + 'lib/gitlab/sql/foo' | [:database] + 'rubocop/cop/migration/foo' | [:database] + + 'db/fixtures/foo.rb' | [:backend] + 'ee/db/fixtures/foo.rb' | [:backend] + + 'qa/foo' | [:qa] + 'ee/qa/foo' | [:qa] + + 'changelogs/foo' | [:none] + 'ee/changelogs/foo' | [:none] + 'locale/gitlab.pot' | [:none] + + 'FOO' | [:unknown] + 'foo' | [:unknown] + + 'foo/bar.rb' | [:backend] + 'foo/bar.js' | [:frontend] + 'foo/bar.txt' | [:none] + 'foo/bar.md' | [:none] end with_them do - subject { helper.category_for_file(path) } + subject { helper.categories_for_file(path) } - it { is_expected.to eq(expected_category) } + it { is_expected.to eq(expected_categories) } + end + + context 'having specific changes' do + it 'has database and backend categories' do + allow(fake_git).to receive(:diff_for_file).with('usage_data.rb') { double(:diff, patch: "+ count(User.active)") } + + expect(helper.categories_for_file('usage_data.rb')).to eq([:database, :backend]) + end + + it 'has backend category' do + allow(fake_git).to receive(:diff_for_file).with('usage_data.rb') { double(:diff, patch: "+ alt_usage_data(User.active)") } + + expect(helper.categories_for_file('usage_data.rb')).to eq([:backend]) + end + + it 'has backend category for changes outside usage_data files' do + allow(fake_git).to receive(:diff_for_file).with('user.rb') { double(:diff, patch: "+ count(User.active)") } + + expect(helper.categories_for_file('user.rb')).to eq([:backend]) + end end end @@ -296,6 +323,7 @@ describe Gitlab::Danger::Helper do :frontend | '~frontend' :none | '' :qa | '~QA' + :engineering_productivity | '~"Engineering Productivity" for CI, Danger' end with_them do @@ -335,6 +363,11 @@ describe Gitlab::Danger::Helper do where(:mr_title, :expected_mr_title) do 'My MR title' | 'My MR title' 'WIP: My MR title' | 'My MR title' + 'Draft: My MR title' | 'My MR title' + '(Draft) My MR title' | 'My MR title' + '[Draft] My MR title' | 'My MR title' + '[DRAFT] My MR title' | 'My MR title' + 'DRAFT: My MR title' | 'My MR title' end with_them do @@ -366,6 +399,69 @@ describe Gitlab::Danger::Helper do end end + describe '#cherry_pick_mr?' do + it 'returns false when `gitlab_helper` is unavailable' do + expect(helper).to receive(:gitlab_helper).and_return(nil) + + expect(helper).not_to be_cherry_pick_mr + end + + context 'when MR title does not mention a cherry-pick' do + it 'returns false' do + expect(fake_gitlab).to receive(:mr_json) + .and_return('title' => 'Add feature xyz') + + expect(helper).not_to be_cherry_pick_mr + end + end + + context 'when MR title mentions a cherry-pick' do + [ + 'Cherry Pick !1234', + 'cherry-pick !1234', + 'CherryPick !1234' + ].each do |mr_title| + it 'returns true' do + expect(fake_gitlab).to receive(:mr_json) + .and_return('title' => mr_title) + + expect(helper).to be_cherry_pick_mr + end + end + end + end + + describe '#stable_branch?' do + it 'returns false when `gitlab_helper` is unavailable' do + expect(helper).to receive(:gitlab_helper).and_return(nil) + + expect(helper).not_to be_stable_branch + end + + context 'when MR target branch is not a stable branch' do + it 'returns false' do + expect(fake_gitlab).to receive(:mr_json) + .and_return('target_branch' => 'my-feature-branch') + + expect(helper).not_to be_stable_branch + end + end + + context 'when MR target branch is a stable branch' do + %w[ + 13-1-stable-ee + 13-1-stable-ee-patch-1 + ].each do |target_branch| + it 'returns true' do + expect(fake_gitlab).to receive(:mr_json) + .and_return('target_branch' => target_branch) + + expect(helper).to be_stable_branch + end + end + end + end + describe '#mr_has_label?' do it 'returns false when `gitlab_helper` is unavailable' do expect(helper).to receive(:gitlab_helper).and_return(nil) diff --git a/spec/lib/gitlab/danger/roulette_spec.rb b/spec/lib/gitlab/danger/roulette_spec.rb index b6148cd1407..676edca2459 100644 --- a/spec/lib/gitlab/danger/roulette_spec.rb +++ b/spec/lib/gitlab/danger/roulette_spec.rb @@ -2,16 +2,23 @@ require 'fast_spec_helper' require 'webmock/rspec' +require 'timecop' require 'gitlab/danger/roulette' -describe Gitlab::Danger::Roulette do +RSpec.describe Gitlab::Danger::Roulette do + around do |example| + Timecop.freeze(Time.utc(2020, 06, 22, 10)) { example.run } + end + let(:backend_maintainer) do { username: 'backend-maintainer', name: 'Backend maintainer', role: 'Backend engineer', - projects: { 'gitlab' => 'maintainer backend' } + projects: { 'gitlab' => 'maintainer backend' }, + available: true, + tz_offset_hours: 2.0 } end let(:frontend_reviewer) do @@ -19,7 +26,9 @@ describe Gitlab::Danger::Roulette do username: 'frontend-reviewer', name: 'Frontend reviewer', role: 'Frontend engineer', - projects: { 'gitlab' => 'reviewer frontend' } + projects: { 'gitlab' => 'reviewer frontend' }, + available: true, + tz_offset_hours: 2.0 } end let(:frontend_maintainer) do @@ -27,7 +36,9 @@ describe Gitlab::Danger::Roulette do username: 'frontend-maintainer', name: 'Frontend maintainer', role: 'Frontend engineer', - projects: { 'gitlab' => "maintainer frontend" } + projects: { 'gitlab' => "maintainer frontend" }, + available: true, + tz_offset_hours: 2.0 } end let(:software_engineer_in_test) do @@ -38,7 +49,9 @@ describe Gitlab::Danger::Roulette do projects: { 'gitlab' => 'reviewer qa', 'gitlab-qa' => 'maintainer' - } + }, + available: true, + tz_offset_hours: 2.0 } end let(:engineering_productivity_reviewer) do @@ -46,7 +59,9 @@ describe Gitlab::Danger::Roulette do username: 'eng-prod-reviewer', name: 'EP engineer', role: 'Engineering Productivity', - projects: { 'gitlab' => 'reviewer backend' } + projects: { 'gitlab' => 'reviewer backend' }, + available: true, + tz_offset_hours: 2.0 } end @@ -73,10 +88,17 @@ describe Gitlab::Danger::Roulette do def matching_spin(category, reviewer: { username: nil }, maintainer: { username: nil }, optional: nil) satisfy do |spin| - spin.category == category && - spin.reviewer&.username == reviewer[:username] && - spin.maintainer&.username == maintainer[:username] && - spin.optional_role == optional + bool = spin.category == category + bool &&= spin.reviewer&.username == reviewer[:username] + + bool &&= + if maintainer + spin.maintainer&.username == maintainer[:username] + else + spin.maintainer.nil? + end + + bool && spin.optional_role == optional end end @@ -85,67 +107,114 @@ describe Gitlab::Danger::Roulette do let!(:branch_name) { 'a-branch' } let!(:mr_labels) { ['backend', 'devops::create'] } let!(:author) { Gitlab::Danger::Teammate.new('username' => 'filipa') } - - before do - [ - backend_maintainer, - frontend_reviewer, - frontend_maintainer, - software_engineer_in_test, - engineering_productivity_reviewer - ].each do |person| - stub_person_status(instance_double(Gitlab::Danger::Teammate, username: person[:username]), message: 'making GitLab magic') - end - + let(:timezone_experiment) { false } + let(:spins) do + # Stub the request at the latest time so that we can modify the raw data, e.g. available fields. WebMock .stub_request(:get, described_class::ROULETTE_DATA_URL) .to_return(body: teammate_json) + + subject.spin(project, categories, branch_name, timezone_experiment: timezone_experiment) + end + + before do allow(subject).to receive_message_chain(:gitlab, :mr_author).and_return(author.username) allow(subject).to receive_message_chain(:gitlab, :mr_labels).and_return(mr_labels) end - context 'when change contains backend category' do - it 'assigns backend reviewer and maintainer' do - categories = [:backend] - spins = subject.spin(project, categories, branch_name) + context 'when timezone_experiment == false' do + context 'when change contains backend category' do + let(:categories) { [:backend] } - expect(spins).to contain_exactly(matching_spin(:backend, reviewer: engineering_productivity_reviewer, maintainer: backend_maintainer)) + it 'assigns backend reviewer and maintainer' do + expect(spins).to contain_exactly(matching_spin(:backend, reviewer: engineering_productivity_reviewer, maintainer: backend_maintainer)) + end + + context 'when teammate is not available' do + before do + backend_maintainer[:available] = false + end + + it 'assigns backend reviewer and no maintainer' do + expect(spins).to contain_exactly(matching_spin(:backend, reviewer: engineering_productivity_reviewer, maintainer: nil)) + end + end end - end - context 'when change contains frontend category' do - it 'assigns frontend reviewer and maintainer' do - categories = [:frontend] - spins = subject.spin(project, categories, branch_name) + context 'when change contains frontend category' do + let(:categories) { [:frontend] } - expect(spins).to contain_exactly(matching_spin(:frontend, reviewer: frontend_reviewer, maintainer: frontend_maintainer)) + it 'assigns frontend reviewer and maintainer' do + expect(spins).to contain_exactly(matching_spin(:frontend, reviewer: frontend_reviewer, maintainer: frontend_maintainer)) + end end - end - context 'when change contains QA category' do - it 'assigns QA reviewer and sets optional QA maintainer' do - categories = [:qa] - spins = subject.spin(project, categories, branch_name) + context 'when change contains QA category' do + let(:categories) { [:qa] } - expect(spins).to contain_exactly(matching_spin(:qa, reviewer: software_engineer_in_test, optional: :maintainer)) + it 'assigns QA reviewer' do + expect(spins).to contain_exactly(matching_spin(:qa, reviewer: software_engineer_in_test)) + end end - end - context 'when change contains Engineering Productivity category' do - it 'assigns Engineering Productivity reviewer and fallback to backend maintainer' do - categories = [:engineering_productivity] - spins = subject.spin(project, categories, branch_name) + context 'when change contains Engineering Productivity category' do + let(:categories) { [:engineering_productivity] } - expect(spins).to contain_exactly(matching_spin(:engineering_productivity, reviewer: engineering_productivity_reviewer, maintainer: backend_maintainer)) + it 'assigns Engineering Productivity reviewer and fallback to backend maintainer' do + expect(spins).to contain_exactly(matching_spin(:engineering_productivity, reviewer: engineering_productivity_reviewer, maintainer: backend_maintainer)) + end + end + + context 'when change contains test category' do + let(:categories) { [:test] } + + it 'assigns corresponding SET' do + expect(spins).to contain_exactly(matching_spin(:test, reviewer: software_engineer_in_test)) + end end end - context 'when change contains test category' do - it 'assigns corresponding SET and sets optional test maintainer' do - categories = [:test] - spins = subject.spin(project, categories, branch_name) + context 'when timezone_experiment == true' do + let(:timezone_experiment) { true } + + context 'when change contains backend category' do + let(:categories) { [:backend] } + + it 'assigns backend reviewer and maintainer' do + expect(spins).to contain_exactly(matching_spin(:backend, reviewer: engineering_productivity_reviewer, maintainer: backend_maintainer)) + end + + context 'when teammate is not in a good timezone' do + before do + backend_maintainer[:tz_offset_hours] = 5.0 + end - expect(spins).to contain_exactly(matching_spin(:test, reviewer: software_engineer_in_test, optional: :maintainer)) + it 'assigns backend reviewer and no maintainer' do + expect(spins).to contain_exactly(matching_spin(:backend, reviewer: engineering_productivity_reviewer, maintainer: nil)) + end + end + end + + context 'when change includes a category with timezone disabled' do + let(:categories) { [:backend] } + + before do + stub_const("#{described_class}::INCLUDE_TIMEZONE_FOR_CATEGORY", backend: false) + end + + it 'assigns backend reviewer and maintainer' do + expect(spins).to contain_exactly(matching_spin(:backend, reviewer: engineering_productivity_reviewer, maintainer: backend_maintainer)) + end + + context 'when teammate is not in a good timezone' do + before do + backend_maintainer[:tz_offset_hours] = 5.0 + end + + it 'assigns backend reviewer and maintainer' do + expect(spins).to contain_exactly(matching_spin(:backend, reviewer: engineering_productivity_reviewer, maintainer: backend_maintainer)) + end + end end end end @@ -217,51 +286,83 @@ describe Gitlab::Danger::Roulette do end describe '#spin_for_person' do - let(:person1) { Gitlab::Danger::Teammate.new('username' => 'rymai') } - let(:person2) { Gitlab::Danger::Teammate.new('username' => 'godfat') } - let(:author) { Gitlab::Danger::Teammate.new('username' => 'filipa') } - let(:ooo) { Gitlab::Danger::Teammate.new('username' => 'jacopo-beschi') } - let(:no_capacity) { Gitlab::Danger::Teammate.new('username' => 'uncharged') } + let(:person_tz_offset_hours) { 0.0 } + let(:person1) do + Gitlab::Danger::Teammate.new( + 'username' => 'rymai', + 'available' => true, + 'tz_offset_hours' => person_tz_offset_hours + ) + end + let(:person2) do + Gitlab::Danger::Teammate.new( + 'username' => 'godfat', + 'available' => true, + 'tz_offset_hours' => person_tz_offset_hours) + end + let(:author) do + Gitlab::Danger::Teammate.new( + 'username' => 'filipa', + 'available' => true, + 'tz_offset_hours' => 0.0) + end + let(:unavailable) do + Gitlab::Danger::Teammate.new( + 'username' => 'jacopo-beschi', + 'available' => false, + 'tz_offset_hours' => 0.0) + end before do - stub_person_status(person1, message: 'making GitLab magic') - stub_person_status(person2, message: 'making GitLab magic') - stub_person_status(ooo, message: 'OOO till 15th') - stub_person_status(no_capacity, message: 'At capacity for the next few days', emoji: 'red_circle') - # we don't stub Filipa, as she is the author and - # we should not fire request checking for her - allow(subject).to receive_message_chain(:gitlab, :mr_author).and_return(author.username) end - it 'returns a random person' do - persons = [person1, person2] + (-4..4).each do |utc_offset| + context "when local hour for person is #{10 + utc_offset} (offset: #{utc_offset})" do + let(:person_tz_offset_hours) { utc_offset } - selected = subject.spin_for_person(persons, random: Random.new) + [false, true].each do |timezone_experiment| + context "with timezone_experiment == #{timezone_experiment}" do + it 'returns a random person' do + persons = [person1, person2] - expect(selected.username).to be_in(persons.map(&:username)) - end + selected = subject.spin_for_person(persons, random: Random.new, timezone_experiment: timezone_experiment) - it 'excludes OOO persons' do - expect(subject.spin_for_person([ooo], random: Random.new)).to be_nil + expect(selected.username).to be_in(persons.map(&:username)) + end + end + end + end end - it 'excludes mr.author' do - expect(subject.spin_for_person([author], random: Random.new)).to be_nil + ((-12..-5).to_a + (5..12).to_a).each do |utc_offset| + context "when local hour for person is #{10 + utc_offset} (offset: #{utc_offset})" do + let(:person_tz_offset_hours) { utc_offset } + + [false, true].each do |timezone_experiment| + context "with timezone_experiment == #{timezone_experiment}" do + it 'returns a random person or nil' do + persons = [person1, person2] + + selected = subject.spin_for_person(persons, random: Random.new, timezone_experiment: timezone_experiment) + + if timezone_experiment + expect(selected).to be_nil + else + expect(selected.username).to be_in(persons.map(&:username)) + end + end + end + end + end end - it 'excludes person with no capacity' do - expect(subject.spin_for_person([no_capacity], random: Random.new)).to be_nil + it 'excludes unavailable persons' do + expect(subject.spin_for_person([unavailable], random: Random.new)).to be_nil end - end - private - - def stub_person_status(person, message: 'dummy message', emoji: 'unicorn') - body = { message: message, emoji: emoji }.to_json - - WebMock - .stub_request(:get, "https://gitlab.com/api/v4/users/#{person.username}/status") - .to_return(body: body) + it 'excludes mr.author' do + expect(subject.spin_for_person([author], random: Random.new)).to be_nil + end end end diff --git a/spec/lib/gitlab/danger/sidekiq_queues_spec.rb b/spec/lib/gitlab/danger/sidekiq_queues_spec.rb new file mode 100644 index 00000000000..7dd1a2e6924 --- /dev/null +++ b/spec/lib/gitlab/danger/sidekiq_queues_spec.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +require 'fast_spec_helper' +require 'rspec-parameterized' +require_relative 'danger_spec_helper' + +require 'gitlab/danger/sidekiq_queues' + +RSpec.describe Gitlab::Danger::SidekiqQueues do + using RSpec::Parameterized::TableSyntax + include DangerSpecHelper + + let(:fake_git) { double('fake-git') } + let(:fake_danger) { new_fake_danger.include(described_class) } + + subject(:sidekiq_queues) { fake_danger.new(git: fake_git) } + + describe '#changed_queue_files' do + where(:modified_files, :changed_queue_files) do + %w(app/workers/all_queues.yml ee/app/workers/all_queues.yml foo) | %w(app/workers/all_queues.yml ee/app/workers/all_queues.yml) + %w(app/workers/all_queues.yml ee/app/workers/all_queues.yml) | %w(app/workers/all_queues.yml ee/app/workers/all_queues.yml) + %w(app/workers/all_queues.yml foo) | %w(app/workers/all_queues.yml) + %w(ee/app/workers/all_queues.yml foo) | %w(ee/app/workers/all_queues.yml) + %w(foo) | %w() + %w() | %w() + end + + with_them do + it do + allow(fake_git).to receive(:modified_files).and_return(modified_files) + + expect(sidekiq_queues.changed_queue_files).to match_array(changed_queue_files) + end + end + end + + describe '#added_queue_names' do + it 'returns queue names added by this change' do + old_queues = { post_receive: nil } + + allow(sidekiq_queues).to receive(:old_queues).and_return(old_queues) + allow(sidekiq_queues).to receive(:new_queues).and_return(old_queues.merge(merge: nil, process_commit: nil)) + + expect(sidekiq_queues.added_queue_names).to contain_exactly(:merge, :process_commit) + end + end + + describe '#changed_queue_names' do + it 'returns names for queues whose attributes were changed' do + old_queues = { + merge: { name: :merge, urgency: :low }, + post_receive: { name: :post_receive, urgency: :high }, + process_commit: { name: :process_commit, urgency: :high } + } + + new_queues = old_queues.merge(mailers: { name: :mailers, urgency: :high }, + post_receive: { name: :post_receive, urgency: :low }, + process_commit: { name: :process_commit, urgency: :low }) + + allow(sidekiq_queues).to receive(:old_queues).and_return(old_queues) + allow(sidekiq_queues).to receive(:new_queues).and_return(new_queues) + + expect(sidekiq_queues.changed_queue_names).to contain_exactly(:post_receive, :process_commit) + end + + it 'ignores removed queues' do + old_queues = { + merge: { name: :merge, urgency: :low }, + post_receive: { name: :post_receive, urgency: :high } + } + + new_queues = { + post_receive: { name: :post_receive, urgency: :low } + } + + allow(sidekiq_queues).to receive(:old_queues).and_return(old_queues) + allow(sidekiq_queues).to receive(:new_queues).and_return(new_queues) + + expect(sidekiq_queues.changed_queue_names).to contain_exactly(:post_receive) + end + end +end diff --git a/spec/lib/gitlab/danger/teammate_spec.rb b/spec/lib/gitlab/danger/teammate_spec.rb index ea5aecbc597..a0540a9fbf5 100644 --- a/spec/lib/gitlab/danger/teammate_spec.rb +++ b/spec/lib/gitlab/danger/teammate_spec.rb @@ -2,14 +2,27 @@ require 'fast_spec_helper' +require 'timecop' require 'rspec-parameterized' require 'gitlab/danger/teammate' -describe Gitlab::Danger::Teammate do +RSpec.describe Gitlab::Danger::Teammate do + using RSpec::Parameterized::TableSyntax + subject { described_class.new(options.stringify_keys) } - let(:options) { { username: 'luigi', projects: projects, role: role } } + let(:tz_offset_hours) { 2.0 } + let(:options) do + { + username: 'luigi', + projects: projects, + role: role, + markdown_name: '[Luigi](https://gitlab.com/luigi) (`@luigi`)', + tz_offset_hours: tz_offset_hours + } + end + let(:capabilities) { ['reviewer backend'] } let(:projects) { { project => capabilities } } let(:role) { 'Engineer, Manage' } let(:labels) { [] } @@ -115,78 +128,72 @@ describe Gitlab::Danger::Teammate do end end - describe '#status' do - let(:capabilities) { ['dish washing'] } - - context 'with empty cache' do - context 'for successful request' do - it 'returns the response' do - mock_status = double(does_not: 'matter') - expect(Gitlab::Danger::RequestHelper).to receive(:http_get_json) - .and_return(mock_status) + describe '#local_hour' do + around do |example| + Timecop.freeze(Time.utc(2020, 6, 23, 10)) { example.run } + end - expect(subject.status).to be mock_status - end + context 'when author is given' do + where(:tz_offset_hours, :expected_local_hour) do + -12 | 22 + -10 | 0 + 2 | 12 + 4 | 14 + 12 | 22 end - context 'for failing request' do - it 'returns nil' do - expect(Gitlab::Danger::RequestHelper).to receive(:http_get_json) - .and_raise(Gitlab::Danger::RequestHelper::HTTPError.new) - - expect(subject.status).to be nil + with_them do + it 'returns the correct local_hour' do + expect(subject.local_hour).to eq(expected_local_hour) end end end + end - context 'with filled cache' do - it 'returns the cached response' do - mock_status = double(does_not: 'matter') - expect(Gitlab::Danger::RequestHelper).to receive(:http_get_json) - .and_return(mock_status) - subject.status - - expect(Gitlab::Danger::RequestHelper).not_to receive(:http_get_json) - expect(subject.status).to be mock_status + describe '#markdown_name' do + context 'when timezone_experiment == false' do + it 'returns markdown name as-is' do + expect(subject.markdown_name).to eq(options[:markdown_name]) + expect(subject.markdown_name(timezone_experiment: false)).to eq(options[:markdown_name]) end end - end - describe '#available?' do - using RSpec::Parameterized::TableSyntax - - let(:capabilities) { ['dry head'] } - - where(:status, :result) do - {} | true - { message: 'dear reader' } | true - { message: 'OOO: massage' } | false - { message: 'love it SOOO much' } | false - { emoji: 'red_circle' } | false - { emoji: 'palm_tree' } | false - { emoji: 'beach' } | false - { emoji: 'beach_umbrella' } | false - { emoji: 'beach_with_umbrella' } | false - { emoji: nil } | true - { emoji: '' } | true - { emoji: 'dancer' } | true - end + context 'when timezone_experiment == true' do + it 'returns markdown name with timezone info' do + expect(subject.markdown_name(timezone_experiment: true)).to eq("#{options[:markdown_name]} (UTC+2)") + end + + context 'when offset is 1.5' do + let(:tz_offset_hours) { 1.5 } - with_them do - before do - expect(Gitlab::Danger::RequestHelper).to receive(:http_get_json) - .and_return(status&.stringify_keys) + it 'returns markdown name with timezone info, not truncated' do + expect(subject.markdown_name(timezone_experiment: true)).to eq("#{options[:markdown_name]} (UTC+1.5)") + end end - it { expect(subject.available?).to be result } - end + context 'when author is given' do + where(:tz_offset_hours, :author_offset, :diff_text) do + -12 | -10 | "2 hours behind `@mario`" + -10 | -12 | "2 hours ahead `@mario`" + -10 | 2 | "12 hours behind `@mario`" + 2 | 4 | "2 hours behind `@mario`" + 4 | 2 | "2 hours ahead `@mario`" + 2 | 3 | "1 hour behind `@mario`" + 3 | 2 | "1 hour ahead `@mario`" + 2 | 2 | "same timezone as `@mario`" + end - it 'returns true if request fails' do - expect(Gitlab::Danger::RequestHelper) - .to receive(:http_get_json) - .and_raise(Gitlab::Danger::RequestHelper::HTTPError.new) + with_them do + it 'returns markdown name with timezone info' do + author = described_class.new(options.merge(username: 'mario', tz_offset_hours: author_offset).stringify_keys) - expect(subject.available?).to be true + floored_offset_hours = subject.__send__(:floored_offset_hours) + utc_offset = floored_offset_hours >= 0 ? "+#{floored_offset_hours}" : floored_offset_hours + + expect(subject.markdown_name(timezone_experiment: true, author: author)).to eq("#{options[:markdown_name]} (UTC#{utc_offset}, #{diff_text})") + end + end + end end end end diff --git a/spec/lib/gitlab/data_builder/alert_spec.rb b/spec/lib/gitlab/data_builder/alert_spec.rb index b881fb8139b..6c3dc3cd8b4 100644 --- a/spec/lib/gitlab/data_builder/alert_spec.rb +++ b/spec/lib/gitlab/data_builder/alert_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DataBuilder::Alert do +RSpec.describe Gitlab::DataBuilder::Alert do let_it_be(:project) { create(:project) } let_it_be(:alert) { create(:alert_management_alert, project: project) } diff --git a/spec/lib/gitlab/data_builder/build_spec.rb b/spec/lib/gitlab/data_builder/build_spec.rb index da27125c9a6..cfaaf849b09 100644 --- a/spec/lib/gitlab/data_builder/build_spec.rb +++ b/spec/lib/gitlab/data_builder/build_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DataBuilder::Build do +RSpec.describe Gitlab::DataBuilder::Build do let(:runner) { create(:ci_runner, :instance) } let(:user) { create(:user) } let(:build) { create(:ci_build, :running, runner: runner, user: user) } diff --git a/spec/lib/gitlab/data_builder/deployment_spec.rb b/spec/lib/gitlab/data_builder/deployment_spec.rb index 42d7329494d..57bde6262a9 100644 --- a/spec/lib/gitlab/data_builder/deployment_spec.rb +++ b/spec/lib/gitlab/data_builder/deployment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DataBuilder::Deployment do +RSpec.describe Gitlab::DataBuilder::Deployment do describe '.build' do it 'returns the object kind for a deployment' do deployment = build(:deployment) diff --git a/spec/lib/gitlab/data_builder/note_spec.rb b/spec/lib/gitlab/data_builder/note_spec.rb index 4b799c23de8..90ca5430526 100644 --- a/spec/lib/gitlab/data_builder/note_spec.rb +++ b/spec/lib/gitlab/data_builder/note_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DataBuilder::Note do +RSpec.describe Gitlab::DataBuilder::Note do let(:project) { create(:project, :repository) } let(:user) { create(:user) } let(:data) { described_class.build(note, user) } diff --git a/spec/lib/gitlab/data_builder/pipeline_spec.rb b/spec/lib/gitlab/data_builder/pipeline_spec.rb index 519f5873d75..4e0cc8a1fa9 100644 --- a/spec/lib/gitlab/data_builder/pipeline_spec.rb +++ b/spec/lib/gitlab/data_builder/pipeline_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DataBuilder::Pipeline do +RSpec.describe Gitlab::DataBuilder::Pipeline do let(:user) { create(:user) } let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/data_builder/push_spec.rb b/spec/lib/gitlab/data_builder/push_spec.rb index cbc03fc38eb..7eb81a880bf 100644 --- a/spec/lib/gitlab/data_builder/push_spec.rb +++ b/spec/lib/gitlab/data_builder/push_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DataBuilder::Push do +RSpec.describe Gitlab::DataBuilder::Push do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/data_builder/wiki_page_spec.rb b/spec/lib/gitlab/data_builder/wiki_page_spec.rb index ae338e30a69..ec768cf9719 100644 --- a/spec/lib/gitlab/data_builder/wiki_page_spec.rb +++ b/spec/lib/gitlab/data_builder/wiki_page_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DataBuilder::WikiPage do +RSpec.describe Gitlab::DataBuilder::WikiPage do let_it_be(:project) { create(:project, :repository, :wiki_repo) } let(:wiki_page) { create(:wiki_page, wiki: project.wiki) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/database/background_migration_job_spec.rb b/spec/lib/gitlab/database/background_migration_job_spec.rb new file mode 100644 index 00000000000..40f47325be3 --- /dev/null +++ b/spec/lib/gitlab/database/background_migration_job_spec.rb @@ -0,0 +1,125 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Database::BackgroundMigrationJob do + it_behaves_like 'having unique enum values' + + describe '.for_migration_execution' do + let!(:job1) { create(:background_migration_job) } + let!(:job2) { create(:background_migration_job, arguments: ['hi', 2]) } + let!(:job3) { create(:background_migration_job, class_name: 'OtherJob', arguments: ['hi', 2]) } + + it 'returns jobs matching class_name and arguments' do + relation = described_class.for_migration_execution('TestJob', ['hi', 2]) + + expect(relation.count).to eq(1) + expect(relation.first).to have_attributes(class_name: 'TestJob', arguments: ['hi', 2]) + end + + it 'normalizes class names by removing leading ::' do + relation = described_class.for_migration_execution('::TestJob', ['hi', 2]) + + expect(relation.count).to eq(1) + expect(relation.first).to have_attributes(class_name: 'TestJob', arguments: ['hi', 2]) + end + end + + describe '.for_partitioning_migration' do + let!(:job1) { create(:background_migration_job, arguments: [1, 100, 'other_table']) } + let!(:job2) { create(:background_migration_job, arguments: [1, 100, 'audit_events']) } + let!(:job3) { create(:background_migration_job, class_name: 'OtherJob', arguments: [1, 100, 'audit_events']) } + + it 'returns jobs matching class_name and the table_name job argument' do + relation = described_class.for_partitioning_migration('TestJob', 'audit_events') + + expect(relation.count).to eq(1) + expect(relation.first).to have_attributes(class_name: 'TestJob', arguments: [1, 100, 'audit_events']) + end + + it 'normalizes class names by removing leading ::' do + relation = described_class.for_partitioning_migration('::TestJob', 'audit_events') + + expect(relation.count).to eq(1) + expect(relation.first).to have_attributes(class_name: 'TestJob', arguments: [1, 100, 'audit_events']) + end + end + + describe '.mark_all_as_succeeded' do + let!(:job1) { create(:background_migration_job, arguments: [1, 100]) } + let!(:job2) { create(:background_migration_job, arguments: [1, 100]) } + let!(:job3) { create(:background_migration_job, arguments: [101, 200]) } + let!(:job4) { create(:background_migration_job, class_name: 'OtherJob', arguments: [1, 100]) } + + it 'marks all matching jobs as succeeded' do + expect { described_class.mark_all_as_succeeded('TestJob', [1, 100]) } + .to change { described_class.succeeded.count }.from(0).to(2) + + expect(job1.reload).to be_succeeded + expect(job2.reload).to be_succeeded + expect(job3.reload).to be_pending + expect(job4.reload).to be_pending + end + + it 'normalizes class_names by removing leading ::' do + expect { described_class.mark_all_as_succeeded('::TestJob', [1, 100]) } + .to change { described_class.succeeded.count }.from(0).to(2) + + expect(job1.reload).to be_succeeded + expect(job2.reload).to be_succeeded + expect(job3.reload).to be_pending + expect(job4.reload).to be_pending + end + + context 'when previous matching jobs have already succeeded' do + let(:initial_time) { Time.now.round } + let!(:job1) { create(:background_migration_job, :succeeded, created_at: initial_time, updated_at: initial_time) } + + it 'does not update non-pending jobs' do + Timecop.freeze(initial_time + 1.day) do + expect { described_class.mark_all_as_succeeded('TestJob', [1, 100]) } + .to change { described_class.succeeded.count }.from(1).to(2) + end + + expect(job1.reload.updated_at).to eq(initial_time) + expect(job2.reload).to be_succeeded + expect(job3.reload).to be_pending + expect(job4.reload).to be_pending + end + end + end + + describe '#class_name=' do + context 'when the class_name is given without the leading ::' do + it 'sets the class_name to the given value' do + job = described_class.new(class_name: 'TestJob') + + expect(job.class_name).to eq('TestJob') + end + end + + context 'when the class_name is given with the leading ::' do + it 'removes the leading :: when setting the class_name' do + job = described_class.new(class_name: '::TestJob') + + expect(job.class_name).to eq('TestJob') + end + end + + context 'when the value is nil' do + it 'sets the class_name to nil' do + job = described_class.new(class_name: nil) + + expect(job.class_name).to be_nil + end + end + + context 'when the values is blank' do + it 'sets the class_name to the given value' do + job = described_class.new(class_name: '') + + expect(job.class_name).to eq('') + end + end + end +end diff --git a/spec/lib/gitlab/database/batch_count_spec.rb b/spec/lib/gitlab/database/batch_count_spec.rb index e7cb53f2dbd..656501dbf56 100644 --- a/spec/lib/gitlab/database/batch_count_spec.rb +++ b/spec/lib/gitlab/database/batch_count_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::BatchCount do +RSpec.describe Gitlab::Database::BatchCount do let_it_be(:fallback) { ::Gitlab::Database::BatchCounter::FALLBACK } let_it_be(:small_batch_size) { ::Gitlab::Database::BatchCounter::MIN_REQUIRED_BATCH_SIZE - 1 } let(:model) { Issue } diff --git a/spec/lib/gitlab/database/connection_timer_spec.rb b/spec/lib/gitlab/database/connection_timer_spec.rb index c9e9d770343..2b6746bae07 100644 --- a/spec/lib/gitlab/database/connection_timer_spec.rb +++ b/spec/lib/gitlab/database/connection_timer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::ConnectionTimer do +RSpec.describe Gitlab::Database::ConnectionTimer do let(:current_clock_value) { 1234.56 } before do diff --git a/spec/lib/gitlab/database/count/exact_count_strategy_spec.rb b/spec/lib/gitlab/database/count/exact_count_strategy_spec.rb index 111833a506a..390620379d6 100644 --- a/spec/lib/gitlab/database/count/exact_count_strategy_spec.rb +++ b/spec/lib/gitlab/database/count/exact_count_strategy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::Count::ExactCountStrategy do +RSpec.describe Gitlab::Database::Count::ExactCountStrategy do before do create_list(:project, 3) create(:identity) diff --git a/spec/lib/gitlab/database/count/reltuples_count_strategy_spec.rb b/spec/lib/gitlab/database/count/reltuples_count_strategy_spec.rb index 08032d19d14..324ed498abc 100644 --- a/spec/lib/gitlab/database/count/reltuples_count_strategy_spec.rb +++ b/spec/lib/gitlab/database/count/reltuples_count_strategy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::Count::ReltuplesCountStrategy do +RSpec.describe Gitlab::Database::Count::ReltuplesCountStrategy do before do create_list(:project, 3) create(:identity) diff --git a/spec/lib/gitlab/database/count/tablesample_count_strategy_spec.rb b/spec/lib/gitlab/database/count/tablesample_count_strategy_spec.rb index 0c480709c22..e488bf5ee4c 100644 --- a/spec/lib/gitlab/database/count/tablesample_count_strategy_spec.rb +++ b/spec/lib/gitlab/database/count/tablesample_count_strategy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::Count::TablesampleCountStrategy do +RSpec.describe Gitlab::Database::Count::TablesampleCountStrategy do before do create_list(:project, 3) create(:identity) diff --git a/spec/lib/gitlab/database/count_spec.rb b/spec/lib/gitlab/database/count_spec.rb index 2469ce482e7..d65413c2a00 100644 --- a/spec/lib/gitlab/database/count_spec.rb +++ b/spec/lib/gitlab/database/count_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::Count do +RSpec.describe Gitlab::Database::Count do before do create_list(:project, 3) create(:identity) diff --git a/spec/lib/gitlab/database/custom_structure_spec.rb b/spec/lib/gitlab/database/custom_structure_spec.rb index f03b5ed0a7f..beda9df3684 100644 --- a/spec/lib/gitlab/database/custom_structure_spec.rb +++ b/spec/lib/gitlab/database/custom_structure_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::CustomStructure do +RSpec.describe Gitlab::Database::CustomStructure do let_it_be(:structure) { described_class.new } let_it_be(:filepath) { Rails.root.join(described_class::CUSTOM_DUMP_FILE) } let_it_be(:file_header) do diff --git a/spec/lib/gitlab/database/dynamic_model_helpers_spec.rb b/spec/lib/gitlab/database/dynamic_model_helpers_spec.rb new file mode 100644 index 00000000000..23ad621d0ee --- /dev/null +++ b/spec/lib/gitlab/database/dynamic_model_helpers_spec.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Database::DynamicModelHelpers do + describe '#define_batchable_model' do + subject { including_class.new.define_batchable_model(table_name) } + + let(:including_class) { Class.new.include(described_class) } + let(:table_name) { 'projects' } + + it 'is an ActiveRecord model' do + expect(subject.ancestors).to include(ActiveRecord::Base) + end + + it 'includes EachBatch' do + expect(subject.included_modules).to include(EachBatch) + end + + it 'has the correct table name' do + expect(subject.table_name).to eq(table_name) + end + + it 'has the inheritance type column disable' do + expect(subject.inheritance_column).to eq('_type_disabled') + end + end +end diff --git a/spec/lib/gitlab/database/grant_spec.rb b/spec/lib/gitlab/database/grant_spec.rb index 02697eb2a16..23aec85d1d0 100644 --- a/spec/lib/gitlab/database/grant_spec.rb +++ b/spec/lib/gitlab/database/grant_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::Grant do +RSpec.describe Gitlab::Database::Grant do describe '.create_and_execute_trigger' do it 'returns true when the user can create and execute a trigger' do # We assume the DB/user is set up correctly so that triggers can be diff --git a/spec/lib/gitlab/database/migration_helpers_spec.rb b/spec/lib/gitlab/database/migration_helpers_spec.rb index bed444ee7c7..48e1c97e97f 100644 --- a/spec/lib/gitlab/database/migration_helpers_spec.rb +++ b/spec/lib/gitlab/database/migration_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::MigrationHelpers do +RSpec.describe Gitlab::Database::MigrationHelpers do let(:model) do ActiveRecord::Migration.new.extend(described_class) end @@ -178,6 +178,19 @@ describe Gitlab::Database::MigrationHelpers do model.remove_concurrent_index_by_name(:users, "index_x_by_y") end + + it 'removes the index with keyword arguments' do + expect(model).to receive(:remove_index) + .with(:users, { algorithm: :concurrently, name: "index_x_by_y" }) + + model.remove_concurrent_index_by_name(:users, name: "index_x_by_y") + end + + it 'raises an error if the index is blank' do + expect do + model.remove_concurrent_index_by_name(:users, wrong_key: "index_x_by_y") + end.to raise_error 'remove_concurrent_index_by_name must get an index name as the second argument' + end end end end @@ -690,12 +703,28 @@ describe Gitlab::Database::MigrationHelpers do model.rename_column_concurrently(:users, :old, :new) end + context 'with existing records and type casting' do + let(:trigger_name) { model.rename_trigger_name(:users, :id, :new) } + let(:user) { create(:user) } + + it 'copies the value to the new column using the type_cast_function', :aggregate_failures do + expect(model).to receive(:copy_indexes).with(:users, :id, :new) + expect(model).to receive(:add_not_null_constraint).with(:users, :new) + expect(model).to receive(:execute).with("UPDATE \"users\" SET \"new\" = cast_to_jsonb_with_default(\"users\".\"id\") WHERE \"users\".\"id\" >= #{user.id}") + expect(model).to receive(:execute).with("DROP TRIGGER IF EXISTS #{trigger_name}\nON \"users\"\n") + expect(model).to receive(:execute).with("CREATE TRIGGER #{trigger_name}\nBEFORE INSERT OR UPDATE\nON \"users\"\nFOR EACH ROW\nEXECUTE PROCEDURE #{trigger_name}()\n") + expect(model).to receive(:execute).with("CREATE OR REPLACE FUNCTION #{trigger_name}()\nRETURNS trigger AS\n$BODY$\nBEGIN\n NEW.\"new\" := NEW.\"id\";\n RETURN NEW;\nEND;\n$BODY$\nLANGUAGE 'plpgsql'\nVOLATILE\n") + + model.rename_column_concurrently(:users, :id, :new, type_cast_function: 'cast_to_jsonb_with_default') + end + end + it 'passes the batch_column_name' do expect(model).to receive(:column_exists?).with(:users, :other_batch_column).and_return(true) expect(model).to receive(:check_trigger_permissions!).and_return(true) expect(model).to receive(:create_column_from).with( - :users, :old, :new, type: nil, batch_column_name: :other_batch_column + :users, :old, :new, type: nil, batch_column_name: :other_batch_column, type_cast_function: nil ).and_return(true) expect(model).to receive(:install_rename_triggers).and_return(true) @@ -703,6 +732,14 @@ describe Gitlab::Database::MigrationHelpers do model.rename_column_concurrently(:users, :old, :new, batch_column_name: :other_batch_column) end + it 'passes the type_cast_function' do + expect(model).to receive(:create_column_from).with( + :users, :old, :new, type: nil, batch_column_name: :id, type_cast_function: 'JSON' + ).and_return(true) + + model.rename_column_concurrently(:users, :old, :new, type_cast_function: 'JSON') + end + it 'raises an error with invalid batch_column_name' do expect do model.rename_column_concurrently(:users, :old, :new, batch_column_name: :invalid) @@ -866,10 +903,19 @@ describe Gitlab::Database::MigrationHelpers do describe '#change_column_type_concurrently' do it 'changes the column type' do expect(model).to receive(:rename_column_concurrently) - .with('users', 'username', 'username_for_type_change', type: :text) + .with('users', 'username', 'username_for_type_change', type: :text, type_cast_function: nil) model.change_column_type_concurrently('users', 'username', :text) end + + context 'with type cast' do + it 'changes the column type with casting the value to the new type' do + expect(model).to receive(:rename_column_concurrently) + .with('users', 'username', 'username_for_type_change', type: :text, type_cast_function: 'JSON') + + model.change_column_type_concurrently('users', 'username', :text, type_cast_function: 'JSON') + end + end end describe '#cleanup_concurrent_column_type_change' do @@ -1215,166 +1261,6 @@ describe Gitlab::Database::MigrationHelpers do end end - describe '#bulk_queue_background_migration_jobs_by_range' do - context 'when the model has an ID column' do - let!(:id1) { create(:user).id } - let!(:id2) { create(:user).id } - let!(:id3) { create(:user).id } - - before do - User.class_eval do - include EachBatch - end - end - - context 'with enough rows to bulk queue jobs more than once' do - before do - stub_const('Gitlab::Database::MigrationHelpers::BACKGROUND_MIGRATION_JOB_BUFFER_SIZE', 1) - end - - it 'queues jobs correctly' do - Sidekiq::Testing.fake! do - model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) - - expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]]) - expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]]) - end - end - - it 'queues jobs in groups of buffer size 1' do - expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]]]) - expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id3, id3]]]) - - model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) - end - end - - context 'with not enough rows to bulk queue jobs more than once' do - it 'queues jobs correctly' do - Sidekiq::Testing.fake! do - model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) - - expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]]) - expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]]) - end - end - - it 'queues jobs in bulk all at once (big buffer size)' do - expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]], - ['FooJob', [id3, id3]]]) - - model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) - end - end - - context 'without specifying batch_size' do - it 'queues jobs correctly' do - Sidekiq::Testing.fake! do - model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob') - - expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3]]) - end - end - end - end - - context "when the model doesn't have an ID column" do - it 'raises error (for now)' do - expect do - model.bulk_queue_background_migration_jobs_by_range(ProjectAuthorization, 'FooJob') - end.to raise_error(StandardError, /does not have an ID/) - end - end - end - - describe '#queue_background_migration_jobs_by_range_at_intervals' do - context 'when the model has an ID column' do - let!(:id1) { create(:user).id } - let!(:id2) { create(:user).id } - let!(:id3) { create(:user).id } - - around do |example| - Timecop.freeze { example.run } - end - - before do - User.class_eval do - include EachBatch - end - end - - it 'returns the final expected delay' do - Sidekiq::Testing.fake! do - final_delay = model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, batch_size: 2) - - expect(final_delay.to_f).to eq(20.minutes.to_f) - end - end - - it 'returns zero when nothing gets queued' do - Sidekiq::Testing.fake! do - final_delay = model.queue_background_migration_jobs_by_range_at_intervals(User.none, 'FooJob', 10.minutes) - - expect(final_delay).to eq(0) - end - end - - context 'with batch_size option' do - it 'queues jobs correctly' do - Sidekiq::Testing.fake! do - model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, batch_size: 2) - - expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]]) - expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f) - expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]]) - expect(BackgroundMigrationWorker.jobs[1]['at']).to eq(20.minutes.from_now.to_f) - end - end - end - - context 'without batch_size option' do - it 'queues jobs correctly' do - Sidekiq::Testing.fake! do - model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes) - - expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3]]) - expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f) - end - end - end - - context 'with other_job_arguments option' do - it 'queues jobs correctly' do - Sidekiq::Testing.fake! do - model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, other_job_arguments: [1, 2]) - - expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3, 1, 2]]) - expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f) - end - end - end - - context 'with initial_delay option' do - it 'queues jobs correctly' do - Sidekiq::Testing.fake! do - model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, other_job_arguments: [1, 2], initial_delay: 10.minutes) - - expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3, 1, 2]]) - expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(20.minutes.from_now.to_f) - end - end - end - end - - context "when the model doesn't have an ID column" do - it 'raises error (for now)' do - expect do - model.queue_background_migration_jobs_by_range_at_intervals(ProjectAuthorization, 'FooJob', 10.seconds) - end.to raise_error(StandardError, /does not have an ID/) - end - end - end - describe '#change_column_type_using_background_migration' do let!(:issue) { create(:issue, :closed, closed_at: Time.zone.now) } @@ -1485,26 +1371,6 @@ describe Gitlab::Database::MigrationHelpers do end end - describe '#perform_background_migration_inline?' do - it 'returns true in a test environment' do - stub_rails_env('test') - - expect(model.perform_background_migration_inline?).to eq(true) - end - - it 'returns true in a development environment' do - stub_rails_env('development') - - expect(model.perform_background_migration_inline?).to eq(true) - end - - it 'returns false in a production environment' do - stub_rails_env('production') - - expect(model.perform_background_migration_inline?).to eq(false) - end - end - describe '#index_exists_by_name?' do it 'returns true if an index exists' do ActiveRecord::Base.connection.execute( @@ -1973,62 +1839,6 @@ describe Gitlab::Database::MigrationHelpers do end end - describe '#migrate_async' do - it 'calls BackgroundMigrationWorker.perform_async' do - expect(BackgroundMigrationWorker).to receive(:perform_async).with("Class", "hello", "world") - - model.migrate_async("Class", "hello", "world") - end - - it 'pushes a context with the current class name as caller_id' do - expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) - - model.migrate_async('Class', 'hello', 'world') - end - end - - describe '#migrate_in' do - it 'calls BackgroundMigrationWorker.perform_in' do - expect(BackgroundMigrationWorker).to receive(:perform_in).with(10.minutes, 'Class', 'Hello', 'World') - - model.migrate_in(10.minutes, 'Class', 'Hello', 'World') - end - - it 'pushes a context with the current class name as caller_id' do - expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) - - model.migrate_in(10.minutes, 'Class', 'Hello', 'World') - end - end - - describe '#bulk_migrate_async' do - it 'calls BackgroundMigrationWorker.bulk_perform_async' do - expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([%w(Class hello world)]) - - model.bulk_migrate_async([%w(Class hello world)]) - end - - it 'pushes a context with the current class name as caller_id' do - expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) - - model.bulk_migrate_async([%w(Class hello world)]) - end - end - - describe '#bulk_migrate_in' do - it 'calls BackgroundMigrationWorker.bulk_perform_in_' do - expect(BackgroundMigrationWorker).to receive(:bulk_perform_in).with(10.minutes, [%w(Class hello world)]) - - model.bulk_migrate_in(10.minutes, [%w(Class hello world)]) - end - - it 'pushes a context with the current class name as caller_id' do - expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) - - model.bulk_migrate_in(10.minutes, [%w(Class hello world)]) - end - end - describe '#check_constraint_name' do it 'returns a valid constraint name' do name = model.check_constraint_name(:this_is_a_very_long_table_name, diff --git a/spec/lib/gitlab/database/migrations/background_migration_helpers_spec.rb b/spec/lib/gitlab/database/migrations/background_migration_helpers_spec.rb new file mode 100644 index 00000000000..042ac498373 --- /dev/null +++ b/spec/lib/gitlab/database/migrations/background_migration_helpers_spec.rb @@ -0,0 +1,276 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Database::Migrations::BackgroundMigrationHelpers do + let(:model) do + ActiveRecord::Migration.new.extend(described_class) + end + + describe '#bulk_queue_background_migration_jobs_by_range' do + context 'when the model has an ID column' do + let!(:id1) { create(:user).id } + let!(:id2) { create(:user).id } + let!(:id3) { create(:user).id } + + before do + User.class_eval do + include EachBatch + end + end + + context 'with enough rows to bulk queue jobs more than once' do + before do + stub_const('Gitlab::Database::Migrations::BackgroundMigrationHelpers::BACKGROUND_MIGRATION_JOB_BUFFER_SIZE', 1) + end + + it 'queues jobs correctly' do + Sidekiq::Testing.fake! do + model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) + + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]]) + expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]]) + end + end + + it 'queues jobs in groups of buffer size 1' do + expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]]]) + expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id3, id3]]]) + + model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) + end + end + + context 'with not enough rows to bulk queue jobs more than once' do + it 'queues jobs correctly' do + Sidekiq::Testing.fake! do + model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) + + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]]) + expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]]) + end + end + + it 'queues jobs in bulk all at once (big buffer size)' do + expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([['FooJob', [id1, id2]], + ['FooJob', [id3, id3]]]) + + model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob', batch_size: 2) + end + end + + context 'without specifying batch_size' do + it 'queues jobs correctly' do + Sidekiq::Testing.fake! do + model.bulk_queue_background_migration_jobs_by_range(User, 'FooJob') + + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3]]) + end + end + end + end + + context "when the model doesn't have an ID column" do + it 'raises error (for now)' do + expect do + model.bulk_queue_background_migration_jobs_by_range(ProjectAuthorization, 'FooJob') + end.to raise_error(StandardError, /does not have an ID/) + end + end + end + + describe '#queue_background_migration_jobs_by_range_at_intervals' do + context 'when the model has an ID column' do + let!(:id1) { create(:user).id } + let!(:id2) { create(:user).id } + let!(:id3) { create(:user).id } + + around do |example| + Timecop.freeze { example.run } + end + + before do + User.class_eval do + include EachBatch + end + end + + it 'returns the final expected delay' do + Sidekiq::Testing.fake! do + final_delay = model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, batch_size: 2) + + expect(final_delay.to_f).to eq(20.minutes.to_f) + end + end + + it 'returns zero when nothing gets queued' do + Sidekiq::Testing.fake! do + final_delay = model.queue_background_migration_jobs_by_range_at_intervals(User.none, 'FooJob', 10.minutes) + + expect(final_delay).to eq(0) + end + end + + context 'with batch_size option' do + it 'queues jobs correctly' do + Sidekiq::Testing.fake! do + model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, batch_size: 2) + + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id2]]) + expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f) + expect(BackgroundMigrationWorker.jobs[1]['args']).to eq(['FooJob', [id3, id3]]) + expect(BackgroundMigrationWorker.jobs[1]['at']).to eq(20.minutes.from_now.to_f) + end + end + end + + context 'without batch_size option' do + it 'queues jobs correctly' do + Sidekiq::Testing.fake! do + model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes) + + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3]]) + expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f) + end + end + end + + context 'with other_job_arguments option' do + it 'queues jobs correctly' do + Sidekiq::Testing.fake! do + model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, other_job_arguments: [1, 2]) + + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3, 1, 2]]) + expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(10.minutes.from_now.to_f) + end + end + end + + context 'with initial_delay option' do + it 'queues jobs correctly' do + Sidekiq::Testing.fake! do + model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, other_job_arguments: [1, 2], initial_delay: 10.minutes) + + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq(['FooJob', [id1, id3, 1, 2]]) + expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(20.minutes.from_now.to_f) + end + end + end + + context 'with track_jobs option' do + it 'creates a record for each job in the database' do + Sidekiq::Testing.fake! do + expect do + model.queue_background_migration_jobs_by_range_at_intervals(User, '::FooJob', 10.minutes, + other_job_arguments: [1, 2], track_jobs: true) + end.to change { Gitlab::Database::BackgroundMigrationJob.count }.from(0).to(1) + + expect(BackgroundMigrationWorker.jobs.size).to eq(1) + + tracked_job = Gitlab::Database::BackgroundMigrationJob.first + + expect(tracked_job.class_name).to eq('FooJob') + expect(tracked_job.arguments).to eq([id1, id3, 1, 2]) + expect(tracked_job).to be_pending + end + end + end + + context 'without track_jobs option' do + it 'does not create records in the database' do + Sidekiq::Testing.fake! do + expect do + model.queue_background_migration_jobs_by_range_at_intervals(User, 'FooJob', 10.minutes, other_job_arguments: [1, 2]) + end.not_to change { Gitlab::Database::BackgroundMigrationJob.count } + + expect(BackgroundMigrationWorker.jobs.size).to eq(1) + end + end + end + end + + context "when the model doesn't have an ID column" do + it 'raises error (for now)' do + expect do + model.queue_background_migration_jobs_by_range_at_intervals(ProjectAuthorization, 'FooJob', 10.seconds) + end.to raise_error(StandardError, /does not have an ID/) + end + end + end + + describe '#perform_background_migration_inline?' do + it 'returns true in a test environment' do + stub_rails_env('test') + + expect(model.perform_background_migration_inline?).to eq(true) + end + + it 'returns true in a development environment' do + stub_rails_env('development') + + expect(model.perform_background_migration_inline?).to eq(true) + end + + it 'returns false in a production environment' do + stub_rails_env('production') + + expect(model.perform_background_migration_inline?).to eq(false) + end + end + + describe '#migrate_async' do + it 'calls BackgroundMigrationWorker.perform_async' do + expect(BackgroundMigrationWorker).to receive(:perform_async).with("Class", "hello", "world") + + model.migrate_async("Class", "hello", "world") + end + + it 'pushes a context with the current class name as caller_id' do + expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) + + model.migrate_async('Class', 'hello', 'world') + end + end + + describe '#migrate_in' do + it 'calls BackgroundMigrationWorker.perform_in' do + expect(BackgroundMigrationWorker).to receive(:perform_in).with(10.minutes, 'Class', 'Hello', 'World') + + model.migrate_in(10.minutes, 'Class', 'Hello', 'World') + end + + it 'pushes a context with the current class name as caller_id' do + expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) + + model.migrate_in(10.minutes, 'Class', 'Hello', 'World') + end + end + + describe '#bulk_migrate_async' do + it 'calls BackgroundMigrationWorker.bulk_perform_async' do + expect(BackgroundMigrationWorker).to receive(:bulk_perform_async).with([%w(Class hello world)]) + + model.bulk_migrate_async([%w(Class hello world)]) + end + + it 'pushes a context with the current class name as caller_id' do + expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) + + model.bulk_migrate_async([%w(Class hello world)]) + end + end + + describe '#bulk_migrate_in' do + it 'calls BackgroundMigrationWorker.bulk_perform_in_' do + expect(BackgroundMigrationWorker).to receive(:bulk_perform_in).with(10.minutes, [%w(Class hello world)]) + + model.bulk_migrate_in(10.minutes, [%w(Class hello world)]) + end + + it 'pushes a context with the current class name as caller_id' do + expect(Gitlab::ApplicationContext).to receive(:with_context).with(caller_id: model.class.to_s) + + model.bulk_migrate_in(10.minutes, [%w(Class hello world)]) + end + end +end diff --git a/spec/lib/gitlab/database/multi_threaded_migration_spec.rb b/spec/lib/gitlab/database/multi_threaded_migration_spec.rb index 53c001fbc1b..78dd9e88064 100644 --- a/spec/lib/gitlab/database/multi_threaded_migration_spec.rb +++ b/spec/lib/gitlab/database/multi_threaded_migration_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::MultiThreadedMigration do +RSpec.describe Gitlab::Database::MultiThreadedMigration do let(:migration) do Class.new { include Gitlab::Database::MultiThreadedMigration }.new end diff --git a/spec/lib/gitlab/database/obsolete_ignored_columns_spec.rb b/spec/lib/gitlab/database/obsolete_ignored_columns_spec.rb index dee1d7df1a9..034bf966db7 100644 --- a/spec/lib/gitlab/database/obsolete_ignored_columns_spec.rb +++ b/spec/lib/gitlab/database/obsolete_ignored_columns_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::ObsoleteIgnoredColumns do +RSpec.describe Gitlab::Database::ObsoleteIgnoredColumns do before do stub_const('Testing', Module.new) stub_const('Testing::MyBase', Class.new(ActiveRecord::Base)) diff --git a/spec/lib/gitlab/database/partitioning/monthly_strategy_spec.rb b/spec/lib/gitlab/database/partitioning/monthly_strategy_spec.rb new file mode 100644 index 00000000000..334cac653cf --- /dev/null +++ b/spec/lib/gitlab/database/partitioning/monthly_strategy_spec.rb @@ -0,0 +1,153 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Database::Partitioning::MonthlyStrategy do + describe '#current_partitions' do + subject { described_class.new(model, partitioning_key).current_partitions } + + let(:model) { double('model', table_name: table_name) } + let(:partitioning_key) { double } + let(:table_name) { :partitioned_test } + + before do + ActiveRecord::Base.connection.execute(<<~SQL) + CREATE TABLE #{table_name} + (id serial not null, created_at timestamptz not null, PRIMARY KEY (id, created_at)) + PARTITION BY RANGE (created_at); + + CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_000000 + PARTITION OF #{table_name} + FOR VALUES FROM (MINVALUE) TO ('2020-05-01'); + + CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_202005 + PARTITION OF #{table_name} + FOR VALUES FROM ('2020-05-01') TO ('2020-06-01'); + SQL + end + + it 'detects both partitions' do + expect(subject).to eq([ + Gitlab::Database::Partitioning::TimePartition.new(table_name, nil, '2020-05-01', partition_name: 'partitioned_test_000000'), + Gitlab::Database::Partitioning::TimePartition.new(table_name, '2020-05-01', '2020-06-01', partition_name: 'partitioned_test_202005') + ]) + end + end + + describe '#missing_partitions' do + subject { described_class.new(model, partitioning_key).missing_partitions } + + let(:model) do + Class.new(ActiveRecord::Base) do + self.table_name = 'partitioned_test' + self.primary_key = :id + end + end + + let(:partitioning_key) { :created_at } + + around do |example| + Timecop.freeze(Date.parse('2020-08-22')) { example.run } + end + + context 'with existing partitions' do + before do + ActiveRecord::Base.connection.execute(<<~SQL) + CREATE TABLE #{model.table_name} + (id serial not null, created_at timestamptz not null, PRIMARY KEY (id, created_at)) + PARTITION BY RANGE (created_at); + + CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_000000 + PARTITION OF #{model.table_name} + FOR VALUES FROM (MINVALUE) TO ('2020-05-01'); + + CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_202006 + PARTITION OF #{model.table_name} + FOR VALUES FROM ('2020-06-01') TO ('2020-07-01'); + SQL + + # Insert some data, it doesn't make a difference + model.create!(created_at: Date.parse('2020-04-20')) + model.create!(created_at: Date.parse('2020-06-15')) + end + + it 'detects the gap and the missing partition in May 2020' do + expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-05-01', '2020-06-01')) + end + + it 'detects the missing partitions at the end of the range and expects a partition for July 2020' do + expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-07-01', '2020-08-01')) + end + + it 'detects the missing partitions at the end of the range and expects a partition for August 2020' do + expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-08-01', '2020-09-01')) + end + + it 'creates partitions 6 months out from now (Sep 2020 through Feb 2021)' do + expect(subject).to include( + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-09-01', '2020-10-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-10-01', '2020-11-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-11-01', '2020-12-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-12-01', '2021-01-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2021-01-01', '2021-02-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2021-02-01', '2021-03-01') + ) + end + + it 'detects all missing partitions' do + expect(subject.size).to eq(9) + end + end + + context 'without existing partitions' do + before do + ActiveRecord::Base.connection.execute(<<~SQL) + CREATE TABLE #{model.table_name} + (id serial not null, created_at timestamptz not null, PRIMARY KEY (id, created_at)) + PARTITION BY RANGE (created_at); + SQL + end + + it 'detects the missing catch-all partition at the beginning' do + expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, nil, '2020-08-01')) + end + + it 'detects the missing partition for today and expects a partition for August 2020' do + expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-08-01', '2020-09-01')) + end + + it 'creates partitions 6 months out from now (Sep 2020 through Feb 2021' do + expect(subject).to include( + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-09-01', '2020-10-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-10-01', '2020-11-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-11-01', '2020-12-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-12-01', '2021-01-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2021-01-01', '2021-02-01'), + Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2021-02-01', '2021-03-01') + ) + end + + it 'detects all missing partitions' do + expect(subject.size).to eq(8) + end + end + + context 'with a regular partition but no catchall (MINVALUE, to) partition' do + before do + ActiveRecord::Base.connection.execute(<<~SQL) + CREATE TABLE #{model.table_name} + (id serial not null, created_at timestamptz not null, PRIMARY KEY (id, created_at)) + PARTITION BY RANGE (created_at); + + CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_202006 + PARTITION OF #{model.table_name} + FOR VALUES FROM ('2020-06-01') TO ('2020-07-01'); + SQL + end + + it 'detects a missing catch-all partition to add before the existing partition' do + expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, nil, '2020-06-01')) + end + end + end +end diff --git a/spec/lib/gitlab/database/partitioning/partition_creator_spec.rb b/spec/lib/gitlab/database/partitioning/partition_creator_spec.rb new file mode 100644 index 00000000000..56399941662 --- /dev/null +++ b/spec/lib/gitlab/database/partitioning/partition_creator_spec.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do + include PartitioningHelpers + include ExclusiveLeaseHelpers + + describe '.register' do + let(:model) { double(partitioning_strategy: nil) } + + it 'remembers registered models' do + expect { described_class.register(model) }.to change { described_class.models }.to include(model) + end + end + + describe '#create_partitions (mocked)' do + subject { described_class.new(models).create_partitions } + + let(:models) { [model] } + let(:model) { double(partitioning_strategy: partitioning_strategy, table_name: table) } + let(:partitioning_strategy) { double(missing_partitions: partitions) } + let(:table) { "some_table" } + + before do + allow(ActiveRecord::Base.connection).to receive(:table_exists?).and_call_original + allow(ActiveRecord::Base.connection).to receive(:table_exists?).with(table).and_return(true) + allow(ActiveRecord::Base.connection).to receive(:execute).and_call_original + + stub_exclusive_lease(described_class::LEASE_KEY % table, timeout: described_class::LEASE_TIMEOUT) + end + + let(:partitions) do + [ + instance_double(Gitlab::Database::Partitioning::TimePartition, table: 'bar', partition_name: 'foo', to_sql: "SELECT 1"), + instance_double(Gitlab::Database::Partitioning::TimePartition, table: 'bar', partition_name: 'foo2', to_sql: "SELECT 2") + ] + end + + it 'creates the partition' do + expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.first.to_sql) + expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.second.to_sql) + + subject + end + + context 'error handling with 2 models' do + let(:models) do + [ + double(partitioning_strategy: strategy1, table_name: table), + double(partitioning_strategy: strategy2, table_name: table) + ] + end + + let(:strategy1) { double('strategy1', missing_partitions: nil) } + let(:strategy2) { double('strategy2', missing_partitions: partitions) } + + it 'still creates partitions for the second table' do + expect(strategy1).to receive(:missing_partitions).and_raise('this should never happen (tm)') + expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.first.to_sql) + expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.second.to_sql) + + subject + end + end + end + + describe '#create_partitions' do + subject { described_class.new([my_model]).create_partitions } + + let(:connection) { ActiveRecord::Base.connection } + let(:my_model) do + Class.new(ApplicationRecord) do + include PartitionedTable + + self.table_name = 'my_model_example_table' + + partitioned_by :created_at, strategy: :monthly + end + end + + before do + connection.execute(<<~SQL) + CREATE TABLE my_model_example_table + (id serial not null, created_at timestamptz not null, primary key (id, created_at)) + PARTITION BY RANGE (created_at); + SQL + end + + it 'creates partitions' do + expect { subject }.to change { find_partitions(my_model.table_name, schema: Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA).size }.from(0) + + subject + end + end +end diff --git a/spec/lib/gitlab/database/partitioning/time_partition_spec.rb b/spec/lib/gitlab/database/partitioning/time_partition_spec.rb new file mode 100644 index 00000000000..700202d81c5 --- /dev/null +++ b/spec/lib/gitlab/database/partitioning/time_partition_spec.rb @@ -0,0 +1,174 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Database::Partitioning::TimePartition do + describe '.from_sql' do + subject { described_class.from_sql(table, partition_name, definition) } + + let(:table) { 'foo' } + let(:partition_name) { 'foo_bar' } + let(:definition) { 'FOR VALUES FROM (\'2020-04-01 00:00:00\') TO (\'2020-05-01 00:00:00\')' } + + it 'uses specified table name' do + expect(subject.table).to eq(table) + end + + it 'uses specified partition name' do + expect(subject.partition_name).to eq(partition_name) + end + + it 'parses start date' do + expect(subject.from).to eq(Date.parse('2020-04-01')) + end + + it 'parses end date' do + expect(subject.to).to eq(Date.parse('2020-05-01')) + end + + context 'with MINVALUE as a start date' do + let(:definition) { 'FOR VALUES FROM (MINVALUE) TO (\'2020-05-01\')' } + + it 'sets from to nil' do + expect(subject.from).to be_nil + end + end + + context 'with MAXVALUE as an end date' do + let(:definition) { 'FOR VALUES FROM (\'2020-04-01\') TO (MAXVALUE)' } + + it 'raises a NotImplementedError' do + expect { subject }.to raise_error(NotImplementedError) + end + end + end + + describe '#partition_name' do + subject { described_class.new(table, from, to, partition_name: partition_name).partition_name } + + let(:table) { 'foo' } + let(:from) { '2020-04-01 00:00:00' } + let(:to) { '2020-05-01 00:00:00' } + let(:partition_name) { nil } + + it 'uses table as prefix' do + expect(subject).to start_with(table) + end + + it 'uses Year-Month (from) as suffix' do + expect(subject).to end_with("_202004") + end + + context 'without from date' do + let(:from) { nil } + + it 'uses 000000 as suffix for first partition' do + expect(subject).to end_with("_000000") + end + end + + context 'with partition name explicitly given' do + let(:partition_name) { "foo_bar" } + + it 'uses given partition name' do + expect(subject).to eq(partition_name) + end + end + end + + describe '#to_sql' do + subject { described_class.new(table, from, to).to_sql } + + let(:table) { 'foo' } + let(:from) { '2020-04-01 00:00:00' } + let(:to) { '2020-05-01 00:00:00' } + + it 'transforms to a CREATE TABLE statement' do + expect(subject).to eq(<<~SQL) + CREATE TABLE IF NOT EXISTS "#{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}"."foo_202004" + PARTITION OF "foo" + FOR VALUES FROM ('2020-04-01') TO ('2020-05-01') + SQL + end + + context 'without from date' do + let(:from) { nil } + + it 'uses MINVALUE instead' do + expect(subject).to eq(<<~SQL) + CREATE TABLE IF NOT EXISTS "#{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}"."foo_000000" + PARTITION OF "foo" + FOR VALUES FROM (MINVALUE) TO ('2020-05-01') + SQL + end + end + end + + describe 'object equality - #eql' do + def expect_inequality(actual, other) + expect(actual.eql?(other)).to be_falsey + expect(actual).not_to eq(other) + end + + def expect_equality(actual, other) + expect(actual).to eq(other) + expect(actual.eql?(other)).to be_truthy + expect(actual.hash).to eq(other.hash) + end + + def make_new(table: 'foo', from: '2020-04-01 00:00:00', to: '2020-05-01 00:00:00', partition_name: 'foo_202004') + described_class.new(table, from, to, partition_name: partition_name) + end + + it 'treats objects identical with identical attributes' do + expect_equality(make_new, make_new) + end + + it 'different table leads to in-equality' do + expect_inequality(make_new, make_new(table: 'bar')) + end + + it 'different from leads to in-equality' do + expect_inequality(make_new, make_new(from: '2020-05-01 00:00:00')) + end + + it 'different to leads to in-equality' do + expect_inequality(make_new, make_new(to: '2020-06-01 00:00:00')) + end + + it 'different partition_name leads to in-equality' do + expect_inequality(make_new, make_new(partition_name: 'different')) + end + + it 'nil partition_name is ignored if auto-generated matches' do + expect_equality(make_new, make_new(partition_name: nil)) + end + end + + describe 'Comparable, #<=>' do + let(:table) { 'foo' } + + it 'sorts by partition name, i.e. by month - MINVALUE partition first' do + partitions = [ + described_class.new(table, '2020-04-01', '2020-05-01'), + described_class.new(table, '2020-02-01', '2020-03-01'), + described_class.new(table, nil, '2020-02-01'), + described_class.new(table, '2020-03-01', '2020-04-01') + ] + + expect(partitions.sort).to eq([ + described_class.new(table, nil, '2020-02-01'), + described_class.new(table, '2020-02-01', '2020-03-01'), + described_class.new(table, '2020-03-01', '2020-04-01'), + described_class.new(table, '2020-04-01', '2020-05-01') + ]) + end + + it 'returns nil for partitions of different tables' do + one = described_class.new('foo', '2020-02-01', '2020-03-01') + two = described_class.new('bar', '2020-02-01', '2020-03-01') + + expect(one.<=>(two)).to be_nil + end + end +end diff --git a/spec/lib/gitlab/database/partitioning_migration_helpers/backfill_partitioned_table_spec.rb b/spec/lib/gitlab/database/partitioning_migration_helpers/backfill_partitioned_table_spec.rb new file mode 100644 index 00000000000..49f3f87fe61 --- /dev/null +++ b/spec/lib/gitlab/database/partitioning_migration_helpers/backfill_partitioned_table_spec.rb @@ -0,0 +1,175 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Database::PartitioningMigrationHelpers::BackfillPartitionedTable, '#perform' do + subject { described_class.new } + + let(:source_table) { '_test_partitioning_backfills' } + let(:destination_table) { "#{source_table}_part" } + let(:unique_key) { 'id' } + + before do + allow(subject).to receive(:transaction_open?).and_return(false) + end + + context 'when the destination table exists' do + before do + connection.execute(<<~SQL) + CREATE TABLE #{source_table} ( + id serial NOT NULL PRIMARY KEY, + col1 int NOT NULL, + col2 text NOT NULL, + created_at timestamptz NOT NULL + ) + SQL + + connection.execute(<<~SQL) + CREATE TABLE #{destination_table} ( + id serial NOT NULL, + col1 int NOT NULL, + col2 text NOT NULL, + created_at timestamptz NOT NULL, + PRIMARY KEY (id, created_at) + ) PARTITION BY RANGE (created_at) + SQL + + connection.execute(<<~SQL) + CREATE TABLE #{destination_table}_202001 PARTITION OF #{destination_table} + FOR VALUES FROM ('2020-01-01') TO ('2020-02-01') + SQL + + connection.execute(<<~SQL) + CREATE TABLE #{destination_table}_202002 PARTITION OF #{destination_table} + FOR VALUES FROM ('2020-02-01') TO ('2020-03-01') + SQL + + source_model.table_name = source_table + destination_model.table_name = destination_table + + stub_const("#{described_class}::SUB_BATCH_SIZE", 2) + stub_const("#{described_class}::PAUSE_SECONDS", pause_seconds) + + allow(subject).to receive(:sleep) + end + + let(:connection) { ActiveRecord::Base.connection } + let(:source_model) { Class.new(ActiveRecord::Base) } + let(:destination_model) { Class.new(ActiveRecord::Base) } + let(:timestamp) { Time.utc(2020, 1, 2).round } + let(:pause_seconds) { 1 } + + let!(:source1) { create_source_record(timestamp) } + let!(:source2) { create_source_record(timestamp + 1.day) } + let!(:source3) { create_source_record(timestamp + 1.month) } + + it 'copies data into the destination table idempotently' do + expect(destination_model.count).to eq(0) + + subject.perform(source1.id, source3.id, source_table, destination_table, unique_key) + + expect(destination_model.count).to eq(3) + + source_model.find_each do |source_record| + destination_record = destination_model.find_by_id(source_record.id) + + expect(destination_record.attributes).to eq(source_record.attributes) + end + + subject.perform(source1.id, source3.id, source_table, destination_table, unique_key) + + expect(destination_model.count).to eq(3) + end + + it 'breaks the assigned batch into smaller batches' do + expect_next_instance_of(described_class::BulkCopy) do |bulk_copy| + expect(bulk_copy).to receive(:copy_between).with(source1.id, source2.id) + expect(bulk_copy).to receive(:copy_between).with(source3.id, source3.id) + end + + subject.perform(source1.id, source3.id, source_table, destination_table, unique_key) + end + + it 'pauses after copying each sub-batch' do + expect(subject).to receive(:sleep).with(pause_seconds).twice + + subject.perform(source1.id, source3.id, source_table, destination_table, unique_key) + end + + it 'marks each job record as succeeded after processing' do + create(:background_migration_job, class_name: "::#{described_class.name}", + arguments: [source1.id, source3.id, source_table, destination_table, unique_key]) + + expect(::Gitlab::Database::BackgroundMigrationJob).to receive(:mark_all_as_succeeded).and_call_original + + expect do + subject.perform(source1.id, source3.id, source_table, destination_table, unique_key) + end.to change { ::Gitlab::Database::BackgroundMigrationJob.succeeded.count }.from(0).to(1) + end + + context 'when the feature flag is disabled' do + let(:mock_connection) { double('connection') } + + before do + allow(subject).to receive(:connection).and_return(mock_connection) + stub_feature_flags(backfill_partitioned_audit_events: false) + end + + it 'exits without attempting to copy data' do + expect(mock_connection).not_to receive(:execute) + + subject.perform(1, 100, source_table, destination_table, unique_key) + + expect(destination_model.count).to eq(0) + end + end + + context 'when the job is run within an explicit transaction block' do + let(:mock_connection) { double('connection') } + + before do + allow(subject).to receive(:connection).and_return(mock_connection) + allow(subject).to receive(:transaction_open?).and_return(true) + end + + it 'raises an error before copying data' do + expect(mock_connection).not_to receive(:execute) + + expect do + subject.perform(1, 100, source_table, destination_table, unique_key) + end.to raise_error(/Aborting job to backfill partitioned #{source_table}/) + + expect(destination_model.count).to eq(0) + end + end + end + + context 'when the destination table does not exist' do + let(:mock_connection) { double('connection') } + let(:mock_logger) { double('logger') } + + before do + allow(subject).to receive(:connection).and_return(mock_connection) + allow(subject).to receive(:logger).and_return(mock_logger) + + expect(mock_connection).to receive(:table_exists?).with(destination_table).and_return(false) + allow(mock_logger).to receive(:warn) + end + + it 'exits without attempting to copy data' do + expect(mock_connection).not_to receive(:execute) + + subject.perform(1, 100, source_table, destination_table, unique_key) + end + + it 'logs a warning message that the job was skipped' do + expect(mock_logger).to receive(:warn).with(/#{destination_table} does not exist/) + + subject.perform(1, 100, source_table, destination_table, unique_key) + end + end + + def create_source_record(timestamp) + source_model.create!(col1: 123, col2: 'original value', created_at: timestamp) + end +end diff --git a/spec/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers_spec.rb b/spec/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers_spec.rb index 9cec77b434d..efa9c83b2d2 100644 --- a/spec/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers_spec.rb +++ b/spec/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::PartitioningMigrationHelpers::ForeignKeyHelpers do +RSpec.describe Gitlab::Database::PartitioningMigrationHelpers::ForeignKeyHelpers do include TriggerHelpers let(:model) do diff --git a/spec/lib/gitlab/database/partitioning_migration_helpers/partitioned_foreign_key_spec.rb b/spec/lib/gitlab/database/partitioning_migration_helpers/partitioned_foreign_key_spec.rb index 77f71676252..a58c37f111d 100644 --- a/spec/lib/gitlab/database/partitioning_migration_helpers/partitioned_foreign_key_spec.rb +++ b/spec/lib/gitlab/database/partitioning_migration_helpers/partitioned_foreign_key_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::PartitioningMigrationHelpers::PartitionedForeignKey do +RSpec.describe Gitlab::Database::PartitioningMigrationHelpers::PartitionedForeignKey do let(:foreign_key) do described_class.new( to_table: 'issues', diff --git a/spec/lib/gitlab/database/partitioning_migration_helpers/table_management_helpers_spec.rb b/spec/lib/gitlab/database/partitioning_migration_helpers/table_management_helpers_spec.rb index 586b57d2002..9b24ab7cad4 100644 --- a/spec/lib/gitlab/database/partitioning_migration_helpers/table_management_helpers_spec.rb +++ b/spec/lib/gitlab/database/partitioning_migration_helpers/table_management_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers do +RSpec.describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers do include PartitioningHelpers include TriggerHelpers @@ -11,7 +11,7 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers end let_it_be(:connection) { ActiveRecord::Base.connection } - let(:template_table) { :audit_events } + let(:source_table) { :audit_events } let(:partitioned_table) { '_test_migration_partitioned_table' } let(:function_name) { '_test_migration_function_name' } let(:trigger_name) { '_test_migration_trigger_name' } @@ -22,10 +22,10 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers before do allow(migration).to receive(:puts) allow(migration).to receive(:transaction_open?).and_return(false) - allow(migration).to receive(:partitioned_table_name).and_return(partitioned_table) - allow(migration).to receive(:sync_function_name).and_return(function_name) - allow(migration).to receive(:sync_trigger_name).and_return(trigger_name) - allow(migration).to receive(:assert_table_is_whitelisted) + allow(migration).to receive(:make_partitioned_table_name).and_return(partitioned_table) + allow(migration).to receive(:make_sync_function_name).and_return(function_name) + allow(migration).to receive(:make_sync_trigger_name).and_return(trigger_name) + allow(migration).to receive(:assert_table_is_allowed) end describe '#partition_table_by_date' do @@ -33,15 +33,19 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers let(:old_primary_key) { 'id' } let(:new_primary_key) { [old_primary_key, partition_column] } - context 'when the table is not whitelisted' do - let(:template_table) { :this_table_is_not_whitelisted } + before do + allow(migration).to receive(:queue_background_migration_jobs_by_range_at_intervals) + end + + context 'when the table is not allowed' do + let(:source_table) { :this_table_is_not_allowed } it 'raises an error' do - expect(migration).to receive(:assert_table_is_whitelisted).with(template_table).and_call_original + expect(migration).to receive(:assert_table_is_allowed).with(source_table).and_call_original expect do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date - end.to raise_error(/#{template_table} is not whitelisted for use/) + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date + end.to raise_error(/#{source_table} is not allowed for use/) end end @@ -50,7 +54,7 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers expect(migration).to receive(:transaction_open?).and_return(true) expect do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date end.to raise_error(/can not be run inside a transaction/) end end @@ -60,7 +64,7 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers it 'raises an error' do expect do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date end.to raise_error(/max_date #{max_date} must be greater than min_date #{min_date}/) end end @@ -70,24 +74,24 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers it 'raises an error' do expect do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date end.to raise_error(/max_date #{max_date} must be greater than min_date #{min_date}/) end end context 'when the given table does not have a primary key' do - let(:template_table) { :_partitioning_migration_helper_test_table } + let(:source_table) { :_partitioning_migration_helper_test_table } let(:partition_column) { :some_field } it 'raises an error' do - migration.create_table template_table, id: false do |t| + migration.create_table source_table, id: false do |t| t.integer :id t.datetime partition_column end expect do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date - end.to raise_error(/primary key not defined for #{template_table}/) + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date + end.to raise_error(/primary key not defined for #{source_table}/) end end @@ -96,14 +100,14 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers it 'raises an error' do expect do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date end.to raise_error(/partition column #{partition_column} does not exist/) end end describe 'constructing the partitioned table' do it 'creates a table partitioned by the proper column' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date expect(connection.table_exists?(partitioned_table)).to be(true) expect(connection.primary_key(partitioned_table)).to eq(new_primary_key) @@ -112,7 +116,7 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers end it 'changes the primary key datatype to bigint' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date pk_column = connection.columns(partitioned_table).find { |c| c.name == old_primary_key } @@ -127,13 +131,13 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers end end - let(:template_table) { :another_example } + let(:source_table) { :another_example } let(:old_primary_key) { 'identifier' } it 'does not change the primary key datatype' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date - original_pk_column = connection.columns(template_table).find { |c| c.name == old_primary_key } + original_pk_column = connection.columns(source_table).find { |c| c.name == old_primary_key } pk_column = connection.columns(partitioned_table).find { |c| c.name == old_primary_key } expect(pk_column).not_to be_nil @@ -142,7 +146,7 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers end it 'removes the default from the primary key column' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date pk_column = connection.columns(partitioned_table).find { |c| c.name == old_primary_key } @@ -150,26 +154,100 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers end it 'creates the partitioned table with the same non-key columns' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date copied_columns = filter_columns_by_name(connection.columns(partitioned_table), new_primary_key) - original_columns = filter_columns_by_name(connection.columns(template_table), new_primary_key) + original_columns = filter_columns_by_name(connection.columns(source_table), new_primary_key) expect(copied_columns).to match_array(original_columns) end it 'creates a partition spanning over each month in the range given' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date + + expect_range_partitions_for(partitioned_table, { + '000000' => ['MINVALUE', "'2019-12-01 00:00:00'"], + '201912' => ["'2019-12-01 00:00:00'", "'2020-01-01 00:00:00'"], + '202001' => ["'2020-01-01 00:00:00'", "'2020-02-01 00:00:00'"], + '202002' => ["'2020-02-01 00:00:00'", "'2020-03-01 00:00:00'"], + '202003' => ["'2020-03-01 00:00:00'", "'2020-04-01 00:00:00'"] + }) + end + + context 'when min_date is not given' do + let(:source_table) { :todos } + + context 'with records present already' do + before do + create(:todo, created_at: Date.parse('2019-11-05')) + end + + it 'creates a partition spanning over each month from the first record' do + migration.partition_table_by_date source_table, partition_column, max_date: max_date + + expect_range_partitions_for(partitioned_table, { + '000000' => ['MINVALUE', "'2019-11-01 00:00:00'"], + '201911' => ["'2019-11-01 00:00:00'", "'2019-12-01 00:00:00'"], + '201912' => ["'2019-12-01 00:00:00'", "'2020-01-01 00:00:00'"], + '202001' => ["'2020-01-01 00:00:00'", "'2020-02-01 00:00:00'"], + '202002' => ["'2020-02-01 00:00:00'", "'2020-03-01 00:00:00'"], + '202003' => ["'2020-03-01 00:00:00'", "'2020-04-01 00:00:00'"] + }) + end + end + + context 'without data' do + it 'creates the catchall partition plus two actual partition' do + migration.partition_table_by_date source_table, partition_column, max_date: max_date + + expect_range_partitions_for(partitioned_table, { + '000000' => ['MINVALUE', "'2020-02-01 00:00:00'"], + '202002' => ["'2020-02-01 00:00:00'", "'2020-03-01 00:00:00'"], + '202003' => ["'2020-03-01 00:00:00'", "'2020-04-01 00:00:00'"] + }) + end + end + end - expect_range_partition_of("#{partitioned_table}_000000", partitioned_table, 'MINVALUE', "'2019-12-01 00:00:00'") - expect_range_partition_of("#{partitioned_table}_201912", partitioned_table, "'2019-12-01 00:00:00'", "'2020-01-01 00:00:00'") - expect_range_partition_of("#{partitioned_table}_202001", partitioned_table, "'2020-01-01 00:00:00'", "'2020-02-01 00:00:00'") - expect_range_partition_of("#{partitioned_table}_202002", partitioned_table, "'2020-02-01 00:00:00'", "'2020-03-01 00:00:00'") + context 'when max_date is not given' do + it 'creates partitions including the next month from today' do + today = Date.new(2020, 5, 8) + + Timecop.freeze(today) do + migration.partition_table_by_date source_table, partition_column, min_date: min_date + + expect_range_partitions_for(partitioned_table, { + '000000' => ['MINVALUE', "'2019-12-01 00:00:00'"], + '201912' => ["'2019-12-01 00:00:00'", "'2020-01-01 00:00:00'"], + '202001' => ["'2020-01-01 00:00:00'", "'2020-02-01 00:00:00'"], + '202002' => ["'2020-02-01 00:00:00'", "'2020-03-01 00:00:00'"], + '202003' => ["'2020-03-01 00:00:00'", "'2020-04-01 00:00:00'"], + '202004' => ["'2020-04-01 00:00:00'", "'2020-05-01 00:00:00'"], + '202005' => ["'2020-05-01 00:00:00'", "'2020-06-01 00:00:00'"], + '202006' => ["'2020-06-01 00:00:00'", "'2020-07-01 00:00:00'"] + }) + end + end + end + + context 'without min_date, max_date' do + it 'creates partitions for the current and next month' do + current_date = Date.new(2020, 05, 22) + Timecop.freeze(current_date.to_time) do + migration.partition_table_by_date source_table, partition_column + + expect_range_partitions_for(partitioned_table, { + '000000' => ['MINVALUE', "'2020-05-01 00:00:00'"], + '202005' => ["'2020-05-01 00:00:00'", "'2020-06-01 00:00:00'"], + '202006' => ["'2020-06-01 00:00:00'", "'2020-07-01 00:00:00'"] + }) + end + end end end describe 'keeping data in sync with the partitioned table' do - let(:template_table) { :todos } + let(:source_table) { :todos } let(:model) { Class.new(ActiveRecord::Base) } let(:timestamp) { Time.utc(2019, 12, 1, 12).round } @@ -180,16 +258,16 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers it 'creates a trigger function on the original table' do expect_function_not_to_exist(function_name) - expect_trigger_not_to_exist(template_table, trigger_name) + expect_trigger_not_to_exist(source_table, trigger_name) - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date expect_function_to_exist(function_name) - expect_valid_function_trigger(template_table, trigger_name, function_name, after: %w[delete insert update]) + expect_valid_function_trigger(source_table, trigger_name, function_name, after: %w[delete insert update]) end it 'syncs inserts to the partitioned tables' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date expect(model.count).to eq(0) @@ -202,7 +280,7 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers end it 'syncs updates to the partitioned tables' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date first_todo = create(:todo, :pending, commit_id: nil, created_at: timestamp, updated_at: timestamp) second_todo = create(:todo, created_at: timestamp, updated_at: timestamp) @@ -223,7 +301,7 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers end it 'syncs deletes to the partitioned tables' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date first_todo = create(:todo, created_at: timestamp, updated_at: timestamp) second_todo = create(:todo, created_at: timestamp, updated_at: timestamp) @@ -237,50 +315,129 @@ describe Gitlab::Database::PartitioningMigrationHelpers::TableManagementHelpers expect(model.find(second_todo.id).attributes).to eq(second_todo.attributes) end end + + describe 'copying historic data to the partitioned table' do + let(:source_table) { 'todos' } + let(:migration_class) { '::Gitlab::Database::PartitioningMigrationHelpers::BackfillPartitionedTable' } + let(:sub_batch_size) { described_class::SUB_BATCH_SIZE } + let(:pause_seconds) { described_class::PAUSE_SECONDS } + let!(:first_id) { create(:todo).id } + let!(:second_id) { create(:todo).id } + let!(:third_id) { create(:todo).id } + + before do + stub_const("#{described_class.name}::BATCH_SIZE", 2) + + expect(migration).to receive(:queue_background_migration_jobs_by_range_at_intervals).and_call_original + end + + it 'enqueues jobs to copy each batch of data' do + Sidekiq::Testing.fake! do + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date + + expect(BackgroundMigrationWorker.jobs.size).to eq(2) + + first_job_arguments = [first_id, second_id, source_table, partitioned_table, 'id'] + expect(BackgroundMigrationWorker.jobs[0]['args']).to eq([migration_class, first_job_arguments]) + + second_job_arguments = [third_id, third_id, source_table, partitioned_table, 'id'] + expect(BackgroundMigrationWorker.jobs[1]['args']).to eq([migration_class, second_job_arguments]) + end + end + end end describe '#drop_partitioned_table_for' do let(:expected_tables) do - %w[000000 201912 202001 202002].map { |suffix| "#{partitioned_table}_#{suffix}" }.unshift(partitioned_table) + %w[000000 201912 202001 202002].map { |suffix| "#{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.#{partitioned_table}_#{suffix}" }.unshift(partitioned_table) end + let(:migration_class) { 'Gitlab::Database::PartitioningMigrationHelpers::BackfillPartitionedTable' } - context 'when the table is not whitelisted' do - let(:template_table) { :this_table_is_not_whitelisted } + context 'when the table is not allowed' do + let(:source_table) { :this_table_is_not_allowed } it 'raises an error' do - expect(migration).to receive(:assert_table_is_whitelisted).with(template_table).and_call_original + expect(migration).to receive(:assert_table_is_allowed).with(source_table).and_call_original expect do - migration.drop_partitioned_table_for template_table - end.to raise_error(/#{template_table} is not whitelisted for use/) + migration.drop_partitioned_table_for source_table + end.to raise_error(/#{source_table} is not allowed for use/) end end it 'drops the trigger syncing to the partitioned table' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date expect_function_to_exist(function_name) - expect_valid_function_trigger(template_table, trigger_name, function_name, after: %w[delete insert update]) + expect_valid_function_trigger(source_table, trigger_name, function_name, after: %w[delete insert update]) - migration.drop_partitioned_table_for template_table + migration.drop_partitioned_table_for source_table expect_function_not_to_exist(function_name) - expect_trigger_not_to_exist(template_table, trigger_name) + expect_trigger_not_to_exist(source_table, trigger_name) end it 'drops the partitioned copy and all partitions' do - migration.partition_table_by_date template_table, partition_column, min_date: min_date, max_date: max_date + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date expected_tables.each do |table| expect(connection.table_exists?(table)).to be(true) end - migration.drop_partitioned_table_for template_table + migration.drop_partitioned_table_for source_table expected_tables.each do |table| expect(connection.table_exists?(table)).to be(false) end end + + context 'cleaning up background migration tracking records' do + let!(:job1) { create(:background_migration_job, class_name: migration_class, arguments: [1, 10, source_table]) } + let!(:job2) { create(:background_migration_job, class_name: migration_class, arguments: [11, 20, source_table]) } + let!(:job3) { create(:background_migration_job, class_name: migration_class, arguments: [1, 10, 'other_table']) } + + it 'deletes any tracking records from the background_migration_jobs table' do + migration.partition_table_by_date source_table, partition_column, min_date: min_date, max_date: max_date + + expect { migration.drop_partitioned_table_for(source_table) } + .to change { ::Gitlab::Database::BackgroundMigrationJob.count }.from(3).to(1) + + remaining_record = ::Gitlab::Database::BackgroundMigrationJob.first + expect(remaining_record).to have_attributes(class_name: migration_class, arguments: [1, 10, 'other_table']) + end + end + end + + describe '#create_hash_partitions' do + before do + connection.execute(<<~SQL) + CREATE TABLE #{partitioned_table} + (id serial not null, some_id integer not null, PRIMARY KEY (id, some_id)) + PARTITION BY HASH (some_id); + SQL + end + + it 'creates partitions for the full hash space (8 partitions)' do + partitions = 8 + + migration.create_hash_partitions(partitioned_table, partitions) + + (0..partitions - 1).each do |partition| + partition_name = "#{partitioned_table}_#{"%01d" % partition}" + expect_hash_partition_of(partition_name, partitioned_table, partitions, partition) + end + end + + it 'creates partitions for the full hash space (16 partitions)' do + partitions = 16 + + migration.create_hash_partitions(partitioned_table, partitions) + + (0..partitions - 1).each do |partition| + partition_name = "#{partitioned_table}_#{"%02d" % partition}" + expect_hash_partition_of(partition_name, partitioned_table, partitions, partition) + end + end end def filter_columns_by_name(columns, names) diff --git a/spec/lib/gitlab/database/postgresql_adapter/force_disconnectable_mixin_spec.rb b/spec/lib/gitlab/database/postgresql_adapter/force_disconnectable_mixin_spec.rb index 0523066b593..8b3a0ceb804 100644 --- a/spec/lib/gitlab/database/postgresql_adapter/force_disconnectable_mixin_spec.rb +++ b/spec/lib/gitlab/database/postgresql_adapter/force_disconnectable_mixin_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::PostgresqlAdapter::ForceDisconnectableMixin do +RSpec.describe Gitlab::Database::PostgresqlAdapter::ForceDisconnectableMixin do describe 'checking in a connection to the pool' do let(:model) do Class.new(ActiveRecord::Base) do diff --git a/spec/lib/gitlab/database/postgresql_adapter/schema_versions_copy_mixin_spec.rb b/spec/lib/gitlab/database/postgresql_adapter/schema_versions_copy_mixin_spec.rb index 968dfc1ea43..c6333e4a4dc 100644 --- a/spec/lib/gitlab/database/postgresql_adapter/schema_versions_copy_mixin_spec.rb +++ b/spec/lib/gitlab/database/postgresql_adapter/schema_versions_copy_mixin_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::PostgresqlAdapter::SchemaVersionsCopyMixin do +RSpec.describe Gitlab::Database::PostgresqlAdapter::SchemaVersionsCopyMixin do let(:schema_migration) { double('schem_migration', table_name: table_name, all_versions: versions) } let(:versions) { %w(5 2 1000 200 4 93 2) } let(:table_name) { "schema_migrations" } diff --git a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base_spec.rb b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base_spec.rb index fae57996fb6..76b1be1e497 100644 --- a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base_spec.rb +++ b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::RenameReservedPathsMigration::V1::RenameBase, :delete do +RSpec.describe Gitlab::Database::RenameReservedPathsMigration::V1::RenameBase, :delete do let(:migration) { FakeRenameReservedPathMigrationV1.new } let(:subject) { described_class.new(['the-path'], migration) } diff --git a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces_spec.rb b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces_spec.rb index 46fc48ab3fc..e222a29c6a1 100644 --- a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces_spec.rb +++ b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::RenameReservedPathsMigration::V1::RenameNamespaces, :delete do +RSpec.describe Gitlab::Database::RenameReservedPathsMigration::V1::RenameNamespaces, :delete do let(:migration) { FakeRenameReservedPathMigrationV1.new } let(:subject) { described_class.new(['the-path'], migration) } let(:namespace) { create(:group, name: 'the-path') } diff --git a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects_spec.rb b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects_spec.rb index 1ccdb1d9447..3799fe3c316 100644 --- a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects_spec.rb +++ b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::RenameReservedPathsMigration::V1::RenameProjects, :delete do +RSpec.describe Gitlab::Database::RenameReservedPathsMigration::V1::RenameProjects, :delete do let(:migration) { FakeRenameReservedPathMigrationV1.new } let(:subject) { described_class.new(['the-path'], migration) } let(:project) do diff --git a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1_spec.rb b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1_spec.rb index 56767c21ab7..3b2d3ab1354 100644 --- a/spec/lib/gitlab/database/rename_reserved_paths_migration/v1_spec.rb +++ b/spec/lib/gitlab/database/rename_reserved_paths_migration/v1_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -shared_examples 'renames child namespaces' do |type| +RSpec.shared_examples 'renames child namespaces' do |type| it 'renames namespaces' do rename_namespaces = double expect(described_class::RenameNamespaces) @@ -15,7 +15,7 @@ shared_examples 'renames child namespaces' do |type| end end -describe Gitlab::Database::RenameReservedPathsMigration::V1, :delete do +RSpec.describe Gitlab::Database::RenameReservedPathsMigration::V1, :delete do let(:subject) { FakeRenameReservedPathMigrationV1.new } before do diff --git a/spec/lib/gitlab/database/schema_cleaner_spec.rb b/spec/lib/gitlab/database/schema_cleaner_spec.rb index adaeb85d52d..1303ad7a311 100644 --- a/spec/lib/gitlab/database/schema_cleaner_spec.rb +++ b/spec/lib/gitlab/database/schema_cleaner_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::SchemaCleaner do +RSpec.describe Gitlab::Database::SchemaCleaner do let(:example_schema) { fixture_file(File.join('gitlab', 'database', 'structure_example.sql')) } let(:io) { StringIO.new } diff --git a/spec/lib/gitlab/database/sha_attribute_spec.rb b/spec/lib/gitlab/database/sha_attribute_spec.rb index 15695bc8069..1b855625a6c 100644 --- a/spec/lib/gitlab/database/sha_attribute_spec.rb +++ b/spec/lib/gitlab/database/sha_attribute_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::ShaAttribute do +RSpec.describe Gitlab::Database::ShaAttribute do let(:sha) do '9a573a369a5bfbb9a4a36e98852c21af8a44ea8b' end diff --git a/spec/lib/gitlab/database/with_lock_retries_spec.rb b/spec/lib/gitlab/database/with_lock_retries_spec.rb index d7eee594631..70cbddbb7b7 100644 --- a/spec/lib/gitlab/database/with_lock_retries_spec.rb +++ b/spec/lib/gitlab/database/with_lock_retries_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Database::WithLockRetries do +RSpec.describe Gitlab::Database::WithLockRetries do let(:env) { {} } let(:logger) { Gitlab::Database::WithLockRetries::NULL_LOGGER } let(:subject) { described_class.new(env: env, logger: logger, timing_configuration: timing_configuration) } diff --git a/spec/lib/gitlab/database_importers/common_metrics/importer_spec.rb b/spec/lib/gitlab/database_importers/common_metrics/importer_spec.rb index e6321d48e11..fdf16069381 100644 --- a/spec/lib/gitlab/database_importers/common_metrics/importer_spec.rb +++ b/spec/lib/gitlab/database_importers/common_metrics/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DatabaseImporters::CommonMetrics::Importer do +RSpec.describe Gitlab::DatabaseImporters::CommonMetrics::Importer do subject { described_class.new } context "does import common_metrics.yml" do diff --git a/spec/lib/gitlab/database_importers/common_metrics/prometheus_metric_spec.rb b/spec/lib/gitlab/database_importers/common_metrics/prometheus_metric_spec.rb index e4e8a85e7bc..67da59d6477 100644 --- a/spec/lib/gitlab/database_importers/common_metrics/prometheus_metric_spec.rb +++ b/spec/lib/gitlab/database_importers/common_metrics/prometheus_metric_spec.rb @@ -2,14 +2,14 @@ require 'spec_helper' -describe Gitlab::DatabaseImporters::CommonMetrics::PrometheusMetric do +RSpec.describe Gitlab::DatabaseImporters::CommonMetrics::PrometheusMetric do it 'group enum equals ::PrometheusMetric' do expect(described_class.groups).to eq(::PrometheusMetric.groups) end it '.group_titles equals ::PrometheusMetric' do - existing_group_titles = ::PrometheusMetricEnums.group_details.each_with_object({}) do |(key, value), memo| - memo[key] = value[:group_title] + existing_group_titles = ::PrometheusMetricEnums.group_details.transform_values do |value| + value[:group_title] end expect(Gitlab::DatabaseImporters::CommonMetrics::PrometheusMetricEnums.group_titles).to eq(existing_group_titles) end diff --git a/spec/lib/gitlab/database_importers/instance_administrators/create_group_spec.rb b/spec/lib/gitlab/database_importers/instance_administrators/create_group_spec.rb index 97f4a7eec75..a3661bbe49a 100644 --- a/spec/lib/gitlab/database_importers/instance_administrators/create_group_spec.rb +++ b/spec/lib/gitlab/database_importers/instance_administrators/create_group_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DatabaseImporters::InstanceAdministrators::CreateGroup do +RSpec.describe Gitlab::DatabaseImporters::InstanceAdministrators::CreateGroup do describe '#execute' do let(:result) { subject.execute } diff --git a/spec/lib/gitlab/database_importers/self_monitoring/project/create_service_spec.rb b/spec/lib/gitlab/database_importers/self_monitoring/project/create_service_spec.rb index 923f620a81d..ca9f9ab915f 100644 --- a/spec/lib/gitlab/database_importers/self_monitoring/project/create_service_spec.rb +++ b/spec/lib/gitlab/database_importers/self_monitoring/project/create_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DatabaseImporters::SelfMonitoring::Project::CreateService do +RSpec.describe Gitlab::DatabaseImporters::SelfMonitoring::Project::CreateService do describe '#execute' do let(:result) { subject.execute } diff --git a/spec/lib/gitlab/database_importers/self_monitoring/project/delete_service_spec.rb b/spec/lib/gitlab/database_importers/self_monitoring/project/delete_service_spec.rb index 89d816c0cf7..9d514bcc661 100644 --- a/spec/lib/gitlab/database_importers/self_monitoring/project/delete_service_spec.rb +++ b/spec/lib/gitlab/database_importers/self_monitoring/project/delete_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DatabaseImporters::SelfMonitoring::Project::DeleteService do +RSpec.describe Gitlab::DatabaseImporters::SelfMonitoring::Project::DeleteService do describe '#execute' do let!(:application_setting) { create(:application_setting) } let(:result) { subject.execute } diff --git a/spec/lib/gitlab/database_spec.rb b/spec/lib/gitlab/database_spec.rb index b99f311de29..cd009f955af 100644 --- a/spec/lib/gitlab/database_spec.rb +++ b/spec/lib/gitlab/database_spec.rb @@ -2,11 +2,19 @@ require 'spec_helper' -describe Gitlab::Database do +RSpec.describe Gitlab::Database do before do stub_const('MigrationTest', Class.new { include Gitlab::Database }) end + describe 'EXTRA_SCHEMAS' do + it 'contains only schemas starting with gitlab_ prefix' do + described_class::EXTRA_SCHEMAS.each do |schema| + expect(schema.to_s).to start_with('gitlab_') + end + end + end + describe '.config' do it 'returns a Hash' do expect(described_class.config).to be_an_instance_of(Hash) @@ -82,36 +90,83 @@ describe Gitlab::Database do end describe '.postgresql_minimum_supported_version?' do - it 'returns false when using PostgreSQL 9.5' do - allow(described_class).to receive(:version).and_return('9.5') + it 'returns false when using PostgreSQL 10' do + allow(described_class).to receive(:version).and_return('10') expect(described_class.postgresql_minimum_supported_version?).to eq(false) end - it 'returns true when using PostgreSQL 9.6' do - allow(described_class).to receive(:version).and_return('9.6') + it 'returns true when using PostgreSQL 11' do + allow(described_class).to receive(:version).and_return('11') expect(described_class.postgresql_minimum_supported_version?).to eq(true) end - it 'returns true when using PostgreSQL 10 or newer' do - allow(described_class).to receive(:version).and_return('10') + it 'returns true when using PostgreSQL 12' do + allow(described_class).to receive(:version).and_return('12') expect(described_class.postgresql_minimum_supported_version?).to eq(true) end end - describe '.replication_slots_supported?' do - it 'returns false when using PostgreSQL 9.3' do - allow(described_class).to receive(:version).and_return('9.3.1') + describe '.postgresql_upcoming_deprecation?' do + it 'returns true when database version is lower than the upcoming minimum' do + allow(described_class).to receive(:version).and_return('11') + + expect(described_class.postgresql_upcoming_deprecation?).to eq(true) + end + + it 'returns false when database version equals the upcoming minimum' do + allow(described_class).to receive(:version).and_return('12') + + expect(described_class.postgresql_upcoming_deprecation?).to eq(false) + end + + it 'returns false when database version is greater the upcoming minimum' do + allow(described_class).to receive(:version).and_return('13') + + expect(described_class.postgresql_upcoming_deprecation?).to eq(false) + end + end + + describe '.check_postgres_version_and_print_warning' do + subject { described_class.check_postgres_version_and_print_warning } + + it 'prints a warning if not compliant with minimum postgres version' do + allow(described_class).to receive(:postgresql_minimum_supported_version?).and_return(false) + + expect(Kernel).to receive(:warn).with(/You are using PostgreSQL/) - expect(described_class.replication_slots_supported?).to eq(false) + subject end - it 'returns true when using PostgreSQL 9.4.0 or newer' do - allow(described_class).to receive(:version).and_return('9.4.0') + it 'doesnt print a warning if compliant with minimum postgres version' do + allow(described_class).to receive(:postgresql_minimum_supported_version?).and_return(true) - expect(described_class.replication_slots_supported?).to eq(true) + expect(Kernel).not_to receive(:warn).with(/You are using PostgreSQL/) + + subject + end + + it 'doesnt print a warning in Rails runner environment' do + allow(described_class).to receive(:postgresql_minimum_supported_version?).and_return(false) + allow(Gitlab::Runtime).to receive(:rails_runner?).and_return(true) + + expect(Kernel).not_to receive(:warn).with(/You are using PostgreSQL/) + + subject + end + + it 'ignores ActiveRecord errors' do + allow(described_class).to receive(:postgresql_minimum_supported_version?).and_raise(ActiveRecord::ActiveRecordError) + + expect { subject }.not_to raise_error + end + + it 'ignores Postgres errors' do + allow(described_class).to receive(:postgresql_minimum_supported_version?).and_raise(PG::Error) + + expect { subject }.not_to raise_error end end @@ -228,7 +283,6 @@ describe Gitlab::Database do describe '.bulk_insert' do before do allow(described_class).to receive(:connection).and_return(connection) - allow(described_class).to receive(:version).and_return(version) allow(connection).to receive(:quote_column_name, &:itself) allow(connection).to receive(:quote, &:itself) allow(connection).to receive(:execute) @@ -243,8 +297,6 @@ describe Gitlab::Database do ] end - let_it_be(:version) { 9.6 } - it 'does nothing with empty rows' do expect(connection).not_to receive(:execute) @@ -311,28 +363,13 @@ describe Gitlab::Database do expect(ids).to eq([10]) end - context 'with version >= 9.5' do - it 'allows setting the upsert to do nothing' do - expect(connection) - .to receive(:execute) - .with(/ON CONFLICT DO NOTHING/) - - described_class - .bulk_insert('test', [{ number: 10 }], on_conflict: :do_nothing) - end - end - - context 'with version < 9.5' do - let(:version) { 9.4 } - - it 'refuses setting the upsert' do - expect(connection) - .not_to receive(:execute) - .with(/ON CONFLICT/) + it 'allows setting the upsert to do nothing' do + expect(connection) + .to receive(:execute) + .with(/ON CONFLICT DO NOTHING/) - described_class - .bulk_insert('test', [{ number: 10 }], on_conflict: :do_nothing) - end + described_class + .bulk_insert('test', [{ number: 10 }], on_conflict: :do_nothing) end end end diff --git a/spec/lib/gitlab/dependency_linker/base_linker_spec.rb b/spec/lib/gitlab/dependency_linker/base_linker_spec.rb index 1466ce2dfcc..678d4a90e8d 100644 --- a/spec/lib/gitlab/dependency_linker/base_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/base_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::BaseLinker do +RSpec.describe Gitlab::DependencyLinker::BaseLinker do let(:linker_class) do Class.new(described_class) do def link_dependencies diff --git a/spec/lib/gitlab/dependency_linker/cargo_toml_linker_spec.rb b/spec/lib/gitlab/dependency_linker/cargo_toml_linker_spec.rb index 86d5bc93bf7..8068fa30367 100644 --- a/spec/lib/gitlab/dependency_linker/cargo_toml_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/cargo_toml_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::CargoTomlLinker do +RSpec.describe Gitlab::DependencyLinker::CargoTomlLinker do describe '.support?' do it 'supports Cargo.toml' do expect(described_class.support?('Cargo.toml')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/cartfile_linker_spec.rb b/spec/lib/gitlab/dependency_linker/cartfile_linker_spec.rb index 6d61edaa870..52ddba24458 100644 --- a/spec/lib/gitlab/dependency_linker/cartfile_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/cartfile_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::CartfileLinker do +RSpec.describe Gitlab::DependencyLinker::CartfileLinker do describe '.support?' do it 'supports Cartfile' do expect(described_class.support?('Cartfile')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/composer_json_linker_spec.rb b/spec/lib/gitlab/dependency_linker/composer_json_linker_spec.rb index cc1f09628ef..c24d6a44d9b 100644 --- a/spec/lib/gitlab/dependency_linker/composer_json_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/composer_json_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::ComposerJsonLinker do +RSpec.describe Gitlab::DependencyLinker::ComposerJsonLinker do describe '.support?' do it 'supports composer.json' do expect(described_class.support?('composer.json')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/gemfile_linker_spec.rb b/spec/lib/gitlab/dependency_linker/gemfile_linker_spec.rb index c6b6dfa77cb..00e95dea224 100644 --- a/spec/lib/gitlab/dependency_linker/gemfile_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/gemfile_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::GemfileLinker do +RSpec.describe Gitlab::DependencyLinker::GemfileLinker do describe '.support?' do it 'supports Gemfile' do expect(described_class.support?('Gemfile')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/gemspec_linker_spec.rb b/spec/lib/gitlab/dependency_linker/gemspec_linker_spec.rb index c1cbfa31684..ae82dd51c95 100644 --- a/spec/lib/gitlab/dependency_linker/gemspec_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/gemspec_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::GemspecLinker do +RSpec.describe Gitlab::DependencyLinker::GemspecLinker do describe '.support?' do it 'supports *.gemspec' do expect(described_class.support?('gitlab_git.gemspec')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/go_mod_linker_spec.rb b/spec/lib/gitlab/dependency_linker/go_mod_linker_spec.rb index 769daa0b3a6..605b14bc923 100644 --- a/spec/lib/gitlab/dependency_linker/go_mod_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/go_mod_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::GoModLinker do +RSpec.describe Gitlab::DependencyLinker::GoModLinker do let(:file_name) { 'go.mod' } let(:file_content) do <<-CONTENT.strip_heredoc diff --git a/spec/lib/gitlab/dependency_linker/go_sum_linker_spec.rb b/spec/lib/gitlab/dependency_linker/go_sum_linker_spec.rb index f5cb7809ad3..2836c0e9f29 100644 --- a/spec/lib/gitlab/dependency_linker/go_sum_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/go_sum_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::GoSumLinker do +RSpec.describe Gitlab::DependencyLinker::GoSumLinker do let(:file_name) { 'go.sum' } let(:file_content) do <<-CONTENT.strip_heredoc diff --git a/spec/lib/gitlab/dependency_linker/godeps_json_linker_spec.rb b/spec/lib/gitlab/dependency_linker/godeps_json_linker_spec.rb index 7128689e362..c1ed030c548 100644 --- a/spec/lib/gitlab/dependency_linker/godeps_json_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/godeps_json_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::GodepsJsonLinker do +RSpec.describe Gitlab::DependencyLinker::GodepsJsonLinker do describe '.support?' do it 'supports Godeps.json' do expect(described_class.support?('Godeps.json')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/package_json_linker_spec.rb b/spec/lib/gitlab/dependency_linker/package_json_linker_spec.rb index eb0c5e0675a..cdfc0e89bc7 100644 --- a/spec/lib/gitlab/dependency_linker/package_json_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/package_json_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::PackageJsonLinker do +RSpec.describe Gitlab::DependencyLinker::PackageJsonLinker do describe '.support?' do it 'supports package.json' do expect(described_class.support?('package.json')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/parser/gemfile_spec.rb b/spec/lib/gitlab/dependency_linker/parser/gemfile_spec.rb index 5b69ef5af24..15f580a3a60 100644 --- a/spec/lib/gitlab/dependency_linker/parser/gemfile_spec.rb +++ b/spec/lib/gitlab/dependency_linker/parser/gemfile_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::Parser::Gemfile do +RSpec.describe Gitlab::DependencyLinker::Parser::Gemfile do describe '#parse' do let(:file_content) do <<-CONTENT.strip_heredoc diff --git a/spec/lib/gitlab/dependency_linker/podfile_linker_spec.rb b/spec/lib/gitlab/dependency_linker/podfile_linker_spec.rb index 77326e73505..8e536c00ea6 100644 --- a/spec/lib/gitlab/dependency_linker/podfile_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/podfile_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::PodfileLinker do +RSpec.describe Gitlab::DependencyLinker::PodfileLinker do describe '.support?' do it 'supports Podfile' do expect(described_class.support?('Podfile')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/podspec_json_linker_spec.rb b/spec/lib/gitlab/dependency_linker/podspec_json_linker_spec.rb index d522a08cdd9..1f81049a41e 100644 --- a/spec/lib/gitlab/dependency_linker/podspec_json_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/podspec_json_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::PodspecJsonLinker do +RSpec.describe Gitlab::DependencyLinker::PodspecJsonLinker do describe '.support?' do it 'supports *.podspec.json' do expect(described_class.support?('Reachability.podspec.json')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/podspec_linker_spec.rb b/spec/lib/gitlab/dependency_linker/podspec_linker_spec.rb index baabd0c0460..132b5b21d85 100644 --- a/spec/lib/gitlab/dependency_linker/podspec_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/podspec_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::PodspecLinker do +RSpec.describe Gitlab::DependencyLinker::PodspecLinker do describe '.support?' do it 'supports *.podspec' do expect(described_class.support?('Reachability.podspec')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker/requirements_txt_linker_spec.rb b/spec/lib/gitlab/dependency_linker/requirements_txt_linker_spec.rb index 04ac5f10479..e59756cb7bc 100644 --- a/spec/lib/gitlab/dependency_linker/requirements_txt_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker/requirements_txt_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker::RequirementsTxtLinker do +RSpec.describe Gitlab::DependencyLinker::RequirementsTxtLinker do describe '.support?' do it 'supports requirements.txt' do expect(described_class.support?('requirements.txt')).to be_truthy diff --git a/spec/lib/gitlab/dependency_linker_spec.rb b/spec/lib/gitlab/dependency_linker_spec.rb index acd4376615c..2daa8df815d 100644 --- a/spec/lib/gitlab/dependency_linker_spec.rb +++ b/spec/lib/gitlab/dependency_linker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DependencyLinker do +RSpec.describe Gitlab::DependencyLinker do describe '.link' do it 'links using GemfileLinker' do blob_name = 'Gemfile' diff --git a/spec/lib/gitlab/devise_failure_spec.rb b/spec/lib/gitlab/devise_failure_spec.rb index eee05c7befd..a452de59795 100644 --- a/spec/lib/gitlab/devise_failure_spec.rb +++ b/spec/lib/gitlab/devise_failure_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DeviseFailure do +RSpec.describe Gitlab::DeviseFailure do let(:env) do { 'REQUEST_URI' => 'http://test.host/', diff --git a/spec/lib/gitlab/diff/diff_refs_spec.rb b/spec/lib/gitlab/diff/diff_refs_spec.rb index 33a7cf5ae12..c1ee34ba874 100644 --- a/spec/lib/gitlab/diff/diff_refs_spec.rb +++ b/spec/lib/gitlab/diff/diff_refs_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::DiffRefs do +RSpec.describe Gitlab::Diff::DiffRefs do let(:project) { create(:project, :repository) } describe '#==' do diff --git a/spec/lib/gitlab/diff/file_collection/commit_spec.rb b/spec/lib/gitlab/diff/file_collection/commit_spec.rb index 34ed22b8941..6c109e96a53 100644 --- a/spec/lib/gitlab/diff/file_collection/commit_spec.rb +++ b/spec/lib/gitlab/diff/file_collection/commit_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::FileCollection::Commit do +RSpec.describe Gitlab::Diff::FileCollection::Commit do let(:project) { create(:project, :repository) } it_behaves_like 'diff statistics' do diff --git a/spec/lib/gitlab/diff/file_collection/compare_spec.rb b/spec/lib/gitlab/diff/file_collection/compare_spec.rb index f330f299ac1..168d58e584e 100644 --- a/spec/lib/gitlab/diff/file_collection/compare_spec.rb +++ b/spec/lib/gitlab/diff/file_collection/compare_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::FileCollection::Compare do +RSpec.describe Gitlab::Diff::FileCollection::Compare do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/diff/file_collection/merge_request_diff_batch_spec.rb b/spec/lib/gitlab/diff/file_collection/merge_request_diff_batch_spec.rb index 7e945d1d140..bd60c24859c 100644 --- a/spec/lib/gitlab/diff/file_collection/merge_request_diff_batch_spec.rb +++ b/spec/lib/gitlab/diff/file_collection/merge_request_diff_batch_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::FileCollection::MergeRequestDiffBatch do +RSpec.describe Gitlab::Diff::FileCollection::MergeRequestDiffBatch do let(:merge_request) { create(:merge_request) } let(:batch_page) { 1 } let(:batch_size) { 10 } diff --git a/spec/lib/gitlab/diff/file_collection/merge_request_diff_spec.rb b/spec/lib/gitlab/diff/file_collection/merge_request_diff_spec.rb index c2b6ca4164c..a5e714c90fc 100644 --- a/spec/lib/gitlab/diff/file_collection/merge_request_diff_spec.rb +++ b/spec/lib/gitlab/diff/file_collection/merge_request_diff_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::FileCollection::MergeRequestDiff do +RSpec.describe Gitlab::Diff::FileCollection::MergeRequestDiff do let(:merge_request) { create(:merge_request) } let(:diffable) { merge_request.merge_request_diff } let(:subject) { described_class.new(diffable, diff_options: nil) } diff --git a/spec/lib/gitlab/diff/file_spec.rb b/spec/lib/gitlab/diff/file_spec.rb index 8dbedcf26b9..94abfcf079a 100644 --- a/spec/lib/gitlab/diff/file_spec.rb +++ b/spec/lib/gitlab/diff/file_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::File do +RSpec.describe Gitlab::Diff::File do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/diff/formatters/image_formatter_spec.rb b/spec/lib/gitlab/diff/formatters/image_formatter_spec.rb index 3f88f39ba92..579776d44aa 100644 --- a/spec/lib/gitlab/diff/formatters/image_formatter_spec.rb +++ b/spec/lib/gitlab/diff/formatters/image_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::Formatters::ImageFormatter do +RSpec.describe Gitlab::Diff::Formatters::ImageFormatter do let(:base_attrs) do { base_sha: 123, diff --git a/spec/lib/gitlab/diff/formatters/text_formatter_spec.rb b/spec/lib/gitlab/diff/formatters/text_formatter_spec.rb index 50dd597c5a7..41877a16ebf 100644 --- a/spec/lib/gitlab/diff/formatters/text_formatter_spec.rb +++ b/spec/lib/gitlab/diff/formatters/text_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::Formatters::TextFormatter do +RSpec.describe Gitlab::Diff::Formatters::TextFormatter do let!(:base) do { base_sha: 123, diff --git a/spec/lib/gitlab/diff/highlight_cache_spec.rb b/spec/lib/gitlab/diff/highlight_cache_spec.rb index 3c128aad976..80cc10051c4 100644 --- a/spec/lib/gitlab/diff/highlight_cache_spec.rb +++ b/spec/lib/gitlab/diff/highlight_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::HighlightCache, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::Diff::HighlightCache, :clean_gitlab_redis_cache do let(:merge_request) { create(:merge_request_with_diffs) } let(:diff_hash) do { ".gitignore-false-false-false" => diff --git a/spec/lib/gitlab/diff/highlight_spec.rb b/spec/lib/gitlab/diff/highlight_spec.rb index ff4ec75358e..283437e7fbd 100644 --- a/spec/lib/gitlab/diff/highlight_spec.rb +++ b/spec/lib/gitlab/diff/highlight_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::Highlight do +RSpec.describe Gitlab::Diff::Highlight do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/diff/inline_diff_markdown_marker_spec.rb b/spec/lib/gitlab/diff/inline_diff_markdown_marker_spec.rb index a668bb464a4..60f7f3a103f 100644 --- a/spec/lib/gitlab/diff/inline_diff_markdown_marker_spec.rb +++ b/spec/lib/gitlab/diff/inline_diff_markdown_marker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::InlineDiffMarkdownMarker do +RSpec.describe Gitlab::Diff::InlineDiffMarkdownMarker do describe '#mark' do let(:raw) { "abc 'def'" } let(:inline_diffs) { [2..5] } diff --git a/spec/lib/gitlab/diff/inline_diff_marker_spec.rb b/spec/lib/gitlab/diff/inline_diff_marker_spec.rb index 26b99870b31..6820a7df95e 100644 --- a/spec/lib/gitlab/diff/inline_diff_marker_spec.rb +++ b/spec/lib/gitlab/diff/inline_diff_marker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::InlineDiffMarker do +RSpec.describe Gitlab::Diff::InlineDiffMarker do describe '#mark' do let(:inline_diffs) { [2..5] } let(:raw) { "abc 'def'" } diff --git a/spec/lib/gitlab/diff/inline_diff_spec.rb b/spec/lib/gitlab/diff/inline_diff_spec.rb index fdbee3b4230..35284e952f7 100644 --- a/spec/lib/gitlab/diff/inline_diff_spec.rb +++ b/spec/lib/gitlab/diff/inline_diff_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::InlineDiff do +RSpec.describe Gitlab::Diff::InlineDiff do describe '.for_lines' do let(:diff) do <<-EOF.strip_heredoc diff --git a/spec/lib/gitlab/diff/line_mapper_spec.rb b/spec/lib/gitlab/diff/line_mapper_spec.rb index 6a86f885c3b..1c1f8201a81 100644 --- a/spec/lib/gitlab/diff/line_mapper_spec.rb +++ b/spec/lib/gitlab/diff/line_mapper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::LineMapper do +RSpec.describe Gitlab::Diff::LineMapper do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/diff/line_spec.rb b/spec/lib/gitlab/diff/line_spec.rb index 7961bec9d57..e10a50afde9 100644 --- a/spec/lib/gitlab/diff/line_spec.rb +++ b/spec/lib/gitlab/diff/line_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::Line do +RSpec.describe Gitlab::Diff::Line do shared_examples 'line object initialized by hash' do it 'round-trips correctly with to_hash' do expect(described_class.safe_init_from_hash(line.to_hash).to_hash) diff --git a/spec/lib/gitlab/diff/lines_unfolder_spec.rb b/spec/lib/gitlab/diff/lines_unfolder_spec.rb index ebcbe1fb1a0..b891f9e8285 100644 --- a/spec/lib/gitlab/diff/lines_unfolder_spec.rb +++ b/spec/lib/gitlab/diff/lines_unfolder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::LinesUnfolder do +RSpec.describe Gitlab::Diff::LinesUnfolder do let(:raw_diff) do <<-DIFF.strip_heredoc @@ -7,9 +7,6 @@ diff --git a/spec/lib/gitlab/diff/parallel_diff_spec.rb b/spec/lib/gitlab/diff/parallel_diff_spec.rb index d275bf2c223..f574d7ec707 100644 --- a/spec/lib/gitlab/diff/parallel_diff_spec.rb +++ b/spec/lib/gitlab/diff/parallel_diff_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::ParallelDiff do +RSpec.describe Gitlab::Diff::ParallelDiff do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/diff/parser_spec.rb b/spec/lib/gitlab/diff/parser_spec.rb index 00a446c4e20..7448ae0b2ea 100644 --- a/spec/lib/gitlab/diff/parser_spec.rb +++ b/spec/lib/gitlab/diff/parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::Parser do +RSpec.describe Gitlab::Diff::Parser do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/diff/position_collection_spec.rb b/spec/lib/gitlab/diff/position_collection_spec.rb index dd8434ab10b..b1478c774f1 100644 --- a/spec/lib/gitlab/diff/position_collection_spec.rb +++ b/spec/lib/gitlab/diff/position_collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::PositionCollection do +RSpec.describe Gitlab::Diff::PositionCollection do let(:merge_request) { build(:merge_request) } let(:text_position) do diff --git a/spec/lib/gitlab/diff/position_spec.rb b/spec/lib/gitlab/diff/position_spec.rb index b32a2c59bb9..a7f6ea0cbfb 100644 --- a/spec/lib/gitlab/diff/position_spec.rb +++ b/spec/lib/gitlab/diff/position_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::Position do +RSpec.describe Gitlab::Diff::Position do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/diff/position_tracer/image_strategy_spec.rb b/spec/lib/gitlab/diff/position_tracer/image_strategy_spec.rb index 900816af53a..7dceb64b776 100644 --- a/spec/lib/gitlab/diff/position_tracer/image_strategy_spec.rb +++ b/spec/lib/gitlab/diff/position_tracer/image_strategy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::PositionTracer::ImageStrategy do +RSpec.describe Gitlab::Diff::PositionTracer::ImageStrategy do include PositionTracerHelpers let(:project) { create(:project, :repository) } @@ -234,5 +234,118 @@ describe Gitlab::Diff::PositionTracer::ImageStrategy do end end end + + describe 'symlink scenarios' do + let(:new_file) { old_file_status == :new } + let(:deleted_file) { old_file_status == :deleted } + let(:renamed_file) { old_file_status == :renamed } + + let(:file_identifier) { "#{file_name}-#{new_file}-#{deleted_file}-#{renamed_file}" } + let(:file_identifier_hash) { Digest::SHA1.hexdigest(file_identifier) } + let(:old_position) { position(old_path: file_name, new_path: file_name, position_type: 'image', file_identifier_hash: file_identifier_hash) } + + let(:update_file_commit) do + initial_commit + + update_file( + branch_name, + file_name, + Base64.encode64('morecontent') + ) + end + + let(:delete_file_commit) do + initial_commit + + delete_file(branch_name, file_name) + end + + let(:create_second_file_commit) do + initial_commit + + create_file( + branch_name, + second_file_name, + Base64.encode64('morecontent') + ) + end + + before do + stub_feature_flags(file_identifier_hash: true) + end + + describe 'from symlink to image' do + let(:initial_commit) { project.commit('a19c7f9a147e35e535c797cf148d29c24dac5544') } + let(:symlink_to_image_commit) { project.commit('8cfca8420812e5bd7479aa32cf33e0c95a3ca576') } + let(:branch_name) { 'diff-files-symlink-to-image' } + let(:file_name) { 'symlink-to-image.png' } + + context "when the old position is on the new image file" do + let(:old_file_status) { :new } + + context "when the image file's content was unchanged between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit, symlink_to_image_commit) } + let(:new_diff_refs) { diff_refs(initial_commit, create_second_file_commit) } + + it "returns the new position" do + expect_new_position( + old_path: file_name, + new_path: file_name + ) + end + end + + context "when the image file's content was changed between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit, symlink_to_image_commit) } + let(:new_diff_refs) { diff_refs(initial_commit, update_file_commit) } + let(:change_diff_refs) { diff_refs(symlink_to_image_commit, update_file_commit) } + + it "returns the position of the change" do + expect_change_position( + old_path: file_name, + new_path: file_name + ) + end + end + + context "when the image file was removed between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit, symlink_to_image_commit) } + let(:new_diff_refs) { diff_refs(initial_commit, delete_file_commit) } + let(:change_diff_refs) { diff_refs(symlink_to_image_commit, delete_file_commit) } + + it "returns the position of the change" do + expect_change_position( + old_path: file_name, + new_path: file_name + ) + end + end + end + end + + describe 'from image to symlink' do + let(:initial_commit) { project.commit('d10dcdfbbb2b59a959a5f5d66a4adf28f0ea4008') } + let(:image_to_symlink_commit) { project.commit('3e94fdaa60da8aed38401b91bc56be70d54ca424') } + let(:branch_name) { 'diff-files-image-to-symlink' } + let(:file_name) { 'image-to-symlink.png' } + + context "when the old position is on the added image file" do + let(:old_file_status) { :new } + + context "when the image file gets changed to a symlink between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit.parent, initial_commit) } + let(:new_diff_refs) { diff_refs(initial_commit.parent, image_to_symlink_commit) } + let(:change_diff_refs) { diff_refs(initial_commit, image_to_symlink_commit) } + + it "returns the position of the change" do + expect_change_position( + old_path: file_name, + new_path: file_name + ) + end + end + end + end + end end end diff --git a/spec/lib/gitlab/diff/position_tracer/line_strategy_spec.rb b/spec/lib/gitlab/diff/position_tracer/line_strategy_spec.rb index 7f4902c5b86..d9f384fb47f 100644 --- a/spec/lib/gitlab/diff/position_tracer/line_strategy_spec.rb +++ b/spec/lib/gitlab/diff/position_tracer/line_strategy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::PositionTracer::LineStrategy do +RSpec.describe Gitlab::Diff::PositionTracer::LineStrategy do # Douwe's diary New York City, 2016-06-28 # -------------------------------------------------------------------------- # @@ -1801,5 +1801,143 @@ describe Gitlab::Diff::PositionTracer::LineStrategy do end end end + + describe 'symlink scenarios' do + let(:new_file) { old_file_status == :new } + let(:deleted_file) { old_file_status == :deleted } + let(:renamed_file) { old_file_status == :renamed } + + let(:file_identifier) { "#{file_name}-#{new_file}-#{deleted_file}-#{renamed_file}" } + let(:file_identifier_hash) { Digest::SHA1.hexdigest(file_identifier) } + + let(:update_line_commit) do + update_file( + branch_name, + file_name, + <<-CONTENT.strip_heredoc + A + BB + C + CONTENT + ) + end + + let(:delete_file_commit) do + delete_file(branch_name, file_name) + end + + let(:create_second_file_commit) do + create_file( + branch_name, + second_file_name, + <<-CONTENT.strip_heredoc + D + E + CONTENT + ) + end + + before do + stub_feature_flags(file_identifier_hash: true) + end + + describe 'from symlink to text' do + let(:initial_commit) { project.commit('0e5b363105e9176a77bac94d7ff6d8c4fb35c3eb') } + let(:symlink_to_text_commit) { project.commit('689815e617abc6889f1fded4834d2dd7d942a58e') } + let(:branch_name) { 'diff-files-symlink-to-text' } + let(:file_name) { 'symlink-to-text.txt' } + let(:old_position) { position(old_path: file_name, new_path: file_name, new_line: 3, file_identifier_hash: file_identifier_hash) } + + before do + create_branch('diff-files-symlink-to-text-test', branch_name) + end + + context "when the old position is on the new text file" do + let(:old_file_status) { :new } + + context "when the text file's content was unchanged between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit, symlink_to_text_commit) } + let(:new_diff_refs) { diff_refs(initial_commit, create_second_file_commit) } + + it "returns the new position" do + expect_new_position( + new_path: old_position.new_path, + new_line: old_position.new_line + ) + end + end + + context "when the text file's content has change, but the line was unchanged between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit, symlink_to_text_commit) } + let(:new_diff_refs) { diff_refs(initial_commit, update_line_commit) } + + it "returns the new position" do + expect_new_position( + new_path: old_position.new_path, + new_line: old_position.new_line + ) + end + end + + context "when the text file's line was changed between the old and the new diff" do + let(:old_position) { position(old_path: file_name, new_path: file_name, new_line: 2, file_identifier_hash: file_identifier_hash) } + + let(:old_diff_refs) { diff_refs(initial_commit, symlink_to_text_commit) } + let(:new_diff_refs) { diff_refs(initial_commit, update_line_commit) } + let(:change_diff_refs) { diff_refs(symlink_to_text_commit, update_line_commit) } + + it "returns the position of the change" do + expect_change_position( + old_path: file_name, + new_path: file_name, + old_line: 2, + new_line: nil + ) + end + end + + context "when the text file was removed between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit, symlink_to_text_commit) } + let(:new_diff_refs) { diff_refs(initial_commit, delete_file_commit) } + let(:change_diff_refs) { diff_refs(symlink_to_text_commit, delete_file_commit) } + + it "returns the position of the change" do + expect_change_position( + old_path: file_name, + new_path: file_name, + old_line: 3, + new_line: nil + ) + end + end + end + + describe 'from text to symlink' do + let(:initial_commit) { project.commit('3db7bd90bab8ce8f02c9818590b84739a2e97230') } + let(:text_to_symlink_commit) { project.commit('5e2c2708c2e403dece5dd25759369150aac51644') } + let(:branch_name) { 'diff-files-text-to-symlink' } + let(:file_name) { 'text-to-symlink.txt' } + + context "when the position is on the added text file" do + let(:old_file_status) { :new } + + context "when the text file gets changed to a symlink between the old and the new diff" do + let(:old_diff_refs) { diff_refs(initial_commit.parent, initial_commit) } + let(:new_diff_refs) { diff_refs(initial_commit.parent, text_to_symlink_commit) } + let(:change_diff_refs) { diff_refs(initial_commit, text_to_symlink_commit) } + + it "returns the position of the change" do + expect_change_position( + old_path: file_name, + new_path: file_name, + old_line: 3, + new_line: nil + ) + end + end + end + end + end + end end end diff --git a/spec/lib/gitlab/diff/position_tracer_spec.rb b/spec/lib/gitlab/diff/position_tracer_spec.rb index 47d78e0b18c..fc649812b0a 100644 --- a/spec/lib/gitlab/diff/position_tracer_spec.rb +++ b/spec/lib/gitlab/diff/position_tracer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::PositionTracer do +RSpec.describe Gitlab::Diff::PositionTracer do include PositionTracerHelpers subject do diff --git a/spec/lib/gitlab/diff/stats_cache_spec.rb b/spec/lib/gitlab/diff/stats_cache_spec.rb new file mode 100644 index 00000000000..8bf510c0bdd --- /dev/null +++ b/spec/lib/gitlab/diff/stats_cache_spec.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Diff::StatsCache, :use_clean_rails_memory_store_caching do + subject(:stats_cache) { described_class.new(cachable_key: cachable_key) } + + let(:key) { ['diff_stats', cachable_key, described_class::VERSION].join(":") } + let(:cachable_key) { 'cachecachecache' } + let(:stat) { Gitaly::DiffStats.new(path: 'temp', additions: 10, deletions: 15) } + let(:stats) { Gitlab::Git::DiffStatsCollection.new([stat]) } + let(:cache) { Rails.cache } + + describe '#read' do + before do + stats_cache.write_if_empty(stats) + end + + it 'returns the expected stats' do + expect(stats_cache.read.to_json).to eq(stats.to_json) + end + end + + describe '#write_if_empty' do + context 'when the cache already exists' do + before do + Rails.cache.write(key, true) + end + + it 'does not write the stats' do + expect(cache).not_to receive(:write) + + stats_cache.write_if_empty(stats) + end + end + + context 'when the cache does not exist' do + it 'writes the stats' do + expect(cache) + .to receive(:write) + .with(key, stats.as_json, expires_in: described_class::EXPIRATION) + .and_call_original + + stats_cache.write_if_empty(stats) + + expect(stats_cache.read.to_a).to eq(stats.to_a) + end + + context 'when given non utf-8 characters' do + let(:non_utf8_path) { 'ä½ å¥½'.b } + let(:stat) { Gitaly::DiffStats.new(path: non_utf8_path, additions: 10, deletions: 15) } + + it 'writes the stats' do + expect(cache) + .to receive(:write) + .with(key, stats.as_json, expires_in: described_class::EXPIRATION) + .and_call_original + + stats_cache.write_if_empty(stats) + + expect(stats_cache.read.to_a).to eq(stats.to_a) + end + end + + context 'when given empty stats' do + let(:stats) { nil } + + it 'does not write the stats' do + expect(cache).not_to receive(:write) + + stats_cache.write_if_empty(stats) + end + end + end + end + + describe '#clear' do + it 'clears cache' do + expect(cache).to receive(:delete).with(key) + + stats_cache.clear + end + end +end diff --git a/spec/lib/gitlab/diff/suggestion_diff_spec.rb b/spec/lib/gitlab/diff/suggestion_diff_spec.rb index 0d4fe33bc47..9546c581112 100644 --- a/spec/lib/gitlab/diff/suggestion_diff_spec.rb +++ b/spec/lib/gitlab/diff/suggestion_diff_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::SuggestionDiff do +RSpec.describe Gitlab::Diff::SuggestionDiff do describe '#diff_lines' do let(:from_content) do <<-BLOB.strip_heredoc diff --git a/spec/lib/gitlab/diff/suggestion_spec.rb b/spec/lib/gitlab/diff/suggestion_spec.rb index d7ca0e0a522..5a5c5555818 100644 --- a/spec/lib/gitlab/diff/suggestion_spec.rb +++ b/spec/lib/gitlab/diff/suggestion_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::Suggestion do +RSpec.describe Gitlab::Diff::Suggestion do shared_examples 'correct suggestion raw content' do it 'returns correct raw data' do expect(suggestion.to_hash).to include(from_content: expected_lines.join, diff --git a/spec/lib/gitlab/diff/suggestions_parser_spec.rb b/spec/lib/gitlab/diff/suggestions_parser_spec.rb index 1f2af42f6e7..5efce414dc8 100644 --- a/spec/lib/gitlab/diff/suggestions_parser_spec.rb +++ b/spec/lib/gitlab/diff/suggestions_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Diff::SuggestionsParser do +RSpec.describe Gitlab::Diff::SuggestionsParser do describe '.parse' do let(:merge_request) { create(:merge_request) } let(:project) { merge_request.project } diff --git a/spec/lib/gitlab/discussions_diff/file_collection_spec.rb b/spec/lib/gitlab/discussions_diff/file_collection_spec.rb index a13727b62ea..f85a68ada15 100644 --- a/spec/lib/gitlab/discussions_diff/file_collection_spec.rb +++ b/spec/lib/gitlab/discussions_diff/file_collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DiscussionsDiff::FileCollection do +RSpec.describe Gitlab::DiscussionsDiff::FileCollection do let(:merge_request) { create(:merge_request) } let!(:diff_note_a) { create(:diff_note_on_merge_request, project: merge_request.project, noteable: merge_request) } let!(:diff_note_b) { create(:diff_note_on_merge_request, project: merge_request.project, noteable: merge_request) } diff --git a/spec/lib/gitlab/discussions_diff/highlight_cache_spec.rb b/spec/lib/gitlab/discussions_diff/highlight_cache_spec.rb index 97d3a49ea90..9f10811d765 100644 --- a/spec/lib/gitlab/discussions_diff/highlight_cache_spec.rb +++ b/spec/lib/gitlab/discussions_diff/highlight_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DiscussionsDiff::HighlightCache, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::DiscussionsDiff::HighlightCache, :clean_gitlab_redis_cache do def fake_file(offset) { text: 'foo', diff --git a/spec/lib/gitlab/doctor/secrets_spec.rb b/spec/lib/gitlab/doctor/secrets_spec.rb index f118519fd9f..b9e054ce14f 100644 --- a/spec/lib/gitlab/doctor/secrets_spec.rb +++ b/spec/lib/gitlab/doctor/secrets_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Doctor::Secrets do +RSpec.describe Gitlab::Doctor::Secrets do let!(:user) { create(:user, otp_secret: "test") } let!(:group) { create(:group, runners_token: "test") } let(:logger) { double(:logger).as_null_object } diff --git a/spec/lib/gitlab/downtime_check/message_spec.rb b/spec/lib/gitlab/downtime_check/message_spec.rb index 2beb5a19a32..2d82836db33 100644 --- a/spec/lib/gitlab/downtime_check/message_spec.rb +++ b/spec/lib/gitlab/downtime_check/message_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DowntimeCheck::Message do +RSpec.describe Gitlab::DowntimeCheck::Message do describe '#to_s' do it 'returns an ANSI formatted String for an offline migration' do message = described_class.new('foo.rb', true, 'hello') diff --git a/spec/lib/gitlab/downtime_check_spec.rb b/spec/lib/gitlab/downtime_check_spec.rb index 5a5e34961a4..761519425f6 100644 --- a/spec/lib/gitlab/downtime_check_spec.rb +++ b/spec/lib/gitlab/downtime_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::DowntimeCheck do +RSpec.describe Gitlab::DowntimeCheck do subject { described_class.new } let(:path) { 'foo.rb' } diff --git a/spec/lib/gitlab/elasticsearch/logs/lines_spec.rb b/spec/lib/gitlab/elasticsearch/logs/lines_spec.rb index 45a262c0e77..f93c1aa1974 100644 --- a/spec/lib/gitlab/elasticsearch/logs/lines_spec.rb +++ b/spec/lib/gitlab/elasticsearch/logs/lines_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Elasticsearch::Logs::Lines do +RSpec.describe Gitlab::Elasticsearch::Logs::Lines do let(:client) { Elasticsearch::Transport::Client } let(:es_message_1) { { timestamp: "2019-12-13T14:35:34.034Z", pod: "production-6866bc8974-m4sk4", message: "10.8.2.1 - - [25/Oct/2019:08:03:22 UTC] \"GET / HTTP/1.1\" 200 13" } } diff --git a/spec/lib/gitlab/elasticsearch/logs/pods_spec.rb b/spec/lib/gitlab/elasticsearch/logs/pods_spec.rb index c2c3074e965..07fa0980d36 100644 --- a/spec/lib/gitlab/elasticsearch/logs/pods_spec.rb +++ b/spec/lib/gitlab/elasticsearch/logs/pods_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Elasticsearch::Logs::Pods do +RSpec.describe Gitlab::Elasticsearch::Logs::Pods do let(:client) { Elasticsearch::Transport::Client } let(:es_query) { Gitlab::Json.parse(fixture_file('lib/elasticsearch/pods_query.json'), symbolize_names: true) } diff --git a/spec/lib/gitlab/email/attachment_uploader_spec.rb b/spec/lib/gitlab/email/attachment_uploader_spec.rb index 5104e0a3f8f..6beadb6e1a5 100644 --- a/spec/lib/gitlab/email/attachment_uploader_spec.rb +++ b/spec/lib/gitlab/email/attachment_uploader_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Email::AttachmentUploader do +RSpec.describe Gitlab::Email::AttachmentUploader do describe "#execute" do let(:project) { create(:project) } let(:message_raw) { fixture_file("emails/attachment.eml") } diff --git a/spec/lib/gitlab/email/handler/create_issue_handler_spec.rb b/spec/lib/gitlab/email/handler/create_issue_handler_spec.rb index 7833b9f387d..ee2173a9c8d 100644 --- a/spec/lib/gitlab/email/handler/create_issue_handler_spec.rb +++ b/spec/lib/gitlab/email/handler/create_issue_handler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Handler::CreateIssueHandler do +RSpec.describe Gitlab::Email::Handler::CreateIssueHandler do include_context :email_shared_context it_behaves_like :reply_processing_shared_examples diff --git a/spec/lib/gitlab/email/handler/create_merge_request_handler_spec.rb b/spec/lib/gitlab/email/handler/create_merge_request_handler_spec.rb index 9f5413f9607..75d5fc040cb 100644 --- a/spec/lib/gitlab/email/handler/create_merge_request_handler_spec.rb +++ b/spec/lib/gitlab/email/handler/create_merge_request_handler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Handler::CreateMergeRequestHandler do +RSpec.describe Gitlab::Email::Handler::CreateMergeRequestHandler do include_context :email_shared_context it_behaves_like :reply_processing_shared_examples diff --git a/spec/lib/gitlab/email/handler/create_note_handler_spec.rb b/spec/lib/gitlab/email/handler/create_note_handler_spec.rb index af963e1b695..e5598bbd10f 100644 --- a/spec/lib/gitlab/email/handler/create_note_handler_spec.rb +++ b/spec/lib/gitlab/email/handler/create_note_handler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Handler::CreateNoteHandler do +RSpec.describe Gitlab::Email::Handler::CreateNoteHandler do include_context :email_shared_context it_behaves_like :reply_processing_shared_examples @@ -242,4 +242,70 @@ describe Gitlab::Email::Handler::CreateNoteHandler do it_behaves_like 'a reply to existing comment' end + + context 'when the service desk' do + let(:project) { create(:project, :public, service_desk_enabled: true) } + let(:support_bot) { User.support_bot } + let(:noteable) { create(:issue, project: project, author: support_bot, title: 'service desk issue') } + let(:note) { create(:note, project: project, noteable: noteable) } + let(:email_raw) { fixture_file('emails/valid_reply_with_quick_actions.eml') } + + let!(:sent_notification) do + SentNotification.record_note(note, support_bot.id, mail_key) + end + + context 'is enabled' do + before do + allow(Gitlab::ServiceDesk).to receive(:enabled?).with(project: project).and_return(true) + project.project_feature.update!(issues_access_level: issues_access_level) + end + + context 'when issues are enabled for everyone' do + let(:issues_access_level) { ProjectFeature::ENABLED } + + it 'creates a comment' do + expect { receiver.execute }.to change { noteable.notes.count }.by(1) + end + + context 'when quick actions are present' do + it 'encloses quick actions with code span markdown' do + receiver.execute + noteable.reload + + note = Note.last + expect(note.note).to include("Jake out\n\n`/close`\n`/title test`") + expect(noteable.title).to eq('service desk issue') + expect(noteable).to be_opened + end + end + end + + context 'when issues are protected members only' do + let(:issues_access_level) { ProjectFeature::PRIVATE } + + it 'creates a comment' do + expect { receiver.execute }.to change { noteable.notes.count }.by(1) + end + end + + context 'when issues are disabled' do + let(:issues_access_level) { ProjectFeature::DISABLED } + + it 'does not create a comment' do + expect { receiver.execute }.to raise_error(Gitlab::Email::UserNotAuthorizedError) + end + end + end + + context 'is disabled' do + before do + allow(Gitlab::ServiceDesk).to receive(:enabled?).and_return(false) + allow(Gitlab::ServiceDesk).to receive(:enabled?).with(project: project).and_return(false) + end + + it 'does not create a comment' do + expect { receiver.execute }.to raise_error(Gitlab::Email::ProjectNotFound) + end + end + end end diff --git a/spec/lib/gitlab/email/handler/service_desk_handler_spec.rb b/spec/lib/gitlab/email/handler/service_desk_handler_spec.rb new file mode 100644 index 00000000000..a38fe2c51ca --- /dev/null +++ b/spec/lib/gitlab/email/handler/service_desk_handler_spec.rb @@ -0,0 +1,311 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Email::Handler::ServiceDeskHandler do + include_context :email_shared_context + + before do + stub_incoming_email_setting(enabled: true, address: "incoming+%{key}@appmail.adventuretime.ooo") + stub_config_setting(host: 'localhost') + end + + let(:email_raw) { email_fixture('emails/service_desk.eml') } + let_it_be(:namespace) { create(:namespace, name: "email") } + let(:expected_description) do + "Service desk stuff!\n\n```\na = b\n```\n\n`/label ~label1`\n`/assign @user1`\n`/close`\n![image](uploads/image.png)" + end + + context 'service desk is enabled for the project' do + let_it_be(:project) { create(:project, :repository, :public, namespace: namespace, path: 'test', service_desk_enabled: true) } + + before do + allow(Gitlab::ServiceDesk).to receive(:supported?).and_return(true) + end + + shared_examples 'a new issue request' do + before do + setup_attachment + end + + it 'creates a new issue' do + expect { receiver.execute }.to change { Issue.count }.by(1) + + new_issue = Issue.last + + expect(new_issue.author).to eql(User.support_bot) + expect(new_issue.confidential?).to be true + expect(new_issue.all_references.all).to be_empty + expect(new_issue.title).to eq("Service Desk (from jake@adventuretime.ooo): The message subject! @all") + expect(new_issue.description).to eq(expected_description.strip) + end + + it 'sends thank you email' do + expect { receiver.execute }.to have_enqueued_job.on_queue('mailers') + end + end + + context 'when everything is fine' do + it_behaves_like 'a new issue request' + + context 'with legacy incoming email address' do + let(:email_raw) { fixture_file('emails/service_desk_legacy.eml') } + + it_behaves_like 'a new issue request' + end + + context 'when using issue templates' do + let_it_be(:user) { create(:user) } + + before do + setup_attachment + end + + context 'and template is present' do + let_it_be(:settings) { create(:service_desk_setting, project: project) } + + def set_template_file(file_name, content) + file_path = ".gitlab/issue_templates/#{file_name}.md" + project.repository.create_file(user, file_path, content, message: 'message', branch_name: 'master') + settings.update!(issue_template_key: file_name) + end + + it 'appends template text to issue description' do + set_template_file('service_desk', 'text from template') + + receiver.execute + + issue_description = Issue.last.description + expect(issue_description).to include(expected_description) + expect(issue_description.lines.last).to eq('text from template') + end + + context 'when quick actions are present' do + let(:label) { create(:label, project: project, title: 'label1') } + let(:milestone) { create(:milestone, project: project) } + let!(:user) { create(:user, username: 'user1') } + + before do + project.add_developer(user) + end + + it 'applies quick action commands present on templates' do + file_content = %(Text from template \n/label ~#{label.title} \n/milestone %"#{milestone.name}"") + set_template_file('with_slash_commands', file_content) + + receiver.execute + + issue = Issue.last + expect(issue.description).to include('Text from template') + expect(issue.label_ids).to include(label.id) + expect(issue.milestone).to eq(milestone) + end + + it 'redacts quick actions present on user email body' do + set_template_file('service_desk1', 'text from template') + + receiver.execute + + issue = Issue.last + expect(issue).to be_opened + expect(issue.description).to include('`/label ~label1`') + expect(issue.description).to include('`/assign @user1`') + expect(issue.description).to include('`/close`') + expect(issue.assignees).to be_empty + expect(issue.milestone).to be_nil + end + end + end + + context 'and template cannot be found' do + before do + service = ServiceDeskSetting.new(project_id: project.id, issue_template_key: 'unknown') + service.save!(validate: false) + end + + it 'does not append template text to issue description' do + receiver.execute + + new_issue = Issue.last + + expect(new_issue.description).to eq(expected_description.strip) + end + + it 'creates support bot note on issue' do + receiver.execute + + note = Note.last + + expect(note.note).to include("WARNING: The template file unknown.md used for service desk issues is empty or could not be found.") + expect(note.author).to eq(User.support_bot) + end + + it 'does not send warning note email' do + ActionMailer::Base.deliveries = [] + + perform_enqueued_jobs do + expect { receiver.execute }.to change { ActionMailer::Base.deliveries.size }.by(1) + end + + # Only sends created issue email + expect(ActionMailer::Base.deliveries.last.text_part.body).to include("Thank you for your support request!") + end + end + end + + context 'when using service desk key' do + let_it_be(:service_desk_settings) { create(:service_desk_setting, project: project, project_key: 'mykey') } + let(:email_raw) { service_desk_fixture('emails/service_desk_custom_address.eml') } + let(:receiver) { Gitlab::Email::ServiceDeskReceiver.new(email_raw) } + + before do + stub_service_desk_email_setting(enabled: true, address: 'support+%{key}@example.com') + end + + it_behaves_like 'a new issue request' + + context 'when there is no project with the key' do + let(:email_raw) { service_desk_fixture('emails/service_desk_custom_address.eml', key: 'some_key') } + + it 'bounces the email' do + expect { receiver.execute }.to raise_error(Gitlab::Email::ProjectNotFound) + end + end + + context 'when the project slug does not match' do + let(:email_raw) { service_desk_fixture('emails/service_desk_custom_address.eml', slug: 'some-slug') } + + it 'bounces the email' do + expect { receiver.execute }.to raise_error(Gitlab::Email::ProjectNotFound) + end + end + + context 'when service_desk_custom_address feature is disabled' do + before do + stub_feature_flags(service_desk_custom_address: false) + end + + it 'bounces the email' do + expect { receiver.execute }.to raise_error(Gitlab::Email::ProjectNotFound) + end + end + end + end + + describe '#can_handle?' do + let(:mail) { Mail::Message.new(email_raw) } + + it 'handles the new email key format' do + handler = described_class.new(mail, "h5bp-html5-boilerplate-#{project.project_id}-issue-") + + expect(handler.instance_variable_get(:@project_id).to_i).to eq project.project_id + expect(handler.can_handle?).to be_truthy + end + + it 'handles the legacy email key format' do + handler = described_class.new(mail, "h5bp/html5-boilerplate") + + expect(handler.instance_variable_get(:@project_path)).to eq 'h5bp/html5-boilerplate' + expect(handler.can_handle?).to be_truthy + end + + it "doesn't handle invalid email key" do + handler = described_class.new(mail, "h5bp-html5-boilerplate-invalid") + + expect(handler.can_handle?).to be_falsey + end + end + + context 'when there is no from address' do + before do + allow_next_instance_of(described_class) do |instance| + allow(instance).to receive(:from_address).and_return(nil) + end + end + + it "creates a new issue" do + expect { receiver.execute }.to change { Issue.count }.by(1) + end + + it 'does not send thank you email' do + expect { receiver.execute }.not_to have_enqueued_job.on_queue('mailers') + end + end + + context 'when there is a sender address and a from address' do + let(:email_raw) { email_fixture('emails/service_desk_sender_and_from.eml') } + + it 'prefers the from address' do + setup_attachment + + expect { receiver.execute }.to change { Issue.count }.by(1) + + new_issue = Issue.last + + expect(new_issue.service_desk_reply_to).to eq('finn@adventuretime.ooo') + end + end + + context 'when service desk is not enabled for project' do + before do + allow(Gitlab::ServiceDesk).to receive(:enabled?).and_return(false) + end + + it 'does not create an issue' do + expect { receiver.execute rescue nil }.not_to change { Issue.count } + end + + it 'does not send thank you email' do + expect { receiver.execute rescue nil }.not_to have_enqueued_job.on_queue('mailers') + end + end + + context 'when the email is forwarded through an alias' do + let(:email_raw) { email_fixture('emails/service_desk_forwarded.eml') } + + it_behaves_like 'a new issue request' + end + + context 'when the email is forwarded' do + let(:email_raw) { email_fixture('emails/service_desk_forwarded_new_issue.eml') } + + it_behaves_like 'a new issue request' do + let(:expected_description) do + <<~EOF + Service desk stuff! + + ---------- Forwarded message --------- + From: Jake the Dog <jake@adventuretime.ooo> + To: <jake@adventuretime.ooo> + + + forwarded content + + ![image](uploads/image.png) + EOF + end + end + end + end + + context 'service desk is disabled for the project' do + let(:project) { create(:project, :public, namespace: namespace, path: 'test', service_desk_enabled: false) } + + it 'bounces the email' do + expect { receiver.execute }.to raise_error(Gitlab::Email::ProcessingError) + end + + it "doesn't create an issue" do + expect { receiver.execute rescue nil }.not_to change { Issue.count } + end + end + + def email_fixture(path) + fixture_file(path).gsub('project_id', project.project_id.to_s) + end + + def service_desk_fixture(path, slug: nil, key: 'mykey') + slug ||= project.full_path_slug.to_s + fixture_file(path).gsub('project_slug', slug).gsub('project_key', key) + end +end diff --git a/spec/lib/gitlab/email/handler/unsubscribe_handler_spec.rb b/spec/lib/gitlab/email/handler/unsubscribe_handler_spec.rb index dcddd00df59..13ad9ddd8ef 100644 --- a/spec/lib/gitlab/email/handler/unsubscribe_handler_spec.rb +++ b/spec/lib/gitlab/email/handler/unsubscribe_handler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Handler::UnsubscribeHandler do +RSpec.describe Gitlab::Email::Handler::UnsubscribeHandler do include_context :email_shared_context before do diff --git a/spec/lib/gitlab/email/handler_spec.rb b/spec/lib/gitlab/email/handler_spec.rb index 6dbf069f07c..2cd8c31e6b2 100644 --- a/spec/lib/gitlab/email/handler_spec.rb +++ b/spec/lib/gitlab/email/handler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Handler do +RSpec.describe Gitlab::Email::Handler do let(:email) { Mail.new { body 'email' } } describe '.for' do @@ -33,12 +33,40 @@ describe Gitlab::Email::Handler do it 'returns nil if provided email is nil' do expect(described_class.for(nil, '')).to be_nil end + + context 'new issue email' do + def handler_for(fixture, mail_key) + described_class.for(fixture_file(fixture), mail_key) + end + + before do + stub_incoming_email_setting(enabled: true, address: "incoming+%{key}@appmail.adventuretime.ooo") + stub_config_setting(host: 'localhost') + end + + let!(:user) { create(:user, email: 'jake@adventuretime.ooo', incoming_email_token: 'auth_token') } + + context 'a Service Desk email' do + it 'uses the Service Desk handler' do + expect(handler_for('emails/service_desk.eml', 'some/project')).to be_instance_of(Gitlab::Email::Handler::ServiceDeskHandler) + end + end + + it 'return new issue handler' do + expect(handler_for('emails/valid_new_issue.eml', 'some/project+auth_token')).to be_instance_of(Gitlab::Email::Handler::CreateIssueHandler) + end + end end describe 'regexps are set properly' do let(:addresses) do - %W(sent_notification_key#{Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX} sent_notification_key path-to-project-123-user_email_token-merge-request path-to-project-123-user_email_token-issue) + - %W(sent_notification_key#{Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX_LEGACY} sent_notification_key path/to/project+merge-request+user_email_token path/to/project+user_email_token) + %W(sent_notification_key#{Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX} sent_notification_key path-to-project-123-user_email_token-merge-request) + + %W(sent_notification_key#{Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX_LEGACY} sent_notification_key path-to-project-123-user_email_token-issue) + + %w(path/to/project+user_email_token path/to/project+merge-request+user_email_token some/project) + end + + before do + allow(Gitlab::ServiceDesk).to receive(:supported?).and_return(true) end it 'picks each handler at least once' do @@ -46,12 +74,12 @@ describe Gitlab::Email::Handler do described_class.for(email, address).class end - expect(matched_handlers.uniq).to match_array(ce_handlers) + expect(matched_handlers.uniq).to match_array(Gitlab::Email::Handler.handlers) end it 'can pick exactly one handler for each address' do addresses.each do |address| - matched_handlers = ce_handlers.select do |handler| + matched_handlers = Gitlab::Email::Handler.handlers.select do |handler| handler.new(email, address).can_handle? end @@ -59,10 +87,4 @@ describe Gitlab::Email::Handler do end end end - - def ce_handlers - @ce_handlers ||= Gitlab::Email::Handler.handlers.reject do |handler| - handler.name.start_with?('Gitlab::Email::Handler::EE::') - end - end end diff --git a/spec/lib/gitlab/email/hook/additional_headers_interceptor_spec.rb b/spec/lib/gitlab/email/hook/additional_headers_interceptor_spec.rb index 65e4e27d56f..deaa086d689 100644 --- a/spec/lib/gitlab/email/hook/additional_headers_interceptor_spec.rb +++ b/spec/lib/gitlab/email/hook/additional_headers_interceptor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Hook::AdditionalHeadersInterceptor do +RSpec.describe Gitlab::Email::Hook::AdditionalHeadersInterceptor do let(:mail) do ActionMailer::Base.mail(to: 'test@mail.com', from: 'info@mail.com', body: 'hello') end diff --git a/spec/lib/gitlab/email/hook/delivery_metrics_observer_spec.rb b/spec/lib/gitlab/email/hook/delivery_metrics_observer_spec.rb index 24da47c42ac..73a0573be26 100644 --- a/spec/lib/gitlab/email/hook/delivery_metrics_observer_spec.rb +++ b/spec/lib/gitlab/email/hook/delivery_metrics_observer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Hook::DeliveryMetricsObserver do +RSpec.describe Gitlab::Email::Hook::DeliveryMetricsObserver do let(:email) do ActionMailer::Base.mail(to: 'test@example.com', from: 'info@example.com', diff --git a/spec/lib/gitlab/email/hook/disable_email_interceptor_spec.rb b/spec/lib/gitlab/email/hook/disable_email_interceptor_spec.rb index c8ed12523d0..47f6015c6f8 100644 --- a/spec/lib/gitlab/email/hook/disable_email_interceptor_spec.rb +++ b/spec/lib/gitlab/email/hook/disable_email_interceptor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Hook::DisableEmailInterceptor do +RSpec.describe Gitlab::Email::Hook::DisableEmailInterceptor do before do Mail.register_interceptor(described_class) end diff --git a/spec/lib/gitlab/email/hook/smime_signature_interceptor_spec.rb b/spec/lib/gitlab/email/hook/smime_signature_interceptor_spec.rb index 31ba48e9df1..56cf58dcf92 100644 --- a/spec/lib/gitlab/email/hook/smime_signature_interceptor_spec.rb +++ b/spec/lib/gitlab/email/hook/smime_signature_interceptor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Hook::SmimeSignatureInterceptor do +RSpec.describe Gitlab::Email::Hook::SmimeSignatureInterceptor do include SmimeHelper # certs generation is an expensive operation and they are used read-only, diff --git a/spec/lib/gitlab/email/message/repository_push_spec.rb b/spec/lib/gitlab/email/message/repository_push_spec.rb index 9e95d31f41c..10586527239 100644 --- a/spec/lib/gitlab/email/message/repository_push_spec.rb +++ b/spec/lib/gitlab/email/message/repository_push_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Message::RepositoryPush do +RSpec.describe Gitlab::Email::Message::RepositoryPush do include RepoHelpers let!(:group) { create(:group, name: 'my_group') } diff --git a/spec/lib/gitlab/email/receiver_spec.rb b/spec/lib/gitlab/email/receiver_spec.rb index d860968ab98..592d3f3f0e4 100644 --- a/spec/lib/gitlab/email/receiver_spec.rb +++ b/spec/lib/gitlab/email/receiver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Receiver do +RSpec.describe Gitlab::Email::Receiver do include_context :email_shared_context shared_examples 'correctly finds the mail key' do diff --git a/spec/lib/gitlab/email/reply_parser_spec.rb b/spec/lib/gitlab/email/reply_parser_spec.rb index 646575b2edd..575ff7f357b 100644 --- a/spec/lib/gitlab/email/reply_parser_spec.rb +++ b/spec/lib/gitlab/email/reply_parser_spec.rb @@ -3,7 +3,7 @@ require "spec_helper" # Inspired in great part by Discourse's Email::Receiver -describe Gitlab::Email::ReplyParser do +RSpec.describe Gitlab::Email::ReplyParser do describe '#execute' do def test_parse_body(mail_string, params = {}) described_class.new(Mail::Message.new(mail_string), params).execute diff --git a/spec/lib/gitlab/email/service_desk_receiver_spec.rb b/spec/lib/gitlab/email/service_desk_receiver_spec.rb new file mode 100644 index 00000000000..6ba58ad5e93 --- /dev/null +++ b/spec/lib/gitlab/email/service_desk_receiver_spec.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Email::ServiceDeskReceiver do + let(:email) { fixture_file('emails/service_desk_custom_address.eml') } + let(:receiver) { described_class.new(email) } + + context 'when the email contains a valid email address' do + before do + stub_service_desk_email_setting(enabled: true, address: 'support+%{key}@example.com') + end + + it 'finds the service desk key' do + handler = double(execute: true, metrics_event: true, metrics_params: true) + expected_params = [ + an_instance_of(Mail::Message), nil, + { service_desk_key: 'project_slug-project_key' } + ] + + expect(Gitlab::Email::Handler::ServiceDeskHandler) + .to receive(:new).with(*expected_params).and_return(handler) + + receiver.execute + end + end + + context 'when the email does not contain a valid email address' do + before do + stub_service_desk_email_setting(enabled: true, address: 'other_support+%{key}@example.com') + end + + it 'raises an error' do + expect { receiver.execute }.to raise_error(Gitlab::Email::UnknownIncomingEmail) + end + end +end diff --git a/spec/lib/gitlab/email/smime/certificate_spec.rb b/spec/lib/gitlab/email/smime/certificate_spec.rb index 07b8c1e4de1..e4a085d971b 100644 --- a/spec/lib/gitlab/email/smime/certificate_spec.rb +++ b/spec/lib/gitlab/email/smime/certificate_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Smime::Certificate do +RSpec.describe Gitlab::Email::Smime::Certificate do include SmimeHelper # cert generation is an expensive operation and they are used read-only, diff --git a/spec/lib/gitlab/email/smime/signer_spec.rb b/spec/lib/gitlab/email/smime/signer_spec.rb index d891b86da08..217c0d62950 100644 --- a/spec/lib/gitlab/email/smime/signer_spec.rb +++ b/spec/lib/gitlab/email/smime/signer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Email::Smime::Signer do +RSpec.describe Gitlab::Email::Smime::Signer do include SmimeHelper let_it_be(:root_ca) { generate_root } diff --git a/spec/lib/gitlab/emoji_spec.rb b/spec/lib/gitlab/emoji_spec.rb new file mode 100644 index 00000000000..ada37f25d1e --- /dev/null +++ b/spec/lib/gitlab/emoji_spec.rb @@ -0,0 +1,125 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Emoji do + let_it_be(:emojis) { Gemojione.index.instance_variable_get(:@emoji_by_name) } + let_it_be(:emojis_by_moji) { Gemojione.index.instance_variable_get(:@emoji_by_moji) } + let_it_be(:emoji_unicode_versions_by_name) { Gitlab::Json.parse(File.read(Rails.root.join('fixtures', 'emojis', 'emoji-unicode-version-map.json'))) } + let_it_be(:emojis_aliases) { Gitlab::Json.parse(File.read(Rails.root.join('fixtures', 'emojis', 'aliases.json'))) } + + describe '.emojis' do + it 'returns emojis' do + current_emojis = described_class.emojis + + expect(current_emojis).to eq(emojis) + end + end + + describe '.emojis_by_moji' do + it 'return emojis by moji' do + current_emojis_by_moji = described_class.emojis_by_moji + + expect(current_emojis_by_moji).to eq(emojis_by_moji) + end + end + + describe '.emojis_unicodes' do + it 'returns emoji unicodes' do + emoji_keys = described_class.emojis_unicodes + + expect(emoji_keys).to eq(emojis_by_moji.keys) + end + end + + describe '.emojis_names' do + it 'returns emoji names' do + emoji_names = described_class.emojis_names + + expect(emoji_names).to eq(emojis.keys) + end + end + + describe '.emojis_aliases' do + it 'returns emoji aliases' do + emoji_aliases = described_class.emojis_aliases + + expect(emoji_aliases).to eq(emojis_aliases) + end + end + + describe '.emoji_filename' do + it 'returns emoji filename' do + # "100" => {"unicode"=>"1F4AF"...} + emoji_filename = described_class.emoji_filename('100') + + expect(emoji_filename).to eq(emojis['100']['unicode']) + end + end + + describe '.emoji_unicode_filename' do + it 'returns emoji unicode filename' do + emoji_unicode_filename = described_class.emoji_unicode_filename('💯') + + expect(emoji_unicode_filename).to eq(emojis_by_moji['💯']['unicode']) + end + end + + describe '.emoji_unicode_version' do + it 'returns emoji unicode version by name' do + emoji_unicode_version = described_class.emoji_unicode_version('100') + + expect(emoji_unicode_version).to eq(emoji_unicode_versions_by_name['100']) + end + end + + describe '.normalize_emoji_name' do + it 'returns same name if not found in aliases' do + emoji_name = described_class.normalize_emoji_name('random') + + expect(emoji_name).to eq('random') + end + + it 'returns name if name found in aliases' do + emoji_name = described_class.normalize_emoji_name('small_airplane') + + expect(emoji_name).to eq(emojis_aliases['small_airplane']) + end + end + + describe '.emoji_image_tag' do + it 'returns emoji image tag' do + emoji_image = described_class.emoji_image_tag('emoji_one', 'src_url') + + expect(emoji_image).to eq( "<img class='emoji' title=':emoji_one:' alt=':emoji_one:' src='src_url' height='20' width='20' align='absmiddle' />") + end + end + + describe '.emoji_exists?' do + it 'returns true if the name exists' do + emoji_exists = described_class.emoji_exists?('100') + + expect(emoji_exists).to be_truthy + end + + it 'returns false if the name does not exist' do + emoji_exists = described_class.emoji_exists?('random') + + expect(emoji_exists).to be_falsey + end + end + + describe '.gl_emoji_tag' do + it 'returns gl emoji tag if emoji is found' do + gl_tag = described_class.gl_emoji_tag('small_airplane') + + expect(gl_tag).to eq('<gl-emoji title="small airplane" data-name="airplane_small" data-unicode-version="7.0">🛩</gl-emoji>') + end + + it 'returns nil if emoji name is not found' do + gl_tag = described_class.gl_emoji_tag('random') + + expect(gl_tag).to be_nil + end + end +end diff --git a/spec/lib/gitlab/encoding_helper_spec.rb b/spec/lib/gitlab/encoding_helper_spec.rb index e6dfd8728aa..5394c04c6ba 100644 --- a/spec/lib/gitlab/encoding_helper_spec.rb +++ b/spec/lib/gitlab/encoding_helper_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::EncodingHelper do +RSpec.describe Gitlab::EncodingHelper do let(:ext_class) { Class.new { extend Gitlab::EncodingHelper } } let(:binary_string) { File.read(Rails.root + "spec/fixtures/dk.png") } diff --git a/spec/lib/gitlab/error_tracking/stack_trace_highlight_decorator_spec.rb b/spec/lib/gitlab/error_tracking/stack_trace_highlight_decorator_spec.rb index d553fb4848b..5c496d653b2 100644 --- a/spec/lib/gitlab/error_tracking/stack_trace_highlight_decorator_spec.rb +++ b/spec/lib/gitlab/error_tracking/stack_trace_highlight_decorator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ErrorTracking::StackTraceHighlightDecorator do +RSpec.describe Gitlab::ErrorTracking::StackTraceHighlightDecorator do let(:error_event) { build(:error_tracking_error_event) } describe '.decorate' do diff --git a/spec/lib/gitlab/error_tracking_spec.rb b/spec/lib/gitlab/error_tracking_spec.rb index c40369f5965..2cc9ff36c99 100644 --- a/spec/lib/gitlab/error_tracking_spec.rb +++ b/spec/lib/gitlab/error_tracking_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' require 'raven/transports/dummy' -describe Gitlab::ErrorTracking do +RSpec.describe Gitlab::ErrorTracking do let(:exception) { RuntimeError.new('boom') } let(:issue_url) { 'http://gitlab.com/gitlab-org/gitlab-foss/issues/1' } @@ -18,6 +18,8 @@ describe Gitlab::ErrorTracking do ] end + let(:sentry_event) { Gitlab::Json.parse(Raven.client.transport.events.last[1]) } + before do stub_sentry_settings @@ -29,6 +31,86 @@ describe Gitlab::ErrorTracking do end end + describe '.configure' do + context 'default tags from GITLAB_SENTRY_EXTRA_TAGS' do + context 'when the value is a JSON hash' do + it 'includes those tags in all events' do + stub_env('GITLAB_SENTRY_EXTRA_TAGS', { foo: 'bar', baz: 'quux' }.to_json) + + described_class.configure do |config| + config.encoding = 'json' + end + + described_class.track_exception(StandardError.new) + + expect(sentry_event['tags'].except('correlation_id', 'locale', 'program')) + .to eq('foo' => 'bar', 'baz' => 'quux') + end + end + + context 'when the value is not set' do + before do + stub_env('GITLAB_SENTRY_EXTRA_TAGS', nil) + end + + it 'does not log an error' do + expect(Gitlab::AppLogger).not_to receive(:debug) + + described_class.configure do |config| + config.encoding = 'json' + end + end + + it 'does not send any extra tags' do + described_class.configure do |config| + config.encoding = 'json' + end + + described_class.track_exception(StandardError.new) + + expect(sentry_event['tags'].keys).to contain_exactly('correlation_id', 'locale', 'program') + end + end + + context 'when the value is not a JSON hash' do + using RSpec::Parameterized::TableSyntax + + where(:env_var, :error) do + { foo: 'bar', baz: 'quux' }.inspect | 'JSON::ParserError' + [].to_json | 'NoMethodError' + [%w[foo bar]].to_json | 'NoMethodError' + %w[foo bar].to_json | 'NoMethodError' + '"string"' | 'NoMethodError' + end + + with_them do + before do + stub_env('GITLAB_SENTRY_EXTRA_TAGS', env_var) + end + + it 'does not include any extra tags' do + described_class.configure do |config| + config.encoding = 'json' + end + + described_class.track_exception(StandardError.new) + + expect(sentry_event['tags'].except('correlation_id', 'locale', 'program')) + .to be_empty + end + + it 'logs the error class' do + expect(Gitlab::AppLogger).to receive(:debug).with(a_string_matching(error)) + + described_class.configure do |config| + config.encoding = 'json' + end + end + end + end + end + end + describe '.with_context' do it 'adds the expected tags' do described_class.with_context {} @@ -202,8 +284,6 @@ describe Gitlab::ErrorTracking do described_class.track_exception(exception, extra) - sentry_event = Gitlab::Json.parse(Raven.client.transport.events.last[1]) - expect(sentry_event.dig('extra', 'sidekiq', 'args')).to eq(['[FILTERED]', 1, 2]) end end diff --git a/spec/lib/gitlab/etag_caching/middleware_spec.rb b/spec/lib/gitlab/etag_caching/middleware_spec.rb index 5e9df555241..361b2329e15 100644 --- a/spec/lib/gitlab/etag_caching/middleware_spec.rb +++ b/spec/lib/gitlab/etag_caching/middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::EtagCaching::Middleware do +RSpec.describe Gitlab::EtagCaching::Middleware do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } let(:app_status_code) { 200 } diff --git a/spec/lib/gitlab/etag_caching/router_spec.rb b/spec/lib/gitlab/etag_caching/router_spec.rb index d9eeb5b9a2b..3e939e588ad 100644 --- a/spec/lib/gitlab/etag_caching/router_spec.rb +++ b/spec/lib/gitlab/etag_caching/router_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::EtagCaching::Router do +RSpec.describe Gitlab::EtagCaching::Router do it 'matches issue notes endpoint' do result = described_class.match( '/my-group/and-subgroup/here-comes-the-project/noteable/issue/1/notes' diff --git a/spec/lib/gitlab/exclusive_lease_helpers/sleeping_lock_spec.rb b/spec/lib/gitlab/exclusive_lease_helpers/sleeping_lock_spec.rb index 8917eeec56f..f74fbf1206f 100644 --- a/spec/lib/gitlab/exclusive_lease_helpers/sleeping_lock_spec.rb +++ b/spec/lib/gitlab/exclusive_lease_helpers/sleeping_lock_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExclusiveLeaseHelpers::SleepingLock, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::ExclusiveLeaseHelpers::SleepingLock, :clean_gitlab_redis_shared_state do include ::ExclusiveLeaseHelpers let(:timeout) { 1.second } diff --git a/spec/lib/gitlab/exclusive_lease_helpers_spec.rb b/spec/lib/gitlab/exclusive_lease_helpers_spec.rb index 9914518cda5..01e2fe8ce17 100644 --- a/spec/lib/gitlab/exclusive_lease_helpers_spec.rb +++ b/spec/lib/gitlab/exclusive_lease_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExclusiveLeaseHelpers, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::ExclusiveLeaseHelpers, :clean_gitlab_redis_shared_state do include ::ExclusiveLeaseHelpers let(:class_instance) { (Class.new { include ::Gitlab::ExclusiveLeaseHelpers }).new } diff --git a/spec/lib/gitlab/exclusive_lease_spec.rb b/spec/lib/gitlab/exclusive_lease_spec.rb index 2c0bb23a0b6..e730ddd6577 100644 --- a/spec/lib/gitlab/exclusive_lease_spec.rb +++ b/spec/lib/gitlab/exclusive_lease_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExclusiveLease, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::ExclusiveLease, :clean_gitlab_redis_shared_state do let(:unique_key) { SecureRandom.hex(10) } describe '#try_obtain' do diff --git a/spec/lib/gitlab/experimentation_spec.rb b/spec/lib/gitlab/experimentation_spec.rb index f6e6c031624..a6408aeae8b 100644 --- a/spec/lib/gitlab/experimentation_spec.rb +++ b/spec/lib/gitlab/experimentation_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Experimentation do +RSpec.describe Gitlab::Experimentation do before do stub_const('Gitlab::Experimentation::EXPERIMENTS', { test_experiment: { diff --git a/spec/lib/gitlab/external_authorization/access_spec.rb b/spec/lib/gitlab/external_authorization/access_spec.rb index 8a08b2a6275..4bb81230ac0 100644 --- a/spec/lib/gitlab/external_authorization/access_spec.rb +++ b/spec/lib/gitlab/external_authorization/access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExternalAuthorization::Access, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::ExternalAuthorization::Access, :clean_gitlab_redis_cache do subject(:access) { described_class.new(build(:user), 'dummy_label') } describe '#loaded?' do diff --git a/spec/lib/gitlab/external_authorization/cache_spec.rb b/spec/lib/gitlab/external_authorization/cache_spec.rb index 1f217249f97..9037c04cf2b 100644 --- a/spec/lib/gitlab/external_authorization/cache_spec.rb +++ b/spec/lib/gitlab/external_authorization/cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExternalAuthorization::Cache, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::ExternalAuthorization::Cache, :clean_gitlab_redis_cache do let(:user) { build_stubbed(:user) } let(:cache_key) { "external_authorization:user-#{user.id}:label-dummy_label" } diff --git a/spec/lib/gitlab/external_authorization/client_spec.rb b/spec/lib/gitlab/external_authorization/client_spec.rb index e28a155a47f..473b57441fa 100644 --- a/spec/lib/gitlab/external_authorization/client_spec.rb +++ b/spec/lib/gitlab/external_authorization/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExternalAuthorization::Client do +RSpec.describe Gitlab::ExternalAuthorization::Client do let(:user) { build(:user, email: 'dummy_user@example.com') } let(:dummy_url) { 'https://dummy.net/' } diff --git a/spec/lib/gitlab/external_authorization/logger_spec.rb b/spec/lib/gitlab/external_authorization/logger_spec.rb index 380e765309c..167ce500911 100644 --- a/spec/lib/gitlab/external_authorization/logger_spec.rb +++ b/spec/lib/gitlab/external_authorization/logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExternalAuthorization::Logger do +RSpec.describe Gitlab::ExternalAuthorization::Logger do let(:request_time) { Time.parse('2018-03-26 20:22:15') } def fake_access(has_access, user, load_type = :request) diff --git a/spec/lib/gitlab/external_authorization/response_spec.rb b/spec/lib/gitlab/external_authorization/response_spec.rb index 5ce3325ef77..11f83feb76f 100644 --- a/spec/lib/gitlab/external_authorization/response_spec.rb +++ b/spec/lib/gitlab/external_authorization/response_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExternalAuthorization::Response do +RSpec.describe Gitlab::ExternalAuthorization::Response do let(:excon_response) { double } subject(:response) { described_class.new(excon_response) } diff --git a/spec/lib/gitlab/external_authorization_spec.rb b/spec/lib/gitlab/external_authorization_spec.rb index 97055e7b3f9..76025d70e9a 100644 --- a/spec/lib/gitlab/external_authorization_spec.rb +++ b/spec/lib/gitlab/external_authorization_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ExternalAuthorization, :request_store do +RSpec.describe Gitlab::ExternalAuthorization, :request_store do include ExternalAuthorizationServiceHelpers let(:user) { build(:user) } diff --git a/spec/lib/gitlab/fake_application_settings_spec.rb b/spec/lib/gitlab/fake_application_settings_spec.rb index 6a872185713..ec32afcfb7b 100644 --- a/spec/lib/gitlab/fake_application_settings_spec.rb +++ b/spec/lib/gitlab/fake_application_settings_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::FakeApplicationSettings do +RSpec.describe Gitlab::FakeApplicationSettings do let(:defaults) do described_class.defaults.merge( foobar: 'asdf', diff --git a/spec/lib/gitlab/file_detector_spec.rb b/spec/lib/gitlab/file_detector_spec.rb index 5bf70ef898a..8c0c56ea2c3 100644 --- a/spec/lib/gitlab/file_detector_spec.rb +++ b/spec/lib/gitlab/file_detector_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::FileDetector do +RSpec.describe Gitlab::FileDetector do describe '.types_in_paths' do it 'returns the file types for the given paths' do expect(described_class.types_in_paths(%w(README.md CHANGELOG VERSION VERSION))) diff --git a/spec/lib/gitlab/file_finder_spec.rb b/spec/lib/gitlab/file_finder_spec.rb index 90aa759671a..36fb4c48fb2 100644 --- a/spec/lib/gitlab/file_finder_spec.rb +++ b/spec/lib/gitlab/file_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::FileFinder do +RSpec.describe Gitlab::FileFinder do describe '#find' do let(:project) { create(:project, :public, :repository) } diff --git a/spec/lib/gitlab/file_hook_spec.rb b/spec/lib/gitlab/file_hook_spec.rb index fda3583289b..7f40d9ae772 100644 --- a/spec/lib/gitlab/file_hook_spec.rb +++ b/spec/lib/gitlab/file_hook_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::FileHook do +RSpec.describe Gitlab::FileHook do let(:file_hook) { Rails.root.join('file_hooks', 'test.rb') } let(:tmp_file) { Tempfile.new('file_hook-dump') } diff --git a/spec/lib/gitlab/file_markdown_link_builder_spec.rb b/spec/lib/gitlab/file_markdown_link_builder_spec.rb index de0ac9733e6..ea21bda12d3 100644 --- a/spec/lib/gitlab/file_markdown_link_builder_spec.rb +++ b/spec/lib/gitlab/file_markdown_link_builder_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::FileMarkdownLinkBuilder do +RSpec.describe Gitlab::FileMarkdownLinkBuilder do let(:custom_class) do Class.new do include Gitlab::FileMarkdownLinkBuilder diff --git a/spec/lib/gitlab/file_type_detection_spec.rb b/spec/lib/gitlab/file_type_detection_spec.rb index 2f1fc57c559..ba5e7cfabf2 100644 --- a/spec/lib/gitlab/file_type_detection_spec.rb +++ b/spec/lib/gitlab/file_type_detection_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::FileTypeDetection do +RSpec.describe Gitlab::FileTypeDetection do describe '.extension_match?' do let(:extensions) { %w[foo bar] } diff --git a/spec/lib/gitlab/fogbugz_import/client_spec.rb b/spec/lib/gitlab/fogbugz_import/client_spec.rb index ca6f374476c..560cb98ccfd 100644 --- a/spec/lib/gitlab/fogbugz_import/client_spec.rb +++ b/spec/lib/gitlab/fogbugz_import/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::FogbugzImport::Client do +RSpec.describe Gitlab::FogbugzImport::Client do let(:client) { described_class.new(uri: '', token: '') } let(:one_user) { { 'people' => { 'person' => { "ixPerson" => "2", "sFullName" => "James" } } } } let(:two_users) { { 'people' => { 'person' => [one_user, { "ixPerson" => "3" }] } } } diff --git a/spec/lib/gitlab/fogbugz_import/importer_spec.rb b/spec/lib/gitlab/fogbugz_import/importer_spec.rb index 9e67047eeda..d2be3e3f6b1 100644 --- a/spec/lib/gitlab/fogbugz_import/importer_spec.rb +++ b/spec/lib/gitlab/fogbugz_import/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::FogbugzImport::Importer do +RSpec.describe Gitlab::FogbugzImport::Importer do let(:project) { create(:project_empty_repo) } let(:importer) { described_class.new(project) } let(:repo) do diff --git a/spec/lib/gitlab/fogbugz_import/project_creator_spec.rb b/spec/lib/gitlab/fogbugz_import/project_creator_spec.rb index 503fe897e29..6b8bb2229a9 100644 --- a/spec/lib/gitlab/fogbugz_import/project_creator_spec.rb +++ b/spec/lib/gitlab/fogbugz_import/project_creator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::FogbugzImport::ProjectCreator do +RSpec.describe Gitlab::FogbugzImport::ProjectCreator do let(:user) { create(:user) } let(:repo) do diff --git a/spec/lib/gitlab/gfm/reference_rewriter_spec.rb b/spec/lib/gitlab/gfm/reference_rewriter_spec.rb index 335135696ef..1c9004262c5 100644 --- a/spec/lib/gitlab/gfm/reference_rewriter_spec.rb +++ b/spec/lib/gitlab/gfm/reference_rewriter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Gfm::ReferenceRewriter do +RSpec.describe Gitlab::Gfm::ReferenceRewriter do let_it_be(:group) { create(:group) } let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/gfm/uploads_rewriter_spec.rb b/spec/lib/gitlab/gfm/uploads_rewriter_spec.rb index 7279399d1b8..5b78acc3b1d 100644 --- a/spec/lib/gitlab/gfm/uploads_rewriter_spec.rb +++ b/spec/lib/gitlab/gfm/uploads_rewriter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Gfm::UploadsRewriter do +RSpec.describe Gitlab::Gfm::UploadsRewriter do let(:user) { create(:user) } let(:old_project) { create(:project) } let(:new_project) { create(:project) } diff --git a/spec/lib/gitlab/git/attributes_at_ref_parser_spec.rb b/spec/lib/gitlab/git/attributes_at_ref_parser_spec.rb index 6c4f650fa83..96cd70b4ff1 100644 --- a/spec/lib/gitlab/git/attributes_at_ref_parser_spec.rb +++ b/spec/lib/gitlab/git/attributes_at_ref_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::AttributesAtRefParser, :seed_helper do +RSpec.describe Gitlab::Git::AttributesAtRefParser, :seed_helper do let(:project) { create(:project, :repository) } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/git/attributes_parser_spec.rb b/spec/lib/gitlab/git/attributes_parser_spec.rb index 45db4acd3ac..4bc39921e85 100644 --- a/spec/lib/gitlab/git/attributes_parser_spec.rb +++ b/spec/lib/gitlab/git/attributes_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::AttributesParser, :seed_helper do +RSpec.describe Gitlab::Git::AttributesParser, :seed_helper do let(:attributes_path) { File.join(SEED_STORAGE_PATH, 'with-git-attributes.git', 'info', 'attributes') } let(:data) { File.read(attributes_path) } diff --git a/spec/lib/gitlab/git/blame_spec.rb b/spec/lib/gitlab/git/blame_spec.rb index 9b2d6fa3bcb..67d7b37dd45 100644 --- a/spec/lib/gitlab/git/blame_spec.rb +++ b/spec/lib/gitlab/git/blame_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Blame, :seed_helper do +RSpec.describe Gitlab::Git::Blame, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } let(:blame) do Gitlab::Git::Blame.new(repository, SeedRepo::Commit::ID, "CONTRIBUTING.md") diff --git a/spec/lib/gitlab/git/blob_spec.rb b/spec/lib/gitlab/git/blob_spec.rb index 46d9b78c14b..fb4510a78de 100644 --- a/spec/lib/gitlab/git/blob_spec.rb +++ b/spec/lib/gitlab/git/blob_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Blob, :seed_helper do +RSpec.describe Gitlab::Git::Blob, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } let(:rugged) do Rugged::Repository.new(File.join(TestEnv.repos_path, TEST_REPO_PATH)) diff --git a/spec/lib/gitlab/git/branch_spec.rb b/spec/lib/gitlab/git/branch_spec.rb index cb3f4df2dbd..bac1b4c57f9 100644 --- a/spec/lib/gitlab/git/branch_spec.rb +++ b/spec/lib/gitlab/git/branch_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Branch, :seed_helper do +RSpec.describe Gitlab::Git::Branch, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } let(:rugged) do Rugged::Repository.new(File.join(TestEnv.repos_path, repository.relative_path)) diff --git a/spec/lib/gitlab/git/bundle_file_spec.rb b/spec/lib/gitlab/git/bundle_file_spec.rb index e88e163a03f..701febadc1b 100644 --- a/spec/lib/gitlab/git/bundle_file_spec.rb +++ b/spec/lib/gitlab/git/bundle_file_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::BundleFile do +RSpec.describe Gitlab::Git::BundleFile do describe '.check!' do let(:valid_bundle) { Tempfile.new } let(:valid_bundle_path) { valid_bundle.path } diff --git a/spec/lib/gitlab/git/changes_spec.rb b/spec/lib/gitlab/git/changes_spec.rb index 7f56d30cb48..310be7a3731 100644 --- a/spec/lib/gitlab/git/changes_spec.rb +++ b/spec/lib/gitlab/git/changes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::Changes do +RSpec.describe Gitlab::Git::Changes do let(:changes) { described_class.new } describe '#includes_branches?' do diff --git a/spec/lib/gitlab/git/commit_spec.rb b/spec/lib/gitlab/git/commit_spec.rb index edd367673fb..666b49f27f7 100644 --- a/spec/lib/gitlab/git/commit_spec.rb +++ b/spec/lib/gitlab/git/commit_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Commit, :seed_helper do +RSpec.describe Gitlab::Git::Commit, :seed_helper do include GitHelpers let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } @@ -227,6 +227,34 @@ describe Gitlab::Git::Commit, :seed_helper do end end + context 'pathspec' do + let(:pathspec) { 'files/ruby/*' } + + context 'with default literal_pathspec value' do + it 'finds the seed commit' do + commit = described_class.last_for_path(repository, 'master', pathspec) + + expect(commit.id).to eq(SeedRepo::Commit::ID) + end + end + + context 'with literal_pathspec set to false' do + it 'finds the seed commit' do + commit = described_class.last_for_path(repository, 'master', pathspec, literal_pathspec: false) + + expect(commit.id).to eq(SeedRepo::Commit::ID) + end + end + + context 'with literal_pathspec set to true' do + it 'does not find the seed commit' do + commit = described_class.last_for_path(repository, 'master', pathspec, literal_pathspec: true) + + expect(commit).to be_nil + end + end + end + context 'ref + path' do subject { described_class.last_for_path(repository, SeedRepo::Commit::ID, 'encoding') } @@ -560,7 +588,7 @@ describe Gitlab::Git::Commit, :seed_helper do end skip 'move this test to gitaly-ruby' do - describe '#init_from_rugged' do + RSpec.describe '#init_from_rugged' do let(:gitlab_commit) { described_class.new(repository, rugged_commit) } subject { gitlab_commit } diff --git a/spec/lib/gitlab/git/compare_spec.rb b/spec/lib/gitlab/git/compare_spec.rb index 6136df57acb..51043355ede 100644 --- a/spec/lib/gitlab/git/compare_spec.rb +++ b/spec/lib/gitlab/git/compare_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Compare, :seed_helper do +RSpec.describe Gitlab::Git::Compare, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } let(:compare) { Gitlab::Git::Compare.new(repository, SeedRepo::BigCommit::ID, SeedRepo::Commit::ID, straight: false) } let(:compare_straight) { Gitlab::Git::Compare.new(repository, SeedRepo::BigCommit::ID, SeedRepo::Commit::ID, straight: true) } diff --git a/spec/lib/gitlab/git/conflict/file_spec.rb b/spec/lib/gitlab/git/conflict/file_spec.rb index 0ee9ff93e87..454a48a1d3a 100644 --- a/spec/lib/gitlab/git/conflict/file_spec.rb +++ b/spec/lib/gitlab/git/conflict/file_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::Conflict::File do +RSpec.describe Gitlab::Git::Conflict::File do let(:conflict) { { theirs: { path: 'foo', mode: 33188 }, ours: { path: 'foo', mode: 33188 } } } let(:invalid_content) { described_class.new(nil, nil, conflict, (+"a\xC4\xFC").force_encoding(Encoding::ASCII_8BIT)) } let(:valid_content) { described_class.new(nil, nil, conflict, (+"Espa\xC3\xB1a").force_encoding(Encoding::ASCII_8BIT)) } diff --git a/spec/lib/gitlab/git/conflict/parser_spec.rb b/spec/lib/gitlab/git/conflict/parser_spec.rb index 92ea44394b1..67bd48256ce 100644 --- a/spec/lib/gitlab/git/conflict/parser_spec.rb +++ b/spec/lib/gitlab/git/conflict/parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::Conflict::Parser do +RSpec.describe Gitlab::Git::Conflict::Parser do describe '.parse' do def parse_text(text) described_class.parse(text, our_path: 'README.md', their_path: 'README.md') diff --git a/spec/lib/gitlab/git/cross_repo_comparer_spec.rb b/spec/lib/gitlab/git/cross_repo_comparer_spec.rb index 8b37b6d1667..1c49486b7b1 100644 --- a/spec/lib/gitlab/git/cross_repo_comparer_spec.rb +++ b/spec/lib/gitlab/git/cross_repo_comparer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::CrossRepoComparer do +RSpec.describe Gitlab::Git::CrossRepoComparer do let(:source_project) { create(:project, :repository) } let(:target_project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/git/diff_collection_spec.rb b/spec/lib/gitlab/git/diff_collection_spec.rb index 6aa4f884d20..6da07ce84a1 100644 --- a/spec/lib/gitlab/git/diff_collection_spec.rb +++ b/spec/lib/gitlab/git/diff_collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::DiffCollection, :seed_helper do +RSpec.describe Gitlab::Git::DiffCollection, :seed_helper do before do stub_const('MutatingConstantIterator', Class.new) diff --git a/spec/lib/gitlab/git/diff_spec.rb b/spec/lib/gitlab/git/diff_spec.rb index ff54d7fbcd3..91688c31f5e 100644 --- a/spec/lib/gitlab/git/diff_spec.rb +++ b/spec/lib/gitlab/git/diff_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Diff, :seed_helper do +RSpec.describe Gitlab::Git::Diff, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } let(:gitaly_diff) do Gitlab::GitalyClient::Diff.new( diff --git a/spec/lib/gitlab/git/diff_stats_collection_spec.rb b/spec/lib/gitlab/git/diff_stats_collection_spec.rb index 82d15a49062..f2fe03829be 100644 --- a/spec/lib/gitlab/git/diff_stats_collection_spec.rb +++ b/spec/lib/gitlab/git/diff_stats_collection_spec.rb @@ -2,13 +2,13 @@ require "spec_helper" -describe Gitlab::Git::DiffStatsCollection do +RSpec.describe Gitlab::Git::DiffStatsCollection do let(:stats_a) do - double(Gitaly::DiffStats, additions: 10, deletions: 15, path: 'foo') + Gitaly::DiffStats.new(additions: 10, deletions: 15, path: 'foo') end let(:stats_b) do - double(Gitaly::DiffStats, additions: 5, deletions: 1, path: 'bar') + Gitaly::DiffStats.new(additions: 5, deletions: 1, path: 'bar') end let(:diff_stats) { [stats_a, stats_b] } diff --git a/spec/lib/gitlab/git/gitmodules_parser_spec.rb b/spec/lib/gitlab/git/gitmodules_parser_spec.rb index 58d1d2c71da..0e386c7f3d1 100644 --- a/spec/lib/gitlab/git/gitmodules_parser_spec.rb +++ b/spec/lib/gitlab/git/gitmodules_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::GitmodulesParser do +RSpec.describe Gitlab::Git::GitmodulesParser do it 'parses a .gitmodules file correctly' do data = <<~GITMODULES [submodule "vendor/libgit2"] diff --git a/spec/lib/gitlab/git/hook_env_spec.rb b/spec/lib/gitlab/git/hook_env_spec.rb index 22b016cee3e..c8f9218916e 100644 --- a/spec/lib/gitlab/git/hook_env_spec.rb +++ b/spec/lib/gitlab/git/hook_env_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::HookEnv do +RSpec.describe Gitlab::Git::HookEnv do let(:gl_repository) { 'project-123' } describe ".set" do diff --git a/spec/lib/gitlab/git/keep_around_spec.rb b/spec/lib/gitlab/git/keep_around_spec.rb index 04ccf86cd28..44c3caf3f8d 100644 --- a/spec/lib/gitlab/git/keep_around_spec.rb +++ b/spec/lib/gitlab/git/keep_around_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::KeepAround do +RSpec.describe Gitlab::Git::KeepAround do include RepoHelpers let(:repository) { create(:project, :repository).repository } diff --git a/spec/lib/gitlab/git/lfs_changes_spec.rb b/spec/lib/gitlab/git/lfs_changes_spec.rb index adc63401b89..286c5b98771 100644 --- a/spec/lib/gitlab/git/lfs_changes_spec.rb +++ b/spec/lib/gitlab/git/lfs_changes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::LfsChanges do +RSpec.describe Gitlab::Git::LfsChanges do let_it_be(:project) { create(:project, :repository) } let(:newrev) { '54fcc214b94e78d7a41a9a8fe6d87a5e59500e51' } let(:blob_object_id) { '0c304a93cb8430108629bbbcaa27db3343299bc0' } diff --git a/spec/lib/gitlab/git/lfs_pointer_file_spec.rb b/spec/lib/gitlab/git/lfs_pointer_file_spec.rb index 8bb26ed4854..f45c7cccca0 100644 --- a/spec/lib/gitlab/git/lfs_pointer_file_spec.rb +++ b/spec/lib/gitlab/git/lfs_pointer_file_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::LfsPointerFile do +RSpec.describe Gitlab::Git::LfsPointerFile do let(:data) { "1234\n" } subject { described_class.new(data) } diff --git a/spec/lib/gitlab/git/merge_base_spec.rb b/spec/lib/gitlab/git/merge_base_spec.rb index d92b13c5023..1410e44a220 100644 --- a/spec/lib/gitlab/git/merge_base_spec.rb +++ b/spec/lib/gitlab/git/merge_base_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::MergeBase do +RSpec.describe Gitlab::Git::MergeBase do let_it_be(:project) { create(:project, :repository) } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/git/object_pool_spec.rb b/spec/lib/gitlab/git/object_pool_spec.rb index ebeb7b7b633..c8fbc674c73 100644 --- a/spec/lib/gitlab/git/object_pool_spec.rb +++ b/spec/lib/gitlab/git/object_pool_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::ObjectPool do +RSpec.describe Gitlab::Git::ObjectPool do include RepoHelpers let(:pool_repository) { create(:pool_repository) } diff --git a/spec/lib/gitlab/git/patches/collection_spec.rb b/spec/lib/gitlab/git/patches/collection_spec.rb index 080be141c59..eb92f4663c8 100644 --- a/spec/lib/gitlab/git/patches/collection_spec.rb +++ b/spec/lib/gitlab/git/patches/collection_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Git::Patches::Collection do +RSpec.describe Gitlab::Git::Patches::Collection do let(:patches_folder) { Rails.root.join('spec/fixtures/patchfiles') } let(:patch_content1) do File.read(File.join(patches_folder, "0001-This-does-not-apply-to-the-feature-branch.patch")) diff --git a/spec/lib/gitlab/git/patches/commit_patches_spec.rb b/spec/lib/gitlab/git/patches/commit_patches_spec.rb index 760112155ce..cd1e03a6de0 100644 --- a/spec/lib/gitlab/git/patches/commit_patches_spec.rb +++ b/spec/lib/gitlab/git/patches/commit_patches_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Git::Patches::CommitPatches do +RSpec.describe Gitlab::Git::Patches::CommitPatches do describe '#commit' do let(:patches) do patches_folder = Rails.root.join('spec/fixtures/patchfiles') diff --git a/spec/lib/gitlab/git/patches/patch_spec.rb b/spec/lib/gitlab/git/patches/patch_spec.rb index 7466e853b65..629f43d3636 100644 --- a/spec/lib/gitlab/git/patches/patch_spec.rb +++ b/spec/lib/gitlab/git/patches/patch_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Git::Patches::Patch do +RSpec.describe Gitlab::Git::Patches::Patch do let(:patches_folder) { Rails.root.join('spec/fixtures/patchfiles') } let(:patch_content) do File.read(File.join(patches_folder, "0001-This-does-not-apply-to-the-feature-branch.patch")) diff --git a/spec/lib/gitlab/git/pre_receive_error_spec.rb b/spec/lib/gitlab/git/pre_receive_error_spec.rb index cb539261671..bf4530c8945 100644 --- a/spec/lib/gitlab/git/pre_receive_error_spec.rb +++ b/spec/lib/gitlab/git/pre_receive_error_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::PreReceiveError do +RSpec.describe Gitlab::Git::PreReceiveError do Gitlab::Git::PreReceiveError::SAFE_MESSAGE_PREFIXES.each do |prefix| context "error messages prefixed with #{prefix}" do it 'accepts only errors lines with the prefix' do diff --git a/spec/lib/gitlab/git/push_spec.rb b/spec/lib/gitlab/git/push_spec.rb index c09e8a085df..0f52f10c0a6 100644 --- a/spec/lib/gitlab/git/push_spec.rb +++ b/spec/lib/gitlab/git/push_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::Push do +RSpec.describe Gitlab::Git::Push do let_it_be(:project) { create(:project, :repository) } let(:oldrev) { project.commit('HEAD~2').id } let(:newrev) { project.commit.id } diff --git a/spec/lib/gitlab/git/raw_diff_change_spec.rb b/spec/lib/gitlab/git/raw_diff_change_spec.rb index 79b2fc21011..f894ae1d98b 100644 --- a/spec/lib/gitlab/git/raw_diff_change_spec.rb +++ b/spec/lib/gitlab/git/raw_diff_change_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::RawDiffChange do +RSpec.describe Gitlab::Git::RawDiffChange do let(:raw_change) { } let(:change) { described_class.new(raw_change) } diff --git a/spec/lib/gitlab/git/remote_mirror_spec.rb b/spec/lib/gitlab/git/remote_mirror_spec.rb index edef91b8bc6..423c4aa9620 100644 --- a/spec/lib/gitlab/git/remote_mirror_spec.rb +++ b/spec/lib/gitlab/git/remote_mirror_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::RemoteMirror do +RSpec.describe Gitlab::Git::RemoteMirror do describe '#update' do let(:project) { create(:project, :repository) } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/git/remote_repository_spec.rb b/spec/lib/gitlab/git/remote_repository_spec.rb index b53eee293f0..84c17234ae4 100644 --- a/spec/lib/gitlab/git/remote_repository_spec.rb +++ b/spec/lib/gitlab/git/remote_repository_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::RemoteRepository, :seed_helper do +RSpec.describe Gitlab::Git::RemoteRepository, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } subject { described_class.new(repository) } diff --git a/spec/lib/gitlab/git/repository_cleaner_spec.rb b/spec/lib/gitlab/git/repository_cleaner_spec.rb index b387d1033d3..9f1bf9e48ee 100644 --- a/spec/lib/gitlab/git/repository_cleaner_spec.rb +++ b/spec/lib/gitlab/git/repository_cleaner_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::RepositoryCleaner do +RSpec.describe Gitlab::Git::RepositoryCleaner do include HttpIOHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/git/repository_spec.rb b/spec/lib/gitlab/git/repository_spec.rb index 183e6e8d044..e7f4573c95f 100644 --- a/spec/lib/gitlab/git/repository_spec.rb +++ b/spec/lib/gitlab/git/repository_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Repository, :seed_helper do +RSpec.describe Gitlab::Git::Repository, :seed_helper do include Gitlab::EncodingHelper include RepoHelpers using RSpec::Parameterized::TableSyntax @@ -2187,34 +2187,47 @@ describe Gitlab::Git::Repository, :seed_helper do 'gitaly_address' => Gitlab.config.repositories.storages.default.gitaly_address, 'path' => TestEnv::SECOND_STORAGE_PATH }) - new_repository.create_repository end after do new_repository.remove end - it 'mirrors the source repository' do - subject + context 'destination does not exist' do + it 'mirrors the source repository' do + subject - expect(refs(new_repository_path)).to eq(refs(repository_path)) + expect(refs(new_repository_path)).to eq(refs(repository_path)) + end end - context 'with keep-around refs' do - let(:sha) { SeedRepo::Commit::ID } - let(:keep_around_ref) { "refs/keep-around/#{sha}" } - let(:tmp_ref) { "refs/tmp/#{SecureRandom.hex}" } - + context 'destination exists' do before do - repository.write_ref(keep_around_ref, sha) - repository.write_ref(tmp_ref, sha) + new_repository.create_repository end - it 'includes the temporary and keep-around refs' do + it 'mirrors the source repository' do subject - expect(refs(new_repository_path)).to include(keep_around_ref) - expect(refs(new_repository_path)).to include(tmp_ref) + expect(refs(new_repository_path)).to eq(refs(repository_path)) + end + + context 'with keep-around refs' do + let(:sha) { SeedRepo::Commit::ID } + let(:keep_around_ref) { "refs/keep-around/#{sha}" } + let(:tmp_ref) { "refs/tmp/#{SecureRandom.hex}" } + + before do + repository.write_ref(keep_around_ref, sha) + repository.write_ref(tmp_ref, sha) + end + + it 'includes the temporary and keep-around refs' do + subject + + expect(refs(new_repository_path)).to include(keep_around_ref) + expect(refs(new_repository_path)).to include(tmp_ref) + end end end end diff --git a/spec/lib/gitlab/git/rugged_impl/use_rugged_spec.rb b/spec/lib/gitlab/git/rugged_impl/use_rugged_spec.rb index 8339006fe9f..4f6a3fb823e 100644 --- a/spec/lib/gitlab/git/rugged_impl/use_rugged_spec.rb +++ b/spec/lib/gitlab/git/rugged_impl/use_rugged_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' require 'json' require 'tempfile' -describe Gitlab::Git::RuggedImpl::UseRugged, :seed_helper do +RSpec.describe Gitlab::Git::RuggedImpl::UseRugged, :seed_helper do let(:project) { create(:project, :repository) } let(:repository) { project.repository } let(:feature_flag_name) { 'feature-flag-name' } diff --git a/spec/lib/gitlab/git/tag_spec.rb b/spec/lib/gitlab/git/tag_spec.rb index 6d3b239c38f..f83ccc6cae0 100644 --- a/spec/lib/gitlab/git/tag_spec.rb +++ b/spec/lib/gitlab/git/tag_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Tag, :seed_helper do +RSpec.describe Gitlab::Git::Tag, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } describe '#tags' do diff --git a/spec/lib/gitlab/git/tree_spec.rb b/spec/lib/gitlab/git/tree_spec.rb index b254dd3f036..5ef964ac3c1 100644 --- a/spec/lib/gitlab/git/tree_spec.rb +++ b/spec/lib/gitlab/git/tree_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Git::Tree, :seed_helper do +RSpec.describe Gitlab::Git::Tree, :seed_helper do let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '', 'group/project') } shared_examples :repo do diff --git a/spec/lib/gitlab/git/user_spec.rb b/spec/lib/gitlab/git/user_spec.rb index 6761413320a..4414195ebf4 100644 --- a/spec/lib/gitlab/git/user_spec.rb +++ b/spec/lib/gitlab/git/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::User do +RSpec.describe Gitlab::Git::User do let(:username) { 'janedoe' } let(:name) { 'Jane Doé' } let(:email) { 'janedoé@example.com' } diff --git a/spec/lib/gitlab/git/util_spec.rb b/spec/lib/gitlab/git/util_spec.rb index 81918f036f9..a0237c821b5 100644 --- a/spec/lib/gitlab/git/util_spec.rb +++ b/spec/lib/gitlab/git/util_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::Util do +RSpec.describe Gitlab::Git::Util do describe '#count_lines' do [ ["", 0], diff --git a/spec/lib/gitlab/git/wiki_spec.rb b/spec/lib/gitlab/git/wiki_spec.rb index 8bae2e8125e..a88097705f6 100644 --- a/spec/lib/gitlab/git/wiki_spec.rb +++ b/spec/lib/gitlab/git/wiki_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::Wiki do +RSpec.describe Gitlab::Git::Wiki do using RSpec::Parameterized::TableSyntax let(:project) { create(:project) } diff --git a/spec/lib/gitlab/git/wraps_gitaly_errors_spec.rb b/spec/lib/gitlab/git/wraps_gitaly_errors_spec.rb index a4489cca443..e448277b307 100644 --- a/spec/lib/gitlab/git/wraps_gitaly_errors_spec.rb +++ b/spec/lib/gitlab/git/wraps_gitaly_errors_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git::WrapsGitalyErrors do +RSpec.describe Gitlab::Git::WrapsGitalyErrors do subject(:wrapper) do klazz = Class.new { include Gitlab::Git::WrapsGitalyErrors } klazz.new diff --git a/spec/lib/gitlab/git_access_design_spec.rb b/spec/lib/gitlab/git_access_design_spec.rb index d816608f7e5..ee25f6c2979 100644 --- a/spec/lib/gitlab/git_access_design_spec.rb +++ b/spec/lib/gitlab/git_access_design_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::GitAccessDesign do +RSpec.describe Gitlab::GitAccessDesign do include DesignManagementTestHelpers let_it_be(:project) { create(:project) } diff --git a/spec/lib/gitlab/git_access_project_spec.rb b/spec/lib/gitlab/git_access_project_spec.rb index f7f7976ccb8..520300363c9 100644 --- a/spec/lib/gitlab/git_access_project_spec.rb +++ b/spec/lib/gitlab/git_access_project_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitAccessProject do +RSpec.describe Gitlab::GitAccessProject do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, :repository) } let(:actor) { user } diff --git a/spec/lib/gitlab/git_access_snippet_spec.rb b/spec/lib/gitlab/git_access_snippet_spec.rb index 48b425a8ec5..3b8b5fd82c6 100644 --- a/spec/lib/gitlab/git_access_snippet_spec.rb +++ b/spec/lib/gitlab/git_access_snippet_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitAccessSnippet do +RSpec.describe Gitlab::GitAccessSnippet do include ProjectHelpers include TermsHelper include_context 'ProjectPolicyTable context' diff --git a/spec/lib/gitlab/git_access_spec.rb b/spec/lib/gitlab/git_access_spec.rb index 7c09fc5cc79..01691f87092 100644 --- a/spec/lib/gitlab/git_access_spec.rb +++ b/spec/lib/gitlab/git_access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitAccess do +RSpec.describe Gitlab::GitAccess do include TermsHelper include GitHelpers diff --git a/spec/lib/gitlab/git_access_wiki_spec.rb b/spec/lib/gitlab/git_access_wiki_spec.rb index e42570804a8..738269e4a14 100644 --- a/spec/lib/gitlab/git_access_wiki_spec.rb +++ b/spec/lib/gitlab/git_access_wiki_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitAccessWiki do +RSpec.describe Gitlab::GitAccessWiki do let(:access) { described_class.new(user, project, 'web', authentication_abilities: authentication_abilities, redirected_path: redirected_path) } let(:project) { create(:project, :wiki_repo) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/git_post_receive_spec.rb b/spec/lib/gitlab/git_post_receive_spec.rb index 0e25a616810..45d536a437f 100644 --- a/spec/lib/gitlab/git_post_receive_spec.rb +++ b/spec/lib/gitlab/git_post_receive_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::GitPostReceive do +RSpec.describe ::Gitlab::GitPostReceive do let_it_be(:project) { create(:project, :repository) } subject { described_class.new(project, "project-#{project.id}", changes.dup, {}) } diff --git a/spec/lib/gitlab/git_ref_validator_spec.rb b/spec/lib/gitlab/git_ref_validator_spec.rb index 28cc13f02de..6938ad51189 100644 --- a/spec/lib/gitlab/git_ref_validator_spec.rb +++ b/spec/lib/gitlab/git_ref_validator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitRefValidator do +RSpec.describe Gitlab::GitRefValidator do using RSpec::Parameterized::TableSyntax describe '.validate' do diff --git a/spec/lib/gitlab/git_spec.rb b/spec/lib/gitlab/git_spec.rb index d6d12b84724..784d25f55c1 100644 --- a/spec/lib/gitlab/git_spec.rb +++ b/spec/lib/gitlab/git_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Git do +RSpec.describe Gitlab::Git do let(:committer_email) { 'user@example.org' } let(:committer_name) { 'John Doe' } diff --git a/spec/lib/gitlab/gitaly_client/blob_service_spec.rb b/spec/lib/gitlab/gitaly_client/blob_service_spec.rb index e609acc8fb0..037734f1b13 100644 --- a/spec/lib/gitlab/gitaly_client/blob_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/blob_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::BlobService do +RSpec.describe Gitlab::GitalyClient::BlobService do let(:project) { create(:project, :repository) } let(:storage_name) { project.repository_storage } let(:relative_path) { project.disk_path + '.git' } diff --git a/spec/lib/gitlab/gitaly_client/blobs_stitcher_spec.rb b/spec/lib/gitlab/gitaly_client/blobs_stitcher_spec.rb index e88b86c71f2..e0c3e8d4b40 100644 --- a/spec/lib/gitlab/gitaly_client/blobs_stitcher_spec.rb +++ b/spec/lib/gitlab/gitaly_client/blobs_stitcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::BlobsStitcher do +RSpec.describe Gitlab::GitalyClient::BlobsStitcher do describe 'enumeration' do it 'combines segregated blob messages together' do messages = [ diff --git a/spec/lib/gitlab/gitaly_client/call_spec.rb b/spec/lib/gitlab/gitaly_client/call_spec.rb new file mode 100644 index 00000000000..5c33ac40460 --- /dev/null +++ b/spec/lib/gitlab/gitaly_client/call_spec.rb @@ -0,0 +1,122 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::GitalyClient::Call do + describe '#call', :request_store do + let(:client) { Gitlab::GitalyClient } + let(:storage) { 'default' } + let(:remote_storage) { nil } + let(:request) { Gitaly::FindLocalBranchesRequest.new } + let(:rpc) { :find_local_branches } + let(:service) { :ref_service } + let(:timeout) { client.long_timeout } + + subject do + described_class.new(storage, service, rpc, request, remote_storage, timeout).call + end + + before do + allow(client).to receive(:execute) { response } + allow(Gitlab::PerformanceBar).to receive(:enabled_for_request?) { true } + end + + def expect_call_details_to_match(duration_higher_than: 0) + expect(client.list_call_details.size).to eq(1) + expect(client.list_call_details.first) + .to match a_hash_including(feature: "#{service}##{rpc}", + duration: a_value > duration_higher_than, + request: an_instance_of(Hash), + rpc: rpc, + backtrace: an_instance_of(Array)) + end + + context 'when the response is not an enumerator' do + let(:response) do + Gitaly::FindLocalBranchesResponse.new + end + + it 'returns the response' do + expect(subject).to eq(response) + end + + it 'stores timings and call details' do + subject + + expect(client.query_time).to be > 0 + expect_call_details_to_match + end + + context 'when err' do + before do + allow(client).to receive(:execute).and_raise(StandardError) + end + + it 'stores timings and call details' do + expect { subject }.to raise_error(StandardError) + + expect(client.query_time).to be > 0 + expect_call_details_to_match + end + end + end + + context 'when the response is an enumerator' do + let(:response) do + Enumerator.new do |yielder| + yielder << 1 + yielder << 2 + end + end + + it 'returns a consumable enumerator' do + instrumented_response = subject + + expect(instrumented_response).to be_a(Enumerator) + expect(instrumented_response.to_a).to eq([1, 2]) + end + + context 'time measurements' do + let(:response) do + Enumerator.new do |yielder| + sleep 0.1 + yielder << 1 + sleep 0.2 + yielder << 2 + end + end + + it 'records full rpc stream consumption' do + subject.to_a + + expect(client.query_time).to be > 0.3 + expect_call_details_to_match(duration_higher_than: 0.3) + end + + it 'records partial rpc stream consumption' do + subject.first + + expect(client.query_time).to be > 0.1 + expect_call_details_to_match(duration_higher_than: 0.1) + end + + context 'when err' do + let(:response) do + Enumerator.new do |yielder| + sleep 0.2 + yielder << 1 + raise StandardError + end + end + + it 'records partial rpc stream consumption' do + expect { subject.to_a }.to raise_error(StandardError) + + expect(client.query_time).to be > 0.2 + expect_call_details_to_match(duration_higher_than: 0.2) + end + end + end + end + end +end diff --git a/spec/lib/gitlab/gitaly_client/cleanup_service_spec.rb b/spec/lib/gitlab/gitaly_client/cleanup_service_spec.rb index 07f53797b2a..3381c69ea0d 100644 --- a/spec/lib/gitlab/gitaly_client/cleanup_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/cleanup_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::CleanupService do +RSpec.describe Gitlab::GitalyClient::CleanupService do let(:project) { create(:project) } let(:storage_name) { project.repository_storage } let(:relative_path) { project.disk_path + '.git' } diff --git a/spec/lib/gitlab/gitaly_client/commit_service_spec.rb b/spec/lib/gitlab/gitaly_client/commit_service_spec.rb index 29a5ef0d2fc..45a25ccfc88 100644 --- a/spec/lib/gitlab/gitaly_client/commit_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/commit_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::CommitService do +RSpec.describe Gitlab::GitalyClient::CommitService do let(:project) { create(:project, :repository) } let(:storage_name) { project.repository_storage } let(:relative_path) { project.disk_path + '.git' } @@ -290,7 +290,8 @@ describe Gitlab::GitalyClient::CommitService do request = Gitaly::FindCommitsRequest.new( repository: repository_message, disable_walk: true, - order: 'NONE' + order: 'NONE', + global_options: Gitaly::GlobalOptions.new(literal_pathspecs: false) ) expect_any_instance_of(Gitaly::CommitService::Stub).to receive(:find_commits) @@ -303,7 +304,8 @@ describe Gitlab::GitalyClient::CommitService do request = Gitaly::FindCommitsRequest.new( repository: repository_message, disable_walk: true, - order: 'TOPO' + order: 'TOPO', + global_options: Gitaly::GlobalOptions.new(literal_pathspecs: false) ) expect_any_instance_of(Gitaly::CommitService::Stub).to receive(:find_commits) @@ -317,7 +319,8 @@ describe Gitlab::GitalyClient::CommitService do repository: repository_message, disable_walk: true, order: 'NONE', - author: "Billy Baggins <bilbo@shire.com>" + author: "Billy Baggins <bilbo@shire.com>", + global_options: Gitaly::GlobalOptions.new(literal_pathspecs: false) ) expect_any_instance_of(Gitaly::CommitService::Stub).to receive(:find_commits) @@ -338,7 +341,8 @@ describe Gitlab::GitalyClient::CommitService do revision: (options[:revision] || '').dup.force_encoding(Encoding::ASCII_8BIT), path: (options[:path] || '').dup.force_encoding(Encoding::ASCII_8BIT), limit: (options[:limit] || 1000).to_i, - offset: (options[:offset] || 0).to_i + offset: (options[:offset] || 0).to_i, + global_options: Gitaly::GlobalOptions.new(literal_pathspecs: true) ) allow_any_instance_of(Gitaly::CommitService::Stub) @@ -381,4 +385,19 @@ describe Gitlab::GitalyClient::CommitService do commits.map { |commit| Gitlab::Git::Commit.new(repository, commit) } end end + + describe '#list_commits_by_ref_name' do + let(:project) { create(:project, :repository, create_branch: 'ü/unicode/multi-byte') } + + it 'lists latest commits grouped by a ref name' do + response = client.list_commits_by_ref_name(%w[master feature v1.0.0 nonexistent ü/unicode/multi-byte]) + + expect(response.keys.count).to eq 4 + expect(response.fetch('master').id).to eq 'b83d6e391c22777fca1ed3012fce84f633d7fed0' + expect(response.fetch('feature').id).to eq '0b4bc9a49b562e85de7cc9e834518ea6828729b9' + expect(response.fetch('v1.0.0').id).to eq '6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9' + expect(response.fetch('ü/unicode/multi-byte')).to be_present + expect(response).not_to have_key 'nonexistent' + end + end end diff --git a/spec/lib/gitlab/gitaly_client/conflict_files_stitcher_spec.rb b/spec/lib/gitlab/gitaly_client/conflict_files_stitcher_spec.rb index db734b1c129..0bb8628af6c 100644 --- a/spec/lib/gitlab/gitaly_client/conflict_files_stitcher_spec.rb +++ b/spec/lib/gitlab/gitaly_client/conflict_files_stitcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::ConflictFilesStitcher do +RSpec.describe Gitlab::GitalyClient::ConflictFilesStitcher do describe 'enumeration' do it 'combines segregated ConflictFile messages together' do target_project = create(:project, :repository) diff --git a/spec/lib/gitlab/gitaly_client/conflicts_service_spec.rb b/spec/lib/gitlab/gitaly_client/conflicts_service_spec.rb index f19bcae2470..b016e8bdf5a 100644 --- a/spec/lib/gitlab/gitaly_client/conflicts_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/conflicts_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::ConflictsService do +RSpec.describe Gitlab::GitalyClient::ConflictsService do let(:project) { create(:project, :repository) } let(:target_project) { create(:project, :repository) } let(:source_repository) { project.repository.raw } diff --git a/spec/lib/gitlab/gitaly_client/diff_spec.rb b/spec/lib/gitlab/gitaly_client/diff_spec.rb index d86497da7f5..230322faecd 100644 --- a/spec/lib/gitlab/gitaly_client/diff_spec.rb +++ b/spec/lib/gitlab/gitaly_client/diff_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::Diff do +RSpec.describe Gitlab::GitalyClient::Diff do let(:diff_fields) do { to_path: ".gitmodules", diff --git a/spec/lib/gitlab/gitaly_client/diff_stitcher_spec.rb b/spec/lib/gitlab/gitaly_client/diff_stitcher_spec.rb index c9d42ad32cf..113c47b4f2c 100644 --- a/spec/lib/gitlab/gitaly_client/diff_stitcher_spec.rb +++ b/spec/lib/gitlab/gitaly_client/diff_stitcher_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::DiffStitcher do +RSpec.describe Gitlab::GitalyClient::DiffStitcher do describe 'enumeration' do it 'combines segregated diff messages together' do diff_1 = OpenStruct.new( diff --git a/spec/lib/gitlab/gitaly_client/health_check_service_spec.rb b/spec/lib/gitlab/gitaly_client/health_check_service_spec.rb index 615bc80fff2..0855544d11e 100644 --- a/spec/lib/gitlab/gitaly_client/health_check_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/health_check_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::HealthCheckService do +RSpec.describe Gitlab::GitalyClient::HealthCheckService do let(:project) { create(:project) } let(:storage_name) { project.repository_storage } diff --git a/spec/lib/gitlab/gitaly_client/object_pool_service_spec.rb b/spec/lib/gitlab/gitaly_client/object_pool_service_spec.rb index 0e0c3d329b5..15eebf62a39 100644 --- a/spec/lib/gitlab/gitaly_client/object_pool_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/object_pool_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::ObjectPoolService do +RSpec.describe Gitlab::GitalyClient::ObjectPoolService do let(:pool_repository) { create(:pool_repository) } let(:project) { create(:project, :repository) } let(:raw_repository) { project.repository.raw } diff --git a/spec/lib/gitlab/gitaly_client/operation_service_spec.rb b/spec/lib/gitlab/gitaly_client/operation_service_spec.rb index 45701b501bb..4e16f760235 100644 --- a/spec/lib/gitlab/gitaly_client/operation_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/operation_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::OperationService do +RSpec.describe Gitlab::GitalyClient::OperationService do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, :repository) } let(:repository) { project.repository.raw } @@ -191,6 +191,20 @@ describe Gitlab::GitalyClient::OperationService do it { expect(subject).to be_nil } end + + context "when the pre-receive hook fails" do + let(:response) do + Gitaly::UserFFBranchResponse.new( + branch_update: nil, + pre_receive_error: "pre-receive hook error message\n" + ) + end + + it "raises the error" do + # the PreReceiveError class strips the GL-HOOK-ERR prefix from this error + expect { subject }.to raise_error(Gitlab::Git::PreReceiveError, "pre-receive hook failed.") + end + end end shared_examples 'cherry pick and revert errors' do diff --git a/spec/lib/gitlab/gitaly_client/praefect_info_service_spec.rb b/spec/lib/gitlab/gitaly_client/praefect_info_service_spec.rb index 9b5c751e0ec..5f90745f4e0 100644 --- a/spec/lib/gitlab/gitaly_client/praefect_info_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/praefect_info_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::PraefectInfoService do +RSpec.describe Gitlab::GitalyClient::PraefectInfoService do let(:project) { create(:project, :repository) } let(:repository) { project.repository } let(:gitaly_repository) { repository.gitaly_repository } diff --git a/spec/lib/gitlab/gitaly_client/ref_service_spec.rb b/spec/lib/gitlab/gitaly_client/ref_service_spec.rb index d4a7f6e6df9..a4c6e30bba8 100644 --- a/spec/lib/gitlab/gitaly_client/ref_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/ref_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::RefService do +RSpec.describe Gitlab::GitalyClient::RefService do let(:project) { create(:project, :repository) } let(:storage_name) { project.repository_storage } let(:relative_path) { project.disk_path + '.git' } @@ -34,7 +34,7 @@ describe Gitlab::GitalyClient::RefService do subject end - it 'concantes and returns the response branches as Gitlab::Git::Branch objects' do + it 'concatenates and returns the response branches as Gitlab::Git::Branch objects' do target_commits = create_list(:gitaly_commit, 4) response_branches = target_commits.each_with_index.map do |gitaly_commit, i| Gitaly::Branch.new(name: "#{remote_name}/#{i}", target_commit: gitaly_commit) @@ -59,6 +59,17 @@ describe Gitlab::GitalyClient::RefService do end end + describe '#merged_branches' do + it 'sends a find_all_branches message' do + expect_any_instance_of(Gitaly::RefService::Stub) + .to receive(:find_all_branches) + .with(gitaly_request_with_params(merged_only: true, merged_branches: ['test']), kind_of(Hash)) + .and_return([]) + + client.merged_branches(%w(test)) + end + end + describe '#branch_names' do it 'sends a find_all_branch_names message' do expect_any_instance_of(Gitaly::RefService::Stub) @@ -135,6 +146,38 @@ describe Gitlab::GitalyClient::RefService do end end + describe '#tags' do + it 'sends a find_all_tags message' do + expect_any_instance_of(Gitaly::RefService::Stub) + .to receive(:find_all_tags) + .and_return([]) + + client.tags + end + end + + describe '#branch_names_contains_sha' do + it 'sends a list_branch_names_containing_commit message' do + expect_any_instance_of(Gitaly::RefService::Stub) + .to receive(:list_branch_names_containing_commit) + .with(gitaly_request_with_params(commit_id: '123', limit: 0), kind_of(Hash)) + .and_return([]) + + client.branch_names_contains_sha('123') + end + end + + describe '#get_tag_messages' do + it 'sends a get_tag_messages message' do + expect_any_instance_of(Gitaly::RefService::Stub) + .to receive(:get_tag_messages) + .with(gitaly_request_with_params(tag_ids: ['some_tag_id']), kind_of(Hash)) + .and_return([]) + + client.get_tag_messages(['some_tag_id']) + end + end + describe '#find_ref_name', :seed_helper do subject { client.find_ref_name(SeedRepo::Commit::ID, 'refs/heads/master') } diff --git a/spec/lib/gitlab/gitaly_client/remote_service_spec.rb b/spec/lib/gitlab/gitaly_client/remote_service_spec.rb index 2bddec739fc..b9ef76e1f41 100644 --- a/spec/lib/gitlab/gitaly_client/remote_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/remote_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::RemoteService do +RSpec.describe Gitlab::GitalyClient::RemoteService do let(:project) { create(:project) } let(:storage_name) { project.repository_storage } let(:relative_path) { project.disk_path + '.git' } @@ -73,8 +73,11 @@ describe Gitlab::GitalyClient::RemoteService do describe '.exists?' do context "when the remote doesn't exist" do let(:url) { 'https://gitlab.com/gitlab-org/ik-besta-niet-of-ik-word-geplaagd.git' } + let(:storage_name) { 'default' } it 'returns false' do + expect(Gitaly::FindRemoteRepositoryRequest).to receive(:new).with(remote: url, storage_name: storage_name).and_call_original + expect(described_class.exists?(url)).to be(false) end end diff --git a/spec/lib/gitlab/gitaly_client/repository_service_spec.rb b/spec/lib/gitlab/gitaly_client/repository_service_spec.rb index 5f4147f6ff6..c7ea0a95596 100644 --- a/spec/lib/gitlab/gitaly_client/repository_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/repository_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::RepositoryService do +RSpec.describe Gitlab::GitalyClient::RepositoryService do using RSpec::Parameterized::TableSyntax let(:project) { create(:project) } diff --git a/spec/lib/gitlab/gitaly_client/storage_settings_spec.rb b/spec/lib/gitlab/gitaly_client/storage_settings_spec.rb index a6b29489df3..0c4c8de52ae 100644 --- a/spec/lib/gitlab/gitaly_client/storage_settings_spec.rb +++ b/spec/lib/gitlab/gitaly_client/storage_settings_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::StorageSettings do +RSpec.describe Gitlab::GitalyClient::StorageSettings do describe "#initialize" do context 'when the storage contains no path' do it 'raises an error' do diff --git a/spec/lib/gitlab/gitaly_client/util_spec.rb b/spec/lib/gitlab/gitaly_client/util_spec.rb index f31b7c349ff..b6589a08f7d 100644 --- a/spec/lib/gitlab/gitaly_client/util_spec.rb +++ b/spec/lib/gitlab/gitaly_client/util_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::Util do +RSpec.describe Gitlab::GitalyClient::Util do describe '.repository' do let(:repository_storage) { 'default' } let(:relative_path) { 'my/repo.git' } diff --git a/spec/lib/gitlab/gitaly_client/wiki_service_spec.rb b/spec/lib/gitlab/gitaly_client/wiki_service_spec.rb index cb04f9a1637..a06f8459963 100644 --- a/spec/lib/gitlab/gitaly_client/wiki_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/wiki_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitalyClient::WikiService do +RSpec.describe Gitlab::GitalyClient::WikiService do let(:project) { create(:project) } let(:storage_name) { project.repository_storage } let(:relative_path) { project.disk_path + '.git' } diff --git a/spec/lib/gitlab/gitaly_client_spec.rb b/spec/lib/gitlab/gitaly_client_spec.rb index c2b989c2fdc..16dd2bbee6d 100644 --- a/spec/lib/gitlab/gitaly_client_spec.rb +++ b/spec/lib/gitlab/gitaly_client_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' # We stub Gitaly in `spec/support/gitaly.rb` for other tests. We don't want # those stubs while testing the GitalyClient itself. -describe Gitlab::GitalyClient do +RSpec.describe Gitlab::GitalyClient do let(:sample_cert) { Rails.root.join('spec/fixtures/clusters/sample_cert.pem').to_s } before do @@ -521,8 +521,6 @@ describe Gitlab::GitalyClient do context 'when the request store is active', :request_store do it 'records call details if a RPC is called' do - expect(described_class).to receive(:measure_timings).and_call_original - gitaly_server.server_version expect(described_class.list_call_details).not_to be_empty diff --git a/spec/lib/gitlab/github_import/bulk_importing_spec.rb b/spec/lib/gitlab/github_import/bulk_importing_spec.rb index 3266ec4ab50..63dce51c5da 100644 --- a/spec/lib/gitlab/github_import/bulk_importing_spec.rb +++ b/spec/lib/gitlab/github_import/bulk_importing_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::BulkImporting do +RSpec.describe Gitlab::GithubImport::BulkImporting do let(:importer) do Class.new { include(Gitlab::GithubImport::BulkImporting) }.new end diff --git a/spec/lib/gitlab/github_import/client_spec.rb b/spec/lib/gitlab/github_import/client_spec.rb index 3b269d64b07..7cff6ed1388 100644 --- a/spec/lib/gitlab/github_import/client_spec.rb +++ b/spec/lib/gitlab/github_import/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Client do +RSpec.describe Gitlab::GithubImport::Client do describe '#parallel?' do it 'returns true when the client is running in parallel mode' do client = described_class.new('foo', parallel: true) diff --git a/spec/lib/gitlab/github_import/importer/diff_note_importer_spec.rb b/spec/lib/gitlab/github_import/importer/diff_note_importer_spec.rb index 66909976b43..9eea85526f5 100644 --- a/spec/lib/gitlab/github_import/importer/diff_note_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/diff_note_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::DiffNoteImporter do +RSpec.describe Gitlab::GithubImport::Importer::DiffNoteImporter do let(:project) { create(:project) } let(:client) { double(:client) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/github_import/importer/diff_notes_importer_spec.rb b/spec/lib/gitlab/github_import/importer/diff_notes_importer_spec.rb index 23ed21294e3..7750e508713 100644 --- a/spec/lib/gitlab/github_import/importer/diff_notes_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/diff_notes_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::DiffNotesImporter do +RSpec.describe Gitlab::GithubImport::Importer::DiffNotesImporter do let(:project) { double(:project, id: 4, import_source: 'foo/bar') } let(:client) { double(:client) } diff --git a/spec/lib/gitlab/github_import/importer/issue_and_label_links_importer_spec.rb b/spec/lib/gitlab/github_import/importer/issue_and_label_links_importer_spec.rb index 399e2d9a563..49a76fb5e6b 100644 --- a/spec/lib/gitlab/github_import/importer/issue_and_label_links_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/issue_and_label_links_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::IssueAndLabelLinksImporter do +RSpec.describe Gitlab::GithubImport::Importer::IssueAndLabelLinksImporter do describe '#execute' do it 'imports an issue and its labels' do issue = double(:issue) diff --git a/spec/lib/gitlab/github_import/importer/issue_importer_spec.rb b/spec/lib/gitlab/github_import/importer/issue_importer_spec.rb index 0f2ba99f816..fb826c987e1 100644 --- a/spec/lib/gitlab/github_import/importer/issue_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/issue_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::IssueImporter, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::Importer::IssueImporter, :clean_gitlab_redis_cache do let(:project) { create(:project) } let(:client) { double(:client) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/github_import/importer/issues_importer_spec.rb b/spec/lib/gitlab/github_import/importer/issues_importer_spec.rb index 8920ef9fedb..2c2b6a2aff0 100644 --- a/spec/lib/gitlab/github_import/importer/issues_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/issues_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::IssuesImporter do +RSpec.describe Gitlab::GithubImport::Importer::IssuesImporter do let(:project) { double(:project, id: 4, import_source: 'foo/bar') } let(:client) { double(:client) } let(:created_at) { Time.new(2017, 1, 1, 12, 00) } diff --git a/spec/lib/gitlab/github_import/importer/label_links_importer_spec.rb b/spec/lib/gitlab/github_import/importer/label_links_importer_spec.rb index 9c02b0e280f..4d3245fc988 100644 --- a/spec/lib/gitlab/github_import/importer/label_links_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/label_links_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::LabelLinksImporter do +RSpec.describe Gitlab::GithubImport::Importer::LabelLinksImporter do let(:project) { create(:project) } let(:client) { double(:client) } let(:issue) do diff --git a/spec/lib/gitlab/github_import/importer/labels_importer_spec.rb b/spec/lib/gitlab/github_import/importer/labels_importer_spec.rb index 16326da9ca4..0010b959a49 100644 --- a/spec/lib/gitlab/github_import/importer/labels_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/labels_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::LabelsImporter, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::Importer::LabelsImporter, :clean_gitlab_redis_cache do let(:project) { create(:project, import_source: 'foo/bar') } let(:client) { double(:client) } let(:importer) { described_class.new(project, client) } diff --git a/spec/lib/gitlab/github_import/importer/lfs_object_importer_spec.rb b/spec/lib/gitlab/github_import/importer/lfs_object_importer_spec.rb index a02b620f131..add554992f1 100644 --- a/spec/lib/gitlab/github_import/importer/lfs_object_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/lfs_object_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::LfsObjectImporter do +RSpec.describe Gitlab::GithubImport::Importer::LfsObjectImporter do let(:project) { create(:project) } let(:lfs_attributes) do { diff --git a/spec/lib/gitlab/github_import/importer/lfs_objects_importer_spec.rb b/spec/lib/gitlab/github_import/importer/lfs_objects_importer_spec.rb index bec039a48eb..1f7b14661c2 100644 --- a/spec/lib/gitlab/github_import/importer/lfs_objects_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/lfs_objects_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::LfsObjectsImporter do +RSpec.describe Gitlab::GithubImport::Importer::LfsObjectsImporter do let(:project) { double(:project, id: 4, import_source: 'foo/bar') } let(:client) { double(:client) } let(:download_link) { "http://www.gitlab.com/lfs_objects/oid" } diff --git a/spec/lib/gitlab/github_import/importer/milestones_importer_spec.rb b/spec/lib/gitlab/github_import/importer/milestones_importer_spec.rb index 294599c02f4..dad1efc5a8d 100644 --- a/spec/lib/gitlab/github_import/importer/milestones_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/milestones_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::MilestonesImporter, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::Importer::MilestonesImporter, :clean_gitlab_redis_cache do let(:project) { create(:project, import_source: 'foo/bar') } let(:client) { double(:client) } let(:importer) { described_class.new(project, client) } diff --git a/spec/lib/gitlab/github_import/importer/note_importer_spec.rb b/spec/lib/gitlab/github_import/importer/note_importer_spec.rb index 816041b771b..3bb57e152fe 100644 --- a/spec/lib/gitlab/github_import/importer/note_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/note_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::NoteImporter do +RSpec.describe Gitlab::GithubImport::Importer::NoteImporter do let(:client) { double(:client) } let(:project) { create(:project) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/github_import/importer/notes_importer_spec.rb b/spec/lib/gitlab/github_import/importer/notes_importer_spec.rb index 128f8f95fa0..3782dab5ee3 100644 --- a/spec/lib/gitlab/github_import/importer/notes_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/notes_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::NotesImporter do +RSpec.describe Gitlab::GithubImport::Importer::NotesImporter do let(:project) { double(:project, id: 4, import_source: 'foo/bar') } let(:client) { double(:client) } diff --git a/spec/lib/gitlab/github_import/importer/pull_request_importer_spec.rb b/spec/lib/gitlab/github_import/importer/pull_request_importer_spec.rb index bffae9e2ba0..46850618945 100644 --- a/spec/lib/gitlab/github_import/importer/pull_request_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/pull_request_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::PullRequestImporter, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::Importer::PullRequestImporter, :clean_gitlab_redis_cache do let(:project) { create(:project, :repository) } let(:client) { double(:client) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/github_import/importer/pull_requests_importer_spec.rb b/spec/lib/gitlab/github_import/importer/pull_requests_importer_spec.rb index 526a5589743..05ac0248ec9 100644 --- a/spec/lib/gitlab/github_import/importer/pull_requests_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/pull_requests_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::PullRequestsImporter do +RSpec.describe Gitlab::GithubImport::Importer::PullRequestsImporter do let(:project) { create(:project, import_source: 'foo/bar') } let(:client) { double(:client) } diff --git a/spec/lib/gitlab/github_import/importer/releases_importer_spec.rb b/spec/lib/gitlab/github_import/importer/releases_importer_spec.rb index f8d53208619..1a25824bc8a 100644 --- a/spec/lib/gitlab/github_import/importer/releases_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/releases_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::ReleasesImporter do +RSpec.describe Gitlab::GithubImport::Importer::ReleasesImporter do let(:project) { create(:project) } let(:client) { double(:client) } let(:importer) { described_class.new(project, client) } diff --git a/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb b/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb index e26ac7bf81e..65dba2711b9 100644 --- a/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb +++ b/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Importer::RepositoryImporter do +RSpec.describe Gitlab::GithubImport::Importer::RepositoryImporter do let(:repository) { double(:repository) } let(:import_state) { double(:import_state) } let(:client) { double(:client) } diff --git a/spec/lib/gitlab/github_import/issuable_finder_spec.rb b/spec/lib/gitlab/github_import/issuable_finder_spec.rb index 55add863d43..f009b61ad89 100644 --- a/spec/lib/gitlab/github_import/issuable_finder_spec.rb +++ b/spec/lib/gitlab/github_import/issuable_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::IssuableFinder, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::IssuableFinder, :clean_gitlab_redis_cache do let(:project) { double(:project, id: 4) } let(:issue) do double(:issue, issuable_type: MergeRequest, iid: 1) diff --git a/spec/lib/gitlab/github_import/label_finder_spec.rb b/spec/lib/gitlab/github_import/label_finder_spec.rb index bb946a15a2d..452f3c896a4 100644 --- a/spec/lib/gitlab/github_import/label_finder_spec.rb +++ b/spec/lib/gitlab/github_import/label_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::LabelFinder, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::LabelFinder, :clean_gitlab_redis_cache do let(:project) { create(:project) } let(:finder) { described_class.new(project) } let!(:bug) { create(:label, project: project, name: 'Bug') } diff --git a/spec/lib/gitlab/github_import/markdown_text_spec.rb b/spec/lib/gitlab/github_import/markdown_text_spec.rb index a1216db7aac..4995caa0733 100644 --- a/spec/lib/gitlab/github_import/markdown_text_spec.rb +++ b/spec/lib/gitlab/github_import/markdown_text_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::MarkdownText do +RSpec.describe Gitlab::GithubImport::MarkdownText do describe '.format' do it 'formats the text' do author = double(:author, login: 'Alice') diff --git a/spec/lib/gitlab/github_import/milestone_finder_spec.rb b/spec/lib/gitlab/github_import/milestone_finder_spec.rb index ecb533b7e39..419184d6115 100644 --- a/spec/lib/gitlab/github_import/milestone_finder_spec.rb +++ b/spec/lib/gitlab/github_import/milestone_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::MilestoneFinder, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::MilestoneFinder, :clean_gitlab_redis_cache do let!(:project) { create(:project) } let!(:milestone) { create(:milestone, project: project) } let(:finder) { described_class.new(project) } diff --git a/spec/lib/gitlab/github_import/page_counter_spec.rb b/spec/lib/gitlab/github_import/page_counter_spec.rb index 95125c9c22f..a1305b714b5 100644 --- a/spec/lib/gitlab/github_import/page_counter_spec.rb +++ b/spec/lib/gitlab/github_import/page_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::PageCounter, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::PageCounter, :clean_gitlab_redis_cache do let(:project) { double(:project, id: 1) } let(:counter) { described_class.new(project, :issues) } diff --git a/spec/lib/gitlab/github_import/parallel_importer_spec.rb b/spec/lib/gitlab/github_import/parallel_importer_spec.rb index a8d5cc58bd5..06304bf84ca 100644 --- a/spec/lib/gitlab/github_import/parallel_importer_spec.rb +++ b/spec/lib/gitlab/github_import/parallel_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::ParallelImporter do +RSpec.describe Gitlab::GithubImport::ParallelImporter do describe '.async?' do it 'returns true' do expect(described_class).to be_async diff --git a/spec/lib/gitlab/github_import/parallel_scheduling_spec.rb b/spec/lib/gitlab/github_import/parallel_scheduling_spec.rb index a6ae99b395c..578743be96b 100644 --- a/spec/lib/gitlab/github_import/parallel_scheduling_spec.rb +++ b/spec/lib/gitlab/github_import/parallel_scheduling_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::ParallelScheduling do +RSpec.describe Gitlab::GithubImport::ParallelScheduling do let(:importer_class) do Class.new do include(Gitlab::GithubImport::ParallelScheduling) diff --git a/spec/lib/gitlab/github_import/representation/diff_note_spec.rb b/spec/lib/gitlab/github_import/representation/diff_note_spec.rb index e743a87cdd1..7e540674258 100644 --- a/spec/lib/gitlab/github_import/representation/diff_note_spec.rb +++ b/spec/lib/gitlab/github_import/representation/diff_note_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation::DiffNote do +RSpec.describe Gitlab::GithubImport::Representation::DiffNote do let(:hunk) do '@@ -1 +1 @@ -Hello diff --git a/spec/lib/gitlab/github_import/representation/expose_attribute_spec.rb b/spec/lib/gitlab/github_import/representation/expose_attribute_spec.rb index e3b48df4ae9..d40be0e841c 100644 --- a/spec/lib/gitlab/github_import/representation/expose_attribute_spec.rb +++ b/spec/lib/gitlab/github_import/representation/expose_attribute_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation::ExposeAttribute do +RSpec.describe Gitlab::GithubImport::Representation::ExposeAttribute do it 'defines a getter method that returns an attribute value' do klass = Class.new do include Gitlab::GithubImport::Representation::ExposeAttribute diff --git a/spec/lib/gitlab/github_import/representation/issue_spec.rb b/spec/lib/gitlab/github_import/representation/issue_spec.rb index 741a912e53b..3d306a4a3a3 100644 --- a/spec/lib/gitlab/github_import/representation/issue_spec.rb +++ b/spec/lib/gitlab/github_import/representation/issue_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation::Issue do +RSpec.describe Gitlab::GithubImport::Representation::Issue do let(:created_at) { Time.new(2017, 1, 1, 12, 00) } let(:updated_at) { Time.new(2017, 1, 1, 12, 15) } diff --git a/spec/lib/gitlab/github_import/representation/note_spec.rb b/spec/lib/gitlab/github_import/representation/note_spec.rb index a171a38bc9e..112bb7eb908 100644 --- a/spec/lib/gitlab/github_import/representation/note_spec.rb +++ b/spec/lib/gitlab/github_import/representation/note_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation::Note do +RSpec.describe Gitlab::GithubImport::Representation::Note do let(:created_at) { Time.new(2017, 1, 1, 12, 00) } let(:updated_at) { Time.new(2017, 1, 1, 12, 15) } diff --git a/spec/lib/gitlab/github_import/representation/pull_request_spec.rb b/spec/lib/gitlab/github_import/representation/pull_request_spec.rb index b6dcd098c9c..370eac1d993 100644 --- a/spec/lib/gitlab/github_import/representation/pull_request_spec.rb +++ b/spec/lib/gitlab/github_import/representation/pull_request_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation::PullRequest do +RSpec.describe Gitlab::GithubImport::Representation::PullRequest do let(:created_at) { Time.new(2017, 1, 1, 12, 00) } let(:updated_at) { Time.new(2017, 1, 1, 12, 15) } let(:merged_at) { Time.new(2017, 1, 1, 12, 17) } diff --git a/spec/lib/gitlab/github_import/representation/to_hash_spec.rb b/spec/lib/gitlab/github_import/representation/to_hash_spec.rb index 9c47349b376..2770e5c5397 100644 --- a/spec/lib/gitlab/github_import/representation/to_hash_spec.rb +++ b/spec/lib/gitlab/github_import/representation/to_hash_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation::ToHash do +RSpec.describe Gitlab::GithubImport::Representation::ToHash do describe '#to_hash' do let(:user) { double(:user, attributes: { login: 'alice' }) } diff --git a/spec/lib/gitlab/github_import/representation/user_spec.rb b/spec/lib/gitlab/github_import/representation/user_spec.rb index a7ad6bda3ad..14204886e9b 100644 --- a/spec/lib/gitlab/github_import/representation/user_spec.rb +++ b/spec/lib/gitlab/github_import/representation/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation::User do +RSpec.describe Gitlab::GithubImport::Representation::User do shared_examples 'a User' do it 'returns an instance of User' do expect(user).to be_an_instance_of(described_class) diff --git a/spec/lib/gitlab/github_import/representation_spec.rb b/spec/lib/gitlab/github_import/representation_spec.rb index 76753a0ff21..58c10c4a775 100644 --- a/spec/lib/gitlab/github_import/representation_spec.rb +++ b/spec/lib/gitlab/github_import/representation_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::Representation do +RSpec.describe Gitlab::GithubImport::Representation do describe '.symbolize_hash' do it 'returns a Hash with the keys as Symbols' do hash = described_class.symbolize_hash('number' => 10) diff --git a/spec/lib/gitlab/github_import/sequential_importer_spec.rb b/spec/lib/gitlab/github_import/sequential_importer_spec.rb index 256155dea03..fe13fcd2568 100644 --- a/spec/lib/gitlab/github_import/sequential_importer_spec.rb +++ b/spec/lib/gitlab/github_import/sequential_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::SequentialImporter do +RSpec.describe Gitlab::GithubImport::SequentialImporter do describe '#execute' do it 'imports a project in sequence' do repository = double(:repository) diff --git a/spec/lib/gitlab/github_import/user_finder_spec.rb b/spec/lib/gitlab/github_import/user_finder_spec.rb index 8764ebef32b..0dd2bd4df45 100644 --- a/spec/lib/gitlab/github_import/user_finder_spec.rb +++ b/spec/lib/gitlab/github_import/user_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport::UserFinder, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::GithubImport::UserFinder, :clean_gitlab_redis_cache do let(:project) { create(:project) } let(:client) { double(:client) } let(:finder) { described_class.new(project, client) } diff --git a/spec/lib/gitlab/github_import_spec.rb b/spec/lib/gitlab/github_import_spec.rb index 290d66243aa..1a690b81d2b 100644 --- a/spec/lib/gitlab/github_import_spec.rb +++ b/spec/lib/gitlab/github_import_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GithubImport do +RSpec.describe Gitlab::GithubImport do let(:project) { double(:project) } describe '.new_client_for' do diff --git a/spec/lib/gitlab/gitlab_import/client_spec.rb b/spec/lib/gitlab/gitlab_import/client_spec.rb index 6e4e88093bb..7f57d5fbf1b 100644 --- a/spec/lib/gitlab/gitlab_import/client_spec.rb +++ b/spec/lib/gitlab/gitlab_import/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitlabImport::Client do +RSpec.describe Gitlab::GitlabImport::Client do include ImportSpecHelper let(:token) { '123456' } diff --git a/spec/lib/gitlab/gitlab_import/importer_spec.rb b/spec/lib/gitlab/gitlab_import/importer_spec.rb index 2db1ddcfd0a..eb4c404e454 100644 --- a/spec/lib/gitlab/gitlab_import/importer_spec.rb +++ b/spec/lib/gitlab/gitlab_import/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitlabImport::Importer do +RSpec.describe Gitlab::GitlabImport::Importer do include ImportSpecHelper describe '#execute' do diff --git a/spec/lib/gitlab/gitlab_import/project_creator_spec.rb b/spec/lib/gitlab/gitlab_import/project_creator_spec.rb index c7ef978df37..44bcfb93c51 100644 --- a/spec/lib/gitlab/gitlab_import/project_creator_spec.rb +++ b/spec/lib/gitlab/gitlab_import/project_creator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GitlabImport::ProjectCreator do +RSpec.describe Gitlab::GitlabImport::ProjectCreator do let(:user) { create(:user) } let(:repo) do { diff --git a/spec/lib/gitlab/gl_repository/identifier_spec.rb b/spec/lib/gitlab/gl_repository/identifier_spec.rb index c36f296702e..e95aaaa6690 100644 --- a/spec/lib/gitlab/gl_repository/identifier_spec.rb +++ b/spec/lib/gitlab/gl_repository/identifier_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GlRepository::Identifier do +RSpec.describe Gitlab::GlRepository::Identifier do let_it_be(:project) { create(:project) } let_it_be(:personal_snippet) { create(:personal_snippet, author: project.owner) } let_it_be(:project_snippet) { create(:project_snippet, project: project, author: project.owner) } @@ -14,6 +14,21 @@ describe Gitlab::GlRepository::Identifier do let(:expected_container) { project } let(:expected_type) { Gitlab::GlRepository::PROJECT } end + + pending 'https://gitlab.com/gitlab-org/gitlab/-/issues/219192' do + it_behaves_like 'parsing gl_repository identifier' do + let(:record_id) { project.id } + let(:identifier) { "project-#{record_id}-code" } + let(:expected_container) { project } + let(:expected_type) { Gitlab::GlRepository::PROJECT } + end + end + + it_behaves_like 'parsing gl_repository identifier' do + let(:identifier) { "project-1000000" } + let(:expected_container) { nil } + let(:expected_type) { Gitlab::GlRepository::PROJECT } + end end describe 'wiki' do @@ -23,6 +38,13 @@ describe Gitlab::GlRepository::Identifier do let(:expected_container) { project } let(:expected_type) { Gitlab::GlRepository::WIKI } end + + it_behaves_like 'parsing gl_repository identifier' do + let(:record_id) { project.id } + let(:identifier) { "project-#{record_id}-wiki" } + let(:expected_container) { project } + let(:expected_type) { Gitlab::GlRepository::WIKI } + end end describe 'snippet' do @@ -54,29 +76,30 @@ describe Gitlab::GlRepository::Identifier do end end - describe 'incorrect format' do - def expect_error_raised_for(identifier) - expect { described_class.new(identifier) }.to raise_error(ArgumentError) - end - - it 'raises error for incorrect id' do - expect_error_raised_for('wiki-noid') + context 'when the format is incorrect' do + where(:identifier) do + [ + 'wiki-noid', + 'foo-2', + 'project-0', + '2-project', + 'snippet-2-wiki', + 'project-wibble-wiki', + 'wiki-1-project', + 'snippet', + 'project-1-wiki-bar' + ] end - it 'raises error for incorrect type' do - expect_error_raised_for('foo-2') - end - - it 'raises error for incorrect three-segment container' do - expect_error_raised_for('snippet-2-wiki') - end - - it 'raises error for one segment' do - expect_error_raised_for('snippet') + with_them do + it 'raises InvalidIdentifier' do + expect { described_class.parse(identifier) }.to raise_error(described_class::InvalidIdentifier) + end end - it 'raises error for more than three segments' do - expect_error_raised_for('project-1-wiki-bar') + it 'raises InvalidIdentifier on project-1-project' do + pending 'https://gitlab.com/gitlab-org/gitlab/-/issues/219192' + expect { described_class.parse('project-1-project') }.to raise_error(described_class::InvalidIdentifier) end end end diff --git a/spec/lib/gitlab/gl_repository/repo_type_spec.rb b/spec/lib/gitlab/gl_repository/repo_type_spec.rb index f5270104d2f..e920fc7cd3b 100644 --- a/spec/lib/gitlab/gl_repository/repo_type_spec.rb +++ b/spec/lib/gitlab/gl_repository/repo_type_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::GlRepository::RepoType do +RSpec.describe Gitlab::GlRepository::RepoType do let_it_be(:project) { create(:project) } let_it_be(:personal_snippet) { create(:personal_snippet, author: project.owner) } let_it_be(:project_snippet) { create(:project_snippet, project: project, author: project.owner) } diff --git a/spec/lib/gitlab/gl_repository_spec.rb b/spec/lib/gitlab/gl_repository_spec.rb index 413540b4db8..f90103ee6f7 100644 --- a/spec/lib/gitlab/gl_repository_spec.rb +++ b/spec/lib/gitlab/gl_repository_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::GlRepository do +RSpec.describe ::Gitlab::GlRepository do describe '.parse' do let_it_be(:project) { create(:project, :repository) } let_it_be(:snippet) { create(:personal_snippet) } diff --git a/spec/lib/gitlab/global_id_spec.rb b/spec/lib/gitlab/global_id_spec.rb index 719743ed5dc..3fc18858eee 100644 --- a/spec/lib/gitlab/global_id_spec.rb +++ b/spec/lib/gitlab/global_id_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GlobalId do +RSpec.describe Gitlab::GlobalId do describe '.build' do let_it_be(:object) { create(:issue) } @@ -34,4 +34,37 @@ describe Gitlab::GlobalId do expect { described_class.build }.to raise_error(URI::InvalidComponentError) end end + + describe '.as_global_id' do + let(:project) { build_stubbed(:project) } + + it 'is the identify function on GlobalID instances' do + gid = project.to_global_id + + expect(described_class.as_global_id(gid)).to eq(gid) + end + + it 'wraps URI::GID in GlobalID' do + uri = described_class.build(model_name: 'Foo', id: 1) + + expect(described_class.as_global_id(uri)).to eq(GlobalID.new(uri)) + end + + it 'cannot coerce Integers without a model name' do + expect { described_class.as_global_id(1) } + .to raise_error(described_class::CoerceError, 'Cannot coerce Integer') + end + + it 'can coerce Integers with a model name' do + uri = described_class.build(model_name: 'Foo', id: 1) + + expect(described_class.as_global_id(1, model_name: 'Foo')).to eq(GlobalID.new(uri)) + end + + it 'rejects any other value' do + [:symbol, 'string', nil, [], {}, project].each do |value| + expect { described_class.as_global_id(value) }.to raise_error(described_class::CoerceError) + end + end + end end diff --git a/spec/lib/gitlab/gon_helper_spec.rb b/spec/lib/gitlab/gon_helper_spec.rb index 7b0e0d01257..95db6b2b4e0 100644 --- a/spec/lib/gitlab/gon_helper_spec.rb +++ b/spec/lib/gitlab/gon_helper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GonHelper do +RSpec.describe Gitlab::GonHelper do let(:helper) do Class.new do include Gitlab::GonHelper diff --git a/spec/lib/gitlab/google_code_import/client_spec.rb b/spec/lib/gitlab/google_code_import/client_spec.rb index fb1c7085017..402d2169432 100644 --- a/spec/lib/gitlab/google_code_import/client_spec.rb +++ b/spec/lib/gitlab/google_code_import/client_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::GoogleCodeImport::Client do +RSpec.describe Gitlab::GoogleCodeImport::Client do let(:raw_data) { Gitlab::Json.parse(fixture_file("GoogleCodeProjectHosting.json")) } subject { described_class.new(raw_data) } diff --git a/spec/lib/gitlab/google_code_import/importer_spec.rb b/spec/lib/gitlab/google_code_import/importer_spec.rb index 3118671bb5e..f681e3c9f31 100644 --- a/spec/lib/gitlab/google_code_import/importer_spec.rb +++ b/spec/lib/gitlab/google_code_import/importer_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::GoogleCodeImport::Importer do +RSpec.describe Gitlab::GoogleCodeImport::Importer do let(:mapped_user) { create(:user, username: "thilo123") } let(:raw_data) { Gitlab::Json.parse(fixture_file("GoogleCodeProjectHosting.json")) } let(:client) { Gitlab::GoogleCodeImport::Client.new(raw_data) } diff --git a/spec/lib/gitlab/google_code_import/project_creator_spec.rb b/spec/lib/gitlab/google_code_import/project_creator_spec.rb index 2353c24f77b..4be2e16c116 100644 --- a/spec/lib/gitlab/google_code_import/project_creator_spec.rb +++ b/spec/lib/gitlab/google_code_import/project_creator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GoogleCodeImport::ProjectCreator do +RSpec.describe Gitlab::GoogleCodeImport::ProjectCreator do let(:user) { create(:user) } let(:repo) do Gitlab::GoogleCodeImport::Repository.new( diff --git a/spec/lib/gitlab/gpg/commit_spec.rb b/spec/lib/gitlab/gpg/commit_spec.rb index ea0a6e1b967..55102554508 100644 --- a/spec/lib/gitlab/gpg/commit_spec.rb +++ b/spec/lib/gitlab/gpg/commit_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Gpg::Commit do +RSpec.describe Gitlab::Gpg::Commit do describe '#signature' do shared_examples 'returns the cached signature on second call' do it 'returns the cached signature on second call' do diff --git a/spec/lib/gitlab/gpg_spec.rb b/spec/lib/gitlab/gpg_spec.rb index c7b9775f642..72c6c8efb5e 100644 --- a/spec/lib/gitlab/gpg_spec.rb +++ b/spec/lib/gitlab/gpg_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Gpg do +RSpec.describe Gitlab::Gpg do describe '.fingerprints_from_key' do before do # make sure that each method is using the temporary keychain @@ -244,7 +244,7 @@ describe Gitlab::Gpg do end end -describe Gitlab::Gpg::CurrentKeyChain do +RSpec.describe Gitlab::Gpg::CurrentKeyChain do around do |example| Gitlab::Gpg.using_tmp_keychain do example.run diff --git a/spec/lib/gitlab/grape_logging/formatters/lograge_with_timestamp_spec.rb b/spec/lib/gitlab/grape_logging/formatters/lograge_with_timestamp_spec.rb index 84f23bb2ad9..e5d0adcfd5f 100644 --- a/spec/lib/gitlab/grape_logging/formatters/lograge_with_timestamp_spec.rb +++ b/spec/lib/gitlab/grape_logging/formatters/lograge_with_timestamp_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GrapeLogging::Formatters::LogrageWithTimestamp do +RSpec.describe Gitlab::GrapeLogging::Formatters::LogrageWithTimestamp do let(:log_entry) do { status: 200, diff --git a/spec/lib/gitlab/grape_logging/loggers/cloudflare_logger_spec.rb b/spec/lib/gitlab/grape_logging/loggers/cloudflare_logger_spec.rb index 922a433d7ac..f683f98f019 100644 --- a/spec/lib/gitlab/grape_logging/loggers/cloudflare_logger_spec.rb +++ b/spec/lib/gitlab/grape_logging/loggers/cloudflare_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GrapeLogging::Loggers::CloudflareLogger do +RSpec.describe Gitlab::GrapeLogging::Loggers::CloudflareLogger do subject { described_class.new } describe "#parameters" do diff --git a/spec/lib/gitlab/grape_logging/loggers/exception_logger_spec.rb b/spec/lib/gitlab/grape_logging/loggers/exception_logger_spec.rb index cc9535d4d2c..bcb1f6c5af7 100644 --- a/spec/lib/gitlab/grape_logging/loggers/exception_logger_spec.rb +++ b/spec/lib/gitlab/grape_logging/loggers/exception_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GrapeLogging::Loggers::ExceptionLogger do +RSpec.describe Gitlab::GrapeLogging::Loggers::ExceptionLogger do let(:mock_request) { OpenStruct.new(env: {}) } let(:response_body) { nil } diff --git a/spec/lib/gitlab/grape_logging/loggers/perf_logger_spec.rb b/spec/lib/gitlab/grape_logging/loggers/perf_logger_spec.rb index 09ba4b89a1a..95e3af34174 100644 --- a/spec/lib/gitlab/grape_logging/loggers/perf_logger_spec.rb +++ b/spec/lib/gitlab/grape_logging/loggers/perf_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GrapeLogging::Loggers::PerfLogger do +RSpec.describe Gitlab::GrapeLogging::Loggers::PerfLogger do subject { described_class.new } describe ".parameters" do diff --git a/spec/lib/gitlab/grape_logging/loggers/queue_duration_logger_spec.rb b/spec/lib/gitlab/grape_logging/loggers/queue_duration_logger_spec.rb index 17c0659327d..e68c1446502 100644 --- a/spec/lib/gitlab/grape_logging/loggers/queue_duration_logger_spec.rb +++ b/spec/lib/gitlab/grape_logging/loggers/queue_duration_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GrapeLogging::Loggers::QueueDurationLogger do +RSpec.describe Gitlab::GrapeLogging::Loggers::QueueDurationLogger do subject { described_class.new } describe ".parameters" do diff --git a/spec/lib/gitlab/graphql/authorize/authorize_field_service_spec.rb b/spec/lib/gitlab/graphql/authorize/authorize_field_service_spec.rb index c1dab5feb91..efe6c27c463 100644 --- a/spec/lib/gitlab/graphql/authorize/authorize_field_service_spec.rb +++ b/spec/lib/gitlab/graphql/authorize/authorize_field_service_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' # Also see spec/graphql/features/authorization_spec.rb for # integration tests of AuthorizeFieldService -describe Gitlab::Graphql::Authorize::AuthorizeFieldService do +RSpec.describe Gitlab::Graphql::Authorize::AuthorizeFieldService do def type(type_authorizations = []) Class.new(Types::BaseObject) do graphql_name 'TestType' diff --git a/spec/lib/gitlab/graphql/authorize/authorize_resource_spec.rb b/spec/lib/gitlab/graphql/authorize/authorize_resource_spec.rb index 67cb064b966..83873081a98 100644 --- a/spec/lib/gitlab/graphql/authorize/authorize_resource_spec.rb +++ b/spec/lib/gitlab/graphql/authorize/authorize_resource_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Authorize::AuthorizeResource do +RSpec.describe Gitlab::Graphql::Authorize::AuthorizeResource do let(:fake_class) do Class.new do include Gitlab::Graphql::Authorize::AuthorizeResource diff --git a/spec/lib/gitlab/graphql/calls_gitaly/instrumentation_spec.rb b/spec/lib/gitlab/graphql/calls_gitaly/instrumentation_spec.rb index d93ce464a92..f16767f7d14 100644 --- a/spec/lib/gitlab/graphql/calls_gitaly/instrumentation_spec.rb +++ b/spec/lib/gitlab/graphql/calls_gitaly/instrumentation_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Graphql::CallsGitaly::Instrumentation do +RSpec.describe Gitlab::Graphql::CallsGitaly::Instrumentation do subject { described_class.new } describe '#calls_gitaly_check' do diff --git a/spec/lib/gitlab/graphql/copy_field_description_spec.rb b/spec/lib/gitlab/graphql/copy_field_description_spec.rb index e7462c5b954..310b4046b56 100644 --- a/spec/lib/gitlab/graphql/copy_field_description_spec.rb +++ b/spec/lib/gitlab/graphql/copy_field_description_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::CopyFieldDescription do +RSpec.describe Gitlab::Graphql::CopyFieldDescription do subject { Class.new.include(described_class) } describe '.copy_field_description' do diff --git a/spec/lib/gitlab/graphql/docs/renderer_spec.rb b/spec/lib/gitlab/graphql/docs/renderer_spec.rb index 87079a1786c..81ef7fcda97 100644 --- a/spec/lib/gitlab/graphql/docs/renderer_spec.rb +++ b/spec/lib/gitlab/graphql/docs/renderer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Docs::Renderer do +RSpec.describe Gitlab::Graphql::Docs::Renderer do describe '#contents' do # Returns a Schema that uses the given `type` def mock_schema(type) diff --git a/spec/lib/gitlab/graphql/find_argument_in_parent_spec.rb b/spec/lib/gitlab/graphql/find_argument_in_parent_spec.rb index 91e90315b3e..68b24a60a99 100644 --- a/spec/lib/gitlab/graphql/find_argument_in_parent_spec.rb +++ b/spec/lib/gitlab/graphql/find_argument_in_parent_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::FindArgumentInParent do +RSpec.describe Gitlab::Graphql::FindArgumentInParent do describe '#find' do def build_node(parent = nil, args: {}) props = { irep_node: double(arguments: args) } diff --git a/spec/lib/gitlab/graphql/generic_tracing_spec.rb b/spec/lib/gitlab/graphql/generic_tracing_spec.rb index ae92dcc40af..cd116225ecd 100644 --- a/spec/lib/gitlab/graphql/generic_tracing_spec.rb +++ b/spec/lib/gitlab/graphql/generic_tracing_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::GenericTracing do +RSpec.describe Gitlab::Graphql::GenericTracing do let(:graphql_duration_seconds_histogram) { double('Gitlab::Metrics::NullMetric') } it 'updates graphql histogram with expected labels' do diff --git a/spec/lib/gitlab/graphql/loaders/batch_lfs_oid_loader_spec.rb b/spec/lib/gitlab/graphql/loaders/batch_lfs_oid_loader_spec.rb index b3d57c899d5..ae5d9686c54 100644 --- a/spec/lib/gitlab/graphql/loaders/batch_lfs_oid_loader_spec.rb +++ b/spec/lib/gitlab/graphql/loaders/batch_lfs_oid_loader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Loaders::BatchLfsOidLoader do +RSpec.describe Gitlab::Graphql::Loaders::BatchLfsOidLoader do include GraphqlHelpers let_it_be(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/graphql/loaders/batch_model_loader_spec.rb b/spec/lib/gitlab/graphql/loaders/batch_model_loader_spec.rb index 79f9ecb39cf..cf1f00bc176 100644 --- a/spec/lib/gitlab/graphql/loaders/batch_model_loader_spec.rb +++ b/spec/lib/gitlab/graphql/loaders/batch_model_loader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Loaders::BatchModelLoader do +RSpec.describe Gitlab::Graphql::Loaders::BatchModelLoader do describe '#find' do let(:issue) { create(:issue) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/graphql/loaders/batch_project_statistics_loader_spec.rb b/spec/lib/gitlab/graphql/loaders/batch_project_statistics_loader_spec.rb index ec2fcad31e5..7ae28fdcf0f 100644 --- a/spec/lib/gitlab/graphql/loaders/batch_project_statistics_loader_spec.rb +++ b/spec/lib/gitlab/graphql/loaders/batch_project_statistics_loader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Loaders::BatchProjectStatisticsLoader do +RSpec.describe Gitlab::Graphql::Loaders::BatchProjectStatisticsLoader do describe '#find' do it 'only queries once for project statistics' do stats = create_list(:project_statistics, 2) diff --git a/spec/lib/gitlab/graphql/loaders/batch_root_storage_statistics_loader_spec.rb b/spec/lib/gitlab/graphql/loaders/batch_root_storage_statistics_loader_spec.rb index 38931f7ab5e..f73eace274d 100644 --- a/spec/lib/gitlab/graphql/loaders/batch_root_storage_statistics_loader_spec.rb +++ b/spec/lib/gitlab/graphql/loaders/batch_root_storage_statistics_loader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Loaders::BatchRootStorageStatisticsLoader do +RSpec.describe Gitlab::Graphql::Loaders::BatchRootStorageStatisticsLoader do describe '#find' do it 'only queries once for project statistics' do stats = create_list(:namespace_root_storage_statistics, 2) diff --git a/spec/lib/gitlab/graphql/loaders/issuable_loader_spec.rb b/spec/lib/gitlab/graphql/loaders/issuable_loader_spec.rb new file mode 100644 index 00000000000..180966de895 --- /dev/null +++ b/spec/lib/gitlab/graphql/loaders/issuable_loader_spec.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Graphql::Loaders::IssuableLoader do + subject { described_class.new(parent, finder) } + + let(:params) { HashWithIndifferentAccess.new } + + describe '#find_all' do + let(:finder) { double(:finder, params: params, execute: %i[x y z]) } + + where(:factory, :param_name) do + %i[project group].map { |thing| [thing, :"#{thing}_id"] } + end + + with_them do + let(:parent) { build_stubbed(factory) } + + it 'assignes the parent parameter, and batching_find_alls the finder' do + expect(subject.find_all).to contain_exactly(:x, :y, :z) + expect(params).to include(param_name => parent) + end + end + + context 'the parent is of an unexpected type' do + let(:parent) { build(:merge_request) } + + it 'raises an error if we pass an unexpected parent' do + expect { subject.find_all }.to raise_error(/Unexpected parent/) + end + end + end + + describe '#batching_find_all' do + context 'the finder params are anything other than [iids]' do + let(:finder) { double(:finder, params: params, execute: [:foo]) } + let(:parent) { build_stubbed(:project) } + + it 'batching_find_alls the finder, setting the correct parent parameter' do + expect(subject.batching_find_all).to eq([:foo]) + expect(params[:project_id]).to eq(parent) + end + + it 'allows a post-process block' do + expect(subject.batching_find_all(&:first)).to eq(:foo) + end + end + + context 'the finder params are exactly [iids]' do + # Dumb finder class, that only implements what we need, and has + # predictable query counts. + let(:finder_class) do + Class.new do + attr_reader :current_user, :params + + def initialize(user, args) + @current_user = user + @params = HashWithIndifferentAccess.new(args.to_h) + end + + def execute + params[:project_id].issues.where(iid: params[:iids]) + end + end + end + + it 'batches requests' do + issue_a = create(:issue) + issue_b = create(:issue) + issue_c = create(:issue, project: issue_a.project) + proj_1 = issue_a.project + proj_2 = issue_b.project + user = create(:user, developer_projects: [proj_1, proj_2]) + + finder_a = finder_class.new(user, iids: [issue_a.iid]) + finder_b = finder_class.new(user, iids: [issue_b.iid]) + finder_c = finder_class.new(user, iids: [issue_c.iid]) + + results = [] + + expect do + results.concat(described_class.new(proj_1, finder_a).batching_find_all) + results.concat(described_class.new(proj_2, finder_b).batching_find_all) + results.concat(described_class.new(proj_1, finder_c).batching_find_all) + end.not_to exceed_query_limit(0) + + expect do + results = results.map(&:sync) + end.not_to exceed_query_limit(2) + + expect(results).to contain_exactly(issue_a, issue_b, issue_c) + end + end + end +end diff --git a/spec/lib/gitlab/graphql/markdown_field/resolver_spec.rb b/spec/lib/gitlab/graphql/markdown_field/resolver_spec.rb index b95bcdef188..af604e1c7d5 100644 --- a/spec/lib/gitlab/graphql/markdown_field/resolver_spec.rb +++ b/spec/lib/gitlab/graphql/markdown_field/resolver_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Graphql::MarkdownField::Resolver do +RSpec.describe Gitlab::Graphql::MarkdownField::Resolver do include Gitlab::Routing let(:resolver) { described_class.new(:note) } diff --git a/spec/lib/gitlab/graphql/markdown_field_spec.rb b/spec/lib/gitlab/graphql/markdown_field_spec.rb index 866a20801d3..e3da925376e 100644 --- a/spec/lib/gitlab/graphql/markdown_field_spec.rb +++ b/spec/lib/gitlab/graphql/markdown_field_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Graphql::MarkdownField do +RSpec.describe Gitlab::Graphql::MarkdownField do describe '.markdown_field' do it 'creates the field with some default attributes' do field = class_with_markdown_field(:test_html, null: true, method: :hello).fields['testHtml'] diff --git a/spec/lib/gitlab/graphql/mount_mutation_spec.rb b/spec/lib/gitlab/graphql/mount_mutation_spec.rb new file mode 100644 index 00000000000..d6b932e08d2 --- /dev/null +++ b/spec/lib/gitlab/graphql/mount_mutation_spec.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true +require 'spec_helper' + +RSpec.describe Gitlab::Graphql::MountMutation do + let_it_be(:mutation) do + Class.new(Mutations::BaseMutation) do + graphql_name 'TestMutation' + + argument :foo, GraphQL::STRING_TYPE, required: false + field :bar, GraphQL::STRING_TYPE, null: true + end + end + + describe '.mount_mutation' do + subject(:field) do + mutation_type = mutation_type_factory do |f| + f.mount_mutation(mutation) + end + + mutation_type.get_field('testMutation').to_graphql + end + + it 'mounts a mutation' do + expect(field.mutation).to be_present + end + end + + describe '.mount_aliased_mutation' do + subject(:field) do + mutation_type = mutation_type_factory do |f| + f.mount_aliased_mutation('MyAlias', mutation) + end + + mutation_type.get_field('myAlias').to_graphql + end + + it 'mounts a mutation' do + expect(field.mutation).to be_present + end + + it 'has a correct `graphql_name`' do + expect(field.mutation.graphql_name).to eq('MyAlias') + end + + it 'has a correct type' do + expect(field.type.name).to eq('MyAliasPayload') + end + + it 'has a correct input argument' do + expect(field.arguments['input'].type.unwrap.name).to eq('MyAliasInput') + end + end + + def mutation_type_factory + Class.new(GraphQL::Schema::Object) do + include Gitlab::Graphql::MountMutation + + graphql_name 'MutationType' + + yield(self) if block_given? + end + end +end diff --git a/spec/lib/gitlab/graphql/pagination/externally_paginated_array_connection_spec.rb b/spec/lib/gitlab/graphql/pagination/externally_paginated_array_connection_spec.rb index 11cf14523c2..932bcd8cd92 100644 --- a/spec/lib/gitlab/graphql/pagination/externally_paginated_array_connection_spec.rb +++ b/spec/lib/gitlab/graphql/pagination/externally_paginated_array_connection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Pagination::ExternallyPaginatedArrayConnection do +RSpec.describe Gitlab::Graphql::Pagination::ExternallyPaginatedArrayConnection do let(:prev_cursor) { 1 } let(:next_cursor) { 6 } let(:values) { [2, 3, 4, 5] } diff --git a/spec/lib/gitlab/graphql/pagination/keyset/conditions/not_null_condition_spec.rb b/spec/lib/gitlab/graphql/pagination/keyset/conditions/not_null_condition_spec.rb index 33dc6bdea97..eecdaa3409f 100644 --- a/spec/lib/gitlab/graphql/pagination/keyset/conditions/not_null_condition_spec.rb +++ b/spec/lib/gitlab/graphql/pagination/keyset/conditions/not_null_condition_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Pagination::Keyset::Conditions::NotNullCondition do +RSpec.describe Gitlab::Graphql::Pagination::Keyset::Conditions::NotNullCondition do describe '#build' do let(:operators) { ['>', '>'] } let(:before_or_after) { :after } diff --git a/spec/lib/gitlab/graphql/pagination/keyset/conditions/null_condition_spec.rb b/spec/lib/gitlab/graphql/pagination/keyset/conditions/null_condition_spec.rb index 1c74f2fb0ab..582f96299ec 100644 --- a/spec/lib/gitlab/graphql/pagination/keyset/conditions/null_condition_spec.rb +++ b/spec/lib/gitlab/graphql/pagination/keyset/conditions/null_condition_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Pagination::Keyset::Conditions::NullCondition do +RSpec.describe Gitlab::Graphql::Pagination::Keyset::Conditions::NullCondition do describe '#build' do let(:values) { [nil, 500] } let(:operators) { [nil, '>'] } diff --git a/spec/lib/gitlab/graphql/pagination/keyset/connection_spec.rb b/spec/lib/gitlab/graphql/pagination/keyset/connection_spec.rb index ed728444b17..65698caac34 100644 --- a/spec/lib/gitlab/graphql/pagination/keyset/connection_spec.rb +++ b/spec/lib/gitlab/graphql/pagination/keyset/connection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Pagination::Keyset::Connection do +RSpec.describe Gitlab::Graphql::Pagination::Keyset::Connection do let(:nodes) { Project.all.order(id: :asc) } let(:arguments) { {} } let(:query_type) { GraphQL::ObjectType.new } diff --git a/spec/lib/gitlab/graphql/pagination/keyset/order_info_spec.rb b/spec/lib/gitlab/graphql/pagination/keyset/order_info_spec.rb index cb5656d7c00..9f310f30253 100644 --- a/spec/lib/gitlab/graphql/pagination/keyset/order_info_spec.rb +++ b/spec/lib/gitlab/graphql/pagination/keyset/order_info_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Pagination::Keyset::OrderInfo do +RSpec.describe Gitlab::Graphql::Pagination::Keyset::OrderInfo do describe '#build_order_list' do let(:order_list) { described_class.build_order_list(relation) } diff --git a/spec/lib/gitlab/graphql/pagination/keyset/query_builder_spec.rb b/spec/lib/gitlab/graphql/pagination/keyset/query_builder_spec.rb index 7fd5b889cf9..31c02fd43e8 100644 --- a/spec/lib/gitlab/graphql/pagination/keyset/query_builder_spec.rb +++ b/spec/lib/gitlab/graphql/pagination/keyset/query_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Pagination::Keyset::QueryBuilder do +RSpec.describe Gitlab::Graphql::Pagination::Keyset::QueryBuilder do context 'when number of ordering fields is 0' do it 'raises an error' do expect { described_class.new(Issue.arel_table, [], {}, :after) } diff --git a/spec/lib/gitlab/graphql/pagination/offset_active_record_relation_connection_spec.rb b/spec/lib/gitlab/graphql/pagination/offset_active_record_relation_connection_spec.rb index 931b1e708de..86f35de94ed 100644 --- a/spec/lib/gitlab/graphql/pagination/offset_active_record_relation_connection_spec.rb +++ b/spec/lib/gitlab/graphql/pagination/offset_active_record_relation_connection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Pagination::OffsetActiveRecordRelationConnection do +RSpec.describe Gitlab::Graphql::Pagination::OffsetActiveRecordRelationConnection do it 'subclasses from GraphQL::Relay::RelationConnection' do expect(described_class.superclass).to eq GraphQL::Pagination::ActiveRecordRelationConnection end diff --git a/spec/lib/gitlab/graphql/query_analyzers/logger_analyzer_spec.rb b/spec/lib/gitlab/graphql/query_analyzers/logger_analyzer_spec.rb index 66033736e01..89d2ab8bb87 100644 --- a/spec/lib/gitlab/graphql/query_analyzers/logger_analyzer_spec.rb +++ b/spec/lib/gitlab/graphql/query_analyzers/logger_analyzer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::QueryAnalyzers::LoggerAnalyzer do +RSpec.describe Gitlab::Graphql::QueryAnalyzers::LoggerAnalyzer do subject { described_class.new } describe '#analyze?' do @@ -17,9 +17,27 @@ describe Gitlab::Graphql::QueryAnalyzers::LoggerAnalyzer do end context 'feature flag enabled by default' do + let(:monotonic_time_before) { 42 } + let(:monotonic_time_after) { 500 } + let(:monotonic_time_duration) { monotonic_time_after - monotonic_time_before } + it 'enables the analyzer' do expect(subject.analyze?(anything)).to be_truthy end + + it 'returns a duration in seconds' do + allow(GraphQL::Analysis).to receive(:analyze_query).and_return([4, 2]) + allow(Gitlab::Metrics::System).to receive(:monotonic_time).and_return(monotonic_time_before, monotonic_time_after) + allow(Gitlab::GraphqlLogger).to receive(:info) + + expected_duration = monotonic_time_duration + memo = subject.initial_value(spy('query')) + + subject.final_value(memo) + + expect(memo).to have_key(:duration_s) + expect(memo[:duration_s]).to eq(expected_duration) + end end end end diff --git a/spec/lib/gitlab/graphql/representation/submodule_tree_entry_spec.rb b/spec/lib/gitlab/graphql/representation/submodule_tree_entry_spec.rb index ed092a846ae..eb56f1f9671 100644 --- a/spec/lib/gitlab/graphql/representation/submodule_tree_entry_spec.rb +++ b/spec/lib/gitlab/graphql/representation/submodule_tree_entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Representation::SubmoduleTreeEntry do +RSpec.describe Gitlab::Graphql::Representation::SubmoduleTreeEntry do let(:project) { create(:project, :repository) } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/graphql/representation/tree_entry_spec.rb b/spec/lib/gitlab/graphql/representation/tree_entry_spec.rb index d45e690160c..f4eb7b37774 100644 --- a/spec/lib/gitlab/graphql/representation/tree_entry_spec.rb +++ b/spec/lib/gitlab/graphql/representation/tree_entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Representation::TreeEntry do +RSpec.describe Gitlab::Graphql::Representation::TreeEntry do let(:project) { create(:project, :repository) } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/graphql/timeout_spec.rb b/spec/lib/gitlab/graphql/timeout_spec.rb index 8e04586d0ec..3669a89ba7c 100644 --- a/spec/lib/gitlab/graphql/timeout_spec.rb +++ b/spec/lib/gitlab/graphql/timeout_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphql::Timeout do +RSpec.describe Gitlab::Graphql::Timeout do it 'inherits from ' do expect(described_class.superclass).to eq GraphQL::Schema::Timeout end diff --git a/spec/lib/gitlab/graphql_logger_spec.rb b/spec/lib/gitlab/graphql_logger_spec.rb index 12cb56c78c1..c92666e0663 100644 --- a/spec/lib/gitlab/graphql_logger_spec.rb +++ b/spec/lib/gitlab/graphql_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GraphqlLogger do +RSpec.describe Gitlab::GraphqlLogger do subject { described_class.new('/dev/null') } let(:now) { Time.now } diff --git a/spec/lib/gitlab/graphs/commits_spec.rb b/spec/lib/gitlab/graphs/commits_spec.rb index f92c7fb11a1..79cec2d8705 100644 --- a/spec/lib/gitlab/graphs/commits_spec.rb +++ b/spec/lib/gitlab/graphs/commits_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Graphs::Commits do +RSpec.describe Gitlab::Graphs::Commits do let!(:project) { create(:project, :public) } let!(:commit1) { create(:commit, git_commit: RepoHelpers.sample_commit, project: project, committed_date: Time.now) } diff --git a/spec/lib/gitlab/group_search_results_spec.rb b/spec/lib/gitlab/group_search_results_spec.rb index 746f505c877..b6a3c8b5e76 100644 --- a/spec/lib/gitlab/group_search_results_spec.rb +++ b/spec/lib/gitlab/group_search_results_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::GroupSearchResults do +RSpec.describe Gitlab::GroupSearchResults do let(:user) { create(:user) } describe 'user search' do diff --git a/spec/lib/gitlab/hashed_storage/migrator_spec.rb b/spec/lib/gitlab/hashed_storage/migrator_spec.rb index c59b152a982..0549b3128c7 100644 --- a/spec/lib/gitlab/hashed_storage/migrator_spec.rb +++ b/spec/lib/gitlab/hashed_storage/migrator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HashedStorage::Migrator, :redis do +RSpec.describe Gitlab::HashedStorage::Migrator, :redis do describe '#bulk_schedule_migration' do it 'schedules job to HashedStorage::MigratorWorker' do Sidekiq::Testing.fake! do diff --git a/spec/lib/gitlab/health_checks/db_check_spec.rb b/spec/lib/gitlab/health_checks/db_check_spec.rb index 3c1c1e3818d..60ebc596a0f 100644 --- a/spec/lib/gitlab/health_checks/db_check_spec.rb +++ b/spec/lib/gitlab/health_checks/db_check_spec.rb @@ -3,6 +3,6 @@ require 'spec_helper' require_relative './simple_check_shared' -describe Gitlab::HealthChecks::DbCheck do +RSpec.describe Gitlab::HealthChecks::DbCheck do include_examples 'simple_check', 'db_ping', 'Db', '1' end diff --git a/spec/lib/gitlab/health_checks/gitaly_check_spec.rb b/spec/lib/gitlab/health_checks/gitaly_check_spec.rb index d4ce16ce6fc..7c346e3eb69 100644 --- a/spec/lib/gitlab/health_checks/gitaly_check_spec.rb +++ b/spec/lib/gitlab/health_checks/gitaly_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HealthChecks::GitalyCheck do +RSpec.describe Gitlab::HealthChecks::GitalyCheck do let(:result_class) { Gitlab::HealthChecks::Result } let(:repository_storages) { ['default'] } diff --git a/spec/lib/gitlab/health_checks/master_check_spec.rb b/spec/lib/gitlab/health_checks/master_check_spec.rb index dcfc733d5ad..1c1efe178e2 100644 --- a/spec/lib/gitlab/health_checks/master_check_spec.rb +++ b/spec/lib/gitlab/health_checks/master_check_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require_relative './simple_check_shared' -describe Gitlab::HealthChecks::MasterCheck do +RSpec.describe Gitlab::HealthChecks::MasterCheck do let(:result_class) { Gitlab::HealthChecks::Result } before do diff --git a/spec/lib/gitlab/health_checks/probes/collection_spec.rb b/spec/lib/gitlab/health_checks/probes/collection_spec.rb index d8c411fa27b..03138e936aa 100644 --- a/spec/lib/gitlab/health_checks/probes/collection_spec.rb +++ b/spec/lib/gitlab/health_checks/probes/collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HealthChecks::Probes::Collection do +RSpec.describe Gitlab::HealthChecks::Probes::Collection do let(:readiness) { described_class.new(*checks) } describe '#execute' do @@ -47,6 +47,20 @@ describe Gitlab::HealthChecks::Probes::Collection do status: 'failed', message: 'check error') end end + + context 'when check raises exception not handled inside the check' do + before do + expect(Gitlab::HealthChecks::Redis::RedisCheck).to receive(:readiness).and_raise( + ::Redis::CannotConnectError, 'Redis down') + end + + it 'responds with failure including the exception info' do + expect(subject.http_status).to eq(500) + + expect(subject.json[:status]).to eq('failed') + expect(subject.json[:message]).to eq('Redis::CannotConnectError : Redis down') + end + end end context 'without checks' do diff --git a/spec/lib/gitlab/health_checks/puma_check_spec.rb b/spec/lib/gitlab/health_checks/puma_check_spec.rb index 93ef81978a8..0bd0965518f 100644 --- a/spec/lib/gitlab/health_checks/puma_check_spec.rb +++ b/spec/lib/gitlab/health_checks/puma_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HealthChecks::PumaCheck do +RSpec.describe Gitlab::HealthChecks::PumaCheck do let(:result_class) { Gitlab::HealthChecks::Result } let(:readiness) { described_class.readiness } let(:metrics) { described_class.metrics } diff --git a/spec/lib/gitlab/health_checks/redis/cache_check_spec.rb b/spec/lib/gitlab/health_checks/redis/cache_check_spec.rb index aaf474d7eeb..c44bd2ed585 100644 --- a/spec/lib/gitlab/health_checks/redis/cache_check_spec.rb +++ b/spec/lib/gitlab/health_checks/redis/cache_check_spec.rb @@ -3,6 +3,6 @@ require 'spec_helper' require_relative '../simple_check_shared' -describe Gitlab::HealthChecks::Redis::CacheCheck do +RSpec.describe Gitlab::HealthChecks::Redis::CacheCheck do include_examples 'simple_check', 'redis_cache_ping', 'RedisCache', 'PONG' end diff --git a/spec/lib/gitlab/health_checks/redis/queues_check_spec.rb b/spec/lib/gitlab/health_checks/redis/queues_check_spec.rb index f4b5e18da2a..3882e7db9d9 100644 --- a/spec/lib/gitlab/health_checks/redis/queues_check_spec.rb +++ b/spec/lib/gitlab/health_checks/redis/queues_check_spec.rb @@ -3,6 +3,6 @@ require 'spec_helper' require_relative '../simple_check_shared' -describe Gitlab::HealthChecks::Redis::QueuesCheck do +RSpec.describe Gitlab::HealthChecks::Redis::QueuesCheck do include_examples 'simple_check', 'redis_queues_ping', 'RedisQueues', 'PONG' end diff --git a/spec/lib/gitlab/health_checks/redis/redis_check_spec.rb b/spec/lib/gitlab/health_checks/redis/redis_check_spec.rb index ae7ee0d0859..43e890a6c4f 100644 --- a/spec/lib/gitlab/health_checks/redis/redis_check_spec.rb +++ b/spec/lib/gitlab/health_checks/redis/redis_check_spec.rb @@ -3,6 +3,6 @@ require 'spec_helper' require_relative '../simple_check_shared' -describe Gitlab::HealthChecks::Redis::RedisCheck do +RSpec.describe Gitlab::HealthChecks::Redis::RedisCheck do include_examples 'simple_check', 'redis_ping', 'Redis', 'PONG' end diff --git a/spec/lib/gitlab/health_checks/redis/shared_state_check_spec.rb b/spec/lib/gitlab/health_checks/redis/shared_state_check_spec.rb index 3e92b072254..25917741a1c 100644 --- a/spec/lib/gitlab/health_checks/redis/shared_state_check_spec.rb +++ b/spec/lib/gitlab/health_checks/redis/shared_state_check_spec.rb @@ -3,6 +3,6 @@ require 'spec_helper' require_relative '../simple_check_shared' -describe Gitlab::HealthChecks::Redis::SharedStateCheck do +RSpec.describe Gitlab::HealthChecks::Redis::SharedStateCheck do include_examples 'simple_check', 'redis_shared_state_ping', 'RedisSharedState', 'PONG' end diff --git a/spec/lib/gitlab/health_checks/simple_check_shared.rb b/spec/lib/gitlab/health_checks/simple_check_shared.rb index 3d0f9b3cf7a..591a11d5ab6 100644 --- a/spec/lib/gitlab/health_checks/simple_check_shared.rb +++ b/spec/lib/gitlab/health_checks/simple_check_shared.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -shared_context 'simple_check' do |metrics_prefix, check_name, success_result| +RSpec.shared_context 'simple_check' do |metrics_prefix, check_name, success_result| describe '#metrics' do subject { described_class.metrics } diff --git a/spec/lib/gitlab/health_checks/unicorn_check_spec.rb b/spec/lib/gitlab/health_checks/unicorn_check_spec.rb index 7c57b6f1ca5..1cc44016002 100644 --- a/spec/lib/gitlab/health_checks/unicorn_check_spec.rb +++ b/spec/lib/gitlab/health_checks/unicorn_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HealthChecks::UnicornCheck do +RSpec.describe Gitlab::HealthChecks::UnicornCheck do let(:result_class) { Gitlab::HealthChecks::Result } let(:readiness) { described_class.readiness } let(:metrics) { described_class.metrics } diff --git a/spec/lib/gitlab/highlight_spec.rb b/spec/lib/gitlab/highlight_spec.rb index 2140cbae488..9271b868e36 100644 --- a/spec/lib/gitlab/highlight_spec.rb +++ b/spec/lib/gitlab/highlight_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Highlight do +RSpec.describe Gitlab::Highlight do include RepoHelpers let(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/hook_data/base_builder_spec.rb b/spec/lib/gitlab/hook_data/base_builder_spec.rb index 4c3fd854c09..5d9d9fbffe2 100644 --- a/spec/lib/gitlab/hook_data/base_builder_spec.rb +++ b/spec/lib/gitlab/hook_data/base_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HookData::BaseBuilder do +RSpec.describe Gitlab::HookData::BaseBuilder do describe '#absolute_image_urls' do let(:subclass) do Class.new(described_class) do diff --git a/spec/lib/gitlab/hook_data/issuable_builder_spec.rb b/spec/lib/gitlab/hook_data/issuable_builder_spec.rb index afbc48e9ca2..50f3a4776be 100644 --- a/spec/lib/gitlab/hook_data/issuable_builder_spec.rb +++ b/spec/lib/gitlab/hook_data/issuable_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HookData::IssuableBuilder do +RSpec.describe Gitlab::HookData::IssuableBuilder do let_it_be(:user) { create(:user) } # This shared example requires a `builder` and `user` variable diff --git a/spec/lib/gitlab/hook_data/issue_builder_spec.rb b/spec/lib/gitlab/hook_data/issue_builder_spec.rb index 1f681faa8f7..8a2395d70b2 100644 --- a/spec/lib/gitlab/hook_data/issue_builder_spec.rb +++ b/spec/lib/gitlab/hook_data/issue_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HookData::IssueBuilder do +RSpec.describe Gitlab::HookData::IssueBuilder do let_it_be(:label) { create(:label) } let_it_be(:issue) { create(:labeled_issue, labels: [label], project: label.project) } let(:builder) { described_class.new(issue) } diff --git a/spec/lib/gitlab/hook_data/merge_request_builder_spec.rb b/spec/lib/gitlab/hook_data/merge_request_builder_spec.rb index 67fa0a7426a..fede7f273f1 100644 --- a/spec/lib/gitlab/hook_data/merge_request_builder_spec.rb +++ b/spec/lib/gitlab/hook_data/merge_request_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HookData::MergeRequestBuilder do +RSpec.describe Gitlab::HookData::MergeRequestBuilder do let_it_be(:merge_request) { create(:merge_request) } let(:builder) { described_class.new(merge_request) } diff --git a/spec/lib/gitlab/http_connection_adapter_spec.rb b/spec/lib/gitlab/http_connection_adapter_spec.rb index 1532fd1103e..389bc1a85f4 100644 --- a/spec/lib/gitlab/http_connection_adapter_spec.rb +++ b/spec/lib/gitlab/http_connection_adapter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HTTPConnectionAdapter do +RSpec.describe Gitlab::HTTPConnectionAdapter do include StubRequests describe '#connection' do diff --git a/spec/lib/gitlab/http_io_spec.rb b/spec/lib/gitlab/http_io_spec.rb index e53c361e169..5ba0cb5e686 100644 --- a/spec/lib/gitlab/http_io_spec.rb +++ b/spec/lib/gitlab/http_io_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HttpIO do +RSpec.describe Gitlab::HttpIO do include HttpIOHelpers let(:http_io) { described_class.new(url, size) } diff --git a/spec/lib/gitlab/http_spec.rb b/spec/lib/gitlab/http_spec.rb index 85cfc8e2852..09da94e7559 100644 --- a/spec/lib/gitlab/http_spec.rb +++ b/spec/lib/gitlab/http_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::HTTP do +RSpec.describe Gitlab::HTTP do include StubRequests context 'when allow_local_requests' do diff --git a/spec/lib/gitlab/i18n/metadata_entry_spec.rb b/spec/lib/gitlab/i18n/metadata_entry_spec.rb index 2d8bb538681..2f8816e62cc 100644 --- a/spec/lib/gitlab/i18n/metadata_entry_spec.rb +++ b/spec/lib/gitlab/i18n/metadata_entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::I18n::MetadataEntry do +RSpec.describe Gitlab::I18n::MetadataEntry do describe '#expected_forms' do it 'returns the number of plurals' do data = { diff --git a/spec/lib/gitlab/i18n/po_linter_spec.rb b/spec/lib/gitlab/i18n/po_linter_spec.rb index 2ab363ee45c..5dfc9d3613c 100644 --- a/spec/lib/gitlab/i18n/po_linter_spec.rb +++ b/spec/lib/gitlab/i18n/po_linter_spec.rb @@ -5,7 +5,7 @@ require 'simple_po_parser' # Disabling this cop to allow for multi-language examples in comments # rubocop:disable Style/AsciiComments -describe Gitlab::I18n::PoLinter do +RSpec.describe Gitlab::I18n::PoLinter do let(:linter) { described_class.new(po_path) } let(:po_path) { 'spec/fixtures/valid.po' } diff --git a/spec/lib/gitlab/i18n/translation_entry_spec.rb b/spec/lib/gitlab/i18n/translation_entry_spec.rb index 880da38052e..76879f75bec 100644 --- a/spec/lib/gitlab/i18n/translation_entry_spec.rb +++ b/spec/lib/gitlab/i18n/translation_entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::I18n::TranslationEntry do +RSpec.describe Gitlab::I18n::TranslationEntry do describe '#singular_translation' do it 'returns the normal `msgstr` for translations without plural' do data = { msgid: 'Hello world', msgstr: 'Bonjour monde' } diff --git a/spec/lib/gitlab/i18n_spec.rb b/spec/lib/gitlab/i18n_spec.rb index 2664423af88..592adadc362 100644 --- a/spec/lib/gitlab/i18n_spec.rb +++ b/spec/lib/gitlab/i18n_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::I18n do +RSpec.describe Gitlab::I18n do let(:user) { create(:user, preferred_language: 'es') } describe '.locale=' do diff --git a/spec/lib/gitlab/identifier_spec.rb b/spec/lib/gitlab/identifier_spec.rb index 9c7972d4bde..cc8d68e5c18 100644 --- a/spec/lib/gitlab/identifier_spec.rb +++ b/spec/lib/gitlab/identifier_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Identifier do +RSpec.describe Gitlab::Identifier do let(:identifier) do Class.new { include Gitlab::Identifier }.new end diff --git a/spec/lib/gitlab/import/database_helpers_spec.rb b/spec/lib/gitlab/import/database_helpers_spec.rb index 3ac34455177..d56e05df5d7 100644 --- a/spec/lib/gitlab/import/database_helpers_spec.rb +++ b/spec/lib/gitlab/import/database_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Import::DatabaseHelpers do +RSpec.describe Gitlab::Import::DatabaseHelpers do let(:database_helper) do Class.new do include Gitlab::Import::DatabaseHelpers diff --git a/spec/lib/gitlab/import/merge_request_creator_spec.rb b/spec/lib/gitlab/import/merge_request_creator_spec.rb index 48a57f9b251..9aedca40f1b 100644 --- a/spec/lib/gitlab/import/merge_request_creator_spec.rb +++ b/spec/lib/gitlab/import/merge_request_creator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Import::MergeRequestCreator do +RSpec.describe Gitlab::Import::MergeRequestCreator do let(:project) { create(:project, :repository) } subject { described_class.new(project) } diff --git a/spec/lib/gitlab/import/merge_request_helpers_spec.rb b/spec/lib/gitlab/import/merge_request_helpers_spec.rb index d81251c4a43..f858ab934bb 100644 --- a/spec/lib/gitlab/import/merge_request_helpers_spec.rb +++ b/spec/lib/gitlab/import/merge_request_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Import::MergeRequestHelpers, type: :helper do +RSpec.describe Gitlab::Import::MergeRequestHelpers, type: :helper do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/import/metrics_spec.rb b/spec/lib/gitlab/import/metrics_spec.rb index 0799d19fcef..0a912427014 100644 --- a/spec/lib/gitlab/import/metrics_spec.rb +++ b/spec/lib/gitlab/import/metrics_spec.rb @@ -2,55 +2,39 @@ require 'spec_helper' -describe Gitlab::Import::Metrics do - let(:importer_stub) do - Class.new do - prepend Gitlab::Import::Metrics - - Gitlab::Import::Metrics.measure :execute, metrics: { - importer_counter: { - type: :counter, - description: 'description' - }, - importer_histogram: { - type: :histogram, - labels: { importer: 'importer' }, - description: 'description' - } - } - - def execute - true - end +RSpec.describe Gitlab::Import::Metrics do + let(:importer) { :test_importer } + let(:project) { create(:project) } + let(:histogram) { double(:histogram) } + let(:counter) { double(:counter) } + + subject { described_class.new(importer, project) } + + describe '#report_import_time' do + before do + allow(Gitlab::Metrics).to receive(:counter) { counter } + allow(Gitlab::Metrics).to receive(:histogram) { histogram } + allow(counter).to receive(:increment) + allow(counter).to receive(:observe) end - end - - subject { importer_stub.new.execute } - describe '#execute' do - let(:counter) { double(:counter) } - let(:histogram) { double(:histogram) } + it 'emits importer metrics' do + expect(Gitlab::Metrics).to receive(:counter).with( + :test_importer_imported_projects_total, + 'The number of imported projects' + ) - it 'increments counter metric' do - expect(Gitlab::Metrics) - .to receive(:counter) - .with(:importer_counter, 'description') - .and_return(counter) + expect(Gitlab::Metrics).to receive(:histogram).with( + :test_importer_total_duration_seconds, + 'Total time spent importing projects, in seconds', + {}, + described_class::IMPORT_DURATION_BUCKETS + ) expect(counter).to receive(:increment) + expect(histogram).to receive(:observe).with({ importer: :test_importer }, anything) - subject - end - - it 'measures method duration and reports histogram metric' do - expect(Gitlab::Metrics) - .to receive(:histogram) - .with(:importer_histogram, 'description') - .and_return(histogram) - - expect(histogram).to receive(:observe).with({ importer: 'importer' }, anything) - - subject + subject.track_finished_import end end end diff --git a/spec/lib/gitlab/import/set_async_jid_spec.rb b/spec/lib/gitlab/import/set_async_jid_spec.rb index d2933cfd371..6931a7a953d 100644 --- a/spec/lib/gitlab/import/set_async_jid_spec.rb +++ b/spec/lib/gitlab/import/set_async_jid_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Import::SetAsyncJid do +RSpec.describe Gitlab::Import::SetAsyncJid do describe '.set_jid', :clean_gitlab_redis_shared_state do let(:project) { create(:project, :import_scheduled) } diff --git a/spec/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy_spec.rb b/spec/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy_spec.rb index 1631de393b5..fc794f11499 100644 --- a/spec/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy_spec.rb +++ b/spec/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::AfterExportStrategies::BaseAfterExportStrategy do +RSpec.describe Gitlab::ImportExport::AfterExportStrategies::BaseAfterExportStrategy do before do allow_next_instance_of(ProjectExportWorker) do |job| allow(job).to receive(:jid).and_return(SecureRandom.hex(8)) diff --git a/spec/lib/gitlab/import_export/after_export_strategies/web_upload_strategy_spec.rb b/spec/lib/gitlab/import_export/after_export_strategies/web_upload_strategy_spec.rb index 7792daed99c..38f1d48798b 100644 --- a/spec/lib/gitlab/import_export/after_export_strategies/web_upload_strategy_spec.rb +++ b/spec/lib/gitlab/import_export/after_export_strategies/web_upload_strategy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::AfterExportStrategies::WebUploadStrategy do +RSpec.describe Gitlab::ImportExport::AfterExportStrategies::WebUploadStrategy do include StubRequests before do diff --git a/spec/lib/gitlab/import_export/after_export_strategy_builder_spec.rb b/spec/lib/gitlab/import_export/after_export_strategy_builder_spec.rb index 9fe9e2eb73d..91a3dce0b4e 100644 --- a/spec/lib/gitlab/import_export/after_export_strategy_builder_spec.rb +++ b/spec/lib/gitlab/import_export/after_export_strategy_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::AfterExportStrategyBuilder do +RSpec.describe Gitlab::ImportExport::AfterExportStrategyBuilder do let!(:strategies_namespace) { 'Gitlab::ImportExport::AfterExportStrategies' } describe '.build!' do diff --git a/spec/lib/gitlab/import_export/all_models.yml b/spec/lib/gitlab/import_export/all_models.yml index ef9321dc1fc..02500778426 100644 --- a/spec/lib/gitlab/import_export/all_models.yml +++ b/spec/lib/gitlab/import_export/all_models.yml @@ -31,6 +31,8 @@ issues: - closed_by - epic_issue - epic +- feature_flag_issues +- feature_flags - designs - design_versions - description_versions @@ -95,6 +97,7 @@ snippets: - user_agent_detail - user_mentions - snippet_repository +- statistics releases: - author - project @@ -217,13 +220,15 @@ ci_pipelines: - parent_pipeline - downstream_bridges - job_artifacts -- vulnerabilities_occurrence_pipelines +- vulnerabilities_finding_pipelines - vulnerability_findings - pipeline_config - security_scans - daily_build_group_report_results - latest_builds - daily_report_results +- latest_builds_report_results +- messages ci_refs: - project - ci_pipelines @@ -317,6 +322,7 @@ project: - last_event - services - campfire_service +- confluence_service - discord_service - drone_ci_service - emails_on_push_service @@ -458,6 +464,8 @@ project: - vulnerability_feedback - vulnerability_identifiers - vulnerability_scanners +- dast_site_profiles +- dast_sites - operations_feature_flags - operations_feature_flags_client - operations_feature_flags_user_lists @@ -465,6 +473,7 @@ project: - prometheus_alert_events - self_managed_prometheus_alert_events - software_license_policies +- software_licenses - project_registry - packages - package_files @@ -505,6 +514,7 @@ project: - freeze_periods - webex_teams_service - build_report_results +- vulnerability_statistic award_emoji: - awardable - user @@ -569,6 +579,9 @@ self_managed_prometheus_alert_events: epic_issues: - issue - epic +feature_flag_issues: +- issue +- feature_flag tracing_setting: - project reviews: diff --git a/spec/lib/gitlab/import_export/attribute_cleaner_spec.rb b/spec/lib/gitlab/import_export/attribute_cleaner_spec.rb index 65e99c0c3b8..733be7fc226 100644 --- a/spec/lib/gitlab/import_export/attribute_cleaner_spec.rb +++ b/spec/lib/gitlab/import_export/attribute_cleaner_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::AttributeCleaner do +RSpec.describe Gitlab::ImportExport::AttributeCleaner do let(:relation_class) { double('relation_class').as_null_object } let(:unsafe_hash) do { diff --git a/spec/lib/gitlab/import_export/attribute_configuration_spec.rb b/spec/lib/gitlab/import_export/attribute_configuration_spec.rb index f97dafc6bf9..0581f07dd3f 100644 --- a/spec/lib/gitlab/import_export/attribute_configuration_spec.rb +++ b/spec/lib/gitlab/import_export/attribute_configuration_spec.rb @@ -9,7 +9,7 @@ require 'spec_helper' # to be included as part of the export, or blacklist them using the import_export.yml configuration file. # Likewise, new models added to import_export.yml, will need to be added with their correspondent attributes # to this spec. -describe 'Import/Export attribute configuration' do +RSpec.describe 'Import/Export attribute configuration' do include ConfigurationHelper let(:safe_attributes_file) { 'spec/lib/gitlab/import_export/safe_model_attributes.yml' } diff --git a/spec/lib/gitlab/import_export/attributes_finder_spec.rb b/spec/lib/gitlab/import_export/attributes_finder_spec.rb index 3cbc1375d6e..7f6ebf577af 100644 --- a/spec/lib/gitlab/import_export/attributes_finder_spec.rb +++ b/spec/lib/gitlab/import_export/attributes_finder_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::ImportExport::AttributesFinder do +RSpec.describe Gitlab::ImportExport::AttributesFinder do describe '#find_root' do subject { described_class.new(config: config).find_root(model_key) } diff --git a/spec/lib/gitlab/import_export/attributes_permitter_spec.rb b/spec/lib/gitlab/import_export/attributes_permitter_spec.rb index d6217811b9c..0c1b1cd74bf 100644 --- a/spec/lib/gitlab/import_export/attributes_permitter_spec.rb +++ b/spec/lib/gitlab/import_export/attributes_permitter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::AttributesPermitter do +RSpec.describe Gitlab::ImportExport::AttributesPermitter do let(:yml_config) do <<-EOF tree: diff --git a/spec/lib/gitlab/import_export/avatar_restorer_spec.rb b/spec/lib/gitlab/import_export/avatar_restorer_spec.rb index 662e1a5eaab..994132239b9 100644 --- a/spec/lib/gitlab/import_export/avatar_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/avatar_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::AvatarRestorer do +RSpec.describe Gitlab::ImportExport::AvatarRestorer do include UploadHelpers let(:shared) { project.import_export_shared } diff --git a/spec/lib/gitlab/import_export/avatar_saver_spec.rb b/spec/lib/gitlab/import_export/avatar_saver_spec.rb index d2349e47c0a..334d930c47c 100644 --- a/spec/lib/gitlab/import_export/avatar_saver_spec.rb +++ b/spec/lib/gitlab/import_export/avatar_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::AvatarSaver do +RSpec.describe Gitlab::ImportExport::AvatarSaver do let(:shared) { project.import_export_shared } let(:export_path) { "#{Dir.tmpdir}/project_tree_saver_spec" } let(:project_with_avatar) { create(:project, avatar: fixture_file_upload("spec/fixtures/dk.png", "image/png")) } diff --git a/spec/lib/gitlab/import_export/base/object_builder_spec.rb b/spec/lib/gitlab/import_export/base/object_builder_spec.rb index e5242ae0bfc..d560c8ea5a7 100644 --- a/spec/lib/gitlab/import_export/base/object_builder_spec.rb +++ b/spec/lib/gitlab/import_export/base/object_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Base::ObjectBuilder do +RSpec.describe Gitlab::ImportExport::Base::ObjectBuilder do let(:project) do create(:project, :repository, :builds_disabled, diff --git a/spec/lib/gitlab/import_export/base/relation_factory_spec.rb b/spec/lib/gitlab/import_export/base/relation_factory_spec.rb index 50d93763ad6..09e6e5a03bb 100644 --- a/spec/lib/gitlab/import_export/base/relation_factory_spec.rb +++ b/spec/lib/gitlab/import_export/base/relation_factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Base::RelationFactory do +RSpec.describe Gitlab::ImportExport::Base::RelationFactory do let(:user) { create(:admin) } let(:project) { create(:project) } let(:members_mapper) { double('members_mapper').as_null_object } diff --git a/spec/lib/gitlab/import_export/command_line_util_spec.rb b/spec/lib/gitlab/import_export/command_line_util_spec.rb index 8e5e0aefac0..b00a2597681 100644 --- a/spec/lib/gitlab/import_export/command_line_util_spec.rb +++ b/spec/lib/gitlab/import_export/command_line_util_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::CommandLineUtil do +RSpec.describe Gitlab::ImportExport::CommandLineUtil do include ExportFileHelper let(:path) { "#{Dir.tmpdir}/symlink_test" } diff --git a/spec/lib/gitlab/import_export/config_spec.rb b/spec/lib/gitlab/import_export/config_spec.rb index f09a29b84db..40cf75779b6 100644 --- a/spec/lib/gitlab/import_export/config_spec.rb +++ b/spec/lib/gitlab/import_export/config_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::ImportExport::Config do +RSpec.describe Gitlab::ImportExport::Config do let(:yaml_file) { described_class.new } describe '#to_h' do diff --git a/spec/lib/gitlab/import_export/design_repo_restorer_spec.rb b/spec/lib/gitlab/import_export/design_repo_restorer_spec.rb index 5662b8af280..b311a02833c 100644 --- a/spec/lib/gitlab/import_export/design_repo_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/design_repo_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::DesignRepoRestorer do +RSpec.describe Gitlab::ImportExport::DesignRepoRestorer do include GitHelpers describe 'bundle a design Git repo' do diff --git a/spec/lib/gitlab/import_export/design_repo_saver_spec.rb b/spec/lib/gitlab/import_export/design_repo_saver_spec.rb index bff48e8b52a..2575d209db5 100644 --- a/spec/lib/gitlab/import_export/design_repo_saver_spec.rb +++ b/spec/lib/gitlab/import_export/design_repo_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::DesignRepoSaver do +RSpec.describe Gitlab::ImportExport::DesignRepoSaver do describe 'bundle a design Git repo' do let_it_be(:user) { create(:user) } let_it_be(:design) { create(:design, :with_file, versions_count: 1) } diff --git a/spec/lib/gitlab/import_export/error_spec.rb b/spec/lib/gitlab/import_export/error_spec.rb index 067f7049097..015133a399b 100644 --- a/spec/lib/gitlab/import_export/error_spec.rb +++ b/spec/lib/gitlab/import_export/error_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Error do +RSpec.describe Gitlab::ImportExport::Error do describe '.permission_error' do subject(:error) do described_class.permission_error(user, importable) diff --git a/spec/lib/gitlab/import_export/fast_hash_serializer_spec.rb b/spec/lib/gitlab/import_export/fast_hash_serializer_spec.rb index 916ed692a05..5b6be0b3198 100644 --- a/spec/lib/gitlab/import_export/fast_hash_serializer_spec.rb +++ b/spec/lib/gitlab/import_export/fast_hash_serializer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::FastHashSerializer do +RSpec.describe Gitlab::ImportExport::FastHashSerializer do # FastHashSerializer#execute generates the hash which is not easily accessible # and includes `JSONBatchRelation` items which are serialized at this point. # Wrapping the result into JSON generating/parsing is for making @@ -175,14 +175,6 @@ describe Gitlab::ImportExport::FastHashSerializer do expect(subject['merge_requests'].first['resource_label_events']).not_to be_empty end - it 'saves the correct service type' do - expect(subject['services'].first['type']).to eq('CustomIssueTrackerService') - end - - it 'saves the properties for a service' do - expect(subject['services'].first['properties']).to eq('one' => 'value') - end - it 'has project feature' do project_feature = subject['project_feature'] expect(project_feature).not_to be_empty diff --git a/spec/lib/gitlab/import_export/file_importer_spec.rb b/spec/lib/gitlab/import_export/file_importer_spec.rb index 7c54c5f2da1..47485cc7edb 100644 --- a/spec/lib/gitlab/import_export/file_importer_spec.rb +++ b/spec/lib/gitlab/import_export/file_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::FileImporter do +RSpec.describe Gitlab::ImportExport::FileImporter do include ExportFileHelper let(:shared) { Gitlab::ImportExport::Shared.new(nil) } diff --git a/spec/lib/gitlab/import_export/fork_spec.rb b/spec/lib/gitlab/import_export/fork_spec.rb index bb79331efac..ef7394053b9 100644 --- a/spec/lib/gitlab/import_export/fork_spec.rb +++ b/spec/lib/gitlab/import_export/fork_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'forked project import' do +RSpec.describe 'forked project import' do include ProjectForksHelper let(:user) { create(:user) } diff --git a/spec/lib/gitlab/import_export/group/legacy_tree_restorer_spec.rb b/spec/lib/gitlab/import_export/group/legacy_tree_restorer_spec.rb index 4c926da1436..bfcd4994995 100644 --- a/spec/lib/gitlab/import_export/group/legacy_tree_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/group/legacy_tree_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Group::LegacyTreeRestorer do +RSpec.describe Gitlab::ImportExport::Group::LegacyTreeRestorer do include ImportExport::CommonUtil let(:shared) { Gitlab::ImportExport::Shared.new(group) } diff --git a/spec/lib/gitlab/import_export/group/legacy_tree_saver_spec.rb b/spec/lib/gitlab/import_export/group/legacy_tree_saver_spec.rb index a0490c255aa..6b324b952dc 100644 --- a/spec/lib/gitlab/import_export/group/legacy_tree_saver_spec.rb +++ b/spec/lib/gitlab/import_export/group/legacy_tree_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Group::LegacyTreeSaver do +RSpec.describe Gitlab::ImportExport::Group::LegacyTreeSaver do describe 'saves the group tree into a json object' do let(:shared) { Gitlab::ImportExport::Shared.new(group) } let(:group_tree_saver) { described_class.new(group: group, current_user: user, shared: shared) } diff --git a/spec/lib/gitlab/import_export/group/object_builder_spec.rb b/spec/lib/gitlab/import_export/group/object_builder_spec.rb index 781670b0aa5..028bd5463a1 100644 --- a/spec/lib/gitlab/import_export/group/object_builder_spec.rb +++ b/spec/lib/gitlab/import_export/group/object_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Group::ObjectBuilder do +RSpec.describe Gitlab::ImportExport::Group::ObjectBuilder do let(:group) { create(:group) } let(:base_attributes) do { diff --git a/spec/lib/gitlab/import_export/group/relation_factory_spec.rb b/spec/lib/gitlab/import_export/group/relation_factory_spec.rb index 332648d5c89..eb9a3fa9bd8 100644 --- a/spec/lib/gitlab/import_export/group/relation_factory_spec.rb +++ b/spec/lib/gitlab/import_export/group/relation_factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Group::RelationFactory do +RSpec.describe Gitlab::ImportExport::Group::RelationFactory do let(:group) { create(:group) } let(:members_mapper) { double('members_mapper').as_null_object } let(:user) { create(:admin) } diff --git a/spec/lib/gitlab/import_export/group/tree_restorer_spec.rb b/spec/lib/gitlab/import_export/group/tree_restorer_spec.rb index 327f36c664e..6cc16ee9cbb 100644 --- a/spec/lib/gitlab/import_export/group/tree_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/group/tree_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Group::TreeRestorer do +RSpec.describe Gitlab::ImportExport::Group::TreeRestorer do include ImportExport::CommonUtil describe 'restore group tree' do diff --git a/spec/lib/gitlab/import_export/group/tree_saver_spec.rb b/spec/lib/gitlab/import_export/group/tree_saver_spec.rb index 06e8484a3cb..908896e4891 100644 --- a/spec/lib/gitlab/import_export/group/tree_saver_spec.rb +++ b/spec/lib/gitlab/import_export/group/tree_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Group::TreeSaver do +RSpec.describe Gitlab::ImportExport::Group::TreeSaver do describe 'saves the group tree into a json object' do let_it_be(:user) { create(:user) } let_it_be(:group) { setup_groups } diff --git a/spec/lib/gitlab/import_export/hash_util_spec.rb b/spec/lib/gitlab/import_export/hash_util_spec.rb index b97c6665d0e..467342e6e96 100644 --- a/spec/lib/gitlab/import_export/hash_util_spec.rb +++ b/spec/lib/gitlab/import_export/hash_util_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::HashUtil do +RSpec.describe Gitlab::ImportExport::HashUtil do let(:stringified_array) { [{ 'test' => 1 }] } let(:stringified_array_with_date) { [{ 'test_date' => '2016-04-06 06:17:44 +0200' }] } diff --git a/spec/lib/gitlab/import_export/import_export_equivalence_spec.rb b/spec/lib/gitlab/import_export/import_export_equivalence_spec.rb index 95df9cd0e6e..18f2e8f80d7 100644 --- a/spec/lib/gitlab/import_export/import_export_equivalence_spec.rb +++ b/spec/lib/gitlab/import_export/import_export_equivalence_spec.rb @@ -13,7 +13,7 @@ require 'spec_helper' # - randomly generated fields like tokens # # as these are expected to change between import/export cycles. -describe Gitlab::ImportExport do +RSpec.describe Gitlab::ImportExport do include ImportExport::CommonUtil include ConfigurationHelper include ImportExport::ProjectTreeExpectations diff --git a/spec/lib/gitlab/import_export/import_export_spec.rb b/spec/lib/gitlab/import_export/import_export_spec.rb index 300ba66ee5b..62b4717fc96 100644 --- a/spec/lib/gitlab/import_export/import_export_spec.rb +++ b/spec/lib/gitlab/import_export/import_export_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport do +RSpec.describe Gitlab::ImportExport do describe 'export filename' do let(:group) { create(:group, :nested) } let(:project) { create(:project, :public, path: 'project-path', namespace: group) } diff --git a/spec/lib/gitlab/import_export/import_failure_service_spec.rb b/spec/lib/gitlab/import_export/import_failure_service_spec.rb index 324328181e4..c8bb067d40c 100644 --- a/spec/lib/gitlab/import_export/import_failure_service_spec.rb +++ b/spec/lib/gitlab/import_export/import_failure_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::ImportFailureService do +RSpec.describe Gitlab::ImportExport::ImportFailureService do let(:importable) { create(:project, :builds_enabled, :issues_disabled, name: 'project', path: 'project') } let(:label) { create(:label) } let(:subject) { described_class.new(importable) } diff --git a/spec/lib/gitlab/import_export/import_test_coverage_spec.rb b/spec/lib/gitlab/import_export/import_test_coverage_spec.rb index c5a7327332e..9737a0f39fc 100644 --- a/spec/lib/gitlab/import_export/import_test_coverage_spec.rb +++ b/spec/lib/gitlab/import_export/import_test_coverage_spec.rb @@ -7,7 +7,7 @@ require 'spec_helper' # Fixture JSONs we use for testing Import such as # `spec/fixtures/lib/gitlab/import_export/complex/project.json` # should include these relations being non-empty. -describe 'Test coverage of the Project Import' do +RSpec.describe 'Test coverage of the Project Import' do include ConfigurationHelper # `muted_relations` is a technical debt. diff --git a/spec/lib/gitlab/import_export/importer_spec.rb b/spec/lib/gitlab/import_export/importer_spec.rb index 494f7e3a00d..dc44296321c 100644 --- a/spec/lib/gitlab/import_export/importer_spec.rb +++ b/spec/lib/gitlab/import_export/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Importer do +RSpec.describe Gitlab::ImportExport::Importer do let(:user) { create(:user) } let(:test_path) { "#{Dir.tmpdir}/importer_spec" } let(:shared) { project.import_export_shared } diff --git a/spec/lib/gitlab/import_export/json/legacy_reader/file_spec.rb b/spec/lib/gitlab/import_export/json/legacy_reader/file_spec.rb index 99932404fd9..9c7f41cbb89 100644 --- a/spec/lib/gitlab/import_export/json/legacy_reader/file_spec.rb +++ b/spec/lib/gitlab/import_export/json/legacy_reader/file_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require_relative 'shared_example.rb' -describe Gitlab::ImportExport::JSON::LegacyReader::File do +RSpec.describe Gitlab::ImportExport::JSON::LegacyReader::File do it_behaves_like 'import/export json legacy reader' do let(:valid_path) { 'spec/fixtures/lib/gitlab/import_export/light/project.json' } let(:data) { valid_path } diff --git a/spec/lib/gitlab/import_export/json/legacy_reader/hash_spec.rb b/spec/lib/gitlab/import_export/json/legacy_reader/hash_spec.rb index e793dc7339d..d0899accf59 100644 --- a/spec/lib/gitlab/import_export/json/legacy_reader/hash_spec.rb +++ b/spec/lib/gitlab/import_export/json/legacy_reader/hash_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require_relative 'shared_example.rb' -describe Gitlab::ImportExport::JSON::LegacyReader::Hash do +RSpec.describe Gitlab::ImportExport::JSON::LegacyReader::Hash do it_behaves_like 'import/export json legacy reader' do let(:path) { 'spec/fixtures/lib/gitlab/import_export/light/project.json' } diff --git a/spec/lib/gitlab/import_export/json/legacy_writer_spec.rb b/spec/lib/gitlab/import_export/json/legacy_writer_spec.rb index 1f39b26e46a..eb7a2d4aa8b 100644 --- a/spec/lib/gitlab/import_export/json/legacy_writer_spec.rb +++ b/spec/lib/gitlab/import_export/json/legacy_writer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::JSON::LegacyWriter do +RSpec.describe Gitlab::ImportExport::JSON::LegacyWriter do let(:path) { "#{Dir.tmpdir}/legacy_writer_spec/test.json" } subject do diff --git a/spec/lib/gitlab/import_export/json/ndjson_reader_spec.rb b/spec/lib/gitlab/import_export/json/ndjson_reader_spec.rb index 34e8b1ddd59..a347d835428 100644 --- a/spec/lib/gitlab/import_export/json/ndjson_reader_spec.rb +++ b/spec/lib/gitlab/import_export/json/ndjson_reader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::JSON::NdjsonReader do +RSpec.describe Gitlab::ImportExport::JSON::NdjsonReader do include ImportExport::CommonUtil let(:fixture) { 'spec/fixtures/lib/gitlab/import_export/light/tree' } diff --git a/spec/lib/gitlab/import_export/json/ndjson_writer_spec.rb b/spec/lib/gitlab/import_export/json/ndjson_writer_spec.rb index bae3672474c..0af74dee604 100644 --- a/spec/lib/gitlab/import_export/json/ndjson_writer_spec.rb +++ b/spec/lib/gitlab/import_export/json/ndjson_writer_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::ImportExport::JSON::NdjsonWriter do +RSpec.describe Gitlab::ImportExport::JSON::NdjsonWriter do include ImportExport::CommonUtil let(:path) { "#{Dir.tmpdir}/ndjson_writer_spec/tree" } diff --git a/spec/lib/gitlab/import_export/json/streaming_serializer_spec.rb b/spec/lib/gitlab/import_export/json/streaming_serializer_spec.rb index 30f8280fda3..eb6b07ce02f 100644 --- a/spec/lib/gitlab/import_export/json/streaming_serializer_spec.rb +++ b/spec/lib/gitlab/import_export/json/streaming_serializer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::JSON::StreamingSerializer do +RSpec.describe Gitlab::ImportExport::JSON::StreamingSerializer do let_it_be(:user) { create(:user) } let_it_be(:release) { create(:release) } let_it_be(:group) { create(:group) } @@ -61,6 +61,20 @@ describe Gitlab::ImportExport::JSON::StreamingSerializer do subject.execute end + + context 'relation ordering' do + before do + create_list(:issue, 5, project: exportable) + end + + it 'orders exported issues by primary key' do + expected_issues = exportable.issues.reorder(:id).map(&:to_json) + + expect(json_writer).to receive(:write_relation_array).with(exportable_path, :issues, expected_issues) + + subject.execute + end + end end context 'with single relation' do diff --git a/spec/lib/gitlab/import_export/legacy_relation_tree_saver_spec.rb b/spec/lib/gitlab/import_export/legacy_relation_tree_saver_spec.rb index 6562aa5b8a6..454cc74b9d4 100644 --- a/spec/lib/gitlab/import_export/legacy_relation_tree_saver_spec.rb +++ b/spec/lib/gitlab/import_export/legacy_relation_tree_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::LegacyRelationTreeSaver do +RSpec.describe Gitlab::ImportExport::LegacyRelationTreeSaver do let(:exportable) { create(:group) } let(:relation_tree_saver) { described_class.new } let(:tree) { {} } diff --git a/spec/lib/gitlab/import_export/lfs_restorer_spec.rb b/spec/lib/gitlab/import_export/lfs_restorer_spec.rb index a932dc3ee4e..a9f7fb72612 100644 --- a/spec/lib/gitlab/import_export/lfs_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/lfs_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::LfsRestorer do +RSpec.describe Gitlab::ImportExport::LfsRestorer do include UploadHelpers let(:export_path) { "#{Dir.tmpdir}/lfs_object_restorer_spec" } diff --git a/spec/lib/gitlab/import_export/lfs_saver_spec.rb b/spec/lib/gitlab/import_export/lfs_saver_spec.rb index e9d06573e70..db76eb9538b 100644 --- a/spec/lib/gitlab/import_export/lfs_saver_spec.rb +++ b/spec/lib/gitlab/import_export/lfs_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::LfsSaver do +RSpec.describe Gitlab::ImportExport::LfsSaver do let(:shared) { project.import_export_shared } let(:export_path) { "#{Dir.tmpdir}/project_tree_saver_spec" } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/import_export/members_mapper_spec.rb b/spec/lib/gitlab/import_export/members_mapper_spec.rb index 61e893bfb3c..9755e322221 100644 --- a/spec/lib/gitlab/import_export/members_mapper_spec.rb +++ b/spec/lib/gitlab/import_export/members_mapper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::MembersMapper do +RSpec.describe Gitlab::ImportExport::MembersMapper do describe 'map members' do shared_examples 'imports exported members' do let(:user) { create(:admin) } diff --git a/spec/lib/gitlab/import_export/merge_request_parser_spec.rb b/spec/lib/gitlab/import_export/merge_request_parser_spec.rb index 0cdb3c43992..c558c12f581 100644 --- a/spec/lib/gitlab/import_export/merge_request_parser_spec.rb +++ b/spec/lib/gitlab/import_export/merge_request_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::MergeRequestParser do +RSpec.describe Gitlab::ImportExport::MergeRequestParser do include ProjectForksHelper let(:user) { create(:user) } diff --git a/spec/lib/gitlab/import_export/model_configuration_spec.rb b/spec/lib/gitlab/import_export/model_configuration_spec.rb index cfbfe244988..34591122a97 100644 --- a/spec/lib/gitlab/import_export/model_configuration_spec.rb +++ b/spec/lib/gitlab/import_export/model_configuration_spec.rb @@ -5,7 +5,7 @@ require 'spec_helper' # Part of the test security suite for the Import/Export feature # Finds if a new model has been added that can potentially be part of the Import/Export # If it finds a new model, it will show a +failure_message+ with the options available. -describe 'Import/Export model configuration' do +RSpec.describe 'Import/Export model configuration' do include ConfigurationHelper let(:all_models_yml) { 'spec/lib/gitlab/import_export/all_models.yml' } diff --git a/spec/lib/gitlab/import_export/project/export_task_spec.rb b/spec/lib/gitlab/import_export/project/export_task_spec.rb index dc8eb54dc14..1048379a5d6 100644 --- a/spec/lib/gitlab/import_export/project/export_task_spec.rb +++ b/spec/lib/gitlab/import_export/project/export_task_spec.rb @@ -2,7 +2,7 @@ require 'rake_helper' -describe Gitlab::ImportExport::Project::ExportTask do +RSpec.describe Gitlab::ImportExport::Project::ExportTask do let_it_be(:username) { 'root' } let(:namespace_path) { username } let_it_be(:user) { create(:user, username: username) } diff --git a/spec/lib/gitlab/import_export/project/import_task_spec.rb b/spec/lib/gitlab/import_export/project/import_task_spec.rb index 7c11161aaa7..90f4501acdc 100644 --- a/spec/lib/gitlab/import_export/project/import_task_spec.rb +++ b/spec/lib/gitlab/import_export/project/import_task_spec.rb @@ -2,7 +2,7 @@ require 'rake_helper' -describe Gitlab::ImportExport::Project::ImportTask, :request_store do +RSpec.describe Gitlab::ImportExport::Project::ImportTask, :request_store do let(:username) { 'root' } let(:namespace_path) { username } let!(:user) { create(:user, username: username) } diff --git a/spec/lib/gitlab/import_export/project/object_builder_spec.rb b/spec/lib/gitlab/import_export/project/object_builder_spec.rb index c9d1410400a..20d882c82be 100644 --- a/spec/lib/gitlab/import_export/project/object_builder_spec.rb +++ b/spec/lib/gitlab/import_export/project/object_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Project::ObjectBuilder do +RSpec.describe Gitlab::ImportExport::Project::ObjectBuilder do let!(:group) { create(:group, :private) } let!(:subgroup) { create(:group, :private, parent: group) } let!(:project) do diff --git a/spec/lib/gitlab/import_export/project/relation_factory_spec.rb b/spec/lib/gitlab/import_export/project/relation_factory_spec.rb index 3339129cb8f..31cf2362628 100644 --- a/spec/lib/gitlab/import_export/project/relation_factory_spec.rb +++ b/spec/lib/gitlab/import_export/project/relation_factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Project::RelationFactory do +RSpec.describe Gitlab::ImportExport::Project::RelationFactory do let(:group) { create(:group) } let(:project) { create(:project, :repository, group: group) } let(:members_mapper) { double('members_mapper').as_null_object } diff --git a/spec/lib/gitlab/import_export/project/tree_restorer_spec.rb b/spec/lib/gitlab/import_export/project/tree_restorer_spec.rb index 867dc37c5c5..6d5604dc40f 100644 --- a/spec/lib/gitlab/import_export/project/tree_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/project/tree_restorer_spec.rb @@ -6,7 +6,7 @@ def match_mr1_note(content_regex) MergeRequest.find_by(title: 'MR1').notes.select { |n| n.note.match(/#{content_regex}/)}.first end -describe Gitlab::ImportExport::Project::TreeRestorer do +RSpec.describe Gitlab::ImportExport::Project::TreeRestorer do include ImportExport::CommonUtil using RSpec::Parameterized::TableSyntax @@ -291,10 +291,6 @@ describe Gitlab::ImportExport::Project::TreeRestorer do expect(@project.auto_devops.deploy_strategy).to eq('continuous') end - it 'restores the correct service' do - expect(CustomIssueTrackerService.first).not_to be_nil - end - it 'restores zoom meetings' do meetings = @project.issues.first.zoom_meetings @@ -553,8 +549,7 @@ describe Gitlab::ImportExport::Project::TreeRestorer do labels: 2, label_with_priorities: 'A project label', milestones: 1, - first_issue_labels: 1, - services: 1 + first_issue_labels: 1 end context 'when there is an existing build with build token' do @@ -637,7 +632,6 @@ describe Gitlab::ImportExport::Project::TreeRestorer do label_with_priorities: 'A project label', milestones: 1, first_issue_labels: 1, - services: 1, import_failures: 1 it 'records the failures in the database' do @@ -757,18 +751,6 @@ describe Gitlab::ImportExport::Project::TreeRestorer do setup_reader(reader) end - it 'does not import any templated services' do - expect(restored_project_json).to eq(true) - - expect(project.services.where(template: true).count).to eq(0) - end - - it 'does not import any instance services' do - expect(restored_project_json).to eq(true) - - expect(project.services.where(instance: true).count).to eq(0) - end - it 'imports labels' do create(:group_label, name: 'Another label', group: project.group) @@ -972,7 +954,6 @@ describe Gitlab::ImportExport::Project::TreeRestorer do label_with_priorities: nil, milestones: 1, first_issue_labels: 0, - services: 0, import_failures: 1 it 'records the failures in the database' do diff --git a/spec/lib/gitlab/import_export/project/tree_saver_spec.rb b/spec/lib/gitlab/import_export/project/tree_saver_spec.rb index 533d1097928..40c103eeda6 100644 --- a/spec/lib/gitlab/import_export/project/tree_saver_spec.rb +++ b/spec/lib/gitlab/import_export/project/tree_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Project::TreeSaver do +RSpec.describe Gitlab::ImportExport::Project::TreeSaver do let_it_be(:export_path) { "#{Dir.tmpdir}/project_tree_saver_spec" } let_it_be(:exportable_path) { 'project' } @@ -223,18 +223,6 @@ describe Gitlab::ImportExport::Project::TreeSaver do it { is_expected.not_to be_empty } end - context 'with services' do - let(:relation_name) { :services } - - it 'saves the correct service type' do - expect(subject.first['type']).to eq('CustomIssueTrackerService') - end - - it 'saves the properties for a service' do - expect(subject.first['properties']).to eq('one' => 'value') - end - end - context 'with project_feature' do let(:relation_name) { :project_feature } @@ -453,7 +441,6 @@ describe Gitlab::ImportExport::Project::TreeSaver do create(:resource_label_event, label: group_label, merge_request: merge_request) create(:event, :created, target: milestone, project: project, author: user) - create(:service, project: project, type: 'CustomIssueTrackerService', category: 'issue_tracker', properties: { one: 'value' }) create(:project_custom_attribute, project: project) create(:project_custom_attribute, project: project) diff --git a/spec/lib/gitlab/import_export/reader_spec.rb b/spec/lib/gitlab/import_export/reader_spec.rb index e37ad281eb5..8828c7ceb62 100644 --- a/spec/lib/gitlab/import_export/reader_spec.rb +++ b/spec/lib/gitlab/import_export/reader_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::Reader do +RSpec.describe Gitlab::ImportExport::Reader do let(:shared) { Gitlab::ImportExport::Shared.new(nil) } describe '#project_tree' do diff --git a/spec/lib/gitlab/import_export/references_configuration_spec.rb b/spec/lib/gitlab/import_export/references_configuration_spec.rb index 91cf9f964c0..2934d0059ee 100644 --- a/spec/lib/gitlab/import_export/references_configuration_spec.rb +++ b/spec/lib/gitlab/import_export/references_configuration_spec.rb @@ -9,7 +9,7 @@ require 'spec_helper' # or to be blacklisted by using the import_export.yml configuration file. # Likewise, new models added to import_export.yml, will need to be added with their correspondent relations # to this spec. -describe 'Import/Export Project configuration' do +RSpec.describe 'Import/Export Project configuration' do include ConfigurationHelper where(:relation_path, :relation_name) do diff --git a/spec/lib/gitlab/import_export/relation_tree_restorer_spec.rb b/spec/lib/gitlab/import_export/relation_tree_restorer_spec.rb index 8fe419da450..ddc96b83208 100644 --- a/spec/lib/gitlab/import_export/relation_tree_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/relation_tree_restorer_spec.rb @@ -9,7 +9,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::RelationTreeRestorer do +RSpec.describe Gitlab::ImportExport::RelationTreeRestorer do include ImportExport::CommonUtil let(:user) { create(:user) } diff --git a/spec/lib/gitlab/import_export/repo_restorer_spec.rb b/spec/lib/gitlab/import_export/repo_restorer_spec.rb index d5839589633..ace4449042e 100644 --- a/spec/lib/gitlab/import_export/repo_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/repo_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::RepoRestorer do +RSpec.describe Gitlab::ImportExport::RepoRestorer do include GitHelpers describe 'bundle a project Git repo' do diff --git a/spec/lib/gitlab/import_export/repo_saver_spec.rb b/spec/lib/gitlab/import_export/repo_saver_spec.rb index a95d661ec3c..73d51000c67 100644 --- a/spec/lib/gitlab/import_export/repo_saver_spec.rb +++ b/spec/lib/gitlab/import_export/repo_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::RepoSaver do +RSpec.describe Gitlab::ImportExport::RepoSaver do describe 'bundle a project Git repo' do let_it_be(:user) { create(:user) } let!(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/import_export/safe_model_attributes.yml b/spec/lib/gitlab/import_export/safe_model_attributes.yml index 0d112bfdb2a..2d313b4dcad 100644 --- a/spec/lib/gitlab/import_export/safe_model_attributes.yml +++ b/spec/lib/gitlab/import_export/safe_model_attributes.yml @@ -461,36 +461,6 @@ DeployKey: - public - can_push - last_used_at -Service: -- id -- type -- title -- project_id -- created_at -- updated_at -- active -- properties -- template -- instance -- alert_events -- push_events -- issues_events -- commit_events -- merge_requests_events -- tag_push_events -- note_events -- pipeline_events -- job_events -- comment_on_event_enabled -- comment_detail -- category -- default -- wiki_page_events -- confidential_issues_events -- confidential_note_events -- deployment_events -- description -- inherit_from_id ProjectHook: - id - url @@ -618,6 +588,7 @@ ProtectedBranch::PushAccessLevel: - updated_at - user_id - group_id +- deploy_key_id ProtectedBranch::UnprotectAccessLevel: - id - protected_branch_id @@ -705,6 +676,7 @@ ProjectCiCdSetting: - group_runners_enabled ProjectSetting: - allow_merge_on_skipped_pipeline +- has_confluence ProtectedEnvironment: - id - project_id diff --git a/spec/lib/gitlab/import_export/saver_spec.rb b/spec/lib/gitlab/import_export/saver_spec.rb index 18e9d7da32d..865c7e57b5a 100644 --- a/spec/lib/gitlab/import_export/saver_spec.rb +++ b/spec/lib/gitlab/import_export/saver_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'fileutils' -describe Gitlab::ImportExport::Saver do +RSpec.describe Gitlab::ImportExport::Saver do let!(:project) { create(:project, :public, name: 'project') } let(:base_path) { "#{Dir.tmpdir}/project_tree_saver_spec" } let(:export_path) { "#{base_path}/project_tree_saver_spec/export" } diff --git a/spec/lib/gitlab/import_export/shared_spec.rb b/spec/lib/gitlab/import_export/shared_spec.rb index 8c16243576d..22f2d4c5077 100644 --- a/spec/lib/gitlab/import_export/shared_spec.rb +++ b/spec/lib/gitlab/import_export/shared_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'fileutils' -describe Gitlab::ImportExport::Shared do +RSpec.describe Gitlab::ImportExport::Shared do let(:project) { build(:project) } subject { project.import_export_shared } diff --git a/spec/lib/gitlab/import_export/snippet_repo_restorer_spec.rb b/spec/lib/gitlab/import_export/snippet_repo_restorer_spec.rb index 43c4b164b2d..fe934cadedd 100644 --- a/spec/lib/gitlab/import_export/snippet_repo_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/snippet_repo_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::SnippetRepoRestorer do +RSpec.describe Gitlab::ImportExport::SnippetRepoRestorer do let_it_be(:user) { create(:user) } let(:project) { create(:project, namespace: user.namespace) } @@ -35,6 +35,12 @@ describe Gitlab::ImportExport::SnippetRepoRestorer do end end + it 'does not call snippet update statistics service' do + expect(Snippets::UpdateStatisticsService).not_to receive(:new).with(snippet) + + restorer.restore + end + context 'when the repository creation fails' do it 'returns false' do allow_any_instance_of(Gitlab::BackgroundMigration::BackfillSnippetRepositories).to receive(:perform_by_ids).and_return(nil) @@ -66,6 +72,10 @@ describe Gitlab::ImportExport::SnippetRepoRestorer do before do expect(exporter.save).to be_truthy + + allow_next_instance_of(Snippets::RepositoryValidationService) do |instance| + allow(instance).to receive(:execute).and_return(ServiceResponse.success) + end end context 'when it is valid' do @@ -115,5 +125,19 @@ describe Gitlab::ImportExport::SnippetRepoRestorer do end end end + + it 'refreshes snippet statistics' do + expect(snippet.statistics.commit_count).to be_zero + expect(snippet.statistics.file_count).to be_zero + expect(snippet.statistics.repository_size).to be_zero + + expect(Snippets::UpdateStatisticsService).to receive(:new).with(snippet).and_call_original + + restorer.restore + + expect(snippet.statistics.commit_count).not_to be_zero + expect(snippet.statistics.file_count).not_to be_zero + expect(snippet.statistics.repository_size).not_to be_zero + end end end diff --git a/spec/lib/gitlab/import_export/snippet_repo_saver_spec.rb b/spec/lib/gitlab/import_export/snippet_repo_saver_spec.rb index 7ad1ff213a1..323ed9a746e 100644 --- a/spec/lib/gitlab/import_export/snippet_repo_saver_spec.rb +++ b/spec/lib/gitlab/import_export/snippet_repo_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::SnippetRepoSaver do +RSpec.describe Gitlab::ImportExport::SnippetRepoSaver do describe 'bundle a project Git repo' do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, namespace: user.namespace) } diff --git a/spec/lib/gitlab/import_export/snippets_repo_restorer_spec.rb b/spec/lib/gitlab/import_export/snippets_repo_restorer_spec.rb index ac73462073e..7ca365762b5 100644 --- a/spec/lib/gitlab/import_export/snippets_repo_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/snippets_repo_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::SnippetsRepoRestorer do +RSpec.describe Gitlab::ImportExport::SnippetsRepoRestorer do include GitHelpers describe 'bundle a snippet Git repo' do diff --git a/spec/lib/gitlab/import_export/snippets_repo_saver_spec.rb b/spec/lib/gitlab/import_export/snippets_repo_saver_spec.rb index 5332990a975..8507c46ec83 100644 --- a/spec/lib/gitlab/import_export/snippets_repo_saver_spec.rb +++ b/spec/lib/gitlab/import_export/snippets_repo_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::SnippetsRepoSaver do +RSpec.describe Gitlab::ImportExport::SnippetsRepoSaver do describe 'bundle a project Git repo' do let_it_be(:user) { create(:user) } let!(:project) { create(:project) } diff --git a/spec/lib/gitlab/import_export/uploads_manager_spec.rb b/spec/lib/gitlab/import_export/uploads_manager_spec.rb index e6d6ba840be..33ad0e12c37 100644 --- a/spec/lib/gitlab/import_export/uploads_manager_spec.rb +++ b/spec/lib/gitlab/import_export/uploads_manager_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::UploadsManager do +RSpec.describe Gitlab::ImportExport::UploadsManager do let(:shared) { project.import_export_shared } let(:export_path) { "#{Dir.tmpdir}/project_tree_saver_spec" } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/import_export/uploads_restorer_spec.rb b/spec/lib/gitlab/import_export/uploads_restorer_spec.rb index 077ece87b31..864fd8d72fa 100644 --- a/spec/lib/gitlab/import_export/uploads_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/uploads_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::UploadsRestorer do +RSpec.describe Gitlab::ImportExport::UploadsRestorer do describe 'bundle a project Git repo' do let(:export_path) { "#{Dir.tmpdir}/uploads_saver_spec" } let(:shared) { project.import_export_shared } diff --git a/spec/lib/gitlab/import_export/uploads_saver_spec.rb b/spec/lib/gitlab/import_export/uploads_saver_spec.rb index 8a36caef316..8e9be209f89 100644 --- a/spec/lib/gitlab/import_export/uploads_saver_spec.rb +++ b/spec/lib/gitlab/import_export/uploads_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::UploadsSaver do +RSpec.describe Gitlab::ImportExport::UploadsSaver do describe 'bundle a project Git repo' do let(:export_path) { "#{Dir.tmpdir}/uploads_saver_spec" } let(:file) { fixture_file_upload('spec/fixtures/banana_sample.gif', 'image/gif') } diff --git a/spec/lib/gitlab/import_export/version_checker_spec.rb b/spec/lib/gitlab/import_export/version_checker_spec.rb index befbd1b4c19..8b39330656f 100644 --- a/spec/lib/gitlab/import_export/version_checker_spec.rb +++ b/spec/lib/gitlab/import_export/version_checker_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' include ImportExport::CommonUtil -describe Gitlab::ImportExport::VersionChecker do +RSpec.describe Gitlab::ImportExport::VersionChecker do let!(:shared) { Gitlab::ImportExport::Shared.new(nil) } describe 'bundle a project Git repo' do diff --git a/spec/lib/gitlab/import_export/wiki_repo_saver_spec.rb b/spec/lib/gitlab/import_export/wiki_repo_saver_spec.rb index 264272d2026..778d0859bf1 100644 --- a/spec/lib/gitlab/import_export/wiki_repo_saver_spec.rb +++ b/spec/lib/gitlab/import_export/wiki_repo_saver_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::WikiRepoSaver do +RSpec.describe Gitlab::ImportExport::WikiRepoSaver do describe 'bundle a wiki Git repo' do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, :wiki_repo) } diff --git a/spec/lib/gitlab/import_export/wiki_restorer_spec.rb b/spec/lib/gitlab/import_export/wiki_restorer_spec.rb index 33cd3e55393..6c80c410d07 100644 --- a/spec/lib/gitlab/import_export/wiki_restorer_spec.rb +++ b/spec/lib/gitlab/import_export/wiki_restorer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportExport::WikiRestorer do +RSpec.describe Gitlab::ImportExport::WikiRestorer do describe 'restore a wiki Git repo' do let!(:project_with_wiki) { create(:project, :wiki_repo) } let!(:project_without_wiki) { create(:project) } diff --git a/spec/lib/gitlab/import_formatter_spec.rb b/spec/lib/gitlab/import_formatter_spec.rb index e9f63ba5777..fbf00ab92d3 100644 --- a/spec/lib/gitlab/import_formatter_spec.rb +++ b/spec/lib/gitlab/import_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportFormatter do +RSpec.describe Gitlab::ImportFormatter do let(:formatter) { Gitlab::ImportFormatter.new } describe '#comment' do diff --git a/spec/lib/gitlab/import_sources_spec.rb b/spec/lib/gitlab/import_sources_spec.rb index 265241dc2af..0dfd8a2ee50 100644 --- a/spec/lib/gitlab/import_sources_spec.rb +++ b/spec/lib/gitlab/import_sources_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ImportSources do +RSpec.describe Gitlab::ImportSources do describe '.options' do it 'returns a hash' do expected = diff --git a/spec/lib/gitlab/incident_management/pager_duty/incident_issue_description_spec.rb b/spec/lib/gitlab/incident_management/pager_duty/incident_issue_description_spec.rb new file mode 100644 index 00000000000..9a55e21d031 --- /dev/null +++ b/spec/lib/gitlab/incident_management/pager_duty/incident_issue_description_spec.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +require 'fast_spec_helper' +require 'timecop' + +RSpec.describe Gitlab::IncidentManagement::PagerDuty::IncidentIssueDescription do + describe '#to_s' do + let(:markdown_line_break) { ' ' } + let(:created_at) { '2017-09-26T15:14:36Z' } + let(:assignees) do + [{ 'summary' => 'Laura Haley', 'url' => 'https://webdemo.pagerduty.com/users/P553OPV' }] + end + let(:impacted_services) do + [{ 'summary' => 'Production XDB Cluster', 'url' => 'https://webdemo.pagerduty.com/services/PN49J75' }] + end + let(:incident_payload) do + { + 'url' => 'https://webdemo.pagerduty.com/incidents/PRORDTY', + 'incident_number' => 33, + 'title' => 'My new incident', + 'status' => 'triggered', + 'created_at' => created_at, + 'urgency' => 'high', + 'incident_key' => 'SOME-KEY', + 'assignees' => assignees, + 'impacted_services' => impacted_services + } + end + + subject(:to_s) { described_class.new(incident_payload).to_s } + + it 'returns description' do + expect(to_s).to eq( + <<~MARKDOWN.chomp + **Incident:** [My new incident](https://webdemo.pagerduty.com/incidents/PRORDTY)#{markdown_line_break} + **Incident number:** 33#{markdown_line_break} + **Urgency:** high#{markdown_line_break} + **Status:** triggered#{markdown_line_break} + **Incident key:** SOME-KEY#{markdown_line_break} + **Created at:** 26 September 2017, 3:14PM (UTC)#{markdown_line_break} + **Assignees:** [Laura Haley](https://webdemo.pagerduty.com/users/P553OPV)#{markdown_line_break} + **Impacted services:** [Production XDB Cluster](https://webdemo.pagerduty.com/services/PN49J75) + MARKDOWN + ) + end + + context 'when created_at is missing' do + let(:created_at) { nil } + + it 'description contains current time in UTC' do + Timecop.freeze do + now = Time.current.utc.strftime('%d %B %Y, %-l:%M%p (%Z)') + + expect(to_s).to include( + <<~MARKDOWN.chomp + **Created at:** #{now}#{markdown_line_break} + MARKDOWN + ) + end + end + end + + context 'when there are several assignees' do + let(:assignees) do + [ + { 'summary' => 'Laura Haley', 'url' => 'https://laura.pagerduty.com' }, + { 'summary' => 'John Doe', 'url' => 'https://john.pagerduty.com' } + ] + end + + it 'assignees is a list of links' do + expect(to_s).to include( + <<~MARKDOWN.chomp + **Assignees:** [Laura Haley](https://laura.pagerduty.com), [John Doe](https://john.pagerduty.com)#{markdown_line_break} + MARKDOWN + ) + end + end + + context 'when there are several impacted services' do + let(:impacted_services) do + [ + { 'summary' => 'XDB Cluster', 'url' => 'https://xdb.pagerduty.com' }, + { 'summary' => 'BRB Cluster', 'url' => 'https://brb.pagerduty.com' } + ] + end + + it 'impacted services is a list of links' do + expect(to_s).to include( + <<~MARKDOWN.chomp + **Impacted services:** [XDB Cluster](https://xdb.pagerduty.com), [BRB Cluster](https://brb.pagerduty.com) + MARKDOWN + ) + end + end + end +end diff --git a/spec/lib/gitlab/incoming_email_spec.rb b/spec/lib/gitlab/incoming_email_spec.rb index 2dd45d18ee9..19d608cf48e 100644 --- a/spec/lib/gitlab/incoming_email_spec.rb +++ b/spec/lib/gitlab/incoming_email_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::IncomingEmail do +RSpec.describe Gitlab::IncomingEmail do describe "self.enabled?" do context "when reply by email is enabled" do before do diff --git a/spec/lib/gitlab/insecure_key_fingerprint_spec.rb b/spec/lib/gitlab/insecure_key_fingerprint_spec.rb index 8d0422bae9f..2f3489edcd8 100644 --- a/spec/lib/gitlab/insecure_key_fingerprint_spec.rb +++ b/spec/lib/gitlab/insecure_key_fingerprint_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::InsecureKeyFingerprint do +RSpec.describe Gitlab::InsecureKeyFingerprint do let(:key) do 'ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn' \ '1SJejgt4596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9wa++Oi7Qk' \ diff --git a/spec/lib/gitlab/instrumentation/redis_base_spec.rb b/spec/lib/gitlab/instrumentation/redis_base_spec.rb index 5ea8f00114e..07be0ccf6e9 100644 --- a/spec/lib/gitlab/instrumentation/redis_base_spec.rb +++ b/spec/lib/gitlab/instrumentation/redis_base_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Instrumentation::RedisBase, :request_store do +RSpec.describe Gitlab::Instrumentation::RedisBase, :request_store do let(:instrumentation_class_a) do stub_const('InstanceA', Class.new(described_class)) end diff --git a/spec/lib/gitlab/instrumentation/redis_cluster_validator_spec.rb b/spec/lib/gitlab/instrumentation/redis_cluster_validator_spec.rb new file mode 100644 index 00000000000..2ca7465e775 --- /dev/null +++ b/spec/lib/gitlab/instrumentation/redis_cluster_validator_spec.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require 'fast_spec_helper' +require 'support/helpers/rails_helpers' +require 'rspec-parameterized' + +RSpec.describe Gitlab::Instrumentation::RedisClusterValidator do + include RailsHelpers + + describe '.validate!' do + using RSpec::Parameterized::TableSyntax + + context 'Rails environments' do + where(:env, :should_raise) do + 'production' | false + 'staging' | false + 'development' | true + 'test' | true + end + + with_them do + it do + stub_rails_env(env) + + args = [:mget, 'foo', 'bar'] + + if should_raise + expect { described_class.validate!(args) } + .to raise_error(described_class::CrossSlotError) + else + expect { described_class.validate!(args) }.not_to raise_error + end + end + end + end + + where(:command, :arguments, :should_raise) do + :rename | %w(foo bar) | true + :RENAME | %w(foo bar) | true + 'rename' | %w(foo bar) | true + 'RENAME' | %w(foo bar) | true + :rename | %w(iaa ahy) | false # 'iaa' and 'ahy' hash to the same slot + :rename | %w({foo}:1 {foo}:2) | false + :rename | %w(foo foo bar) | false # This is not a valid command but should not raise here + :mget | %w(foo bar) | true + :mget | %w(foo foo bar) | true + :mget | %w(foo foo) | false + :blpop | %w(foo bar 1) | true + :blpop | %w(foo foo 1) | false + :mset | %w(foo a bar a) | true + :mset | %w(foo a foo a) | false + :del | %w(foo bar) | true + :del | [%w(foo bar)] | true # Arguments can be a nested array + :del | %w(foo foo) | false + :hset | %w(foo bar) | false # Not a multi-key command + end + + with_them do + it do + args = [command] + arguments + + if should_raise + expect { described_class.validate!(args) } + .to raise_error(described_class::CrossSlotError) + else + expect { described_class.validate!(args) }.not_to raise_error + end + end + end + end + + describe '.allow_cross_slot_commands' do + it 'does not raise for invalid arguments' do + expect do + described_class.allow_cross_slot_commands do + described_class.validate!([:mget, 'foo', 'bar']) + end + end.not_to raise_error + end + + it 'allows nested invocation' do + expect do + described_class.allow_cross_slot_commands do + described_class.allow_cross_slot_commands do + described_class.validate!([:mget, 'foo', 'bar']) + end + + described_class.validate!([:mget, 'foo', 'bar']) + end + end.not_to raise_error + end + end +end diff --git a/spec/lib/gitlab/instrumentation/redis_interceptor_spec.rb b/spec/lib/gitlab/instrumentation/redis_interceptor_spec.rb index 25506d63091..5b0ad63ee72 100644 --- a/spec/lib/gitlab/instrumentation/redis_interceptor_spec.rb +++ b/spec/lib/gitlab/instrumentation/redis_interceptor_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rspec-parameterized' -describe Gitlab::Instrumentation::RedisInterceptor, :clean_gitlab_redis_shared_state, :request_store do +RSpec.describe Gitlab::Instrumentation::RedisInterceptor, :clean_gitlab_redis_shared_state, :request_store do using RSpec::Parameterized::TableSyntax describe 'read and write' do @@ -42,4 +42,73 @@ describe Gitlab::Instrumentation::RedisInterceptor, :clean_gitlab_redis_shared_s end end end + + describe 'counting' do + let(:instrumentation_class) { Gitlab::Redis::SharedState.instrumentation_class } + + it 'counts successful requests' do + expect(instrumentation_class).to receive(:instance_count_request).and_call_original + + Gitlab::Redis::SharedState.with { |redis| redis.call(:get, 'foobar') } + end + + it 'counts exceptions' do + expect(instrumentation_class).to receive(:instance_count_exception) + .with(instance_of(Redis::CommandError)).and_call_original + expect(instrumentation_class).to receive(:instance_count_request).and_call_original + + expect do + Gitlab::Redis::SharedState.with do |redis| + redis.call(:auth, 'foo', 'bar') + end + end.to raise_exception(Redis::CommandError) + end + end + + describe 'latency' do + let(:instrumentation_class) { Gitlab::Redis::SharedState.instrumentation_class } + + describe 'commands in the apdex' do + where(:command) do + [ + [[:get, 'foobar']], + [%w[GET foobar]] + ] + end + + with_them do + it 'measures requests we want in the apdex' do + expect(instrumentation_class).to receive(:instance_observe_duration).with(a_value > 0) + .and_call_original + + Gitlab::Redis::SharedState.with { |redis| redis.call(*command) } + end + end + end + + describe 'commands not in the apdex' do + where(:command) do + [ + [%w[brpop foobar 0.01]], + [%w[blpop foobar 0.01]], + [%w[brpoplpush foobar bazqux 0.01]], + [%w[bzpopmin foobar 0.01]], + [%w[bzpopmax foobar 0.01]], + [%w[xread block 1 streams mystream 0-0]], + [%w[xreadgroup group mygroup myconsumer block 1 streams foobar 0-0]] + ] + end + + with_them do + it 'skips requests we do not want in the apdex' do + expect(instrumentation_class).not_to receive(:instance_observe_duration) + + begin + Gitlab::Redis::SharedState.with { |redis| redis.call(*command) } + rescue Gitlab::Instrumentation::RedisClusterValidator::CrossSlotError, ::Redis::CommandError + end + end + end + end + end end diff --git a/spec/lib/gitlab/instrumentation/redis_spec.rb b/spec/lib/gitlab/instrumentation/redis_spec.rb index 8311c4f5bbb..e927f39cae2 100644 --- a/spec/lib/gitlab/instrumentation/redis_spec.rb +++ b/spec/lib/gitlab/instrumentation/redis_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Instrumentation::Redis do +RSpec.describe Gitlab::Instrumentation::Redis do def stub_storages(method, value) described_class::STORAGES.each do |storage| allow(storage).to receive(method) { value } diff --git a/spec/lib/gitlab/instrumentation_helper_spec.rb b/spec/lib/gitlab/instrumentation_helper_spec.rb index 15d377a16fc..35bbdcdccd6 100644 --- a/spec/lib/gitlab/instrumentation_helper_spec.rb +++ b/spec/lib/gitlab/instrumentation_helper_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rspec-parameterized' -describe Gitlab::InstrumentationHelper do +RSpec.describe Gitlab::InstrumentationHelper do using RSpec::Parameterized::TableSyntax describe '.keys' do diff --git a/spec/lib/gitlab/internal_post_receive/response_spec.rb b/spec/lib/gitlab/internal_post_receive/response_spec.rb index d90b85a41ed..135596c2de3 100644 --- a/spec/lib/gitlab/internal_post_receive/response_spec.rb +++ b/spec/lib/gitlab/internal_post_receive/response_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::InternalPostReceive::Response do +RSpec.describe Gitlab::InternalPostReceive::Response do subject { described_class.new } describe '#add_merge_request_urls' do diff --git a/spec/lib/gitlab/issuable_metadata_spec.rb b/spec/lib/gitlab/issuable_metadata_spec.rb index 1920cecfc29..3ba1d069bc9 100644 --- a/spec/lib/gitlab/issuable_metadata_spec.rb +++ b/spec/lib/gitlab/issuable_metadata_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::IssuableMetadata do +RSpec.describe Gitlab::IssuableMetadata do let(:user) { create(:user) } let!(:project) { create(:project, :public, :repository, creator: user, namespace: user.namespace) } diff --git a/spec/lib/gitlab/issuable_sorter_spec.rb b/spec/lib/gitlab/issuable_sorter_spec.rb index 486e9539b92..60f62062f04 100644 --- a/spec/lib/gitlab/issuable_sorter_spec.rb +++ b/spec/lib/gitlab/issuable_sorter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::IssuableSorter do +RSpec.describe Gitlab::IssuableSorter do let(:namespace1) { build_stubbed(:namespace, id: 1) } let(:project1) { build_stubbed(:project, id: 1, namespace: namespace1) } diff --git a/spec/lib/gitlab/issuables_count_for_state_spec.rb b/spec/lib/gitlab/issuables_count_for_state_spec.rb index 9380aa53470..1c186a8e6ca 100644 --- a/spec/lib/gitlab/issuables_count_for_state_spec.rb +++ b/spec/lib/gitlab/issuables_count_for_state_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::IssuablesCountForState do +RSpec.describe Gitlab::IssuablesCountForState do let(:finder) do double(:finder, count_by_state: { opened: 2, closed: 1 }) end diff --git a/spec/lib/gitlab/jira_import/base_importer_spec.rb b/spec/lib/gitlab/jira_import/base_importer_spec.rb index cda491393e8..1470bad2c4c 100644 --- a/spec/lib/gitlab/jira_import/base_importer_spec.rb +++ b/spec/lib/gitlab/jira_import/base_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JiraImport::BaseImporter do +RSpec.describe Gitlab::JiraImport::BaseImporter do include JiraServiceHelper let(:project) { create(:project) } diff --git a/spec/lib/gitlab/jira_import/handle_labels_service_spec.rb b/spec/lib/gitlab/jira_import/handle_labels_service_spec.rb index 0eeff180575..4e2c5afb077 100644 --- a/spec/lib/gitlab/jira_import/handle_labels_service_spec.rb +++ b/spec/lib/gitlab/jira_import/handle_labels_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JiraImport::HandleLabelsService do +RSpec.describe Gitlab::JiraImport::HandleLabelsService do describe '#execute' do let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, group: group) } diff --git a/spec/lib/gitlab/jira_import/issue_serializer_spec.rb b/spec/lib/gitlab/jira_import/issue_serializer_spec.rb index ce38a1234cf..4adc4e4d22a 100644 --- a/spec/lib/gitlab/jira_import/issue_serializer_spec.rb +++ b/spec/lib/gitlab/jira_import/issue_serializer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JiraImport::IssueSerializer do +RSpec.describe Gitlab::JiraImport::IssueSerializer do describe '#execute' do let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, group: group) } @@ -10,6 +10,7 @@ describe Gitlab::JiraImport::IssueSerializer do let_it_be(:other_project_label) { create(:label, project: project, title: 'feature') } let_it_be(:group_label) { create(:group_label, group: group, title: 'dev') } let_it_be(:current_user) { create(:user) } + let_it_be(:user) { create(:user) } let(:iid) { 5 } let(:key) { 'PROJECT-5' } @@ -17,8 +18,8 @@ describe Gitlab::JiraImport::IssueSerializer do let(:description) { 'basic description' } let(:created_at) { '2020-01-01 20:00:00' } let(:updated_at) { '2020-01-10 20:00:00' } - let(:assignee) { double(attrs: { 'displayName' => 'Solver', 'emailAddress' => 'assignee@example.com' }) } - let(:reporter) { double(attrs: { 'displayName' => 'Reporter', 'emailAddress' => 'reporter@example.com' }) } + let(:assignee) { nil } + let(:reporter) { nil } let(:jira_status) { 'new' } let(:parent_field) do @@ -109,11 +110,12 @@ describe Gitlab::JiraImport::IssueSerializer do end context 'author' do - context 'when reporter maps to a valid GitLab user' do - let!(:user) { create(:user, email: 'reporter@example.com') } + let(:reporter) { double(attrs: { 'displayName' => 'Solver', 'accountId' => 'abcd' }) } + context 'when reporter maps to a valid GitLab user' do it 'sets the issue author to the mapped user' do - project.add_developer(user) + expect(Gitlab::JiraImport).to receive(:get_user_mapping).with(project.id, 'abcd') + .and_return(user.id) expect(subject[:author_id]).to eq(user.id) end @@ -121,6 +123,9 @@ describe Gitlab::JiraImport::IssueSerializer do context 'when reporter does not map to a valid Gitlab user' do it 'defaults the issue author to project creator' do + expect(Gitlab::JiraImport).to receive(:get_user_mapping).with(project.id, 'abcd') + .and_return(nil) + expect(subject[:author_id]).to eq(current_user.id) end end @@ -129,25 +134,30 @@ describe Gitlab::JiraImport::IssueSerializer do let(:reporter) { nil } it 'defaults the issue author to project creator' do + expect(Gitlab::JiraImport).not_to receive(:get_user_mapping) + expect(subject[:author_id]).to eq(current_user.id) end end - context 'when reporter field is missing email address' do + context 'when reporter field is missing accountId' do let(:reporter) { double(attrs: { 'displayName' => 'Reporter' }) } it 'defaults the issue author to project creator' do + expect(Gitlab::JiraImport).not_to receive(:get_user_mapping) + expect(subject[:author_id]).to eq(current_user.id) end end end context 'assignee' do - context 'when assignee maps to a valid GitLab user' do - let!(:user) { create(:user, email: 'assignee@example.com') } + let(:assignee) { double(attrs: { 'displayName' => 'Solver', 'accountId' => '1234' }) } + context 'when assignee maps to a valid GitLab user' do it 'sets the issue assignees to the mapped user' do - project.add_developer(user) + expect(Gitlab::JiraImport).to receive(:get_user_mapping).with(project.id, '1234') + .and_return(user.id) expect(subject[:assignee_ids]).to eq([user.id]) end @@ -155,6 +165,9 @@ describe Gitlab::JiraImport::IssueSerializer do context 'when assignee does not map to a valid GitLab user' do it 'leaves the assignee empty' do + expect(Gitlab::JiraImport).to receive(:get_user_mapping).with(project.id, '1234') + .and_return(nil) + expect(subject[:assignee_ids]).to be_nil end end @@ -163,14 +176,18 @@ describe Gitlab::JiraImport::IssueSerializer do let(:assignee) { nil } it 'leaves the assignee empty' do + expect(Gitlab::JiraImport).not_to receive(:get_user_mapping) + expect(subject[:assignee_ids]).to be_nil end end - context 'when assginee field is missing email address' do - let(:assignee) { double(attrs: { 'displayName' => 'Reporter' }) } + context 'when assginee field is missing accountId' do + let(:assignee) { double(attrs: { 'displayName' => 'Solver' }) } it 'leaves the assignee empty' do + expect(Gitlab::JiraImport).not_to receive(:get_user_mapping) + expect(subject[:assignee_ids]).to be_nil end end diff --git a/spec/lib/gitlab/jira_import/issues_importer_spec.rb b/spec/lib/gitlab/jira_import/issues_importer_spec.rb index 0d790f49450..4a32f0fd3a9 100644 --- a/spec/lib/gitlab/jira_import/issues_importer_spec.rb +++ b/spec/lib/gitlab/jira_import/issues_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JiraImport::IssuesImporter do +RSpec.describe Gitlab::JiraImport::IssuesImporter do include JiraServiceHelper let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/jira_import/labels_importer_spec.rb b/spec/lib/gitlab/jira_import/labels_importer_spec.rb index 19661ff4e73..db98a83cb3c 100644 --- a/spec/lib/gitlab/jira_import/labels_importer_spec.rb +++ b/spec/lib/gitlab/jira_import/labels_importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JiraImport::LabelsImporter do +RSpec.describe Gitlab::JiraImport::LabelsImporter do include JiraServiceHelper let_it_be(:user) { create(:user) } diff --git a/spec/lib/gitlab/jira_import/metadata_collector_spec.rb b/spec/lib/gitlab/jira_import/metadata_collector_spec.rb index af479810df0..86863d67f25 100644 --- a/spec/lib/gitlab/jira_import/metadata_collector_spec.rb +++ b/spec/lib/gitlab/jira_import/metadata_collector_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JiraImport::MetadataCollector do +RSpec.describe Gitlab::JiraImport::MetadataCollector do describe '#execute' do let(:key) { 'PROJECT-5' } let(:summary) { 'some title' } diff --git a/spec/lib/gitlab/jira_import/user_mapper_spec.rb b/spec/lib/gitlab/jira_import/user_mapper_spec.rb deleted file mode 100644 index c8c8bd3c5b0..00000000000 --- a/spec/lib/gitlab/jira_import/user_mapper_spec.rb +++ /dev/null @@ -1,80 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' - -describe Gitlab::JiraImport::UserMapper do - let_it_be(:group) { create(:group) } - let_it_be(:project) { create(:project, group: group) } - let_it_be(:user) { create(:user, email: 'user@example.com') } - let_it_be(:email) { create(:email, user: user, email: 'second_email@example.com', confirmed_at: nil) } - - let(:jira_user) { { 'acountId' => '1a2b', 'emailAddress' => 'user@example.com' } } - - describe '#execute' do - subject { described_class.new(project, jira_user).execute } - - context 'when jira_user is nil' do - let(:jira_user) { nil } - - it 'returns nil' do - expect(subject).to be_nil - end - end - - context 'when Gitlab user is not found by email' do - let(:jira_user) { { 'acountId' => '1a2b', 'emailAddress' => 'other@example.com' } } - - it 'returns nil' do - expect(subject).to be_nil - end - end - - context 'when jira_user emailAddress is nil' do - let(:jira_user) { { 'acountId' => '1a2b', 'emailAddress' => nil } } - - it 'returns nil' do - expect(subject).to be_nil - end - end - - context 'when jira_user emailAddress key is missing' do - let(:jira_user) { { 'acountId' => '1a2b' } } - - it 'returns nil' do - expect(subject).to be_nil - end - end - - context 'when found user is not a project member' do - it 'returns nil' do - expect(subject).to be_nil - end - end - - context 'when found user is a project member' do - it 'returns the found user' do - project.add_developer(user) - - expect(subject).to eq(user) - end - end - - context 'when user found by unconfirmd secondary address is a project member' do - let(:jira_user) { { 'acountId' => '1a2b', 'emailAddress' => 'second_email@example.com' } } - - it 'returns the found user' do - project.add_developer(user) - - expect(subject).to eq(user) - end - end - - context 'when user is a group member' do - it 'returns the found user' do - group.add_developer(user) - - expect(subject).to eq(user) - end - end - end -end diff --git a/spec/lib/gitlab/jira_import_spec.rb b/spec/lib/gitlab/jira_import_spec.rb index 5b95891c97e..c8cecb576da 100644 --- a/spec/lib/gitlab/jira_import_spec.rb +++ b/spec/lib/gitlab/jira_import_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JiraImport do +RSpec.describe Gitlab::JiraImport do let(:project_id) { 321 } describe '.validate_project_settings!' do diff --git a/spec/lib/gitlab/job_waiter_spec.rb b/spec/lib/gitlab/job_waiter_spec.rb index da6a6a9149b..4d7c838aa3b 100644 --- a/spec/lib/gitlab/job_waiter_spec.rb +++ b/spec/lib/gitlab/job_waiter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JobWaiter do +RSpec.describe Gitlab::JobWaiter do describe '.notify' do it 'pushes the jid to the named queue' do key = 'gitlab:job_waiter:foo' diff --git a/spec/lib/gitlab/json_cache_spec.rb b/spec/lib/gitlab/json_cache_spec.rb index 9379499f602..563b3d35823 100644 --- a/spec/lib/gitlab/json_cache_spec.rb +++ b/spec/lib/gitlab/json_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JsonCache do +RSpec.describe Gitlab::JsonCache do let_it_be(:broadcast_message) { create(:broadcast_message) } let(:backend) { double('backend').as_null_object } let(:namespace) { 'geo' } diff --git a/spec/lib/gitlab/json_logger_spec.rb b/spec/lib/gitlab/json_logger_spec.rb index 41dafc84ef2..23f7191454a 100644 --- a/spec/lib/gitlab/json_logger_spec.rb +++ b/spec/lib/gitlab/json_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JsonLogger do +RSpec.describe Gitlab::JsonLogger do subject { described_class.new('/dev/null') } let(:now) { Time.now } diff --git a/spec/lib/gitlab/json_spec.rb b/spec/lib/gitlab/json_spec.rb index ee7c98a5a54..d7671dda323 100644 --- a/spec/lib/gitlab/json_spec.rb +++ b/spec/lib/gitlab/json_spec.rb @@ -7,189 +7,404 @@ RSpec.describe Gitlab::Json do stub_feature_flags(json_wrapper_legacy_mode: true) end - describe ".parse" do - context "legacy_mode is disabled by default" do - it "parses an object" do - expect(subject.parse('{ "foo": "bar" }')).to eq({ "foo" => "bar" }) - end + shared_examples "json" do + describe ".parse" do + context "legacy_mode is disabled by default" do + it "parses an object" do + expect(subject.parse('{ "foo": "bar" }')).to eq({ "foo" => "bar" }) + end - it "parses an array" do - expect(subject.parse('[{ "foo": "bar" }]')).to eq([{ "foo" => "bar" }]) - end + it "parses an array" do + expect(subject.parse('[{ "foo": "bar" }]')).to eq([{ "foo" => "bar" }]) + end - it "parses a string" do - expect(subject.parse('"foo"', legacy_mode: false)).to eq("foo") - end + it "parses a string" do + expect(subject.parse('"foo"', legacy_mode: false)).to eq("foo") + end - it "parses a true bool" do - expect(subject.parse("true", legacy_mode: false)).to be(true) - end + it "parses a true bool" do + expect(subject.parse("true", legacy_mode: false)).to be(true) + end - it "parses a false bool" do - expect(subject.parse("false", legacy_mode: false)).to be(false) + it "parses a false bool" do + expect(subject.parse("false", legacy_mode: false)).to be(false) + end end - end - context "legacy_mode is enabled" do - it "parses an object" do - expect(subject.parse('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) - end + context "legacy_mode is enabled" do + it "parses an object" do + expect(subject.parse('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) + end - it "parses an array" do - expect(subject.parse('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) - end + it "parses an array" do + expect(subject.parse('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) + end - it "raises an error on a string" do - expect { subject.parse('"foo"', legacy_mode: true) }.to raise_error(JSON::ParserError) - end + it "raises an error on a string" do + expect { subject.parse('"foo"', legacy_mode: true) }.to raise_error(JSON::ParserError) + end - it "raises an error on a true bool" do - expect { subject.parse("true", legacy_mode: true) }.to raise_error(JSON::ParserError) + it "raises an error on a true bool" do + expect { subject.parse("true", legacy_mode: true) }.to raise_error(JSON::ParserError) + end + + it "raises an error on a false bool" do + expect { subject.parse("false", legacy_mode: true) }.to raise_error(JSON::ParserError) + end end - it "raises an error on a false bool" do - expect { subject.parse("false", legacy_mode: true) }.to raise_error(JSON::ParserError) + context "feature flag is disabled" do + before do + stub_feature_flags(json_wrapper_legacy_mode: false) + end + + it "parses an object" do + expect(subject.parse('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) + end + + it "parses an array" do + expect(subject.parse('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) + end + + it "parses a string" do + expect(subject.parse('"foo"', legacy_mode: true)).to eq("foo") + end + + it "parses a true bool" do + expect(subject.parse("true", legacy_mode: true)).to be(true) + end + + it "parses a false bool" do + expect(subject.parse("false", legacy_mode: true)).to be(false) + end end end - context "feature flag is disabled" do - before do - stub_feature_flags(json_wrapper_legacy_mode: false) - end + describe ".parse!" do + context "legacy_mode is disabled by default" do + it "parses an object" do + expect(subject.parse!('{ "foo": "bar" }')).to eq({ "foo" => "bar" }) + end - it "parses an object" do - expect(subject.parse('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) - end + it "parses an array" do + expect(subject.parse!('[{ "foo": "bar" }]')).to eq([{ "foo" => "bar" }]) + end - it "parses an array" do - expect(subject.parse('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) - end + it "parses a string" do + expect(subject.parse!('"foo"', legacy_mode: false)).to eq("foo") + end - it "parses a string" do - expect(subject.parse('"foo"', legacy_mode: true)).to eq("foo") + it "parses a true bool" do + expect(subject.parse!("true", legacy_mode: false)).to be(true) + end + + it "parses a false bool" do + expect(subject.parse!("false", legacy_mode: false)).to be(false) + end end - it "parses a true bool" do - expect(subject.parse("true", legacy_mode: true)).to be(true) + context "legacy_mode is enabled" do + it "parses an object" do + expect(subject.parse!('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) + end + + it "parses an array" do + expect(subject.parse!('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) + end + + it "raises an error on a string" do + expect { subject.parse!('"foo"', legacy_mode: true) }.to raise_error(JSON::ParserError) + end + + it "raises an error on a true bool" do + expect { subject.parse!("true", legacy_mode: true) }.to raise_error(JSON::ParserError) + end + + it "raises an error on a false bool" do + expect { subject.parse!("false", legacy_mode: true) }.to raise_error(JSON::ParserError) + end end - it "parses a false bool" do - expect(subject.parse("false", legacy_mode: true)).to be(false) + context "feature flag is disabled" do + before do + stub_feature_flags(json_wrapper_legacy_mode: false) + end + + it "parses an object" do + expect(subject.parse!('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) + end + + it "parses an array" do + expect(subject.parse!('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) + end + + it "parses a string" do + expect(subject.parse!('"foo"', legacy_mode: true)).to eq("foo") + end + + it "parses a true bool" do + expect(subject.parse!("true", legacy_mode: true)).to be(true) + end + + it "parses a false bool" do + expect(subject.parse!("false", legacy_mode: true)).to be(false) + end end end - end - describe ".parse!" do - context "legacy_mode is disabled by default" do - it "parses an object" do - expect(subject.parse!('{ "foo": "bar" }')).to eq({ "foo" => "bar" }) + describe ".dump" do + it "dumps an object" do + expect(subject.dump({ "foo" => "bar" })).to eq('{"foo":"bar"}') end - it "parses an array" do - expect(subject.parse!('[{ "foo": "bar" }]')).to eq([{ "foo" => "bar" }]) + it "dumps an array" do + expect(subject.dump([{ "foo" => "bar" }])).to eq('[{"foo":"bar"}]') end - it "parses a string" do - expect(subject.parse!('"foo"', legacy_mode: false)).to eq("foo") + it "dumps a string" do + expect(subject.dump("foo")).to eq('"foo"') end - it "parses a true bool" do - expect(subject.parse!("true", legacy_mode: false)).to be(true) + it "dumps a true bool" do + expect(subject.dump(true)).to eq("true") end - it "parses a false bool" do - expect(subject.parse!("false", legacy_mode: false)).to be(false) + it "dumps a false bool" do + expect(subject.dump(false)).to eq("false") end end - context "legacy_mode is enabled" do - it "parses an object" do - expect(subject.parse!('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) + describe ".generate" do + let(:obj) do + { test: true, "foo.bar" => "baz", is_json: 1, some: [1, 2, 3] } end - it "parses an array" do - expect(subject.parse!('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) - end + it "generates JSON" do + expected_string = <<~STR.chomp + {"test":true,"foo.bar":"baz","is_json":1,"some":[1,2,3]} + STR - it "raises an error on a string" do - expect { subject.parse!('"foo"', legacy_mode: true) }.to raise_error(JSON::ParserError) + expect(subject.generate(obj)).to eq(expected_string) end - it "raises an error on a true bool" do - expect { subject.parse!("true", legacy_mode: true) }.to raise_error(JSON::ParserError) + it "allows you to customise the output" do + opts = { + indent: " ", + space: " ", + space_before: " ", + object_nl: "\n", + array_nl: "\n" + } + + json = subject.generate(obj, opts) + + expected_string = <<~STR.chomp + { + "test" : true, + "foo.bar" : "baz", + "is_json" : 1, + "some" : [ + 1, + 2, + 3 + ] + } + STR + + expect(json).to eq(expected_string) end + end - it "raises an error on a false bool" do - expect { subject.parse!("false", legacy_mode: true) }.to raise_error(JSON::ParserError) + describe ".pretty_generate" do + let(:obj) do + { + test: true, + "foo.bar" => "baz", + is_json: 1, + some: [1, 2, 3], + more: { test: true }, + multi_line_empty_array: [], + multi_line_empty_obj: {} + } + end + + it "generates pretty JSON" do + expected_string = <<~STR.chomp + { + "test": true, + "foo.bar": "baz", + "is_json": 1, + "some": [ + 1, + 2, + 3 + ], + "more": { + "test": true + }, + "multi_line_empty_array": [ + + ], + "multi_line_empty_obj": { + } + } + STR + + expect(subject.pretty_generate(obj)).to eq(expected_string) + end + + it "allows you to customise the output" do + opts = { + space_before: " " + } + + json = subject.pretty_generate(obj, opts) + + expected_string = <<~STR.chomp + { + "test" : true, + "foo.bar" : "baz", + "is_json" : 1, + "some" : [ + 1, + 2, + 3 + ], + "more" : { + "test" : true + }, + "multi_line_empty_array" : [ + + ], + "multi_line_empty_obj" : { + } + } + STR + + expect(json).to eq(expected_string) end end - context "feature flag is disabled" do + context "the feature table is missing" do before do - stub_feature_flags(json_wrapper_legacy_mode: false) + allow(Feature::FlipperFeature).to receive(:table_exists?).and_return(false) end - it "parses an object" do - expect(subject.parse!('{ "foo": "bar" }', legacy_mode: true)).to eq({ "foo" => "bar" }) + it "skips legacy mode handling" do + expect(Feature).not_to receive(:enabled?).with(:json_wrapper_legacy_mode, default_enabled: true) + + subject.send(:handle_legacy_mode!, {}) end - it "parses an array" do - expect(subject.parse!('[{ "foo": "bar" }]', legacy_mode: true)).to eq([{ "foo" => "bar" }]) + it "skips oj feature detection" do + expect(Feature).not_to receive(:enabled?).with(:oj_json, default_enabled: true) + + subject.send(:enable_oj?) end + end - it "parses a string" do - expect(subject.parse!('"foo"', legacy_mode: true)).to eq("foo") + context "the database is missing" do + before do + allow(Feature::FlipperFeature).to receive(:table_exists?).and_raise(PG::ConnectionBad) end - it "parses a true bool" do - expect(subject.parse!("true", legacy_mode: true)).to be(true) + it "still parses json" do + expect(subject.parse("{}")).to eq({}) end - it "parses a false bool" do - expect(subject.parse!("false", legacy_mode: true)).to be(false) + it "still generates json" do + expect(subject.dump({})).to eq("{}") end end end - describe ".dump" do - it "dumps an object" do - expect(subject.dump({ "foo" => "bar" })).to eq('{"foo":"bar"}') + context "oj gem" do + before do + stub_feature_flags(oj_json: true) end - it "dumps an array" do - expect(subject.dump([{ "foo" => "bar" }])).to eq('[{"foo":"bar"}]') - end + it_behaves_like "json" - it "dumps a string" do - expect(subject.dump("foo")).to eq('"foo"') + describe "#enable_oj?" do + it "returns true" do + expect(subject.enable_oj?).to be(true) + end end + end - it "dumps a true bool" do - expect(subject.dump(true)).to eq("true") + context "json gem" do + before do + stub_feature_flags(oj_json: false) end - it "dumps a false bool" do - expect(subject.dump(false)).to eq("false") + it_behaves_like "json" + + describe "#enable_oj?" do + it "returns false" do + expect(subject.enable_oj?).to be(false) + end end end - describe ".generate" do - it "delegates to the adapter" do - args = [{ foo: "bar" }] + describe Gitlab::Json::GrapeFormatter do + subject { described_class.call(obj, env) } + + let(:obj) { { test: true } } + let(:env) { {} } + let(:result) { "{\"test\":true}" } + + context "oj is enabled" do + before do + stub_feature_flags(oj_json: true) + end + + context "grape_gitlab_json flag is enabled" do + before do + stub_feature_flags(grape_gitlab_json: true) + end + + it "generates JSON" do + expect(subject).to eq(result) + end + + it "uses Gitlab::Json" do + expect(Gitlab::Json).to receive(:dump).with(obj) + + subject + end + end + + context "grape_gitlab_json flag is disabled" do + before do + stub_feature_flags(grape_gitlab_json: false) + end + + it "generates JSON" do + expect(subject).to eq(result) + end - expect(JSON).to receive(:generate).with(*args) + it "uses Grape::Formatter::Json" do + expect(Grape::Formatter::Json).to receive(:call).with(obj, env) - subject.generate(*args) + subject + end + end end - end - describe ".pretty_generate" do - it "delegates to the adapter" do - args = [{ foo: "bar" }] + context "oj is disabled" do + before do + stub_feature_flags(oj_json: false) + end - expect(JSON).to receive(:pretty_generate).with(*args) + it "generates JSON" do + expect(subject).to eq(result) + end + + it "uses Grape::Formatter::Json" do + expect(Grape::Formatter::Json).to receive(:call).with(obj, env) - subject.pretty_generate(*args) + subject + end end end end diff --git a/spec/lib/gitlab/jwt_authenticatable_spec.rb b/spec/lib/gitlab/jwt_authenticatable_spec.rb index 0c1c491b308..36bb46cb250 100644 --- a/spec/lib/gitlab/jwt_authenticatable_spec.rb +++ b/spec/lib/gitlab/jwt_authenticatable_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::JwtAuthenticatable do +RSpec.describe Gitlab::JwtAuthenticatable do let(:test_class) do Class.new do include Gitlab::JwtAuthenticatable diff --git a/spec/lib/gitlab/kubernetes/cluster_role_binding_spec.rb b/spec/lib/gitlab/kubernetes/cluster_role_binding_spec.rb index e1106f7496a..02729d53da8 100644 --- a/spec/lib/gitlab/kubernetes/cluster_role_binding_spec.rb +++ b/spec/lib/gitlab/kubernetes/cluster_role_binding_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::ClusterRoleBinding do +RSpec.describe Gitlab::Kubernetes::ClusterRoleBinding do let(:cluster_role_binding) { described_class.new(name, cluster_role_name, subjects) } let(:name) { 'cluster-role-binding-name' } let(:cluster_role_name) { 'cluster-admin' } diff --git a/spec/lib/gitlab/kubernetes/config_map_spec.rb b/spec/lib/gitlab/kubernetes/config_map_spec.rb index 0203772e069..2d0d205ffb1 100644 --- a/spec/lib/gitlab/kubernetes/config_map_spec.rb +++ b/spec/lib/gitlab/kubernetes/config_map_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::ConfigMap do +RSpec.describe Gitlab::Kubernetes::ConfigMap do let(:kubeclient) { double('kubernetes client') } let(:application) { create(:clusters_applications_prometheus) } let(:config_map) { described_class.new(application.name, application.files) } diff --git a/spec/lib/gitlab/kubernetes/config_maps/aws_node_auth_spec.rb b/spec/lib/gitlab/kubernetes/config_maps/aws_node_auth_spec.rb index f701643860a..9c3e41dfbff 100644 --- a/spec/lib/gitlab/kubernetes/config_maps/aws_node_auth_spec.rb +++ b/spec/lib/gitlab/kubernetes/config_maps/aws_node_auth_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::ConfigMaps::AwsNodeAuth do +RSpec.describe Gitlab::Kubernetes::ConfigMaps::AwsNodeAuth do describe '#generate' do let(:role) { 'arn:aws:iam::123456789012:role/node-instance-role' } diff --git a/spec/lib/gitlab/kubernetes/default_namespace_spec.rb b/spec/lib/gitlab/kubernetes/default_namespace_spec.rb index 1fda547f35c..976fe4a0a87 100644 --- a/spec/lib/gitlab/kubernetes/default_namespace_spec.rb +++ b/spec/lib/gitlab/kubernetes/default_namespace_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::DefaultNamespace do +RSpec.describe Gitlab::Kubernetes::DefaultNamespace do let(:generator) { described_class.new(cluster, project: environment.project) } describe '#from_environment_name' do diff --git a/spec/lib/gitlab/kubernetes/generic_secret_spec.rb b/spec/lib/gitlab/kubernetes/generic_secret_spec.rb index fe1d4cc11e6..8b56d76410e 100644 --- a/spec/lib/gitlab/kubernetes/generic_secret_spec.rb +++ b/spec/lib/gitlab/kubernetes/generic_secret_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::GenericSecret do +RSpec.describe Gitlab::Kubernetes::GenericSecret do let(:secret) { described_class.new(name, data, namespace) } let(:name) { 'example-name' } let(:data) { 'example-data' } diff --git a/spec/lib/gitlab/kubernetes/helm/api_spec.rb b/spec/lib/gitlab/kubernetes/helm/api_spec.rb index 0e4179d5887..dabbab27b13 100644 --- a/spec/lib/gitlab/kubernetes/helm/api_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/api_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::API do +RSpec.describe Gitlab::Kubernetes::Helm::API do let(:client) { double('kubernetes client') } let(:helm) { described_class.new(client) } let(:gitlab_namespace) { Gitlab::Kubernetes::Helm::NAMESPACE } diff --git a/spec/lib/gitlab/kubernetes/helm/base_command_spec.rb b/spec/lib/gitlab/kubernetes/helm/base_command_spec.rb index f9bcb8abdb1..57fafaebf98 100644 --- a/spec/lib/gitlab/kubernetes/helm/base_command_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/base_command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::BaseCommand do +RSpec.describe Gitlab::Kubernetes::Helm::BaseCommand do subject(:base_command) do test_class.new(rbac) end diff --git a/spec/lib/gitlab/kubernetes/helm/certificate_spec.rb b/spec/lib/gitlab/kubernetes/helm/certificate_spec.rb index 04649353976..b446c5e1149 100644 --- a/spec/lib/gitlab/kubernetes/helm/certificate_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/certificate_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Kubernetes::Helm::Certificate do +RSpec.describe Gitlab::Kubernetes::Helm::Certificate do describe '.generate_root' do subject { described_class.generate_root } diff --git a/spec/lib/gitlab/kubernetes/helm/delete_command_spec.rb b/spec/lib/gitlab/kubernetes/helm/delete_command_spec.rb index 2bf8b294821..7b182478cc3 100644 --- a/spec/lib/gitlab/kubernetes/helm/delete_command_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/delete_command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::DeleteCommand do +RSpec.describe Gitlab::Kubernetes::Helm::DeleteCommand do subject(:delete_command) { described_class.new(name: app_name, rbac: rbac, files: files, local_tiller_enabled: local_tiller_enabled) } let(:app_name) { 'app-name' } diff --git a/spec/lib/gitlab/kubernetes/helm/init_command_spec.rb b/spec/lib/gitlab/kubernetes/helm/init_command_spec.rb index 61b8eb30b42..c982a417682 100644 --- a/spec/lib/gitlab/kubernetes/helm/init_command_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/init_command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::InitCommand do +RSpec.describe Gitlab::Kubernetes::Helm::InitCommand do subject(:init_command) { described_class.new(name: application.name, files: files, rbac: rbac, local_tiller_enabled: false) } let(:application) { create(:clusters_applications_helm) } diff --git a/spec/lib/gitlab/kubernetes/helm/install_command_spec.rb b/spec/lib/gitlab/kubernetes/helm/install_command_spec.rb index 6fc91300f5b..aad350256ec 100644 --- a/spec/lib/gitlab/kubernetes/helm/install_command_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/install_command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::InstallCommand do +RSpec.describe Gitlab::Kubernetes::Helm::InstallCommand do subject(:install_command) do described_class.new( name: 'app-name', diff --git a/spec/lib/gitlab/kubernetes/helm/parsers/list_v2_spec.rb b/spec/lib/gitlab/kubernetes/helm/parsers/list_v2_spec.rb index 0ad5dc189c0..435c296d5f1 100644 --- a/spec/lib/gitlab/kubernetes/helm/parsers/list_v2_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/parsers/list_v2_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Kubernetes::Helm::Parsers::ListV2 do +RSpec.describe Gitlab::Kubernetes::Helm::Parsers::ListV2 do let(:valid_file_contents) do <<~EOF { diff --git a/spec/lib/gitlab/kubernetes/helm/patch_command_spec.rb b/spec/lib/gitlab/kubernetes/helm/patch_command_spec.rb index 8d965a25f84..ea2ade18e37 100644 --- a/spec/lib/gitlab/kubernetes/helm/patch_command_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/patch_command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::PatchCommand do +RSpec.describe Gitlab::Kubernetes::Helm::PatchCommand do let(:files) { { 'ca.pem': 'some file content' } } let(:repository) { 'https://repository.example.com' } let(:rbac) { false } diff --git a/spec/lib/gitlab/kubernetes/helm/pod_spec.rb b/spec/lib/gitlab/kubernetes/helm/pod_spec.rb index ea32ac96213..54e3289dd25 100644 --- a/spec/lib/gitlab/kubernetes/helm/pod_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/pod_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::Pod do +RSpec.describe Gitlab::Kubernetes::Helm::Pod do describe '#generate' do let(:app) { create(:clusters_applications_prometheus) } let(:command) { app.install_command } @@ -32,7 +32,7 @@ describe Gitlab::Kubernetes::Helm::Pod do it 'generates the appropriate specifications for the container' do container = subject.generate.spec.containers.first expect(container.name).to eq('helm') - expect(container.image).to eq('registry.gitlab.com/gitlab-org/cluster-integration/helm-install-image/releases/2.16.6-kube-1.13.12') + expect(container.image).to eq('registry.gitlab.com/gitlab-org/cluster-integration/helm-install-image/releases/2.16.9-kube-1.13.12') expect(container.env.count).to eq(3) expect(container.env.map(&:name)).to match_array([:HELM_VERSION, :TILLER_NAMESPACE, :COMMAND_SCRIPT]) expect(container.command).to match_array(["/bin/sh"]) diff --git a/spec/lib/gitlab/kubernetes/helm/reset_command_spec.rb b/spec/lib/gitlab/kubernetes/helm/reset_command_spec.rb index 3773c428713..8d386d41ad5 100644 --- a/spec/lib/gitlab/kubernetes/helm/reset_command_spec.rb +++ b/spec/lib/gitlab/kubernetes/helm/reset_command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Helm::ResetCommand do +RSpec.describe Gitlab::Kubernetes::Helm::ResetCommand do subject(:reset_command) { described_class.new(name: name, rbac: rbac, files: files, local_tiller_enabled: false) } let(:rbac) { true } diff --git a/spec/lib/gitlab/kubernetes/kube_client_spec.rb b/spec/lib/gitlab/kubernetes/kube_client_spec.rb index 32597aa4f5a..a15be42f393 100644 --- a/spec/lib/gitlab/kubernetes/kube_client_spec.rb +++ b/spec/lib/gitlab/kubernetes/kube_client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::KubeClient do +RSpec.describe Gitlab::Kubernetes::KubeClient do include StubRequests include KubernetesHelpers diff --git a/spec/lib/gitlab/kubernetes/kubectl_cmd_spec.rb b/spec/lib/gitlab/kubernetes/kubectl_cmd_spec.rb index b65d7b9fdc6..e80bb3dfb07 100644 --- a/spec/lib/gitlab/kubernetes/kubectl_cmd_spec.rb +++ b/spec/lib/gitlab/kubernetes/kubectl_cmd_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Kubernetes::KubectlCmd do +RSpec.describe Gitlab::Kubernetes::KubectlCmd do describe '.delete' do it 'constructs string properly' do args = %w(resource_type type --flag-1 --flag-2) diff --git a/spec/lib/gitlab/kubernetes/namespace_spec.rb b/spec/lib/gitlab/kubernetes/namespace_spec.rb index 467b10e21b1..5fe4e008469 100644 --- a/spec/lib/gitlab/kubernetes/namespace_spec.rb +++ b/spec/lib/gitlab/kubernetes/namespace_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Namespace do +RSpec.describe Gitlab::Kubernetes::Namespace do let(:name) { 'a_namespace' } let(:client) { double('kubernetes client') } let(:labels) { nil } diff --git a/spec/lib/gitlab/kubernetes/network_policy_spec.rb b/spec/lib/gitlab/kubernetes/network_policy_spec.rb index 5a920d78436..a8ca15f998b 100644 --- a/spec/lib/gitlab/kubernetes/network_policy_spec.rb +++ b/spec/lib/gitlab/kubernetes/network_policy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::NetworkPolicy do +RSpec.describe Gitlab::Kubernetes::NetworkPolicy do let(:policy) do described_class.new( name: name, diff --git a/spec/lib/gitlab/kubernetes/node_spec.rb b/spec/lib/gitlab/kubernetes/node_spec.rb new file mode 100644 index 00000000000..732bf29bc44 --- /dev/null +++ b/spec/lib/gitlab/kubernetes/node_spec.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Kubernetes::Node do + include KubernetesHelpers + + describe '#all' do + let(:cluster) { create(:cluster, :provided_by_user, :group) } + let(:expected_nodes) { [] } + + before do + stub_kubeclient_nodes_and_nodes_metrics(cluster.platform.api_url) + end + + subject { described_class.new(cluster).all } + + context 'when connection to the cluster is successful' do + let(:expected_nodes) { [kube_node.merge(kube_node_metrics)] } + + it { is_expected.to eq(expected_nodes) } + end + + context 'when cluster cannot be reached' do + before do + allow(cluster.kubeclient.core_client).to receive(:discover) + .and_raise(SocketError) + end + + it { is_expected.to eq(expected_nodes) } + end + + context 'when cluster cannot be authenticated to' do + before do + allow(cluster.kubeclient.core_client).to receive(:discover) + .and_raise(OpenSSL::X509::CertificateError.new('Certificate error')) + end + + it { is_expected.to eq(expected_nodes) } + end + + context 'when Kubeclient::HttpError is raised' do + before do + allow(cluster.kubeclient.core_client).to receive(:discover) + .and_raise(Kubeclient::HttpError.new(403, 'Forbidden', nil)) + end + + it { is_expected.to eq(expected_nodes) } + end + + context 'when an uncategorised error is raised' do + before do + allow(cluster.kubeclient.core_client).to receive(:discover) + .and_raise(StandardError) + end + + it { is_expected.to eq(expected_nodes) } + + it 'notifies Sentry' do + expect(Gitlab::ErrorTracking).to receive(:track_exception) + .with(instance_of(StandardError), hash_including(cluster_id: cluster.id)) + .once + + subject + end + end + end +end diff --git a/spec/lib/gitlab/kubernetes/role_binding_spec.rb b/spec/lib/gitlab/kubernetes/role_binding_spec.rb index 4c200eb545f..3003fe25301 100644 --- a/spec/lib/gitlab/kubernetes/role_binding_spec.rb +++ b/spec/lib/gitlab/kubernetes/role_binding_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::RoleBinding, '#generate' do +RSpec.describe Gitlab::Kubernetes::RoleBinding, '#generate' do let(:role_name) { 'edit' } let(:role_kind) { 'ClusterRole' } let(:namespace) { 'my-namespace' } diff --git a/spec/lib/gitlab/kubernetes/role_spec.rb b/spec/lib/gitlab/kubernetes/role_spec.rb index 3a5cd3b6704..acb9b5d4e8e 100644 --- a/spec/lib/gitlab/kubernetes/role_spec.rb +++ b/spec/lib/gitlab/kubernetes/role_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::Role do +RSpec.describe Gitlab::Kubernetes::Role do let(:role) { described_class.new(name: name, namespace: namespace, rules: rules) } let(:name) { 'example-name' } let(:namespace) { 'example-namespace' } diff --git a/spec/lib/gitlab/kubernetes/service_account_spec.rb b/spec/lib/gitlab/kubernetes/service_account_spec.rb index 0d525966d18..998d1a6d954 100644 --- a/spec/lib/gitlab/kubernetes/service_account_spec.rb +++ b/spec/lib/gitlab/kubernetes/service_account_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::ServiceAccount do +RSpec.describe Gitlab::Kubernetes::ServiceAccount do let(:name) { 'a_service_account' } let(:namespace_name) { 'a_namespace' } let(:service_account) { described_class.new(name, namespace_name) } diff --git a/spec/lib/gitlab/kubernetes/service_account_token_spec.rb b/spec/lib/gitlab/kubernetes/service_account_token_spec.rb index 0d334bed45f..18423fdb2a3 100644 --- a/spec/lib/gitlab/kubernetes/service_account_token_spec.rb +++ b/spec/lib/gitlab/kubernetes/service_account_token_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::ServiceAccountToken do +RSpec.describe Gitlab::Kubernetes::ServiceAccountToken do let(:name) { 'token-name' } let(:service_account_name) { 'a_service_account' } let(:namespace_name) { 'a_namespace' } diff --git a/spec/lib/gitlab/kubernetes/tls_secret_spec.rb b/spec/lib/gitlab/kubernetes/tls_secret_spec.rb index 438a0dc79fc..b40ed3c88c9 100644 --- a/spec/lib/gitlab/kubernetes/tls_secret_spec.rb +++ b/spec/lib/gitlab/kubernetes/tls_secret_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes::TlsSecret do +RSpec.describe Gitlab::Kubernetes::TlsSecret do let(:secret) { described_class.new(name, cert, key, namespace) } let(:name) { 'example-name' } let(:cert) { 'example-cert' } diff --git a/spec/lib/gitlab/kubernetes_spec.rb b/spec/lib/gitlab/kubernetes_spec.rb index 40c3e7d0b3c..eff5c019ad0 100644 --- a/spec/lib/gitlab/kubernetes_spec.rb +++ b/spec/lib/gitlab/kubernetes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Kubernetes do +RSpec.describe Gitlab::Kubernetes do include KubernetesHelpers include described_class diff --git a/spec/lib/gitlab/language_data_spec.rb b/spec/lib/gitlab/language_data_spec.rb index b08150855fe..bb4b0c3855c 100644 --- a/spec/lib/gitlab/language_data_spec.rb +++ b/spec/lib/gitlab/language_data_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LanguageData do +RSpec.describe Gitlab::LanguageData do describe '#extensions' do before do described_class.clear_extensions! diff --git a/spec/lib/gitlab/language_detection_spec.rb b/spec/lib/gitlab/language_detection_spec.rb index 770fe2f80db..04ad19a04ec 100644 --- a/spec/lib/gitlab/language_detection_spec.rb +++ b/spec/lib/gitlab/language_detection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LanguageDetection do +RSpec.describe Gitlab::LanguageDetection do let_it_be(:project) { create(:project, :repository) } let_it_be(:ruby) { create(:programming_language, name: 'Ruby') } let_it_be(:haskell) { create(:programming_language, name: 'Haskell') } diff --git a/spec/lib/gitlab/lazy_spec.rb b/spec/lib/gitlab/lazy_spec.rb index 19758a18589..3e929cf200a 100644 --- a/spec/lib/gitlab/lazy_spec.rb +++ b/spec/lib/gitlab/lazy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Lazy do +RSpec.describe Gitlab::Lazy do let(:dummy) { double(:dummy) } context 'when not calling any methods' do diff --git a/spec/lib/gitlab/legacy_github_import/branch_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/branch_formatter_spec.rb index e96745f5fbe..1a21ed29ab7 100644 --- a/spec/lib/gitlab/legacy_github_import/branch_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/branch_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::BranchFormatter do +RSpec.describe Gitlab::LegacyGithubImport::BranchFormatter do let(:project) { create(:project, :repository) } let(:commit) { create(:commit, project: project) } let(:repo) { double } diff --git a/spec/lib/gitlab/legacy_github_import/client_spec.rb b/spec/lib/gitlab/legacy_github_import/client_spec.rb index d266b39bd81..0929b90d1f4 100644 --- a/spec/lib/gitlab/legacy_github_import/client_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::Client do +RSpec.describe Gitlab::LegacyGithubImport::Client do let(:token) { '123456' } let(:github_provider) { Settingslogic.new('app_id' => 'asd123', 'app_secret' => 'asd123', 'name' => 'github', 'args' => { 'client_options' => {} }) } let(:wait_for_rate_limit_reset) { true } diff --git a/spec/lib/gitlab/legacy_github_import/comment_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/comment_formatter_spec.rb index 0f03db312ce..85f7666fe85 100644 --- a/spec/lib/gitlab/legacy_github_import/comment_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/comment_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::CommentFormatter do +RSpec.describe Gitlab::LegacyGithubImport::CommentFormatter do let(:client) { double } let(:project) { create(:project) } let(:octocat) { double(id: 123456, login: 'octocat', email: 'octocat@example.com') } diff --git a/spec/lib/gitlab/legacy_github_import/importer_spec.rb b/spec/lib/gitlab/legacy_github_import/importer_spec.rb index 8cc3fd8efbd..c443944678f 100644 --- a/spec/lib/gitlab/legacy_github_import/importer_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::Importer do +RSpec.describe Gitlab::LegacyGithubImport::Importer do shared_examples 'Gitlab::LegacyGithubImport::Importer#execute' do let(:expected_not_called) { [] } diff --git a/spec/lib/gitlab/legacy_github_import/issuable_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/issuable_formatter_spec.rb index f5bfc379e89..6a51cb6f39d 100644 --- a/spec/lib/gitlab/legacy_github_import/issuable_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/issuable_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::IssuableFormatter do +RSpec.describe Gitlab::LegacyGithubImport::IssuableFormatter do let(:raw_data) do double(number: 42) end diff --git a/spec/lib/gitlab/legacy_github_import/issue_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/issue_formatter_spec.rb index 9a7a34afbe7..4b1e0d2c144 100644 --- a/spec/lib/gitlab/legacy_github_import/issue_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/issue_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::IssueFormatter do +RSpec.describe Gitlab::LegacyGithubImport::IssueFormatter do let(:client) { double } let!(:project) { create(:project, namespace: create(:namespace, path: 'octocat')) } let(:octocat) { double(id: 123456, login: 'octocat', email: 'octocat@example.com') } diff --git a/spec/lib/gitlab/legacy_github_import/label_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/label_formatter_spec.rb index e56e2772f6a..ab7c8ea4a58 100644 --- a/spec/lib/gitlab/legacy_github_import/label_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/label_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::LabelFormatter do +RSpec.describe Gitlab::LegacyGithubImport::LabelFormatter do let(:project) { create(:project) } let(:raw) { double(name: 'improvements', color: 'e6e6e6') } diff --git a/spec/lib/gitlab/legacy_github_import/milestone_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/milestone_formatter_spec.rb index f5d71888ac9..2ac79c4f5b8 100644 --- a/spec/lib/gitlab/legacy_github_import/milestone_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/milestone_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::MilestoneFormatter do +RSpec.describe Gitlab::LegacyGithubImport::MilestoneFormatter do let(:project) { create(:project) } let(:created_at) { DateTime.strptime('2011-01-26T19:01:12Z') } let(:updated_at) { DateTime.strptime('2011-01-27T19:01:12Z') } diff --git a/spec/lib/gitlab/legacy_github_import/project_creator_spec.rb b/spec/lib/gitlab/legacy_github_import/project_creator_spec.rb index b0687474c80..02cc2eba4da 100644 --- a/spec/lib/gitlab/legacy_github_import/project_creator_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/project_creator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::ProjectCreator do +RSpec.describe Gitlab::LegacyGithubImport::ProjectCreator do let(:user) { create(:user) } let(:namespace) { create(:group) } diff --git a/spec/lib/gitlab/legacy_github_import/pull_request_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/pull_request_formatter_spec.rb index 622210508b9..3e6b9340d0b 100644 --- a/spec/lib/gitlab/legacy_github_import/pull_request_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/pull_request_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::PullRequestFormatter do +RSpec.describe Gitlab::LegacyGithubImport::PullRequestFormatter do let(:client) { double } let(:project) { create(:project, :repository) } let(:source_sha) { create(:commit, project: project).id } diff --git a/spec/lib/gitlab/legacy_github_import/release_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/release_formatter_spec.rb index 554be57fbec..73b35d3a4e7 100644 --- a/spec/lib/gitlab/legacy_github_import/release_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/release_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::ReleaseFormatter do +RSpec.describe Gitlab::LegacyGithubImport::ReleaseFormatter do let!(:project) { create(:project, namespace: create(:namespace, path: 'octocat')) } let(:octocat) { double(id: 123456, login: 'octocat') } let(:created_at) { DateTime.strptime('2011-01-26T19:01:12Z') } diff --git a/spec/lib/gitlab/legacy_github_import/user_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/user_formatter_spec.rb index 919847fe061..34659030020 100644 --- a/spec/lib/gitlab/legacy_github_import/user_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/user_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::UserFormatter do +RSpec.describe Gitlab::LegacyGithubImport::UserFormatter do let(:client) { double } let(:octocat) { double(id: 123456, login: 'octocat', email: 'octocat@example.com') } diff --git a/spec/lib/gitlab/legacy_github_import/wiki_formatter_spec.rb b/spec/lib/gitlab/legacy_github_import/wiki_formatter_spec.rb index 639fb9d80eb..df443fa3dbb 100644 --- a/spec/lib/gitlab/legacy_github_import/wiki_formatter_spec.rb +++ b/spec/lib/gitlab/legacy_github_import/wiki_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LegacyGithubImport::WikiFormatter do +RSpec.describe Gitlab::LegacyGithubImport::WikiFormatter do let(:project) do create(:project, namespace: create(:namespace, path: 'gitlabhq'), diff --git a/spec/lib/gitlab/lets_encrypt/challenge_spec.rb b/spec/lib/gitlab/lets_encrypt/challenge_spec.rb index fcd92586362..d853275520b 100644 --- a/spec/lib/gitlab/lets_encrypt/challenge_spec.rb +++ b/spec/lib/gitlab/lets_encrypt/challenge_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::LetsEncrypt::Challenge do +RSpec.describe ::Gitlab::LetsEncrypt::Challenge do include LetsEncryptHelpers let(:challenge) { described_class.new(acme_challenge_double) } diff --git a/spec/lib/gitlab/lets_encrypt/client_spec.rb b/spec/lib/gitlab/lets_encrypt/client_spec.rb index e86de04b5cf..54b9bd3bfba 100644 --- a/spec/lib/gitlab/lets_encrypt/client_spec.rb +++ b/spec/lib/gitlab/lets_encrypt/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::LetsEncrypt::Client do +RSpec.describe ::Gitlab::LetsEncrypt::Client do include LetsEncryptHelpers let(:client) { described_class.new } diff --git a/spec/lib/gitlab/lets_encrypt/order_spec.rb b/spec/lib/gitlab/lets_encrypt/order_spec.rb index 333fce8e36a..419f9e28871 100644 --- a/spec/lib/gitlab/lets_encrypt/order_spec.rb +++ b/spec/lib/gitlab/lets_encrypt/order_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::LetsEncrypt::Order do +RSpec.describe ::Gitlab::LetsEncrypt::Order do include LetsEncryptHelpers let(:acme_order) { acme_order_double } diff --git a/spec/lib/gitlab/lets_encrypt_spec.rb b/spec/lib/gitlab/lets_encrypt_spec.rb index 2229393fb32..7597359847b 100644 --- a/spec/lib/gitlab/lets_encrypt_spec.rb +++ b/spec/lib/gitlab/lets_encrypt_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::LetsEncrypt do +RSpec.describe ::Gitlab::LetsEncrypt do include LetsEncryptHelpers before do diff --git a/spec/lib/gitlab/lfs_token_spec.rb b/spec/lib/gitlab/lfs_token_spec.rb index 58a3767b242..9b8b2c1417a 100644 --- a/spec/lib/gitlab/lfs_token_spec.rb +++ b/spec/lib/gitlab/lfs_token_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LfsToken, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::LfsToken, :clean_gitlab_redis_shared_state do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project) } let_it_be(:deploy_key) { create(:deploy_key) } diff --git a/spec/lib/gitlab/log_timestamp_formatter_spec.rb b/spec/lib/gitlab/log_timestamp_formatter_spec.rb index 1a76d02889b..e06baa2324f 100644 --- a/spec/lib/gitlab/log_timestamp_formatter_spec.rb +++ b/spec/lib/gitlab/log_timestamp_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LogTimestampFormatter do +RSpec.describe Gitlab::LogTimestampFormatter do subject { described_class.new } let(:formatted_timestamp) { Time.now.utc.iso8601(3) } diff --git a/spec/lib/gitlab/logging/cloudflare_helper_spec.rb b/spec/lib/gitlab/logging/cloudflare_helper_spec.rb index 2b73fb7bc1c..87ac438d38d 100644 --- a/spec/lib/gitlab/logging/cloudflare_helper_spec.rb +++ b/spec/lib/gitlab/logging/cloudflare_helper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Logging::CloudflareHelper do +RSpec.describe Gitlab::Logging::CloudflareHelper do let(:helper) do Class.new do include Gitlab::Logging::CloudflareHelper diff --git a/spec/lib/gitlab/lograge/custom_options_spec.rb b/spec/lib/gitlab/lograge/custom_options_spec.rb index ebf150d21ef..218007c6e2a 100644 --- a/spec/lib/gitlab/lograge/custom_options_spec.rb +++ b/spec/lib/gitlab/lograge/custom_options_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Lograge::CustomOptions do +RSpec.describe Gitlab::Lograge::CustomOptions do describe '.call' do let(:params) do { @@ -44,18 +44,6 @@ describe Gitlab::Lograge::CustomOptions do end end - context 'with transaction' do - let(:transaction) { Gitlab::Metrics::WebTransaction.new({}) } - - before do - allow(Gitlab::Metrics::Transaction).to receive(:current).and_return(transaction) - end - - it 'adds db counters' do - expect(subject).to include(:db_count, :db_write_count, :db_cached_count) - end - end - it 'adds the user id' do expect(subject[:user_id]).to eq('test') end @@ -77,14 +65,14 @@ describe Gitlab::Lograge::CustomOptions do end end - context 'when correlation_id is overriden' do + context 'when correlation_id is overridden' do let(:correlation_id_key) { Labkit::Correlation::CorrelationId::LOG_KEY } before do event_payload[correlation_id_key] = '123456' end - it 'sets the overriden value' do + it 'sets the overridden value' do expect(subject[correlation_id_key]).to eq('123456') end end diff --git a/spec/lib/gitlab/loop_helpers_spec.rb b/spec/lib/gitlab/loop_helpers_spec.rb index 7e59b41d5b9..0535cb6068c 100644 --- a/spec/lib/gitlab/loop_helpers_spec.rb +++ b/spec/lib/gitlab/loop_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::LoopHelpers do +RSpec.describe Gitlab::LoopHelpers do let(:class_instance) { (Class.new { include ::Gitlab::LoopHelpers }).new } describe '#loop_until' do diff --git a/spec/lib/gitlab/mail_room/mail_room_spec.rb b/spec/lib/gitlab/mail_room/mail_room_spec.rb index 4b09205a181..ab9a9a035f1 100644 --- a/spec/lib/gitlab/mail_room/mail_room_spec.rb +++ b/spec/lib/gitlab/mail_room/mail_room_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::MailRoom do +RSpec.describe Gitlab::MailRoom do let(:default_port) { 143 } let(:yml_config) do { diff --git a/spec/lib/gitlab/manifest_import/manifest_spec.rb b/spec/lib/gitlab/manifest_import/manifest_spec.rb index c1135f710ea..2e8753b0880 100644 --- a/spec/lib/gitlab/manifest_import/manifest_spec.rb +++ b/spec/lib/gitlab/manifest_import/manifest_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ManifestImport::Manifest do +RSpec.describe Gitlab::ManifestImport::Manifest do let(:file) { File.open(Rails.root.join('spec/fixtures/aosp_manifest.xml')) } let(:manifest) { described_class.new(file) } diff --git a/spec/lib/gitlab/manifest_import/project_creator_spec.rb b/spec/lib/gitlab/manifest_import/project_creator_spec.rb index a8cfcfb41d3..354acf53b7a 100644 --- a/spec/lib/gitlab/manifest_import/project_creator_spec.rb +++ b/spec/lib/gitlab/manifest_import/project_creator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ManifestImport::ProjectCreator do +RSpec.describe Gitlab::ManifestImport::ProjectCreator do let(:group) { create(:group) } let(:user) { create(:user) } let(:repository) do diff --git a/spec/lib/gitlab/markdown_cache/active_record/extension_spec.rb b/spec/lib/gitlab/markdown_cache/active_record/extension_spec.rb index 5b6c769d6eb..be562d916d3 100644 --- a/spec/lib/gitlab/markdown_cache/active_record/extension_spec.rb +++ b/spec/lib/gitlab/markdown_cache/active_record/extension_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::MarkdownCache::ActiveRecord::Extension do +RSpec.describe Gitlab::MarkdownCache::ActiveRecord::Extension do let(:klass) do Class.new(ActiveRecord::Base) do self.table_name = 'issues' diff --git a/spec/lib/gitlab/markdown_cache/field_data_spec.rb b/spec/lib/gitlab/markdown_cache/field_data_spec.rb index 393bf85aa43..76d8cbe6b7d 100644 --- a/spec/lib/gitlab/markdown_cache/field_data_spec.rb +++ b/spec/lib/gitlab/markdown_cache/field_data_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::MarkdownCache::FieldData do +RSpec.describe Gitlab::MarkdownCache::FieldData do subject(:field_data) { described_class.new } before do diff --git a/spec/lib/gitlab/markdown_cache/redis/extension_spec.rb b/spec/lib/gitlab/markdown_cache/redis/extension_spec.rb index b6a781de426..3dcb9f160ba 100644 --- a/spec/lib/gitlab/markdown_cache/redis/extension_spec.rb +++ b/spec/lib/gitlab/markdown_cache/redis/extension_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::MarkdownCache::Redis::Extension, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::MarkdownCache::Redis::Extension, :clean_gitlab_redis_cache do let(:klass) do Class.new do include CacheMarkdownField @@ -49,6 +49,31 @@ describe Gitlab::MarkdownCache::Redis::Extension, :clean_gitlab_redis_cache do expect(thing.cached_markdown_version).to eq(cache_version) end + describe '.preload_markdown_cache!' do + before do + Gitlab::Redis::Cache.with do |r| + r.mapped_hmset(expected_cache_key, + title_html: 'hello', + description_html: 'world', + cached_markdown_version: cache_version) + end + end + + it 'does not preload the markdown twice' do + expect(Gitlab::MarkdownCache::Redis::Store).to receive(:bulk_read).and_call_original + expect(Gitlab::Redis::Cache).to receive(:with).twice.and_call_original + + klass.preload_markdown_cache!([thing]) + + aggregate_failures do + expect(Gitlab::Redis::Cache).not_to receive(:with) + expect(thing.title_html).to eq('hello') + expect(thing.description_html).to eq('world') + expect(thing.cached_markdown_version).to eq(cache_version) + end + end + end + describe "#refresh_markdown_cache!" do it "stores the value in redis" do expected_results = { "title_html" => "`Hello`", diff --git a/spec/lib/gitlab/markdown_cache/redis/store_spec.rb b/spec/lib/gitlab/markdown_cache/redis/store_spec.rb index 95c68e7d491..40ff9a765a6 100644 --- a/spec/lib/gitlab/markdown_cache/redis/store_spec.rb +++ b/spec/lib/gitlab/markdown_cache/redis/store_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::MarkdownCache::Redis::Store, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::MarkdownCache::Redis::Store, :clean_gitlab_redis_cache do let(:storable_class) do Class.new do cattr_reader :cached_markdown_fields do @@ -37,6 +37,23 @@ describe Gitlab::MarkdownCache::Redis::Store, :clean_gitlab_redis_cache do end end + describe '.bulk_read' do + before do + store.save(field_1_html: "hello", field_2_html: "world", cached_markdown_version: 1) + end + + it 'returns a hash of values from store' do + Gitlab::Redis::Cache.with do |redis| + expect(redis).to receive(:pipelined).and_call_original + end + + results = described_class.bulk_read([storable]) + + expect(results[storable.cache_key].value.symbolize_keys) + .to eq(field_1_html: "hello", field_2_html: "world", cached_markdown_version: "1") + end + end + describe '#save' do it 'stores updates to html fields and version' do values_to_store = { field_1_html: "hello", field_2_html: "world", cached_markdown_version: 1 } @@ -44,7 +61,7 @@ describe Gitlab::MarkdownCache::Redis::Store, :clean_gitlab_redis_cache do store.save(values_to_store) expect(read_values) - .to eq({ field_1_html: "hello", field_2_html: "world", cached_markdown_version: "1" }) + .to eq(field_1_html: "hello", field_2_html: "world", cached_markdown_version: "1") end end @@ -54,7 +71,8 @@ describe Gitlab::MarkdownCache::Redis::Store, :clean_gitlab_redis_cache do store_values(stored_values) - expect(store.read.symbolize_keys).to eq(stored_values) + expect(store.read.symbolize_keys) + .to eq(field_1_html: "hello", field_2_html: "world", cached_markdown_version: "1") end it 'is mared loaded after reading' do diff --git a/spec/lib/gitlab/markup_helper_spec.rb b/spec/lib/gitlab/markup_helper_spec.rb index b93538cae5a..bf5415ba1d7 100644 --- a/spec/lib/gitlab/markup_helper_spec.rb +++ b/spec/lib/gitlab/markup_helper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::MarkupHelper do +RSpec.describe Gitlab::MarkupHelper do describe '#markup?' do %w(textile rdoc org creole wiki mediawiki rst adoc ad asciidoc mdown md markdown).each do |type| diff --git a/spec/lib/gitlab/metrics/background_transaction_spec.rb b/spec/lib/gitlab/metrics/background_transaction_spec.rb index 84f405d7369..640bbebf0da 100644 --- a/spec/lib/gitlab/metrics/background_transaction_spec.rb +++ b/spec/lib/gitlab/metrics/background_transaction_spec.rb @@ -2,14 +2,23 @@ require 'spec_helper' -describe Gitlab::Metrics::BackgroundTransaction do +RSpec.describe Gitlab::Metrics::BackgroundTransaction do let(:test_worker_class) { double(:class, name: 'TestWorker') } subject { described_class.new(test_worker_class) } describe '#label' do it 'returns labels based on class name' do - expect(subject.labels).to eq(controller: 'TestWorker', action: 'perform') + expect(subject.labels).to eq(controller: 'TestWorker', action: 'perform', feature_category: '') + end + + it 'contains only the labels defined for metrics' do + expect(subject.labels.keys).to contain_exactly(*described_class.superclass::BASE_LABELS.keys) + end + + it 'includes the feature category if there is one' do + expect(test_worker_class).to receive(:get_feature_category).and_return('source_code_management') + expect(subject.labels).to include(feature_category: 'source_code_management') end end end diff --git a/spec/lib/gitlab/metrics/dashboard/defaults_spec.rb b/spec/lib/gitlab/metrics/dashboard/defaults_spec.rb index 420b246b3f5..dd61f8ebc4d 100644 --- a/spec/lib/gitlab/metrics/dashboard/defaults_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/defaults_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Dashboard::Defaults do +RSpec.describe Gitlab::Metrics::Dashboard::Defaults do it { is_expected.to be_const_defined(:DEFAULT_PANEL_TYPE) } it { is_expected.to be_const_defined(:DEFAULT_PANEL_WEIGHT) } end diff --git a/spec/lib/gitlab/metrics/dashboard/finder_spec.rb b/spec/lib/gitlab/metrics/dashboard/finder_spec.rb index 2703339d89c..60e1e29d4c5 100644 --- a/spec/lib/gitlab/metrics/dashboard/finder_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_caching do +RSpec.describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_caching do include MetricsDashboardHelpers let_it_be(:project) { create(:project) } @@ -118,7 +118,7 @@ describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_cachi end describe '.find_raw' do - let(:dashboard) { YAML.load_file(Rails.root.join('config', 'prometheus', 'common_metrics.yml')) } + let(:dashboard) { load_dashboard_yaml(File.read(Rails.root.join('config', 'prometheus', 'common_metrics.yml'))) } let(:params) { {} } subject { described_class.find_raw(project, **params) } @@ -132,7 +132,7 @@ describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_cachi end context 'when an existing project dashboard is specified' do - let(:dashboard) { YAML.safe_load(fixture_file('lib/gitlab/metrics/dashboard/sample_dashboard.yml')) } + let(:dashboard) { load_sample_dashboard } let(:params) { { dashboard_path: '.gitlab/dashboards/test.yml' } } let(:project) { project_with_dashboard(params[:dashboard_path]) } @@ -142,7 +142,7 @@ describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_cachi describe '.find_all_paths' do let(:all_dashboard_paths) { described_class.find_all_paths(project) } - let(:system_dashboard) { { path: system_dashboard_path, display_name: 'Default dashboard', default: true, system_dashboard: true } } + let(:system_dashboard) { { path: system_dashboard_path, display_name: 'Default dashboard', default: true, system_dashboard: true, out_of_the_box_dashboard: true } } it 'includes only the system dashboard by default' do expect(all_dashboard_paths).to eq([system_dashboard]) @@ -153,7 +153,7 @@ describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_cachi let(:project) { project_with_dashboard(dashboard_path) } it 'includes system and project dashboards' do - project_dashboard = { path: dashboard_path, display_name: 'test.yml', default: false, system_dashboard: false } + project_dashboard = { path: dashboard_path, display_name: 'test.yml', default: false, system_dashboard: false, out_of_the_box_dashboard: false } expect(all_dashboard_paths).to contain_exactly(system_dashboard, project_dashboard) end @@ -165,7 +165,8 @@ describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_cachi path: self_monitoring_dashboard_path, display_name: 'Default dashboard', default: true, - system_dashboard: false + system_dashboard: false, + out_of_the_box_dashboard: true } end let(:dashboard_path) { '.gitlab/dashboards/test.yml' } @@ -180,7 +181,8 @@ describe Gitlab::Metrics::Dashboard::Finder, :use_clean_rails_memory_store_cachi path: dashboard_path, display_name: 'test.yml', default: false, - system_dashboard: false + system_dashboard: false, + out_of_the_box_dashboard: false } expect(all_dashboard_paths).to contain_exactly(self_monitoring_dashboard, project_dashboard) diff --git a/spec/lib/gitlab/metrics/dashboard/processor_spec.rb b/spec/lib/gitlab/metrics/dashboard/processor_spec.rb index 7250cefb9ff..7f7070dfafb 100644 --- a/spec/lib/gitlab/metrics/dashboard/processor_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/processor_spec.rb @@ -2,10 +2,12 @@ require 'spec_helper' -describe Gitlab::Metrics::Dashboard::Processor do +RSpec.describe Gitlab::Metrics::Dashboard::Processor do + include MetricsDashboardHelpers + let(:project) { build(:project) } let(:environment) { create(:environment, project: project) } - let(:dashboard_yml) { YAML.load_file('spec/fixtures/lib/gitlab/metrics/dashboard/sample_dashboard.yml') } + let(:dashboard_yml) { load_sample_dashboard } describe 'process' do let(:sequence) do @@ -13,7 +15,7 @@ describe Gitlab::Metrics::Dashboard::Processor do Gitlab::Metrics::Dashboard::Stages::CommonMetricsInserter, Gitlab::Metrics::Dashboard::Stages::CustomMetricsInserter, Gitlab::Metrics::Dashboard::Stages::CustomMetricsDetailsInserter, - Gitlab::Metrics::Dashboard::Stages::EndpointInserter, + Gitlab::Metrics::Dashboard::Stages::MetricEndpointInserter, Gitlab::Metrics::Dashboard::Stages::Sorter, Gitlab::Metrics::Dashboard::Stages::AlertsInserter, Gitlab::Metrics::Dashboard::Stages::PanelIdsInserter, @@ -98,7 +100,7 @@ describe Gitlab::Metrics::Dashboard::Processor do let(:sequence) do [ Gitlab::Metrics::Dashboard::Stages::CommonMetricsInserter, - Gitlab::Metrics::Dashboard::Stages::EndpointInserter, + Gitlab::Metrics::Dashboard::Stages::MetricEndpointInserter, Gitlab::Metrics::Dashboard::Stages::Sorter ] end @@ -202,27 +204,6 @@ describe Gitlab::Metrics::Dashboard::Processor do it_behaves_like 'errors with message', 'Each "metric" must define one of :query or :query_range' end - - describe 'validating links' do - context 'when the links contain a blocked url' do - let(:dashboard_yml_links) do - [{ 'url' => 'http://1.1.1.1.1' }, { 'url' => 'https://gitlab.com' }] - end - - let(:expected) do - [{ url: '' }, { url: 'https://gitlab.com' }] - end - - before do - stub_env('RSPEC_ALLOW_INVALID_URLS', 'false') - dashboard_yml['links'] = dashboard_yml_links - end - - it 'replaces the blocked url with an empty string' do - expect(dashboard[:links]).to eq(expected) - end - end - end end private diff --git a/spec/lib/gitlab/metrics/dashboard/service_selector_spec.rb b/spec/lib/gitlab/metrics/dashboard/service_selector_spec.rb index 245c98cdd00..f3c8209e0b6 100644 --- a/spec/lib/gitlab/metrics/dashboard/service_selector_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/service_selector_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Dashboard::ServiceSelector do +RSpec.describe Gitlab::Metrics::Dashboard::ServiceSelector do include MetricsDashboardHelpers describe '#call' do @@ -109,6 +109,46 @@ describe Gitlab::Metrics::Dashboard::ServiceSelector do it { is_expected.to be Metrics::Dashboard::TransientEmbedService } end + + context 'when cluster is provided' do + let(:arguments) { { cluster: "some cluster" } } + + it { is_expected.to be Metrics::Dashboard::ClusterDashboardService } + end + + context 'when cluster is provided and embedded is not true' do + let(:arguments) { { cluster: "some cluster", embedded: 'false' } } + + it { is_expected.to be Metrics::Dashboard::ClusterDashboardService } + end + + context 'when cluster dashboard_path is provided' do + let(:arguments) { { dashboard_path: ::Metrics::Dashboard::ClusterDashboardService::DASHBOARD_PATH } } + + it { is_expected.to be Metrics::Dashboard::ClusterDashboardService } + end + + context 'when cluster is provided and embed params' do + let(:arguments) do + { + cluster: "some cluster", + embedded: 'true', + cluster_type: 'project', + format: :json, + group: 'Food metrics', + title: 'Pizza Consumption', + y_label: 'Slice Count' + } + end + + it { is_expected.to be Metrics::Dashboard::ClusterMetricsEmbedService } + end + + context 'when metrics embed is for an alert' do + let(:arguments) { { embedded: true, prometheus_alert_id: 5 } } + + it { is_expected.to be Metrics::Dashboard::GitlabAlertEmbedService } + end end end end diff --git a/spec/lib/gitlab/metrics/dashboard/stages/grafana_formatter_spec.rb b/spec/lib/gitlab/metrics/dashboard/stages/grafana_formatter_spec.rb index 5d4bd4512e3..8a236f72a60 100644 --- a/spec/lib/gitlab/metrics/dashboard/stages/grafana_formatter_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/stages/grafana_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Dashboard::Stages::GrafanaFormatter do +RSpec.describe Gitlab::Metrics::Dashboard::Stages::GrafanaFormatter do include GrafanaApiHelpers let_it_be(:namespace) { create(:namespace, name: 'foo') } diff --git a/spec/lib/gitlab/metrics/dashboard/stages/panel_ids_inserter_spec.rb b/spec/lib/gitlab/metrics/dashboard/stages/panel_ids_inserter_spec.rb index 6124f471e39..7a3a9021f86 100644 --- a/spec/lib/gitlab/metrics/dashboard/stages/panel_ids_inserter_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/stages/panel_ids_inserter_spec.rb @@ -2,7 +2,9 @@ require 'spec_helper' -describe Gitlab::Metrics::Dashboard::Stages::PanelIdsInserter do +RSpec.describe Gitlab::Metrics::Dashboard::Stages::PanelIdsInserter do + include MetricsDashboardHelpers + let(:project) { build_stubbed(:project) } def fetch_panel_ids(dashboard_hash) @@ -12,7 +14,7 @@ describe Gitlab::Metrics::Dashboard::Stages::PanelIdsInserter do describe '#transform!' do subject(:transform!) { described_class.new(project, dashboard, nil).transform! } - let(:dashboard) { YAML.safe_load(fixture_file('lib/gitlab/metrics/dashboard/sample_dashboard.yml')).deep_symbolize_keys } + let(:dashboard) { load_sample_dashboard.deep_symbolize_keys } context 'when dashboard panels are present' do it 'assigns unique ids to each panel using PerformanceMonitoring::PrometheusPanel', :aggregate_failures do diff --git a/spec/lib/gitlab/metrics/dashboard/stages/url_validator_spec.rb b/spec/lib/gitlab/metrics/dashboard/stages/url_validator_spec.rb new file mode 100644 index 00000000000..83cf161c4e2 --- /dev/null +++ b/spec/lib/gitlab/metrics/dashboard/stages/url_validator_spec.rb @@ -0,0 +1,101 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Metrics::Dashboard::Stages::UrlValidator do + let(:project) { build_stubbed(:project) } + + describe '#transform!' do + context 'when the links contain a blocked url' do + let(:dashboard) do + { + dashboard: "Test Dashboard", + links: [ + { url: "http://1.1.1.1.1" }, + { url: "https://gitlab.com" }, + { url: "http://0.0.0.0" } + ], + panel_groups: [ + { + group: "Group A", + panels: [ + { + title: "Super Chart A1", + type: "area-chart", + y_label: "y_label", + metrics: [ + { + id: "metric_a1", + query_range: "query", + unit: "unit", + label: "Legend Label" + } + ], + links: [ + { url: "http://1.1.1.1.1" }, + { url: "https://gitlab.com" }, + { url: "http://0.0.0.0" } + ] + } + ] + } + ] + } + end + + let(:expected) do + [{ url: '' }, { url: 'https://gitlab.com' }, { url: 'http://0.0.0.0' }] + end + + let(:transform!) { described_class.new(project, dashboard, nil).transform! } + + before do + stub_env('RSPEC_ALLOW_INVALID_URLS', 'false') + stub_application_setting(allow_local_requests_from_web_hooks_and_services: true) + end + + context 'dashboard related links' do + it 'replaces the blocked url with an empty string' do + transform! + + expect(dashboard[:links]).to eq(expected) + end + end + + context 'chart links' do + it 'replaces the blocked url with an empty string' do + transform! + + result = dashboard.dig(:panel_groups, 0, :panels, 0, :links) + expect(result).to eq(expected) + end + end + + context 'when local requests are not allowed' do + before do + stub_application_setting(allow_local_requests_from_web_hooks_and_services: false) + end + + let(:expected) do + [{ url: '' }, { url: 'https://gitlab.com' }, { url: '' }] + end + + it 'replaces the blocked url with an empty string' do + transform! + + expect(dashboard[:links]).to eq(expected) + end + end + + context 'when the links are an array of strings instead of hashes' do + before do + dashboard[:links] = dashboard[:links].map(&:values) + end + + it 'prevents an invalid link definition from erroring out' do + expect { transform! }.not_to raise_error + end + end + end + end +end diff --git a/spec/lib/gitlab/metrics/dashboard/stages/variable_endpoint_inserter_spec.rb b/spec/lib/gitlab/metrics/dashboard/stages/variable_endpoint_inserter_spec.rb new file mode 100644 index 00000000000..9303ff981fb --- /dev/null +++ b/spec/lib/gitlab/metrics/dashboard/stages/variable_endpoint_inserter_spec.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Metrics::Dashboard::Stages::VariableEndpointInserter do + include MetricsDashboardHelpers + + let(:project) { build_stubbed(:project) } + let(:environment) { build_stubbed(:environment, project: project) } + + describe '#transform!' do + subject(:transform!) { described_class.new(project, dashboard, environment: environment).transform! } + + let(:dashboard) { load_sample_dashboard.deep_symbolize_keys } + + context 'when dashboard variables are present' do + it 'assigns prometheus_endpoint_path to metric_label_values variable type' do + endpoint_path = Gitlab::Routing.url_helpers.prometheus_api_project_environment_path( + project, + environment, + proxy_path: :series, + match: ['backend:haproxy_backend_availability:ratio{env="{{env}}"}'] + ) + + transform! + + expect( + dashboard.dig(:templating, :variables, :metric_label_values_variable, :options) + ).to include(prometheus_endpoint_path: endpoint_path) + end + + it 'does not modify other variable types' do + original_text_variable = dashboard[:templating][:variables][:text_variable_full_syntax].deep_dup + + transform! + + expect(dashboard[:templating][:variables][:text_variable_full_syntax]).to eq(original_text_variable) + end + + context 'when variable does not have the required series_selector' do + it 'adds prometheus_endpoint_path without match parameter' do + dashboard[:templating][:variables][:metric_label_values_variable][:options].delete(:series_selector) + endpoint_path = Gitlab::Routing.url_helpers.prometheus_api_project_environment_path( + project, + environment, + proxy_path: :series + ) + + transform! + + expect( + dashboard.dig(:templating, :variables, :metric_label_values_variable, :options) + ).to include(prometheus_endpoint_path: endpoint_path) + end + end + end + + context 'when no variables are present' do + it 'does not fail' do + dashboard.delete(:templating) + + expect { transform! }.not_to raise_error + end + end + + context 'with no environment' do + subject(:transform!) { described_class.new(project, dashboard, {}).transform! } + + it 'raises error' do + expect { transform! }.to raise_error( + Gitlab::Metrics::Dashboard::Errors::DashboardProcessingError, + 'Environment is required for Stages::VariableEndpointInserter' + ) + end + end + end +end diff --git a/spec/lib/gitlab/metrics/dashboard/url_spec.rb b/spec/lib/gitlab/metrics/dashboard/url_spec.rb index 75f9f99c8a6..56556423b05 100644 --- a/spec/lib/gitlab/metrics/dashboard/url_spec.rb +++ b/spec/lib/gitlab/metrics/dashboard/url_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Dashboard::Url do +RSpec.describe Gitlab::Metrics::Dashboard::Url do include Gitlab::Routing.url_helpers describe '#metrics_regex' do @@ -46,6 +46,35 @@ describe Gitlab::Metrics::Dashboard::Url do end end + describe '#clusters_regex' do + let(:url) do + Gitlab::Routing.url_helpers.namespace_project_cluster_url( + 'foo', + 'bar', + '1', + group: 'Cluster Health', + title: 'Memory Usage', + y_label: 'Memory 20(GiB)', + anchor: 'title' + ) + end + + let(:expected_params) do + { + 'url' => url, + 'namespace' => 'foo', + 'project' => 'bar', + 'cluster_id' => '1', + 'query' => '?group=Cluster+Health&title=Memory+Usage&y_label=Memory+20%28GiB%29', + 'anchor' => '#title' + } + end + + subject { described_class.clusters_regex } + + it_behaves_like 'regex which matches url when expected' + end + describe '#grafana_regex' do let(:url) do namespace_project_grafana_api_metrics_dashboard_url( diff --git a/spec/lib/gitlab/metrics/delta_spec.rb b/spec/lib/gitlab/metrics/delta_spec.rb index 9bb011dc8fc..e768da875c2 100644 --- a/spec/lib/gitlab/metrics/delta_spec.rb +++ b/spec/lib/gitlab/metrics/delta_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Delta do +RSpec.describe Gitlab::Metrics::Delta do let(:delta) { described_class.new } describe '#compared_with' do diff --git a/spec/lib/gitlab/metrics/elasticsearch_rack_middleware_spec.rb b/spec/lib/gitlab/metrics/elasticsearch_rack_middleware_spec.rb index 305768ef060..1fbd41bcc88 100644 --- a/spec/lib/gitlab/metrics/elasticsearch_rack_middleware_spec.rb +++ b/spec/lib/gitlab/metrics/elasticsearch_rack_middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::ElasticsearchRackMiddleware do +RSpec.describe Gitlab::Metrics::ElasticsearchRackMiddleware do let(:app) { double(:app, call: 'app call result') } let(:middleware) { described_class.new(app) } let(:env) { {} } diff --git a/spec/lib/gitlab/metrics/exporter/base_exporter_spec.rb b/spec/lib/gitlab/metrics/exporter/base_exporter_spec.rb index 47ec69e2f45..e4f85243528 100644 --- a/spec/lib/gitlab/metrics/exporter/base_exporter_spec.rb +++ b/spec/lib/gitlab/metrics/exporter/base_exporter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Exporter::BaseExporter do +RSpec.describe Gitlab::Metrics::Exporter::BaseExporter do let(:exporter) { described_class.new } let(:log_filename) { File.join(Rails.root, 'log', 'sidekiq_exporter.log') } let(:settings) { double('settings') } diff --git a/spec/lib/gitlab/metrics/exporter/sidekiq_exporter_spec.rb b/spec/lib/gitlab/metrics/exporter/sidekiq_exporter_spec.rb index 0b820fdbde9..2c5ef09f799 100644 --- a/spec/lib/gitlab/metrics/exporter/sidekiq_exporter_spec.rb +++ b/spec/lib/gitlab/metrics/exporter/sidekiq_exporter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Exporter::SidekiqExporter do +RSpec.describe Gitlab::Metrics::Exporter::SidekiqExporter do let(:exporter) { described_class.new } after do diff --git a/spec/lib/gitlab/metrics/exporter/web_exporter_spec.rb b/spec/lib/gitlab/metrics/exporter/web_exporter_spec.rb index f22993cf057..ce98c807e2e 100644 --- a/spec/lib/gitlab/metrics/exporter/web_exporter_spec.rb +++ b/spec/lib/gitlab/metrics/exporter/web_exporter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Exporter::WebExporter do +RSpec.describe Gitlab::Metrics::Exporter::WebExporter do let(:exporter) { described_class.new } let(:readiness_probe) { exporter.send(:readiness_probe).execute } diff --git a/spec/lib/gitlab/metrics/instrumentation_spec.rb b/spec/lib/gitlab/metrics/instrumentation_spec.rb index bf84a476df9..2729fbce974 100644 --- a/spec/lib/gitlab/metrics/instrumentation_spec.rb +++ b/spec/lib/gitlab/metrics/instrumentation_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Instrumentation do +RSpec.describe Gitlab::Metrics::Instrumentation do let(:env) { {} } let(:transaction) { Gitlab::Metrics::WebTransaction.new(env) } diff --git a/spec/lib/gitlab/metrics/method_call_spec.rb b/spec/lib/gitlab/metrics/method_call_spec.rb index 035d875258c..42361cbc36a 100644 --- a/spec/lib/gitlab/metrics/method_call_spec.rb +++ b/spec/lib/gitlab/metrics/method_call_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::MethodCall do +RSpec.describe Gitlab::Metrics::MethodCall do let(:transaction) { double(:transaction, labels: {}) } let(:method_call) { described_class.new('Foo#bar', :Foo, '#bar', transaction) } diff --git a/spec/lib/gitlab/metrics/methods_spec.rb b/spec/lib/gitlab/metrics/methods_spec.rb index 5cf8db55142..3c171680272 100644 --- a/spec/lib/gitlab/metrics/methods_spec.rb +++ b/spec/lib/gitlab/metrics/methods_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Methods do +RSpec.describe Gitlab::Metrics::Methods do subject { Class.new { include Gitlab::Metrics::Methods } } shared_context 'metric' do |metric_type, *args| diff --git a/spec/lib/gitlab/metrics/prometheus_spec.rb b/spec/lib/gitlab/metrics/prometheus_spec.rb index e15a063fc9e..2273987551d 100644 --- a/spec/lib/gitlab/metrics/prometheus_spec.rb +++ b/spec/lib/gitlab/metrics/prometheus_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Prometheus, :prometheus do +RSpec.describe Gitlab::Metrics::Prometheus, :prometheus do let(:all_metrics) { Gitlab::Metrics } let(:registry) { all_metrics.registry } diff --git a/spec/lib/gitlab/metrics/rack_middleware_spec.rb b/spec/lib/gitlab/metrics/rack_middleware_spec.rb index dd1dbf7a1f4..335e5a490a6 100644 --- a/spec/lib/gitlab/metrics/rack_middleware_spec.rb +++ b/spec/lib/gitlab/metrics/rack_middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::RackMiddleware do +RSpec.describe Gitlab::Metrics::RackMiddleware do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } diff --git a/spec/lib/gitlab/metrics/redis_rack_middleware_spec.rb b/spec/lib/gitlab/metrics/redis_rack_middleware_spec.rb index f2f36ccad20..a85968dbd43 100644 --- a/spec/lib/gitlab/metrics/redis_rack_middleware_spec.rb +++ b/spec/lib/gitlab/metrics/redis_rack_middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::RedisRackMiddleware do +RSpec.describe Gitlab::Metrics::RedisRackMiddleware do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } let(:env) { {} } diff --git a/spec/lib/gitlab/metrics/requests_rack_middleware_spec.rb b/spec/lib/gitlab/metrics/requests_rack_middleware_spec.rb index 6ee8acbf6fd..69b779d36eb 100644 --- a/spec/lib/gitlab/metrics/requests_rack_middleware_spec.rb +++ b/spec/lib/gitlab/metrics/requests_rack_middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::RequestsRackMiddleware do +RSpec.describe Gitlab::Metrics::RequestsRackMiddleware do let(:app) { double('app') } subject { described_class.new(app) } diff --git a/spec/lib/gitlab/metrics/samplers/database_sampler_spec.rb b/spec/lib/gitlab/metrics/samplers/database_sampler_spec.rb index 087a0bfbac5..b94d19ff227 100644 --- a/spec/lib/gitlab/metrics/samplers/database_sampler_spec.rb +++ b/spec/lib/gitlab/metrics/samplers/database_sampler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Samplers::DatabaseSampler do +RSpec.describe Gitlab::Metrics::Samplers::DatabaseSampler do subject { described_class.new } describe '#interval' do diff --git a/spec/lib/gitlab/metrics/samplers/puma_sampler_spec.rb b/spec/lib/gitlab/metrics/samplers/puma_sampler_spec.rb index df63f2ebe28..214649d3e7e 100644 --- a/spec/lib/gitlab/metrics/samplers/puma_sampler_spec.rb +++ b/spec/lib/gitlab/metrics/samplers/puma_sampler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Samplers::PumaSampler do +RSpec.describe Gitlab::Metrics::Samplers::PumaSampler do subject { described_class.new } let(:null_metric) { double('null_metric', set: nil, observe: nil) } diff --git a/spec/lib/gitlab/metrics/samplers/ruby_sampler_spec.rb b/spec/lib/gitlab/metrics/samplers/ruby_sampler_spec.rb index 9fc8dd10922..59a70ac74a5 100644 --- a/spec/lib/gitlab/metrics/samplers/ruby_sampler_spec.rb +++ b/spec/lib/gitlab/metrics/samplers/ruby_sampler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Samplers::RubySampler do +RSpec.describe Gitlab::Metrics::Samplers::RubySampler do let(:sampler) { described_class.new } let(:null_metric) { double('null_metric', set: nil, observe: nil) } diff --git a/spec/lib/gitlab/metrics/samplers/unicorn_sampler_spec.rb b/spec/lib/gitlab/metrics/samplers/unicorn_sampler_spec.rb index a64aae73d43..9f2180c4170 100644 --- a/spec/lib/gitlab/metrics/samplers/unicorn_sampler_spec.rb +++ b/spec/lib/gitlab/metrics/samplers/unicorn_sampler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Samplers::UnicornSampler do +RSpec.describe Gitlab::Metrics::Samplers::UnicornSampler do subject { described_class.new(1.second) } describe '#sample' do diff --git a/spec/lib/gitlab/metrics/sidekiq_middleware_spec.rb b/spec/lib/gitlab/metrics/sidekiq_middleware_spec.rb index ea9e8fa6795..c66d8b1075c 100644 --- a/spec/lib/gitlab/metrics/sidekiq_middleware_spec.rb +++ b/spec/lib/gitlab/metrics/sidekiq_middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::SidekiqMiddleware do +RSpec.describe Gitlab::Metrics::SidekiqMiddleware do let(:middleware) { described_class.new } let(:message) { { 'args' => ['test'], 'enqueued_at' => Time.new(2016, 6, 23, 6, 59).to_f } } @@ -18,8 +18,20 @@ describe Gitlab::Metrics::SidekiqMiddleware do middleware.call(worker, message, :test) do ActiveRecord::Base.connection.execute('SELECT pg_sleep(0.1);') end + end + + it 'prevents database counters from leaking to the next transaction' do + worker = double(:worker, class: double(:class, name: 'TestWorker')) - expect(message).to include(:db_count, :db_write_count, :db_cached_count) + 2.times do + Gitlab::WithRequestStore.with_request_store do + middleware.call(worker, message, :test) do + ActiveRecord::Base.connection.execute('SELECT pg_sleep(0.1);') + end + end + end + + expect(message).to include(db_count: 1, db_write_count: 0, db_cached_count: 0) end it 'tracks the transaction (for messages without `enqueued_at`)', :aggregate_failures do @@ -35,19 +47,20 @@ describe Gitlab::Metrics::SidekiqMiddleware do middleware.call(worker, {}, :test) { nil } end - it 'tracks any raised exceptions', :aggregate_failures do + it 'tracks any raised exceptions', :aggregate_failures, :request_store do worker = double(:worker, class: double(:class, name: 'TestWorker')) expect_any_instance_of(Gitlab::Metrics::Transaction) - .to receive(:run).and_raise(RuntimeError) - - expect_any_instance_of(Gitlab::Metrics::Transaction) .to receive(:add_event).with(:sidekiq_exception) - expect { middleware.call(worker, message, :test) } - .to raise_error(RuntimeError) + expect do + middleware.call(worker, message, :test) do + ActiveRecord::Base.connection.execute('SELECT pg_sleep(0.1);') + raise RuntimeError + end + end.to raise_error(RuntimeError) - expect(message).to include(:db_count, :db_write_count, :db_cached_count) + expect(message).to include(db_count: 1, db_write_count: 0, db_cached_count: 0) end end end diff --git a/spec/lib/gitlab/metrics/subscribers/action_view_spec.rb b/spec/lib/gitlab/metrics/subscribers/action_view_spec.rb index 857e54d3432..161527c01aa 100644 --- a/spec/lib/gitlab/metrics/subscribers/action_view_spec.rb +++ b/spec/lib/gitlab/metrics/subscribers/action_view_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Subscribers::ActionView do +RSpec.describe Gitlab::Metrics::Subscribers::ActionView do let(:env) { {} } let(:transaction) { Gitlab::Metrics::WebTransaction.new(env) } diff --git a/spec/lib/gitlab/metrics/subscribers/active_record_spec.rb b/spec/lib/gitlab/metrics/subscribers/active_record_spec.rb index a78d048908d..2fd5dd1d83b 100644 --- a/spec/lib/gitlab/metrics/subscribers/active_record_spec.rb +++ b/spec/lib/gitlab/metrics/subscribers/active_record_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Subscribers::ActiveRecord do +RSpec.describe Gitlab::Metrics::Subscribers::ActiveRecord do let(:env) { {} } let(:transaction) { Gitlab::Metrics::WebTransaction.new(env) } let(:subscriber) { described_class.new } @@ -28,60 +28,45 @@ describe Gitlab::Metrics::Subscribers::ActiveRecord do end describe 'with a current transaction' do - shared_examples 'read only query' do - it 'increments only db count value' do + shared_examples 'track executed query' do + before do allow(subscriber).to receive(:current_transaction) - .at_least(:once) - .and_return(transaction) - - expect(transaction).to receive(:increment) - .with(:db_count, 1) - - expect(transaction).not_to receive(:increment) - .with(:db_cached_count, 1) - - expect(transaction).not_to receive(:increment) - .with(:db_write_count, 1) - - subscriber.sql(event) + .at_least(:once) + .and_return(transaction) end - end - - shared_examples 'write query' do - it 'increments db_write_count and db_count value' do - expect(subscriber).to receive(:current_transaction) - .at_least(:once) - .and_return(transaction) - expect(transaction).to receive(:increment) - .with(:db_count, 1) - - expect(transaction).not_to receive(:increment) - .with(:db_cached_count, 1) - - expect(transaction).to receive(:increment) - .with(:db_write_count, 1) + it 'increments only db count value' do + described_class::DB_COUNTERS.each do |counter| + if expected_counters[counter] > 0 + expect(transaction).to receive(:increment).with(counter, 1) + else + expect(transaction).not_to receive(:increment).with(counter, 1) + end + end subscriber.sql(event) end - end - shared_examples 'cached query' do - it 'increments db_cached_count and db_count value' do - expect(subscriber).to receive(:current_transaction) - .at_least(:once) - .and_return(transaction) - - expect(transaction).to receive(:increment) - .with(:db_count, 1) - - expect(transaction).to receive(:increment) - .with(:db_cached_count, 1) - - expect(transaction).not_to receive(:increment) - .with(:db_write_count, 1) - - subscriber.sql(event) + context 'when RequestStore is enabled' do + it 'caches db count value', :request_store, :aggregate_failures do + subscriber.sql(event) + + described_class::DB_COUNTERS.each do |counter| + expect(Gitlab::SafeRequestStore[counter].to_i).to eq expected_counters[counter] + end + end + + it 'prevents db counters from leaking to the next transaction' do + 2.times do + Gitlab::WithRequestStore.with_request_store do + subscriber.sql(event) + + described_class::DB_COUNTERS.each do |counter| + expect(Gitlab::SafeRequestStore[counter].to_i).to eq expected_counters[counter] + end + end + end + end end end @@ -93,66 +78,96 @@ describe Gitlab::Metrics::Subscribers::ActiveRecord do subscriber.sql(event) end - it_behaves_like 'read only query' + context 'with read query' do + let(:expected_counters) do + { + db_count: 1, + db_write_count: 0, + db_cached_count: 0 + } + end + + it_behaves_like 'track executed query' - context 'with select for update sql event' do - let(:payload) { { sql: 'SELECT * FROM users WHERE id = 10 FOR UPDATE' } } + context 'with only select' do + let(:payload) { { sql: 'WITH active_milestones AS (SELECT COUNT(*), state FROM milestones GROUP BY state) SELECT * FROM active_milestones' } } - it_behaves_like 'write query' + it_behaves_like 'track executed query' + end end - context 'with common table expression' do - context 'with insert' do - let(:payload) { { sql: 'WITH archived_rows AS (SELECT * FROM users WHERE archived = true) INSERT INTO products_log SELECT * FROM archived_rows' } } + context 'write query' do + let(:expected_counters) do + { + db_count: 1, + db_write_count: 1, + db_cached_count: 0 + } + end + + context 'with select for update sql event' do + let(:payload) { { sql: 'SELECT * FROM users WHERE id = 10 FOR UPDATE' } } - it_behaves_like 'write query' + it_behaves_like 'track executed query' end - context 'with only select' do - let(:payload) { { sql: 'WITH active_milestones AS (SELECT COUNT(*), state FROM milestones GROUP BY state) SELECT * FROM active_milestones' } } + context 'with common table expression' do + context 'with insert' do + let(:payload) { { sql: 'WITH archived_rows AS (SELECT * FROM users WHERE archived = true) INSERT INTO products_log SELECT * FROM archived_rows' } } - it_behaves_like 'read only query' + it_behaves_like 'track executed query' + end end - end - context 'with delete sql event' do - let(:payload) { { sql: 'DELETE FROM users where id = 10' } } + context 'with delete sql event' do + let(:payload) { { sql: 'DELETE FROM users where id = 10' } } - it_behaves_like 'write query' - end + it_behaves_like 'track executed query' + end - context 'with insert sql event' do - let(:payload) { { sql: 'INSERT INTO project_ci_cd_settings (project_id) SELECT id FROM projects' } } + context 'with insert sql event' do + let(:payload) { { sql: 'INSERT INTO project_ci_cd_settings (project_id) SELECT id FROM projects' } } - it_behaves_like 'write query' - end + it_behaves_like 'track executed query' + end - context 'with update sql event' do - let(:payload) { { sql: 'UPDATE users SET admin = true WHERE id = 10' } } + context 'with update sql event' do + let(:payload) { { sql: 'UPDATE users SET admin = true WHERE id = 10' } } - it_behaves_like 'write query' + it_behaves_like 'track executed query' + end end - context 'with cached payload ' do - let(:payload) do + context 'with cached query' do + let(:expected_counters) do { - sql: 'SELECT * FROM users WHERE id = 10', - cached: true + db_count: 1, + db_write_count: 0, + db_cached_count: 1 } end - it_behaves_like 'cached query' - end + context 'with cached payload ' do + let(:payload) do + { + sql: 'SELECT * FROM users WHERE id = 10', + cached: true + } + end - context 'with cached payload name' do - let(:payload) do - { - sql: 'SELECT * FROM users WHERE id = 10', - name: 'CACHE' - } + it_behaves_like 'track executed query' end - it_behaves_like 'cached query' + context 'with cached payload name' do + let(:payload) do + { + sql: 'SELECT * FROM users WHERE id = 10', + name: 'CACHE' + } + end + + it_behaves_like 'track executed query' + end end context 'events are internal to Rails or irrelevant' do @@ -215,4 +230,54 @@ describe Gitlab::Metrics::Subscribers::ActiveRecord do end end end + + describe 'self.db_counter_payload' do + before do + allow(subscriber).to receive(:current_transaction) + .at_least(:once) + .and_return(transaction) + end + + context 'when RequestStore is enabled', :request_store do + context 'when query is executed' do + let(:expected_payload) do + { + db_count: 1, + db_cached_count: 0, + db_write_count: 0 + } + end + + it 'returns correct payload' do + subscriber.sql(event) + + expect(described_class.db_counter_payload).to eq(expected_payload) + end + end + + context 'when query is not executed' do + let(:expected_payload) do + { + db_count: 0, + db_cached_count: 0, + db_write_count: 0 + } + end + + it 'returns correct payload' do + expect(described_class.db_counter_payload).to eq(expected_payload) + end + end + end + + context 'when RequestStore is disabled' do + let(:expected_payload) { {} } + + it 'returns empty payload' do + subscriber.sql(event) + + expect(described_class.db_counter_payload).to eq(expected_payload) + end + end + end end diff --git a/spec/lib/gitlab/metrics/subscribers/rails_cache_spec.rb b/spec/lib/gitlab/metrics/subscribers/rails_cache_spec.rb index ab0d89b2683..f7ac719c16a 100644 --- a/spec/lib/gitlab/metrics/subscribers/rails_cache_spec.rb +++ b/spec/lib/gitlab/metrics/subscribers/rails_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Subscribers::RailsCache do +RSpec.describe Gitlab::Metrics::Subscribers::RailsCache do let(:env) { {} } let(:transaction) { Gitlab::Metrics::WebTransaction.new(env) } let(:subscriber) { described_class.new } diff --git a/spec/lib/gitlab/metrics/system_spec.rb b/spec/lib/gitlab/metrics/system_spec.rb index abb6a0096d6..720bd5d79b3 100644 --- a/spec/lib/gitlab/metrics/system_spec.rb +++ b/spec/lib/gitlab/metrics/system_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::System do +RSpec.describe Gitlab::Metrics::System do context 'when /proc files exist' do # Fixtures pulled from: # Linux carbon 5.3.0-7648-generic #41~1586789791~19.10~9593806-Ubuntu SMP Mon Apr 13 17:50:40 UTC x86_64 x86_64 x86_64 GNU/Linux diff --git a/spec/lib/gitlab/metrics/transaction_spec.rb b/spec/lib/gitlab/metrics/transaction_spec.rb index 693ec3cb7e7..e64179bd5c1 100644 --- a/spec/lib/gitlab/metrics/transaction_spec.rb +++ b/spec/lib/gitlab/metrics/transaction_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::Transaction do +RSpec.describe Gitlab::Metrics::Transaction do let(:transaction) { described_class.new } let(:sensitive_tags) do @@ -114,15 +114,4 @@ describe Gitlab::Metrics::Transaction do transaction.set(:meow, 1) end end - - describe '#get' do - let(:prometheus_metric) { instance_double(Prometheus::Client::Counter, get: nil) } - - it 'gets a metric' do - expect(described_class).to receive(:fetch_metric).with(:counter, :gitlab_transaction_meow_total).and_return(prometheus_metric) - expect(prometheus_metric).to receive(:get) - - transaction.get(:meow, :counter) - end - end end diff --git a/spec/lib/gitlab/metrics/web_transaction_spec.rb b/spec/lib/gitlab/metrics/web_transaction_spec.rb index 47f1bd3bd10..12e98089066 100644 --- a/spec/lib/gitlab/metrics/web_transaction_spec.rb +++ b/spec/lib/gitlab/metrics/web_transaction_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics::WebTransaction do +RSpec.describe Gitlab::Metrics::WebTransaction do let(:env) { {} } let(:transaction) { described_class.new(env) } let(:prometheus_metric) { double("prometheus metric") } @@ -70,6 +70,9 @@ describe Gitlab::Metrics::WebTransaction do end describe '#labels' do + let(:request) { double(:request, format: double(:format, ref: :html)) } + let(:controller_class) { double(:controller_class, name: 'TestController') } + context 'when request goes to Grape endpoint' do before do route = double(:route, request_method: 'GET', path: '/:version/projects/:id/archive(.:format)') @@ -77,8 +80,13 @@ describe Gitlab::Metrics::WebTransaction do env['api.endpoint'] = endpoint end + it 'provides labels with the method and path of the route in the grape endpoint' do - expect(transaction.labels).to eq({ controller: 'Grape', action: 'GET /projects/:id/archive' }) + expect(transaction.labels).to eq({ controller: 'Grape', action: 'GET /projects/:id/archive', feature_category: '' }) + end + + it 'contains only the labels defined for transactions' do + expect(transaction.labels.keys).to contain_exactly(*described_class.superclass::BASE_LABELS.keys) end it 'does not provide labels if route infos are missing' do @@ -92,24 +100,25 @@ describe Gitlab::Metrics::WebTransaction do end context 'when request goes to ActionController' do - let(:request) { double(:request, format: double(:format, ref: :html)) } - before do - klass = double(:klass, name: 'TestController') - controller = double(:controller, class: klass, action_name: 'show', request: request) + controller = double(:controller, class: controller_class, action_name: 'show', request: request) env['action_controller.instance'] = controller end it 'tags a transaction with the name and action of a controller' do - expect(transaction.labels).to eq({ controller: 'TestController', action: 'show' }) + expect(transaction.labels).to eq({ controller: 'TestController', action: 'show', feature_category: '' }) + end + + it 'contains only the labels defined for transactions' do + expect(transaction.labels.keys).to contain_exactly(*described_class.superclass::BASE_LABELS.keys) end context 'when the request content type is not :html' do let(:request) { double(:request, format: double(:format, ref: :json)) } it 'appends the mime type to the transaction action' do - expect(transaction.labels).to eq({ controller: 'TestController', action: 'show.json' }) + expect(transaction.labels).to eq({ controller: 'TestController', action: 'show.json', feature_category: '' }) end end @@ -117,7 +126,14 @@ describe Gitlab::Metrics::WebTransaction do let(:request) { double(:request, format: double(:format, ref: 'http://example.com')) } it 'does not append the MIME type to the transaction action' do - expect(transaction.labels).to eq({ controller: 'TestController', action: 'show' }) + expect(transaction.labels).to eq({ controller: 'TestController', action: 'show', feature_category: '' }) + end + end + + context 'when the feature category is known' do + it 'includes it in the feature category label' do + expect(controller_class).to receive(:feature_category_for_action).with('show').and_return(:source_code_management) + expect(transaction.labels).to eq({ controller: 'TestController', action: 'show', feature_category: "source_code_management" }) end end end diff --git a/spec/lib/gitlab/metrics_spec.rb b/spec/lib/gitlab/metrics_spec.rb index 2ebe1958487..bdf72a3c288 100644 --- a/spec/lib/gitlab/metrics_spec.rb +++ b/spec/lib/gitlab/metrics_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Metrics do +RSpec.describe Gitlab::Metrics do include StubENV describe '.settings' do diff --git a/spec/lib/gitlab/middleware/basic_health_check_spec.rb b/spec/lib/gitlab/middleware/basic_health_check_spec.rb index 07fda691ac8..0ca96de38da 100644 --- a/spec/lib/gitlab/middleware/basic_health_check_spec.rb +++ b/spec/lib/gitlab/middleware/basic_health_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Middleware::BasicHealthCheck do +RSpec.describe Gitlab::Middleware::BasicHealthCheck do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } let(:env) { {} } diff --git a/spec/lib/gitlab/middleware/go_spec.rb b/spec/lib/gitlab/middleware/go_spec.rb index 43a489f6df0..1fffef53a82 100644 --- a/spec/lib/gitlab/middleware/go_spec.rb +++ b/spec/lib/gitlab/middleware/go_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Middleware::Go do +RSpec.describe Gitlab::Middleware::Go do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } let(:env) do diff --git a/spec/lib/gitlab/middleware/handle_ip_spoof_attack_error_spec.rb b/spec/lib/gitlab/middleware/handle_ip_spoof_attack_error_spec.rb index ccfc5e93887..553ee589c62 100644 --- a/spec/lib/gitlab/middleware/handle_ip_spoof_attack_error_spec.rb +++ b/spec/lib/gitlab/middleware/handle_ip_spoof_attack_error_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Middleware::HandleIpSpoofAttackError do +RSpec.describe Gitlab::Middleware::HandleIpSpoofAttackError do let(:spoof_error) { ActionDispatch::RemoteIp::IpSpoofAttackError.new('sensitive') } let(:standard_error) { StandardError.new('error') } let(:app) { -> (env) { env.is_a?(Exception) ? raise(env) : env } } diff --git a/spec/lib/gitlab/middleware/multipart_spec.rb b/spec/lib/gitlab/middleware/multipart_spec.rb index 705164d5445..3b64fe335e8 100644 --- a/spec/lib/gitlab/middleware/multipart_spec.rb +++ b/spec/lib/gitlab/middleware/multipart_spec.rb @@ -4,7 +4,7 @@ require 'spec_helper' require 'tempfile' -describe Gitlab::Middleware::Multipart do +RSpec.describe Gitlab::Middleware::Multipart do include_context 'multipart middleware context' RSpec.shared_examples_for 'multipart upload files' do @@ -232,4 +232,82 @@ describe Gitlab::Middleware::Multipart do middleware.call(env) end end + + describe '#call' do + context 'with packages storage' do + using RSpec::Parameterized::TableSyntax + + let(:storage_path) { 'shared/packages' } + + RSpec.shared_examples 'allowing the multipart upload' do + it 'allows files to be uploaded' do + with_tmp_dir('tmp/uploads', storage_path) do |dir, env| + allow(Packages::PackageFileUploader).to receive(:root).and_return(File.join(dir, storage_path)) + + expect(app).to receive(:call) do |env| + expect(get_params(env)['file']).to be_a(::UploadedFile) + end + + middleware.call(env) + end + end + end + + RSpec.shared_examples 'not allowing the multipart upload when package upload path is used' do + it 'does not allow files to be uploaded' do + with_tmp_dir('tmp/uploads', storage_path) do |dir, env| + # with_tmp_dir sets the same workhorse_upload_path for all Uploaders, + # so we have to prevent JobArtifactUploader and LfsObjectUploader to + # allow the tested path + allow(JobArtifactUploader).to receive(:workhorse_upload_path).and_return(Dir.tmpdir) + allow(LfsObjectUploader).to receive(:workhorse_upload_path).and_return(Dir.tmpdir) + + status, headers, body = middleware.call(env) + + expect(status).to eq(400) + expect(headers).to eq({ 'Content-Type' => 'text/plain' }) + expect(body).to start_with('insecure path used') + end + end + end + + RSpec.shared_examples 'adding package storage to multipart allowed paths' do + before do + expect(::Packages::PackageFileUploader).to receive(:workhorse_upload_path).and_call_original + end + + it_behaves_like 'allowing the multipart upload' + end + + RSpec.shared_examples 'not adding package storage to multipart allowed paths' do + before do + expect(::Packages::PackageFileUploader).not_to receive(:workhorse_upload_path) + end + + it_behaves_like 'not allowing the multipart upload when package upload path is used' + end + + where(:object_storage_enabled, :direct_upload_enabled, :example_name) do + false | true | 'adding package storage to multipart allowed paths' + false | false | 'adding package storage to multipart allowed paths' + true | true | 'not adding package storage to multipart allowed paths' + true | false | 'adding package storage to multipart allowed paths' + end + + with_them do + before do + stub_config(packages: { + enabled: true, + object_store: { + enabled: object_storage_enabled, + direct_upload: direct_upload_enabled + }, + storage_path: storage_path + }) + end + + it_behaves_like params[:example_name] + end + end + end end diff --git a/spec/lib/gitlab/middleware/rails_queue_duration_spec.rb b/spec/lib/gitlab/middleware/rails_queue_duration_spec.rb index 4f21bd14122..8f9b0aec9eb 100644 --- a/spec/lib/gitlab/middleware/rails_queue_duration_spec.rb +++ b/spec/lib/gitlab/middleware/rails_queue_duration_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Middleware::RailsQueueDuration do +RSpec.describe Gitlab::Middleware::RailsQueueDuration do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } let(:env) { {} } diff --git a/spec/lib/gitlab/middleware/read_only_spec.rb b/spec/lib/gitlab/middleware/read_only_spec.rb index c7e9b38e3ca..3bdf2a5077f 100644 --- a/spec/lib/gitlab/middleware/read_only_spec.rb +++ b/spec/lib/gitlab/middleware/read_only_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Middleware::ReadOnly do +RSpec.describe Gitlab::Middleware::ReadOnly do include Rack::Test::Methods using RSpec::Parameterized::TableSyntax diff --git a/spec/lib/gitlab/middleware/release_env_spec.rb b/spec/lib/gitlab/middleware/release_env_spec.rb index 3ca40f4ebd0..ca0ec0b9d83 100644 --- a/spec/lib/gitlab/middleware/release_env_spec.rb +++ b/spec/lib/gitlab/middleware/release_env_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Middleware::ReleaseEnv do +RSpec.describe Gitlab::Middleware::ReleaseEnv do let(:inner_app) { double(:app, call: 'yay') } let(:app) { described_class.new(inner_app) } let(:env) { { 'action_controller.instance' => 'something' } } diff --git a/spec/lib/gitlab/middleware/request_context_spec.rb b/spec/lib/gitlab/middleware/request_context_spec.rb index 1ed06a97c1e..431f4453e37 100644 --- a/spec/lib/gitlab/middleware/request_context_spec.rb +++ b/spec/lib/gitlab/middleware/request_context_spec.rb @@ -4,7 +4,7 @@ require 'rack' require 'request_store' require_relative '../../../support/helpers/next_instance_of' -describe Gitlab::Middleware::RequestContext do +RSpec.describe Gitlab::Middleware::RequestContext do include NextInstanceOf let(:app) { -> (env) {} } diff --git a/spec/lib/gitlab/middleware/same_site_cookies_spec.rb b/spec/lib/gitlab/middleware/same_site_cookies_spec.rb index 0cf1028a930..7c5262ca318 100644 --- a/spec/lib/gitlab/middleware/same_site_cookies_spec.rb +++ b/spec/lib/gitlab/middleware/same_site_cookies_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Middleware::SameSiteCookies do +RSpec.describe Gitlab::Middleware::SameSiteCookies do include Rack::Test::Methods let(:mock_app) do diff --git a/spec/lib/gitlab/monitor/demo_projects_spec.rb b/spec/lib/gitlab/monitor/demo_projects_spec.rb index 92024a3f9c1..262c78eb62e 100644 --- a/spec/lib/gitlab/monitor/demo_projects_spec.rb +++ b/spec/lib/gitlab/monitor/demo_projects_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Monitor::DemoProjects do +RSpec.describe Gitlab::Monitor::DemoProjects do describe '#primary_keys' do subject { described_class.primary_keys } diff --git a/spec/lib/gitlab/multi_collection_paginator_spec.rb b/spec/lib/gitlab/multi_collection_paginator_spec.rb index f2049884b83..c7c8f4f969f 100644 --- a/spec/lib/gitlab/multi_collection_paginator_spec.rb +++ b/spec/lib/gitlab/multi_collection_paginator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::MultiCollectionPaginator do +RSpec.describe Gitlab::MultiCollectionPaginator do subject(:paginator) { described_class.new(Project.all.order(:id), Group.all.order(:id), per_page: 3) } it 'combines both collections' do diff --git a/spec/lib/gitlab/multi_destination_logger_spec.rb b/spec/lib/gitlab/multi_destination_logger_spec.rb index 7acd7906a26..e0d76afd9bf 100644 --- a/spec/lib/gitlab/multi_destination_logger_spec.rb +++ b/spec/lib/gitlab/multi_destination_logger_spec.rb @@ -31,7 +31,7 @@ class EmptyLogger < Gitlab::MultiDestinationLogger end end -describe Gitlab::MultiDestinationLogger do +RSpec.describe Gitlab::MultiDestinationLogger do after(:all) do TestLogger.loggers.each do |logger| log_file_path = "#{Rails.root}/log/#{logger.file_name}" diff --git a/spec/lib/gitlab/namespaced_session_store_spec.rb b/spec/lib/gitlab/namespaced_session_store_spec.rb index e177c44ad67..a569c86960c 100644 --- a/spec/lib/gitlab/namespaced_session_store_spec.rb +++ b/spec/lib/gitlab/namespaced_session_store_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::NamespacedSessionStore do +RSpec.describe Gitlab::NamespacedSessionStore do let(:key) { :some_key } context 'current session' do diff --git a/spec/lib/gitlab/no_cache_headers_spec.rb b/spec/lib/gitlab/no_cache_headers_spec.rb index c7a73f0e2dc..513a39978e6 100644 --- a/spec/lib/gitlab/no_cache_headers_spec.rb +++ b/spec/lib/gitlab/no_cache_headers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::NoCacheHeaders do +RSpec.describe Gitlab::NoCacheHeaders do before do stub_const('NoCacheTester', Class.new) NoCacheTester.class_eval do diff --git a/spec/lib/gitlab/noteable_metadata_spec.rb b/spec/lib/gitlab/noteable_metadata_spec.rb index b12a1825f04..98c07fc9f62 100644 --- a/spec/lib/gitlab/noteable_metadata_spec.rb +++ b/spec/lib/gitlab/noteable_metadata_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::NoteableMetadata do +RSpec.describe Gitlab::NoteableMetadata do subject { Class.new { include Gitlab::NoteableMetadata }.new } it 'returns an empty Hash if an empty collection is provided' do diff --git a/spec/lib/gitlab/null_request_store_spec.rb b/spec/lib/gitlab/null_request_store_spec.rb index c023dac53ad..f600af2e31f 100644 --- a/spec/lib/gitlab/null_request_store_spec.rb +++ b/spec/lib/gitlab/null_request_store_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::NullRequestStore do +RSpec.describe Gitlab::NullRequestStore do let(:null_store) { described_class.new } describe '#store' do diff --git a/spec/lib/gitlab/object_hierarchy_spec.rb b/spec/lib/gitlab/object_hierarchy_spec.rb index b72aeb6d601..ef2d4fa0cbf 100644 --- a/spec/lib/gitlab/object_hierarchy_spec.rb +++ b/spec/lib/gitlab/object_hierarchy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ObjectHierarchy do +RSpec.describe Gitlab::ObjectHierarchy do let!(:parent) { create(:group) } let!(:child1) { create(:group, parent: parent) } let!(:child2) { create(:group, parent: child1) } diff --git a/spec/lib/gitlab/octokit/middleware_spec.rb b/spec/lib/gitlab/octokit/middleware_spec.rb index 8aa6d17ac9e..bc4d95738c7 100644 --- a/spec/lib/gitlab/octokit/middleware_spec.rb +++ b/spec/lib/gitlab/octokit/middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Octokit::Middleware do +RSpec.describe Gitlab::Octokit::Middleware do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } diff --git a/spec/lib/gitlab/omniauth_initializer_spec.rb b/spec/lib/gitlab/omniauth_initializer_spec.rb index 4afe4545891..a38dffcfce0 100644 --- a/spec/lib/gitlab/omniauth_initializer_spec.rb +++ b/spec/lib/gitlab/omniauth_initializer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::OmniauthInitializer do +RSpec.describe Gitlab::OmniauthInitializer do let(:devise_config) { class_double(Devise) } subject { described_class.new(devise_config) } diff --git a/spec/lib/gitlab/omniauth_logging/json_formatter_spec.rb b/spec/lib/gitlab/omniauth_logging/json_formatter_spec.rb index 36405daed5a..f65b247d5d7 100644 --- a/spec/lib/gitlab/omniauth_logging/json_formatter_spec.rb +++ b/spec/lib/gitlab/omniauth_logging/json_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::OmniauthLogging::JSONFormatter do +RSpec.describe Gitlab::OmniauthLogging::JSONFormatter do it "generates log in json format" do Timecop.freeze(Time.utc(2019, 12, 04, 9, 10, 11, 123456)) do expect(subject.call(:info, Time.now, 'omniauth', 'log message')) diff --git a/spec/lib/gitlab/optimistic_locking_spec.rb b/spec/lib/gitlab/optimistic_locking_spec.rb index 9dfcb775dfa..0862a9c880e 100644 --- a/spec/lib/gitlab/optimistic_locking_spec.rb +++ b/spec/lib/gitlab/optimistic_locking_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::OptimisticLocking do +RSpec.describe Gitlab::OptimisticLocking do let!(:pipeline) { create(:ci_pipeline) } let!(:pipeline2) { Ci::Pipeline.find(pipeline.id) } diff --git a/spec/lib/gitlab/other_markup_spec.rb b/spec/lib/gitlab/other_markup_spec.rb index b5cf5b0999d..26e60251abb 100644 --- a/spec/lib/gitlab/other_markup_spec.rb +++ b/spec/lib/gitlab/other_markup_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::OtherMarkup do +RSpec.describe Gitlab::OtherMarkup do let(:context) { {} } context "XSS Checks" do diff --git a/spec/lib/gitlab/otp_key_rotator_spec.rb b/spec/lib/gitlab/otp_key_rotator_spec.rb index f5a567d5ea0..e328b190db4 100644 --- a/spec/lib/gitlab/otp_key_rotator_spec.rb +++ b/spec/lib/gitlab/otp_key_rotator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::OtpKeyRotator do +RSpec.describe Gitlab::OtpKeyRotator do let(:file) { Tempfile.new("otp-key-rotator-test") } let(:filename) { file.path } let(:old_key) { Gitlab::Application.secrets.otp_key_base } diff --git a/spec/lib/gitlab/pages_spec.rb b/spec/lib/gitlab/pages_spec.rb index 5889689cb81..9f85efd56e6 100644 --- a/spec/lib/gitlab/pages_spec.rb +++ b/spec/lib/gitlab/pages_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Pages do +RSpec.describe Gitlab::Pages do using RSpec::Parameterized::TableSyntax let(:pages_secret) { SecureRandom.random_bytes(Gitlab::Pages::SECRET_LENGTH) } diff --git a/spec/lib/gitlab/pagination/keyset/page_spec.rb b/spec/lib/gitlab/pagination/keyset/page_spec.rb index c5ca27231d8..3f4ef192b5a 100644 --- a/spec/lib/gitlab/pagination/keyset/page_spec.rb +++ b/spec/lib/gitlab/pagination/keyset/page_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Pagination::Keyset::Page do +RSpec.describe Gitlab::Pagination::Keyset::Page do describe '#per_page' do it 'limits to a maximum of 100 records per page' do per_page = described_class.new(per_page: 101).per_page diff --git a/spec/lib/gitlab/pagination/keyset/pager_spec.rb b/spec/lib/gitlab/pagination/keyset/pager_spec.rb index 3ad1bee7225..a3169142279 100644 --- a/spec/lib/gitlab/pagination/keyset/pager_spec.rb +++ b/spec/lib/gitlab/pagination/keyset/pager_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Pagination::Keyset::Pager do +RSpec.describe Gitlab::Pagination::Keyset::Pager do let(:relation) { Project.all.order(id: :asc) } let(:request) { double('request', page: page, apply_headers: nil) } let(:page) { Gitlab::Pagination::Keyset::Page.new(order_by: { id: :asc }, per_page: 3) } diff --git a/spec/lib/gitlab/pagination/keyset/request_context_spec.rb b/spec/lib/gitlab/pagination/keyset/request_context_spec.rb index d6d5340f38b..d4255176a4e 100644 --- a/spec/lib/gitlab/pagination/keyset/request_context_spec.rb +++ b/spec/lib/gitlab/pagination/keyset/request_context_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Pagination::Keyset::RequestContext do +RSpec.describe Gitlab::Pagination::Keyset::RequestContext do let(:request) { double('request', params: params) } describe '#page' do diff --git a/spec/lib/gitlab/pagination/keyset_spec.rb b/spec/lib/gitlab/pagination/keyset_spec.rb index 0ac40080872..81dc40b35d5 100644 --- a/spec/lib/gitlab/pagination/keyset_spec.rb +++ b/spec/lib/gitlab/pagination/keyset_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Pagination::Keyset do +RSpec.describe Gitlab::Pagination::Keyset do describe '.available_for_type?' do subject { described_class } diff --git a/spec/lib/gitlab/pagination/offset_pagination_spec.rb b/spec/lib/gitlab/pagination/offset_pagination_spec.rb index 9c7dd385726..be20f0194f7 100644 --- a/spec/lib/gitlab/pagination/offset_pagination_spec.rb +++ b/spec/lib/gitlab/pagination/offset_pagination_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Pagination::OffsetPagination do +RSpec.describe Gitlab::Pagination::OffsetPagination do let(:resource) { Project.all } let(:custom_port) { 8080 } let(:incoming_api_projects_url) { "#{Gitlab.config.gitlab.url}:#{custom_port}/api/v4/projects" } diff --git a/spec/lib/gitlab/patch/action_dispatch_journey_formatter_spec.rb b/spec/lib/gitlab/patch/action_dispatch_journey_formatter_spec.rb index b1c7f73489d..ca74f7573f3 100644 --- a/spec/lib/gitlab/patch/action_dispatch_journey_formatter_spec.rb +++ b/spec/lib/gitlab/patch/action_dispatch_journey_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Patch::ActionDispatchJourneyFormatter do +RSpec.describe Gitlab::Patch::ActionDispatchJourneyFormatter do let(:group) { create(:group) } let(:project) { create(:project, namespace: group) } let(:pipeline) { create(:ci_empty_pipeline, project: project) } diff --git a/spec/lib/gitlab/patch/draw_route_spec.rb b/spec/lib/gitlab/patch/draw_route_spec.rb index 4009b903dc3..4d1c7bf9fcf 100644 --- a/spec/lib/gitlab/patch/draw_route_spec.rb +++ b/spec/lib/gitlab/patch/draw_route_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Patch::DrawRoute do +RSpec.describe Gitlab::Patch::DrawRoute do subject do Class.new do include Gitlab::Patch::DrawRoute diff --git a/spec/lib/gitlab/patch/prependable_spec.rb b/spec/lib/gitlab/patch/prependable_spec.rb index 255324f89d5..8feab57a8f3 100644 --- a/spec/lib/gitlab/patch/prependable_spec.rb +++ b/spec/lib/gitlab/patch/prependable_spec.rb @@ -5,7 +5,7 @@ require 'fast_spec_helper' # Patching ActiveSupport::Concern require_relative '../../../../config/initializers/0_as_concern' -describe Gitlab::Patch::Prependable do +RSpec.describe Gitlab::Patch::Prependable do before do @prepended_modules = [] end diff --git a/spec/lib/gitlab/path_regex_spec.rb b/spec/lib/gitlab/path_regex_spec.rb index ac506c49100..7cecc29afa4 100644 --- a/spec/lib/gitlab/path_regex_spec.rb +++ b/spec/lib/gitlab/path_regex_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PathRegex do +RSpec.describe Gitlab::PathRegex do let(:starting_with_namespace) { %r{^/\*namespace_id/:(project_)?id} } let(:non_param_parts) { %r{[^:*][a-z\-_/]*} } let(:any_other_path_part) { %r{[a-z\-_/:]*} } diff --git a/spec/lib/gitlab/performance_bar/with_top_level_warnings_spec.rb b/spec/lib/gitlab/performance_bar/with_top_level_warnings_spec.rb index 3b92261f0fe..735f04b3bce 100644 --- a/spec/lib/gitlab/performance_bar/with_top_level_warnings_spec.rb +++ b/spec/lib/gitlab/performance_bar/with_top_level_warnings_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::PerformanceBar::WithTopLevelWarnings do +RSpec.describe Gitlab::PerformanceBar::WithTopLevelWarnings do using RSpec::Parameterized::TableSyntax subject { Module.new } diff --git a/spec/lib/gitlab/performance_bar_spec.rb b/spec/lib/gitlab/performance_bar_spec.rb index 7b79cc82816..12916c41f0f 100644 --- a/spec/lib/gitlab/performance_bar_spec.rb +++ b/spec/lib/gitlab/performance_bar_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PerformanceBar do +RSpec.describe Gitlab::PerformanceBar do it { expect(described_class.l1_cache_backend).to eq(Gitlab::ProcessMemoryCache.cache_backend) } it { expect(described_class.l2_cache_backend).to eq(Rails.cache) } diff --git a/spec/lib/gitlab/phabricator_import/cache/map_spec.rb b/spec/lib/gitlab/phabricator_import/cache/map_spec.rb index 4935ef1bd90..0f760852a68 100644 --- a/spec/lib/gitlab/phabricator_import/cache/map_spec.rb +++ b/spec/lib/gitlab/phabricator_import/cache/map_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PhabricatorImport::Cache::Map, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::PhabricatorImport::Cache::Map, :clean_gitlab_redis_cache do let_it_be(:project) { create(:project) } let(:redis) { Gitlab::Redis::Cache } diff --git a/spec/lib/gitlab/phabricator_import/conduit/client_spec.rb b/spec/lib/gitlab/phabricator_import/conduit/client_spec.rb index 542b3cd060f..dad349f3255 100644 --- a/spec/lib/gitlab/phabricator_import/conduit/client_spec.rb +++ b/spec/lib/gitlab/phabricator_import/conduit/client_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Conduit::Client do +RSpec.describe Gitlab::PhabricatorImport::Conduit::Client do let(:client) do described_class.new('https://see-ya-later.phabricator', 'api-token') end diff --git a/spec/lib/gitlab/phabricator_import/conduit/maniphest_spec.rb b/spec/lib/gitlab/phabricator_import/conduit/maniphest_spec.rb index 0d7714649b9..e655a39a28d 100644 --- a/spec/lib/gitlab/phabricator_import/conduit/maniphest_spec.rb +++ b/spec/lib/gitlab/phabricator_import/conduit/maniphest_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Conduit::Maniphest do +RSpec.describe Gitlab::PhabricatorImport::Conduit::Maniphest do let(:maniphest) do described_class.new(phabricator_url: 'https://see-ya-later.phabricator', api_token: 'api-token') end diff --git a/spec/lib/gitlab/phabricator_import/conduit/response_spec.rb b/spec/lib/gitlab/phabricator_import/conduit/response_spec.rb index 1ffb811cbc1..c368b349a3c 100644 --- a/spec/lib/gitlab/phabricator_import/conduit/response_spec.rb +++ b/spec/lib/gitlab/phabricator_import/conduit/response_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Conduit::Response do +RSpec.describe Gitlab::PhabricatorImport::Conduit::Response do let(:response) { described_class.new(Gitlab::Json.parse(fixture_file('phabricator_responses/maniphest.search.json')))} let(:error_response) { described_class.new(Gitlab::Json.parse(fixture_file('phabricator_responses/auth_failed.json'))) } @@ -30,7 +30,7 @@ describe Gitlab::PhabricatorImport::Conduit::Response do body: 'This is no JSON') expect { described_class.parse!(fake_response) } - .to raise_error(Gitlab::PhabricatorImport::Conduit::ResponseError, /unexpected token at/) + .to raise_error(Gitlab::PhabricatorImport::Conduit::ResponseError, /unexpected character/) end it 'returns a parsed response for valid input' do diff --git a/spec/lib/gitlab/phabricator_import/conduit/tasks_response_spec.rb b/spec/lib/gitlab/phabricator_import/conduit/tasks_response_spec.rb index 2cc12ee0165..4e56dead5c0 100644 --- a/spec/lib/gitlab/phabricator_import/conduit/tasks_response_spec.rb +++ b/spec/lib/gitlab/phabricator_import/conduit/tasks_response_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Conduit::TasksResponse do +RSpec.describe Gitlab::PhabricatorImport::Conduit::TasksResponse do let(:conduit_response) do Gitlab::PhabricatorImport::Conduit::Response .new(Gitlab::Json.parse(fixture_file('phabricator_responses/maniphest.search.json'))) diff --git a/spec/lib/gitlab/phabricator_import/conduit/user_spec.rb b/spec/lib/gitlab/phabricator_import/conduit/user_spec.rb index f3928f390bc..d38421c9405 100644 --- a/spec/lib/gitlab/phabricator_import/conduit/user_spec.rb +++ b/spec/lib/gitlab/phabricator_import/conduit/user_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Conduit::User do +RSpec.describe Gitlab::PhabricatorImport::Conduit::User do let(:user_client) do described_class.new(phabricator_url: 'https://see-ya-later.phabricator', api_token: 'api-token') end diff --git a/spec/lib/gitlab/phabricator_import/conduit/users_response_spec.rb b/spec/lib/gitlab/phabricator_import/conduit/users_response_spec.rb index 999a986b73c..ebbb2c0598c 100644 --- a/spec/lib/gitlab/phabricator_import/conduit/users_response_spec.rb +++ b/spec/lib/gitlab/phabricator_import/conduit/users_response_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Conduit::UsersResponse do +RSpec.describe Gitlab::PhabricatorImport::Conduit::UsersResponse do let(:conduit_response) do Gitlab::PhabricatorImport::Conduit::Response .new(Gitlab::Json.parse(fixture_file('phabricator_responses/user.search.json'))) diff --git a/spec/lib/gitlab/phabricator_import/importer_spec.rb b/spec/lib/gitlab/phabricator_import/importer_spec.rb index 2715b785379..e78024c35c1 100644 --- a/spec/lib/gitlab/phabricator_import/importer_spec.rb +++ b/spec/lib/gitlab/phabricator_import/importer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PhabricatorImport::Importer do +RSpec.describe Gitlab::PhabricatorImport::Importer do it { expect(described_class).to be_async } it "acts like it's importing repositories" do diff --git a/spec/lib/gitlab/phabricator_import/issues/importer_spec.rb b/spec/lib/gitlab/phabricator_import/issues/importer_spec.rb index 02dafd4bb3b..63ba575aea3 100644 --- a/spec/lib/gitlab/phabricator_import/issues/importer_spec.rb +++ b/spec/lib/gitlab/phabricator_import/issues/importer_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Issues::Importer do +RSpec.describe Gitlab::PhabricatorImport::Issues::Importer do let(:project) { create(:project) } let(:response) do diff --git a/spec/lib/gitlab/phabricator_import/issues/task_importer_spec.rb b/spec/lib/gitlab/phabricator_import/issues/task_importer_spec.rb index 79f11d7fae6..3cb15f08627 100644 --- a/spec/lib/gitlab/phabricator_import/issues/task_importer_spec.rb +++ b/spec/lib/gitlab/phabricator_import/issues/task_importer_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::Issues::TaskImporter do +RSpec.describe Gitlab::PhabricatorImport::Issues::TaskImporter do let_it_be(:project) { create(:project) } let(:task) do Gitlab::PhabricatorImport::Representation::Task.new( diff --git a/spec/lib/gitlab/phabricator_import/project_creator_spec.rb b/spec/lib/gitlab/phabricator_import/project_creator_spec.rb index 0b6a71290ed..016aa0abe4d 100644 --- a/spec/lib/gitlab/phabricator_import/project_creator_spec.rb +++ b/spec/lib/gitlab/phabricator_import/project_creator_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::PhabricatorImport::ProjectCreator do +RSpec.describe Gitlab::PhabricatorImport::ProjectCreator do let(:user) { create(:user) } let(:params) do { path: 'new-phab-import', diff --git a/spec/lib/gitlab/phabricator_import/representation/task_spec.rb b/spec/lib/gitlab/phabricator_import/representation/task_spec.rb index 5603a6961d6..25a52af3a7a 100644 --- a/spec/lib/gitlab/phabricator_import/representation/task_spec.rb +++ b/spec/lib/gitlab/phabricator_import/representation/task_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PhabricatorImport::Representation::Task do +RSpec.describe Gitlab::PhabricatorImport::Representation::Task do subject(:task) do described_class.new( { diff --git a/spec/lib/gitlab/phabricator_import/representation/user_spec.rb b/spec/lib/gitlab/phabricator_import/representation/user_spec.rb index f52467a0cf1..f51be0f7d8d 100644 --- a/spec/lib/gitlab/phabricator_import/representation/user_spec.rb +++ b/spec/lib/gitlab/phabricator_import/representation/user_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PhabricatorImport::Representation::User do +RSpec.describe Gitlab::PhabricatorImport::Representation::User do subject(:user) do described_class.new( { diff --git a/spec/lib/gitlab/phabricator_import/user_finder_spec.rb b/spec/lib/gitlab/phabricator_import/user_finder_spec.rb index f260e38b7c8..e63ad6e6626 100644 --- a/spec/lib/gitlab/phabricator_import/user_finder_spec.rb +++ b/spec/lib/gitlab/phabricator_import/user_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PhabricatorImport::UserFinder, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::PhabricatorImport::UserFinder, :clean_gitlab_redis_cache do let(:project) { create(:project, namespace: create(:group)) } subject(:finder) { described_class.new(project, %w[first-phid second-phid]) } diff --git a/spec/lib/gitlab/phabricator_import/worker_state_spec.rb b/spec/lib/gitlab/phabricator_import/worker_state_spec.rb index 51514dd0ffd..4a07e28440f 100644 --- a/spec/lib/gitlab/phabricator_import/worker_state_spec.rb +++ b/spec/lib/gitlab/phabricator_import/worker_state_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PhabricatorImport::WorkerState, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::PhabricatorImport::WorkerState, :clean_gitlab_redis_shared_state do subject(:state) { described_class.new('weird-project-id') } let(:key) { 'phabricator-import/jobs/project-weird-project-id/job-count' } diff --git a/spec/lib/gitlab/polling_interval_spec.rb b/spec/lib/gitlab/polling_interval_spec.rb index 31569b2c51e..bf0eaf80d3b 100644 --- a/spec/lib/gitlab/polling_interval_spec.rb +++ b/spec/lib/gitlab/polling_interval_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PollingInterval do +RSpec.describe Gitlab::PollingInterval do let(:polling_interval) { described_class } describe '.set_header' do diff --git a/spec/lib/gitlab/popen/runner_spec.rb b/spec/lib/gitlab/popen/runner_spec.rb index de19106eaee..5f72852c63e 100644 --- a/spec/lib/gitlab/popen/runner_spec.rb +++ b/spec/lib/gitlab/popen/runner_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Popen::Runner do +RSpec.describe Gitlab::Popen::Runner do subject { described_class.new } describe '#run' do diff --git a/spec/lib/gitlab/popen_spec.rb b/spec/lib/gitlab/popen_spec.rb index b398381a7e0..891482a5f17 100644 --- a/spec/lib/gitlab/popen_spec.rb +++ b/spec/lib/gitlab/popen_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Popen do +RSpec.describe Gitlab::Popen do let(:path) { Rails.root.join('tmp').to_s } before do diff --git a/spec/lib/gitlab/private_commit_email_spec.rb b/spec/lib/gitlab/private_commit_email_spec.rb index 7b7a0f7c0ca..502cc82fd8d 100644 --- a/spec/lib/gitlab/private_commit_email_spec.rb +++ b/spec/lib/gitlab/private_commit_email_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PrivateCommitEmail do +RSpec.describe Gitlab::PrivateCommitEmail do let(:hostname) { Gitlab::CurrentSettings.current_application_settings.commit_email_hostname } let(:id) { 1 } let(:valid_email) { "#{id}-foo@#{hostname}" } diff --git a/spec/lib/gitlab/process_memory_cache/helper_spec.rb b/spec/lib/gitlab/process_memory_cache/helper_spec.rb index 890642b1d5e..27d7fd0bdcf 100644 --- a/spec/lib/gitlab/process_memory_cache/helper_spec.rb +++ b/spec/lib/gitlab/process_memory_cache/helper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ProcessMemoryCache::Helper, :use_clean_rails_memory_store_caching do +RSpec.describe Gitlab::ProcessMemoryCache::Helper, :use_clean_rails_memory_store_caching do let(:minimal_test_class) do Class.new do include Gitlab::ProcessMemoryCache::Helper diff --git a/spec/lib/gitlab/profiler_spec.rb b/spec/lib/gitlab/profiler_spec.rb index 6440f74a49a..89917e515d0 100644 --- a/spec/lib/gitlab/profiler_spec.rb +++ b/spec/lib/gitlab/profiler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Profiler do +RSpec.describe Gitlab::Profiler do let(:null_logger) { Logger.new('/dev/null') } let(:private_token) { 'private' } @@ -229,7 +229,6 @@ describe Gitlab::Profiler do .map { |(total)| total.to_f } expect(total_times).to eq(total_times.sort.reverse) - expect(total_times).not_to eq(total_times.uniq) end end diff --git a/spec/lib/gitlab/project_authorizations_spec.rb b/spec/lib/gitlab/project_authorizations_spec.rb index 261e44bc5fa..5ff07dcec4f 100644 --- a/spec/lib/gitlab/project_authorizations_spec.rb +++ b/spec/lib/gitlab/project_authorizations_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ProjectAuthorizations do +RSpec.describe Gitlab::ProjectAuthorizations do def map_access_levels(rows) rows.each_with_object({}) do |row, hash| hash[row.project_id] = row.access_level diff --git a/spec/lib/gitlab/project_search_results_spec.rb b/spec/lib/gitlab/project_search_results_spec.rb index aa52949ed60..75a3fe06632 100644 --- a/spec/lib/gitlab/project_search_results_spec.rb +++ b/spec/lib/gitlab/project_search_results_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ProjectSearchResults do +RSpec.describe Gitlab::ProjectSearchResults do include SearchHelpers let(:user) { create(:user) } diff --git a/spec/lib/gitlab/project_template_spec.rb b/spec/lib/gitlab/project_template_spec.rb index 35f79042df0..fa45c605b1b 100644 --- a/spec/lib/gitlab/project_template_spec.rb +++ b/spec/lib/gitlab/project_template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ProjectTemplate do +RSpec.describe Gitlab::ProjectTemplate do describe '.all' do it 'returns all templates' do expected = %w[ @@ -10,7 +10,7 @@ describe Gitlab::ProjectTemplate do gomicro gatsby hugo jekyll plainhtml gitbook hexo sse_middleman nfhugo nfjekyll nfplainhtml nfgitbook nfhexo salesforcedx serverless_framework - cluster_management + jsonnet cluster_management ] expect(described_class.all).to be_an(Array) diff --git a/spec/lib/gitlab/project_transfer_spec.rb b/spec/lib/gitlab/project_transfer_spec.rb index d54817ea02b..87c4014264f 100644 --- a/spec/lib/gitlab/project_transfer_spec.rb +++ b/spec/lib/gitlab/project_transfer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ProjectTransfer do +RSpec.describe Gitlab::ProjectTransfer do before do @root_dir = File.join(Rails.root, "public", "uploads") @project_transfer = described_class.new diff --git a/spec/lib/gitlab/prometheus/adapter_spec.rb b/spec/lib/gitlab/prometheus/adapter_spec.rb index afee95467fa..4762e4ad108 100644 --- a/spec/lib/gitlab/prometheus/adapter_spec.rb +++ b/spec/lib/gitlab/prometheus/adapter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Adapter do +RSpec.describe Gitlab::Prometheus::Adapter do let_it_be(:project) { create(:project) } let_it_be(:cluster, reload: true) { create(:cluster, :provided_by_user, environment_scope: '*', projects: [project]) } diff --git a/spec/lib/gitlab/prometheus/additional_metrics_parser_spec.rb b/spec/lib/gitlab/prometheus/additional_metrics_parser_spec.rb index 3f97a69b5eb..3c7496cabd0 100644 --- a/spec/lib/gitlab/prometheus/additional_metrics_parser_spec.rb +++ b/spec/lib/gitlab/prometheus/additional_metrics_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::AdditionalMetricsParser do +RSpec.describe Gitlab::Prometheus::AdditionalMetricsParser do include Prometheus::MetricBuilders let(:parser_error_class) { Gitlab::Prometheus::ParsingError } diff --git a/spec/lib/gitlab/prometheus/internal_spec.rb b/spec/lib/gitlab/prometheus/internal_spec.rb index 884bdcb4e9b..1254610fe32 100644 --- a/spec/lib/gitlab/prometheus/internal_spec.rb +++ b/spec/lib/gitlab/prometheus/internal_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Internal do +RSpec.describe Gitlab::Prometheus::Internal do let(:listen_address) { 'localhost:9090' } let(:prometheus_settings) do diff --git a/spec/lib/gitlab/prometheus/metric_group_spec.rb b/spec/lib/gitlab/prometheus/metric_group_spec.rb index 787f14daf47..a68cdfe5fb2 100644 --- a/spec/lib/gitlab/prometheus/metric_group_spec.rb +++ b/spec/lib/gitlab/prometheus/metric_group_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::MetricGroup do +RSpec.describe Gitlab::Prometheus::MetricGroup do describe '.common_metrics' do let!(:project_metric) { create(:prometheus_metric) } let!(:common_metric_group_a) { create(:prometheus_metric, :common, group: :aws_elb) } diff --git a/spec/lib/gitlab/prometheus/queries/additional_metrics_deployment_query_spec.rb b/spec/lib/gitlab/prometheus/queries/additional_metrics_deployment_query_spec.rb index 55e89395452..8abc944eeb1 100644 --- a/spec/lib/gitlab/prometheus/queries/additional_metrics_deployment_query_spec.rb +++ b/spec/lib/gitlab/prometheus/queries/additional_metrics_deployment_query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Queries::AdditionalMetricsDeploymentQuery do +RSpec.describe Gitlab::Prometheus::Queries::AdditionalMetricsDeploymentQuery do around do |example| Timecop.freeze(Time.local(2008, 9, 1, 12, 0, 0)) { example.run } end diff --git a/spec/lib/gitlab/prometheus/queries/additional_metrics_environment_query_spec.rb b/spec/lib/gitlab/prometheus/queries/additional_metrics_environment_query_spec.rb index 95df8880b90..f5911963108 100644 --- a/spec/lib/gitlab/prometheus/queries/additional_metrics_environment_query_spec.rb +++ b/spec/lib/gitlab/prometheus/queries/additional_metrics_environment_query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Queries::AdditionalMetricsEnvironmentQuery do +RSpec.describe Gitlab::Prometheus::Queries::AdditionalMetricsEnvironmentQuery do around do |example| Timecop.freeze { example.run } end diff --git a/spec/lib/gitlab/prometheus/queries/deployment_query_spec.rb b/spec/lib/gitlab/prometheus/queries/deployment_query_spec.rb index 4af233291f6..4683c4eae28 100644 --- a/spec/lib/gitlab/prometheus/queries/deployment_query_spec.rb +++ b/spec/lib/gitlab/prometheus/queries/deployment_query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Queries::DeploymentQuery do +RSpec.describe Gitlab::Prometheus::Queries::DeploymentQuery do let(:environment) { create(:environment, slug: 'environment-slug') } let(:deployment) { create(:deployment, environment: environment) } let(:client) { double('prometheus_client') } diff --git a/spec/lib/gitlab/prometheus/queries/knative_invocation_query_spec.rb b/spec/lib/gitlab/prometheus/queries/knative_invocation_query_spec.rb index 8eefd22bd29..ff48b9ada90 100644 --- a/spec/lib/gitlab/prometheus/queries/knative_invocation_query_spec.rb +++ b/spec/lib/gitlab/prometheus/queries/knative_invocation_query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Queries::KnativeInvocationQuery do +RSpec.describe Gitlab::Prometheus::Queries::KnativeInvocationQuery do include PrometheusHelpers let(:project) { create(:project) } diff --git a/spec/lib/gitlab/prometheus/queries/matched_metric_query_spec.rb b/spec/lib/gitlab/prometheus/queries/matched_metric_query_spec.rb index 35034d814bf..117ca798022 100644 --- a/spec/lib/gitlab/prometheus/queries/matched_metric_query_spec.rb +++ b/spec/lib/gitlab/prometheus/queries/matched_metric_query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Queries::MatchedMetricQuery do +RSpec.describe Gitlab::Prometheus::Queries::MatchedMetricQuery do include Prometheus::MetricBuilders let(:metric_group_class) { Gitlab::Prometheus::MetricGroup } diff --git a/spec/lib/gitlab/prometheus/queries/validate_query_spec.rb b/spec/lib/gitlab/prometheus/queries/validate_query_spec.rb index 9c0170718f4..045c063ab34 100644 --- a/spec/lib/gitlab/prometheus/queries/validate_query_spec.rb +++ b/spec/lib/gitlab/prometheus/queries/validate_query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::Queries::ValidateQuery do +RSpec.describe Gitlab::Prometheus::Queries::ValidateQuery do include PrometheusHelpers let(:api_url) { 'https://prometheus.example.com' } diff --git a/spec/lib/gitlab/prometheus/query_variables_spec.rb b/spec/lib/gitlab/prometheus/query_variables_spec.rb index 7dfa4de35d6..1422d48152a 100644 --- a/spec/lib/gitlab/prometheus/query_variables_spec.rb +++ b/spec/lib/gitlab/prometheus/query_variables_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Prometheus::QueryVariables do +RSpec.describe Gitlab::Prometheus::QueryVariables do describe '.call' do let(:project) { environment.project } let(:environment) { create(:environment) } diff --git a/spec/lib/gitlab/prometheus_client_spec.rb b/spec/lib/gitlab/prometheus_client_spec.rb index 749192e5795..242a0ced031 100644 --- a/spec/lib/gitlab/prometheus_client_spec.rb +++ b/spec/lib/gitlab/prometheus_client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PrometheusClient do +RSpec.describe Gitlab::PrometheusClient do include PrometheusHelpers subject { described_class.new('https://prometheus.example.com') } @@ -32,7 +32,7 @@ describe Gitlab::PrometheusClient do it 'raises error when status code not 200' do stub_request(:get, subject.health_url).to_return(status: 500, body: '') - expect { subject.healthy? }.to raise_error(Gitlab::PrometheusClient::Error) + expect { subject.healthy? }.to raise_error(Gitlab::PrometheusClient::UnexpectedResponseError) end end @@ -41,41 +41,41 @@ describe Gitlab::PrometheusClient do # - execute_query: A query call shared_examples 'failure response' do context 'when request returns 400 with an error message' do - it 'raises a Gitlab::PrometheusClient::Error error' do + it 'raises a Gitlab::PrometheusClient::QueryError error' do req_stub = stub_prometheus_request(query_url, status: 400, body: { error: 'bar!' }) expect { execute_query } - .to raise_error(Gitlab::PrometheusClient::Error, 'bar!') + .to raise_error(Gitlab::PrometheusClient::QueryError, 'bar!') expect(req_stub).to have_been_requested end end context 'when request returns 400 without an error message' do - it 'raises a Gitlab::PrometheusClient::Error error' do + it 'raises a Gitlab::PrometheusClient::QueryError error' do req_stub = stub_prometheus_request(query_url, status: 400) expect { execute_query } - .to raise_error(Gitlab::PrometheusClient::Error, 'Bad data received') + .to raise_error(Gitlab::PrometheusClient::QueryError, 'Bad data received') expect(req_stub).to have_been_requested end end context 'when request returns 500' do - it 'raises a Gitlab::PrometheusClient::Error error' do + it 'raises a Gitlab::PrometheusClient::UnexpectedResponseError error' do req_stub = stub_prometheus_request(query_url, status: 500, body: { message: 'FAIL!' }) expect { execute_query } - .to raise_error(Gitlab::PrometheusClient::Error, '500 - {"message":"FAIL!"}') + .to raise_error(Gitlab::PrometheusClient::UnexpectedResponseError, '500 - {"message":"FAIL!"}') expect(req_stub).to have_been_requested end end context 'when request returns non json data' do - it 'raises a Gitlab::PrometheusClient::Error error' do + it 'raises a Gitlab::PrometheusClient::UnexpectedResponseError error' do req_stub = stub_prometheus_request(query_url, status: 200, body: 'not json') expect { execute_query } - .to raise_error(Gitlab::PrometheusClient::Error, 'Parsing response failed') + .to raise_error(Gitlab::PrometheusClient::UnexpectedResponseError, 'Parsing response failed') expect(req_stub).to have_been_requested end end @@ -85,35 +85,35 @@ describe Gitlab::PrometheusClient do let(:prometheus_url) {"https://prometheus.invalid.example.com/api/v1/query?query=1"} shared_examples 'exceptions are raised' do - it 'raises a Gitlab::PrometheusClient::Error error when a SocketError is rescued' do + it 'raises a Gitlab::PrometheusClient::ConnectionError error when a SocketError is rescued' do req_stub = stub_prometheus_request_with_exception(prometheus_url, SocketError) expect { subject } - .to raise_error(Gitlab::PrometheusClient::Error, "Can't connect to #{prometheus_url}") + .to raise_error(Gitlab::PrometheusClient::ConnectionError, "Can't connect to #{prometheus_url}") expect(req_stub).to have_been_requested end - it 'raises a Gitlab::PrometheusClient::Error error when a SSLError is rescued' do + it 'raises a Gitlab::PrometheusClient::ConnectionError error when a SSLError is rescued' do req_stub = stub_prometheus_request_with_exception(prometheus_url, OpenSSL::SSL::SSLError) expect { subject } - .to raise_error(Gitlab::PrometheusClient::Error, "#{prometheus_url} contains invalid SSL data") + .to raise_error(Gitlab::PrometheusClient::ConnectionError, "#{prometheus_url} contains invalid SSL data") expect(req_stub).to have_been_requested end - it 'raises a Gitlab::PrometheusClient::Error error when a Gitlab::HTTP::ResponseError is rescued' do + it 'raises a Gitlab::PrometheusClient::ConnectionError error when a Gitlab::HTTP::ResponseError is rescued' do req_stub = stub_prometheus_request_with_exception(prometheus_url, Gitlab::HTTP::ResponseError) expect { subject } - .to raise_error(Gitlab::PrometheusClient::Error, "Network connection error") + .to raise_error(Gitlab::PrometheusClient::ConnectionError, "Network connection error") expect(req_stub).to have_been_requested end - it 'raises a Gitlab::PrometheusClient::Error error when a Gitlab::HTTP::ResponseError with a code is rescued' do + it 'raises a Gitlab::PrometheusClient::ConnectionError error when a Gitlab::HTTP::ResponseError with a code is rescued' do req_stub = stub_prometheus_request_with_exception(prometheus_url, Gitlab::HTTP::ResponseError.new(code: 400)) expect { subject } - .to raise_error(Gitlab::PrometheusClient::Error, "Network connection error") + .to raise_error(Gitlab::PrometheusClient::ConnectionError, "Network connection error") expect(req_stub).to have_been_requested end end @@ -400,9 +400,9 @@ describe Gitlab::PrometheusClient do context "without response code" do let(:response_error) { Gitlab::HTTP::ResponseError } - it 'raises PrometheusClient::Error' do + it 'raises PrometheusClient::ConnectionError' do expect { subject.proxy('query', { query: prometheus_query }) }.to( - raise_error(Gitlab::PrometheusClient::Error, 'Network connection error') + raise_error(Gitlab::PrometheusClient::ConnectionError, 'Network connection error') ) end end diff --git a/spec/lib/gitlab/puma_logging/json_formatter_spec.rb b/spec/lib/gitlab/puma_logging/json_formatter_spec.rb index f7f5b99d5e5..64ace09e01b 100644 --- a/spec/lib/gitlab/puma_logging/json_formatter_spec.rb +++ b/spec/lib/gitlab/puma_logging/json_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PumaLogging::JSONFormatter do +RSpec.describe Gitlab::PumaLogging::JSONFormatter do it "generate json format with timestamp and pid" do Timecop.freeze( Time.utc(2019, 12, 04, 9, 10, 11, 123456)) do expect(subject.call('log message')).to eq "{\"timestamp\":\"2019-12-04T09:10:11.123Z\",\"pid\":#{Process.pid},\"message\":\"log message\"}" diff --git a/spec/lib/gitlab/push_options_spec.rb b/spec/lib/gitlab/push_options_spec.rb index fc9e421bea6..8f43943e2d1 100644 --- a/spec/lib/gitlab/push_options_spec.rb +++ b/spec/lib/gitlab/push_options_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::PushOptions do +RSpec.describe Gitlab::PushOptions do describe 'namespace and key validation' do it 'ignores unrecognised namespaces' do options = described_class.new(['invalid.key=value']) diff --git a/spec/lib/gitlab/query_limiting/active_support_subscriber_spec.rb b/spec/lib/gitlab/query_limiting/active_support_subscriber_spec.rb index 2db6d2fb60f..a8dd482c7b8 100644 --- a/spec/lib/gitlab/query_limiting/active_support_subscriber_spec.rb +++ b/spec/lib/gitlab/query_limiting/active_support_subscriber_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QueryLimiting::ActiveSupportSubscriber do +RSpec.describe Gitlab::QueryLimiting::ActiveSupportSubscriber do let(:transaction) { instance_double(Gitlab::QueryLimiting::Transaction, increment: true) } before do diff --git a/spec/lib/gitlab/query_limiting/middleware_spec.rb b/spec/lib/gitlab/query_limiting/middleware_spec.rb index f397843df54..cae6df8cdd5 100644 --- a/spec/lib/gitlab/query_limiting/middleware_spec.rb +++ b/spec/lib/gitlab/query_limiting/middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QueryLimiting::Middleware do +RSpec.describe Gitlab::QueryLimiting::Middleware do describe '#call' do it 'runs the application with query limiting in place' do middleware = described_class.new(-> (env) { env }) diff --git a/spec/lib/gitlab/query_limiting/transaction_spec.rb b/spec/lib/gitlab/query_limiting/transaction_spec.rb index 4e906314b5a..331c3c1d8b0 100644 --- a/spec/lib/gitlab/query_limiting/transaction_spec.rb +++ b/spec/lib/gitlab/query_limiting/transaction_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QueryLimiting::Transaction do +RSpec.describe Gitlab::QueryLimiting::Transaction do after do Thread.current[described_class::THREAD_KEY] = nil end diff --git a/spec/lib/gitlab/query_limiting_spec.rb b/spec/lib/gitlab/query_limiting_spec.rb index e9c6bbc35a3..0fcd865567d 100644 --- a/spec/lib/gitlab/query_limiting_spec.rb +++ b/spec/lib/gitlab/query_limiting_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QueryLimiting do +RSpec.describe Gitlab::QueryLimiting do describe '.enable?' do it 'returns true in a test environment' do expect(described_class.enable?).to eq(true) diff --git a/spec/lib/gitlab/quick_actions/command_definition_spec.rb b/spec/lib/gitlab/quick_actions/command_definition_spec.rb index 45b710adf07..d63c21954f2 100644 --- a/spec/lib/gitlab/quick_actions/command_definition_spec.rb +++ b/spec/lib/gitlab/quick_actions/command_definition_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QuickActions::CommandDefinition do +RSpec.describe Gitlab::QuickActions::CommandDefinition do subject { described_class.new(:command) } describe "#all_names" do diff --git a/spec/lib/gitlab/quick_actions/dsl_spec.rb b/spec/lib/gitlab/quick_actions/dsl_spec.rb index 1145a7edc85..f990abfb253 100644 --- a/spec/lib/gitlab/quick_actions/dsl_spec.rb +++ b/spec/lib/gitlab/quick_actions/dsl_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QuickActions::Dsl do +RSpec.describe Gitlab::QuickActions::Dsl do before :all do DummyClass = Struct.new(:project) do include Gitlab::QuickActions::Dsl diff --git a/spec/lib/gitlab/quick_actions/extractor_spec.rb b/spec/lib/gitlab/quick_actions/extractor_spec.rb index 6ea597bf01e..f4104b78d5c 100644 --- a/spec/lib/gitlab/quick_actions/extractor_spec.rb +++ b/spec/lib/gitlab/quick_actions/extractor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QuickActions::Extractor do +RSpec.describe Gitlab::QuickActions::Extractor do let(:definitions) do Class.new do include Gitlab::QuickActions::Dsl diff --git a/spec/lib/gitlab/quick_actions/spend_time_and_date_separator_spec.rb b/spec/lib/gitlab/quick_actions/spend_time_and_date_separator_spec.rb index fd149cd1114..0b012bfd970 100644 --- a/spec/lib/gitlab/quick_actions/spend_time_and_date_separator_spec.rb +++ b/spec/lib/gitlab/quick_actions/spend_time_and_date_separator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QuickActions::SpendTimeAndDateSeparator do +RSpec.describe Gitlab::QuickActions::SpendTimeAndDateSeparator do subject { described_class } shared_examples 'arg line with invalid parameters' do diff --git a/spec/lib/gitlab/quick_actions/substitution_definition_spec.rb b/spec/lib/gitlab/quick_actions/substitution_definition_spec.rb index d1a44e2feeb..b28ac49b4ea 100644 --- a/spec/lib/gitlab/quick_actions/substitution_definition_spec.rb +++ b/spec/lib/gitlab/quick_actions/substitution_definition_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::QuickActions::SubstitutionDefinition do +RSpec.describe Gitlab::QuickActions::SubstitutionDefinition do let(:content) do <<EOF Hello! Let's do this! diff --git a/spec/lib/gitlab/rate_limit_helpers_spec.rb b/spec/lib/gitlab/rate_limit_helpers_spec.rb index 5ab79a2bbfe..e7d4c69d47b 100644 --- a/spec/lib/gitlab/rate_limit_helpers_spec.rb +++ b/spec/lib/gitlab/rate_limit_helpers_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RateLimitHelpers, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::RateLimitHelpers, :clean_gitlab_redis_shared_state do let(:limiter_class) do Class.new do include ::Gitlab::RateLimitHelpers diff --git a/spec/lib/gitlab/reactive_cache_set_cache_spec.rb b/spec/lib/gitlab/reactive_cache_set_cache_spec.rb index a0d8f15ba1b..19fb2ada476 100644 --- a/spec/lib/gitlab/reactive_cache_set_cache_spec.rb +++ b/spec/lib/gitlab/reactive_cache_set_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ReactiveCacheSetCache, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::ReactiveCacheSetCache, :clean_gitlab_redis_cache do let_it_be(:project) { create(:project) } let(:cache_prefix) { 'cache_prefix' } let(:expires_in) { 10.minutes } diff --git a/spec/lib/gitlab/redis/boolean_spec.rb b/spec/lib/gitlab/redis/boolean_spec.rb index bfacf0c448b..9c233ba089f 100644 --- a/spec/lib/gitlab/redis/boolean_spec.rb +++ b/spec/lib/gitlab/redis/boolean_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::Redis::Boolean do +RSpec.describe Gitlab::Redis::Boolean do subject(:redis_boolean) { described_class.new(bool) } let(:bool) { true } diff --git a/spec/lib/gitlab/redis/cache_spec.rb b/spec/lib/gitlab/redis/cache_spec.rb index 0718998f981..5f73b84288d 100644 --- a/spec/lib/gitlab/redis/cache_spec.rb +++ b/spec/lib/gitlab/redis/cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Redis::Cache do +RSpec.describe Gitlab::Redis::Cache do let(:config_file_name) { "config/redis.cache.yml" } let(:environment_config_file_name) { "GITLAB_REDIS_CACHE_CONFIG_FILE" } let(:config_old_format_socket) { "spec/fixtures/config/redis_cache_old_format_socket.yml" } diff --git a/spec/lib/gitlab/redis/queues_spec.rb b/spec/lib/gitlab/redis/queues_spec.rb index 93207b6f469..8a32c991943 100644 --- a/spec/lib/gitlab/redis/queues_spec.rb +++ b/spec/lib/gitlab/redis/queues_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Redis::Queues do +RSpec.describe Gitlab::Redis::Queues do let(:config_file_name) { "config/redis.queues.yml" } let(:environment_config_file_name) { "GITLAB_REDIS_QUEUES_CONFIG_FILE" } let(:config_old_format_socket) { "spec/fixtures/config/redis_queues_old_format_socket.yml" } diff --git a/spec/lib/gitlab/redis/shared_state_spec.rb b/spec/lib/gitlab/redis/shared_state_spec.rb index aa61fd99eb5..bd90e4c750d 100644 --- a/spec/lib/gitlab/redis/shared_state_spec.rb +++ b/spec/lib/gitlab/redis/shared_state_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Redis::SharedState do +RSpec.describe Gitlab::Redis::SharedState do let(:config_file_name) { "config/redis.shared_state.yml" } let(:environment_config_file_name) { "GITLAB_REDIS_SHARED_STATE_CONFIG_FILE" } let(:config_old_format_socket) { "spec/fixtures/config/redis_shared_state_old_format_socket.yml" } diff --git a/spec/lib/gitlab/redis/wrapper_spec.rb b/spec/lib/gitlab/redis/wrapper_spec.rb index 51a36eb062c..283853ee863 100644 --- a/spec/lib/gitlab/redis/wrapper_spec.rb +++ b/spec/lib/gitlab/redis/wrapper_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Redis::Wrapper do +RSpec.describe Gitlab::Redis::Wrapper do let(:config_file_name) { "config/resque.yml" } let(:environment_config_file_name) { "GITLAB_REDIS_CONFIG_FILE" } let(:config_old_format_socket) { "spec/fixtures/config/redis_old_format_socket.yml" } diff --git a/spec/lib/gitlab/reference_counter_spec.rb b/spec/lib/gitlab/reference_counter_spec.rb index ae7b18ca007..0d0ac75ee22 100644 --- a/spec/lib/gitlab/reference_counter_spec.rb +++ b/spec/lib/gitlab/reference_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ReferenceCounter, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::ReferenceCounter, :clean_gitlab_redis_shared_state do let(:reference_counter) { described_class.new('project-1') } describe '#increase' do diff --git a/spec/lib/gitlab/reference_extractor_spec.rb b/spec/lib/gitlab/reference_extractor_spec.rb index dd16f3c6035..0172defc75d 100644 --- a/spec/lib/gitlab/reference_extractor_spec.rb +++ b/spec/lib/gitlab/reference_extractor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ReferenceExtractor do +RSpec.describe Gitlab::ReferenceExtractor do let_it_be(:project) { create(:project) } before do diff --git a/spec/lib/gitlab/regex_spec.rb b/spec/lib/gitlab/regex_spec.rb index 2f220272651..7aece6fe697 100644 --- a/spec/lib/gitlab/regex_spec.rb +++ b/spec/lib/gitlab/regex_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Regex do +RSpec.describe Gitlab::Regex do shared_examples_for 'project/group name regex' do it { is_expected.to match('gitlab-ce') } it { is_expected.to match('GitLab CE') } @@ -262,6 +262,39 @@ describe Gitlab::Regex do it { is_expected.not_to match('!!()()') } end + describe '.maven_version_regex' do + subject { described_class.maven_version_regex } + + it { is_expected.to match('0')} + it { is_expected.to match('1') } + it { is_expected.to match('03') } + it { is_expected.to match('2.0') } + it { is_expected.to match('01.2') } + it { is_expected.to match('10.2.3-beta')} + it { is_expected.to match('1.2-SNAPSHOT') } + it { is_expected.to match('20') } + it { is_expected.to match('20.3') } + it { is_expected.to match('1.2.1') } + it { is_expected.to match('1.4.2-12') } + it { is_expected.to match('1.2-beta-2') } + it { is_expected.to match('12.1.2-2-1') } + it { is_expected.to match('1.1-beta-2') } + it { is_expected.to match('1.3.350.v20200505-1744') } + it { is_expected.to match('2.0.0.v200706041905-7C78EK9E_EkMNfNOd2d8qq') } + it { is_expected.to match('1.2-alpha-1-20050205.060708-1') } + it { is_expected.to match('703220b4e2cea9592caeb9f3013f6b1e5335c293') } + it { is_expected.to match('RELEASE') } + it { is_expected.not_to match('..1.2.3') } + it { is_expected.not_to match(' 1.2.3') } + it { is_expected.not_to match("1.2.3 \r\t") } + it { is_expected.not_to match("\r\t 1.2.3") } + it { is_expected.not_to match('1./2.3') } + it { is_expected.not_to match('1.2.3-4/../../') } + it { is_expected.not_to match('1.2.3-4%2e%2e%') } + it { is_expected.not_to match('../../../../../1.2.3') } + it { is_expected.not_to match('%2e%2e%2f1.2.3') } + end + describe '.semver_regex' do subject { described_class.semver_regex } diff --git a/spec/lib/gitlab/repo_path_spec.rb b/spec/lib/gitlab/repo_path_spec.rb index 68571b9de20..05f32459164 100644 --- a/spec/lib/gitlab/repo_path_spec.rb +++ b/spec/lib/gitlab/repo_path_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe ::Gitlab::RepoPath do +RSpec.describe ::Gitlab::RepoPath do include Gitlab::Routing let_it_be(:project) { create(:project, :repository) } diff --git a/spec/lib/gitlab/repository_cache_adapter_spec.rb b/spec/lib/gitlab/repository_cache_adapter_spec.rb index dba5ffc84c5..3727217203e 100644 --- a/spec/lib/gitlab/repository_cache_adapter_spec.rb +++ b/spec/lib/gitlab/repository_cache_adapter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RepositoryCacheAdapter do +RSpec.describe Gitlab::RepositoryCacheAdapter do let(:project) { create(:project, :repository) } let(:repository) { project.repository } let(:cache) { repository.send(:cache) } diff --git a/spec/lib/gitlab/repository_cache_spec.rb b/spec/lib/gitlab/repository_cache_spec.rb index be31be761ad..80285a6c732 100644 --- a/spec/lib/gitlab/repository_cache_spec.rb +++ b/spec/lib/gitlab/repository_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RepositoryCache do +RSpec.describe Gitlab::RepositoryCache do let_it_be(:project) { create(:project) } let(:backend) { double('backend').as_null_object } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/repository_hash_cache_spec.rb b/spec/lib/gitlab/repository_hash_cache_spec.rb index 014a2f235b9..ea856c14a77 100644 --- a/spec/lib/gitlab/repository_hash_cache_spec.rb +++ b/spec/lib/gitlab/repository_hash_cache_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" -describe Gitlab::RepositoryHashCache, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::RepositoryHashCache, :clean_gitlab_redis_cache do let_it_be(:project) { create(:project) } let(:repository) { project.repository } let(:namespace) { "#{repository.full_path}:#{project.id}" } diff --git a/spec/lib/gitlab/repository_set_cache_spec.rb b/spec/lib/gitlab/repository_set_cache_spec.rb index b09194e7d0b..024aae49b04 100644 --- a/spec/lib/gitlab/repository_set_cache_spec.rb +++ b/spec/lib/gitlab/repository_set_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RepositorySetCache, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::RepositorySetCache, :clean_gitlab_redis_cache do let_it_be(:project) { create(:project) } let(:repository) { project.repository } let(:namespace) { "#{repository.full_path}:#{project.id}" } diff --git a/spec/lib/gitlab/repository_size_checker_spec.rb b/spec/lib/gitlab/repository_size_checker_spec.rb index 61f76d716e5..9b2c02b1190 100644 --- a/spec/lib/gitlab/repository_size_checker_spec.rb +++ b/spec/lib/gitlab/repository_size_checker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RepositorySizeChecker do +RSpec.describe Gitlab::RepositorySizeChecker do let(:current_size) { 0 } let(:limit) { 50 } let(:enabled) { true } diff --git a/spec/lib/gitlab/repository_size_error_message_spec.rb b/spec/lib/gitlab/repository_size_error_message_spec.rb index 9e4d19cc572..b6b975143c9 100644 --- a/spec/lib/gitlab/repository_size_error_message_spec.rb +++ b/spec/lib/gitlab/repository_size_error_message_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RepositorySizeErrorMessage do +RSpec.describe Gitlab::RepositorySizeErrorMessage do let(:checker) do Gitlab::RepositorySizeChecker.new( current_size_proc: -> { 15.megabytes }, diff --git a/spec/lib/gitlab/repository_url_builder_spec.rb b/spec/lib/gitlab/repository_url_builder_spec.rb index a5797146cc5..63cb1d7a9ac 100644 --- a/spec/lib/gitlab/repository_url_builder_spec.rb +++ b/spec/lib/gitlab/repository_url_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RepositoryUrlBuilder do +RSpec.describe Gitlab::RepositoryUrlBuilder do describe '.build' do using RSpec::Parameterized::TableSyntax diff --git a/spec/lib/gitlab/request_context_spec.rb b/spec/lib/gitlab/request_context_spec.rb index d7af0765d53..b9acfa4a841 100644 --- a/spec/lib/gitlab/request_context_spec.rb +++ b/spec/lib/gitlab/request_context_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RequestContext, :request_store do +RSpec.describe Gitlab::RequestContext, :request_store do subject { described_class.instance } before do diff --git a/spec/lib/gitlab/request_forgery_protection_spec.rb b/spec/lib/gitlab/request_forgery_protection_spec.rb index b7a3dc16eff..20996dd44b8 100644 --- a/spec/lib/gitlab/request_forgery_protection_spec.rb +++ b/spec/lib/gitlab/request_forgery_protection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RequestForgeryProtection, :allow_forgery_protection do +RSpec.describe Gitlab::RequestForgeryProtection, :allow_forgery_protection do let(:csrf_token) { SecureRandom.base64(ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH) } let(:env) do { diff --git a/spec/lib/gitlab/request_profiler/profile_spec.rb b/spec/lib/gitlab/request_profiler/profile_spec.rb index a75f3c66156..2e9c75dde87 100644 --- a/spec/lib/gitlab/request_profiler/profile_spec.rb +++ b/spec/lib/gitlab/request_profiler/profile_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::RequestProfiler::Profile do +RSpec.describe Gitlab::RequestProfiler::Profile do let(:profile) { described_class.new(filename) } describe '.new' do diff --git a/spec/lib/gitlab/request_profiler_spec.rb b/spec/lib/gitlab/request_profiler_spec.rb index f157189a72d..4d3b361efcb 100644 --- a/spec/lib/gitlab/request_profiler_spec.rb +++ b/spec/lib/gitlab/request_profiler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RequestProfiler do +RSpec.describe Gitlab::RequestProfiler do describe '.profile_token' do it 'returns a token' do expect(described_class.profile_token).to be_present diff --git a/spec/lib/gitlab/route_map_spec.rb b/spec/lib/gitlab/route_map_spec.rb index d5e70b91fb4..e2c71980068 100644 --- a/spec/lib/gitlab/route_map_spec.rb +++ b/spec/lib/gitlab/route_map_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RouteMap do +RSpec.describe Gitlab::RouteMap do describe '#initialize' do context 'when the data is not YAML' do it 'raises an error' do diff --git a/spec/lib/gitlab/routing_spec.rb b/spec/lib/gitlab/routing_spec.rb index 5446d6559fe..304ce57aee3 100644 --- a/spec/lib/gitlab/routing_spec.rb +++ b/spec/lib/gitlab/routing_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Routing do +RSpec.describe Gitlab::Routing do context 'when module is included' do subject do Class.new.include(described_class).new diff --git a/spec/lib/gitlab/rugged_instrumentation_spec.rb b/spec/lib/gitlab/rugged_instrumentation_spec.rb index d6f3fb9be55..393bb957aba 100644 --- a/spec/lib/gitlab/rugged_instrumentation_spec.rb +++ b/spec/lib/gitlab/rugged_instrumentation_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::RuggedInstrumentation, :request_store do +RSpec.describe Gitlab::RuggedInstrumentation, :request_store do subject { described_class } describe '.query_time' do diff --git a/spec/lib/gitlab/runtime_spec.rb b/spec/lib/gitlab/runtime_spec.rb index 8f920bb2e01..8ed7cc141cd 100644 --- a/spec/lib/gitlab/runtime_spec.rb +++ b/spec/lib/gitlab/runtime_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Runtime do +RSpec.describe Gitlab::Runtime do shared_examples "valid runtime" do |runtime, max_threads| it "identifies itself" do expect(subject.identify).to eq(runtime) @@ -48,18 +48,47 @@ describe Gitlab::Runtime do before do stub_const('::Puma', puma_type) allow(puma_type).to receive_message_chain(:cli_config, :options).and_return(max_threads: 2) + stub_env('ACTION_CABLE_IN_APP', 'false') end it_behaves_like "valid runtime", :puma, 3 + + context "when ActionCable in-app mode is enabled" do + before do + stub_env('ACTION_CABLE_IN_APP', 'true') + stub_env('ACTION_CABLE_WORKER_POOL_SIZE', '3') + end + + it_behaves_like "valid runtime", :puma, 6 + end + + context "when ActionCable standalone is run" do + before do + stub_const('ACTION_CABLE_SERVER', true) + stub_env('ACTION_CABLE_WORKER_POOL_SIZE', '8') + end + + it_behaves_like "valid runtime", :puma, 11 + end end context "unicorn" do before do stub_const('::Unicorn', Module.new) stub_const('::Unicorn::HttpServer', Class.new) + stub_env('ACTION_CABLE_IN_APP', 'false') end it_behaves_like "valid runtime", :unicorn, 1 + + context "when ActionCable in-app mode is enabled" do + before do + stub_env('ACTION_CABLE_IN_APP', 'true') + stub_env('ACTION_CABLE_WORKER_POOL_SIZE', '3') + end + + it_behaves_like "valid runtime", :unicorn, 4 + end end context "sidekiq" do @@ -105,17 +134,4 @@ describe Gitlab::Runtime do it_behaves_like "valid runtime", :rails_runner, 1 end - - context "action_cable" do - before do - stub_const('ACTION_CABLE_SERVER', true) - stub_const('::Puma', Module.new) - - allow(Gitlab::Application).to receive_message_chain(:config, :action_cable, :worker_pool_size).and_return(8) - end - - it "reports its maximum concurrency based on ActionCable's worker pool size" do - expect(subject.max_threads).to eq(9) - end - end end diff --git a/spec/lib/gitlab/safe_request_store_spec.rb b/spec/lib/gitlab/safe_request_store_spec.rb index def05a3f285..704102ccaee 100644 --- a/spec/lib/gitlab/safe_request_store_spec.rb +++ b/spec/lib/gitlab/safe_request_store_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SafeRequestStore do +RSpec.describe Gitlab::SafeRequestStore do describe '.store' do context 'when RequestStore is active', :request_store do it 'uses RequestStore' do diff --git a/spec/lib/gitlab/sanitizers/exif_spec.rb b/spec/lib/gitlab/sanitizers/exif_spec.rb index 58fba673f8e..88ef3ce6aa5 100644 --- a/spec/lib/gitlab/sanitizers/exif_spec.rb +++ b/spec/lib/gitlab/sanitizers/exif_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sanitizers::Exif do +RSpec.describe Gitlab::Sanitizers::Exif do let(:sanitizer) { described_class.new } describe '#batch_clean' do diff --git a/spec/lib/gitlab/sanitizers/svg_spec.rb b/spec/lib/gitlab/sanitizers/svg_spec.rb index 18fa96a2914..88fd7b78abe 100644 --- a/spec/lib/gitlab/sanitizers/svg_spec.rb +++ b/spec/lib/gitlab/sanitizers/svg_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sanitizers::SVG do +RSpec.describe Gitlab::Sanitizers::SVG do let(:scrubber) { Gitlab::Sanitizers::SVG::Scrubber.new } let(:namespace) { double(Nokogiri::XML::Namespace, prefix: 'xlink', href: 'http://www.w3.org/1999/xlink') } let(:namespaced_attr) { double(Nokogiri::XML::Attr, name: 'href', namespace: namespace, value: '#awesome_id') } diff --git a/spec/lib/gitlab/search/found_blob_spec.rb b/spec/lib/gitlab/search/found_blob_spec.rb index ce6a54100a5..8b1c91f689d 100644 --- a/spec/lib/gitlab/search/found_blob_spec.rb +++ b/spec/lib/gitlab/search/found_blob_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Search::FoundBlob do +RSpec.describe Gitlab::Search::FoundBlob do let(:project) { create(:project, :public, :repository) } describe 'parsing content results' do diff --git a/spec/lib/gitlab/search/found_wiki_page_spec.rb b/spec/lib/gitlab/search/found_wiki_page_spec.rb index e8b6728aba5..fc166ad3851 100644 --- a/spec/lib/gitlab/search/found_wiki_page_spec.rb +++ b/spec/lib/gitlab/search/found_wiki_page_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Search::FoundWikiPage do +RSpec.describe Gitlab::Search::FoundWikiPage do let(:project) { create(:project, :public, :repository) } describe 'policy' do diff --git a/spec/lib/gitlab/search/query_spec.rb b/spec/lib/gitlab/search/query_spec.rb index 112e9a59f04..e9601002922 100644 --- a/spec/lib/gitlab/search/query_spec.rb +++ b/spec/lib/gitlab/search/query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Search::Query do +RSpec.describe Gitlab::Search::Query do let(:query) { 'base filter:wow anotherfilter:noway name:maybe other:mmm leftover' } let(:subject) do described_class.new(query) do diff --git a/spec/lib/gitlab/search_context/builder_spec.rb b/spec/lib/gitlab/search_context/builder_spec.rb index 1707b54b273..5b4190fc67e 100644 --- a/spec/lib/gitlab/search_context/builder_spec.rb +++ b/spec/lib/gitlab/search_context/builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SearchContext::Builder, type: :controller do +RSpec.describe Gitlab::SearchContext::Builder, type: :controller do controller(ApplicationController) { } subject(:builder) { described_class.new(controller.view_context) } diff --git a/spec/lib/gitlab/search_context/controller_concern_spec.rb b/spec/lib/gitlab/search_context/controller_concern_spec.rb index 16784cafb76..9cf6b8d49aa 100644 --- a/spec/lib/gitlab/search_context/controller_concern_spec.rb +++ b/spec/lib/gitlab/search_context/controller_concern_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SearchContext::ControllerConcern, type: :controller do +RSpec.describe Gitlab::SearchContext::ControllerConcern, type: :controller do controller(ApplicationController) do include Gitlab::SearchContext::ControllerConcern end diff --git a/spec/lib/gitlab/search_results_spec.rb b/spec/lib/gitlab/search_results_spec.rb index ab14602a468..61fa61566cd 100644 --- a/spec/lib/gitlab/search_results_spec.rb +++ b/spec/lib/gitlab/search_results_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SearchResults do +RSpec.describe Gitlab::SearchResults do include ProjectForksHelper include SearchHelpers diff --git a/spec/lib/gitlab/serializer/ci/variables_spec.rb b/spec/lib/gitlab/serializer/ci/variables_spec.rb index 900508420c9..9b0475259fe 100644 --- a/spec/lib/gitlab/serializer/ci/variables_spec.rb +++ b/spec/lib/gitlab/serializer/ci/variables_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Serializer::Ci::Variables do +RSpec.describe Gitlab::Serializer::Ci::Variables do subject do described_class.load(described_class.dump(object)) end diff --git a/spec/lib/gitlab/serializer/pagination_spec.rb b/spec/lib/gitlab/serializer/pagination_spec.rb index 1e7f441f258..69b5e181769 100644 --- a/spec/lib/gitlab/serializer/pagination_spec.rb +++ b/spec/lib/gitlab/serializer/pagination_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Serializer::Pagination do +RSpec.describe Gitlab::Serializer::Pagination do let(:request) { double(url: "#{Gitlab.config.gitlab.url}:8080/api/v4/projects?#{query.to_query}", query_parameters: query) } let(:response) { spy('response') } let(:headers) { spy('headers') } diff --git a/spec/lib/gitlab/serverless/service_spec.rb b/spec/lib/gitlab/serverless/service_spec.rb index 6db8b9cd0ba..3400be5b48e 100644 --- a/spec/lib/gitlab/serverless/service_spec.rb +++ b/spec/lib/gitlab/serverless/service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Serverless::Service do +RSpec.describe Gitlab::Serverless::Service do let(:cluster) { create(:cluster) } let(:environment) { create(:environment) } let(:attributes) do diff --git a/spec/lib/gitlab/service_desk_email_spec.rb b/spec/lib/gitlab/service_desk_email_spec.rb new file mode 100644 index 00000000000..23e2b2ff3cf --- /dev/null +++ b/spec/lib/gitlab/service_desk_email_spec.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::ServiceDeskEmail do + describe '.enabled?' do + context 'when service_desk_email is enabled and address is set' do + before do + stub_service_desk_email_setting(enabled: true, address: 'foo') + end + + it 'returns true' do + expect(described_class.enabled?).to be_truthy + end + end + + context 'when service_desk_email is disabled' do + before do + stub_service_desk_email_setting(enabled: false, address: 'foo') + end + + it 'returns false' do + expect(described_class.enabled?).to be_falsey + end + end + + context 'when service desk address is not set' do + before do + stub_service_desk_email_setting(enabled: true, address: nil) + end + + it 'returns false' do + expect(described_class.enabled?).to be_falsey + end + end + end + + describe '.key_from_address' do + context 'when service desk address is set' do + before do + stub_service_desk_email_setting(address: 'address+%{key}@example.com') + end + + it 'returns key' do + expect(described_class.key_from_address('address+key@example.com')).to eq('key') + end + end + + context 'when service desk address is not set' do + before do + stub_service_desk_email_setting(address: nil) + end + + it 'returns nil' do + expect(described_class.key_from_address('address+key@example.com')).to be_nil + end + end + end +end diff --git a/spec/lib/gitlab/service_desk_spec.rb b/spec/lib/gitlab/service_desk_spec.rb new file mode 100644 index 00000000000..f554840ec78 --- /dev/null +++ b/spec/lib/gitlab/service_desk_spec.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::ServiceDesk do + before do + allow(Gitlab::IncomingEmail).to receive(:enabled?).and_return(true) + allow(Gitlab::IncomingEmail).to receive(:supports_wildcard?).and_return(true) + end + + describe 'enabled?' do + let_it_be(:project) { create(:project) } + + subject { described_class.enabled?(project: project) } + + it { is_expected.to be_truthy } + + context 'when service desk is not supported' do + before do + allow(described_class).to receive(:supported?).and_return(false) + end + + it { is_expected.to be_falsy } + end + + context 'when service desk is disabled for project' do + before do + project.update!(service_desk_enabled: false) + end + + it { is_expected.to be_falsy } + end + end + + describe 'supported?' do + subject { described_class.supported? } + + it { is_expected.to be_truthy } + + context 'when incoming emails are disabled' do + before do + allow(Gitlab::IncomingEmail).to receive(:enabled?).and_return(false) + end + + it { is_expected.to be_falsy } + end + + context 'when email key is not supported' do + before do + allow(Gitlab::IncomingEmail).to receive(:supports_wildcard?).and_return(false) + end + + it { is_expected.to be_falsy } + end + end +end diff --git a/spec/lib/gitlab/session_spec.rb b/spec/lib/gitlab/session_spec.rb index 8db73f0ec7b..de680e8425e 100644 --- a/spec/lib/gitlab/session_spec.rb +++ b/spec/lib/gitlab/session_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Session do +RSpec.describe Gitlab::Session do it 'uses the current thread as a data store' do Thread.current[:session_storage] = { a: :b } diff --git a/spec/lib/gitlab/shard_health_cache_spec.rb b/spec/lib/gitlab/shard_health_cache_spec.rb index f747849b5e9..5c47ac7e9a0 100644 --- a/spec/lib/gitlab/shard_health_cache_spec.rb +++ b/spec/lib/gitlab/shard_health_cache_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ShardHealthCache, :clean_gitlab_redis_cache do +RSpec.describe Gitlab::ShardHealthCache, :clean_gitlab_redis_cache do let(:shards) { %w(foo bar) } before do diff --git a/spec/lib/gitlab/shell_spec.rb b/spec/lib/gitlab/shell_spec.rb index 1f515cffdbf..b0dc34e8abf 100644 --- a/spec/lib/gitlab/shell_spec.rb +++ b/spec/lib/gitlab/shell_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'stringio' -describe Gitlab::Shell do +RSpec.describe Gitlab::Shell do let_it_be(:project) { create(:project, :repository) } let(:repository) { project.repository } let(:gitlab_shell) { described_class.new } diff --git a/spec/lib/gitlab/sherlock/collection_spec.rb b/spec/lib/gitlab/sherlock/collection_spec.rb index bdc89c3d3cf..fcf8e6638f8 100644 --- a/spec/lib/gitlab/sherlock/collection_spec.rb +++ b/spec/lib/gitlab/sherlock/collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::Collection do +RSpec.describe Gitlab::Sherlock::Collection do let(:collection) { described_class.new } let(:transaction) do diff --git a/spec/lib/gitlab/sherlock/file_sample_spec.rb b/spec/lib/gitlab/sherlock/file_sample_spec.rb index b09ba5c62dc..8a1aa51e2d4 100644 --- a/spec/lib/gitlab/sherlock/file_sample_spec.rb +++ b/spec/lib/gitlab/sherlock/file_sample_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::FileSample do +RSpec.describe Gitlab::Sherlock::FileSample do let(:sample) { described_class.new(__FILE__, [], 150.4, 2) } describe '#id' do diff --git a/spec/lib/gitlab/sherlock/line_profiler_spec.rb b/spec/lib/gitlab/sherlock/line_profiler_spec.rb index c1997606839..2220a2cafc8 100644 --- a/spec/lib/gitlab/sherlock/line_profiler_spec.rb +++ b/spec/lib/gitlab/sherlock/line_profiler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::LineProfiler do +RSpec.describe Gitlab::Sherlock::LineProfiler do let(:profiler) { described_class.new } describe '#profile' do diff --git a/spec/lib/gitlab/sherlock/line_sample_spec.rb b/spec/lib/gitlab/sherlock/line_sample_spec.rb index b68e8cc0266..db031377787 100644 --- a/spec/lib/gitlab/sherlock/line_sample_spec.rb +++ b/spec/lib/gitlab/sherlock/line_sample_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::LineSample do +RSpec.describe Gitlab::Sherlock::LineSample do let(:sample) { described_class.new(150.0, 4) } describe '#duration' do diff --git a/spec/lib/gitlab/sherlock/location_spec.rb b/spec/lib/gitlab/sherlock/location_spec.rb index 7b40c84c2d1..4a8b5dffba2 100644 --- a/spec/lib/gitlab/sherlock/location_spec.rb +++ b/spec/lib/gitlab/sherlock/location_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::Location do +RSpec.describe Gitlab::Sherlock::Location do let(:location) { described_class.new(__FILE__, 1) } describe 'from_ruby_location' do diff --git a/spec/lib/gitlab/sherlock/middleware_spec.rb b/spec/lib/gitlab/sherlock/middleware_spec.rb index 8d6e362f622..645bde6681d 100644 --- a/spec/lib/gitlab/sherlock/middleware_spec.rb +++ b/spec/lib/gitlab/sherlock/middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::Middleware do +RSpec.describe Gitlab::Sherlock::Middleware do let(:app) { double(:app) } let(:middleware) { described_class.new(app) } diff --git a/spec/lib/gitlab/sherlock/query_spec.rb b/spec/lib/gitlab/sherlock/query_spec.rb index 13c7e6f8f8b..b8dfd082c37 100644 --- a/spec/lib/gitlab/sherlock/query_spec.rb +++ b/spec/lib/gitlab/sherlock/query_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::Query do +RSpec.describe Gitlab::Sherlock::Query do let(:started_at) { Time.utc(2015, 1, 1) } let(:finished_at) { started_at + 5 } diff --git a/spec/lib/gitlab/sherlock/transaction_spec.rb b/spec/lib/gitlab/sherlock/transaction_spec.rb index 728c44df4f3..535b0ad4d8a 100644 --- a/spec/lib/gitlab/sherlock/transaction_spec.rb +++ b/spec/lib/gitlab/sherlock/transaction_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sherlock::Transaction do +RSpec.describe Gitlab::Sherlock::Transaction do let(:transaction) { described_class.new('POST', '/cat_pictures') } describe '#id' do diff --git a/spec/lib/gitlab/sidekiq_cluster/cli_spec.rb b/spec/lib/gitlab/sidekiq_cluster/cli_spec.rb index fa23bf8958c..cf165d1770b 100644 --- a/spec/lib/gitlab/sidekiq_cluster/cli_spec.rb +++ b/spec/lib/gitlab/sidekiq_cluster/cli_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::SidekiqCluster::CLI do +RSpec.describe Gitlab::SidekiqCluster::CLI do let(:cli) { described_class.new('/dev/null') } let(:timeout) { described_class::DEFAULT_SOFT_TIMEOUT_SECONDS } let(:default_options) do diff --git a/spec/lib/gitlab/sidekiq_cluster_spec.rb b/spec/lib/gitlab/sidekiq_cluster_spec.rb index 3f466e9f2a3..d625a2a2185 100644 --- a/spec/lib/gitlab/sidekiq_cluster_spec.rb +++ b/spec/lib/gitlab/sidekiq_cluster_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::SidekiqCluster do +RSpec.describe Gitlab::SidekiqCluster do describe '.trap_signals' do it 'traps the given signals' do expect(described_class).to receive(:trap).ordered.with(:INT) diff --git a/spec/lib/gitlab/sidekiq_config/cli_methods_spec.rb b/spec/lib/gitlab/sidekiq_config/cli_methods_spec.rb index 7a8aba2d396..01e7c06249a 100644 --- a/spec/lib/gitlab/sidekiq_config/cli_methods_spec.rb +++ b/spec/lib/gitlab/sidekiq_config/cli_methods_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'rspec-parameterized' -describe Gitlab::SidekiqConfig::CliMethods do +RSpec.describe Gitlab::SidekiqConfig::CliMethods do let(:dummy_root) { '/tmp/' } describe '.worker_queues' do diff --git a/spec/lib/gitlab/sidekiq_config/worker_spec.rb b/spec/lib/gitlab/sidekiq_config/worker_spec.rb index 00343a0264d..05987f95b33 100644 --- a/spec/lib/gitlab/sidekiq_config/worker_spec.rb +++ b/spec/lib/gitlab/sidekiq_config/worker_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::SidekiqConfig::Worker do +RSpec.describe Gitlab::SidekiqConfig::Worker do def create_worker(queue:, **attributes) namespace = queue.include?(':') && queue.split(':').first inner_worker = double( diff --git a/spec/lib/gitlab/sidekiq_config_spec.rb b/spec/lib/gitlab/sidekiq_config_spec.rb index 66744d07aaa..d216b9d0c18 100644 --- a/spec/lib/gitlab/sidekiq_config_spec.rb +++ b/spec/lib/gitlab/sidekiq_config_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqConfig do +RSpec.describe Gitlab::SidekiqConfig do describe '.workers' do it 'includes all workers' do worker_classes = described_class.workers.map(&:klass) diff --git a/spec/lib/gitlab/sidekiq_daemon/memory_killer_spec.rb b/spec/lib/gitlab/sidekiq_daemon/memory_killer_spec.rb index 45bcc71dfcb..0ff2dbb234a 100644 --- a/spec/lib/gitlab/sidekiq_daemon/memory_killer_spec.rb +++ b/spec/lib/gitlab/sidekiq_daemon/memory_killer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqDaemon::MemoryKiller do +RSpec.describe Gitlab::SidekiqDaemon::MemoryKiller do let(:memory_killer) { described_class.new } let(:pid) { 12345 } diff --git a/spec/lib/gitlab/sidekiq_daemon/monitor_spec.rb b/spec/lib/gitlab/sidekiq_daemon/monitor_spec.rb index 3f49ef0e9a7..749c7af6f59 100644 --- a/spec/lib/gitlab/sidekiq_daemon/monitor_spec.rb +++ b/spec/lib/gitlab/sidekiq_daemon/monitor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqDaemon::Monitor do +RSpec.describe Gitlab::SidekiqDaemon::Monitor do let(:monitor) { described_class.new } describe '#within_job' do diff --git a/spec/lib/gitlab/sidekiq_logging/deduplication_logger_spec.rb b/spec/lib/gitlab/sidekiq_logging/deduplication_logger_spec.rb index 3cc5c0bed1b..82f927fe481 100644 --- a/spec/lib/gitlab/sidekiq_logging/deduplication_logger_spec.rb +++ b/spec/lib/gitlab/sidekiq_logging/deduplication_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqLogging::DeduplicationLogger do +RSpec.describe Gitlab::SidekiqLogging::DeduplicationLogger do describe '#log_deduplication' do let(:job) do { @@ -18,11 +18,12 @@ describe Gitlab::SidekiqLogging::DeduplicationLogger do expected_payload = { 'job_status' => 'deduplicated', 'message' => "#{job['class']} JID-#{job['jid']}: deduplicated: a fancy strategy", - 'deduplication_type' => 'a fancy strategy' + 'deduplication.type' => 'a fancy strategy', + 'deduplication.options.foo' => :bar } expect(Sidekiq.logger).to receive(:info).with(a_hash_including(expected_payload)).and_call_original - described_class.instance.log(job, "a fancy strategy") + described_class.instance.log(job, "a fancy strategy", { foo: :bar }) end it "does not modify the job" do diff --git a/spec/lib/gitlab/sidekiq_logging/exception_handler_spec.rb b/spec/lib/gitlab/sidekiq_logging/exception_handler_spec.rb index a79a0678e2b..5a68b88c02d 100644 --- a/spec/lib/gitlab/sidekiq_logging/exception_handler_spec.rb +++ b/spec/lib/gitlab/sidekiq_logging/exception_handler_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqLogging::ExceptionHandler do +RSpec.describe Gitlab::SidekiqLogging::ExceptionHandler do describe '#call' do let(:job) do { diff --git a/spec/lib/gitlab/sidekiq_logging/json_formatter_spec.rb b/spec/lib/gitlab/sidekiq_logging/json_formatter_spec.rb index 10354147cf9..c879fdea3ad 100644 --- a/spec/lib/gitlab/sidekiq_logging/json_formatter_spec.rb +++ b/spec/lib/gitlab/sidekiq_logging/json_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqLogging::JSONFormatter do +RSpec.describe Gitlab::SidekiqLogging::JSONFormatter do let(:message) { 'This is a test' } let(:now) { Time.now } let(:timestamp) { now.utc.to_f } diff --git a/spec/lib/gitlab/sidekiq_logging/structured_logger_spec.rb b/spec/lib/gitlab/sidekiq_logging/structured_logger_spec.rb index a456f814e78..03ace9a01c7 100644 --- a/spec/lib/gitlab/sidekiq_logging/structured_logger_spec.rb +++ b/spec/lib/gitlab/sidekiq_logging/structured_logger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqLogging::StructuredLogger do +RSpec.describe Gitlab::SidekiqLogging::StructuredLogger do describe '#call' do let(:timestamp) { Time.iso8601('2018-01-01T12:00:00.000Z') } let(:created_at) { timestamp - 1.second } diff --git a/spec/lib/gitlab/sidekiq_middleware/admin_mode/client_spec.rb b/spec/lib/gitlab/sidekiq_middleware/admin_mode/client_spec.rb index f6449bae8c3..3d9ffb11ae2 100644 --- a/spec/lib/gitlab/sidekiq_middleware/admin_mode/client_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/admin_mode/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::AdminMode::Client, :do_not_mock_admin_mode, :request_store do +RSpec.describe Gitlab::SidekiqMiddleware::AdminMode::Client, :do_not_mock_admin_mode, :request_store do include AdminModeHelper let(:worker) do diff --git a/spec/lib/gitlab/sidekiq_middleware/admin_mode/server_spec.rb b/spec/lib/gitlab/sidekiq_middleware/admin_mode/server_spec.rb index 60475f0e403..20f1e88bcf4 100644 --- a/spec/lib/gitlab/sidekiq_middleware/admin_mode/server_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/admin_mode/server_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::AdminMode::Server, :do_not_mock_admin_mode, :request_store do +RSpec.describe Gitlab::SidekiqMiddleware::AdminMode::Server, :do_not_mock_admin_mode, :request_store do include AdminModeHelper let(:worker) do diff --git a/spec/lib/gitlab/sidekiq_middleware/client_metrics_spec.rb b/spec/lib/gitlab/sidekiq_middleware/client_metrics_spec.rb index 1d45b70ec3e..f7010b2001a 100644 --- a/spec/lib/gitlab/sidekiq_middleware/client_metrics_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/client_metrics_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::ClientMetrics do +RSpec.describe Gitlab::SidekiqMiddleware::ClientMetrics do context "with worker attribution" do subject { described_class.new } diff --git a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/client_spec.rb b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/client_spec.rb index a1e4cbb1e31..98350fb9b8e 100644 --- a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/client_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::DuplicateJobs::Client, :clean_gitlab_redis_queues do +RSpec.describe Gitlab::SidekiqMiddleware::DuplicateJobs::Client, :clean_gitlab_redis_queues do let(:worker_class) do Class.new do def self.name diff --git a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/duplicate_job_spec.rb b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/duplicate_job_spec.rb index 13c86563be7..8ef61d4eae9 100644 --- a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/duplicate_job_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/duplicate_job_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::DuplicateJobs::DuplicateJob, :clean_gitlab_redis_queues do +RSpec.describe Gitlab::SidekiqMiddleware::DuplicateJobs::DuplicateJob, :clean_gitlab_redis_queues do using RSpec::Parameterized::TableSyntax subject(:duplicate_job) do diff --git a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/server_spec.rb b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/server_spec.rb index 312ebd30a76..3f75d867936 100644 --- a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/server_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/server_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::DuplicateJobs::Server, :clean_gitlab_redis_queues do +RSpec.describe Gitlab::SidekiqMiddleware::DuplicateJobs::Server, :clean_gitlab_redis_queues do let(:worker_class) do Class.new do def self.name diff --git a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies/until_executing_spec.rb b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies/until_executing_spec.rb index eb8b0a951a8..77d760d1ae3 100644 --- a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies/until_executing_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies/until_executing_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'timecop' -describe Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies::UntilExecuting do +RSpec.describe Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies::UntilExecuting do let(:fake_duplicate_job) do instance_double(Gitlab::SidekiqMiddleware::DuplicateJobs::DuplicateJob) end @@ -40,6 +40,7 @@ describe Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies::UntilExecuting do allow(fake_duplicate_job).to receive(:scheduled?).and_return(false) allow(fake_duplicate_job).to receive(:check!).and_return('the jid') allow(fake_duplicate_job).to receive(:droppable?).and_return(true) + allow(fake_duplicate_job).to receive(:options).and_return({}) job_hash = {} expect(fake_duplicate_job).to receive(:duplicate?).and_return(true) @@ -102,6 +103,7 @@ describe Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies::UntilExecuting do allow(fake_duplicate_job).to receive(:scheduled?).and_return(false) allow(fake_duplicate_job).to receive(:check!).and_return('the jid') allow(fake_duplicate_job).to receive(:duplicate?).and_return(true) + allow(fake_duplicate_job).to receive(:options).and_return({}) allow(fake_duplicate_job).to receive(:existing_jid).and_return('the jid') allow(fake_duplicate_job).to receive(:droppable?).and_return(true) end @@ -119,7 +121,17 @@ describe Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies::UntilExecuting do fake_logger = instance_double(Gitlab::SidekiqLogging::DeduplicationLogger) expect(Gitlab::SidekiqLogging::DeduplicationLogger).to receive(:instance).and_return(fake_logger) - expect(fake_logger).to receive(:log).with(a_hash_including({ 'jid' => 'new jid' }), 'dropped until executing') + expect(fake_logger).to receive(:log).with(a_hash_including({ 'jid' => 'new jid' }), 'dropped until executing', {}) + + strategy.schedule({ 'jid' => 'new jid' }) {} + end + + it 'logs the deduplication options of the worker' do + fake_logger = instance_double(Gitlab::SidekiqLogging::DeduplicationLogger) + + expect(Gitlab::SidekiqLogging::DeduplicationLogger).to receive(:instance).and_return(fake_logger) + allow(fake_duplicate_job).to receive(:options).and_return({ foo: :bar }) + expect(fake_logger).to receive(:log).with(a_hash_including({ 'jid' => 'new jid' }), 'dropped until executing', { foo: :bar }) strategy.schedule({ 'jid' => 'new jid' }) {} end diff --git a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies_spec.rb b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies_spec.rb index 6ecc2a3a5f8..5d37e3cb1ae 100644 --- a/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/duplicate_jobs/strategies_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies do +RSpec.describe Gitlab::SidekiqMiddleware::DuplicateJobs::Strategies do describe '.for' do it 'returns the right class for `until_executing`' do expect(described_class.for(:until_executing)).to eq(described_class::UntilExecuting) diff --git a/spec/lib/gitlab/sidekiq_middleware/extra_done_log_metadata_spec.rb b/spec/lib/gitlab/sidekiq_middleware/extra_done_log_metadata_spec.rb index 98847885e62..dbab67f5996 100644 --- a/spec/lib/gitlab/sidekiq_middleware/extra_done_log_metadata_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/extra_done_log_metadata_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::ExtraDoneLogMetadata do +RSpec.describe Gitlab::SidekiqMiddleware::ExtraDoneLogMetadata do # Cannot use Class.new for this as ApplicationWorker will need the class to # have a name during `included do`. let(:worker) { AdminEmailWorker.new } diff --git a/spec/lib/gitlab/sidekiq_middleware/memory_killer_spec.rb b/spec/lib/gitlab/sidekiq_middleware/memory_killer_spec.rb index b5be43ec96c..0d1616c4aed 100644 --- a/spec/lib/gitlab/sidekiq_middleware/memory_killer_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/memory_killer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::MemoryKiller do +RSpec.describe Gitlab::SidekiqMiddleware::MemoryKiller do subject { described_class.new } let(:pid) { 999 } diff --git a/spec/lib/gitlab/sidekiq_middleware/monitor_spec.rb b/spec/lib/gitlab/sidekiq_middleware/monitor_spec.rb index 398144025ea..85cddfa7bf1 100644 --- a/spec/lib/gitlab/sidekiq_middleware/monitor_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/monitor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::Monitor do +RSpec.describe Gitlab::SidekiqMiddleware::Monitor do let(:monitor) { described_class.new } describe '#call' do diff --git a/spec/lib/gitlab/sidekiq_middleware/server_metrics_spec.rb b/spec/lib/gitlab/sidekiq_middleware/server_metrics_spec.rb index 4b7baea25e8..1b3b108d9ea 100644 --- a/spec/lib/gitlab/sidekiq_middleware/server_metrics_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/server_metrics_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::ServerMetrics do +RSpec.describe Gitlab::SidekiqMiddleware::ServerMetrics do context "with worker attribution" do subject { described_class.new } diff --git a/spec/lib/gitlab/sidekiq_middleware/worker_context/client_spec.rb b/spec/lib/gitlab/sidekiq_middleware/worker_context/client_spec.rb index 9cb89b1bc10..fff925f8532 100644 --- a/spec/lib/gitlab/sidekiq_middleware/worker_context/client_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/worker_context/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::WorkerContext::Client do +RSpec.describe Gitlab::SidekiqMiddleware::WorkerContext::Client do let(:worker_class) do Class.new do def self.name diff --git a/spec/lib/gitlab/sidekiq_middleware/worker_context/server_spec.rb b/spec/lib/gitlab/sidekiq_middleware/worker_context/server_spec.rb index fdf643a8ad1..bde19fa7552 100644 --- a/spec/lib/gitlab/sidekiq_middleware/worker_context/server_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware/worker_context/server_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqMiddleware::WorkerContext::Server do +RSpec.describe Gitlab::SidekiqMiddleware::WorkerContext::Server do let(:worker_class) do Class.new do def self.name diff --git a/spec/lib/gitlab/sidekiq_middleware_spec.rb b/spec/lib/gitlab/sidekiq_middleware_spec.rb index 5ca0abeb132..018821e6c5e 100644 --- a/spec/lib/gitlab/sidekiq_middleware_spec.rb +++ b/spec/lib/gitlab/sidekiq_middleware_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'sidekiq/testing' -describe Gitlab::SidekiqMiddleware do +RSpec.describe Gitlab::SidekiqMiddleware do before do stub_const('TestWorker', Class.new) diff --git a/spec/lib/gitlab/sidekiq_queue_spec.rb b/spec/lib/gitlab/sidekiq_queue_spec.rb index f5be8d9bfed..44ac89c0816 100644 --- a/spec/lib/gitlab/sidekiq_queue_spec.rb +++ b/spec/lib/gitlab/sidekiq_queue_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqQueue, :clean_gitlab_redis_queues do +RSpec.describe Gitlab::SidekiqQueue, :clean_gitlab_redis_queues do around do |example| Sidekiq::Queue.new('authorized_projects').clear Sidekiq::Testing.disable!(&example) diff --git a/spec/lib/gitlab/sidekiq_signals_spec.rb b/spec/lib/gitlab/sidekiq_signals_spec.rb index 10f1bad32cd..2f751839f6a 100644 --- a/spec/lib/gitlab/sidekiq_signals_spec.rb +++ b/spec/lib/gitlab/sidekiq_signals_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqSignals do +RSpec.describe Gitlab::SidekiqSignals do describe '.install' do let(:result) { Hash.new { |h, k| h[k] = 0 } } let(:int_handler) { -> (_) { result['INT'] += 1 } } diff --git a/spec/lib/gitlab/sidekiq_status/client_middleware_spec.rb b/spec/lib/gitlab/sidekiq_status/client_middleware_spec.rb index 1ca8cea66fc..0cf05fb0a5c 100644 --- a/spec/lib/gitlab/sidekiq_status/client_middleware_spec.rb +++ b/spec/lib/gitlab/sidekiq_status/client_middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqStatus::ClientMiddleware do +RSpec.describe Gitlab::SidekiqStatus::ClientMiddleware do describe '#call' do it 'tracks the job in Redis' do expect(Gitlab::SidekiqStatus).to receive(:set).with('123', Gitlab::SidekiqStatus::DEFAULT_EXPIRATION) diff --git a/spec/lib/gitlab/sidekiq_status/server_middleware_spec.rb b/spec/lib/gitlab/sidekiq_status/server_middleware_spec.rb index 40bcb49d1d3..5a0c4cbd1b5 100644 --- a/spec/lib/gitlab/sidekiq_status/server_middleware_spec.rb +++ b/spec/lib/gitlab/sidekiq_status/server_middleware_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqStatus::ServerMiddleware do +RSpec.describe Gitlab::SidekiqStatus::ServerMiddleware do describe '#call' do it 'stops tracking of a job upon completion' do expect(Gitlab::SidekiqStatus).to receive(:unset).with('123') diff --git a/spec/lib/gitlab/sidekiq_status_spec.rb b/spec/lib/gitlab/sidekiq_status_spec.rb index 7b5c75b2f3b..dd5b8856ccd 100644 --- a/spec/lib/gitlab/sidekiq_status_spec.rb +++ b/spec/lib/gitlab/sidekiq_status_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqStatus do +RSpec.describe Gitlab::SidekiqStatus do describe '.set', :clean_gitlab_redis_shared_state do it 'stores the job ID' do described_class.set('123') diff --git a/spec/lib/gitlab/sidekiq_versioning/manager_spec.rb b/spec/lib/gitlab/sidekiq_versioning/manager_spec.rb index a528ce201a2..84161d9236e 100644 --- a/spec/lib/gitlab/sidekiq_versioning/manager_spec.rb +++ b/spec/lib/gitlab/sidekiq_versioning/manager_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqVersioning::Manager do +RSpec.describe Gitlab::SidekiqVersioning::Manager do before do Sidekiq::Manager.prepend described_class end diff --git a/spec/lib/gitlab/sidekiq_versioning_spec.rb b/spec/lib/gitlab/sidekiq_versioning_spec.rb index 11c866894c2..ed9650fc166 100644 --- a/spec/lib/gitlab/sidekiq_versioning_spec.rb +++ b/spec/lib/gitlab/sidekiq_versioning_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SidekiqVersioning, :redis do +RSpec.describe Gitlab::SidekiqVersioning, :redis do let(:foo_worker) do Class.new do def self.name diff --git a/spec/lib/gitlab/slash_commands/application_help_spec.rb b/spec/lib/gitlab/slash_commands/application_help_spec.rb index afa63c21584..b82121bf3a8 100644 --- a/spec/lib/gitlab/slash_commands/application_help_spec.rb +++ b/spec/lib/gitlab/slash_commands/application_help_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::ApplicationHelp do +RSpec.describe Gitlab::SlashCommands::ApplicationHelp do let(:params) { { command: '/gitlab', text: 'help' } } let(:project) { build(:project) } diff --git a/spec/lib/gitlab/slash_commands/command_spec.rb b/spec/lib/gitlab/slash_commands/command_spec.rb index 9849cf78b2f..069577b3846 100644 --- a/spec/lib/gitlab/slash_commands/command_spec.rb +++ b/spec/lib/gitlab/slash_commands/command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Command do +RSpec.describe Gitlab::SlashCommands::Command do let(:project) { create(:project, :repository) } let(:user) { create(:user) } let(:chat_name) { double(:chat_name, user: user) } diff --git a/spec/lib/gitlab/slash_commands/deploy_spec.rb b/spec/lib/gitlab/slash_commands/deploy_spec.rb index fb9969800a2..36f47c711bc 100644 --- a/spec/lib/gitlab/slash_commands/deploy_spec.rb +++ b/spec/lib/gitlab/slash_commands/deploy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Deploy do +RSpec.describe Gitlab::SlashCommands::Deploy do describe '#execute' do let(:project) { create(:project, :repository) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/slash_commands/issue_close_spec.rb b/spec/lib/gitlab/slash_commands/issue_close_spec.rb index c0760ce0ba6..cf6ac2c5267 100644 --- a/spec/lib/gitlab/slash_commands/issue_close_spec.rb +++ b/spec/lib/gitlab/slash_commands/issue_close_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::IssueClose do +RSpec.describe Gitlab::SlashCommands::IssueClose do describe '#execute' do let(:issue) { create(:issue, project: project) } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/slash_commands/issue_comment_spec.rb b/spec/lib/gitlab/slash_commands/issue_comment_spec.rb index c6f56d10d1f..f3c3bccfade 100644 --- a/spec/lib/gitlab/slash_commands/issue_comment_spec.rb +++ b/spec/lib/gitlab/slash_commands/issue_comment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::IssueComment do +RSpec.describe Gitlab::SlashCommands::IssueComment do describe '#execute' do let(:project) { create(:project, :public) } let(:issue) { create(:issue, project: project) } diff --git a/spec/lib/gitlab/slash_commands/issue_move_spec.rb b/spec/lib/gitlab/slash_commands/issue_move_spec.rb index 1a45b0e06ba..5fffbb2d4cc 100644 --- a/spec/lib/gitlab/slash_commands/issue_move_spec.rb +++ b/spec/lib/gitlab/slash_commands/issue_move_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::IssueMove, service: true do +RSpec.describe Gitlab::SlashCommands::IssueMove, service: true do describe '#match' do shared_examples_for 'move command' do |text_command| it 'can be parsed to extract the needed fields' do diff --git a/spec/lib/gitlab/slash_commands/issue_new_spec.rb b/spec/lib/gitlab/slash_commands/issue_new_spec.rb index 90f0518a63e..c17cee887ee 100644 --- a/spec/lib/gitlab/slash_commands/issue_new_spec.rb +++ b/spec/lib/gitlab/slash_commands/issue_new_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::IssueNew do +RSpec.describe Gitlab::SlashCommands::IssueNew do describe '#execute' do let(:project) { create(:project) } let(:user) { create(:user) } diff --git a/spec/lib/gitlab/slash_commands/issue_search_spec.rb b/spec/lib/gitlab/slash_commands/issue_search_spec.rb index a142c8e4c92..8a86aaf67e3 100644 --- a/spec/lib/gitlab/slash_commands/issue_search_spec.rb +++ b/spec/lib/gitlab/slash_commands/issue_search_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::IssueSearch do +RSpec.describe Gitlab::SlashCommands::IssueSearch do describe '#execute' do let!(:issue) { create(:issue, project: project, title: 'find me') } let!(:confidential) { create(:issue, :confidential, project: project, title: 'mepmep find') } diff --git a/spec/lib/gitlab/slash_commands/issue_show_spec.rb b/spec/lib/gitlab/slash_commands/issue_show_spec.rb index e53f79dcd86..62628daf24d 100644 --- a/spec/lib/gitlab/slash_commands/issue_show_spec.rb +++ b/spec/lib/gitlab/slash_commands/issue_show_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::IssueShow do +RSpec.describe Gitlab::SlashCommands::IssueShow do describe '#execute' do let(:issue) { create(:issue, project: project) } let(:project) { create(:project) } diff --git a/spec/lib/gitlab/slash_commands/presenters/access_spec.rb b/spec/lib/gitlab/slash_commands/presenters/access_spec.rb index 804184a7173..5d62e96971b 100644 --- a/spec/lib/gitlab/slash_commands/presenters/access_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::Access do +RSpec.describe Gitlab::SlashCommands::Presenters::Access do shared_examples_for 'displays an error message' do it do expect(subject[:text]).to match(error_message) diff --git a/spec/lib/gitlab/slash_commands/presenters/deploy_spec.rb b/spec/lib/gitlab/slash_commands/presenters/deploy_spec.rb index 9c2e9ab982f..c6f188de576 100644 --- a/spec/lib/gitlab/slash_commands/presenters/deploy_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/deploy_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::Deploy do +RSpec.describe Gitlab::SlashCommands::Presenters::Deploy do let(:build) { create(:ci_build) } describe '#present' do diff --git a/spec/lib/gitlab/slash_commands/presenters/error_spec.rb b/spec/lib/gitlab/slash_commands/presenters/error_spec.rb index 30ff81510c1..24d6aad1726 100644 --- a/spec/lib/gitlab/slash_commands/presenters/error_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/error_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::Error do +RSpec.describe Gitlab::SlashCommands::Presenters::Error do subject { described_class.new('Error').message } it { is_expected.to be_a(Hash) } diff --git a/spec/lib/gitlab/slash_commands/presenters/issue_close_spec.rb b/spec/lib/gitlab/slash_commands/presenters/issue_close_spec.rb index adc13b4ee56..daa859d4de7 100644 --- a/spec/lib/gitlab/slash_commands/presenters/issue_close_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/issue_close_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::IssueClose do +RSpec.describe Gitlab::SlashCommands::Presenters::IssueClose do let(:project) { create(:project) } let(:issue) { create(:issue, project: project) } let(:attachment) { subject[:attachments].first } diff --git a/spec/lib/gitlab/slash_commands/presenters/issue_comment_spec.rb b/spec/lib/gitlab/slash_commands/presenters/issue_comment_spec.rb index 3741563a744..109b4b8fee1 100644 --- a/spec/lib/gitlab/slash_commands/presenters/issue_comment_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/issue_comment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::IssueComment do +RSpec.describe Gitlab::SlashCommands::Presenters::IssueComment do let_it_be(:project) { create(:project) } let_it_be(:issue) { create(:issue, project: project) } let_it_be(:note) { create(:note, project: project, noteable: issue) } diff --git a/spec/lib/gitlab/slash_commands/presenters/issue_move_spec.rb b/spec/lib/gitlab/slash_commands/presenters/issue_move_spec.rb index 7726c3b6a87..df949154d4c 100644 --- a/spec/lib/gitlab/slash_commands/presenters/issue_move_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/issue_move_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::IssueMove do +RSpec.describe Gitlab::SlashCommands::Presenters::IssueMove do let_it_be(:admin) { create(:admin) } let_it_be(:project, reload: true) { create(:project) } let_it_be(:other_project) { create(:project) } diff --git a/spec/lib/gitlab/slash_commands/presenters/issue_new_spec.rb b/spec/lib/gitlab/slash_commands/presenters/issue_new_spec.rb index f926783fbea..03a94ea5e29 100644 --- a/spec/lib/gitlab/slash_commands/presenters/issue_new_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/issue_new_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::IssueNew do +RSpec.describe Gitlab::SlashCommands::Presenters::IssueNew do let(:project) { create(:project) } let(:issue) { create(:issue, project: project) } let(:attachment) { subject[:attachments].first } diff --git a/spec/lib/gitlab/slash_commands/presenters/issue_search_spec.rb b/spec/lib/gitlab/slash_commands/presenters/issue_search_spec.rb index e1c011133c4..c12e7fa7ee8 100644 --- a/spec/lib/gitlab/slash_commands/presenters/issue_search_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/issue_search_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::IssueSearch do +RSpec.describe Gitlab::SlashCommands::Presenters::IssueSearch do let(:project) { create(:project) } let(:message) { subject[:text] } diff --git a/spec/lib/gitlab/slash_commands/presenters/issue_show_spec.rb b/spec/lib/gitlab/slash_commands/presenters/issue_show_spec.rb index 47b9a67f54f..91fd32d2b55 100644 --- a/spec/lib/gitlab/slash_commands/presenters/issue_show_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/issue_show_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::IssueShow do +RSpec.describe Gitlab::SlashCommands::Presenters::IssueShow do let(:user) { create(:user, :with_avatar) } let(:project) { create(:project, creator: user) } let(:issue) { create(:issue, project: project) } diff --git a/spec/lib/gitlab/slash_commands/presenters/run_spec.rb b/spec/lib/gitlab/slash_commands/presenters/run_spec.rb index f3ab01ef6bb..3a775e8f101 100644 --- a/spec/lib/gitlab/slash_commands/presenters/run_spec.rb +++ b/spec/lib/gitlab/slash_commands/presenters/run_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Presenters::Run do +RSpec.describe Gitlab::SlashCommands::Presenters::Run do let(:presenter) { described_class.new } describe '#present' do diff --git a/spec/lib/gitlab/slash_commands/run_spec.rb b/spec/lib/gitlab/slash_commands/run_spec.rb index 32a23129e3c..c9ff580d586 100644 --- a/spec/lib/gitlab/slash_commands/run_spec.rb +++ b/spec/lib/gitlab/slash_commands/run_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SlashCommands::Run do +RSpec.describe Gitlab::SlashCommands::Run do describe '.available?' do it 'returns true when builds are enabled for the project' do project = double(:project, builds_enabled?: true) diff --git a/spec/lib/gitlab/slug/environment_spec.rb b/spec/lib/gitlab/slug/environment_spec.rb index 7dc583a94b8..f516322b937 100644 --- a/spec/lib/gitlab/slug/environment_spec.rb +++ b/spec/lib/gitlab/slug/environment_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Slug::Environment do +RSpec.describe Gitlab::Slug::Environment do describe '#generate' do { "staging-12345678901234567" => "staging-123456789-q517sa", diff --git a/spec/lib/gitlab/snippet_search_results_spec.rb b/spec/lib/gitlab/snippet_search_results_spec.rb index a41be0eaa95..e1ae26a4d9e 100644 --- a/spec/lib/gitlab/snippet_search_results_spec.rb +++ b/spec/lib/gitlab/snippet_search_results_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SnippetSearchResults do +RSpec.describe Gitlab::SnippetSearchResults do include SearchHelpers let_it_be(:snippet) { create(:snippet, content: 'foo', file_name: 'foo') } diff --git a/spec/lib/gitlab/sourcegraph_spec.rb b/spec/lib/gitlab/sourcegraph_spec.rb index ef4008960a9..ad947475f06 100644 --- a/spec/lib/gitlab/sourcegraph_spec.rb +++ b/spec/lib/gitlab/sourcegraph_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Sourcegraph do +RSpec.describe Gitlab::Sourcegraph do let_it_be(:user) { create(:user) } let(:feature_scope) { true } diff --git a/spec/lib/gitlab/sql/cte_spec.rb b/spec/lib/gitlab/sql/cte_spec.rb index e6194924f5a..fdc150cd4b9 100644 --- a/spec/lib/gitlab/sql/cte_spec.rb +++ b/spec/lib/gitlab/sql/cte_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SQL::CTE do +RSpec.describe Gitlab::SQL::CTE do describe '#to_arel' do it 'generates an Arel relation for the CTE body' do relation = User.where(id: 1) diff --git a/spec/lib/gitlab/sql/glob_spec.rb b/spec/lib/gitlab/sql/glob_spec.rb index 83eed309ecc..8e2b842add6 100644 --- a/spec/lib/gitlab/sql/glob_spec.rb +++ b/spec/lib/gitlab/sql/glob_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SQL::Glob do +RSpec.describe Gitlab::SQL::Glob do describe '.to_like' do it 'matches * as %' do expect(glob('apple', '*')).to be(true) diff --git a/spec/lib/gitlab/sql/pattern_spec.rb b/spec/lib/gitlab/sql/pattern_spec.rb index 38b93913f6d..220ac2ff6da 100644 --- a/spec/lib/gitlab/sql/pattern_spec.rb +++ b/spec/lib/gitlab/sql/pattern_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SQL::Pattern do +RSpec.describe Gitlab::SQL::Pattern do describe '.to_pattern' do subject(:to_pattern) { User.to_pattern(query) } diff --git a/spec/lib/gitlab/sql/recursive_cte_spec.rb b/spec/lib/gitlab/sql/recursive_cte_spec.rb index b15be56dd6d..02611620989 100644 --- a/spec/lib/gitlab/sql/recursive_cte_spec.rb +++ b/spec/lib/gitlab/sql/recursive_cte_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SQL::RecursiveCTE do +RSpec.describe Gitlab::SQL::RecursiveCTE do let(:cte) { described_class.new(:cte_name) } describe '#to_arel' do diff --git a/spec/lib/gitlab/sql/union_spec.rb b/spec/lib/gitlab/sql/union_spec.rb index f736614ae53..c8be83c093d 100644 --- a/spec/lib/gitlab/sql/union_spec.rb +++ b/spec/lib/gitlab/sql/union_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SQL::Union do +RSpec.describe Gitlab::SQL::Union do let(:relation_1) { User.where(email: 'alice@example.com').select(:id) } let(:relation_2) { User.where(email: 'bob@example.com').select(:id) } diff --git a/spec/lib/gitlab/ssh_public_key_spec.rb b/spec/lib/gitlab/ssh_public_key_spec.rb index 08e008c82d9..e1a588a4b7d 100644 --- a/spec/lib/gitlab/ssh_public_key_spec.rb +++ b/spec/lib/gitlab/ssh_public_key_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SSHPublicKey, lib: true do +RSpec.describe Gitlab::SSHPublicKey, lib: true do let(:key) { attributes_for(:rsa_key_2048)[:key] } let(:public_key) { described_class.new(key) } diff --git a/spec/lib/gitlab/static_site_editor/config_spec.rb b/spec/lib/gitlab/static_site_editor/config_spec.rb index 4cfda83b8f6..b60a6a9b006 100644 --- a/spec/lib/gitlab/static_site_editor/config_spec.rb +++ b/spec/lib/gitlab/static_site_editor/config_spec.rb @@ -2,11 +2,14 @@ require 'spec_helper' -describe Gitlab::StaticSiteEditor::Config do +RSpec.describe Gitlab::StaticSiteEditor::Config do subject(:config) { described_class.new(repository, ref, file_path, return_url) } let_it_be(:namespace) { create(:namespace, name: 'namespace') } + let_it_be(:root_group) { create(:group, name: 'group') } + let_it_be(:subgroup) { create(:group, name: 'subgroup', parent: root_group) } let_it_be(:project) { create(:project, :public, :repository, name: 'project', namespace: namespace) } + let_it_be(:project_with_subgroup) { create(:project, :public, :repository, name: 'project', group: subgroup) } let_it_be(:repository) { project.repository } let(:ref) { 'master' } @@ -30,6 +33,34 @@ describe Gitlab::StaticSiteEditor::Config do ) end + context 'when namespace is a subgroup' do + let(:repository) { project_with_subgroup.repository } + + it 'returns data for the frontend component' do + is_expected.to include( + namespace: 'group/subgroup', + project: 'project', + base_url: '/group/subgroup/project/-/sse/master%2FREADME.md' + ) + end + end + + context 'when file has .md.erb extension' do + let(:file_path) { 'README.md.erb' } + + before do + repository.create_file( + project.creator, + file_path, + '', + message: 'message', + branch_name: 'master' + ) + end + + it { is_expected.to include(is_supported_content: 'true') } + end + context 'when file path is nested' do let(:file_path) { 'lib/README.md' } diff --git a/spec/lib/gitlab/string_placeholder_replacer_spec.rb b/spec/lib/gitlab/string_placeholder_replacer_spec.rb index 0295bf1265f..8f17bf64005 100644 --- a/spec/lib/gitlab/string_placeholder_replacer_spec.rb +++ b/spec/lib/gitlab/string_placeholder_replacer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::StringPlaceholderReplacer do +RSpec.describe Gitlab::StringPlaceholderReplacer do describe '.render_url' do it 'returns the nil if the string is blank' do expect(described_class.replace_string_placeholders(nil, /whatever/)).to be_blank diff --git a/spec/lib/gitlab/string_range_marker_spec.rb b/spec/lib/gitlab/string_range_marker_spec.rb index ef9be7cd992..52fab6e3109 100644 --- a/spec/lib/gitlab/string_range_marker_spec.rb +++ b/spec/lib/gitlab/string_range_marker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::StringRangeMarker do +RSpec.describe Gitlab::StringRangeMarker do describe '#mark' do def mark_diff(rich = nil) raw = 'abc <def>' diff --git a/spec/lib/gitlab/string_regex_marker_spec.rb b/spec/lib/gitlab/string_regex_marker_spec.rb index 2ab1ccc447b..2dadd222820 100644 --- a/spec/lib/gitlab/string_regex_marker_spec.rb +++ b/spec/lib/gitlab/string_regex_marker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::StringRegexMarker do +RSpec.describe Gitlab::StringRegexMarker do describe '#mark' do context 'with a single occurrence' do let(:raw) { %{"name": "AFNetworking"} } diff --git a/spec/lib/gitlab/submodule_links_spec.rb b/spec/lib/gitlab/submodule_links_spec.rb index 1f2848a29e9..c69326e12be 100644 --- a/spec/lib/gitlab/submodule_links_spec.rb +++ b/spec/lib/gitlab/submodule_links_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::SubmoduleLinks do +RSpec.describe Gitlab::SubmoduleLinks do let(:submodule_item) { double(id: 'hash', path: 'gitlab-foss') } let(:repo) { double } let(:links) { described_class.new(repo) } diff --git a/spec/lib/gitlab/suggestions/commit_message_spec.rb b/spec/lib/gitlab/suggestions/commit_message_spec.rb index 0774fc80528..1411f64f8b7 100644 --- a/spec/lib/gitlab/suggestions/commit_message_spec.rb +++ b/spec/lib/gitlab/suggestions/commit_message_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Suggestions::CommitMessage do +RSpec.describe Gitlab::Suggestions::CommitMessage do def create_suggestion(file_path, new_line, to_content) position = Gitlab::Diff::Position.new(old_path: file_path, new_path: file_path, diff --git a/spec/lib/gitlab/suggestions/file_suggestion_spec.rb b/spec/lib/gitlab/suggestions/file_suggestion_spec.rb index 6fbbad017c5..1d25bf6edbd 100644 --- a/spec/lib/gitlab/suggestions/file_suggestion_spec.rb +++ b/spec/lib/gitlab/suggestions/file_suggestion_spec.rb @@ -2,8 +2,8 @@ require 'spec_helper' -describe Gitlab::Suggestions::FileSuggestion do - def create_suggestion(new_line, to_content) +RSpec.describe Gitlab::Suggestions::FileSuggestion do + def create_suggestion(new_line, to_content, lines_above = 0, lines_below = 0) position = Gitlab::Diff::Position.new(old_path: file_path, new_path: file_path, old_line: nil, @@ -18,6 +18,8 @@ describe Gitlab::Suggestions::FileSuggestion do create(:suggestion, :content_from_repo, note: diff_note, + lines_above: lines_above, + lines_below: lines_below, to_content: to_content) end @@ -39,27 +41,9 @@ describe Gitlab::Suggestions::FileSuggestion do create_suggestion(15, " *** SUGGESTION 2 ***\n") end - let(:file_suggestion) { described_class.new } + let(:suggestions) { [suggestion1, suggestion2] } - describe '#add_suggestion' do - it 'succeeds when adding a suggestion for the same file as the original' do - file_suggestion.add_suggestion(suggestion1) - - expect { file_suggestion.add_suggestion(suggestion2) }.not_to raise_error - end - - it 'raises an error when adding a suggestion for a different file' do - allow(suggestion2) - .to(receive_message_chain(:diff_file, :file_path) - .and_return('path/to/different/file')) - - file_suggestion.add_suggestion(suggestion1) - - expect { file_suggestion.add_suggestion(suggestion2) }.to( - raise_error(described_class::SuggestionForDifferentFileError) - ) - end - end + let(:file_suggestion) { described_class.new(file_path, suggestions) } describe '#line_conflict' do def stub_suggestions(line_index_spans) @@ -175,67 +159,296 @@ describe Gitlab::Suggestions::FileSuggestion do end describe '#new_content' do - it 'returns a blob with the suggestions applied to it' do - file_suggestion.add_suggestion(suggestion1) - file_suggestion.add_suggestion(suggestion2) + context 'with two suggestions' do + let(:suggestions) { [suggestion1, suggestion2] } - expected_content = <<-CONTENT.strip_heredoc - require 'fileutils' - require 'open3' + it 'returns a blob with the suggestions applied to it' do + expected_content = <<-CONTENT.strip_heredoc + require 'fileutils' + require 'open3' - module Popen - extend self + module Popen + extend self - def popen(cmd, path=nil) - unless cmd.is_a?(Array) - *** SUGGESTION 1 *** + def popen(cmd, path=nil) + unless cmd.is_a?(Array) + *** SUGGESTION 1 *** + end + + path ||= Dir.pwd + + vars = { + *** SUGGESTION 2 *** + } + + options = { + chdir: path + } + + unless File.directory?(path) + FileUtils.mkdir_p(path) + end + + @cmd_output = "" + @cmd_status = 0 + + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| + @cmd_output << stdout.read + @cmd_output << stderr.read + @cmd_status = wait_thr.value.exitstatus + end + + return @cmd_output, @cmd_status end + end + CONTENT - path ||= Dir.pwd + expect(file_suggestion.new_content).to eq(expected_content) + end + end - vars = { - *** SUGGESTION 2 *** - } + context 'when no suggestions have been added' do + let(:suggestions) { [] } - options = { - chdir: path - } + it 'returns an empty string' do + expect(file_suggestion.new_content).to eq('') + end + end + + context 'with multiline suggestions' do + let(:suggestions) { [multi_suggestion1, multi_suggestion2, multi_suggestion3] } + + context 'when the previous suggestion increases the line count' do + let!(:multi_suggestion1) do + create_suggestion(9, " *** SUGGESTION 1 ***\n *** SECOND LINE ***\n *** THIRD LINE ***\n") + end - unless File.directory?(path) - FileUtils.mkdir_p(path) + let!(:multi_suggestion2) do + create_suggestion(15, " *** SUGGESTION 2 ***\n *** SECOND LINE ***\n") + end + + let!(:multi_suggestion3) do + create_suggestion(19, " chdir: *** SUGGESTION 3 ***\n") + end + + it 'returns a blob with the suggestions applied to it' do + expected_content = <<-CONTENT.strip_heredoc + require 'fileutils' + require 'open3' + + module Popen + extend self + + def popen(cmd, path=nil) + unless cmd.is_a?(Array) + *** SUGGESTION 1 *** + *** SECOND LINE *** + *** THIRD LINE *** + end + + path ||= Dir.pwd + + vars = { + *** SUGGESTION 2 *** + *** SECOND LINE *** + } + + options = { + chdir: *** SUGGESTION 3 *** + } + + unless File.directory?(path) + FileUtils.mkdir_p(path) + end + + @cmd_output = "" + @cmd_status = 0 + + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| + @cmd_output << stdout.read + @cmd_output << stderr.read + @cmd_status = wait_thr.value.exitstatus + end + + return @cmd_output, @cmd_status end + end + CONTENT + + expect(file_suggestion.new_content).to eq(expected_content) + end + end - @cmd_output = "" - @cmd_status = 0 + context 'when the previous suggestion decreases and increases the line count' do + let!(:multi_suggestion1) do + create_suggestion(9, " *** SUGGESTION 1 ***\n", 1, 1) + end + + let!(:multi_suggestion2) do + create_suggestion(15, " *** SUGGESTION 2 ***\n *** SECOND LINE ***\n") + end + + let!(:multi_suggestion3) do + create_suggestion(19, " chdir: *** SUGGESTION 3 ***\n") + end + + it 'returns a blob with the suggestions applied to it' do + expected_content = <<-CONTENT.strip_heredoc + require 'fileutils' + require 'open3' + + module Popen + extend self + + def popen(cmd, path=nil) + *** SUGGESTION 1 *** - Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| - @cmd_output << stdout.read - @cmd_output << stderr.read - @cmd_status = wait_thr.value.exitstatus + path ||= Dir.pwd + + vars = { + *** SUGGESTION 2 *** + *** SECOND LINE *** + } + + options = { + chdir: *** SUGGESTION 3 *** + } + + unless File.directory?(path) + FileUtils.mkdir_p(path) + end + + @cmd_output = "" + @cmd_status = 0 + + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| + @cmd_output << stdout.read + @cmd_output << stderr.read + @cmd_status = wait_thr.value.exitstatus + end + + return @cmd_output, @cmd_status end + end + CONTENT + + expect(file_suggestion.new_content).to eq(expected_content) + end + end + + context 'when the previous suggestion replaces with the same number of lines' do + let!(:multi_suggestion1) do + create_suggestion(9, " *** SUGGESTION 1 ***\n *** SECOND LINE ***\n *** THIRD LINE ***\n", 1, 1) + end + + let!(:multi_suggestion2) do + create_suggestion(15, " *** SUGGESTION 2 ***\n") + end + + let!(:multi_suggestion3) do + create_suggestion(19, " chdir: *** SUGGESTION 3 ***\n") + end + + it 'returns a blob with the suggestions applied to it' do + expected_content = <<-CONTENT.strip_heredoc + require 'fileutils' + require 'open3' + + module Popen + extend self + + def popen(cmd, path=nil) + *** SUGGESTION 1 *** + *** SECOND LINE *** + *** THIRD LINE *** + + path ||= Dir.pwd + + vars = { + *** SUGGESTION 2 *** + } + + options = { + chdir: *** SUGGESTION 3 *** + } + + unless File.directory?(path) + FileUtils.mkdir_p(path) + end + + @cmd_output = "" + @cmd_status = 0 + + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| + @cmd_output << stdout.read + @cmd_output << stderr.read + @cmd_status = wait_thr.value.exitstatus + end - return @cmd_output, @cmd_status + return @cmd_output, @cmd_status + end end + CONTENT + + expect(file_suggestion.new_content).to eq(expected_content) end - CONTENT + end - expect(file_suggestion.new_content).to eq(expected_content) - end + context 'when the previous suggestion replaces multiple lines and the suggestions were applied out of order' do + let(:suggestions) { [multi_suggestion1, multi_suggestion3, multi_suggestion2] } - it 'returns an empty string when no suggestions have been added' do - expect(file_suggestion.new_content).to eq('') - end - end + let!(:multi_suggestion1) do + create_suggestion(9, " *** SUGGESTION 1 ***\n *** SECOND LINE ***\n *** THIRD LINE ***\n", 1, 1) + end - describe '#file_path' do - it 'returns the path of the file associated with the suggestions' do - file_suggestion.add_suggestion(suggestion1) + let!(:multi_suggestion3) do + create_suggestion(19, " *** SUGGESTION 3 ***\n", 1, 1) + end - expect(file_suggestion.file_path).to eq(file_path) - end + let!(:multi_suggestion2) do + create_suggestion(15, " *** SUGGESTION 2 ***\n", 1, 1) + end + + it 'returns a blob with the suggestions applied to it' do + expected_content = <<-CONTENT.strip_heredoc + require 'fileutils' + require 'open3' + + module Popen + extend self + + def popen(cmd, path=nil) + *** SUGGESTION 1 *** + *** SECOND LINE *** + *** THIRD LINE *** + + path ||= Dir.pwd + + *** SUGGESTION 2 *** + + *** SUGGESTION 3 *** + + unless File.directory?(path) + FileUtils.mkdir_p(path) + end + + @cmd_output = "" + @cmd_status = 0 - it 'returns nil if no suggestions have been added' do - expect(file_suggestion.file_path).to be(nil) + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| + @cmd_output << stdout.read + @cmd_output << stderr.read + @cmd_status = wait_thr.value.exitstatus + end + + return @cmd_output, @cmd_status + end + end + CONTENT + + expect(file_suggestion.new_content).to eq(expected_content) + end + end end end end diff --git a/spec/lib/gitlab/suggestions/suggestion_set_spec.rb b/spec/lib/gitlab/suggestions/suggestion_set_spec.rb index 8c61e6c42a6..54d79a9d4ba 100644 --- a/spec/lib/gitlab/suggestions/suggestion_set_spec.rb +++ b/spec/lib/gitlab/suggestions/suggestion_set_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Suggestions::SuggestionSet do +RSpec.describe Gitlab::Suggestions::SuggestionSet do def create_suggestion(file_path, new_line, to_content) position = Gitlab::Diff::Position.new(old_path: file_path, new_path: file_path, @@ -87,11 +87,10 @@ describe Gitlab::Suggestions::SuggestionSet do it 'returns an array of hashes with proper key/value pairs' do first_action = suggestion_set.actions.first - file_path, file_suggestion = suggestion_set - .send(:suggestions_per_file).first + file_suggestion = suggestion_set.send(:suggestions_per_file).first expect(first_action[:action]).to be('update') - expect(first_action[:file_path]).to eq(file_path) + expect(first_action[:file_path]).to eq(file_suggestion.file_path) expect(first_action[:content]).to eq(file_suggestion.new_content) end end diff --git a/spec/lib/gitlab/tab_width_spec.rb b/spec/lib/gitlab/tab_width_spec.rb index 3b5014d27e4..f0efb6ec4a7 100644 --- a/spec/lib/gitlab/tab_width_spec.rb +++ b/spec/lib/gitlab/tab_width_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::TabWidth, lib: true do +RSpec.describe Gitlab::TabWidth, lib: true do describe '.css_class_for_user' do it 'returns default CSS class when user is nil' do css_class = described_class.css_class_for_user(nil) diff --git a/spec/lib/gitlab/tcp_checker_spec.rb b/spec/lib/gitlab/tcp_checker_spec.rb index 9474e79cc5d..12149576de0 100644 --- a/spec/lib/gitlab/tcp_checker_spec.rb +++ b/spec/lib/gitlab/tcp_checker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::TcpChecker, :permit_dns do +RSpec.describe Gitlab::TcpChecker, :permit_dns do before do @server = TCPServer.new('localhost', 0) _, @port, _, @ip = @server.addr diff --git a/spec/lib/gitlab/template/finders/global_template_finder_spec.rb b/spec/lib/gitlab/template/finders/global_template_finder_spec.rb index 580da497944..e776284b3e8 100644 --- a/spec/lib/gitlab/template/finders/global_template_finder_spec.rb +++ b/spec/lib/gitlab/template/finders/global_template_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Template::Finders::GlobalTemplateFinder do +RSpec.describe Gitlab::Template::Finders::GlobalTemplateFinder do let(:base_dir) { Dir.mktmpdir } def create_template!(name_with_category) diff --git a/spec/lib/gitlab/template/finders/repo_template_finders_spec.rb b/spec/lib/gitlab/template/finders/repo_template_finders_spec.rb index cd5cde76b73..05f351be702 100644 --- a/spec/lib/gitlab/template/finders/repo_template_finders_spec.rb +++ b/spec/lib/gitlab/template/finders/repo_template_finders_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Template::Finders::RepoTemplateFinder do +RSpec.describe Gitlab::Template::Finders::RepoTemplateFinder do let_it_be(:project) { create(:project, :repository) } let(:categories) { { 'HTML' => 'html' } } diff --git a/spec/lib/gitlab/template/gitignore_template_spec.rb b/spec/lib/gitlab/template/gitignore_template_spec.rb index e8f632889ad..365b579d08e 100644 --- a/spec/lib/gitlab/template/gitignore_template_spec.rb +++ b/spec/lib/gitlab/template/gitignore_template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Template::GitignoreTemplate do +RSpec.describe Gitlab::Template::GitignoreTemplate do subject { described_class } describe '.all' do diff --git a/spec/lib/gitlab/template/gitlab_ci_yml_template_spec.rb b/spec/lib/gitlab/template/gitlab_ci_yml_template_spec.rb index 52e100768a7..3004de6fe08 100644 --- a/spec/lib/gitlab/template/gitlab_ci_yml_template_spec.rb +++ b/spec/lib/gitlab/template/gitlab_ci_yml_template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Template::GitlabCiYmlTemplate do +RSpec.describe Gitlab::Template::GitlabCiYmlTemplate do subject { described_class } describe '.all' do diff --git a/spec/lib/gitlab/template/issue_template_spec.rb b/spec/lib/gitlab/template/issue_template_spec.rb index 54e46d3a9ec..4acbdcc4ba6 100644 --- a/spec/lib/gitlab/template/issue_template_spec.rb +++ b/spec/lib/gitlab/template/issue_template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Template::IssueTemplate do +RSpec.describe Gitlab::Template::IssueTemplate do let(:project) { create(:project, :repository, create_templates: :issue) } describe '.all' do diff --git a/spec/lib/gitlab/template/merge_request_template_spec.rb b/spec/lib/gitlab/template/merge_request_template_spec.rb index bbc184d4dfc..abac0a10e18 100644 --- a/spec/lib/gitlab/template/merge_request_template_spec.rb +++ b/spec/lib/gitlab/template/merge_request_template_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Template::MergeRequestTemplate do +RSpec.describe Gitlab::Template::MergeRequestTemplate do let(:project) { create(:project, :repository, create_templates: :merge_request) } describe '.all' do diff --git a/spec/lib/gitlab/themes_spec.rb b/spec/lib/gitlab/themes_spec.rb index e0278eb9c7f..68ff28becfa 100644 --- a/spec/lib/gitlab/themes_spec.rb +++ b/spec/lib/gitlab/themes_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Themes, lib: true do +RSpec.describe Gitlab::Themes, lib: true do describe '.body_classes' do it 'returns a space-separated list of class names' do css = described_class.body_classes diff --git a/spec/lib/gitlab/throttle_spec.rb b/spec/lib/gitlab/throttle_spec.rb index e3679a1a721..ca2abe94ad2 100644 --- a/spec/lib/gitlab/throttle_spec.rb +++ b/spec/lib/gitlab/throttle_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Throttle do +RSpec.describe Gitlab::Throttle do describe '.protected_paths_enabled?' do subject { described_class.protected_paths_enabled? } diff --git a/spec/lib/gitlab/time_tracking_formatter_spec.rb b/spec/lib/gitlab/time_tracking_formatter_spec.rb index cfc804c13a7..8bbd1263057 100644 --- a/spec/lib/gitlab/time_tracking_formatter_spec.rb +++ b/spec/lib/gitlab/time_tracking_formatter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::TimeTrackingFormatter do +RSpec.describe Gitlab::TimeTrackingFormatter do describe '#parse' do subject { described_class.parse(duration_string) } diff --git a/spec/lib/gitlab/tracking/incident_management_spec.rb b/spec/lib/gitlab/tracking/incident_management_spec.rb index 6f7e04b7c16..e8131b4eeee 100644 --- a/spec/lib/gitlab/tracking/incident_management_spec.rb +++ b/spec/lib/gitlab/tracking/incident_management_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Tracking::IncidentManagement do +RSpec.describe Gitlab::Tracking::IncidentManagement do describe '.track_from_params' do shared_examples 'a tracked event' do |label, value = nil| it 'creates the tracking event with the correct details' do diff --git a/spec/lib/gitlab/tracking_spec.rb b/spec/lib/gitlab/tracking_spec.rb index 82828c2dcce..65b6d9c8899 100644 --- a/spec/lib/gitlab/tracking_spec.rb +++ b/spec/lib/gitlab/tracking_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Tracking do +RSpec.describe Gitlab::Tracking do let(:timestamp) { Time.utc(2017, 3, 22) } before do diff --git a/spec/lib/gitlab/tree_summary_spec.rb b/spec/lib/gitlab/tree_summary_spec.rb index 593b8655e80..4bd08fab60a 100644 --- a/spec/lib/gitlab/tree_summary_spec.rb +++ b/spec/lib/gitlab/tree_summary_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::TreeSummary do +RSpec.describe Gitlab::TreeSummary do using RSpec::Parameterized::TableSyntax let(:project) { create(:project, :empty_repo) } @@ -47,15 +47,17 @@ describe Gitlab::TreeSummary do end describe '#summarize (entries)' do - let(:limit) { 2 } + let(:limit) { 4 } custom_files = { 'a.txt' => '', 'b.txt' => '', - 'directory/c.txt' => '' + 'directory/c.txt' => '', + ':dir/test.txt' => '', + ':file' => '' } - let(:project) { create(:project, :custom_repo, files: custom_files) } + let!(:project) { create(:project, :custom_repo, files: custom_files) } let(:commit) { repo.head_commit } subject(:entries) { summary.summarize.first } @@ -63,13 +65,16 @@ describe Gitlab::TreeSummary do it 'summarizes the entries within the window' do is_expected.to contain_exactly( a_hash_including(type: :tree, file_name: 'directory'), - a_hash_including(type: :blob, file_name: 'a.txt') + a_hash_including(type: :blob, file_name: 'a.txt'), + a_hash_including(type: :blob, file_name: ':file'), + a_hash_including(type: :tree, file_name: ':dir') # b.txt is excluded by the limit ) end it 'references the commit and commit path in entries' do - entry = entries.first + # There are 2 trees and the summary is not ordered + entry = entries.find { |entry| entry[:commit].id == commit.id } expected_commit_path = Gitlab::Routing.url_helpers.project_commit_path(project, commit) expect(entry[:commit]).to be_a(::Commit) @@ -85,6 +90,14 @@ describe Gitlab::TreeSummary do end end + context 'in a subdirectory with a pathspec character' do + let(:path) { ':dir' } + + it 'summarizes the entries in the subdirectory' do + is_expected.to contain_exactly(a_hash_including(type: :blob, file_name: 'test.txt')) + end + end + context 'in a non-existent subdirectory' do let(:path) { 'tmp' } @@ -92,7 +105,7 @@ describe Gitlab::TreeSummary do end context 'custom offset and limit' do - let(:offset) { 2 } + let(:offset) { 4 } it 'returns entries from the offset' do is_expected.to contain_exactly(a_hash_including(type: :blob, file_name: 'b.txt')) diff --git a/spec/lib/gitlab/untrusted_regexp/ruby_syntax_spec.rb b/spec/lib/gitlab/untrusted_regexp/ruby_syntax_spec.rb index cdd681a9345..42fc84cf076 100644 --- a/spec/lib/gitlab/untrusted_regexp/ruby_syntax_spec.rb +++ b/spec/lib/gitlab/untrusted_regexp/ruby_syntax_spec.rb @@ -4,7 +4,7 @@ require 'fast_spec_helper' require 'support/shared_examples/lib/gitlab/malicious_regexp_shared_examples' require 'support/helpers/stub_feature_flags' -describe Gitlab::UntrustedRegexp::RubySyntax do +RSpec.describe Gitlab::UntrustedRegexp::RubySyntax do describe '.matches_syntax?' do it 'returns true if regexp is valid' do expect(described_class.matches_syntax?('/some .* thing/')) diff --git a/spec/lib/gitlab/untrusted_regexp_spec.rb b/spec/lib/gitlab/untrusted_regexp_spec.rb index 60f14d0277b..aac3d5e27f5 100644 --- a/spec/lib/gitlab/untrusted_regexp_spec.rb +++ b/spec/lib/gitlab/untrusted_regexp_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'support/shared_examples/lib/gitlab/malicious_regexp_shared_examples' -describe Gitlab::UntrustedRegexp do +RSpec.describe Gitlab::UntrustedRegexp do describe '#initialize' do subject { described_class.new(pattern) } diff --git a/spec/lib/gitlab/updated_notes_paginator_spec.rb b/spec/lib/gitlab/updated_notes_paginator_spec.rb new file mode 100644 index 00000000000..eedc11777d4 --- /dev/null +++ b/spec/lib/gitlab/updated_notes_paginator_spec.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::UpdatedNotesPaginator do + let(:issue) { create(:issue) } + + let(:project) { issue.project } + let(:finder) { NotesFinder.new(user, target: issue, last_fetched_at: last_fetched_at) } + let(:user) { issue.author } + + let!(:page_1) { create_list(:note, 2, noteable: issue, project: project, updated_at: 2.days.ago) } + let!(:page_2) { [create(:note, noteable: issue, project: project, updated_at: 1.day.ago)] } + + let(:page_1_boundary) { page_1.last.updated_at + NotesFinder::FETCH_OVERLAP } + + around do |example| + Timecop.freeze do + example.run + end + end + + before do + stub_const("Gitlab::UpdatedNotesPaginator::LIMIT", 2) + end + + subject(:paginator) { described_class.new(finder.execute, last_fetched_at: last_fetched_at) } + + describe 'last_fetched_at: start of time' do + let(:last_fetched_at) { Time.at(0) } + + it 'calculates the first page of notes', :aggregate_failures do + expect(paginator.notes).to match_array(page_1) + expect(paginator.metadata).to match( + more: true, + last_fetched_at: microseconds(page_1_boundary) + ) + end + end + + describe 'last_fetched_at: start of final page' do + let(:last_fetched_at) { page_1_boundary } + + it 'calculates a final page', :aggregate_failures do + expect(paginator.notes).to match_array(page_2) + expect(paginator.metadata).to match( + more: false, + last_fetched_at: microseconds(Time.zone.now) + ) + end + end + + # Convert a time to an integer number of microseconds + def microseconds(time) + (time.to_i * 1_000_000) + time.usec + end +end diff --git a/spec/lib/gitlab/uploads_transfer_spec.rb b/spec/lib/gitlab/uploads_transfer_spec.rb index 16560fc8f12..80bbf68e98a 100644 --- a/spec/lib/gitlab/uploads_transfer_spec.rb +++ b/spec/lib/gitlab/uploads_transfer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UploadsTransfer do +RSpec.describe Gitlab::UploadsTransfer do it 'leaves avatar uploads where they are' do project_with_avatar = create(:project, :with_avatar) diff --git a/spec/lib/gitlab/url_blocker_spec.rb b/spec/lib/gitlab/url_blocker_spec.rb index 08678de87c9..7edfde09864 100644 --- a/spec/lib/gitlab/url_blocker_spec.rb +++ b/spec/lib/gitlab/url_blocker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UrlBlocker, :stub_invalid_dns_only do +RSpec.describe Gitlab::UrlBlocker, :stub_invalid_dns_only do include StubRequests describe '#validate!' do diff --git a/spec/lib/gitlab/url_blockers/domain_whitelist_entry_spec.rb b/spec/lib/gitlab/url_blockers/domain_whitelist_entry_spec.rb index 34ea6c328e6..58bae109146 100644 --- a/spec/lib/gitlab/url_blockers/domain_whitelist_entry_spec.rb +++ b/spec/lib/gitlab/url_blockers/domain_whitelist_entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UrlBlockers::DomainWhitelistEntry do +RSpec.describe Gitlab::UrlBlockers::DomainWhitelistEntry do let(:domain) { 'www.example.com' } describe '#initialize' do diff --git a/spec/lib/gitlab/url_blockers/ip_whitelist_entry_spec.rb b/spec/lib/gitlab/url_blockers/ip_whitelist_entry_spec.rb index 042d135d265..52f9b31165a 100644 --- a/spec/lib/gitlab/url_blockers/ip_whitelist_entry_spec.rb +++ b/spec/lib/gitlab/url_blockers/ip_whitelist_entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UrlBlockers::IpWhitelistEntry do +RSpec.describe Gitlab::UrlBlockers::IpWhitelistEntry do let(:ipv4) { IPAddr.new('192.168.1.1') } describe '#initialize' do diff --git a/spec/lib/gitlab/url_blockers/url_whitelist_spec.rb b/spec/lib/gitlab/url_blockers/url_whitelist_spec.rb index e43cd819838..7a65516be3c 100644 --- a/spec/lib/gitlab/url_blockers/url_whitelist_spec.rb +++ b/spec/lib/gitlab/url_blockers/url_whitelist_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UrlBlockers::UrlWhitelist do +RSpec.describe Gitlab::UrlBlockers::UrlWhitelist do include StubRequests let(:whitelist) { [] } diff --git a/spec/lib/gitlab/url_builder_spec.rb b/spec/lib/gitlab/url_builder_spec.rb index e91d17bfbe8..a16ff252bc1 100644 --- a/spec/lib/gitlab/url_builder_spec.rb +++ b/spec/lib/gitlab/url_builder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UrlBuilder do +RSpec.describe Gitlab::UrlBuilder do subject { described_class } describe '#build' do @@ -87,12 +87,41 @@ describe Gitlab::UrlBuilder do end context 'when passing a Snippet' do - let(:snippet) { build_stubbed(:personal_snippet) } + let_it_be(:personal_snippet) { create(:personal_snippet, :repository) } + let_it_be(:project_snippet) { create(:project_snippet, :repository) } + let(:blob) { snippet.blobs.first } + let(:ref) { blob.repository.root_ref } - it 'returns a raw snippet URL if requested' do - url = subject.build(snippet, raw: true) + context 'for a PersonalSnippet' do + let(:snippet) { personal_snippet } - expect(url).to eq "#{Gitlab.config.gitlab.url}/snippets/#{snippet.id}/raw" + it 'returns a raw snippet URL if requested' do + url = subject.build(snippet, raw: true) + + expect(url).to eq "#{Gitlab.config.gitlab.url}/snippets/#{snippet.id}/raw" + end + + it 'returns a raw snippet blob URL if requested' do + url = subject.build(snippet, file: blob.path, ref: ref) + + expect(url).to eq "#{Gitlab.config.gitlab.url}/-/snippets/#{snippet.id}/raw/#{ref}/#{blob.path}" + end + end + + context 'for a ProjectSnippet' do + let(:snippet) { project_snippet } + + it 'returns a raw snippet URL if requested' do + url = subject.build(snippet, raw: true) + + expect(url).to eq "#{Gitlab.config.gitlab.url}/#{snippet.project.full_path}/snippets/#{snippet.id}/raw" + end + + it 'returns a raw snippet blob URL if requested' do + url = subject.build(snippet, file: blob.path, ref: ref) + + expect(url).to eq "#{Gitlab.config.gitlab.url}/#{snippet.project.full_path}/-/snippets/#{snippet.id}/raw/#{ref}/#{blob.path}" + end end end diff --git a/spec/lib/gitlab/url_sanitizer_spec.rb b/spec/lib/gitlab/url_sanitizer_spec.rb index caca22eb98b..aba4ca109a9 100644 --- a/spec/lib/gitlab/url_sanitizer_spec.rb +++ b/spec/lib/gitlab/url_sanitizer_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UrlSanitizer do +RSpec.describe Gitlab::UrlSanitizer do using RSpec::Parameterized::TableSyntax describe '.sanitize' do diff --git a/spec/lib/gitlab/usage_data/topology_spec.rb b/spec/lib/gitlab/usage_data/topology_spec.rb new file mode 100644 index 00000000000..2a7adea261d --- /dev/null +++ b/spec/lib/gitlab/usage_data/topology_spec.rb @@ -0,0 +1,562 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::UsageData::Topology do + include UsageDataHelpers + + describe '#topology_usage_data' do + subject { described_class.new.topology_usage_data } + + before do + # this pins down time shifts when benchmarking durations + allow(Process).to receive(:clock_gettime).and_return(0) + end + + context 'when embedded Prometheus server is enabled' do + before do + expect(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(true) + expect(Gitlab::Prometheus::Internal).to receive(:uri).and_return('http://prom:9090') + end + + context 'tracking node metrics' do + it 'contains node level metrics for each instance' do + expect_prometheus_api_to( + receive_app_request_volume_query, + receive_node_memory_query, + receive_node_cpu_count_query, + receive_node_uname_info_query, + receive_node_service_memory_rss_query, + receive_node_service_memory_uss_query, + receive_node_service_memory_pss_query, + receive_node_service_process_count_query, + receive_node_service_app_server_workers_query + ) + + expect(subject[:topology]).to eq({ + duration_s: 0, + application_requests_per_hour: 36, + failures: [], + nodes: [ + { + node_memory_total_bytes: 512, + node_cpus: 8, + node_uname_info: { + machine: 'x86_64', + sysname: 'Linux', + release: '4.19.76-linuxkit' + }, + node_services: [ + { + name: 'web', + process_count: 10, + process_memory_rss: 300, + process_memory_uss: 301, + process_memory_pss: 302, + server: 'puma' + }, + { + name: 'sidekiq', + process_count: 5, + process_memory_rss: 303 + } + ] + }, + { + node_memory_total_bytes: 1024, + node_cpus: 16, + node_uname_info: { + machine: 'x86_64', + sysname: 'Linux', + release: '4.15.0-101-generic' + }, + node_services: [ + { + name: 'sidekiq', + process_count: 15, + process_memory_rss: 400, + process_memory_pss: 401 + }, + { + name: 'redis', + process_count: 1, + process_memory_rss: 402 + }, + { + name: 'registry', + process_count: 1 + }, + { + name: 'web', + server: 'unicorn' + } + ] + } + ] + }) + end + end + + context 'and some node memory metrics are missing' do + it 'removes the respective entries and includes the failures' do + expect_prometheus_api_to( + receive_app_request_volume_query(result: []), + receive_node_memory_query(result: []), + receive_node_cpu_count_query, + receive_node_uname_info_query, + receive_node_service_memory_rss_query(result: []), + receive_node_service_memory_uss_query(result: []), + receive_node_service_memory_pss_query, + receive_node_service_process_count_query, + receive_node_service_app_server_workers_query(result: []) + ) + + expect(subject[:topology]).to eq({ + duration_s: 0, + failures: [ + { 'app_requests' => 'empty_result' }, + { 'node_memory' => 'empty_result' }, + { 'service_rss' => 'empty_result' }, + { 'service_uss' => 'empty_result' }, + { 'service_workers' => 'empty_result' } + ], + nodes: [ + { + node_cpus: 16, + node_uname_info: { + machine: 'x86_64', + release: '4.15.0-101-generic', + sysname: 'Linux' + }, + node_services: [ + { + name: 'sidekiq', + process_count: 15, + process_memory_pss: 401 + }, + { + name: 'redis', + process_count: 1 + }, + { + name: 'registry', + process_count: 1 + } + ] + }, + { + node_cpus: 8, + node_uname_info: { + machine: 'x86_64', + release: '4.19.76-linuxkit', + sysname: 'Linux' + }, + node_services: [ + { + name: 'web', + process_count: 10, + process_memory_pss: 302 + }, + { + name: 'sidekiq', + process_count: 5 + } + ] + } + ] + }) + end + end + + context 'and services run on the same node but report different instance values' do + let(:node_memory_response) do + [ + { + 'metric' => { 'instance' => 'localhost:9100' }, + 'value' => [1000, '512'] + } + ] + end + let(:node_uname_info_response) do + [ + { + "metric" => { + "__name__" => "node_uname_info", + "domainname" => "(none)", + "instance" => "127.0.0.1:9100", + "job" => "node_exporter", + "machine" => "x86_64", + "nodename" => "127.0.0.1", + "release" => "4.19.76-linuxkit", + "sysname" => "Linux" + }, + "value" => [1592463033.359, "1"] + } + ] + end + # The services in this response should all be mapped to localhost i.e. the same node + let(:service_memory_response) do + [ + { + 'metric' => { 'instance' => 'localhost:8080', 'job' => 'gitlab-rails' }, + 'value' => [1000, '10'] + }, + { + 'metric' => { 'instance' => '127.0.0.1:8090', 'job' => 'gitlab-sidekiq' }, + 'value' => [1000, '11'] + }, + { + 'metric' => { 'instance' => '0.0.0.0:9090', 'job' => 'prometheus' }, + 'value' => [1000, '12'] + }, + { + 'metric' => { 'instance' => '[::1]:1234', 'job' => 'redis' }, + 'value' => [1000, '13'] + }, + { + 'metric' => { 'instance' => '[::]:1234', 'job' => 'postgres' }, + 'value' => [1000, '14'] + } + ] + end + + it 'normalizes equivalent instance values and maps them to the same node' do + expect_prometheus_api_to( + receive_app_request_volume_query(result: []), + receive_node_memory_query(result: node_memory_response), + receive_node_cpu_count_query(result: []), + receive_node_uname_info_query(result: node_uname_info_response), + receive_node_service_memory_rss_query(result: service_memory_response), + receive_node_service_memory_uss_query(result: []), + receive_node_service_memory_pss_query(result: []), + receive_node_service_process_count_query(result: []), + receive_node_service_app_server_workers_query(result: []) + ) + + expect(subject[:topology]).to eq({ + duration_s: 0, + failures: [ + { 'app_requests' => 'empty_result' }, + { 'node_cpus' => 'empty_result' }, + { 'service_uss' => 'empty_result' }, + { 'service_pss' => 'empty_result' }, + { 'service_process_count' => 'empty_result' }, + { 'service_workers' => 'empty_result' } + ], + nodes: [ + { + node_memory_total_bytes: 512, + node_uname_info: { + machine: 'x86_64', + sysname: 'Linux', + release: '4.19.76-linuxkit' + }, + node_services: [ + { + name: 'web', + process_memory_rss: 10 + }, + { + name: 'sidekiq', + process_memory_rss: 11 + }, + { + name: 'prometheus', + process_memory_rss: 12 + }, + { + name: 'redis', + process_memory_rss: 13 + }, + { + name: 'postgres', + process_memory_rss: 14 + } + ] + } + ] + }) + end + end + + context 'and node metrics are missing but service metrics exist' do + it 'still reports service metrics' do + expect_prometheus_api_to( + receive_app_request_volume_query(result: []), + receive_node_memory_query(result: []), + receive_node_cpu_count_query(result: []), + receive_node_uname_info_query(result: []), + receive_node_service_memory_rss_query, + receive_node_service_memory_uss_query(result: []), + receive_node_service_memory_pss_query(result: []), + receive_node_service_process_count_query(result: []), + receive_node_service_app_server_workers_query(result: []) + ) + + expect(subject[:topology]).to eq({ + duration_s: 0, + failures: [ + { 'app_requests' => 'empty_result' }, + { 'node_memory' => 'empty_result' }, + { 'node_cpus' => 'empty_result' }, + { 'node_uname_info' => 'empty_result' }, + { 'service_uss' => 'empty_result' }, + { 'service_pss' => 'empty_result' }, + { 'service_process_count' => 'empty_result' }, + { 'service_workers' => 'empty_result' } + ], + nodes: [ + { + node_services: [ + { + name: 'web', + process_memory_rss: 300 + }, + { + name: 'sidekiq', + process_memory_rss: 303 + } + ] + }, + { + node_services: [ + { + name: 'sidekiq', + process_memory_rss: 400 + }, + { + name: 'redis', + process_memory_rss: 402 + } + ] + } + ] + }) + end + end + + context 'and an error is raised when querying Prometheus' do + it 'returns empty result with failures' do + expect_prometheus_api_to receive(:query) + .at_least(:once) + .and_raise(Gitlab::PrometheusClient::ConnectionError) + + expect(subject[:topology]).to eq({ + duration_s: 0, + failures: [ + { 'app_requests' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'node_memory' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'node_cpus' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'node_uname_info' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'service_rss' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'service_uss' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'service_pss' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'service_process_count' => 'Gitlab::PrometheusClient::ConnectionError' }, + { 'service_workers' => 'Gitlab::PrometheusClient::ConnectionError' } + ], + nodes: [] + }) + end + end + end + + context 'when embedded Prometheus server is disabled' do + it 'returns empty result with no failures' do + expect(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(false) + + expect(subject[:topology]).to eq({ + duration_s: 0, + failures: [] + }) + end + end + + context 'when top-level function raises error' do + it 'returns empty result with generic failure' do + allow(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_raise(RuntimeError) + + expect(subject[:topology]).to eq({ + duration_s: 0, + failures: [ + { 'other' => 'RuntimeError' } + ] + }) + end + end + end + + def receive_app_request_volume_query(result: nil) + receive(:query) + .with(/gitlab_usage_ping:ops:rate/) + .and_return(result || [ + { + 'metric' => { 'component' => 'http_requests', 'service' => 'workhorse' }, + 'value' => [1000, '0.01'] + } + ]) + end + + def receive_node_memory_query(result: nil) + receive(:query) + .with(/node_memory_total_bytes/, an_instance_of(Hash)) + .and_return(result || [ + { + 'metric' => { 'instance' => 'instance1:8080' }, + 'value' => [1000, '512'] + }, + { + 'metric' => { 'instance' => 'instance2:8090' }, + 'value' => [1000, '1024'] + } + ]) + end + + def receive_node_cpu_count_query(result: nil) + receive(:query) + .with(/node_cpus/, an_instance_of(Hash)) + .and_return(result || [ + { + 'metric' => { 'instance' => 'instance2:8090' }, + 'value' => [1000, '16'] + }, + { + 'metric' => { 'instance' => 'instance1:8080' }, + 'value' => [1000, '8'] + } + ]) + end + + def receive_node_uname_info_query(result: nil) + receive(:query) + .with('node_uname_info') + .and_return(result || [ + { + "metric" => { + "__name__" => "node_uname_info", + "domainname" => "(none)", + "instance" => "instance1:9100", + "job" => "node_exporter", + "machine" => "x86_64", + "nodename" => "instance1", + "release" => "4.19.76-linuxkit", + "sysname" => "Linux" + }, + "value" => [1592463033.359, "1"] + }, + { + "metric" => { + "__name__" => "node_uname_info", + "domainname" => "(none)", + "instance" => "instance2:9100", + "job" => "node_exporter", + "machine" => "x86_64", + "nodename" => "instance2", + "release" => "4.15.0-101-generic", + "sysname" => "Linux" + }, + "value" => [1592463033.359, "1"] + } + ]) + end + + def receive_node_service_memory_rss_query(result: nil) + receive(:query) + .with(/process_resident_memory_bytes/, an_instance_of(Hash)) + .and_return(result || [ + { + 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails' }, + 'value' => [1000, '300'] + }, + { + 'metric' => { 'instance' => 'instance1:8090', 'job' => 'gitlab-sidekiq' }, + 'value' => [1000, '303'] + }, + # instance 2: runs a dedicated Sidekiq + Redis (which uses a different metric name) + { + 'metric' => { 'instance' => 'instance2:8090', 'job' => 'gitlab-sidekiq' }, + 'value' => [1000, '400'] + }, + { + 'metric' => { 'instance' => 'instance2:9121', 'job' => 'redis' }, + 'value' => [1000, '402'] + } + ]) + end + + def receive_node_service_memory_uss_query(result: nil) + receive(:query) + .with(/process_unique_memory_bytes/, an_instance_of(Hash)) + .and_return(result || [ + { + 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails' }, + 'value' => [1000, '301'] + } + ]) + end + + def receive_node_service_memory_pss_query(result: nil) + receive(:query) + .with(/process_proportional_memory_bytes/, an_instance_of(Hash)) + .and_return(result || [ + { + 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails' }, + 'value' => [1000, '302'] + }, + { + 'metric' => { 'instance' => 'instance2:8090', 'job' => 'gitlab-sidekiq' }, + 'value' => [1000, '401'] + } + ]) + end + + def receive_node_service_process_count_query(result: nil) + receive(:query) + .with(/service_process:count/, an_instance_of(Hash)) + .and_return(result || [ + # instance 1 + { + 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails' }, + 'value' => [1000, '10'] + }, + { + 'metric' => { 'instance' => 'instance1:8090', 'job' => 'gitlab-sidekiq' }, + 'value' => [1000, '5'] + }, + # instance 2 + { + 'metric' => { 'instance' => 'instance2:8090', 'job' => 'gitlab-sidekiq' }, + 'value' => [1000, '15'] + }, + { + 'metric' => { 'instance' => 'instance2:9121', 'job' => 'redis' }, + 'value' => [1000, '1'] + }, + { + 'metric' => { 'instance' => 'instance2:8080', 'job' => 'registry' }, + 'value' => [1000, '1'] + }, + # unknown service => should be stripped out + { + 'metric' => { 'instance' => 'instance2:9000', 'job' => 'not-a-gitlab-service' }, + 'value' => [1000, '42'] + } + ]) + end + + def receive_node_service_app_server_workers_query(result: nil) + receive(:query) + .with(/app_server_workers/, an_instance_of(Hash)) + .and_return(result || [ + # instance 1 + { + 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails', 'server' => 'puma' }, + 'value' => [1000, '2'] + }, + # instance 2 + { + 'metric' => { 'instance' => 'instance2:8080', 'job' => 'gitlab-rails', 'server' => 'unicorn' }, + 'value' => [1000, '1'] + } + ]) + end +end diff --git a/spec/lib/gitlab/usage_data_concerns/topology_spec.rb b/spec/lib/gitlab/usage_data_concerns/topology_spec.rb deleted file mode 100644 index 0428900690c..00000000000 --- a/spec/lib/gitlab/usage_data_concerns/topology_spec.rb +++ /dev/null @@ -1,220 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' - -describe Gitlab::UsageDataConcerns::Topology do - include UsageDataHelpers - - describe '#topology_usage_data' do - subject { Class.new.extend(described_class).topology_usage_data } - - before do - # this pins down time shifts when benchmarking durations - allow(Process).to receive(:clock_gettime).and_return(0) - end - - context 'when embedded Prometheus server is enabled' do - before do - expect(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(true) - expect(Gitlab::Prometheus::Internal).to receive(:uri).and_return('http://prom:9090') - end - - it 'contains a topology element' do - allow_prometheus_queries - - expect(subject).to have_key(:topology) - end - - context 'tracking node metrics' do - it 'contains node level metrics for each instance' do - expect_prometheus_api_to( - receive_node_memory_query, - receive_node_cpu_count_query, - receive_node_service_memory_query, - receive_node_service_process_count_query - ) - - expect(subject[:topology]).to eq({ - duration_s: 0, - nodes: [ - { - node_memory_total_bytes: 512, - node_cpus: 8, - node_services: [ - { - name: 'web', - process_count: 10, - process_memory_rss: 300, - process_memory_uss: 301, - process_memory_pss: 302 - }, - { - name: 'sidekiq', - process_count: 5, - process_memory_rss: 303 - } - ] - }, - { - node_memory_total_bytes: 1024, - node_cpus: 16, - node_services: [ - { - name: 'sidekiq', - process_count: 15, - process_memory_rss: 400, - process_memory_pss: 401 - }, - { - name: 'redis', - process_count: 1, - process_memory_rss: 402 - } - ] - } - ] - }) - end - end - - context 'and some node memory metrics are missing' do - it 'removes the respective entries' do - expect_prometheus_api_to( - receive_node_memory_query(result: []), - receive_node_cpu_count_query, - receive_node_service_memory_query, - receive_node_service_process_count_query - ) - - keys = subject[:topology][:nodes].flat_map(&:keys) - expect(keys).not_to include(:node_memory_total_bytes) - expect(keys).to include(:node_cpus, :node_services) - end - end - - context 'and no results are found' do - it 'does not report anything' do - expect_prometheus_api_to receive(:aggregate).at_least(:once).and_return({}) - - expect(subject[:topology]).to eq({ - duration_s: 0, - nodes: [] - }) - end - end - - context 'and a connection error is raised' do - it 'does not report anything' do - expect_prometheus_api_to receive(:aggregate).and_raise('Connection failed') - - expect(subject[:topology]).to eq({ duration_s: 0 }) - end - end - end - - context 'when embedded Prometheus server is disabled' do - it 'does not report anything' do - expect(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(false) - - expect(subject[:topology]).to eq({ duration_s: 0 }) - end - end - end - - def receive_node_memory_query(result: nil) - receive(:query) - .with(/node_memory_MemTotal_bytes/, an_instance_of(Hash)) - .and_return(result || [ - { - 'metric' => { 'instance' => 'instance1:8080' }, - 'value' => [1000, '512'] - }, - { - 'metric' => { 'instance' => 'instance2:8090' }, - 'value' => [1000, '1024'] - } - ]) - end - - def receive_node_cpu_count_query(result: nil) - receive(:query) - .with(/node_cpu_seconds_total/, an_instance_of(Hash)) - .and_return(result || [ - { - 'metric' => { 'instance' => 'instance2:8090' }, - 'value' => [1000, '16'] - }, - { - 'metric' => { 'instance' => 'instance1:8080' }, - 'value' => [1000, '8'] - } - ]) - end - - def receive_node_service_memory_query(result: nil) - receive(:query) - .with(/process_.+_memory_bytes/, an_instance_of(Hash)) - .and_return(result || [ - # instance 1: runs Puma + a small Sidekiq - { - 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails', '__name__' => 'ruby_process_resident_memory_bytes' }, - 'value' => [1000, '300'] - }, - { - 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails', '__name__' => 'ruby_process_unique_memory_bytes' }, - 'value' => [1000, '301'] - }, - { - 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails', '__name__' => 'ruby_process_proportional_memory_bytes' }, - 'value' => [1000, '302'] - }, - { - 'metric' => { 'instance' => 'instance1:8090', 'job' => 'gitlab-sidekiq', '__name__' => 'ruby_process_resident_memory_bytes' }, - 'value' => [1000, '303'] - }, - # instance 2: runs a dedicated Sidekiq + Redis (which uses a different metric name) - { - 'metric' => { 'instance' => 'instance2:8090', 'job' => 'gitlab-sidekiq', '__name__' => 'ruby_process_resident_memory_bytes' }, - 'value' => [1000, '400'] - }, - { - 'metric' => { 'instance' => 'instance2:8090', 'job' => 'gitlab-sidekiq', '__name__' => 'ruby_process_proportional_memory_bytes' }, - 'value' => [1000, '401'] - }, - { - 'metric' => { 'instance' => 'instance2:9121', 'job' => 'redis', '__name__' => 'process_resident_memory_bytes' }, - 'value' => [1000, '402'] - } - ]) - end - - def receive_node_service_process_count_query(result: nil) - receive(:query) - .with(/process_start_time_seconds/, an_instance_of(Hash)) - .and_return(result || [ - # instance 1 - { - 'metric' => { 'instance' => 'instance1:8080', 'job' => 'gitlab-rails' }, - 'value' => [1000, '10'] - }, - { - 'metric' => { 'instance' => 'instance1:8090', 'job' => 'gitlab-sidekiq' }, - 'value' => [1000, '5'] - }, - # instance 2 - { - 'metric' => { 'instance' => 'instance2:8090', 'job' => 'gitlab-sidekiq' }, - 'value' => [1000, '15'] - }, - { - 'metric' => { 'instance' => 'instance2:9121', 'job' => 'redis' }, - 'value' => [1000, '1'] - }, - # unknown service => should be stripped out - { - 'metric' => { 'instance' => 'instance2:9000', 'job' => 'not-a-gitlab-service' }, - 'value' => [1000, '42'] - } - ]) - end -end diff --git a/spec/lib/gitlab/usage_data_counters/cycle_analytics_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/cycle_analytics_counter_spec.rb index 71be37692e2..18c21ef7eba 100644 --- a/spec/lib/gitlab/usage_data_counters/cycle_analytics_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/cycle_analytics_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::CycleAnalyticsCounter do +RSpec.describe Gitlab::UsageDataCounters::CycleAnalyticsCounter do it_behaves_like 'a redis usage counter', 'CycleAnalytics', :views it_behaves_like 'a redis usage counter with totals', :cycle_analytics, views: 3 diff --git a/spec/lib/gitlab/usage_data_counters/designs_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/designs_counter_spec.rb index deaf7ebc7f3..10a09e737f9 100644 --- a/spec/lib/gitlab/usage_data_counters/designs_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/designs_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::DesignsCounter do +RSpec.describe Gitlab::UsageDataCounters::DesignsCounter do it_behaves_like 'a redis usage counter', 'Designs', :create it_behaves_like 'a redis usage counter', 'Designs', :update it_behaves_like 'a redis usage counter', 'Designs', :delete diff --git a/spec/lib/gitlab/usage_data_counters/merge_request_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/merge_request_counter_spec.rb index 4be4a661260..d16c73e9312 100644 --- a/spec/lib/gitlab/usage_data_counters/merge_request_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/merge_request_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::MergeRequestCounter do +RSpec.describe Gitlab::UsageDataCounters::MergeRequestCounter do it_behaves_like 'a redis usage counter', 'Merge Request', :create it_behaves_like 'a redis usage counter with totals', :merge_request, create: 5 diff --git a/spec/lib/gitlab/usage_data_counters/note_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/note_counter_spec.rb index b385d1b07c7..7e8f0172e06 100644 --- a/spec/lib/gitlab/usage_data_counters/note_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/note_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::NoteCounter, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::UsageDataCounters::NoteCounter, :clean_gitlab_redis_shared_state do shared_examples 'a note usage counter' do |event, noteable_type| describe ".count(#{event})" do it "increments the Note #{event} counter by 1" do diff --git a/spec/lib/gitlab/usage_data_counters/productivity_analytics_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/productivity_analytics_counter_spec.rb index f4e92791728..34b2cfcf1de 100644 --- a/spec/lib/gitlab/usage_data_counters/productivity_analytics_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/productivity_analytics_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::ProductivityAnalyticsCounter do +RSpec.describe Gitlab::UsageDataCounters::ProductivityAnalyticsCounter do it_behaves_like 'a redis usage counter', 'ProductivityAnalytics', :views it_behaves_like 'a redis usage counter with totals', :productivity_analytics, views: 3 diff --git a/spec/lib/gitlab/usage_data_counters/redis_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/redis_counter_spec.rb index c34ac7867ab..be528b081c5 100644 --- a/spec/lib/gitlab/usage_data_counters/redis_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/redis_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::RedisCounter, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::UsageDataCounters::RedisCounter, :clean_gitlab_redis_shared_state do let(:redis_key) { 'foobar' } subject { Class.new.extend(described_class) } diff --git a/spec/lib/gitlab/usage_data_counters/search_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/search_counter_spec.rb index 35b0f9a67f4..b55e20ba555 100644 --- a/spec/lib/gitlab/usage_data_counters/search_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/search_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::SearchCounter, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::UsageDataCounters::SearchCounter, :clean_gitlab_redis_shared_state do shared_examples_for 'usage counter with totals' do |counter| it 'increments counter and returns total count' do expect(described_class.read(counter)).to eq(0) diff --git a/spec/lib/gitlab/usage_data_counters/snippet_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/snippet_counter_spec.rb index 65381ed36d1..6109437da77 100644 --- a/spec/lib/gitlab/usage_data_counters/snippet_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/snippet_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::SnippetCounter do +RSpec.describe Gitlab::UsageDataCounters::SnippetCounter do it_behaves_like 'a redis usage counter', 'Snippet', :create it_behaves_like 'a redis usage counter', 'Snippet', :update diff --git a/spec/lib/gitlab/usage_data_counters/source_code_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/source_code_counter_spec.rb index 47077345e0c..73d5b4038f8 100644 --- a/spec/lib/gitlab/usage_data_counters/source_code_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/source_code_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::SourceCodeCounter do +RSpec.describe Gitlab::UsageDataCounters::SourceCodeCounter do it_behaves_like 'a redis usage counter', 'Source Code', :pushes it_behaves_like 'a redis usage counter with totals', :source_code, pushes: 5 diff --git a/spec/lib/gitlab/usage_data_counters/track_unique_actions_spec.rb b/spec/lib/gitlab/usage_data_counters/track_unique_actions_spec.rb new file mode 100644 index 00000000000..584d8407e79 --- /dev/null +++ b/spec/lib/gitlab/usage_data_counters/track_unique_actions_spec.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::UsageDataCounters::TrackUniqueActions, :clean_gitlab_redis_shared_state do + subject(:track_unique_events) { described_class } + + let(:time) { Time.zone.now } + + def track_action(params) + track_unique_events.track_action(params) + end + + def count_unique_events(params) + track_unique_events.count_unique_events(params) + end + + context 'tracking an event' do + context 'when tracking successfully' do + context 'when the feature flag and the application setting is enabled' do + context 'when the target and the action is valid' do + before do + stub_feature_flags(described_class::FEATURE_FLAG => true) + stub_application_setting(usage_ping_enabled: true) + end + + it 'tracks and counts the events as expected' do + project = Event::TARGET_TYPES[:project] + design = Event::TARGET_TYPES[:design] + wiki = Event::TARGET_TYPES[:wiki] + + expect(track_action(event_action: :pushed, event_target: project, author_id: 1)).to be_truthy + expect(track_action(event_action: :pushed, event_target: project, author_id: 1)).to be_truthy + expect(track_action(event_action: :pushed, event_target: project, author_id: 2)).to be_truthy + expect(track_action(event_action: :pushed, event_target: project, author_id: 3)).to be_truthy + expect(track_action(event_action: :pushed, event_target: project, author_id: 4, time: time - 3.days)).to be_truthy + expect(track_action(event_action: :created, event_target: project, author_id: 5, time: time - 3.days)).to be_truthy + + expect(track_action(event_action: :destroyed, event_target: design, author_id: 3)).to be_truthy + expect(track_action(event_action: :created, event_target: design, author_id: 4)).to be_truthy + expect(track_action(event_action: :updated, event_target: design, author_id: 5)).to be_truthy + expect(track_action(event_action: :pushed, event_target: design, author_id: 6)).to be_truthy + + expect(track_action(event_action: :destroyed, event_target: wiki, author_id: 5)).to be_truthy + expect(track_action(event_action: :created, event_target: wiki, author_id: 3)).to be_truthy + expect(track_action(event_action: :updated, event_target: wiki, author_id: 4)).to be_truthy + expect(track_action(event_action: :pushed, event_target: wiki, author_id: 6)).to be_truthy + + expect(count_unique_events(event_action: described_class::PUSH_ACTION, date_from: time, date_to: Date.today)).to eq(3) + expect(count_unique_events(event_action: described_class::PUSH_ACTION, date_from: time - 5.days, date_to: Date.tomorrow)).to eq(4) + expect(count_unique_events(event_action: described_class::DESIGN_ACTION, date_from: time - 5.days, date_to: Date.today)).to eq(3) + expect(count_unique_events(event_action: described_class::WIKI_ACTION, date_from: time - 5.days, date_to: Date.today)).to eq(3) + expect(count_unique_events(event_action: described_class::PUSH_ACTION, date_from: time - 5.days, date_to: time - 2.days)).to eq(1) + end + end + end + end + + context 'when tracking unsuccessfully' do + using RSpec::Parameterized::TableSyntax + + where(:feature_flag, :application_setting, :target, :action) do + true | true | Project | :invalid_action + false | true | Project | :pushed + true | false | Project | :pushed + true | true | :invalid_target | :pushed + end + + with_them do + before do + stub_application_setting(usage_ping_enabled: application_setting) + stub_feature_flags(described_class::FEATURE_FLAG => feature_flag) + end + + it 'returns the expected values' do + expect(track_action(event_action: action, event_target: target, author_id: 2)).to be_nil + expect(count_unique_events(event_action: described_class::PUSH_ACTION, date_from: time, date_to: Date.today)).to eq(0) + end + end + end + end +end diff --git a/spec/lib/gitlab/usage_data_counters/web_ide_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/web_ide_counter_spec.rb index 42abbecead0..b0e5bd18b66 100644 --- a/spec/lib/gitlab/usage_data_counters/web_ide_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/web_ide_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::WebIdeCounter, :clean_gitlab_redis_shared_state do +RSpec.describe Gitlab::UsageDataCounters::WebIdeCounter, :clean_gitlab_redis_shared_state do shared_examples 'counter examples' do |event| it 'increments counter and return the total count' do expect(described_class.public_send(:total_count, event)).to eq(0) diff --git a/spec/lib/gitlab/usage_data_counters/wiki_page_counter_spec.rb b/spec/lib/gitlab/usage_data_counters/wiki_page_counter_spec.rb index 4e8ae35187e..685f6ea0a85 100644 --- a/spec/lib/gitlab/usage_data_counters/wiki_page_counter_spec.rb +++ b/spec/lib/gitlab/usage_data_counters/wiki_page_counter_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageDataCounters::WikiPageCounter do +RSpec.describe Gitlab::UsageDataCounters::WikiPageCounter do it_behaves_like 'a redis usage counter', 'Wiki Page', :create it_behaves_like 'a redis usage counter', 'Wiki Page', :update it_behaves_like 'a redis usage counter', 'Wiki Page', :delete diff --git a/spec/lib/gitlab/usage_data_spec.rb b/spec/lib/gitlab/usage_data_spec.rb index 31176999333..bca2f49eb33 100644 --- a/spec/lib/gitlab/usage_data_spec.rb +++ b/spec/lib/gitlab/usage_data_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UsageData, :aggregate_failures do +RSpec.describe Gitlab::UsageData, :aggregate_failures do include UsageDataHelpers before do @@ -10,7 +10,282 @@ describe Gitlab::UsageData, :aggregate_failures do stub_object_store_settings end - describe '#uncached_data' do + describe '.uncached_data' do + describe '.usage_activity_by_stage' do + it 'includes usage_activity_by_stage data' do + expect(described_class.uncached_data).to include(:usage_activity_by_stage) + expect(described_class.uncached_data).to include(:usage_activity_by_stage_monthly) + end + + it 'clears memoized values' do + values = %i(issue_minimum_id issue_maximum_id + user_minimum_id user_maximum_id unique_visit_service + deployment_minimum_id deployment_maximum_id + approval_merge_request_rule_minimum_id + approval_merge_request_rule_maximum_id) + values.each do |key| + expect(described_class).to receive(:clear_memoization).with(key) + end + + described_class.uncached_data + end + + context 'for configure' do + it 'includes accurate usage_activity_by_stage data' do + for_defined_days_back do + user = create(:user) + cluster = create(:cluster, user: user) + create(:clusters_applications_cert_manager, :installed, cluster: cluster) + create(:clusters_applications_helm, :installed, cluster: cluster) + create(:clusters_applications_ingress, :installed, cluster: cluster) + create(:clusters_applications_knative, :installed, cluster: cluster) + create(:cluster, :disabled, user: user) + create(:cluster_provider_gcp, :created) + create(:cluster_provider_aws, :created) + create(:cluster_platform_kubernetes) + create(:cluster, :group, :disabled, user: user) + create(:cluster, :group, user: user) + create(:cluster, :instance, :disabled, :production_environment) + create(:cluster, :instance, :production_environment) + create(:cluster, :management_project) + end + + expect(described_class.uncached_data[:usage_activity_by_stage][:configure]).to include( + clusters_applications_cert_managers: 2, + clusters_applications_helm: 2, + clusters_applications_ingress: 2, + clusters_applications_knative: 2, + clusters_management_project: 2, + clusters_disabled: 4, + clusters_enabled: 12, + clusters_platforms_gke: 2, + clusters_platforms_eks: 2, + clusters_platforms_user: 2, + instance_clusters_disabled: 2, + instance_clusters_enabled: 2, + group_clusters_disabled: 2, + group_clusters_enabled: 2, + project_clusters_disabled: 2, + project_clusters_enabled: 10 + ) + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:configure]).to include( + clusters_applications_cert_managers: 1, + clusters_applications_helm: 1, + clusters_applications_ingress: 1, + clusters_applications_knative: 1, + clusters_management_project: 1, + clusters_disabled: 2, + clusters_enabled: 6, + clusters_platforms_gke: 1, + clusters_platforms_eks: 1, + clusters_platforms_user: 1, + instance_clusters_disabled: 1, + instance_clusters_enabled: 1, + group_clusters_disabled: 1, + group_clusters_enabled: 1, + project_clusters_disabled: 1, + project_clusters_enabled: 5 + ) + end + end + + context 'for create' do + it 'include usage_activity_by_stage data' do + expect(described_class.uncached_data[:usage_activity_by_stage][:create]) + .not_to include( + :merge_requests_users + ) + end + + it 'includes monthly usage_activity_by_stage data' do + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:create]) + .to include( + :merge_requests_users + ) + end + + it 'includes accurate usage_activity_by_stage data' do + for_defined_days_back do + user = create(:user) + project = create(:project, :repository_private, + :test_repo, :remote_mirror, creator: user) + create(:merge_request, source_project: project) + create(:deploy_key, user: user) + create(:key, user: user) + create(:project, creator: user, disable_overriding_approvers_per_merge_request: true) + create(:project, creator: user, disable_overriding_approvers_per_merge_request: false) + create(:remote_mirror, project: project) + create(:snippet, author: user) + end + + expect(described_class.uncached_data[:usage_activity_by_stage][:create]).to include( + deploy_keys: 2, + keys: 2, + merge_requests: 2, + projects_with_disable_overriding_approvers_per_merge_request: 2, + projects_without_disable_overriding_approvers_per_merge_request: 4, + remote_mirrors: 2, + snippets: 2 + ) + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:create]).to include( + deploy_keys: 1, + keys: 1, + merge_requests: 1, + projects_with_disable_overriding_approvers_per_merge_request: 1, + projects_without_disable_overriding_approvers_per_merge_request: 2, + remote_mirrors: 1, + snippets: 1 + ) + end + end + + context 'for manage' do + it 'includes accurate usage_activity_by_stage data' do + stub_config( + omniauth: + { providers: omniauth_providers } + ) + + for_defined_days_back do + user = create(:user) + create(:event, author: user) + create(:group_member, user: user) + end + + expect(described_class.uncached_data[:usage_activity_by_stage][:manage]).to include( + events: 2, + groups: 2, + users_created: Gitlab.ee? ? 6 : 5, + omniauth_providers: ['google_oauth2'] + ) + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:manage]).to include( + events: 1, + groups: 1, + users_created: Gitlab.ee? ? 4 : 3, + omniauth_providers: ['google_oauth2'] + ) + end + + def omniauth_providers + [ + OpenStruct.new(name: 'google_oauth2'), + OpenStruct.new(name: 'ldapmain'), + OpenStruct.new(name: 'group_saml') + ] + end + end + + context 'for monitor' do + it 'includes accurate usage_activity_by_stage data' do + for_defined_days_back do + user = create(:user, dashboard: 'operations') + cluster = create(:cluster, user: user) + create(:project, creator: user) + create(:clusters_applications_prometheus, :installed, cluster: cluster) + end + + expect(described_class.uncached_data[:usage_activity_by_stage][:monitor]).to include( + clusters: 2, + clusters_applications_prometheus: 2, + operations_dashboard_default_dashboard: 2 + ) + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:monitor]).to include( + clusters: 1, + clusters_applications_prometheus: 1, + operations_dashboard_default_dashboard: 1 + ) + end + end + + context 'for plan' do + it 'includes accurate usage_activity_by_stage data' do + for_defined_days_back do + user = create(:user) + project = create(:project, creator: user) + issue = create(:issue, project: project, author: user) + create(:note, project: project, noteable: issue, author: user) + create(:todo, project: project, target: issue, author: user) + end + + expect(described_class.uncached_data[:usage_activity_by_stage][:plan]).to include( + issues: 2, + notes: 2, + projects: 2, + todos: 2 + ) + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:plan]).to include( + issues: 1, + notes: 1, + projects: 1, + todos: 1 + ) + end + end + + context 'for release' do + it 'includes accurate usage_activity_by_stage data' do + for_defined_days_back do + user = create(:user) + create(:deployment, :failed, user: user) + create(:release, author: user) + create(:deployment, :success, user: user) + end + + expect(described_class.uncached_data[:usage_activity_by_stage][:release]).to include( + deployments: 2, + failed_deployments: 2, + releases: 2, + successful_deployments: 2 + ) + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:release]).to include( + deployments: 1, + failed_deployments: 1, + releases: 1, + successful_deployments: 1 + ) + end + end + + context 'for verify' do + it 'includes accurate usage_activity_by_stage data' do + for_defined_days_back do + user = create(:user) + create(:ci_build, user: user) + create(:ci_empty_pipeline, source: :external, user: user) + create(:ci_empty_pipeline, user: user) + create(:ci_pipeline, :auto_devops_source, user: user) + create(:ci_pipeline, :repository_source, user: user) + create(:ci_pipeline_schedule, owner: user) + create(:ci_trigger, owner: user) + create(:clusters_applications_runner, :installed) + end + + expect(described_class.uncached_data[:usage_activity_by_stage][:verify]).to include( + ci_builds: 2, + ci_external_pipelines: 2, + ci_internal_pipelines: 2, + ci_pipeline_config_auto_devops: 2, + ci_pipeline_config_repository: 2, + ci_pipeline_schedules: 2, + ci_pipelines: 2, + ci_triggers: 2, + clusters_applications_runner: 2 + ) + expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:verify]).to include( + ci_builds: 1, + ci_external_pipelines: 1, + ci_internal_pipelines: 1, + ci_pipeline_config_auto_devops: 1, + ci_pipeline_config_repository: 1, + ci_pipeline_schedules: 1, + ci_pipelines: 1, + ci_triggers: 1, + clusters_applications_runner: 1 + ) + end + end + end + it 'ensures recorded_at is set before any other usage data calculation' do %i(alt_usage_data redis_usage_data distinct_count count).each do |method| expect(described_class).not_to receive(method) @@ -21,7 +296,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#data' do + describe '.data' do let!(:ud) { build(:usage_data) } before do @@ -44,7 +319,11 @@ describe Gitlab::UsageData, :aggregate_failures do expect(UsageDataHelpers::COUNTS_KEYS - count_data.keys).to be_empty end - it 'gathers projects data correctly' do + it 'gathers usage counts monthly hash' do + expect(subject[:counts_monthly]).to be_an(Hash) + end + + it 'gathers usage counts correctly' do count_data = subject[:counts] expect(count_data[:projects]).to eq(4) @@ -56,8 +335,6 @@ describe Gitlab::UsageData, :aggregate_failures do expect(count_data[:jira_imports_projects_count]).to eq(2) expect(count_data[:jira_imports_total_imported_count]).to eq(3) expect(count_data[:jira_imports_total_imported_issues_count]).to eq(13) - expect(count_data[:projects_slack_notifications_active]).to eq(2) - expect(count_data[:projects_slack_slash_active]).to eq(1) expect(count_data[:projects_slack_active]).to eq(2) expect(count_data[:projects_slack_slash_commands_active]).to eq(1) expect(count_data[:projects_custom_issue_tracker_active]).to eq(1) @@ -102,7 +379,15 @@ describe Gitlab::UsageData, :aggregate_failures do expect(count_data[:clusters_applications_elastic_stack]).to eq(1) expect(count_data[:grafana_integrated_projects]).to eq(2) expect(count_data[:clusters_applications_jupyter]).to eq(1) + expect(count_data[:clusters_applications_cilium]).to eq(1) expect(count_data[:clusters_management_project]).to eq(1) + + expect(count_data[:deployments]).to eq(4) + expect(count_data[:successful_deployments]).to eq(2) + expect(count_data[:failed_deployments]).to eq(2) + expect(count_data[:snippets]).to eq(6) + expect(count_data[:personal_snippets]).to eq(2) + expect(count_data[:project_snippets]).to eq(4) end it 'gathers object store usage correctly' do @@ -169,6 +454,10 @@ describe Gitlab::UsageData, :aggregate_failures do expect { subject }.not_to raise_error end + it 'includes a recording_ce_finished_at timestamp' do + expect(subject[:recording_ce_finished_at]).to be_a(Time) + end + it 'jira usage works when queries time out' do allow_any_instance_of(ActiveRecord::Relation) .to receive(:find_in_batches).and_raise(ActiveRecord::StatementInvalid.new('')) @@ -177,7 +466,24 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#usage_data_counters' do + describe '.system_usage_data_monthly' do + let!(:ud) { build(:usage_data) } + + subject { described_class.system_usage_data_monthly } + + it 'gathers monthly usage counts correctly' do + counts_monthly = subject[:counts_monthly] + + expect(counts_monthly[:deployments]).to eq(2) + expect(counts_monthly[:successful_deployments]).to eq(1) + expect(counts_monthly[:failed_deployments]).to eq(1) + expect(counts_monthly[:snippets]).to eq(3) + expect(counts_monthly[:personal_snippets]).to eq(1) + expect(counts_monthly[:project_snippets]).to eq(2) + end + end + + describe '.usage_data_counters' do subject { described_class.usage_data_counters } it { is_expected.to all(respond_to :totals) } @@ -204,7 +510,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#license_usage_data' do + describe '.license_usage_data' do subject { described_class.license_usage_data } it 'gathers license data' do @@ -216,16 +522,8 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '.recording_ce_finished_at' do - subject { described_class.recording_ce_finish_data } - - it 'gathers time ce recording finishes at' do - expect(subject[:recording_ce_finished_at]).to be_a(Time) - end - end - context 'when not relying on database records' do - describe '#features_usage_data_ce' do + describe '.features_usage_data_ce' do subject { described_class.features_usage_data_ce } it 'gathers feature usage data', :aggregate_failures do @@ -243,6 +541,20 @@ describe Gitlab::UsageData, :aggregate_failures do expect(subject[:grafana_link_enabled]).to eq(Gitlab::CurrentSettings.grafana_enabled?) end + context 'with embedded Prometheus' do + it 'returns true when embedded Prometheus is enabled' do + allow(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(true) + + expect(subject[:prometheus_enabled]).to eq(true) + end + + it 'returns false when embedded Prometheus is disabled' do + allow(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(false) + + expect(subject[:prometheus_enabled]).to eq(false) + end + end + context 'with embedded grafana' do it 'returns true when embedded grafana is enabled' do stub_application_setting(grafana_enabled: true) @@ -258,7 +570,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#components_usage_data' do + describe '.components_usage_data' do subject { described_class.components_usage_data } it 'gathers basic components usage data' do @@ -282,7 +594,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#app_server_type' do + describe '.app_server_type' do subject { described_class.app_server_type } it 'successfully identifies runtime and returns the identifier' do @@ -304,7 +616,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#object_store_config' do + describe '.object_store_config' do let(:component) { 'lfs' } subject { described_class.object_store_config(component) } @@ -345,7 +657,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#object_store_usage_data' do + describe '.object_store_usage_data' do subject { described_class.object_store_usage_data } it 'fetches object store config of five components' do @@ -364,7 +676,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#cycle_analytics_usage_data' do + describe '.cycle_analytics_usage_data' do subject { described_class.cycle_analytics_usage_data } it 'works when queries time out in new' do @@ -382,7 +694,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#ingress_modsecurity_usage' do + describe '.ingress_modsecurity_usage' do subject { described_class.ingress_modsecurity_usage } let(:environment) { create(:environment) } @@ -514,7 +826,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#grafana_embed_usage_data' do + describe '.grafana_embed_usage_data' do subject { described_class.grafana_embed_usage_data } let(:project) { create(:project) } @@ -580,7 +892,7 @@ describe Gitlab::UsageData, :aggregate_failures do end end - describe '#merge_requests_usage' do + describe '.merge_requests_users' do let(:time_period) { { created_at: 2.days.ago..Time.current } } let(:merge_request) { create(:merge_request) } let(:other_user) { create(:user) } @@ -597,9 +909,94 @@ describe Gitlab::UsageData, :aggregate_failures do end it 'returns the distinct count of users using merge requests (via events table) within the specified time period' do - expect(described_class.merge_requests_usage(time_period)).to eq( - merge_requests_users: 2 - ) + expect(described_class.merge_requests_users(time_period)).to eq(2) + end + end + + def for_defined_days_back(days: [29, 2]) + days.each do |n| + Timecop.travel(n.days.ago) do + yield + end + end + end + + describe '#action_monthly_active_users', :clean_gitlab_redis_shared_state do + let(:time_period) { { created_at: 2.days.ago..time } } + let(:time) { Time.zone.now } + + before do + stub_feature_flags(Gitlab::UsageDataCounters::TrackUniqueActions::FEATURE_FLAG => feature_flag) + end + + context 'when the feature flag is enabled' do + let(:feature_flag) { true } + + before do + counter = Gitlab::UsageDataCounters::TrackUniqueActions + project = Event::TARGET_TYPES[:project] + wiki = Event::TARGET_TYPES[:wiki] + design = Event::TARGET_TYPES[:design] + + counter.track_action(event_action: :pushed, event_target: project, author_id: 1) + counter.track_action(event_action: :pushed, event_target: project, author_id: 1) + counter.track_action(event_action: :pushed, event_target: project, author_id: 2) + counter.track_action(event_action: :pushed, event_target: project, author_id: 3) + counter.track_action(event_action: :pushed, event_target: project, author_id: 4, time: time - 3.days) + counter.track_action(event_action: :created, event_target: project, author_id: 5, time: time - 3.days) + counter.track_action(event_action: :created, event_target: wiki, author_id: 3) + counter.track_action(event_action: :created, event_target: design, author_id: 3) + end + + it 'returns the distinct count of user actions within the specified time period' do + expect(described_class.action_monthly_active_users(time_period)).to eq( + { + action_monthly_active_users_design_management: 1, + action_monthly_active_users_project_repo: 3, + action_monthly_active_users_wiki_repo: 1 + } + ) + end + end + + context 'when the feature flag is disabled' do + let(:feature_flag) { false } + + it 'returns an empty hash' do + expect(described_class.action_monthly_active_users(time_period)).to eq({}) + end + end + end + + describe '.analytics_unique_visits_data' do + subject { described_class.analytics_unique_visits_data } + + it 'returns the number of unique visits to pages with analytics features' do + ::Gitlab::Analytics::UniqueVisits::TARGET_IDS.each do |target_id| + expect_any_instance_of(::Gitlab::Analytics::UniqueVisits).to receive(:weekly_unique_visits_for_target).with(target_id).and_return(123) + end + + expect_any_instance_of(::Gitlab::Analytics::UniqueVisits).to receive(:weekly_unique_visits_for_any_target).and_return(543) + + expect(subject).to eq({ + analytics_unique_visits: { + 'g_analytics_contribution' => 123, + 'g_analytics_insights' => 123, + 'g_analytics_issues' => 123, + 'g_analytics_productivity' => 123, + 'g_analytics_valuestream' => 123, + 'p_analytics_pipelines' => 123, + 'p_analytics_code_reviews' => 123, + 'p_analytics_valuestream' => 123, + 'p_analytics_insights' => 123, + 'p_analytics_issues' => 123, + 'p_analytics_repo' => 123, + 'u_analytics_todos' => 123, + 'i_analytics_cohorts' => 123, + 'i_analytics_dev_ops_score' => 123, + 'analytics_unique_visits_for_any_target' => 543 + } + }) end end end diff --git a/spec/lib/gitlab/user_access_snippet_spec.rb b/spec/lib/gitlab/user_access_snippet_spec.rb index 2e8a0a49a76..4143a3017e8 100644 --- a/spec/lib/gitlab/user_access_snippet_spec.rb +++ b/spec/lib/gitlab/user_access_snippet_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UserAccessSnippet do +RSpec.describe Gitlab::UserAccessSnippet do subject(:access) { described_class.new(user, snippet: snippet) } let_it_be(:project) { create(:project, :private) } diff --git a/spec/lib/gitlab/user_access_spec.rb b/spec/lib/gitlab/user_access_spec.rb index 78370f0136c..1a81d0127dc 100644 --- a/spec/lib/gitlab/user_access_spec.rb +++ b/spec/lib/gitlab/user_access_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::UserAccess do +RSpec.describe Gitlab::UserAccess do include ProjectForksHelper let(:access) { described_class.new(user, project: project) } diff --git a/spec/lib/gitlab/utils/deep_size_spec.rb b/spec/lib/gitlab/utils/deep_size_spec.rb index 5a155fb6c80..7595fb2c1b0 100644 --- a/spec/lib/gitlab/utils/deep_size_spec.rb +++ b/spec/lib/gitlab/utils/deep_size_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Utils::DeepSize do +RSpec.describe Gitlab::Utils::DeepSize do let(:data) do { a: [1, 2, 3], diff --git a/spec/lib/gitlab/utils/inline_hash_spec.rb b/spec/lib/gitlab/utils/inline_hash_spec.rb index 867db0b92a5..d1354a7ae0a 100644 --- a/spec/lib/gitlab/utils/inline_hash_spec.rb +++ b/spec/lib/gitlab/utils/inline_hash_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Utils::InlineHash do +RSpec.describe Gitlab::Utils::InlineHash do describe '.merge_keys' do subject { described_class.merge_keys(source) } diff --git a/spec/lib/gitlab/utils/json_size_estimator_spec.rb b/spec/lib/gitlab/utils/json_size_estimator_spec.rb index ae24e25558a..5fd66caa5e9 100644 --- a/spec/lib/gitlab/utils/json_size_estimator_spec.rb +++ b/spec/lib/gitlab/utils/json_size_estimator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Utils::JsonSizeEstimator do +RSpec.describe Gitlab::Utils::JsonSizeEstimator do RSpec::Matchers.define :match_json_bytesize_of do |expected| match do |actual| actual == expected.to_json.bytesize diff --git a/spec/lib/gitlab/utils/lazy_attributes_spec.rb b/spec/lib/gitlab/utils/lazy_attributes_spec.rb index c0005c194c4..dfffe70defb 100644 --- a/spec/lib/gitlab/utils/lazy_attributes_spec.rb +++ b/spec/lib/gitlab/utils/lazy_attributes_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' require 'active_support/concern' -describe Gitlab::Utils::LazyAttributes do +RSpec.describe Gitlab::Utils::LazyAttributes do subject(:klass) do Class.new do include Gitlab::Utils::LazyAttributes diff --git a/spec/lib/gitlab/utils/log_limited_array_spec.rb b/spec/lib/gitlab/utils/log_limited_array_spec.rb index a236ab37614..a55a176be48 100644 --- a/spec/lib/gitlab/utils/log_limited_array_spec.rb +++ b/spec/lib/gitlab/utils/log_limited_array_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Utils::LogLimitedArray do +RSpec.describe Gitlab::Utils::LogLimitedArray do describe '.log_limited_array' do context 'when the argument is not an array' do it 'returns an empty array' do diff --git a/spec/lib/gitlab/utils/markdown_spec.rb b/spec/lib/gitlab/utils/markdown_spec.rb new file mode 100644 index 00000000000..001ff5bc487 --- /dev/null +++ b/spec/lib/gitlab/utils/markdown_spec.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Gitlab::Utils::Markdown do + let(:klass) do + Class.new do + include Gitlab::Utils::Markdown + end + end + + subject(:object) { klass.new } + + describe '#string_to_anchor' do + subject { object.string_to_anchor(string) } + + let(:string) { 'My Header' } + + it 'converts string to anchor' do + is_expected.to eq 'my-header' + end + + context 'when string has punctuation' do + let(:string) { 'My, Header!' } + + it 'removes punctuation' do + is_expected.to eq 'my-header' + end + end + + context 'when string starts and ends with spaces' do + let(:string) { ' My Header ' } + + it 'removes extra spaces' do + is_expected.to eq 'my-header' + end + end + + context 'when string has multiple spaces and dashes in the middle' do + let(:string) { 'My - - - Header' } + + it 'removes consecutive dashes' do + is_expected.to eq 'my-header' + end + end + + context 'when string contains only digits' do + let(:string) { '123' } + + it 'adds anchor prefix' do + is_expected.to eq 'anchor-123' + end + end + + context 'when string is empty' do + let(:string) { '' } + + it 'returns an empty string' do + is_expected.to eq '' + end + end + end +end diff --git a/spec/lib/gitlab/utils/measuring_spec.rb b/spec/lib/gitlab/utils/measuring_spec.rb index 254f53f7da3..4931ebf26f0 100644 --- a/spec/lib/gitlab/utils/measuring_spec.rb +++ b/spec/lib/gitlab/utils/measuring_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Utils::Measuring do +RSpec.describe Gitlab::Utils::Measuring do describe '#with_measuring' do let(:base_log_data) { {} } let(:result) { "result" } diff --git a/spec/lib/gitlab/utils/merge_hash_spec.rb b/spec/lib/gitlab/utils/merge_hash_spec.rb index 72620e549a9..11daa05c9ee 100644 --- a/spec/lib/gitlab/utils/merge_hash_spec.rb +++ b/spec/lib/gitlab/utils/merge_hash_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::Utils::MergeHash do +RSpec.describe Gitlab::Utils::MergeHash do describe '.crush' do it 'can flatten a hash to each element' do input = { hello: "world", this: { crushes: ["an entire", "hash"] } } diff --git a/spec/lib/gitlab/utils/override_spec.rb b/spec/lib/gitlab/utils/override_spec.rb index e2776efac85..7ba7392df0f 100644 --- a/spec/lib/gitlab/utils/override_spec.rb +++ b/spec/lib/gitlab/utils/override_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Utils::Override do +RSpec.describe Gitlab::Utils::Override do let(:base) do Struct.new(:good) do def self.good diff --git a/spec/lib/gitlab/utils/safe_inline_hash_spec.rb b/spec/lib/gitlab/utils/safe_inline_hash_spec.rb index 617845332bc..f7c50140cf7 100644 --- a/spec/lib/gitlab/utils/safe_inline_hash_spec.rb +++ b/spec/lib/gitlab/utils/safe_inline_hash_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Gitlab::Utils::SafeInlineHash do +RSpec.describe Gitlab::Utils::SafeInlineHash do describe '.merge_keys!' do let(:source) { { 'foo' => { 'bar' => 'baz' } } } let(:validator) { instance_double(Gitlab::Utils::DeepSize, valid?: valid) } diff --git a/spec/lib/gitlab/utils/sanitize_node_link_spec.rb b/spec/lib/gitlab/utils/sanitize_node_link_spec.rb index dd379f2fe1f..514051b1cc0 100644 --- a/spec/lib/gitlab/utils/sanitize_node_link_spec.rb +++ b/spec/lib/gitlab/utils/sanitize_node_link_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Utils::SanitizeNodeLink do +RSpec.describe Gitlab::Utils::SanitizeNodeLink do let(:klass) do struct = Struct.new(:value) struct.include(described_class) diff --git a/spec/lib/gitlab/utils/strong_memoize_spec.rb b/spec/lib/gitlab/utils/strong_memoize_spec.rb index 624e799c5e9..d9fa2e516e1 100644 --- a/spec/lib/gitlab/utils/strong_memoize_spec.rb +++ b/spec/lib/gitlab/utils/strong_memoize_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Utils::StrongMemoize do +RSpec.describe Gitlab::Utils::StrongMemoize do let(:klass) do struct = Struct.new(:value) do def method_name diff --git a/spec/lib/gitlab/utils/usage_data_spec.rb b/spec/lib/gitlab/utils/usage_data_spec.rb index 7de615384c5..7940c9af6ff 100644 --- a/spec/lib/gitlab/utils/usage_data_spec.rb +++ b/spec/lib/gitlab/utils/usage_data_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Utils::UsageData do +RSpec.describe Gitlab::Utils::UsageData do describe '#count' do let(:relation) { double(:relation) } @@ -88,13 +88,21 @@ describe Gitlab::Utils::UsageData do end context 'when Prometheus is disabled' do - it 'returns nil' do + before do expect(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(false) + end + it 'returns nil by default' do result = described_class.with_prometheus_client { |client| client } expect(result).to be nil end + + it 'returns fallback if provided' do + result = described_class.with_prometheus_client(fallback: []) { |client| client } + + expect(result).to eq([]) + end end end @@ -108,4 +116,14 @@ describe Gitlab::Utils::UsageData do expect(duration).to eq(2) end end + + describe '#with_finished_at' do + it 'adds a timestamp to the hash yielded by the block' do + freeze_time do + result = described_class.with_finished_at(:current_time) { { a: 1 } } + + expect(result).to eq(a: 1, current_time: Time.now) + end + end + end end diff --git a/spec/lib/gitlab/utils_spec.rb b/spec/lib/gitlab/utils_spec.rb index 3a2430d1f2d..7a0d40ff0d2 100644 --- a/spec/lib/gitlab/utils_spec.rb +++ b/spec/lib/gitlab/utils_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Utils do +RSpec.describe Gitlab::Utils do delegate :to_boolean, :boolean_to_yes_no, :slugify, :random_string, :which, :ensure_array_from_string, :to_exclusive_sentence, :bytes_to_megabytes, :append_path, :check_path_traversal!, :ms_to_round_sec, to: :described_class @@ -358,4 +358,40 @@ describe Gitlab::Utils do }) end end + + describe '.stable_sort_by' do + subject(:sorted_list) { described_class.stable_sort_by(list) { |obj| obj[:priority] } } + + context 'when items have the same priority' do + let(:list) do + [ + { name: 'obj 1', priority: 1 }, + { name: 'obj 2', priority: 1 }, + { name: 'obj 3', priority: 1 } + ] + end + + it 'does not change order in cases of ties' do + expect(sorted_list).to eq(list) + end + end + + context 'when items have different priorities' do + let(:list) do + [ + { name: 'obj 1', priority: 2 }, + { name: 'obj 2', priority: 1 }, + { name: 'obj 3', priority: 3 } + ] + end + + it 'sorts items like the regular sort_by' do + expect(sorted_list).to eq([ + { name: 'obj 2', priority: 1 }, + { name: 'obj 1', priority: 2 }, + { name: 'obj 3', priority: 3 } + ]) + end + end + end end diff --git a/spec/lib/gitlab/verify/job_artifacts_spec.rb b/spec/lib/gitlab/verify/job_artifacts_spec.rb index b50ec1528d4..fde7ebd442e 100644 --- a/spec/lib/gitlab/verify/job_artifacts_spec.rb +++ b/spec/lib/gitlab/verify/job_artifacts_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Verify::JobArtifacts do +RSpec.describe Gitlab::Verify::JobArtifacts do include GitlabVerifyHelpers it_behaves_like 'Gitlab::Verify::BatchVerifier subclass' do diff --git a/spec/lib/gitlab/verify/lfs_objects_spec.rb b/spec/lib/gitlab/verify/lfs_objects_spec.rb index c27c9b6efa1..760162dd627 100644 --- a/spec/lib/gitlab/verify/lfs_objects_spec.rb +++ b/spec/lib/gitlab/verify/lfs_objects_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Verify::LfsObjects do +RSpec.describe Gitlab::Verify::LfsObjects do include GitlabVerifyHelpers it_behaves_like 'Gitlab::Verify::BatchVerifier subclass' do diff --git a/spec/lib/gitlab/verify/uploads_spec.rb b/spec/lib/gitlab/verify/uploads_spec.rb index a3d3f5d46f3..3e5154d5029 100644 --- a/spec/lib/gitlab/verify/uploads_spec.rb +++ b/spec/lib/gitlab/verify/uploads_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Verify::Uploads do +RSpec.describe Gitlab::Verify::Uploads do include GitlabVerifyHelpers it_behaves_like 'Gitlab::Verify::BatchVerifier subclass' do diff --git a/spec/lib/gitlab/version_info_spec.rb b/spec/lib/gitlab/version_info_spec.rb index 8c14b187410..f81e3aa070a 100644 --- a/spec/lib/gitlab/version_info_spec.rb +++ b/spec/lib/gitlab/version_info_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Gitlab::VersionInfo' do +RSpec.describe 'Gitlab::VersionInfo' do before do @unknown = Gitlab::VersionInfo.new @v0_0_1 = Gitlab::VersionInfo.new(0, 0, 1) diff --git a/spec/lib/gitlab/view/presenter/base_spec.rb b/spec/lib/gitlab/view/presenter/base_spec.rb index e196ab23482..1ab6973e279 100644 --- a/spec/lib/gitlab/view/presenter/base_spec.rb +++ b/spec/lib/gitlab/view/presenter/base_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::View::Presenter::Base do +RSpec.describe Gitlab::View::Presenter::Base do let(:project) { double(:project) } let(:presenter_class) do Struct.new(:subject).include(described_class) diff --git a/spec/lib/gitlab/view/presenter/delegated_spec.rb b/spec/lib/gitlab/view/presenter/delegated_spec.rb index 0a21cd1358e..27cff970f06 100644 --- a/spec/lib/gitlab/view/presenter/delegated_spec.rb +++ b/spec/lib/gitlab/view/presenter/delegated_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::View::Presenter::Delegated do +RSpec.describe Gitlab::View::Presenter::Delegated do let(:project) { double(:project, user: 'John Doe') } let(:presenter_class) do Class.new(described_class) diff --git a/spec/lib/gitlab/view/presenter/factory_spec.rb b/spec/lib/gitlab/view/presenter/factory_spec.rb index 7bf3c325019..92986e89b73 100644 --- a/spec/lib/gitlab/view/presenter/factory_spec.rb +++ b/spec/lib/gitlab/view/presenter/factory_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::View::Presenter::Factory do +RSpec.describe Gitlab::View::Presenter::Factory do let(:build) { Ci::Build.new } describe '#initialize' do diff --git a/spec/lib/gitlab/view/presenter/simple_spec.rb b/spec/lib/gitlab/view/presenter/simple_spec.rb index 70e2b170a36..2b764fcccef 100644 --- a/spec/lib/gitlab/view/presenter/simple_spec.rb +++ b/spec/lib/gitlab/view/presenter/simple_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::View::Presenter::Simple do +RSpec.describe Gitlab::View::Presenter::Simple do let(:project) { double(:project, user: 'John Doe') } let(:presenter_class) do Class.new(described_class) diff --git a/spec/lib/gitlab/visibility_level_checker_spec.rb b/spec/lib/gitlab/visibility_level_checker_spec.rb index fc929d5cbbf..833021a22ca 100644 --- a/spec/lib/gitlab/visibility_level_checker_spec.rb +++ b/spec/lib/gitlab/visibility_level_checker_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::VisibilityLevelChecker do +RSpec.describe Gitlab::VisibilityLevelChecker do let(:user) { create(:user) } let(:project) { create(:project) } let(:visibility_level_checker) { } diff --git a/spec/lib/gitlab/visibility_level_spec.rb b/spec/lib/gitlab/visibility_level_spec.rb index a249b3a235e..2ac343cd1e7 100644 --- a/spec/lib/gitlab/visibility_level_spec.rb +++ b/spec/lib/gitlab/visibility_level_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::VisibilityLevel do +RSpec.describe Gitlab::VisibilityLevel do describe '.level_value' do it 'converts "public" to integer value' do expect(described_class.level_value('public')).to eq(Gitlab::VisibilityLevel::PUBLIC) diff --git a/spec/lib/gitlab/web_ide/config/entry/global_spec.rb b/spec/lib/gitlab/web_ide/config/entry/global_spec.rb index 04b0752c6fe..3a50667163b 100644 --- a/spec/lib/gitlab/web_ide/config/entry/global_spec.rb +++ b/spec/lib/gitlab/web_ide/config/entry/global_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::WebIde::Config::Entry::Global do +RSpec.describe Gitlab::WebIde::Config::Entry::Global do let(:global) { described_class.new(hash) } describe '.nodes' do diff --git a/spec/lib/gitlab/web_ide/config/entry/terminal_spec.rb b/spec/lib/gitlab/web_ide/config/entry/terminal_spec.rb index 882e389e040..0df0f56f440 100644 --- a/spec/lib/gitlab/web_ide/config/entry/terminal_spec.rb +++ b/spec/lib/gitlab/web_ide/config/entry/terminal_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::WebIde::Config::Entry::Terminal do +RSpec.describe Gitlab::WebIde::Config::Entry::Terminal do let(:entry) { described_class.new(config, with_image_ports: true) } describe '.nodes' do diff --git a/spec/lib/gitlab/web_ide/config_spec.rb b/spec/lib/gitlab/web_ide/config_spec.rb index c1dafd01197..7a9011d03c0 100644 --- a/spec/lib/gitlab/web_ide/config_spec.rb +++ b/spec/lib/gitlab/web_ide/config_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::WebIde::Config do +RSpec.describe Gitlab::WebIde::Config do let(:config) do described_class.new(yml) end diff --git a/spec/lib/gitlab/wiki_file_finder_spec.rb b/spec/lib/gitlab/wiki_file_finder_spec.rb index aeba081f3d3..7abe92a5a2b 100644 --- a/spec/lib/gitlab/wiki_file_finder_spec.rb +++ b/spec/lib/gitlab/wiki_file_finder_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::WikiFileFinder do +RSpec.describe Gitlab::WikiFileFinder do describe '#find' do let(:project) { create(:project, :public, :wiki_repo) } let(:wiki) { build(:project_wiki, project: project) } diff --git a/spec/lib/gitlab/wiki_pages/front_matter_parser_spec.rb b/spec/lib/gitlab/wiki_pages/front_matter_parser_spec.rb index 01701589e63..c78103f33f4 100644 --- a/spec/lib/gitlab/wiki_pages/front_matter_parser_spec.rb +++ b/spec/lib/gitlab/wiki_pages/front_matter_parser_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::WikiPages::FrontMatterParser do +RSpec.describe Gitlab::WikiPages::FrontMatterParser do subject(:parser) { described_class.new(raw_content, gate) } let(:content) { 'This is the content' } diff --git a/spec/lib/gitlab/with_request_store_spec.rb b/spec/lib/gitlab/with_request_store_spec.rb index 1ef8d986f96..353ad02fbd8 100644 --- a/spec/lib/gitlab/with_request_store_spec.rb +++ b/spec/lib/gitlab/with_request_store_spec.rb @@ -3,7 +3,7 @@ require 'fast_spec_helper' require 'request_store' -describe Gitlab::WithRequestStore do +RSpec.describe Gitlab::WithRequestStore do let(:fake_class) { Class.new { include Gitlab::WithRequestStore } } subject(:object) { fake_class.new } diff --git a/spec/lib/gitlab/workhorse_spec.rb b/spec/lib/gitlab/workhorse_spec.rb index 53b6f461a48..5cb08ac1e76 100644 --- a/spec/lib/gitlab/workhorse_spec.rb +++ b/spec/lib/gitlab/workhorse_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::Workhorse do +RSpec.describe Gitlab::Workhorse do let_it_be(:project) { create(:project, :repository) } let(:repository) { project.repository } diff --git a/spec/lib/gitlab/x509/commit_spec.rb b/spec/lib/gitlab/x509/commit_spec.rb index ac93609b467..a81955b995e 100644 --- a/spec/lib/gitlab/x509/commit_spec.rb +++ b/spec/lib/gitlab/x509/commit_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::X509::Commit do +RSpec.describe Gitlab::X509::Commit do describe '#signature' do let(:signature) { described_class.new(commit).signature } diff --git a/spec/lib/gitlab/x509/signature_spec.rb b/spec/lib/gitlab/x509/signature_spec.rb index cff2fd7748b..ac6f7e49fe0 100644 --- a/spec/lib/gitlab/x509/signature_spec.rb +++ b/spec/lib/gitlab/x509/signature_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::X509::Signature do +RSpec.describe Gitlab::X509::Signature do let(:issuer_attributes) do { subject_key_identifier: X509Helpers::User1.issuer_subject_key_identifier, diff --git a/spec/lib/gitlab/x509/tag_spec.rb b/spec/lib/gitlab/x509/tag_spec.rb index 4bc9723bd0d..b011ea515de 100644 --- a/spec/lib/gitlab/x509/tag_spec.rb +++ b/spec/lib/gitlab/x509/tag_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -describe Gitlab::X509::Tag do +RSpec.describe Gitlab::X509::Tag do subject(:signature) { described_class.new(tag).signature } describe '#signature' do diff --git a/spec/lib/gitlab/zoom_link_extractor_spec.rb b/spec/lib/gitlab/zoom_link_extractor_spec.rb index c3d1679d031..363668fb2b5 100644 --- a/spec/lib/gitlab/zoom_link_extractor_spec.rb +++ b/spec/lib/gitlab/zoom_link_extractor_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab::ZoomLinkExtractor do +RSpec.describe Gitlab::ZoomLinkExtractor do describe "#links" do using RSpec::Parameterized::TableSyntax diff --git a/spec/lib/gitlab_danger_spec.rb b/spec/lib/gitlab_danger_spec.rb index 8115fbca5e0..49c7a46f321 100644 --- a/spec/lib/gitlab_danger_spec.rb +++ b/spec/lib/gitlab_danger_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe GitlabDanger do +RSpec.describe GitlabDanger do let(:gitlab_danger_helper) { nil } subject { described_class.new(gitlab_danger_helper) } diff --git a/spec/lib/gitlab_spec.rb b/spec/lib/gitlab_spec.rb index 84d072a50ec..7c2758bf27e 100644 --- a/spec/lib/gitlab_spec.rb +++ b/spec/lib/gitlab_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Gitlab do +RSpec.describe Gitlab do describe '.root' do it 'returns the root path of the app' do expect(described_class.root).to eq(Pathname.new(File.expand_path('../..', __dir__))) diff --git a/spec/lib/google_api/auth_spec.rb b/spec/lib/google_api/auth_spec.rb index fa4e6288681..eeb99bfbb6c 100644 --- a/spec/lib/google_api/auth_spec.rb +++ b/spec/lib/google_api/auth_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe GoogleApi::Auth do +RSpec.describe GoogleApi::Auth do let(:redirect_uri) { 'http://localhost:3000/google_api/authorizations/callback' } let(:redirect_to) { 'http://localhost:3000/namaspace/project/clusters' } diff --git a/spec/lib/google_api/cloud_platform/client_spec.rb b/spec/lib/google_api/cloud_platform/client_spec.rb index bd063648ca1..d217699f79d 100644 --- a/spec/lib/google_api/cloud_platform/client_spec.rb +++ b/spec/lib/google_api/cloud_platform/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe GoogleApi::CloudPlatform::Client do +RSpec.describe GoogleApi::CloudPlatform::Client do let(:token) { 'token' } let(:client) { described_class.new(token, nil) } let(:user_agent_options) { client.instance_eval { user_agent_header } } diff --git a/spec/lib/grafana/client_spec.rb b/spec/lib/grafana/client_spec.rb index 699344e940e..c233d0b8445 100644 --- a/spec/lib/grafana/client_spec.rb +++ b/spec/lib/grafana/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Grafana::Client do +RSpec.describe Grafana::Client do let(:grafana_url) { 'https://grafanatest.com/-/grafana-project' } let(:token) { 'test-token' } diff --git a/spec/lib/grafana/time_window_spec.rb b/spec/lib/grafana/time_window_spec.rb index e70861658ca..9ee65c6cf20 100644 --- a/spec/lib/grafana/time_window_spec.rb +++ b/spec/lib/grafana/time_window_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Grafana::TimeWindow do +RSpec.describe Grafana::TimeWindow do let(:from) { '1552799400000' } let(:to) { '1552828200000' } @@ -32,7 +32,7 @@ describe Grafana::TimeWindow do end end -describe Grafana::RangeWithDefaults do +RSpec.describe Grafana::RangeWithDefaults do let(:from) { Grafana::Timestamp.from_ms_since_epoch('1552799400000') } let(:to) { Grafana::Timestamp.from_ms_since_epoch('1552828200000') } @@ -78,7 +78,7 @@ describe Grafana::RangeWithDefaults do end end -describe Grafana::Timestamp do +RSpec.describe Grafana::Timestamp do let(:timestamp) { Time.at(1552799400) } around do |example| diff --git a/spec/lib/grafana/validator_spec.rb b/spec/lib/grafana/validator_spec.rb index a048a1f3470..b45749ffc95 100644 --- a/spec/lib/grafana/validator_spec.rb +++ b/spec/lib/grafana/validator_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Grafana::Validator do +RSpec.describe Grafana::Validator do let(:grafana_dashboard) { Gitlab::Json.parse(fixture_file('grafana/simplified_dashboard_response.json'), symbolize_names: true) } let(:datasource) { Gitlab::Json.parse(fixture_file('grafana/datasource_response.json'), symbolize_names: true) } let(:panel) { grafana_dashboard[:dashboard][:panels].first } diff --git a/spec/lib/json_web_token/hmac_token_spec.rb b/spec/lib/json_web_token/hmac_token_spec.rb index f2cbc381967..cf7e5c54f45 100644 --- a/spec/lib/json_web_token/hmac_token_spec.rb +++ b/spec/lib/json_web_token/hmac_token_spec.rb @@ -3,7 +3,7 @@ require 'json' require 'timecop' -describe JSONWebToken::HMACToken do +RSpec.describe JSONWebToken::HMACToken do let(:secret) { 'shh secret squirrel' } shared_examples 'a valid, non-expired token' do diff --git a/spec/lib/json_web_token/rsa_token_spec.rb b/spec/lib/json_web_token/rsa_token_spec.rb index 62fddbb97c7..f19471917c2 100644 --- a/spec/lib/json_web_token/rsa_token_spec.rb +++ b/spec/lib/json_web_token/rsa_token_spec.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -describe JSONWebToken::RSAToken do +RSpec.describe JSONWebToken::RSAToken do let(:rsa_key) do OpenSSL::PKey::RSA.new <<-eos.strip_heredoc -----BEGIN RSA PRIVATE KEY----- diff --git a/spec/lib/json_web_token/token_spec.rb b/spec/lib/json_web_token/token_spec.rb index ca587a6ebcd..6fb15ae0a9c 100644 --- a/spec/lib/json_web_token/token_spec.rb +++ b/spec/lib/json_web_token/token_spec.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -describe JSONWebToken::Token do +RSpec.describe JSONWebToken::Token do let(:token) { described_class.new } context 'custom parameters' do diff --git a/spec/lib/kramdown/parser/atlassian_document_format_spec.rb b/spec/lib/kramdown/parser/atlassian_document_format_spec.rb new file mode 100644 index 00000000000..f3559503388 --- /dev/null +++ b/spec/lib/kramdown/parser/atlassian_document_format_spec.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.context Kramdown::Parser::AtlassianDocumentFormat do + let_it_be(:options) { { input: 'AtlassianDocumentFormat', html_tables: true } } + let_it_be(:fixtures_path) { 'lib/kramdown/atlassian_document_format' } + + context 'markdown render' do + shared_examples 'render elements to markdown' do |base_name| + let(:json_file) { "#{base_name}.json" } + let(:markdown_file) { "#{base_name}.md" } + + it "renders #{base_name}" do + source = fixture_file(File.join(fixtures_path, json_file)) + target = fixture_file(File.join(fixtures_path, markdown_file)) + parser = Kramdown::Document.new(source, options) + + expect(parser.to_commonmark).to eq target + end + end + + it_behaves_like 'render elements to markdown', 'blockquote' + it_behaves_like 'render elements to markdown', 'bullet_list' + it_behaves_like 'render elements to markdown', 'code_block' + it_behaves_like 'render elements to markdown', 'emoji' + it_behaves_like 'render elements to markdown', 'hard_break' + it_behaves_like 'render elements to markdown', 'heading' + it_behaves_like 'render elements to markdown', 'inline_card' + it_behaves_like 'render elements to markdown', 'media_group' + it_behaves_like 'render elements to markdown', 'media_single' + it_behaves_like 'render elements to markdown', 'mention' + it_behaves_like 'render elements to markdown', 'ordered_list' + it_behaves_like 'render elements to markdown', 'panel' + it_behaves_like 'render elements to markdown', 'paragraph' + it_behaves_like 'render elements to markdown', 'rule' + it_behaves_like 'render elements to markdown', 'table' + + it_behaves_like 'render elements to markdown', 'strong_em_mark' + it_behaves_like 'render elements to markdown', 'code_mark' + it_behaves_like 'render elements to markdown', 'link_mark' + it_behaves_like 'render elements to markdown', 'strike_sup_sub_mark' + it_behaves_like 'render elements to markdown', 'underline_text_color_mark' + + it_behaves_like 'render elements to markdown', 'complex_document' + + it 'renders header id to html' do + source = fixture_file(File.join(fixtures_path, 'heading.json')) + parser = Kramdown::Document.new(source, options) + + expect(parser.to_html).to include('id="header-2"') + end + + it 'logs an error with invalid json' do + source = fixture_file(File.join(fixtures_path, 'invalid_json.json')) + + expect(Gitlab::AppLogger).to receive(:error).with(/Invalid Atlassian Document Format JSON/) + expect(Gitlab::AppLogger).to receive(:error).with(any_args) + expect { Kramdown::Document.new(source, options) }.to raise_error(::Kramdown::Error, /Invalid Atlassian Document Format JSON/) + end + + it 'logs an error if no valid document node' do + source = fixture_file(File.join(fixtures_path, 'invalid_no_doc.json')) + + expect(Gitlab::AppLogger).to receive(:error).with(/Invalid Atlassian Document Format JSON/) + expect(Gitlab::AppLogger).to receive(:error).with(any_args) + expect { Kramdown::Document.new(source, options) }.to raise_error(::Kramdown::Error, /Invalid Atlassian Document Format JSON/) + end + + it 'invalid node gets ignored' do + source = fixture_file(File.join(fixtures_path, 'invalid_node_type.json')) + parser = Kramdown::Document.new(source, options) + + expect(parser.to_commonmark).to eq "This is a second paragraph\n\n" + end + end +end diff --git a/spec/lib/learn_gitlab_spec.rb b/spec/lib/learn_gitlab_spec.rb new file mode 100644 index 00000000000..abfd82999c3 --- /dev/null +++ b/spec/lib/learn_gitlab_spec.rb @@ -0,0 +1,61 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe LearnGitlab do + let_it_be(:current_user) { create(:user) } + let_it_be(:learn_gitlab_project) { create(:project, name: LearnGitlab::PROJECT_NAME) } + let_it_be(:learn_gitlab_board) { create(:board, project: learn_gitlab_project, name: LearnGitlab::BOARD_NAME) } + let_it_be(:learn_gitlab_label) { create(:label, project: learn_gitlab_project, name: LearnGitlab::LABEL_NAME) } + + before do + learn_gitlab_project.add_developer(current_user) + end + + describe '.available?' do + using RSpec::Parameterized::TableSyntax + + where(:project, :board, :label, :expected_result) do + nil | nil | nil | nil + nil | nil | true | nil + nil | true | nil | nil + nil | true | true | nil + true | nil | nil | nil + true | nil | true | nil + true | true | nil | nil + true | true | true | true + end + + with_them do + before do + allow_next_instance_of(described_class) do |learn_gitlab| + allow(learn_gitlab).to receive(:project).and_return(project) + allow(learn_gitlab).to receive(:board).and_return(board) + allow(learn_gitlab).to receive(:label).and_return(label) + end + end + + subject { described_class.new(current_user).available? } + + it { is_expected.to be expected_result } + end + end + + describe '.project' do + subject { described_class.new(current_user).project } + + it { is_expected.to eq learn_gitlab_project } + end + + describe '.board' do + subject { described_class.new(current_user).board } + + it { is_expected.to eq learn_gitlab_board } + end + + describe '.label' do + subject { described_class.new(current_user).label } + + it { is_expected.to eq learn_gitlab_label } + end +end diff --git a/spec/lib/marginalia_spec.rb b/spec/lib/marginalia_spec.rb index 2f446694083..a920f598c24 100644 --- a/spec/lib/marginalia_spec.rb +++ b/spec/lib/marginalia_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe 'Marginalia spec' do +RSpec.describe 'Marginalia spec' do class MarginaliaTestController < ActionController::Base def first_user User.first diff --git a/spec/lib/mattermost/client_spec.rb b/spec/lib/mattermost/client_spec.rb index 5fe35eb5f93..32755d1103c 100644 --- a/spec/lib/mattermost/client_spec.rb +++ b/spec/lib/mattermost/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Mattermost::Client do +RSpec.describe Mattermost::Client do let(:user) { build(:user) } subject { described_class.new(user) } diff --git a/spec/lib/mattermost/command_spec.rb b/spec/lib/mattermost/command_spec.rb index f8c451a1522..26d1ec32232 100644 --- a/spec/lib/mattermost/command_spec.rb +++ b/spec/lib/mattermost/command_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Mattermost::Command do +RSpec.describe Mattermost::Command do let(:params) { { 'token' => 'token', team_id: 'abc' } } before do diff --git a/spec/lib/mattermost/session_spec.rb b/spec/lib/mattermost/session_spec.rb index ea12bd76c8d..5110d3cdfa3 100644 --- a/spec/lib/mattermost/session_spec.rb +++ b/spec/lib/mattermost/session_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Mattermost::Session, type: :request do +RSpec.describe Mattermost::Session, type: :request do include ExclusiveLeaseHelpers include StubRequests diff --git a/spec/lib/mattermost/team_spec.rb b/spec/lib/mattermost/team_spec.rb index 2823dab67c9..0870114ca28 100644 --- a/spec/lib/mattermost/team_spec.rb +++ b/spec/lib/mattermost/team_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Mattermost::Team do +RSpec.describe Mattermost::Team do before do session = Mattermost::Session.new(nil) session.base_uri = 'http://mattermost.example.com' diff --git a/spec/lib/microsoft_teams/activity_spec.rb b/spec/lib/microsoft_teams/activity_spec.rb index 3fad2437f3e..d1eac7204a6 100644 --- a/spec/lib/microsoft_teams/activity_spec.rb +++ b/spec/lib/microsoft_teams/activity_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe MicrosoftTeams::Activity do +RSpec.describe MicrosoftTeams::Activity do subject { described_class.new(title: 'title', subtitle: 'subtitle', text: 'text', image: 'image') } describe '#prepare' do diff --git a/spec/lib/microsoft_teams/notifier_spec.rb b/spec/lib/microsoft_teams/notifier_spec.rb index 25538db159e..c35d7e8420c 100644 --- a/spec/lib/microsoft_teams/notifier_spec.rb +++ b/spec/lib/microsoft_teams/notifier_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe MicrosoftTeams::Notifier do +RSpec.describe MicrosoftTeams::Notifier do subject { described_class.new(webhook_url) } let(:webhook_url) { 'https://example.gitlab.com/'} diff --git a/spec/lib/object_storage/direct_upload_spec.rb b/spec/lib/object_storage/direct_upload_spec.rb index c3890c72852..1c1455e2456 100644 --- a/spec/lib/object_storage/direct_upload_spec.rb +++ b/spec/lib/object_storage/direct_upload_spec.rb @@ -2,10 +2,11 @@ require 'spec_helper' -describe ObjectStorage::DirectUpload do +RSpec.describe ObjectStorage::DirectUpload do let(:region) { 'us-east-1' } let(:path_style) { false } let(:use_iam_profile) { false } + let(:consolidated_settings) { false } let(:credentials) do { provider: 'AWS', @@ -23,7 +24,7 @@ describe ObjectStorage::DirectUpload do let(:object_name) { 'tmp/uploads/my-file' } let(:maximum_size) { 1.gigabyte } - let(:direct_upload) { described_class.new(credentials, bucket_name, object_name, has_length: has_length, maximum_size: maximum_size) } + let(:direct_upload) { described_class.new(credentials, bucket_name, object_name, has_length: has_length, maximum_size: maximum_size, consolidated_settings: consolidated_settings) } before do Fog.unmock! @@ -60,6 +61,38 @@ describe ObjectStorage::DirectUpload do end end + describe '#get_url' do + subject { described_class.new(credentials, bucket_name, object_name, has_length: true) } + + context 'when AWS is used' do + it 'calls the proper method' do + expect_next_instance_of(::Fog::Storage, credentials) do |connection| + expect(connection).to receive(:get_object_url).once + end + + subject.get_url + end + end + + context 'when Google is used' do + let(:credentials) do + { + provider: 'Google', + google_storage_access_key_id: 'GOOGLE_ACCESS_KEY_ID', + google_storage_secret_access_key: 'GOOGLE_SECRET_ACCESS_KEY' + } + end + + it 'calls the proper method' do + expect_next_instance_of(::Fog::Storage, credentials) do |connection| + expect(connection).to receive(:get_object_https_url).once + end + + subject.get_url + end + end + end + describe '#to_hash' do subject { direct_upload.to_hash } @@ -109,6 +142,14 @@ describe ObjectStorage::DirectUpload do expect(subject[:UseWorkhorseClient]).to eq(use_iam_profile) end end + + context 'when consolidated settings are used' do + let(:consolidated_settings) { true } + + it 'enables the Workhorse client' do + expect(subject[:UseWorkhorseClient]).to be true + end + end end shared_examples 'a valid Google upload' do diff --git a/spec/lib/omni_auth/strategies/jwt_spec.rb b/spec/lib/omni_auth/strategies/jwt_spec.rb index 302329cf198..0f4528d4fbe 100644 --- a/spec/lib/omni_auth/strategies/jwt_spec.rb +++ b/spec/lib/omni_auth/strategies/jwt_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe OmniAuth::Strategies::Jwt do +RSpec.describe OmniAuth::Strategies::Jwt do include Rack::Test::Methods include DeviseHelpers diff --git a/spec/lib/pager_duty/webhook_payload_parser_spec.rb b/spec/lib/pager_duty/webhook_payload_parser_spec.rb new file mode 100644 index 00000000000..0010165318d --- /dev/null +++ b/spec/lib/pager_duty/webhook_payload_parser_spec.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +require 'fast_spec_helper' + +RSpec.describe PagerDuty::WebhookPayloadParser do + describe '.call' do + let(:fixture_file) do + File.read(File.join(File.dirname(__FILE__), '../../fixtures/pager_duty/webhook_incident_trigger.json')) + end + + subject(:parse) { described_class.call(payload) } + + context 'when payload is a correct PagerDuty payload' do + let(:payload) { Gitlab::Json.parse(fixture_file) } + + it 'returns parsed payload' do + is_expected.to eq( + [ + { + 'event' => 'incident.trigger', + 'incident' => { + 'url' => 'https://webdemo.pagerduty.com/incidents/PRORDTY', + 'incident_number' => 33, + 'title' => 'My new incident', + 'status' => 'triggered', + 'created_at' => '2017-09-26T15:14:36Z', + 'urgency' => 'high', + 'incident_key' => nil, + 'assignees' => [{ + 'summary' => 'Laura Haley', + 'url' => 'https://webdemo.pagerduty.com/users/P553OPV' + }], + 'impacted_services' => [{ + 'summary' => 'Production XDB Cluster', + 'url' => 'https://webdemo.pagerduty.com/services/PN49J75' + }] + } + } + ] + ) + end + + context 'when assignments summary and html_url are blank' do + before do + payload['messages'].each do |m| + m['incident']['assignments'] = [{ 'assignee' => { 'summary' => '', 'html_url' => '' } }] + end + end + + it 'returns parsed payload with blank assignees' do + assignees = parse.map { |events| events['incident'].slice('assignees') } + + expect(assignees).to eq([{ 'assignees' => [] }]) + end + end + + context 'when impacted_services summary and html_url are blank' do + before do + payload['messages'].each do |m| + m['incident']['impacted_services'] = [{ 'summary' => '', 'html_url' => '' }] + end + end + + it 'returns parsed payload with blank assignees' do + assignees = parse.map { |events| events['incident'].slice('impacted_services') } + + expect(assignees).to eq([{ 'impacted_services' => [] }]) + end + end + end + + context 'when payload has no incidents' do + let(:payload) { { 'messages' => [{ 'event' => 'incident.trigger' }] } } + + it 'returns payload with blank incidents' do + is_expected.to eq([{ 'event' => 'incident.trigger', 'incident' => {} }]) + end + end + end +end diff --git a/spec/lib/peek/views/bullet_detailed_spec.rb b/spec/lib/peek/views/bullet_detailed_spec.rb index a482cadc7db..ec2f798a320 100644 --- a/spec/lib/peek/views/bullet_detailed_spec.rb +++ b/spec/lib/peek/views/bullet_detailed_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Peek::Views::BulletDetailed do +RSpec.describe Peek::Views::BulletDetailed do subject { described_class.new } before do diff --git a/spec/lib/peek/views/detailed_view_spec.rb b/spec/lib/peek/views/detailed_view_spec.rb index d8660a55ea9..8d6d9a829ef 100644 --- a/spec/lib/peek/views/detailed_view_spec.rb +++ b/spec/lib/peek/views/detailed_view_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Peek::Views::DetailedView, :request_store do +RSpec.describe Peek::Views::DetailedView, :request_store do context 'when a class defines thresholds' do let(:threshold_view) do Class.new(described_class) do diff --git a/spec/lib/peek/views/redis_detailed_spec.rb b/spec/lib/peek/views/redis_detailed_spec.rb index a270c006a43..a757af50dcb 100644 --- a/spec/lib/peek/views/redis_detailed_spec.rb +++ b/spec/lib/peek/views/redis_detailed_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Peek::Views::RedisDetailed, :request_store do +RSpec.describe Peek::Views::RedisDetailed, :request_store do subject { described_class.new } using RSpec::Parameterized::TableSyntax diff --git a/spec/lib/peek/views/rugged_spec.rb b/spec/lib/peek/views/rugged_spec.rb index 39968afed39..31418b5fc81 100644 --- a/spec/lib/peek/views/rugged_spec.rb +++ b/spec/lib/peek/views/rugged_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Peek::Views::Rugged, :request_store do +RSpec.describe Peek::Views::Rugged, :request_store do subject { described_class.new } let(:project) { create(:project) } diff --git a/spec/lib/product_analytics/event_params_spec.rb b/spec/lib/product_analytics/event_params_spec.rb new file mode 100644 index 00000000000..d6c098599d6 --- /dev/null +++ b/spec/lib/product_analytics/event_params_spec.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ProductAnalytics::EventParams do + describe '.parse_event_params' do + subject { described_class.parse_event_params(raw_event) } + + let(:raw_event) { Gitlab::Json.parse(fixture_file('product_analytics/event.json')) } + + it 'extracts all params from raw event' do + expected_params = { + project_id: '1', + platform: 'web', + name_tracker: 'sp', + v_tracker: 'js-2.14.0', + event_id: 'fbf14096-74ee-47e4-883c-8a0d6cb72e37', + domain_userid: '79543c31-cfc3-4479-a737-fafb9333c8ba', + domain_sessionid: '54f6d3f3-f4f9-4fdc-87e0-a2c775234c1b', + domain_sessionidx: 4, + page_url: 'http://example.com/products/1', + page_referrer: 'http://example.com/products/1', + br_lang: 'en-US', + br_cookies: true, + os_timezone: 'America/Los_Angeles', + doc_charset: 'UTF-8' + } + + expect(subject).to include(expected_params) + end + end + + describe '.has_required_params?' do + subject { described_class.has_required_params?(params) } + + context 'aid and eid are present' do + let(:params) { { 'aid' => 1, 'eid' => 2 } } + + it { expect(subject).to be_truthy } + end + + context 'aid and eid are missing' do + let(:params) { {} } + + it { expect(subject).to be_falsey } + end + + context 'eid is missing' do + let(:params) { { 'aid' => 1 } } + + it { expect(subject).to be_falsey } + end + end +end diff --git a/spec/lib/prometheus/cleanup_multiproc_dir_service_spec.rb b/spec/lib/prometheus/cleanup_multiproc_dir_service_spec.rb index c7302a1a656..db77a5d42d8 100644 --- a/spec/lib/prometheus/cleanup_multiproc_dir_service_spec.rb +++ b/spec/lib/prometheus/cleanup_multiproc_dir_service_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Prometheus::CleanupMultiprocDirService do +RSpec.describe Prometheus::CleanupMultiprocDirService do describe '.call' do subject { described_class.new.execute } diff --git a/spec/lib/prometheus/pid_provider_spec.rb b/spec/lib/prometheus/pid_provider_spec.rb index 5a17f25f144..f1d7f2ffff5 100644 --- a/spec/lib/prometheus/pid_provider_spec.rb +++ b/spec/lib/prometheus/pid_provider_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Prometheus::PidProvider do +RSpec.describe Prometheus::PidProvider do describe '.worker_id' do subject { described_class.worker_id } diff --git a/spec/lib/quality/helm3_client_spec.rb b/spec/lib/quality/helm3_client_spec.rb deleted file mode 100644 index 1144ee9369d..00000000000 --- a/spec/lib/quality/helm3_client_spec.rb +++ /dev/null @@ -1,133 +0,0 @@ -# frozen_string_literal: true - -require 'fast_spec_helper' - -RSpec.describe Quality::Helm3Client do - let(:namespace) { 'review-apps-ee' } - let(:release_name) { 'my-release' } - let(:raw_helm_list_page1) do - <<~OUTPUT - [ - {"name":"review-qa-60-reor-1mugd1","namespace":"#{namespace}","revision":1,"updated":"2020-04-03 17:27:10.245952 +0800 +08","status":"failed","chart":"gitlab-1.1.3","app_version":"12.9.2"}, - {"name":"review-7846-fix-s-261vd6","namespace":"#{namespace}","revision":2,"updated":"2020-04-02 17:27:12.245952 +0800 +08","status":"deployed","chart":"gitlab-1.1.3","app_version":"12.9.2"}, - {"name":"review-7867-snowp-lzo3iy","namespace":"#{namespace}","revision":1,"updated":"2020-04-02 15:27:12.245952 +0800 +08","status":"deployed","chart":"gitlab-1.1.3","app_version":"12.9.1"}, - {"name":"review-6709-group-2pzeec","namespace":"#{namespace}","revision":2,"updated":"2020-04-01 21:27:12.245952 +0800 +08","status":"failed","chart":"gitlab-1.1.3","app_version":"12.9.1"} - ] - OUTPUT - end - let(:raw_helm_list_page2) do - <<~OUTPUT - [ - {"name":"review-6709-group-t40qbv","namespace":"#{namespace}","revision":2,"updated":"2020-04-01 11:27:12.245952 +0800 +08","status":"deployed","chart":"gitlab-1.1.3","app_version":"12.9.1"} - ] - OUTPUT - end - let(:raw_helm_list_empty) do - <<~OUTPUT - [] - OUTPUT - end - - subject { described_class.new(namespace: namespace) } - - describe '#releases' do - it 'raises an error if the Helm command fails' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm list --namespace "#{namespace}" --max 256 --offset 0 --output json)]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: false))) - - expect { subject.releases.to_a }.to raise_error(described_class::CommandFailedError) - end - - it 'calls helm list with default arguments' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm list --namespace "#{namespace}" --max 256 --offset 0 --output json)]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - subject.releases.to_a - end - - it 'calls helm list with extra arguments' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm list --namespace "#{namespace}" --max 256 --offset 0 --output json --deployed)]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - subject.releases(args: ['--deployed']).to_a - end - - it 'returns a list of Release objects' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm list --namespace "#{namespace}" --max 256 --offset 0 --output json --deployed)]) - .and_return(Gitlab::Popen::Result.new([], raw_helm_list_page2, '', double(success?: true))) - expect(Gitlab::Popen).to receive(:popen_with_detail).ordered - .and_return(Gitlab::Popen::Result.new([], raw_helm_list_empty, '', double(success?: true))) - - releases = subject.releases(args: ['--deployed']).to_a - - expect(releases.size).to eq(1) - expect(releases[0]).to have_attributes( - name: 'review-6709-group-t40qbv', - revision: 2, - last_update: Time.parse('2020-04-01 11:27:12.245952 +0800 +08'), - status: 'deployed', - chart: 'gitlab-1.1.3', - app_version: '12.9.1', - namespace: namespace - ) - end - - it 'automatically paginates releases' do - expect(Gitlab::Popen).to receive(:popen_with_detail).ordered - .with([%(helm list --namespace "#{namespace}" --max 256 --offset 0 --output json)]) - .and_return(Gitlab::Popen::Result.new([], raw_helm_list_page1, '', double(success?: true))) - expect(Gitlab::Popen).to receive(:popen_with_detail).ordered - .with([%(helm list --namespace "#{namespace}" --max 256 --offset 256 --output json)]) - .and_return(Gitlab::Popen::Result.new([], raw_helm_list_page2, '', double(success?: true))) - expect(Gitlab::Popen).to receive(:popen_with_detail).ordered - .with([%(helm list --namespace "#{namespace}" --max 256 --offset 512 --output json)]) - .and_return(Gitlab::Popen::Result.new([], raw_helm_list_empty, '', double(success?: true))) - releases = subject.releases.to_a - - expect(releases.size).to eq(5) - expect(releases.last.name).to eq('review-6709-group-t40qbv') - end - end - - describe '#delete' do - it 'raises an error if the Helm command fails' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm uninstall --namespace "#{namespace}" #{release_name})]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: false))) - - expect { subject.delete(release_name: release_name) }.to raise_error(described_class::CommandFailedError) - end - - it 'calls helm uninstall with default arguments' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm uninstall --namespace "#{namespace}" #{release_name})]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - expect(subject.delete(release_name: release_name)).to eq('') - end - - context 'with multiple release names' do - let(:release_name) { %w[my-release my-release-2] } - - it 'raises an error if the Helm command fails' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm uninstall --namespace "#{namespace}" #{release_name.join(' ')})]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: false))) - - expect { subject.delete(release_name: release_name) }.to raise_error(described_class::CommandFailedError) - end - - it 'calls helm uninstall with multiple release names' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(helm uninstall --namespace "#{namespace}" #{release_name.join(' ')})]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - expect(subject.delete(release_name: release_name)).to eq('') - end - end - end -end diff --git a/spec/lib/quality/kubernetes_client_spec.rb b/spec/lib/quality/kubernetes_client_spec.rb deleted file mode 100644 index 1cfee5200f3..00000000000 --- a/spec/lib/quality/kubernetes_client_spec.rb +++ /dev/null @@ -1,111 +0,0 @@ -# frozen_string_literal: true - -require 'fast_spec_helper' - -RSpec.describe Quality::KubernetesClient do - let(:namespace) { 'review-apps-ee' } - let(:release_name) { 'my-release' } - let(:pod_for_release) { "pod-my-release-abcd" } - let(:raw_resource_names_str) { "NAME\nfoo\n#{pod_for_release}\nbar" } - let(:raw_resource_names) { raw_resource_names_str.lines.map(&:strip) } - - subject { described_class.new(namespace: namespace) } - - describe 'RESOURCE_LIST' do - it 'returns the correct list of resources separated by commas' do - expect(described_class::RESOURCE_LIST).to eq('ingress,svc,pdb,hpa,deploy,statefulset,job,pod,secret,configmap,pvc,secret,clusterrole,clusterrolebinding,role,rolebinding,sa,crd') - end - end - - describe '#cleanup' do - before do - allow(subject).to receive(:raw_resource_names).and_return(raw_resource_names) - end - - it 'raises an error if the Kubernetes command fails' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with(["kubectl delete #{described_class::RESOURCE_LIST} " + - %(--namespace "#{namespace}" --now --ignore-not-found --include-uninitialized --wait=true -l release="#{release_name}")]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: false))) - - expect { subject.cleanup(release_name: release_name) }.to raise_error(described_class::CommandFailedError) - end - - it 'calls kubectl with the correct arguments' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with(["kubectl delete #{described_class::RESOURCE_LIST} " + - %(--namespace "#{namespace}" --now --ignore-not-found --include-uninitialized --wait=true -l release="#{release_name}")]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(kubectl delete --namespace "#{namespace}" --ignore-not-found #{pod_for_release})]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - # We're not verifying the output here, just silencing it - expect { subject.cleanup(release_name: release_name) }.to output.to_stdout - end - - context 'with multiple releases' do - let(:release_name) { %w[my-release my-release-2] } - - it 'raises an error if the Kubernetes command fails' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with(["kubectl delete #{described_class::RESOURCE_LIST} " + - %(--namespace "#{namespace}" --now --ignore-not-found --include-uninitialized --wait=true -l 'release in (#{release_name.join(', ')})')]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: false))) - - expect { subject.cleanup(release_name: release_name) }.to raise_error(described_class::CommandFailedError) - end - - it 'calls kubectl with the correct arguments' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with(["kubectl delete #{described_class::RESOURCE_LIST} " + - %(--namespace "#{namespace}" --now --ignore-not-found --include-uninitialized --wait=true -l 'release in (#{release_name.join(', ')})')]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(kubectl delete --namespace "#{namespace}" --ignore-not-found #{pod_for_release})]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - # We're not verifying the output here, just silencing it - expect { subject.cleanup(release_name: release_name) }.to output.to_stdout - end - end - - context 'with `wait: false`' do - it 'raises an error if the Kubernetes command fails' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with(["kubectl delete #{described_class::RESOURCE_LIST} " + - %(--namespace "#{namespace}" --now --ignore-not-found --include-uninitialized --wait=false -l release="#{release_name}")]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: false))) - - expect { subject.cleanup(release_name: release_name, wait: false) }.to raise_error(described_class::CommandFailedError) - end - - it 'calls kubectl with the correct arguments' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with(["kubectl delete #{described_class::RESOURCE_LIST} " + - %(--namespace "#{namespace}" --now --ignore-not-found --include-uninitialized --wait=false -l release="#{release_name}")]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with([%(kubectl delete --namespace "#{namespace}" --ignore-not-found #{pod_for_release})]) - .and_return(Gitlab::Popen::Result.new([], '', '', double(success?: true))) - - # We're not verifying the output here, just silencing it - expect { subject.cleanup(release_name: release_name, wait: false) }.to output.to_stdout - end - end - end - - describe '#raw_resource_names' do - it 'calls kubectl to retrieve the resource names' do - expect(Gitlab::Popen).to receive(:popen_with_detail) - .with(["kubectl get #{described_class::RESOURCE_LIST} " + - %(--namespace "#{namespace}" -o name)]) - .and_return(Gitlab::Popen::Result.new([], raw_resource_names_str, '', double(success?: true))) - - expect(subject.__send__(:raw_resource_names)).to eq(raw_resource_names) - end - end -end diff --git a/spec/lib/quality/test_level_spec.rb b/spec/lib/quality/test_level_spec.rb index ad29c80b07a..0b113e8b63a 100644 --- a/spec/lib/quality/test_level_spec.rb +++ b/spec/lib/quality/test_level_spec.rb @@ -28,7 +28,7 @@ RSpec.describe Quality::TestLevel do context 'when level is migration' do it 'returns a pattern' do expect(subject.pattern(:migration)) - .to eq("spec/{migrations}{,/**/}*_spec.rb") + .to eq("spec/{migrations,lib/gitlab/background_migration,lib/ee/gitlab/background_migration}{,/**/}*_spec.rb") end end @@ -96,7 +96,7 @@ RSpec.describe Quality::TestLevel do context 'when level is migration' do it 'returns a regexp' do expect(subject.regexp(:migration)) - .to eq(%r{spec/(migrations)}) + .to eq(%r{spec/(migrations|lib/gitlab/background_migration|lib/ee/gitlab/background_migration)}) end end diff --git a/spec/lib/rspec_flaky/config_spec.rb b/spec/lib/rspec_flaky/config_spec.rb index 13b2219267b..6b148599b67 100644 --- a/spec/lib/rspec_flaky/config_spec.rb +++ b/spec/lib/rspec_flaky/config_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe RspecFlaky::Config, :aggregate_failures do +RSpec.describe RspecFlaky::Config, :aggregate_failures do before do # Stub these env variables otherwise specs don't behave the same on the CI stub_env('FLAKY_RSPEC_GENERATE_REPORT', nil) diff --git a/spec/lib/rspec_flaky/example_spec.rb b/spec/lib/rspec_flaky/example_spec.rb index 4679dd818db..aaf5ddc6f74 100644 --- a/spec/lib/rspec_flaky/example_spec.rb +++ b/spec/lib/rspec_flaky/example_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe RspecFlaky::Example do +RSpec.describe RspecFlaky::Example do let(:example_attrs) do { id: 'spec/foo/bar_spec.rb:2', diff --git a/spec/lib/rspec_flaky/flaky_example_spec.rb b/spec/lib/rspec_flaky/flaky_example_spec.rb index d4a1d6c882a..8ac323475d6 100644 --- a/spec/lib/rspec_flaky/flaky_example_spec.rb +++ b/spec/lib/rspec_flaky/flaky_example_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe RspecFlaky::FlakyExample, :aggregate_failures do +RSpec.describe RspecFlaky::FlakyExample, :aggregate_failures do let(:flaky_example_attrs) do { example_id: 'spec/foo/bar_spec.rb:2', diff --git a/spec/lib/rspec_flaky/flaky_examples_collection_spec.rb b/spec/lib/rspec_flaky/flaky_examples_collection_spec.rb index 2e224cda61b..5718d8211af 100644 --- a/spec/lib/rspec_flaky/flaky_examples_collection_spec.rb +++ b/spec/lib/rspec_flaky/flaky_examples_collection_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe RspecFlaky::FlakyExamplesCollection, :aggregate_failures do +RSpec.describe RspecFlaky::FlakyExamplesCollection, :aggregate_failures do let(:collection_hash) do { a: { example_id: 'spec/foo/bar_spec.rb:2' }, diff --git a/spec/lib/rspec_flaky/listener_spec.rb b/spec/lib/rspec_flaky/listener_spec.rb index 44b8d99b74f..2438ae171d3 100644 --- a/spec/lib/rspec_flaky/listener_spec.rb +++ b/spec/lib/rspec_flaky/listener_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe RspecFlaky::Listener, :aggregate_failures do +RSpec.describe RspecFlaky::Listener, :aggregate_failures do let(:already_flaky_example_uid) { '6e869794f4cfd2badd93eb68719371d1' } let(:suite_flaky_example_report) do { diff --git a/spec/lib/rspec_flaky/report_spec.rb b/spec/lib/rspec_flaky/report_spec.rb index 37330f39e1c..e735329a8a3 100644 --- a/spec/lib/rspec_flaky/report_spec.rb +++ b/spec/lib/rspec_flaky/report_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe RspecFlaky::Report, :aggregate_failures do +RSpec.describe RspecFlaky::Report, :aggregate_failures do let(:thirty_one_days) { 3600 * 24 * 31 } let(:collection_hash) do { diff --git a/spec/lib/safe_zip/entry_spec.rb b/spec/lib/safe_zip/entry_spec.rb index be3d46917ee..9929b8073a0 100644 --- a/spec/lib/safe_zip/entry_spec.rb +++ b/spec/lib/safe_zip/entry_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe SafeZip::Entry do +RSpec.describe SafeZip::Entry do let(:target_path) { Dir.mktmpdir('safe-zip') } let(:directories) { %w(public folder/with/subfolder) } let(:params) { SafeZip::ExtractParams.new(directories: directories, to: target_path) } diff --git a/spec/lib/safe_zip/extract_params_spec.rb b/spec/lib/safe_zip/extract_params_spec.rb index f66d3de89ee..880c4358663 100644 --- a/spec/lib/safe_zip/extract_params_spec.rb +++ b/spec/lib/safe_zip/extract_params_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe SafeZip::ExtractParams do +RSpec.describe SafeZip::ExtractParams do let(:target_path) { Dir.mktmpdir("safe-zip") } let(:params) { described_class.new(directories: directories, to: target_path) } let(:directories) { %w(public folder/with/subfolder) } diff --git a/spec/lib/safe_zip/extract_spec.rb b/spec/lib/safe_zip/extract_spec.rb index d388135c3fb..30b7e1cdd2c 100644 --- a/spec/lib/safe_zip/extract_spec.rb +++ b/spec/lib/safe_zip/extract_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe SafeZip::Extract do +RSpec.describe SafeZip::Extract do let(:target_path) { Dir.mktmpdir('safe-zip') } let(:directories) { %w(public) } let(:object) { described_class.new(archive) } diff --git a/spec/lib/sentry/api_urls_spec.rb b/spec/lib/sentry/api_urls_spec.rb index 78455f8d51f..d56b4397e1c 100644 --- a/spec/lib/sentry/api_urls_spec.rb +++ b/spec/lib/sentry/api_urls_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Sentry::ApiUrls do +RSpec.describe Sentry::ApiUrls do let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project/' } let(:token) { 'test-token' } let(:issue_id) { '123456' } diff --git a/spec/lib/sentry/client/event_spec.rb b/spec/lib/sentry/client/event_spec.rb index 58891895bfa..af1e28d09bb 100644 --- a/spec/lib/sentry/client/event_spec.rb +++ b/spec/lib/sentry/client/event_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Sentry::Client do +RSpec.describe Sentry::Client do include SentryClientHelpers let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' } diff --git a/spec/lib/sentry/client/issue_link_spec.rb b/spec/lib/sentry/client/issue_link_spec.rb index 293937f6100..fe3abe7cb23 100644 --- a/spec/lib/sentry/client/issue_link_spec.rb +++ b/spec/lib/sentry/client/issue_link_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Sentry::Client::IssueLink do +RSpec.describe Sentry::Client::IssueLink do include SentryClientHelpers let_it_be(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' } diff --git a/spec/lib/sentry/client/issue_spec.rb b/spec/lib/sentry/client/issue_spec.rb index b683ad6d4a9..a6279aeadd2 100644 --- a/spec/lib/sentry/client/issue_spec.rb +++ b/spec/lib/sentry/client/issue_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Sentry::Client::Issue do +RSpec.describe Sentry::Client::Issue do include SentryClientHelpers let(:token) { 'test-token' } @@ -234,6 +234,7 @@ describe Sentry::Client::Issue do :first_release_short_version | [:firstRelease, :shortVersion] :last_release_short_version | [:lastRelease, :shortVersion] :first_release_version | [:firstRelease, :version] + :last_release_version | [:lastRelease, :version] end with_them do diff --git a/spec/lib/sentry/client/projects_spec.rb b/spec/lib/sentry/client/projects_spec.rb index 1b5bbb8f81a..ea2c5ccb81e 100644 --- a/spec/lib/sentry/client/projects_spec.rb +++ b/spec/lib/sentry/client/projects_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Sentry::Client::Projects do +RSpec.describe Sentry::Client::Projects do include SentryClientHelpers let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' } diff --git a/spec/lib/sentry/client/repo_spec.rb b/spec/lib/sentry/client/repo_spec.rb index 524dca8dcf6..956c0b6eee1 100644 --- a/spec/lib/sentry/client/repo_spec.rb +++ b/spec/lib/sentry/client/repo_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Sentry::Client::Repo do +RSpec.describe Sentry::Client::Repo do include SentryClientHelpers let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' } diff --git a/spec/lib/sentry/client_spec.rb b/spec/lib/sentry/client_spec.rb index e2da4564ca1..cddcb6e98fa 100644 --- a/spec/lib/sentry/client_spec.rb +++ b/spec/lib/sentry/client_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe Sentry::Client do +RSpec.describe Sentry::Client do let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' } let(:token) { 'test-token' } diff --git a/spec/lib/sentry/pagination_parser_spec.rb b/spec/lib/sentry/pagination_parser_spec.rb index 1be6f9f4163..c4ed24827bb 100644 --- a/spec/lib/sentry/pagination_parser_spec.rb +++ b/spec/lib/sentry/pagination_parser_spec.rb @@ -1,11 +1,8 @@ # frozen_string_literal: true require 'fast_spec_helper' -require 'support/helpers/fixture_helpers' - -describe Sentry::PaginationParser do - include FixtureHelpers +RSpec.describe Sentry::PaginationParser do describe '.parse' do subject { described_class.parse(headers) } diff --git a/spec/lib/serializers/json_spec.rb b/spec/lib/serializers/json_spec.rb index dfe85d3f362..7054f98a719 100644 --- a/spec/lib/serializers/json_spec.rb +++ b/spec/lib/serializers/json_spec.rb @@ -2,7 +2,7 @@ require 'fast_spec_helper' -describe Serializers::JSON do +RSpec.describe Serializers::JSON do describe '.dump' do let(:obj) { { key: "value" } } diff --git a/spec/lib/system_check/app/authorized_keys_permission_check_spec.rb b/spec/lib/system_check/app/authorized_keys_permission_check_spec.rb index 1a8123c3f0a..a5a3105c125 100644 --- a/spec/lib/system_check/app/authorized_keys_permission_check_spec.rb +++ b/spec/lib/system_check/app/authorized_keys_permission_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe SystemCheck::App::AuthorizedKeysPermissionCheck do +RSpec.describe SystemCheck::App::AuthorizedKeysPermissionCheck do subject(:system_check) { described_class.new } describe '#skip?' do diff --git a/spec/lib/system_check/app/git_user_default_ssh_config_check_spec.rb b/spec/lib/system_check/app/git_user_default_ssh_config_check_spec.rb index f132f608ab6..2c996635c36 100644 --- a/spec/lib/system_check/app/git_user_default_ssh_config_check_spec.rb +++ b/spec/lib/system_check/app/git_user_default_ssh_config_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe SystemCheck::App::GitUserDefaultSSHConfigCheck do +RSpec.describe SystemCheck::App::GitUserDefaultSSHConfigCheck do let(:username) { '_this_user_will_not_exist_unless_it_is_stubbed' } let(:base_dir) { Dir.mktmpdir } let(:home_dir) { File.join(base_dir, "/var/lib/#{username}") } diff --git a/spec/lib/system_check/app/hashed_storage_all_projects_check_spec.rb b/spec/lib/system_check/app/hashed_storage_all_projects_check_spec.rb index e5e7f6a4450..14bf9d61ab5 100644 --- a/spec/lib/system_check/app/hashed_storage_all_projects_check_spec.rb +++ b/spec/lib/system_check/app/hashed_storage_all_projects_check_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rake_helper' -describe SystemCheck::App::HashedStorageAllProjectsCheck do +RSpec.describe SystemCheck::App::HashedStorageAllProjectsCheck do before do silence_output end diff --git a/spec/lib/system_check/app/hashed_storage_enabled_check_spec.rb b/spec/lib/system_check/app/hashed_storage_enabled_check_spec.rb index d5a0014b791..32a2f409858 100644 --- a/spec/lib/system_check/app/hashed_storage_enabled_check_spec.rb +++ b/spec/lib/system_check/app/hashed_storage_enabled_check_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rake_helper' -describe SystemCheck::App::HashedStorageEnabledCheck do +RSpec.describe SystemCheck::App::HashedStorageEnabledCheck do before do silence_output end diff --git a/spec/lib/system_check/base_check_spec.rb b/spec/lib/system_check/base_check_spec.rb index ccb7b483bdc..59b2fc519ae 100644 --- a/spec/lib/system_check/base_check_spec.rb +++ b/spec/lib/system_check/base_check_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe SystemCheck::BaseCheck do +RSpec.describe SystemCheck::BaseCheck do context 'helpers on instance level' do it 'responds to SystemCheck::Helpers methods' do expect(subject).to respond_to :fix_and_rerun, :for_more_information, :see_installation_guide_section, diff --git a/spec/lib/system_check/orphans/namespace_check_spec.rb b/spec/lib/system_check/orphans/namespace_check_spec.rb index f7491e40438..795dfde9029 100644 --- a/spec/lib/system_check/orphans/namespace_check_spec.rb +++ b/spec/lib/system_check/orphans/namespace_check_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rake_helper' -describe SystemCheck::Orphans::NamespaceCheck do +RSpec.describe SystemCheck::Orphans::NamespaceCheck do let(:storages) { Gitlab.config.repositories.storages.reject { |key, _| key.eql? 'broken' } } before do diff --git a/spec/lib/system_check/orphans/repository_check_spec.rb b/spec/lib/system_check/orphans/repository_check_spec.rb index a5e06f30e75..2ab30f4802d 100644 --- a/spec/lib/system_check/orphans/repository_check_spec.rb +++ b/spec/lib/system_check/orphans/repository_check_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rake_helper' -describe SystemCheck::Orphans::RepositoryCheck do +RSpec.describe SystemCheck::Orphans::RepositoryCheck do let(:storages) { Gitlab.config.repositories.storages.reject { |key, _| key.eql? 'broken' } } before do diff --git a/spec/lib/system_check/simple_executor_spec.rb b/spec/lib/system_check/simple_executor_spec.rb index 58f3a7df197..c9a09d86e32 100644 --- a/spec/lib/system_check/simple_executor_spec.rb +++ b/spec/lib/system_check/simple_executor_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rake_helper' -describe SystemCheck::SimpleExecutor do +RSpec.describe SystemCheck::SimpleExecutor do before do stub_const('SimpleCheck', Class.new(SystemCheck::BaseCheck)) stub_const('OtherCheck', Class.new(SystemCheck::BaseCheck)) diff --git a/spec/lib/system_check_spec.rb b/spec/lib/system_check_spec.rb index da1916455ba..5ddb2741c4a 100644 --- a/spec/lib/system_check_spec.rb +++ b/spec/lib/system_check_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rake_helper' -describe SystemCheck do +RSpec.describe SystemCheck do before do stub_const('SimpleCheck', Class.new(SystemCheck::BaseCheck)) stub_const('OtherCheck', Class.new(SystemCheck::BaseCheck)) diff --git a/spec/lib/uploaded_file_spec.rb b/spec/lib/uploaded_file_spec.rb index 39055a2479f..5ff46193b4f 100644 --- a/spec/lib/uploaded_file_spec.rb +++ b/spec/lib/uploaded_file_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe UploadedFile do +RSpec.describe UploadedFile do let(:temp_dir) { Dir.tmpdir } let(:temp_file) { Tempfile.new(%w[test test], temp_dir) } |