INSTRUCTION
stringlengths
202
35.5k
RESPONSE
stringlengths
75
161k
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups class CreateService < Groups::BaseService def initialize(user, params = {}) @current_user = user @params = params.dup @chat_team = @params.delete(:create_chat_team) @create_event = @params.delete(:create_event) end def execute remove_unallowed_params set_visibility_level @group = Group.new(params.except(*::NamespaceSetting.allowed_namespace_settings_params)) @group.build_namespace_settings handle_namespace_settings after_build_hook(@group, params) inherit_group_shared_runners_settings unless can_use_visibility_level? && can_create_group? return @group end @group.name ||= @group.path.dup if create_chat_team? response = ::Mattermost::CreateTeamService.new(@group, current_user).execute return @group if @group.errors.any? @group.build_chat_team(name: response['name'], team_id: response['id']) end Gitlab::Database::QueryAnalyzers::PreventCrossDatabaseModification.temporary_ignore_tables_in_transaction( %w[routes redirect_routes], url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/424281' ) do Group.transaction do if @group.save @group.add_owner(current_user) Integration.create_from_active_default_integrations(@group, :group_id) end end end after_create_hook @group end private attr_reader :create_event def after_build_hook(group, params) # overridden in EE end def after_create_hook # overridden in EE end def remove_unallowed_params unless can?(current_user, :create_group_with_default_branch_protection) params.delete(:default_branch_protection) params.delete(:default_branch_protection_defaults) end params.delete(:allow_mfa_for_subgroups) end def create_chat_team? Gitlab.config.mattermost.enabled && @chat_team && group.chat_team.nil? end def can_create_group? if @group.subgroup? unless can?(current_user, :create_subgroup, @group.parent) @group.parent = nil @group.errors.add(:parent_id, s_('CreateGroup|You don’t have permission to create a subgroup in this group.')) return false end else unless can?(current_user, :create_group) @group.errors.add(:base, s_('CreateGroup|You don’t have permission to create groups.')) return false end end true end def can_use_visibility_level? unless Gitlab::VisibilityLevel.allowed_for?(current_user, visibility_level) deny_visibility_level(@group) return false end true end def set_visibility_level return if visibility_level.present? params[:visibility_level] = Gitlab::CurrentSettings.current_application_settings.default_group_visibility end def inherit_group_shared_runners_settings return unless @group.parent @group.shared_runners_enabled = @group.parent.shared_runners_enabled @group.allow_descendants_override_disabled_shared_runners = @group.parent.allow_descendants_override_disabled_shared_runners end end end Groups::CreateService.prepend_mod_with('Groups::CreateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::CreateService, '#execute', feature_category: :groups_and_projects do let!(:user) { create(:user) } let!(:group_params) { { path: "group_path", visibility_level: Gitlab::VisibilityLevel::PUBLIC } } subject { service.execute } shared_examples 'has sync-ed traversal_ids' do specify { expect(subject.reload.traversal_ids).to eq([subject.parent&.traversal_ids, subject.id].flatten.compact) } end describe 'visibility level restrictions' do let!(:service) { described_class.new(user, group_params) } context "create groups without restricted visibility level" do it { is_expected.to be_persisted } end context "cannot create group with restricted visibility level" do before do allow_any_instance_of(ApplicationSetting).to receive(:restricted_visibility_levels).and_return([Gitlab::VisibilityLevel::PUBLIC]) end it { is_expected.not_to be_persisted } end end context 'when `setup_for_company:true` is passed' do let(:params) { group_params.merge(setup_for_company: true) } let(:service) { described_class.new(user, params) } let(:created_group) { service.execute } it 'creates group with the specified setup_for_company' do expect(created_group.setup_for_company).to eq(true) end end context 'creating a group with `default_branch_protection` attribute' do let(:params) { group_params.merge(default_branch_protection: Gitlab::Access::PROTECTION_NONE) } let(:service) { described_class.new(user, params) } let(:created_group) { service.execute } context 'for users who have the ability to create a group with `default_branch_protection`' do it 'creates group with the specified branch protection level' do expect(created_group.default_branch_protection).to eq(Gitlab::Access::PROTECTION_NONE) end end context 'for users who do not have the ability to create a group with `default_branch_protection`' do it 'does not create the group with the specified branch protection level' do allow(Ability).to receive(:allowed?).and_call_original allow(Ability).to receive(:allowed?).with(user, :create_group_with_default_branch_protection) { false } expect(created_group.default_branch_protection).not_to eq(Gitlab::Access::PROTECTION_NONE) end end end context 'creating a group with `default_branch_protection_defaults` attribute' do let(:branch_protection) { ::Gitlab::Access::BranchProtection.protected_against_developer_pushes.stringify_keys } let(:params) { group_params.merge(default_branch_protection_defaults: branch_protection) } let(:service) { described_class.new(user, params) } let(:created_group) { service.execute } context 'for users who have the ability to create a group with `default_branch_protection`' do before do allow(Ability).to receive(:allowed?).and_call_original allow(Ability).to receive(:allowed?).with(user, :update_default_branch_protection, an_instance_of(Group)).and_return(true) end it 'creates group with the specified default branch protection settings' do expect(created_group.default_branch_protection_defaults).to eq(branch_protection) end end context 'for users who do not have the ability to create a group with `default_branch_protection_defaults`' do it 'does not create the group with the specified default branch protection settings' do allow(Ability).to receive(:allowed?).and_call_original allow(Ability).to receive(:allowed?).with(user, :create_group_with_default_branch_protection) { false } expect(created_group.default_branch_protection_defaults).not_to eq(Gitlab::Access::PROTECTION_NONE) end end end context 'creating a group with `allow_mfa_for_subgroups` attribute' do let(:params) { group_params.merge(allow_mfa_for_subgroups: false) } let(:service) { described_class.new(user, params) } it 'creates group without error' do expect(service.execute).to be_persisted end end describe 'creating a top level group' do let(:service) { described_class.new(user, group_params) } context 'when user can create a group' do before do user.update_attribute(:can_create_group, true) end it { is_expected.to be_persisted } context 'with before_commit callback' do it_behaves_like 'has sync-ed traversal_ids' end end context 'when user can not create a group' do before do user.update_attribute(:can_create_group, false) end it { is_expected.not_to be_persisted } end end describe 'creating subgroup' do let!(:group) { create(:group) } let!(:service) { described_class.new(user, group_params.merge(parent_id: group.id)) } context 'as group owner' do before do group.add_owner(user) end it { is_expected.to be_persisted } it_behaves_like 'has sync-ed traversal_ids' end context 'as guest' do it 'does not save group and returns an error' do is_expected.not_to be_persisted expect(subject.errors[:parent_id].first).to eq(s_('CreateGroup|You don’t have permission to create a subgroup in this group.')) expect(subject.parent_id).to be_nil end end context 'as owner' do before do group.add_owner(user) end it { is_expected.to be_persisted } end context 'as maintainer' do before do group.add_maintainer(user) end it { is_expected.to be_persisted } end end describe "when visibility level is passed as a string" do let(:service) { described_class.new(user, group_params) } let(:group_params) { { path: 'group_path', visibility: 'public' } } it "assigns the correct visibility level" do group = service.execute expect(group.visibility_level).to eq(Gitlab::VisibilityLevel::PUBLIC) end end describe 'creating a mattermost team' do let!(:params) { group_params.merge(create_chat_team: "true") } let!(:service) { described_class.new(user, params) } before do stub_mattermost_setting(enabled: true) end it 'create the chat team with the group' do allow_any_instance_of(::Mattermost::Team).to receive(:create) .and_return({ 'name' => 'tanuki', 'id' => 'lskdjfwlekfjsdifjj' }) expect { subject }.to change { ChatTeam.count }.from(0).to(1) end end describe 'creating a setting record' do let(:service) { described_class.new(user, group_params) } it 'create the settings record connected to the group' do group = subject expect(group.namespace_settings).to be_persisted end end describe 'creating a details record' do let(:service) { described_class.new(user, group_params) } it 'create the details record connected to the group' do group = subject expect(group.namespace_details).to be_persisted end end describe 'create service for the group' do let(:service) { described_class.new(user, group_params) } let(:created_group) { service.execute } context 'with an active instance-level integration' do let!(:instance_integration) { create(:prometheus_integration, :instance, api_url: 'https://prometheus.instance.com/') } it 'creates a service from the instance-level integration' do expect(created_group.integrations.count).to eq(1) expect(created_group.integrations.first.api_url).to eq(instance_integration.api_url) expect(created_group.integrations.first.inherit_from_id).to eq(instance_integration.id) end context 'with an active group-level integration' do let(:service) { described_class.new(user, group_params.merge(parent_id: group.id)) } let!(:group_integration) { create(:prometheus_integration, :group, group: group, api_url: 'https://prometheus.group.com/') } let(:group) do create(:group).tap do |group| group.add_owner(user) end end it 'creates a service from the group-level integration' do expect(created_group.integrations.count).to eq(1) expect(created_group.integrations.first.api_url).to eq(group_integration.api_url) expect(created_group.integrations.first.inherit_from_id).to eq(group_integration.id) end context 'with an active subgroup' do let(:service) { described_class.new(user, group_params.merge(parent_id: subgroup.id)) } let!(:subgroup_integration) { create(:prometheus_integration, :group, group: subgroup, api_url: 'https://prometheus.subgroup.com/') } let(:subgroup) do create(:group, parent: group).tap do |subgroup| subgroup.add_owner(user) end end it 'creates a service from the subgroup-level integration' do expect(created_group.integrations.count).to eq(1) expect(created_group.integrations.first.api_url).to eq(subgroup_integration.api_url) expect(created_group.integrations.first.inherit_from_id).to eq(subgroup_integration.id) end end end end end context 'shared runners configuration' do context 'parent group present' do using RSpec::Parameterized::TableSyntax where(:shared_runners_config, :descendants_override_disabled_shared_runners_config) do true | false false | false # true | true # invalid at the group level, leaving as comment to make explicit false | true end with_them do let!(:group) { create(:group, shared_runners_enabled: shared_runners_config, allow_descendants_override_disabled_shared_runners: descendants_override_disabled_shared_runners_config) } let!(:service) { described_class.new(user, group_params.merge(parent_id: group.id)) } before do group.add_owner(user) end it 'creates group following the parent config' do new_group = service.execute expect(new_group.shared_runners_enabled).to eq(shared_runners_config) expect(new_group.allow_descendants_override_disabled_shared_runners).to eq(descendants_override_disabled_shared_runners_config) end end end context 'root group' do let!(:service) { described_class.new(user) } it 'follows default config' do new_group = service.execute expect(new_group.shared_runners_enabled).to eq(true) expect(new_group.allow_descendants_override_disabled_shared_runners).to eq(false) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups class NestedCreateService < Groups::BaseService attr_reader :group_path, :visibility_level def initialize(user, params) @current_user = user @params = params.dup @group_path = @params.delete(:group_path) @visibility_level = @params.delete(:visibility_level) || Gitlab::CurrentSettings.current_application_settings.default_group_visibility end def execute return unless group_path if namespace = namespace_or_group(group_path) return namespace end create_group_path end private def create_group_path group_path_segments = group_path.split('/') last_group = nil partial_path_segments = [] while subgroup_name = group_path_segments.shift partial_path_segments << subgroup_name partial_path = partial_path_segments.join('/') new_params = params.reverse_merge( path: subgroup_name, name: subgroup_name, parent: last_group, visibility_level: visibility_level ) last_group = namespace_or_group(partial_path) || Groups::CreateService.new(current_user, new_params).execute end last_group end def namespace_or_group(group_path) Namespace.find_by_full_path(group_path) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::NestedCreateService, feature_category: :groups_and_projects do let(:user) { create(:user) } subject(:service) { described_class.new(user, params) } shared_examples 'with a visibility level' do it 'creates the group with correct visibility level' do allow(Gitlab::CurrentSettings.current_application_settings) .to receive(:default_group_visibility) { Gitlab::VisibilityLevel::INTERNAL } group = service.execute expect(group.visibility_level).to eq(Gitlab::VisibilityLevel::INTERNAL) end context 'adding a visibility level ' do it 'overwrites the visibility level' do service = described_class.new(user, params.merge(visibility_level: Gitlab::VisibilityLevel::PRIVATE)) group = service.execute expect(group.visibility_level).to eq(Gitlab::VisibilityLevel::PRIVATE) end end end describe 'with subgroups' do let(:params) { { group_path: 'a-group/a-sub-group' } } describe "#execute" do it 'returns the group if it already existed' do parent = create(:group, path: 'a-group') child = create(:group, path: 'a-sub-group', parent: parent) parent.add_owner(user) child.add_owner(user) expect(service.execute).to eq(child) end it 'reuses a parent if it already existed' do parent = create(:group, path: 'a-group') parent.add_owner(user) expect(service.execute.parent).to eq(parent) end it 'creates group and subgroup in the database' do service.execute parent = Group.find_by_full_path('a-group') child = parent.children.find_by(path: 'a-sub-group') expect(parent).not_to be_nil expect(child).not_to be_nil end it_behaves_like 'with a visibility level' end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module GroupLinks class DestroyService < ::Groups::BaseService def execute(one_or_more_links, skip_authorization: false) unless skip_authorization || group && can?(current_user, :admin_group_member, group) return error('Not Found', 404) end links = Array(one_or_more_links) if GroupGroupLink.delete(links) Gitlab::AppLogger.info( "GroupGroupLinks with ids: #{links.map(&:id)} have been deleted.") groups_to_refresh = links.map(&:shared_with_group) groups_to_refresh.uniq.each do |group| next if Feature.enabled?(:skip_group_share_unlink_auth_refresh, group.root_ancestor) group.refresh_members_authorized_projects(direct_members_only: true) end else Gitlab::AppLogger.info( "Failed to delete GroupGroupLinks with ids: #{links.map(&:id)}.") end links end end end end Groups::GroupLinks::DestroyService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::GroupLinks::DestroyService, '#execute', feature_category: :groups_and_projects do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group, :private) } let_it_be(:shared_group) { create(:group, :private) } let_it_be(:project) { create(:project, group: shared_group) } let_it_be(:owner) { create(:user) } subject { described_class.new(shared_group, owner) } context 'when authorizing by user' do before do group.add_developer(owner) shared_group.add_owner(owner) end context 'single link' do let!(:link) { create(:group_group_link, shared_group: shared_group, shared_with_group: group) } it 'destroys the link' do expect { subject.execute(link) }.to change { shared_group.shared_with_group_links.count }.from(1).to(0) end context 'with skip_group_share_unlink_auth_refresh feature flag disabled' do before do stub_feature_flags(skip_group_share_unlink_auth_refresh: false) end it 'revokes project authorization', :sidekiq_inline do group.add_developer(user) expect { subject.execute(link) }.to( change { Ability.allowed?(user, :read_project, project) }.from(true).to(false)) end end context 'with skip_group_share_unlink_auth_refresh feature flag enabled' do before do stub_feature_flags(skip_group_share_unlink_auth_refresh: true) end it 'maintains project authorization', :sidekiq_inline do group.add_developer(user) expect(Ability.allowed?(user, :read_project, project)).to be_truthy end end end context 'multiple links' do let_it_be(:another_group) { create(:group, :private) } let_it_be(:another_shared_group) { create(:group, :private) } let!(:links) do [ create(:group_group_link, shared_group: shared_group, shared_with_group: group), create(:group_group_link, shared_group: shared_group, shared_with_group: another_group), create(:group_group_link, shared_group: another_shared_group, shared_with_group: group), create(:group_group_link, shared_group: another_shared_group, shared_with_group: another_group) ] end context 'with skip_group_share_unlink_auth_refresh feature flag disabled' do before do stub_feature_flags(skip_group_share_unlink_auth_refresh: false) end it 'updates project authorization once per group' do expect(GroupGroupLink).to receive(:delete).and_call_original expect(group).to receive(:refresh_members_authorized_projects).with(direct_members_only: true).once expect(another_group).to receive(:refresh_members_authorized_projects).with(direct_members_only: true).once subject.execute(links) end end context 'with skip_group_share_unlink_auth_refresh feature flag enabled' do before do stub_feature_flags(skip_group_share_unlink_auth_refresh: true) end it 'does not update project authorization once per group' do expect(GroupGroupLink).to receive(:delete).and_call_original expect(group).not_to receive(:refresh_members_authorized_projects) expect(another_group).not_to receive(:refresh_members_authorized_projects) subject.execute(links) end end end end context 'when skipping authorization' do let!(:link) { create(:group_group_link, shared_group: shared_group, shared_with_group: group) } context 'with provided group and owner' do it 'destroys the link' do expect do subject.execute(link, skip_authorization: true) end.to change { shared_group.shared_with_group_links.count }.from(1).to(0) end end context 'without providing group or owner' do subject { described_class.new(nil, nil) } it 'destroys the link' do expect do subject.execute(link, skip_authorization: true) end.to change { shared_group.shared_with_group_links.count }.from(1).to(0) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module GroupLinks class UpdateService < ::Groups::BaseService def initialize(group_link, user = nil) super(group_link.shared_group, user) @group_link = group_link end def execute(group_link_params) group_link.update!(group_link_params) if requires_authorization_refresh?(group_link_params) group_link.shared_with_group.refresh_members_authorized_projects(direct_members_only: true) end group_link end private attr_accessor :group_link def requires_authorization_refresh?(params) params.include?(:group_access) end end end end Groups::GroupLinks::UpdateService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::GroupLinks::UpdateService, '#execute', feature_category: :groups_and_projects do let(:user) { create(:user) } let_it_be(:group) { create(:group, :private) } let_it_be(:shared_group) { create(:group, :private) } let_it_be(:project) { create(:project, group: shared_group) } let(:group_member_user) { create(:user) } let!(:link) { create(:group_group_link, shared_group: shared_group, shared_with_group: group) } let(:expiry_date) { 1.month.from_now.to_date } let(:group_link_params) do { group_access: Gitlab::Access::GUEST, expires_at: expiry_date } end subject { described_class.new(link, user).execute(group_link_params) } before do group.add_developer(group_member_user) end it 'updates existing link' do expect(link.group_access).to eq(Gitlab::Access::DEVELOPER) expect(link.expires_at).to be_nil subject link.reload expect(link.group_access).to eq(Gitlab::Access::GUEST) expect(link.expires_at).to eq(expiry_date) end it 'updates project permissions', :sidekiq_inline do expect { subject }.to change { group_member_user.can?(:create_release, project) }.from(true).to(false) end it 'executes UserProjectAccessChangedService' do expect_next_instance_of(UserProjectAccessChangedService, [group_member_user.id]) do |service| expect(service).to receive(:execute) end subject end context 'with only param not requiring authorization refresh' do let(:group_link_params) { { expires_at: Date.tomorrow } } it 'does not execute UserProjectAccessChangedService' do expect(UserProjectAccessChangedService).not_to receive(:new) subject end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module GroupLinks class CreateService < ::Groups::BaseService include GroupLinkable def initialize(group, shared_with_group, user, params) @shared_with_group = shared_with_group super(group, user, params) end private delegate :root_ancestor, to: :group def valid_to_create? can?(current_user, :admin_group_member, group) && can?(current_user, :read_group, shared_with_group) && sharing_allowed? end def build_link @link = GroupGroupLink.new( shared_group: group, shared_with_group: shared_with_group, group_access: params[:shared_group_access], expires_at: params[:expires_at] ) end def setup_authorizations shared_with_group.refresh_members_authorized_projects(direct_members_only: true) end end end end Groups::GroupLinks::CreateService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::GroupLinks::CreateService, '#execute', feature_category: :groups_and_projects do let_it_be(:shared_with_group_parent) { create(:group, :private) } let_it_be(:shared_with_group) { create(:group, :private, parent: shared_with_group_parent) } let_it_be(:shared_with_group_child) { create(:group, :private, parent: shared_with_group) } let_it_be(:group_parent) { create(:group, :private) } let(:group) { create(:group, :private, parent: group_parent) } let(:opts) do { shared_group_access: Gitlab::Access::DEVELOPER, expires_at: nil } end subject { described_class.new(group, shared_with_group, user, opts) } shared_examples_for 'not shareable' do it 'does not share and returns an error' do expect do result = subject.execute expect(result[:status]).to eq(:error) expect(result[:http_status]).to eq(404) end.not_to change { group.shared_with_group_links.count } end end shared_examples_for 'shareable' do it 'adds group to another group' do expect do result = subject.execute expect(result[:status]).to eq(:success) end.to change { group.shared_with_group_links.count }.from(0).to(1) end end context 'when user has proper membership to share a group' do let_it_be(:group_user) { create(:user) } let(:user) { group_user } before do shared_with_group.add_guest(group_user) group.add_owner(group_user) end it_behaves_like 'shareable' context 'when sharing outside the hierarchy is disabled' do let_it_be_with_refind(:group_parent) do create(:group, namespace_settings: create(:namespace_settings, prevent_sharing_groups_outside_hierarchy: true)) end it_behaves_like 'not shareable' context 'when group is inside hierarchy' do let(:shared_with_group) { create(:group, :private, parent: group_parent) } it_behaves_like 'shareable' end end context 'project authorizations based on group hierarchies' do let_it_be(:child_group_user) { create(:user) } let_it_be(:parent_group_user) { create(:user) } before do shared_with_group_parent.add_owner(parent_group_user) shared_with_group.add_owner(group_user) shared_with_group_child.add_owner(child_group_user) end context 'project authorizations refresh' do it 'is executed only for the direct members of the group' do expect(UserProjectAccessChangedService).to receive(:new).with(contain_exactly(group_user.id)) .and_call_original subject.execute end end context 'project authorizations' do let(:group_child) { create(:group, :private, parent: group) } let(:project_parent) { create(:project, group: group_parent) } let(:project) { create(:project, group: group) } let(:project_child) { create(:project, group: group_child) } context 'group user' do let(:user) { group_user } it 'create proper authorizations' do subject.execute expect(Ability.allowed?(user, :read_project, project_parent)).to be_falsey expect(Ability.allowed?(user, :read_project, project)).to be_truthy expect(Ability.allowed?(user, :read_project, project_child)).to be_truthy end end context 'parent group user' do let(:user) { parent_group_user } it 'create proper authorizations' do subject.execute expect(Ability.allowed?(user, :read_project, project_parent)).to be_falsey expect(Ability.allowed?(user, :read_project, project)).to be_falsey expect(Ability.allowed?(user, :read_project, project_child)).to be_falsey end end context 'child group user' do let(:user) { child_group_user } it 'create proper authorizations' do subject.execute expect(Ability.allowed?(user, :read_project, project_parent)).to be_falsey expect(Ability.allowed?(user, :read_project, project)).to be_falsey expect(Ability.allowed?(user, :read_project, project_child)).to be_falsey end end end end end context 'user does not have access to group' do let(:user) { create(:user) } before do group.add_owner(user) end it_behaves_like 'not shareable' end context 'user does not have admin access to shared group' do let(:user) { create(:user) } before do shared_with_group.add_guest(user) group.add_developer(user) end it_behaves_like 'not shareable' end context 'when group is blank' do let(:group_user) { create(:user) } let(:user) { group_user } let(:group) { nil } it 'does not share and returns an error' do expect do result = subject.execute expect(result[:status]).to eq(:error) expect(result[:http_status]).to eq(404) end.not_to change { shared_with_group.shared_group_links.count } end end context 'when shared_with_group is blank' do let(:group_user) { create(:user) } let(:user) { group_user } let(:shared_with_group) { nil } it_behaves_like 'not shareable' end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module ImportExport class ImportService attr_reader :current_user, :group, :shared def initialize(group:, user:) @group = group @current_user = user @user_role = user_role @shared = Gitlab::ImportExport::Shared.new(@group) @logger = Gitlab::Import::Logger.build end def async_execute group_import_state = GroupImportState.safe_find_or_create_by!(group: group, user: current_user) jid = GroupImportWorker.with_status.perform_async(current_user.id, group.id) if jid.present? group_import_state.update!(jid: jid) else group_import_state.fail_op('Failed to schedule import job') false end end def execute Gitlab::Tracking.event(self.class.name, 'create', label: 'import_group_from_file') if valid_user_permissions? && import_file && valid_import_file? && restorers.all?(&:restore) notify_success Gitlab::Tracking.event( self.class.name, 'create', label: 'import_access_level', user: current_user, extra: { user_role: user_role, import_type: 'import_group_from_file' } ) group else notify_error! end ensure remove_base_tmp_dir remove_import_file end private def user_role # rubocop:disable CodeReuse/ActiveRecord, Style/MultilineTernaryOperator access_level = group.parent ? current_user&.group_members&.find_by(source_id: group.parent&.id)&.access_level : Gitlab::Access::OWNER Gitlab::Access.human_access(access_level) # rubocop:enable CodeReuse/ActiveRecord, Style/MultilineTernaryOperator end def import_file @import_file ||= Gitlab::ImportExport::FileImporter.import( importable: group, archive_file: nil, shared: shared ) end def restorers [tree_restorer] end def tree_restorer @tree_restorer ||= Gitlab::ImportExport::Group::TreeRestorer.new( user: current_user, shared: shared, group: group ) end def remove_import_file upload = group.import_export_upload return unless upload&.import_file&.file upload.remove_import_file! upload.save! end def valid_user_permissions? if current_user.can?(:admin_group, group) true else shared.error(::Gitlab::ImportExport::Error.permission_error(current_user, group)) false end end def valid_import_file? return true if File.exist?(File.join(shared.export_path, 'tree/groups/_all.ndjson')) shared.error(::Gitlab::ImportExport::Error.incompatible_import_file_error) false end def notify_success @logger.info( group_id: group.id, group_name: group.name, message: 'Group Import/Export: Import succeeded' ) end def notify_error @logger.error( group_id: group.id, group_name: group.name, message: "Group Import/Export: Errors occurred, see '#{Gitlab::ErrorTracking::Logger.file_name}' for details" ) end def notify_error! notify_error raise Gitlab::ImportExport::Error, shared.errors.to_sentence end def remove_base_tmp_dir FileUtils.rm_rf(shared.base_path) end end end end Groups::ImportExport::ImportService.prepend_mod_with('Groups::ImportExport::ImportService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::ImportExport::ImportService, feature_category: :importers do describe '#async_execute' do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } before do allow(GroupImportWorker).to receive(:with_status).and_return(GroupImportWorker) end context 'when the job can be successfully scheduled' do subject(:import_service) { described_class.new(group: group, user: user) } it 'creates group import state' do import_service.async_execute import_state = group.import_state expect(import_state.user).to eq(user) expect(import_state.group).to eq(group) end it 'enqueues an import job' do allow(GroupImportWorker).to receive(:with_status).and_return(GroupImportWorker) expect(GroupImportWorker).to receive(:perform_async).with(user.id, group.id) import_service.async_execute end it 'marks the group import as in progress' do import_service.async_execute expect(group.import_state.in_progress?).to eq true end it 'returns truthy' do expect(import_service.async_execute).to be_truthy end end context 'when the job cannot be scheduled' do subject(:import_service) { described_class.new(group: group, user: user) } before do allow(GroupImportWorker).to receive(:perform_async).and_return(nil) end it 'returns falsey' do expect(import_service.async_execute).to be_falsey end it 'does not mark the group import as created' do expect { import_service.async_execute }.not_to change { group.import_state } end end end context 'when importing a ndjson export' do let(:user) { create(:user) } let(:group) { create(:group) } let(:import_file) { fixture_file_upload('spec/fixtures/group_export.tar.gz') } let(:import_logger) { instance_double(Gitlab::Import::Logger) } subject(:service) { described_class.new(group: group, user: user) } before do ImportExportUpload.create!(group: group, import_file: import_file) allow(Gitlab::Import::Logger).to receive(:build).and_return(import_logger) allow(import_logger).to receive(:error) allow(import_logger).to receive(:info) allow(import_logger).to receive(:warn) allow(FileUtils).to receive(:rm_rf).and_call_original end context 'when user has correct permissions' do before do group.add_owner(user) end it 'imports group structure successfully' do expect(service.execute).to be_truthy end it 'tracks the event' do service.execute expect_snowplow_event( category: 'Groups::ImportExport::ImportService', action: 'create', label: 'import_group_from_file' ) expect_snowplow_event( category: 'Groups::ImportExport::ImportService', action: 'create', label: 'import_access_level', user: user, extra: { user_role: 'Owner', import_type: 'import_group_from_file' } ) end it 'removes import file' do service.execute expect(group.import_export_upload.import_file.file).to be_nil end it 'removes tmp files' do shared = Gitlab::ImportExport::Shared.new(group) allow(Gitlab::ImportExport::Shared).to receive(:new).and_return(shared) service.execute expect(FileUtils).to have_received(:rm_rf).with(shared.base_path) expect(Dir.exist?(shared.base_path)).to eq(false) end it 'logs the import success' do expect(import_logger).to receive(:info).with( group_id: group.id, group_name: group.name, message: 'Group Import/Export: Import succeeded' ).once service.execute end end context 'when user does not have correct permissions' do it 'logs the error and raises an exception' do expect(import_logger).to receive(:error).with( group_id: group.id, group_name: group.name, message: a_string_including('Errors occurred') ) expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end it 'tracks the error' do shared = Gitlab::ImportExport::Shared.new(group) allow(Gitlab::ImportExport::Shared).to receive(:new).and_return(shared) expect(shared).to receive(:error) do |param| expect(param.message).to include 'does not have required permissions for' end expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end end context 'when there are errors with the import file' do let(:import_file) { fixture_file_upload('spec/fixtures/symlink_export.tar.gz') } it 'logs the error and raises an exception' do expect(import_logger).to receive(:error).with( group_id: group.id, group_name: group.name, message: a_string_including('Errors occurred') ).once expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end end context 'when there are errors with the sub-relations' do let(:import_file) { fixture_file_upload('spec/fixtures/group_export_invalid_subrelations.tar.gz') } before do group.add_owner(user) end it 'successfully imports the group' do expect(service.execute).to be_truthy end it 'logs the import success' do allow(Gitlab::Import::Logger).to receive(:build).and_return(import_logger) expect(import_logger).to receive(:info).with( group_id: group.id, group_name: group.name, message: 'Group Import/Export: Import succeeded' ) service.execute expect_snowplow_event( category: 'Groups::ImportExport::ImportService', action: 'create', label: 'import_access_level', user: user, extra: { user_role: 'Owner', import_type: 'import_group_from_file' } ) end end end context 'when importing a json export' do let(:user) { create(:user) } let(:group) { create(:group) } let(:import_file) { fixture_file_upload('spec/fixtures/legacy_group_export.tar.gz') } let(:import_logger) { instance_double(Gitlab::Import::Logger) } subject(:service) { described_class.new(group: group, user: user) } before do group.add_owner(user) ImportExportUpload.create!(group: group, import_file: import_file) allow(Gitlab::Import::Logger).to receive(:build).and_return(import_logger) allow(import_logger).to receive(:error) allow(import_logger).to receive(:warn) allow(import_logger).to receive(:info) end it 'logs the error and raises an exception' do expect(import_logger).to receive(:error).with( group_id: group.id, group_name: group.name, message: a_string_including('Errors occurred') ).once expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end it 'tracks the error' do shared = Gitlab::ImportExport::Shared.new(group) allow(Gitlab::ImportExport::Shared).to receive(:new).and_return(shared) expect(shared).to receive(:error) do |param| expect(param.message).to include 'The import file is incompatible' end expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module ImportExport class ExportService def initialize(group:, user:, params: {}) @group = group @current_user = user @params = params @shared = @params[:shared] || Gitlab::ImportExport::Shared.new(@group) @logger = Gitlab::Export::Logger.build end def async_execute GroupExportWorker.perform_async(current_user.id, group.id, params) end def execute validate_user_permissions remove_existing_export! if group.export_file_exists? save! ensure remove_archive_tmp_dir end private attr_reader :group, :current_user, :params attr_accessor :shared def validate_user_permissions unless current_user.can?(:admin_group, group) shared.error(::Gitlab::ImportExport::Error.permission_error(current_user, group)) notify_error! end end def remove_existing_export! import_export_upload = group.import_export_upload import_export_upload.remove_export_file! import_export_upload.save end def save! # We cannot include the file_saver with the other savers because # it removes the tmp dir. This means that if we want to add new savers # in EE the data won't be available. if save_exporters && file_saver.save notify_success else notify_error! end end def save_exporters log_info('Group export started') savers.all? do |exporter| log_info("#{exporter.class.name} saver started") exporter.save end end def savers [version_saver, tree_exporter] end def tree_exporter Gitlab::ImportExport::Group::TreeSaver.new( group: group, current_user: current_user, shared: shared, params: params ) end def version_saver Gitlab::ImportExport::VersionSaver.new(shared: shared) end def file_saver Gitlab::ImportExport::Saver.new(exportable: group, shared: shared) end def remove_archive_tmp_dir FileUtils.rm_rf(shared.archive_path) if shared&.archive_path end def notify_error! notify_error raise Gitlab::ImportExport::Error, shared.errors.to_sentence end def log_info(message) @logger.info( message: message, group_id: group.id, group_name: group.name ) end def notify_success log_info('Group Export succeeded') notification_service.group_was_exported(group, current_user) end def notify_error @logger.error( message: 'Group Export failed', group_id: group.id, group_name: group.name, errors: shared.errors.join(', ') ) notification_service.group_was_not_exported(group, current_user, shared.errors) end def notification_service @notification_service ||= NotificationService.new end end end end Groups::ImportExport::ExportService.prepend_mod_with('Groups::ImportExport::ExportService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::ImportExport::ExportService, feature_category: :importers do describe '#async_execute' do let(:user) { create(:user) } let(:group) { create(:group) } context 'when the job can be successfully scheduled' do let(:export_service) { described_class.new(group: group, user: user) } it 'enqueues an export job' do allow(GroupExportWorker).to receive(:perform_async).with(user.id, group.id, {}) export_service.async_execute end it 'returns truthy' do expect(export_service.async_execute).to be_present end end context 'when the job cannot be scheduled' do let(:export_service) { described_class.new(group: group, user: user) } before do allow(GroupExportWorker).to receive(:perform_async).and_return(nil) end it 'returns falsey' do expect(export_service.async_execute).to be_falsey end end end describe '#execute' do let!(:user) { create(:user) } let(:group) { create(:group) } let(:shared) { Gitlab::ImportExport::Shared.new(group) } let(:archive_path) { shared.archive_path } let(:service) { described_class.new(group: group, user: user, params: { shared: shared }) } before do group.add_owner(user) end after do FileUtils.rm_rf(archive_path) end it 'saves the version' do expect(Gitlab::ImportExport::VersionSaver).to receive(:new).and_call_original service.execute end it 'saves the models using ndjson tree saver' do expect(Gitlab::ImportExport::Group::TreeSaver).to receive(:new).and_call_original service.execute end it 'compresses and removes tmp files' do expect(group.import_export_upload).to be_nil expect(Gitlab::ImportExport::Saver).to receive(:new).and_call_original service.execute expect(Dir.exist?(shared.archive_path)).to eq false expect(File.exist?(group.import_export_upload.export_file.path)).to eq true end it 'notifies the user' do expect_next_instance_of(NotificationService) do |instance| expect(instance).to receive(:group_was_exported) end service.execute end context 'when saver succeeds' do it 'saves the group in the file system' do service.execute expect(group.import_export_upload.export_file.file).not_to be_nil expect(File.directory?(archive_path)).to eq(false) expect(File.exist?(shared.archive_path)).to eq(false) end end context 'when user does not have admin_group permission' do let!(:another_user) { create(:user) } let(:service) { described_class.new(group: group, user: another_user, params: { shared: shared }) } let(:expected_message) do "User with ID: %s does not have required permissions for Group: %s with ID: %s" % [another_user.id, group.name, group.id] end it 'fails' do expect { service.execute }.to raise_error(Gitlab::ImportExport::Error).with_message(expected_message) end it 'logs the error' do expect_next_instance_of(Gitlab::Export::Logger) do |logger| expect(logger).to receive(:error).with( group_id: group.id, group_name: group.name, errors: expected_message, message: 'Group Export failed' ) end expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end it 'tracks the error' do expect(shared).to receive(:error) { |param| expect(param.message).to eq expected_message } expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end end context 'when export fails' do context 'when file saver fails' do before do allow_next_instance_of(Gitlab::ImportExport::Saver) do |saver| allow(saver).to receive(:save).and_return(false) end end it 'removes the remaining exported data' do expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) expect(group.import_export_upload).to be_nil expect(Dir.exist?(shared.archive_path)).to eq(false) end it 'notifies the user about failed group export' do expect_next_instance_of(NotificationService) do |instance| expect(instance).to receive(:group_was_not_exported) end expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end end context 'when file compression fails' do before do allow(service).to receive_message_chain(:tree_exporter, :save).and_return(false) end it 'removes the remaining exported data' do allow_next_instance_of(Gitlab::ImportExport::Saver) do |saver| allow(saver).to receive(:compress_and_save).and_return(false) end expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) expect(group.import_export_upload).to be_nil expect(Dir.exist?(shared.archive_path)).to eq(false) end it 'notifies logger' do allow(service).to receive_message_chain(:tree_exporter, :save).and_return(false) expect(service.instance_variable_get(:@logger)).to receive(:error) expect { service.execute }.to raise_error(Gitlab::ImportExport::Error) end end end context 'when there is an existing export file' do subject(:export_service) { described_class.new(group: group, user: user) } let(:import_export_upload) do create( :import_export_upload, group: group, export_file: fixture_file_upload('spec/fixtures/group_export.tar.gz') ) end it 'removes it' do existing_file = import_export_upload.export_file expect { export_service.execute }.to change { existing_file.file }.to(be_nil) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module DeployTokens class RevokeService < BaseService attr_accessor :token def execute @token = group.deploy_tokens.find(params[:id]) @token.revoke! end end end end Groups::DeployTokens::RevokeService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::DeployTokens::RevokeService, feature_category: :deployment_management do let_it_be(:entity) { create(:group) } let_it_be(:deploy_token) { create(:deploy_token, :group, groups: [entity]) } let_it_be(:user) { create(:user) } let_it_be(:deploy_token_params) { { id: deploy_token.id } } describe '#execute' do subject { described_class.new(entity, user, deploy_token_params).execute } it "revokes a group deploy token" do expect(deploy_token.revoked).to eq(false) expect { subject }.to change { deploy_token.reload.revoked }.to eq(true) end context 'invalid token id' do let(:deploy_token_params) { { token_id: non_existing_record_id } } it 'raises an error' do expect { subject }.to raise_error(ActiveRecord::RecordNotFound) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module DeployTokens class DestroyService < BaseService include DeployTokenMethods def execute destroy_deploy_token(@group, params) end end end end Groups::DeployTokens::DestroyService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::DeployTokens::DestroyService, feature_category: :deployment_management do it_behaves_like 'a deploy token deletion service' do let_it_be(:entity) { create(:group) } let_it_be(:deploy_token_class) { GroupDeployToken } let_it_be(:deploy_token) { create(:deploy_token, :group, groups: [entity]) } end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Groups module DeployTokens class CreateService < BaseService include DeployTokenMethods def execute deploy_token = create_deploy_token_for(@group, current_user, params) create_deploy_token_payload_for(deploy_token) end end end end Groups::DeployTokens::CreateService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Groups::DeployTokens::CreateService, feature_category: :deployment_management do it_behaves_like 'a deploy token creation service' do let(:entity) { create(:group) } let(:deploy_token_class) { GroupDeployToken } end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module PersonalAccessTokens class LastUsedService def initialize(personal_access_token) @personal_access_token = personal_access_token end def execute # Needed to avoid calling service on Oauth tokens return unless @personal_access_token.has_attribute?(:last_used_at) # We _only_ want to update last_used_at and not also updated_at (which # would be updated when using #touch). @personal_access_token.update_column(:last_used_at, Time.zone.now) if update? end private def update? return false if ::Gitlab::Database.read_only? last_used = @personal_access_token.last_used_at return true if last_used.nil? last_used <= 10.minutes.ago end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe PersonalAccessTokens::LastUsedService, feature_category: :system_access do describe '#execute' do subject { described_class.new(personal_access_token).execute } context 'when the personal access token was used 10 minutes ago', :freeze_time do let(:personal_access_token) { create(:personal_access_token, last_used_at: 10.minutes.ago) } it 'updates the last_used_at timestamp' do expect { subject }.to change { personal_access_token.last_used_at } end it 'does not run on read-only GitLab instances' do allow(::Gitlab::Database).to receive(:read_only?).and_return(true) expect { subject }.not_to change { personal_access_token.last_used_at } end end context 'when the personal access token was used less than 10 minutes ago', :freeze_time do let(:personal_access_token) { create(:personal_access_token, last_used_at: (10.minutes - 1.second).ago) } it 'does not update the last_used_at timestamp' do expect { subject }.not_to change { personal_access_token.last_used_at } end end context 'when the last_used_at timestamp is nil' do let_it_be(:personal_access_token) { create(:personal_access_token, last_used_at: nil) } it 'updates the last_used_at timestamp' do expect { subject }.to change { personal_access_token.last_used_at } end end context 'when not a personal access token' do let_it_be(:personal_access_token) { create(:oauth_access_token) } it 'does not execute' do expect(subject).to be_nil end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module PersonalAccessTokens class RotateService EXPIRATION_PERIOD = 1.week def initialize(current_user, token) @current_user = current_user @token = token end def execute(params = {}) return error_response(message: _('token already revoked')) if token.revoked? response = ServiceResponse.success PersonalAccessToken.transaction do unless token.revoke! response = error_response raise ActiveRecord::Rollback end target_user = token.user new_token = target_user.personal_access_tokens.create(create_token_params(token, params)) if new_token.persisted? response = error_response unless update_bot_membership(target_user, new_token.expires_at) response = success_response(new_token) else response = error_response(message: new_token.errors.full_messages.to_sentence) raise ActiveRecord::Rollback end end response end private attr_reader :current_user, :token def expires_at(params) return params[:expires_at] if params[:expires_at] params[:expires_at] || EXPIRATION_PERIOD.from_now.to_date end def success_response(new_token) ServiceResponse.success(payload: { personal_access_token: new_token }) end def error_response(message: _('failed to revoke token')) ServiceResponse.error(message: message) end def create_token_params(token, params) { name: token.name, previous_personal_access_token_id: token.id, impersonation: token.impersonation, scopes: token.scopes, expires_at: expires_at(params) } end def update_bot_membership(target_user, expires_at) return unless target_user.project_bot? target_user.members.first.update(expires_at: expires_at) end end end PersonalAccessTokens::RotateService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe PersonalAccessTokens::RotateService, feature_category: :system_access do describe '#execute' do let_it_be(:token, reload: true) { create(:personal_access_token) } subject(:response) { described_class.new(token.user, token).execute } it "rotates user's own token", :freeze_time do expect(response).to be_success new_token = response.payload[:personal_access_token] expect(new_token.token).not_to eq(token.token) expect(new_token.expires_at).to eq(Date.today + 1.week) expect(new_token.user).to eq(token.user) end it 'revokes the previous token' do expect { response }.to change { token.reload.revoked? }.from(false).to(true) new_token = response.payload[:personal_access_token] expect(new_token).not_to be_revoked end it 'saves the previous token as previous PAT attribute' do response new_token = response.payload[:personal_access_token] expect(new_token.previous_personal_access_token).to eql(token) end context 'when token user has a membership' do context 'when its not a bot user' do let_it_be(:user_membership) do create(:project_member, :developer, user: token.user, project: create(:project)) end it 'does not update membership expires at' do expect { response }.not_to change { user_membership.reload.expires_at } end end context 'when its a bot user' do let_it_be(:bot_user) { create(:user, :project_bot) } let_it_be(:bot_user_membership) do create(:project_member, :developer, user: bot_user, project: create(:project)) end let_it_be(:token, reload: true) { create(:personal_access_token, user: bot_user) } it 'updates membership expires at' do response new_token = response.payload[:personal_access_token] expect(bot_user_membership.reload.expires_at).to eq(new_token.expires_at) end end end context 'when user tries to rotate already revoked token' do let_it_be(:token, reload: true) { create(:personal_access_token, :revoked) } it 'returns an error' do expect { response }.not_to change { token.reload.revoked? }.from(true) expect(response).to be_error expect(response.message).to eq('token already revoked') end end context 'when revoking previous token fails' do it 'returns an error' do expect(token).to receive(:revoke!).and_return(false) expect(response).to be_error end end context 'when creating the new token fails' do let(:error_message) { 'boom!' } before do allow_next_instance_of(PersonalAccessToken) do |token| allow(token).to receive_message_chain(:errors, :full_messages, :to_sentence).and_return(error_message) allow(token).to receive_message_chain(:errors, :clear) allow(token).to receive_message_chain(:errors, :empty?).and_return(false) end end it 'returns an error' do expect(response).to be_error expect(response.message).to eq(error_message) end it 'reverts the changes' do expect { response }.not_to change { token.reload.revoked? }.from(false) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module PersonalAccessTokens class RevokeService < BaseService attr_reader :token, :current_user, :group VALID_SOURCES = %i[self secret_detection].freeze def initialize(current_user = nil, token: nil, group: nil, source: nil) @current_user = current_user @token = token @group = group @source = source @source = :self if @current_user && !@source raise ArgumentError unless VALID_SOURCES.include?(@source) end def execute return ServiceResponse.error(message: 'Not permitted to revoke') unless revocation_permitted? if token.revoke! log_event notification_service.access_token_revoked(token.user, token.name, @source) ServiceResponse.success(message: success_message) else ServiceResponse.error(message: error_message) end end private def error_message _("Could not revoke personal access token %{personal_access_token_name}.") % { personal_access_token_name: token.name } end def success_message _("Revoked personal access token %{personal_access_token_name}!") % { personal_access_token_name: token.name } end def revocation_permitted? case @source when :self Ability.allowed?(current_user, :revoke_token, token) when :secret_detection true else false end end def log_event Gitlab::AppLogger.info( class: self.class.name, message: "PAT Revoked", revoked_by: current_user&.username || @source, revoked_for: token.user.username, token_id: token.id) end end end PersonalAccessTokens::RevokeService.prepend_mod_with('PersonalAccessTokens::RevokeService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe PersonalAccessTokens::RevokeService, feature_category: :system_access do shared_examples_for 'a successfully revoked token' do it { expect(subject.success?).to be true } it { expect(service.token.revoked?).to be true } it 'logs the event' do expect(Gitlab::AppLogger).to receive(:info).with( class: described_class.to_s, message: 'PAT Revoked', revoked_by: revoked_by, revoked_for: token.user.username, token_id: token.id) subject end end shared_examples_for 'an unsuccessfully revoked token' do it { expect(subject.success?).to be false } it { expect(service.token.revoked?).to be false } end describe '#execute' do subject { service.execute } let(:service) { described_class.new(current_user, token: token) } context 'when current_user is an administrator' do context 'when admin mode is enabled', :enable_admin_mode do let_it_be(:current_user) { create(:admin) } let_it_be(:token) { create(:personal_access_token) } it_behaves_like 'a successfully revoked token' do let(:revoked_by) { current_user.username } end end context 'when admin mode is disabled' do let_it_be(:current_user) { create(:admin) } let_it_be(:token) { create(:personal_access_token) } it_behaves_like 'an unsuccessfully revoked token' end end context 'when current_user is not an administrator' do let_it_be(:current_user) { create(:user) } context 'token belongs to a different user' do let_it_be(:token) { create(:personal_access_token) } it_behaves_like 'an unsuccessfully revoked token' end context 'token belongs to current_user' do let_it_be(:token) { create(:personal_access_token, user: current_user) } it_behaves_like 'a successfully revoked token' do let(:revoked_by) { current_user.username } end end end context 'when source' do let(:service) { described_class.new(nil, token: token, source: source) } let_it_be(:current_user) { nil } context 'when source is valid' do let_it_be(:source) { :secret_detection } let_it_be(:token) { create(:personal_access_token) } it_behaves_like 'a successfully revoked token' do let(:revoked_by) { :secret_detection } end end context 'when source is invalid' do let_it_be(:source) { :external_request } let_it_be(:token) { create(:personal_access_token) } it 'raises ArgumentError' do expect { subject }.to raise_error ArgumentError end end context 'when source is missing' do let_it_be(:source) { nil } let_it_be(:token) { create(:personal_access_token) } it 'raises ArgumentError' do expect { subject }.to raise_error ArgumentError end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module PersonalAccessTokens class RevokeTokenFamilyService def initialize(token) @token = token end def execute # A token family is a chain of rotated tokens. Once rotated, the previous # token is revoked. As a result, a single token id should be returned by # this query. # rubocop: disable CodeReuse/ActiveRecord token_ids = pat_family.active.pluck_primary_key # We create another query based on the previous if any id exists. An # alternative is to use a single query, like # `pat_family.active.update_all(...)`). However, #update_all ignores # the CTE, and tries to revoke *all* active tokens. PersonalAccessToken.where(id: token_ids).update_all(revoked: true) if token_ids.any? # rubocop: enable CodeReuse/ActiveRecord ServiceResponse.success end private attr_reader :token def pat_family # rubocop: disable CodeReuse/ActiveRecord cte = Gitlab::SQL::RecursiveCTE.new(:personal_access_tokens_cte) personal_access_token_table = Arel::Table.new(:personal_access_tokens) cte << PersonalAccessToken .select( 'personal_access_tokens.id', 'personal_access_tokens.revoked', 'personal_access_tokens.expires_at') .where(personal_access_token_table[:previous_personal_access_token_id].eq(token.id)) cte << PersonalAccessToken .select( 'personal_access_tokens.id', 'personal_access_tokens.revoked', 'personal_access_tokens.expires_at') .from([personal_access_token_table, cte.table]) .where(personal_access_token_table[:previous_personal_access_token_id].eq(cte.table[:id])) PersonalAccessToken.with.recursive(cte.to_arel).from(cte.alias_to(personal_access_token_table)) # rubocop: enable CodeReuse/ActiveRecord end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe PersonalAccessTokens::RevokeTokenFamilyService, feature_category: :system_access do describe '#execute' do let_it_be(:token_3) { create(:personal_access_token, :revoked) } let_it_be(:token_2) { create(:personal_access_token, :revoked, previous_personal_access_token_id: token_3.id) } let_it_be(:token_1) { create(:personal_access_token, previous_personal_access_token_id: token_2.id) } subject(:response) { described_class.new(token_3).execute } it 'revokes the latest token from the chain of rotated tokens' do expect(response).to be_success expect(token_1.reload).to be_revoked end it 'does not revoke any active token not in the pat family' do unrelated_token = create(:personal_access_token) expect(response).to be_success expect(unrelated_token.reload).to be_active end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module PersonalAccessTokens class CreateService < BaseService def initialize(current_user:, target_user:, params: {}, concatenate_errors: true) @current_user = current_user @target_user = target_user @params = params.dup @ip_address = @params.delete(:ip_address) @concatenate_errors = concatenate_errors end def execute return ServiceResponse.error(message: 'Not permitted to create') unless creation_permitted? token = target_user.personal_access_tokens.create(personal_access_token_params) if token.persisted? log_event(token) notification_service.access_token_created(target_user, token.name) ServiceResponse.success(payload: { personal_access_token: token }) else message = token.errors.full_messages message = message.to_sentence if @concatenate_errors ServiceResponse.error(message: message, payload: { personal_access_token: token }) end end private attr_reader :target_user, :ip_address def personal_access_token_params { name: params[:name], impersonation: params[:impersonation] || false, scopes: params[:scopes], expires_at: pat_expiration } end def pat_expiration params[:expires_at].presence || PersonalAccessToken::MAX_PERSONAL_ACCESS_TOKEN_LIFETIME_IN_DAYS.days.from_now end def creation_permitted? Ability.allowed?(current_user, :create_user_personal_access_token, target_user) end def log_event(token) log_info("PAT CREATION: created_by: '#{current_user.username}', created_for: '#{token.user.username}', token_id: '#{token.id}'") end end end PersonalAccessTokens::CreateService.prepend_mod_with('PersonalAccessTokens::CreateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe PersonalAccessTokens::CreateService, feature_category: :system_access do shared_examples_for 'a successfully created token' do it 'creates personal access token record' do expect(subject.success?).to be true expect(token.name).to eq(params[:name]) expect(token.impersonation).to eq(params[:impersonation]) expect(token.scopes).to eq(params[:scopes]) expect(token.expires_at).to eq(params[:expires_at]) expect(token.user).to eq(user) end it 'logs the event' do expect(Gitlab::AppLogger).to receive(:info).with(/PAT CREATION: created_by: '#{current_user.username}', created_for: '#{user.username}', token_id: '\d+'/) subject end it 'notifies the user' do expect_next_instance_of(NotificationService) do |notification_service| expect(notification_service).to receive(:access_token_created).with(user, params[:name]) end subject end end shared_examples_for 'an unsuccessfully created token' do it { expect(subject.success?).to be false } it { expect(subject.message).to eq('Not permitted to create') } it { expect(token).to be_nil } end describe '#execute' do subject { service.execute } let(:current_user) { create(:user) } let(:user) { create(:user) } let(:params) { { name: 'Test token', impersonation: false, scopes: [:api], expires_at: Date.today + 1.month } } let(:service) { described_class.new(current_user: current_user, target_user: user, params: params, concatenate_errors: false) } let(:token) { subject.payload[:personal_access_token] } context 'when current_user is an administrator' do let(:current_user) { create(:admin) } context 'when admin mode is enabled', :enable_admin_mode do it_behaves_like 'a successfully created token' end context 'when admin mode is disabled' do it_behaves_like 'an unsuccessfully created token' end end context 'when current_user is not an administrator' do context 'target_user is not the same as current_user' do it_behaves_like 'an unsuccessfully created token' end context 'target_user is same as current_user' do let(:current_user) { user } it_behaves_like 'a successfully created token' end end context 'with no expires_at set', :freeze_time do let(:params) { { name: 'Test token', impersonation: false, scopes: [:no_valid] } } let(:service) { described_class.new(current_user: user, target_user: user, params: params) } it { expect(subject.payload[:personal_access_token].expires_at).to eq PersonalAccessToken::MAX_PERSONAL_ACCESS_TOKEN_LIFETIME_IN_DAYS.days.from_now.to_date } end context 'when invalid scope' do let(:params) { { name: 'Test token', impersonation: false, scopes: [:no_valid], expires_at: Date.today + 1.month } } context 'when concatenate_errors: true' do let(:service) { described_class.new(current_user: user, target_user: user, params: params) } it { expect(subject.message).to be_an_instance_of(String) } end context 'when concatenate_errors: false' do let(:service) { described_class.new(current_user: user, target_user: user, params: params, concatenate_errors: false) } it { expect(subject.message).to be_an_instance_of(Array) } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ExportCsv class MapExportFieldsService < BaseService attr_reader :fields, :data def initialize(fields, data) @fields = fields @data = data end def execute return data if fields.empty? selected_fields_to_hash end def invalid_fields fields.reject { |field| permitted_field?(field) } end private def selected_fields_to_hash data.select { |key| requested_field?(key) } end def requested_field?(field) field.downcase.in?(fields.map(&:downcase)) end def permitted_field?(field) field.downcase.in?(keys.map(&:downcase)) end def keys data.keys end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ExportCsv::MapExportFieldsService, feature_category: :team_planning do let(:selected_fields) { ['Title', 'Author username', 'state'] } let(:invalid_fields) { ['Title', 'Author Username', 'State', 'Invalid Field', 'Other Field'] } let(:data) do { 'Requirement ID' => '1', 'Title' => 'foo', 'Description' => 'bar', 'Author' => 'root', 'Author Username' => 'admin', 'Created At (UTC)' => '2023-02-01 15:16:35', 'State' => 'opened', 'State Updated At (UTC)' => '2023-02-01 15:16:35' } end describe '#execute' do it 'returns a hash with selected fields only' do result = described_class.new(selected_fields, data).execute expect(result).to be_a(Hash) expect(result.keys).to match_array(selected_fields.map(&:titleize)) end context 'when the fields collection is empty' do it 'returns a hash with all fields' do result = described_class.new([], data).execute expect(result).to be_a(Hash) expect(result.keys).to match_array(data.keys) end end context 'when fields collection includes invalid fields' do it 'returns a hash with valid selected fields only' do result = described_class.new(invalid_fields, data).execute expect(result).to be_a(Hash) expect(result.keys).to eq(selected_fields.map(&:titleize)) end end end describe '#invalid_fields' do it 'returns an array containing invalid fields' do result = described_class.new(invalid_fields, data).invalid_fields expect(result).to match_array(['Invalid Field', 'Other Field']) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ExportCsv class BaseService # Target attachment size before base64 encoding TARGET_FILESIZE = 15.megabytes def initialize(relation, resource_parent, fields = []) @objects = relation @resource_parent = resource_parent @fields = fields end def csv_data csv_builder.render(TARGET_FILESIZE) end def email(user) raise NotImplementedError end def invalid_fields ::ExportCsv::MapExportFieldsService.new(fields, header_to_value_hash).invalid_fields end private attr_reader :resource_parent, :objects, :fields # rubocop: disable CodeReuse/ActiveRecord def csv_builder @csv_builder ||= begin data_hash = MapExportFieldsService.new(fields, header_to_value_hash).execute if preload_associations_in_batches? CsvBuilder.new(objects, data_hash, associations_to_preload) else CsvBuilder.new(objects.preload(associations_to_preload), data_hash, []) end end end # rubocop: enable CodeReuse/ActiveRecord def associations_to_preload [] end def header_to_value_hash raise NotImplementedError end def preload_associations_in_batches? false end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ExportCsv::BaseService, feature_category: :importers do let_it_be(:issue) { create(:issue) } let_it_be(:relation) { Issue.all } let_it_be(:resource_parent) { issue.project } subject { described_class.new(relation, resource_parent) } describe '#email' do it 'raises NotImplementedError' do user = create(:user) expect { subject.email(user) }.to raise_error(NotImplementedError) end end describe '#header_to_value_hash' do it 'raises NotImplementedError' do expect { subject.send(:header_to_value_hash) }.to raise_error(NotImplementedError) end end describe '#associations_to_preload' do it 'return []' do expect(subject.send(:associations_to_preload)).to eq([]) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class PushedBranchesService < MergeRequests::BaseService include ::Gitlab::Utils::StrongMemoize # Skip moving this logic into models since it's too specific # rubocop: disable CodeReuse/ActiveRecord def execute return [] if branch_names.blank? source_branches = project.source_of_merge_requests.open_and_closed .from_source_branches(branch_names).pluck(:source_branch) target_branches = project.merge_requests.opened .by_target_branch(branch_names).distinct.pluck(:target_branch) source_branches.concat(target_branches).to_set end # rubocop: enable CodeReuse/ActiveRecord private def branch_names strong_memoize(:branch_names) do params[:changes].map do |change| Gitlab::Git.branch_name(change[:ref]) end.compact end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::PushedBranchesService, feature_category: :source_code_management do let(:project) { create(:project) } let!(:service) { described_class.new(project: project, current_user: nil, params: { changes: pushed_branches }) } context 'when branches pushed' do let(:pushed_branches) do %w[branch1 branch2 closed-branch1 closed-branch2 extra1 extra2].map do |branch| { ref: "refs/heads/#{branch}" } end end it 'returns only branches which have a open and closed merge request' do create(:merge_request, source_branch: 'branch1', source_project: project) create(:merge_request, source_branch: 'branch2', source_project: project) create(:merge_request, target_branch: 'branch2', source_project: project) create(:merge_request, :closed, target_branch: 'closed-branch1', source_project: project) create(:merge_request, :closed, source_branch: 'closed-branch2', source_project: project) create(:merge_request, source_branch: 'extra1') expect(service.execute).to contain_exactly( 'branch1', 'branch2', 'closed-branch2' ) end end context 'when tags pushed' do let(:pushed_branches) do %w[v10.0.0 v11.0.2 v12.1.0].map do |branch| { ref: "refs/tags/#{branch}" } end end it 'returns empty result without any SQL query performed' do control_count = ActiveRecord::QueryRecorder.new do expect(service.execute).to be_empty end.count expect(control_count).to be_zero end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class RebaseService < MergeRequests::BaseService REBASE_ERROR = 'Rebase failed: Rebase locally, resolve all conflicts, then push the branch.' attr_reader :merge_request, :rebase_error def validate(merge_request) return error_response(_('Source branch does not exist')) unless merge_request.source_branch_exists? return error_response(_('Cannot push to source branch')) unless user_access.can_push_to_branch?(merge_request.source_branch) return error_response(_('Source branch is protected from force push')) unless merge_request.permits_force_push? ServiceResponse.success end def execute(merge_request, skip_ci: false) @merge_request = merge_request @skip_ci = skip_ci if rebase success else error(rebase_error) end end def rebase repository.rebase(current_user, merge_request, skip_ci: @skip_ci) true rescue StandardError => e set_rebase_error(e) log_error(exception: e, message: rebase_error, save_message_on_model: true) false ensure merge_request.update_column(:rebase_jid, nil) end private def set_rebase_error(exception) @rebase_error = if exception.is_a?(Gitlab::Git::PreReceiveError) "The rebase pre-receive hook failed: #{exception.message}." else REBASE_ERROR end end def user_access Gitlab::UserAccess.new(current_user, container: project) end def error_response(message) ServiceResponse.error(message: message) end end end ::MergeRequests::RebaseService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::RebaseService, feature_category: :source_code_management do include ProjectForksHelper let(:user) { create(:user) } let(:rebase_jid) { 'fake-rebase-jid' } let(:merge_request) do create( :merge_request, source_branch: 'feature_conflict', target_branch: 'master', rebase_jid: rebase_jid ) end let(:project) { merge_request.project } let(:repository) { project.repository.raw } let(:skip_ci) { false } subject(:service) { described_class.new(project: project, current_user: user) } before do project.add_maintainer(user) end describe '#validate' do subject { service.validate(merge_request) } it { is_expected.to be_success } context 'when source branch does not exist' do before do merge_request.update!(source_branch: 'does_not_exist') end it 'returns an error' do is_expected.to be_error expect(subject.message).to eq('Source branch does not exist') end end context 'when user has no permissions to rebase' do before do project.add_guest(user) end it 'returns an error' do is_expected.to be_error expect(subject.message).to eq('Cannot push to source branch') end end context 'when branch is protected' do before do create(:protected_branch, project: project, name: merge_request.source_branch, allow_force_push: false) end it 'returns an error' do is_expected.to be_error expect(subject.message).to eq('Source branch is protected from force push') end end end describe '#execute' do shared_examples 'sequence of failure and success' do it 'properly clears the error message' do allow(repository).to receive(:gitaly_operation_client).and_raise('Something went wrong') service.execute(merge_request) merge_request.reload expect(merge_request.reload.merge_error).to eq(described_class::REBASE_ERROR) expect(merge_request.rebase_jid).to eq(nil) allow(repository).to receive(:gitaly_operation_client).and_call_original merge_request.update!(rebase_jid: rebase_jid) service.execute(merge_request) merge_request.reload expect(merge_request.merge_error).to eq(nil) expect(merge_request.rebase_jid).to eq(nil) end end it_behaves_like 'sequence of failure and success' context 'when unexpected error occurs' do let(:exception) { RuntimeError.new('Something went wrong') } let(:merge_request_ref) { merge_request.to_reference(full: true) } before do allow(repository).to receive(:gitaly_operation_client).and_raise(exception) end it 'saves a generic error message' do service.execute(merge_request) expect(merge_request.reload.merge_error).to eq(described_class::REBASE_ERROR) end it 'returns an error' do expect(service.execute(merge_request)).to match( status: :error, message: described_class::REBASE_ERROR ) end it 'logs the error' do expect(service).to receive(:log_error).with(exception: exception, message: described_class::REBASE_ERROR, save_message_on_model: true).and_call_original expect(Gitlab::ErrorTracking).to receive(:track_exception).with(exception, { class: described_class.to_s, merge_request: merge_request_ref, merge_request_id: merge_request.id, message: described_class::REBASE_ERROR, save_message_on_model: true }).and_call_original service.execute(merge_request) end end context 'with a pre-receive failure' do let(:pre_receive_error) { "Commit message does not follow the pattern 'ACME'" } let(:merge_error) { "The rebase pre-receive hook failed: #{pre_receive_error}." } before do allow(repository).to receive(:gitaly_operation_client).and_raise(Gitlab::Git::PreReceiveError, "GitLab: #{pre_receive_error}") end it 'saves a specific message' do subject.execute(merge_request) expect(merge_request.reload.merge_error).to eq merge_error end it 'returns an error' do expect(service.execute(merge_request)).to match( status: :error, message: merge_error) end end context 'with git command failure' do before do allow(repository).to receive(:gitaly_operation_client).and_raise(Gitlab::Git::Repository::GitError, 'Something went wrong') end it 'saves a generic error message' do subject.execute(merge_request) expect(merge_request.reload.merge_error).to eq described_class::REBASE_ERROR end it 'returns an error' do expect(service.execute(merge_request)).to match( status: :error, message: described_class::REBASE_ERROR ) end end context 'valid params' do shared_examples_for 'a service that can execute a successful rebase' do before do service.execute(merge_request, skip_ci: skip_ci) end it 'rebases source branch' do parent_sha = merge_request.source_project.repository.commit(merge_request.source_branch).parents.first.sha target_branch_sha = merge_request.target_project.repository.commit(merge_request.target_branch).sha expect(parent_sha).to eq(target_branch_sha) end it 'records the new SHA on the merge request' do head_sha = merge_request.source_project.repository.commit(merge_request.source_branch).sha expect(merge_request.reload.rebase_commit_sha).to eq(head_sha) end it 'logs correct author and committer' do head_commit = merge_request.source_project.repository.commit(merge_request.source_branch) expect(head_commit.author_email).to eq('[email protected]') expect(head_commit.author_name).to eq('Dmitriy Zaporozhets') expect(head_commit.committer_email).to eq(user.email) expect(head_commit.committer_name).to eq(user.name) end end it_behaves_like 'a service that can execute a successful rebase' it 'clears rebase_jid' do expect { service.execute(merge_request) } .to change(merge_request, :rebase_jid) .from(rebase_jid) .to(nil) end context 'when skip_ci flag is set' do let(:skip_ci) { true } it_behaves_like 'a service that can execute a successful rebase' end context 'fork' do describe 'successful fork rebase' do let(:forked_project) do fork_project(project, user, repository: true) end let(:merge_request_from_fork) do forked_project.repository.create_file( user, 'new-file-to-target', '', message: 'Add new file to target', branch_name: 'master') create( :merge_request, source_branch: 'master', source_project: forked_project, target_branch: 'master', target_project: project ) end it 'rebases source branch', :sidekiq_might_not_need_inline do parent_sha = forked_project.repository.commit(merge_request_from_fork.source_branch).parents.first.sha target_branch_sha = project.repository.commit(merge_request_from_fork.target_branch).sha expect(parent_sha).to eq(target_branch_sha) end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ExportCsvService < ExportCsv::BaseService include Gitlab::Routing.url_helpers include GitlabRoutingHelper def email(user) Notify.merge_requests_csv_email(user, resource_parent, csv_data, csv_builder.status).deliver_now end private def header_to_value_hash { 'Title' => 'title', 'Description' => 'description', 'MR IID' => 'iid', 'URL' => -> (merge_request) { merge_request_url(merge_request) }, 'State' => 'state', 'Source Branch' => 'source_branch', 'Target Branch' => 'target_branch', 'Source Project ID' => 'source_project_id', 'Target Project ID' => 'target_project_id', 'Author' => -> (merge_request) { merge_request.author.name }, 'Author Username' => -> (merge_request) { merge_request.author.username }, 'Assignees' => -> (merge_request) { merge_request.assignees.map(&:name).join(', ') }, 'Assignee Usernames' => -> (merge_request) { merge_request.assignees.map(&:username).join(', ') }, 'Approvers' => -> (merge_request) { merge_request.approved_by_users.map(&:name).join(', ') }, 'Approver Usernames' => -> (merge_request) { merge_request.approved_by_users.map(&:username).join(', ') }, 'Merged User' => -> (merge_request) { merge_request.metrics&.merged_by&.name.to_s }, 'Merged Username' => -> (merge_request) { merge_request.metrics&.merged_by&.username.to_s }, 'Milestone ID' => -> (merge_request) { merge_request&.milestone&.id || '' }, 'Created At (UTC)' => -> (merge_request) { merge_request.created_at.utc }, 'Updated At (UTC)' => -> (merge_request) { merge_request.updated_at.utc } } end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ExportCsvService, feature_category: :importers do let_it_be(:merge_request) { create(:merge_request) } let(:csv) { CSV.parse(subject.csv_data, headers: true).first } subject { described_class.new(MergeRequest.where(id: merge_request.id), merge_request.project) } describe 'csv_data' do it 'contains the correct information', :aggregate_failures do expect(csv['MR IID']).to eq(merge_request.iid.to_s) expect(csv['Title']).to eq(merge_request.title) expect(csv['State']).to eq(merge_request.state) expect(csv['Description']).to eq(merge_request.description) expect(csv['Source Branch']).to eq(merge_request.source_branch) expect(csv['Target Branch']).to eq(merge_request.target_branch) expect(csv['Source Project ID']).to eq(merge_request.source_project_id.to_s) expect(csv['Target Project ID']).to eq(merge_request.target_project_id.to_s) expect(csv['Author']).to eq(merge_request.author.name) expect(csv['Author Username']).to eq(merge_request.author.username) end describe 'assignees' do context 'when assigned' do let_it_be(:merge_request) { create(:merge_request, assignees: create_list(:user, 2)) } it 'contains the names of assignees' do expect(csv['Assignees'].split(', ')).to match_array(merge_request.assignees.map(&:name)) end it 'contains the usernames of assignees' do expect(csv['Assignee Usernames'].split(', ')).to match_array(merge_request.assignees.map(&:username)) end end context 'when not assigned' do it 'returns empty strings' do expect(csv['Assignees']).to eq('') expect(csv['Assignee Usernames']).to eq('') end end end describe 'approvers' do context 'when approved' do let_it_be(:merge_request) { create(:merge_request) } let(:approvers) { create_list(:user, 2) } before do merge_request.approved_by_users = approvers end it 'contains the names of approvers separated by a comma' do expect(csv['Approvers'].split(', ')).to contain_exactly(approvers[0].name, approvers[1].name) end it 'contains the usernames of approvers separated by a comma' do expect(csv['Approver Usernames'].split(', ')).to contain_exactly(approvers[0].username, approvers[1].username) end end context 'when not approved' do it 'returns empty strings' do expect(csv['Approvers']).to eq('') expect(csv['Approver Usernames']).to eq('') end end end describe 'merged user' do context 'MR is merged' do let_it_be(:merge_request) { create(:merge_request, :merged, :with_merged_metrics) } it 'is merged' do expect(csv['State']).to eq('merged') end it 'has a merged user' do expect(csv['Merged User']).to eq(merge_request.metrics.merged_by.name) expect(csv['Merged Username']).to eq(merge_request.metrics.merged_by.username) end end context 'MR is not merged' do it 'returns empty strings' do expect(csv['Merged User']).to eq('') expect(csv['Merged Username']).to eq('') end end end describe 'milestone' do context 'milestone is assigned' do let_it_be(:merge_request) { create(:merge_request) } let_it_be(:milestone) { create(:milestone, :active, project: merge_request.project) } before do merge_request.update!(milestone_id: milestone.id) end it 'contains the milestone ID' do expect(csv['Milestone ID']).to eq(merge_request.milestone.id.to_s) end end context 'no milestone is assigned' do it 'returns an empty string' do expect(csv['Milestone ID']).to eq('') end end end describe '#email' do let_it_be(:user) { create(:user) } it 'emails csv' do expect { subject.email(user) }.to change { ActionMailer::Base.deliveries.count } end it 'renders with a target filesize' do expect_next_instance_of(CsvBuilder) do |csv_builder| expect(csv_builder).to receive(:render).with(described_class::TARGET_FILESIZE).once end subject.email(user) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class LinkLfsObjectsService < ::BaseProjectService def execute(merge_request, oldrev: merge_request.diff_base_sha, newrev: merge_request.diff_head_sha) return if merge_request.source_project == project return if no_changes?(oldrev, newrev) new_lfs_oids = lfs_oids(merge_request.source_project.repository, oldrev, newrev) return if new_lfs_oids.empty? Projects::LfsPointers::LfsLinkService .new(project) .execute(new_lfs_oids) end private def no_changes?(oldrev, newrev) oldrev == newrev end def lfs_oids(source_repository, oldrev, newrev) Gitlab::Git::LfsChanges .new(source_repository, newrev) .new_pointers(not_in: [oldrev]) .map(&:lfs_oid) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::LinkLfsObjectsService, :sidekiq_inline, feature_category: :code_review_workflow do include ProjectForksHelper include RepoHelpers let(:target_project) { create(:project, :public, :repository) } let(:merge_request) do create( :merge_request, target_project: target_project, target_branch: 'lfs', source_project: source_project, source_branch: 'link-lfs-objects' ) end subject { described_class.new(project: target_project) } shared_examples_for 'linking LFS objects' do context 'when source project is the same as target project' do let(:source_project) { target_project } it 'does not call Projects::LfsPointers::LfsLinkService#execute' do expect(Projects::LfsPointers::LfsLinkService).not_to receive(:new) execute end end context 'when source project is different from target project' do let(:user) { create(:user) } let(:source_project) { fork_project(target_project, user, namespace: user.namespace, repository: true) } before do create_branch(source_project, 'link-lfs-objects', 'lfs') end context 'and there are changes' do before do allow(source_project).to receive(:lfs_enabled?).and_return(true) end context 'and there are LFS objects added' do before do create_file_in_repo(source_project, 'link-lfs-objects', 'link-lfs-objects', 'one.lfs', 'One') create_file_in_repo(source_project, 'link-lfs-objects', 'link-lfs-objects', 'two.lfs', 'Two') end it 'calls Projects::LfsPointers::LfsLinkService#execute with OIDs of LFS objects in merge request' do expect_next_instance_of(Projects::LfsPointers::LfsLinkService) do |service| expect(service).to receive(:execute).with( %w[ 8b12507783d5becacbf2ebe5b01a60024d8728a8f86dcc818bce699e8b3320bc 94a72c074cfe574742c9e99e863322f73feff82981d065ff65a0308f44f19f62 ]) end execute end end context 'but there are no LFS objects added' do before do create_file_in_repo(source_project, 'link-lfs-objects', 'link-lfs-objects', 'one.txt', 'One') end it 'does not call Projects::LfsPointers::LfsLinkService#execute' do expect(Projects::LfsPointers::LfsLinkService).not_to receive(:new) execute end end end context 'and there are no changes' do it 'does not call Projects::LfsPointers::LfsLinkService#execute' do expect(Projects::LfsPointers::LfsLinkService).not_to receive(:new) execute end end end end context 'when no oldrev and newrev passed' do let(:execute) { subject.execute(merge_request) } it_behaves_like 'linking LFS objects' end context 'when oldrev and newrev are passed' do let(:execute) { subject.execute(merge_request, oldrev: merge_request.diff_base_sha, newrev: merge_request.diff_head_sha) } it_behaves_like 'linking LFS objects' end def create_branch(project, new_name, branch_name) ::Branches::CreateService.new(project, user).execute(new_name, branch_name) end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class MergeabilityCheckService < ::BaseService include Gitlab::Utils::StrongMemoize include Gitlab::ExclusiveLeaseHelpers delegate :project, to: :@merge_request delegate :repository, to: :project def initialize(merge_request) @merge_request = merge_request end def async_execute return service_error if service_error merge_request.mark_as_checking MergeRequestMergeabilityCheckWorker.perform_async(merge_request.id) end # Updates the MR merge_status. Whenever it switches to a can_be_merged state, # the merge-ref is refreshed. # # recheck - When given, it'll enforce a merge-ref refresh if the current merge_status is # can_be_merged or cannot_be_merged and merge-ref is outdated. # Given MergeRequests::RefreshService is called async, it might happen that the target # branch gets updated, but the MergeRequest#merge_status lags behind. So in scenarios # where we need the current state of the merge ref in repository, the `recheck` # argument is required. # # retry_lease - Concurrent calls wait for at least 10 seconds until the # lease is granted (other process finishes running). Returns an error # ServiceResponse if the lease is not granted during this time. # # Returns a ServiceResponse indicating merge_status is/became can_be_merged # and the merge-ref is synced. Success in case of being/becoming mergeable, # error otherwise. def execute(recheck: false, retry_lease: true) return service_error if service_error in_write_lock(retry_lease: retry_lease) do |retried| # When multiple calls are waiting for the same lock (retry_lease), # it's possible that when granted, the MR status was already updated for # that object, therefore we reset if there was a lease retry. merge_request.reset if retried check_mergeability(recheck) end rescue FailedToObtainLockError => error ServiceResponse.error(message: error.message) end private attr_reader :merge_request def check_mergeability(recheck) recheck! if recheck update_merge_status unless merge_request.can_be_merged? return ServiceResponse.error(message: 'Merge request is not mergeable') end unless payload.fetch(:merge_ref_head) return ServiceResponse.error(message: 'Merge ref cannot be updated') end ServiceResponse.success(payload: payload) end # It's possible for this service to send concurrent requests to Gitaly in order # to "git update-ref" the same ref. Therefore we handle a light exclusive # lease here. # def in_write_lock(retry_lease:, &block) lease_key = "mergeability_check:#{merge_request.id}" lease_opts = { ttl: 1.minute, retries: retry_lease ? 10 : 0, sleep_sec: retry_lease ? 1.second : 0 } in_lock(lease_key, **lease_opts, &block) end def payload strong_memoize(:payload) do { merge_ref_head: merge_ref_head_payload } end end def merge_ref_head_payload commit = merge_request.merge_ref_head return unless commit target_id, source_id = commit.parent_ids { commit_id: commit.id, source_id: source_id, target_id: target_id } end def update_merge_status return unless merge_request.recheck_merge_status? return merge_request.mark_as_unmergeable if merge_request.broken? merge_to_ref_success = merge_to_ref reload_merge_head_diff update_diff_discussion_positions! if merge_to_ref_success if merge_to_ref_success && can_git_merge? merge_request.mark_as_mergeable else merge_request.mark_as_unmergeable end end def reload_merge_head_diff MergeRequests::ReloadMergeHeadDiffService.new(merge_request).execute end def update_diff_discussion_positions! Discussions::CaptureDiffNotePositionsService.new(merge_request).execute end def recheck! if !merge_request.recheck_merge_status? && outdated_merge_ref? merge_request.mark_as_unchecked end end # Checks if the existing merge-ref is synced with the target branch. # # Returns true if the merge-ref does not exists or is out of sync. def outdated_merge_ref? return false unless merge_request.open? return true unless ref_head = merge_request.merge_ref_head return true unless target_sha = merge_request.target_branch_sha return true unless source_sha = merge_request.source_branch_sha ref_head.parent_ids != [target_sha, source_sha] end def can_git_merge? repository.can_be_merged?(merge_request.diff_head_sha, merge_request.target_branch) end def merge_to_ref result = MergeRequests::MergeToRefService.new(project: project, current_user: merge_request.author, params: {}).execute(merge_request) result[:status] == :success end def service_error strong_memoize(:service_error) do if !merge_request ServiceResponse.error(message: 'Invalid argument') elsif Gitlab::Database.read_only? ServiceResponse.error(message: 'Unsupported operation') end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::MergeabilityCheckService, :clean_gitlab_redis_shared_state, feature_category: :code_review_workflow do shared_examples_for 'unmergeable merge request' do it 'updates or keeps merge status as cannot_be_merged' do subject expect(merge_request.merge_status).to eq('cannot_be_merged') end it 'does not change the merge ref HEAD' do merge_ref_head = merge_request.merge_ref_head subject expect(merge_request.reload.merge_ref_head).to eq merge_ref_head end it 'returns ServiceResponse.error' do result = subject expect(result).to be_a(ServiceResponse) expect(result).to be_error end end shared_examples_for 'mergeable merge request' do it 'updates or keeps merge status as can_be_merged' do subject expect(merge_request.merge_status).to eq('can_be_merged') end it 'reloads merge head diff' do expect_next_instance_of(MergeRequests::ReloadMergeHeadDiffService) do |service| expect(service).to receive(:execute) end subject end it 'update diff discussion positions' do expect_next_instance_of(Discussions::CaptureDiffNotePositionsService) do |service| expect(service).to receive(:execute) end subject end it 'updates the merge ref' do expect { subject }.to change(merge_request, :merge_ref_head).from(nil) end it 'returns ServiceResponse.success' do result = subject expect(result).to be_a(ServiceResponse) expect(result).to be_success end it 'ServiceResponse has merge_ref_head payload' do result = subject expect(result.payload.keys).to contain_exactly(:merge_ref_head) expect(result.payload[:merge_ref_head].keys) .to contain_exactly(:commit_id, :target_id, :source_id) end end let(:project) { create(:project, :repository) } let(:merge_request) { create(:merge_request, merge_status: :unchecked, source_project: project, target_project: project) } describe '#async_execute' do it 'updates merge status to checking' do described_class.new(merge_request).async_execute expect(merge_request).to be_checking end it 'enqueues MergeRequestMergeabilityCheckWorker' do expect(MergeRequestMergeabilityCheckWorker).to receive(:perform_async) described_class.new(merge_request).async_execute end context 'when read-only DB' do before do allow(Gitlab::Database).to receive(:read_only?) { true } end it 'does not enqueue MergeRequestMergeabilityCheckWorker' do expect(MergeRequestMergeabilityCheckWorker).not_to receive(:perform_async) described_class.new(merge_request).async_execute end end end describe '#execute' do let(:repo) { project.repository } subject { described_class.new(merge_request).execute } def execute_within_threads(amount:, retry_lease: true) threads = [] amount.times do # Let's use a different object for each thread to get closer # to a real world scenario. mr = MergeRequest.find(merge_request.id) threads << Thread.new do described_class.new(mr).execute(retry_lease: retry_lease) end end threads.each(&:join) threads end before do project.add_developer(merge_request.author) end it_behaves_like 'mergeable merge request' context 'when concurrent calls' do it 'waits first lock and returns "cached" result in subsequent calls' do threads = execute_within_threads(amount: 3) results = threads.map { |t| t.value.status } expect(results).to contain_exactly(:success, :success, :success) end it 'writes the merge-ref once' do service = instance_double(MergeRequests::MergeToRefService) expect(MergeRequests::MergeToRefService).to receive(:new).once { service } expect(service).to receive(:execute).once.and_return(success: true) execute_within_threads(amount: 3) end it 'resets one merge request upon execution' do expect_next_instance_of(MergeRequests::ReloadMergeHeadDiffService) do |svc| expect(svc).to receive(:execute).and_return(status: :success) end expect_any_instance_of(MergeRequest).to receive(:reset).once.and_call_original execute_within_threads(amount: 2) end context 'when retry_lease flag is false' do it 'the first call succeeds, subsequent concurrent calls get a lock error response' do threads = execute_within_threads(amount: 3, retry_lease: false) results = threads.map { |t| [t.value.status, t.value.message] } expect(results).to contain_exactly( [:error, 'Failed to obtain a lock'], [:error, 'Failed to obtain a lock'], [:success, nil] ) end end end context 'when broken' do before do expect(merge_request).to receive(:broken?) { true } end it_behaves_like 'unmergeable merge request' it 'returns ServiceResponse.error' do result = subject expect(result).to be_a(ServiceResponse) expect(result.error?).to be(true) expect(result.message).to eq('Merge request is not mergeable') end end context 'when it cannot be merged on git' do let(:merge_request) do create( :merge_request, merge_status: :unchecked, source_branch: 'conflict-resolvable', source_project: project, target_branch: 'conflict-start' ) end it 'returns ServiceResponse.error and keeps merge status as cannot_be_merged' do result = subject expect(merge_request.merge_status).to eq('cannot_be_merged') expect(result).to be_a(ServiceResponse) expect(result.error?).to be(true) expect(result.message).to eq('Merge request is not mergeable') end end context 'when MR cannot be merged and has no merge ref' do before do merge_request.mark_as_unmergeable! end it_behaves_like 'unmergeable merge request' it 'returns ServiceResponse.error' do result = subject expect(result).to be_a(ServiceResponse) expect(result.error?).to be(true) expect(result.message).to eq('Merge request is not mergeable') end end context 'when MR cannot be merged and has outdated merge ref' do before do MergeRequests::MergeToRefService.new(project: project, current_user: merge_request.author).execute(merge_request) merge_request.mark_as_unmergeable! end it_behaves_like 'unmergeable merge request' it 'returns ServiceResponse.error' do result = subject expect(result).to be_a(ServiceResponse) expect(result.error?).to be(true) expect(result.message).to eq('Merge request is not mergeable') end end context 'when merge request is not given' do subject { described_class.new(nil).execute } it 'returns ServiceResponse.error' do result = subject expect(result).to be_a(ServiceResponse) expect(result.message).to eq('Invalid argument') end end context 'when read-only DB' do it 'returns ServiceResponse.error' do allow(Gitlab::Database).to receive(:read_only?) { true } result = subject expect(result).to be_a(ServiceResponse) expect(result.message).to eq('Unsupported operation') end end context 'when fails to update the merge-ref' do before do expect_next_instance_of(MergeRequests::MergeToRefService) do |merge_to_ref| expect(merge_to_ref).to receive(:execute).and_return(status: :failed) end end it_behaves_like 'unmergeable merge request' it 'reloads merge head diff' do expect_next_instance_of(MergeRequests::ReloadMergeHeadDiffService) do |service| expect(service).to receive(:execute) end subject end it 'returns ServiceResponse.error' do result = subject expect(result).to be_a(ServiceResponse) expect(result.error?).to be(true) expect(result.message).to eq('Merge request is not mergeable') end end context 'recheck enforced' do subject { described_class.new(merge_request).execute(recheck: true) } context 'when MR is marked as mergeable, but repo is not mergeable and MR is not opened' do before do # Making sure that we don't touch the merge-status after # the MR is not opened any longer. Source branch might # have been removed, etc. allow(merge_request).to receive(:broken?) { true } merge_request.mark_as_mergeable! merge_request.close! end it 'returns ServiceResponse.error' do result = subject expect(result).to be_a(ServiceResponse) expect(result.error?).to be(true) expect(result.message).to eq('Merge ref cannot be updated') expect(result.payload).to be_empty end it 'does not change the merge status' do expect { subject }.not_to change(merge_request, :merge_status).from('can_be_merged') end end context 'when MR is mergeable but merge-ref does not exists' do before do merge_request.mark_as_mergeable! end it_behaves_like 'mergeable merge request' end context 'when MR is mergeable but merge-ref is already updated' do before do MergeRequests::MergeToRefService.new(project: project, current_user: merge_request.author).execute(merge_request) merge_request.mark_as_mergeable! end it 'returns ServiceResponse.success' do result = subject expect(result).to be_a(ServiceResponse) expect(result).to be_success expect(result.payload[:merge_ref_head]).to be_present end it 'does not recreate the merge-ref' do expect(MergeRequests::MergeToRefService).not_to receive(:new) subject end it 'does not reload merge head diff' do expect(MergeRequests::ReloadMergeHeadDiffService).not_to receive(:new) subject end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class AssignIssuesService < BaseProjectService def assignable_issues @assignable_issues ||= if current_user == merge_request.author closes_issues.select do |issue| !issue.is_a?(ExternalIssue) && !issue.assignees.present? && can?(current_user, :admin_issue, issue) end else [] end end def execute assignable_issues.each do |issue| Issues::UpdateService.new(container: issue.project, current_user: current_user, params: { assignee_ids: [current_user.id] }).execute(issue) end { count: assignable_issues.count } end private def merge_request params[:merge_request] end def closes_issues @closes_issues ||= params[:closes_issues] || merge_request.closes_issues(current_user) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::AssignIssuesService, feature_category: :code_review_workflow do let(:user) { create(:user) } let(:project) { create(:project, :public, :repository) } let(:issue) { create(:issue, project: project) } let(:merge_request) { create(:merge_request, :simple, source_project: project, author: user, description: "fixes #{issue.to_reference}") } let(:service) { described_class.new(project: project, current_user: user, params: { merge_request: merge_request }) } before do project.add_developer(user) end it 'finds unassigned issues fixed in merge request' do expect(service.assignable_issues.map(&:id)).to include(issue.id) end it 'ignores issues the user cannot update assignee on', :sidekiq_inline do project.team.truncate expect(service.assignable_issues).to be_empty end it 'ignores issues already assigned to any user' do issue.assignees = [create(:user)] expect(service.assignable_issues).to be_empty end it 'ignores all issues unless current_user is merge_request.author' do merge_request.update!(author: create(:user)) expect(service.assignable_issues).to be_empty end it 'accepts precomputed data for closes_issues' do issue2 = create(:issue, project: project) service2 = described_class.new( project: project, current_user: user, params: { merge_request: merge_request, closes_issues: [issue, issue2] } ) expect(service2.assignable_issues.count).to eq 2 end it 'assigns these to the merge request owner' do expect { service.execute }.to change { issue.assignees.first }.to(user) end it 'ignores external issues' do external_issue = ExternalIssue.new('JIRA-123', project) service = described_class.new( project: project, current_user: user, params: { merge_request: merge_request, closes_issues: [external_issue] } ) expect(service.assignable_issues.count).to eq 0 end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ReloadDiffsService def initialize(merge_request, current_user) @merge_request = merge_request @current_user = current_user end def execute old_diff_refs = merge_request.diff_refs new_diff = merge_request.create_merge_request_diff clear_cache(new_diff) update_diff_discussion_positions(old_diff_refs) end private attr_reader :merge_request, :current_user def update_diff_discussion_positions(old_diff_refs) new_diff_refs = merge_request.diff_refs merge_request.update_diff_discussion_positions( old_diff_refs: old_diff_refs, new_diff_refs: new_diff_refs, current_user: current_user ) end # rubocop: disable CodeReuse/ActiveRecord def clear_cache(new_diff) # Remove cache for all diffs on this MR. Do not use the association on the # model, as that will interfere with other actions happening when # reloading the diff. MergeRequestDiff .where(merge_request: merge_request) .preload(merge_request: :target_project) .find_each do |merge_request_diff| next if merge_request_diff == new_diff cacheable_collection(merge_request_diff).clear_cache end end # rubocop: enable CodeReuse/ActiveRecord def cacheable_collection(diff) # There are scenarios where we don't need to request Diff Stats. # Mainly when clearing / writing diff caches. diff.diffs(include_stats: false) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ReloadDiffsService, :use_clean_rails_memory_store_caching, feature_category: :code_review_workflow do let(:current_user) { create(:user) } let(:merge_request) { create(:merge_request) } let(:subject) { described_class.new(merge_request, current_user) } describe '#execute' do it 'creates new merge request diff' do expect { subject.execute }.to change { merge_request.merge_request_diffs.count }.by(1) end it 'calls update_diff_discussion_positions with correct params' do old_diff_refs = merge_request.diff_refs new_diff = merge_request.create_merge_request_diff new_diff_refs = merge_request.diff_refs expect(merge_request).to receive(:create_merge_request_diff).and_return(new_diff) expect(merge_request).to receive(:update_diff_discussion_positions).with( old_diff_refs: old_diff_refs, new_diff_refs: new_diff_refs, current_user: current_user ) subject.execute end it 'does not change existing merge request diff' do expect(merge_request.merge_request_diff).not_to receive(:save_git_content) subject.execute end context 'cache clearing' do it 'clears the cache for older diffs on the merge request' do expect_next_instance_of(Gitlab::Diff::FileCollection::MergeRequestDiff) do |instance| expect(instance).to receive(:clear_cache).and_call_original end subject.execute end it 'avoids N+1 queries', :request_store do current_user merge_request control_count = ActiveRecord::QueryRecorder.new do subject.execute end.count expect { subject.execute }.not_to exceed_query_limit(control_count) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class MigrateExternalDiffsService < ::BaseService MAX_JOBS = 1000 attr_reader :diff def self.enqueue! ids = MergeRequestDiff.ids_for_external_storage_migration(limit: MAX_JOBS) # rubocop:disable Scalability/BulkPerformWithContext # https://gitlab.com/gitlab-org/gitlab/issues/202100 MigrateExternalDiffsWorker.bulk_perform_async(ids.map { |id| [id] }) # rubocop:enable Scalability/BulkPerformWithContext end def initialize(merge_request_diff) @diff = merge_request_diff end def execute diff.migrate_files_to_external_storage! end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::MigrateExternalDiffsService, feature_category: :code_review_workflow do let(:merge_request) { create(:merge_request) } let(:diff) { merge_request.merge_request_diff } describe '.enqueue!' do around do |example| Sidekiq::Testing.fake! { example.run } end it 'enqueues nothing if external diffs are disabled' do expect(diff).not_to be_stored_externally expect { described_class.enqueue! } .not_to change { MigrateExternalDiffsWorker.jobs.count } end it 'enqueues eligible in-database diffs if external diffs are enabled' do expect(diff).not_to be_stored_externally stub_external_diffs_setting(enabled: true) expect { described_class.enqueue! } .to change { MigrateExternalDiffsWorker.jobs.count } .by(1) end end describe '#execute' do it 'migrates an in-database diff to the external store' do expect(diff).not_to be_stored_externally stub_external_diffs_setting(enabled: true) described_class.new(diff).execute expect(diff).to be_stored_externally end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class UpdateReviewerStateService < MergeRequests::BaseService def execute(merge_request, state) return error("Invalid permissions") unless can?(current_user, :update_merge_request, merge_request) reviewer = merge_request.find_reviewer(current_user) if reviewer return error("Failed to update reviewer") unless reviewer.update(state: state) trigger_merge_request_reviewers_updated(merge_request) return success if state != 'requested_changes' if merge_request.approved_by?(current_user) && !remove_approval(merge_request) return error("Failed to remove approval") end success else error("Reviewer not found") end end private def remove_approval(merge_request) MergeRequests::RemoveApprovalService.new(project: project, current_user: current_user) .execute(merge_request) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::UpdateReviewerStateService, feature_category: :code_review_workflow do let_it_be(:current_user) { create(:user) } let_it_be(:merge_request) { create(:merge_request, reviewers: [current_user]) } let(:reviewer) { merge_request.merge_request_reviewers.find_by(user_id: current_user.id) } let(:project) { merge_request.project } let(:service) { described_class.new(project: project, current_user: current_user) } let(:state) { 'requested_changes' } let(:result) { service.execute(merge_request, state) } before do project.add_developer(current_user) end describe '#execute' do shared_examples_for 'failed service execution' do it 'returns an error' do expect(result[:status]).to eq :error end it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { result } end end describe 'invalid permissions' do let(:service) { described_class.new(project: project, current_user: create(:user)) } it_behaves_like 'failed service execution' end describe 'reviewer exists' do it 'returns success' do expect(result[:status]).to eq :success end it 'updates reviewers state' do expect(result[:status]).to eq :success expect(reviewer.state).to eq 'requested_changes' end it 'does not call MergeRequests::RemoveApprovalService' do expect(MergeRequests::RemoveApprovalService).not_to receive(:new) expect(result[:status]).to eq :success end it_behaves_like 'triggers GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { result } end context 'when reviewer has approved' do before do create(:approval, user: current_user, merge_request: merge_request) end it 'removes approval when state is requested_changes' do expect_next_instance_of( MergeRequests::RemoveApprovalService, project: project, current_user: current_user ) do |service| expect(service).to receive(:execute).with(merge_request).and_return({ success: true }) end expect(result[:status]).to eq :success end it 'renders error when remove approval service fails' do expect_next_instance_of( MergeRequests::RemoveApprovalService, project: project, current_user: current_user ) do |service| expect(service).to receive(:execute).with(merge_request).and_return(nil) end expect(result[:status]).to eq :error expect(result[:message]).to eq "Failed to remove approval" end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class RetargetChainService < MergeRequests::BaseService MAX_RETARGET_MERGE_REQUESTS = 4 def execute(merge_request) # we can only retarget MRs that are targeting the same project return unless merge_request.for_same_project? && merge_request.merged? # find another merge requests that # - as a target have a current source project and branch other_merge_requests = merge_request.source_project .merge_requests .opened .by_target_branch(merge_request.source_branch) .preload_source_project .limit(MAX_RETARGET_MERGE_REQUESTS) other_merge_requests.find_each do |other_merge_request| # Update only MRs on projects that we have access to next unless can?(current_user, :update_merge_request, other_merge_request.source_project) ::MergeRequests::UpdateService.new( project: other_merge_request.source_project, current_user: current_user, params: { target_branch: merge_request.target_branch, target_branch_was_deleted: true } ).execute(other_merge_request) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::RetargetChainService, feature_category: :code_review_workflow do include ProjectForksHelper let_it_be(:user) { create(:user) } let_it_be(:merge_request, reload: true) { create(:merge_request, assignees: [user]) } let_it_be(:project) { merge_request.project } subject { described_class.new(project: project, current_user: user).execute(merge_request) } before do project.add_maintainer(user) end describe '#execute' do context 'when there is another MR' do let!(:another_merge_request) do create(:merge_request, source_project: source_project, source_branch: 'my-awesome-feature', target_project: merge_request.source_project, target_branch: merge_request.source_branch ) end shared_examples 'does not retarget merge request' do it 'another merge request is unchanged' do expect { subject }.not_to change { another_merge_request.reload.target_branch } .from(merge_request.source_branch) end end shared_examples 'retargets merge request' do it 'another merge request is retargeted' do expect(SystemNoteService) .to receive(:change_branch).once .with(another_merge_request, another_merge_request.project, user, 'target', 'delete', merge_request.source_branch, merge_request.target_branch) expect { subject }.to change { another_merge_request.reload.target_branch } .from(merge_request.source_branch) .to(merge_request.target_branch) end end context 'in the same project' do let(:source_project) { project } context 'and current is merged' do before do merge_request.mark_as_merged end it_behaves_like 'retargets merge request' end context 'and current is closed' do before do merge_request.close end it_behaves_like 'does not retarget merge request' end context 'and another is closed' do before do another_merge_request.close end it_behaves_like 'does not retarget merge request' end context 'and another is merged' do before do another_merge_request.mark_as_merged end it_behaves_like 'does not retarget merge request' end end context 'in forked project' do let!(:source_project) { fork_project(project) } context 'when user has access to source project' do before do source_project.add_developer(user) merge_request.mark_as_merged end it_behaves_like 'retargets merge request' end context 'when user does not have access to source project' do it_behaves_like 'does not retarget merge request' end end context 'and current and another MR is from a fork' do let(:project) { create(:project) } let(:source_project) { fork_project(project) } let(:merge_request) do create(:merge_request, source_project: source_project, target_project: project ) end before do source_project.add_developer(user) end it_behaves_like 'does not retarget merge request' end end context 'when many merge requests are to be retargeted' do let!(:many_merge_requests) do create_list(:merge_request, 10, :unique_branches, source_project: merge_request.source_project, target_project: merge_request.source_project, target_branch: merge_request.source_branch ) end before do merge_request.mark_as_merged end it 'retargets only 4 of them' do subject expect(many_merge_requests.each(&:reload).pluck(:target_branch).tally) .to eq( merge_request.source_branch => 6, merge_request.target_branch => 4 ) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class CleanupRefsService include BaseServiceUtility TIME_THRESHOLD = 14.days attr_reader :merge_request def self.schedule(merge_request) merge_request.create_cleanup_schedule(scheduled_at: TIME_THRESHOLD.from_now) end def initialize(merge_request) @merge_request = merge_request @repository = merge_request.project.repository @ref_path = merge_request.ref_path @ref_head_sha = @repository.commit(merge_request.ref_path)&.id @merge_ref_sha = merge_request.merge_ref_head&.id end def execute return error("Merge request is not scheduled to be cleaned up yet.") unless scheduled? return error("Merge request has not been closed nor merged for #{TIME_THRESHOLD.inspect}.") unless eligible? # Ensure that commit shas of refs are kept around so we won't lose them when GC runs. keep_around return error('Failed to create keep around refs.') unless kept_around? return error('Failed to cache merge ref sha.') unless cache_merge_ref_sha delete_refs if repository.exists? return error('Failed to update schedule.') unless update_schedule success rescue Gitlab::Git::Repository::GitError, Gitlab::Git::CommandError => e error(e.message) end private attr_reader :repository, :ref_path, :ref_head_sha, :merge_ref_sha def scheduled? merge_request.cleanup_schedule.present? && merge_request.cleanup_schedule.scheduled_at <= Time.current end def eligible? return met_time_threshold?(merge_request.metrics&.latest_closed_at) if merge_request.closed? merge_request.merged? && met_time_threshold?(merge_request.metrics&.merged_at) end def met_time_threshold?(attr) attr.nil? || attr.to_i <= TIME_THRESHOLD.ago.to_i end def kept_around? service = Gitlab::Git::KeepAround.new(repository) [ref_head_sha, merge_ref_sha].compact.all? do |sha| service.kept_around?(sha) end end def keep_around repository.keep_around(ref_head_sha, merge_ref_sha) end def cache_merge_ref_sha return true if merge_ref_sha.nil? # Caching the merge ref sha is needed before we delete the merge ref so # we can still show the merge ref diff (via `MergeRequest#merge_ref_head`) merge_request.update_column(:merge_ref_sha, merge_ref_sha) end def delete_refs merge_request.schedule_cleanup_refs end def update_schedule merge_request.cleanup_schedule.update(completed_at: Time.current) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::CleanupRefsService, feature_category: :code_review_workflow do describe '.schedule' do let(:merge_request) { create(:merge_request) } it 'creates a merge request cleanup schedule' do freeze_time do described_class.schedule(merge_request) expect(merge_request.reload.cleanup_schedule.scheduled_at) .to eq(described_class::TIME_THRESHOLD.from_now) end end end describe '#execute' do before do stub_feature_flags(merge_request_delete_gitaly_refs_in_batches: false) stub_feature_flags(merge_request_cleanup_ref_worker_async: false) # Need to re-enable this as it's being stubbed in spec_helper for # performance reasons but is needed to run for this test. allow(Gitlab::Git::KeepAround).to receive(:execute).and_call_original merge_request.create_cleanup_schedule(scheduled_at: described_class::TIME_THRESHOLD.ago) end subject(:result) { described_class.new(merge_request).execute } shared_examples_for 'service that cleans up merge request refs' do it 'creates keep around ref and deletes merge request refs' do old_ref_head = ref_head aggregate_failures do expect(result[:status]).to eq(:success) expect(kept_around?(old_ref_head)).to be_truthy expect(ref_head).to be_nil expect(merge_request.cleanup_schedule.completed_at).to be_present end end context 'when merge request has no head ref' do before do # Simulate a merge request with no head ref merge_request.project.repository.delete_refs(merge_request.ref_path) end it 'does not fail' do expect(result[:status]).to eq(:success) expect(merge_request.cleanup_schedule.completed_at).to be_present end end context 'when merge request has merge ref' do before do MergeRequests::MergeToRefService .new(project: merge_request.project, current_user: merge_request.author) .execute(merge_request) end it 'caches merge ref sha and deletes merge ref' do old_merge_ref_head = merge_request.merge_ref_head aggregate_failures do expect(result[:status]).to eq(:success) expect(kept_around?(old_merge_ref_head)).to be_truthy expect(merge_request.reload.merge_ref_sha).to eq(old_merge_ref_head.id) expect(ref_exists?(merge_request.merge_ref_path)).to be_falsy end end context 'when merge ref sha cannot be cached' do before do allow(merge_request) .to receive(:update_column) .with(:merge_ref_sha, merge_request.merge_ref_head.id) .and_return(false) end it_behaves_like 'service that does not clean up merge request refs' end end context 'when keep around ref cannot be created' do before do allow_next_instance_of(Gitlab::Git::KeepAround) do |keep_around| expect(keep_around).to receive(:kept_around?).and_return(false) end end it_behaves_like 'service that does not clean up merge request refs' end context 'when a git error is raised' do context 'Gitlab::Git::Repository::GitError' do before do allow(merge_request.project.repository).to receive(:delete_refs).and_raise(Gitlab::Git::Repository::GitError) end it_behaves_like 'service that does not clean up merge request refs' end context 'Gitlab::Git::CommandError' do before do allow_next_instance_of(Gitlab::Git::KeepAround) do |keep_around| expect(keep_around).to receive(:kept_around?).and_raise(Gitlab::Git::CommandError) end end it_behaves_like 'service that does not clean up merge request refs' end end context 'when cleanup schedule fails to update' do before do allow(merge_request.cleanup_schedule).to receive(:update).and_return(false) end it 'creates keep around ref and deletes merge request refs' do old_ref_head = ref_head aggregate_failures do expect(result[:status]).to eq(:error) expect(kept_around?(old_ref_head)).to be_truthy expect(ref_head).to be_nil expect(merge_request.cleanup_schedule.completed_at).not_to be_present end end end context 'when merge request is not scheduled to be cleaned up yet' do before do merge_request.cleanup_schedule.update!(scheduled_at: 1.day.from_now) end it_behaves_like 'service that does not clean up merge request refs' end context 'when repository no longer exists' do before do Repositories::DestroyService.new(merge_request.project.repository).execute end it 'does not fail and still mark schedule as complete' do aggregate_failures do expect(result[:status]).to eq(:success) expect(merge_request.cleanup_schedule.completed_at).to be_present end end end end shared_examples_for 'service that does not clean up merge request refs' do it 'does not delete merge request refs' do aggregate_failures do expect(result[:status]).to eq(:error) expect(ref_head).to be_present expect(merge_request.cleanup_schedule.completed_at).not_to be_present end end end context 'when merge request is closed' do let(:merge_request) { create(:merge_request, :closed) } context "when closed #{described_class::TIME_THRESHOLD.inspect} ago" do before do merge_request.metrics.update!(latest_closed_at: described_class::TIME_THRESHOLD.ago) end it_behaves_like 'service that cleans up merge request refs' end context "when closed later than #{described_class::TIME_THRESHOLD.inspect} ago" do before do merge_request.metrics.update!(latest_closed_at: (described_class::TIME_THRESHOLD - 1.day).ago) end it_behaves_like 'service that does not clean up merge request refs' end end context 'when merge request is merged' do let(:merge_request) { create(:merge_request, :merged) } context "when merged #{described_class::TIME_THRESHOLD.inspect} ago" do before do merge_request.metrics.update!(merged_at: described_class::TIME_THRESHOLD.ago) end it_behaves_like 'service that cleans up merge request refs' end context "when merged later than #{described_class::TIME_THRESHOLD.inspect} ago" do before do merge_request.metrics.update!(merged_at: (described_class::TIME_THRESHOLD - 1.day).ago) end it_behaves_like 'service that does not clean up merge request refs' end end context 'when merge request is not closed nor merged' do let(:merge_request) { create(:merge_request, :opened) } it_behaves_like 'service that does not clean up merge request refs' end end def kept_around?(commit) Gitlab::Git::KeepAround.new(merge_request.project.repository).kept_around?(commit.id) end def ref_head merge_request.project.repository.commit(merge_request.ref_path) end def ref_exists?(ref) merge_request.project.repository.ref_exists?(ref) end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests # Performs the merge between source SHA and the target branch or the specified first parent ref. Instead # of writing the result to the MR target branch, it targets the `target_ref`. # # Ideally this should leave the `target_ref` state with the same state the # target branch would have if we used the regular `MergeService`, but without # every side-effect that comes with it (MR updates, mails, source branch # deletion, etc). This service should be kept idempotent (i.e. can # be executed regardless of the `target_ref` current state). # class MergeToRefService < MergeRequests::MergeBaseService extend ::Gitlab::Utils::Override def execute(merge_request) @merge_request = merge_request error_check! commit_id = extracted_merge_to_ref raise_error('Conflicts detected during merge') unless commit_id commit = project.commit(commit_id) target_id, source_id = commit.parent_ids success(commit_id: commit.id, target_id: target_id, source_id: source_id) rescue MergeError, ArgumentError => error error(error.message) end private def source merge_request.diff_head_sha end override :error_check! def error_check! raise_error('No source for merge') unless source end ## # The parameter `target_ref` is where the merge result will be written. # Default is the merge ref i.e. `refs/merge-requests/:iid/merge`. def target_ref params[:target_ref] || merge_request.merge_ref_path end ## # The parameter `first_parent_ref` is the main line of the merge commit. # Default is the target branch ref of the merge request. def first_parent_ref params[:first_parent_ref] || merge_request.target_branch_ref end def commit_message params[:commit_message] || merge_request.default_merge_commit_message(user: current_user) end def extracted_merge_to_ref repository.merge_to_ref(current_user, source_sha: source, branch: merge_request.target_branch, target_ref: target_ref, message: commit_message, first_parent_ref: first_parent_ref) rescue Gitlab::Git::PreReceiveError, Gitlab::Git::CommandError => error raise MergeError, error.message end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::MergeToRefService, feature_category: :code_review_workflow do shared_examples_for 'MergeService for target ref' do it 'target_ref has the same state of target branch' do repo = merge_request.target_project.repository process_merge_to_ref merge_service.execute(merge_request) ref_commits = repo.commits(merge_request.merge_ref_path, limit: 3) target_branch_commits = repo.commits(merge_request.target_branch, limit: 3) ref_commits.zip(target_branch_commits).each do |ref_commit, target_branch_commit| expect(ref_commit.parents).to eq(target_branch_commit.parents) end end end shared_examples_for 'successfully merges to ref with merge method' do it 'writes commit to merge ref' do repository = project.repository expect(repository.ref_exists?(target_ref)).to be(false) result = service.execute(merge_request) ref_head = repository.commit(target_ref) expect(result[:status]).to eq(:success) expect(result[:commit_id]).to be_present expect(result[:source_id]).to eq(merge_request.source_branch_sha) expect(result[:target_id]).to eq(repository.commit(first_parent_ref).sha) expect(repository.ref_exists?(target_ref)).to be(true) expect(ref_head.id).to eq(result[:commit_id]) end end shared_examples_for 'successfully evaluates pre-condition checks' do it 'returns an error when the failing to process the merge' do allow(project.repository).to receive(:merge_to_ref).and_return(nil) result = service.execute(merge_request) expect(result[:status]).to eq(:error) expect(result[:message]).to eq('Conflicts detected during merge') end it 'does not send any mail' do expect { process_merge_to_ref }.not_to change { ActionMailer::Base.deliveries.count } end it 'does not change the MR state' do expect { process_merge_to_ref }.not_to change { merge_request.state } end it 'does not create notes' do expect { process_merge_to_ref }.not_to change { merge_request.notes.count } end it 'does not delete the source branch' do expect(::Branches::DeleteService).not_to receive(:new) process_merge_to_ref end end let_it_be(:user) { create(:user) } let(:merge_request) { create(:merge_request, :simple) } let(:project) { merge_request.project } describe '#execute' do let(:service) do described_class.new(project: project, current_user: user, params: params) end let(:params) { { commit_message: 'Awesome message', should_remove_source_branch: true, sha: merge_request.diff_head_sha } } def process_merge_to_ref perform_enqueued_jobs do service.execute(merge_request) end end it_behaves_like 'successfully merges to ref with merge method' do let(:first_parent_ref) { 'refs/heads/master' } let(:target_ref) { merge_request.merge_ref_path } end it_behaves_like 'successfully evaluates pre-condition checks' it 'returns an error when Gitlab::Git::CommandError is raised during merge' do allow(project.repository).to receive(:merge_to_ref) do raise Gitlab::Git::CommandError, 'Failed to create merge commit' end result = service.execute(merge_request) expect(result[:status]).to eq(:error) expect(result[:message]).to eq('Failed to create merge commit') end context 'commit history comparison with regular MergeService' do before do # The merge service needs an authorized user while merge-to-ref # doesn't. project.add_maintainer(user) end let(:merge_ref_service) do described_class.new(project: project, current_user: user) end let(:merge_service) do MergeRequests::MergeService.new(project: project, current_user: user, params: { sha: merge_request.diff_head_sha }) end context 'when merge commit' do it_behaves_like 'MergeService for target ref' end context 'when merge commit with squash' do before do merge_request.update!(squash: true) end it_behaves_like 'successfully merges to ref with merge method' do let(:first_parent_ref) { 'refs/heads/master' } let(:target_ref) { merge_request.merge_ref_path } end it 'does not squash before merging' do expect(MergeRequests::SquashService).not_to receive(:new) process_merge_to_ref end end end context 'merge pre-condition checks' do before do merge_request.project.update!(merge_method: merge_method) end context 'when semi-linear merge method' do let(:merge_method) { :rebase_merge } it_behaves_like 'successfully merges to ref with merge method' do let(:first_parent_ref) { 'refs/heads/master' } let(:target_ref) { merge_request.merge_ref_path } end it_behaves_like 'successfully evaluates pre-condition checks' end context 'when fast-forward merge method' do let(:merge_method) { :ff } it_behaves_like 'successfully merges to ref with merge method' do let(:first_parent_ref) { 'refs/heads/master' } let(:target_ref) { merge_request.merge_ref_path } end it_behaves_like 'successfully evaluates pre-condition checks' end context 'when MR is not mergeable to ref' do let(:merge_method) { :merge } it 'returns error' do allow(project).to receive_message_chain(:repository, :merge_to_ref) { nil } error_message = 'Conflicts detected during merge' result = service.execute(merge_request) expect(result[:status]).to eq(:error) expect(result[:message]).to eq(error_message) end end end context 'does not close related todos' do let(:merge_request) { create(:merge_request, assignees: [user], author: user) } let(:project) { merge_request.project } let!(:todo) do create( :todo, :assigned, project: project, author: user, user: user, target: merge_request ) end before do allow(service).to receive(:execute_hooks) perform_enqueued_jobs do service.execute(merge_request) todo.reload end end it { expect(todo).not_to be_done } end context 'when source is missing' do it 'returns error' do allow(merge_request).to receive(:diff_head_sha) { nil } error_message = 'No source for merge' result = service.execute(merge_request) expect(result[:status]).to eq(:error) expect(result[:message]).to eq(error_message) end end context 'when target ref is passed as a parameter' do let(:params) { { commit_message: 'merge train', target_ref: target_ref, sha: merge_request.diff_head_sha } } it_behaves_like 'successfully merges to ref with merge method' do let(:first_parent_ref) { 'refs/heads/master' } let(:target_ref) { 'refs/merge-requests/1/train' } end end describe 'cascading merge refs' do let_it_be(:project) { create(:project, :repository) } let(:params) { { commit_message: 'Cascading merge', first_parent_ref: first_parent_ref, target_ref: target_ref, sha: merge_request.diff_head_sha } } context 'when first merge happens' do let(:merge_request) do create( :merge_request, source_project: project, source_branch: 'feature', target_project: project, target_branch: 'master' ) end it_behaves_like 'successfully merges to ref with merge method' do let(:first_parent_ref) { 'refs/heads/master' } let(:target_ref) { 'refs/merge-requests/1/train' } end context 'when second merge happens' do let(:merge_request) do create( :merge_request, source_project: project, source_branch: 'improve/awesome', target_project: project, target_branch: 'master' ) end it_behaves_like 'successfully merges to ref with merge method' do let(:first_parent_ref) { 'refs/merge-requests/1/train' } let(:target_ref) { 'refs/merge-requests/2/train' } end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class CreateApprovalEventService < MergeRequests::BaseService def execute(merge_request) event_service.approve_mr(merge_request, current_user) end end end MergeRequests::CreateApprovalEventService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::CreateApprovalEventService, feature_category: :code_review_workflow do let(:user) { create(:user) } let(:merge_request) { create(:merge_request) } let(:project) { merge_request.project } subject(:service) { described_class.new(project: project, current_user: user) } describe '#execute' do it 'creates approve MR event' do expect_next_instance_of(EventCreateService) do |instance| expect(instance).to receive(:approve_mr) .with(merge_request, user) end service.execute(merge_request) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ReopenService < MergeRequests::BaseService def execute(merge_request) return merge_request unless can?(current_user, :reopen_merge_request, merge_request) if merge_request.reopen users = merge_request.assignees | merge_request.reviewers create_event(merge_request) create_note(merge_request, 'reopened') merge_request_activity_counter.track_reopen_mr_action(user: current_user) notification_service.async.reopen_mr(merge_request, current_user) execute_hooks(merge_request, 'reopen') merge_request.reload_diff(current_user) merge_request.mark_as_unchecked invalidate_cache_counts(merge_request, users: users) merge_request.update_project_counter_caches merge_request.cache_merge_request_closes_issues!(current_user) merge_request.cleanup_schedule&.destroy merge_request.update_column(:merge_ref_sha, nil) end merge_request end private def create_event(merge_request) # Making sure MergeRequest::Metrics updates are in sync with # Event creation. Event.transaction do event_service.reopen_mr(merge_request, current_user) merge_request_metrics_service(merge_request).reopen end end end end MergeRequests::ReopenService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ReopenService, feature_category: :code_review_workflow do let(:user) { create(:user) } let(:user2) { create(:user) } let(:guest) { create(:user) } let(:merge_request) { create(:merge_request, :closed, assignees: [user2], author: create(:user)) } let(:project) { merge_request.project } before do project.add_maintainer(user) project.add_developer(user2) project.add_guest(guest) end describe '#execute' do it_behaves_like 'cache counters invalidator' it_behaves_like 'merge request reviewers cache counters invalidator' context 'valid params' do let(:service) { described_class.new(project: project, current_user: user) } before do allow(service).to receive(:execute_hooks) merge_request.create_cleanup_schedule(scheduled_at: Time.current) merge_request.update_column(:merge_ref_sha, 'abc123') perform_enqueued_jobs do service.execute(merge_request) end end it { expect(merge_request).to be_valid } it { expect(merge_request).to be_opened } it 'executes hooks with reopen action' do expect(service).to have_received(:execute_hooks) .with(merge_request, 'reopen') end it 'does not call GroupMentionWorker' do expect(Integrations::GroupMentionWorker).not_to receive(:perform_async) end it 'sends email to user2 about reopen of merge_request', :sidekiq_inline do email = ActionMailer::Base.deliveries.last expect(email.to.first).to eq(user2.email) expect(email.subject).to include(merge_request.title) end it 'destroys cleanup schedule record' do expect(merge_request.reload.cleanup_schedule).to be_nil end it 'clears the cached merge_ref_sha' do expect(merge_request.reload.merge_ref_sha).to be_nil end context 'note creation' do it 'creates resource state event about merge_request reopen' do event = merge_request.resource_state_events.last expect(event.state).to eq('reopened') end end end it 'caches merge request closing issues' do expect(merge_request).to receive(:cache_merge_request_closes_issues!) described_class.new(project: project, current_user: user).execute(merge_request) end it 'updates metrics' do metrics = merge_request.metrics service = double(MergeRequestMetricsService) allow(MergeRequestMetricsService) .to receive(:new) .with(metrics) .and_return(service) expect(service).to receive(:reopen) described_class.new(project: project, current_user: user).execute(merge_request) end it 'calls the merge request activity counter' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_reopen_mr_action) .with(user: user) described_class.new(project: project, current_user: user).execute(merge_request) end it 'refreshes the number of open merge requests for a valid MR' do service = described_class.new(project: project, current_user: user) expect do service.execute(merge_request) BatchLoader::Executor.clear_current end .to change { project.open_merge_requests_count }.from(0).to(1) end context 'current user is not authorized to reopen merge request' do before do perform_enqueued_jobs do @merge_request = described_class.new(project: project, current_user: guest).execute(merge_request) end end it 'does not reopen the merge request' do expect(@merge_request).to be_closed end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class CreateFromIssueService < MergeRequests::CreateService # TODO: This constructor does not use the "params:" argument from the superclass, # but instead has a custom "mr_params:" argument. This is because historically, # prior to named arguments being introduced to the constructor, it never passed # along the third positional argument when calling `super`. # This should be changed, in order to be consistent (all subclasses should pass # along all of the arguments to the superclass, otherwise it is probably not an # "is a" relationship). However, we need to be sure that passing the params # argument to `super` (especially target_project_id) will not cause any unexpected # behavior in the superclass. Since the addition of the named arguments is # intended to be a low-risk pure refactor, we will defer this fix # to this follow-on issue: # https://gitlab.com/gitlab-org/gitlab/-/issues/328726 def initialize(project:, current_user:, mr_params: {}) # branch - the name of new branch # ref - the source of new branch. @branch_name = mr_params[:branch_name] @issue_iid = mr_params[:issue_iid] @ref = mr_params[:ref] @target_project_id = mr_params[:target_project_id] super(project: project, current_user: current_user) end def execute return error('Project not found') if target_project.blank? return error('Not allowed to create merge request') unless can_create_merge_request? return error('Invalid issue iid') unless @issue_iid.present? && issue.present? result = ::Branches::CreateService.new(target_project, current_user).execute(branch_name, ref) return result if result[:status] == :error new_merge_request = create(merge_request) if new_merge_request.valid? merge_request_activity_counter.track_mr_create_from_issue(user: current_user) SystemNoteService.new_merge_request(issue, project, current_user, new_merge_request) success(new_merge_request) else SystemNoteService.new_issue_branch(issue, project, current_user, branch_name, branch_project: target_project) error(new_merge_request.errors) end end private def can_create_merge_request? can?(current_user, :create_merge_request_from, target_project) end # rubocop: disable CodeReuse/ActiveRecord def issue @issue ||= IssuesFinder.new(current_user, project_id: project.id).find_by(iid: @issue_iid) end # rubocop: enable CodeReuse/ActiveRecord def branch_name @branch ||= @branch_name || issue.to_branch_name end def ref if valid_ref? @ref else default_branch end end def valid_ref? ref_is_branch? || ref_is_tag? end def ref_is_branch? target_project.repository.branch_exists?(@ref) end def ref_is_tag? target_project.repository.tag_exists?(@ref) end def default_branch target_project.default_branch_or_main end def merge_request MergeRequests::BuildService.new(project: target_project, current_user: current_user, params: merge_request_params).execute end def merge_request_params { issue_iid: @issue_iid, source_project_id: target_project.id, source_branch: branch_name, target_project_id: target_project.id, target_branch: target_branch, assignee_ids: [current_user.id] } end def target_branch if ref_is_branch? @ref else default_branch end end def success(merge_request) super().merge(merge_request: merge_request) end def target_project @target_project ||= if @target_project_id.present? project.forks.find_by_id(@target_project_id) else project end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::CreateFromIssueService, feature_category: :code_review_workflow do include ProjectForksHelper let(:project) { create(:project, :repository) } let(:user) { create(:user) } let(:label_ids) { create_pair(:label, project: project).map(&:id) } let(:milestone_id) { create(:milestone, project: project).id } let(:issue) { create(:issue, project: project, milestone_id: milestone_id) } let(:custom_source_branch) { 'custom-source-branch' } let(:service) { described_class.new(project: project, current_user: user, mr_params: service_params) } let(:service_with_custom_source_branch) { described_class.new(project: project, current_user: user, mr_params: { branch_name: custom_source_branch, **service_params }) } before do project.add_developer(user) end describe '#execute' do shared_examples_for 'a service that creates a merge request from an issue' do it 'returns an error when user can not create merge request on target project' do result = described_class.new(project: project, current_user: create(:user), mr_params: service_params).execute expect(result[:status]).to eq(:error) expect(result[:message]).to eq('Not allowed to create merge request') end it 'returns an error with invalid issue iid' do result = described_class.new(project: project, current_user: user, mr_params: { issue_iid: -1 }).execute expect(result[:status]).to eq(:error) expect(result[:message]).to eq('Invalid issue iid') end it 'creates a branch based on issue title' do service.execute expect(target_project.repository.branch_exists?(issue.to_branch_name)).to be_truthy end it 'creates a branch using passed name' do service_with_custom_source_branch.execute expect(target_project.repository.branch_exists?(custom_source_branch)).to be_truthy end it 'creates the new_merge_request system note' do expect(SystemNoteService).to receive(:new_merge_request).with(issue, project, user, instance_of(MergeRequest)) service.execute end it 'tracks the mr creation when the mr is valid' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_mr_create_from_issue) .with(user: user) service.execute end it 'creates the new_issue_branch system note when the branch could be created but the merge_request cannot be created' do expect_next_instance_of(MergeRequest) do |instance| expect(instance).to receive(:valid?).at_least(:once).and_return(false) end expect(SystemNoteService).to receive(:new_issue_branch).with(issue, project, user, issue.to_branch_name, branch_project: target_project) service.execute end it 'does not track the mr creation when the Mr is invalid' do expect_next_instance_of(MergeRequest) do |instance| expect(instance).to receive(:valid?).at_least(:once).and_return(false) end expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_mr_create_from_issue) service.execute end it 'creates a merge request' do expect { service.execute }.to change(target_project.merge_requests, :count).by(1) end it 'sets the merge request author to current user and assigns them' do result = service.execute expect(result[:merge_request].author).to eq(user) expect(result[:merge_request].assignees).to eq([user]) end it 'sets the merge request source branch to the new issue branch' do result = service.execute expect(result[:merge_request].source_branch).to eq(issue.to_branch_name) end it 'sets the merge request source branch to the passed branch name' do result = service_with_custom_source_branch.execute expect(result[:merge_request].source_branch).to eq(custom_source_branch) end it 'sets the merge request target branch to the project default branch' do result = service.execute expect(result[:merge_request].target_branch).to eq(target_project.default_branch) end it 'executes quick actions if the build service sets them in the description' do allow(service).to receive(:merge_request).and_wrap_original do |m, *args| m.call(*args).tap do |merge_request| merge_request.description = "/assign #{user.to_reference}" end end result = service.execute expect(result[:merge_request].assignees).to eq([user]) end context 'when ref branch is set' do subject { described_class.new(project: project, current_user: user, mr_params: { ref: 'feature', **service_params }).execute } it 'sets the merge request source branch to the new issue branch' do expect(subject[:merge_request].source_branch).to eq(issue.to_branch_name) end it 'sets the merge request target branch to the ref branch' do expect(subject[:merge_request].target_branch).to eq('feature') end context 'when the ref is a tag' do subject { described_class.new(project: project, current_user: user, mr_params: { ref: 'v1.0.0', **service_params }).execute } it 'sets the merge request source branch to the new issue branch' do expect(subject[:merge_request].source_branch).to eq(issue.to_branch_name) end it 'creates a merge request' do expect { subject }.to change(target_project.merge_requests, :count).by(1) end it 'sets the merge request target branch to the project default branch' do expect(subject[:merge_request].target_branch).to eq(target_project.default_branch) end end context 'when ref branch does not exist' do subject { described_class.new(project: project, current_user: user, mr_params: { ref: 'no-such-branch', **service_params }).execute } it 'creates a merge request' do expect { subject }.to change(target_project.merge_requests, :count).by(1) end it 'sets the merge request target branch to the project default branch' do expect(subject[:merge_request].target_branch).to eq(target_project.default_branch) end end end end context 'no target_project_id specified' do let(:service_params) { { issue_iid: issue.iid } } let(:target_project) { project } it_behaves_like 'a service that creates a merge request from an issue' it "inherits labels" do issue.assign_attributes(label_ids: label_ids) result = service.execute expect(result[:merge_request].label_ids).to match_array(label_ids) end it "inherits milestones" do result = service.execute expect(result[:merge_request].milestone_id).to eq(milestone_id) end it 'sets the merge request title to: "Draft: Resolves "$issue-title"' do result = service.execute expect(result[:merge_request].title).to eq("Draft: Resolve \"#{issue.title}\"") end end context 'target_project_id is specified' do let(:service_params) { { issue_iid: issue.iid, target_project_id: target_project.id } } context 'target project is not a fork of the project' do let(:target_project) { create(:project, :repository) } it 'returns an error about not finding the project' do result = service.execute expect(result[:status]).to eq(:error) expect(result[:message]).to eq('Project not found') end it 'does not create merge request' do expect { service.execute }.to change(target_project.merge_requests, :count).by(0) end end context 'target project is a fork of project project' do let(:target_project) { fork_project(project, user, repository: true) } it_behaves_like 'a service that creates a merge request from an issue' it 'sets the merge request title to: "Draft: $issue-branch-name' do result = service.execute expect(result[:merge_request].title).to eq("Draft: #{issue.to_branch_name.titleize.humanize}") end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class UpdateAssigneesService < UpdateService # a stripped down service that only does what it must to update the # assignees, and knows that it does not have to check for other updates. # This saves a lot of queries for irrelevant things that cannot possibly # change in the execution of this service. def execute(merge_request) return merge_request unless current_user&.can?(:update_merge_request, merge_request) old_assignees = merge_request.assignees.to_a old_ids = old_assignees.map(&:id) new_ids = new_user_ids(merge_request, update_attrs[:assignee_ids], :assignees) return merge_request if merge_request.errors.any? return merge_request if new_ids.size != update_attrs[:assignee_ids].size return merge_request if old_ids.to_set == new_ids.to_set # no-change attrs = update_attrs.merge(assignee_ids: new_ids) merge_request.update(**attrs) return merge_request unless merge_request.valid? # Defer the more expensive operations (handle_assignee_changes) to the background MergeRequests::HandleAssigneesChangeService .new(project: project, current_user: current_user) .async_execute(merge_request, old_assignees, execute_hooks: true) merge_request end private def assignee_ids filter_sentinel_values(params.fetch(:assignee_ids)).first(1) end def params ps = super # allow either assignee_id or assignee_ids, preferring assignee_id if passed. { assignee_ids: ps.key?(:assignee_id) ? Array.wrap(ps[:assignee_id]) : ps[:assignee_ids] } end def update_attrs @attrs ||= { updated_at: Time.current, updated_by: current_user, assignee_ids: assignee_ids } end end end MergeRequests::UpdateAssigneesService.prepend_mod_with('MergeRequests::UpdateAssigneesService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::UpdateAssigneesService, feature_category: :code_review_workflow do include AfterNextHelpers let_it_be(:group) { create(:group, :public) } let_it_be(:project) { create(:project, :private, :repository, group: group) } let_it_be(:user) { create(:user) } let_it_be(:user2) { create(:user) } let_it_be(:user3) { create(:user) } let_it_be_with_reload(:merge_request) do create( :merge_request, :simple, :unique_branches, title: 'Old title', description: "FYI #{user2.to_reference}", assignee_ids: [user3.id], source_project: project, target_project: project, author: create(:user) ) end before do project.add_maintainer(user) project.add_developer(user2) project.add_developer(user3) merge_request.errors.clear end let(:service) { described_class.new(project: project, current_user: user, params: opts) } let(:opts) { { assignee_ids: [user2.id] } } describe 'execute' do def update_merge_request service.execute(merge_request) end shared_examples 'it updates and enqueues the job' do it 'correctly updates the MR and enqueues the job' do expect_next(MergeRequests::HandleAssigneesChangeService, project: project, current_user: user) do |service| expect(service) .to receive(:async_execute).with(merge_request, [user3], execute_hooks: true) end expect { update_merge_request } .to change { merge_request.reload.assignees }.from([user3]).to(new_users) .and change(merge_request, :updated_at) .and change(merge_request, :updated_by).to(user) end end shared_examples 'removing all assignees' do it 'removes all assignees' do expect(update_merge_request).to have_attributes(assignees: be_empty, errors: be_none) end it 'enqueues the correct background work' do expect_next(MergeRequests::HandleAssigneesChangeService, project: project, current_user: user) do |service| expect(service) .to receive(:async_execute) .with(merge_request, [user3], execute_hooks: true) end update_merge_request end end context 'when the parameters are valid' do context 'when using sentinel values' do context 'when using assignee_ids' do let(:opts) { { assignee_ids: [0] } } it_behaves_like 'removing all assignees' end context 'when using assignee_id' do let(:opts) { { assignee_id: 0 } } it_behaves_like 'removing all assignees' end end context 'when the assignee_ids parameter is the empty list' do let(:opts) { { assignee_ids: [] } } it_behaves_like 'removing all assignees' end it_behaves_like 'it updates and enqueues the job' do let(:new_users) { [user2] } end it 'does not update the assignees if they do not have access' do opts[:assignee_ids] = [create(:user).id] expect(update_merge_request).to have_attributes( assignees: [user3], errors: be_any ) end it 'is more efficient than using the full update-service' do allow_next(MergeRequests::HandleAssigneesChangeService, project: project, current_user: user) do |service| expect(service) .to receive(:async_execute) .with(merge_request, [user3], execute_hooks: true) end other_mr = create( :merge_request, :simple, :unique_branches, title: merge_request.title, description: merge_request.description, assignee_ids: merge_request.assignee_ids, source_project: merge_request.project, author: merge_request.author ) update_service = ::MergeRequests::UpdateService.new(project: project, current_user: user, params: opts) expect { service.execute(merge_request) } .to issue_fewer_queries_than { update_service.execute(other_mr) } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ReloadMergeHeadDiffService include BaseServiceUtility def initialize(merge_request) @merge_request = merge_request end def execute return error("Merge request has no merge ref head.") unless merge_request.merge_ref_head.present? error_msg = recreate_merge_head_diff return error(error_msg) if error_msg success end private attr_reader :merge_request def recreate_merge_head_diff merge_request.merge_head_diff&.destroy! # n+1: https://gitlab.com/gitlab-org/gitlab/-/issues/19377 Gitlab::GitalyClient.allow_n_plus_1_calls do merge_request.create_merge_head_diff! end # Reset the merge request so it won't load the merge head diff as the # MergeRequest#merge_request_diff. merge_request.reset nil rescue StandardError => e message = "Failed to recreate merge head diff: #{e.message}" Gitlab::AppLogger.error(message: message, merge_request_id: merge_request.id) message end end end MergeRequests::ReloadMergeHeadDiffService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ReloadMergeHeadDiffService, feature_category: :code_review_workflow do let(:merge_request) { create(:merge_request) } subject { described_class.new(merge_request).execute } describe '#execute' do before do MergeRequests::MergeToRefService .new(project: merge_request.project, current_user: merge_request.author) .execute(merge_request) end it 'creates a merge head diff' do expect(subject[:status]).to eq(:success) expect(merge_request.reload.merge_head_diff).to be_present end context 'when merge ref head is not present' do before do allow(merge_request).to receive(:merge_ref_head).and_return(nil) end it 'returns error' do expect(subject[:status]).to eq(:error) end end context 'when failed to create merge head diff' do before do allow(merge_request).to receive(:create_merge_head_diff!).and_raise('fail') end it 'returns error' do expect(subject[:status]).to eq(:error) end end context 'when there is existing merge head diff' do let!(:existing_merge_head_diff) { create(:merge_request_diff, :merge_head, merge_request: merge_request) } it 'recreates merge head diff' do expect(subject[:status]).to eq(:success) expect(merge_request.reload.merge_head_diff).not_to eq(existing_merge_head_diff) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class SquashService include BaseServiceUtility include MergeRequests::ErrorLogger def initialize(merge_request:, current_user:, commit_message:) @merge_request = merge_request @target_project = merge_request.target_project @current_user = current_user @commit_message = commit_message end def execute # If performing a squash would result in no change, then # immediately return a success message without performing a squash if merge_request.commits_count == 1 && message&.strip == merge_request.first_commit.safe_message&.strip return success(squash_sha: merge_request.diff_head_sha) end return error(s_("MergeRequests|Squashing not allowed: This project doesn't allow you to squash commits when merging.")) if squash_forbidden? squash! || error(s_('MergeRequests|Squashing failed: Squash the commits locally, resolve any conflicts, then push the branch.')) end private attr_reader :merge_request, :target_project, :current_user, :commit_message def squash! squash_sha = repository.squash(current_user, merge_request, message) success(squash_sha: squash_sha) rescue StandardError => e log_error(exception: e, message: 'Failed to squash merge request') false end def squash_forbidden? target_project.squash_never? end def repository target_project.repository end def message commit_message.presence || merge_request.default_squash_commit_message(user: current_user) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::SquashService, feature_category: :source_code_management do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { project.first_owner } let(:service) { described_class.new(merge_request: merge_request, current_user: user, commit_message: commit_message) } let(:commit_message) { nil } let(:repository) { project.repository.raw } let(:log_error) { "Failed to squash merge request #{merge_request.to_reference(full: true)}:" } let(:squash_dir_path) do File.join(Gitlab.config.shared.path, 'tmp/squash', repository.gl_repository, merge_request.id.to_s) end let_it_be(:merge_request_with_one_commit) do create( :merge_request, source_branch: 'feature', source_project: project, target_branch: 'master', target_project: project ) end let_it_be(:merge_request_with_only_new_files) do create( :merge_request, source_branch: 'video', source_project: project, target_branch: 'master', target_project: project ) end let_it_be(:merge_request_with_large_files) do create( :merge_request, source_branch: 'squash-large-files', source_project: project, target_branch: 'master', target_project: project ) end shared_examples 'the squash succeeds' do it 'returns the squashed commit SHA' do result = service.execute expect(result).to match(status: :success, squash_sha: a_string_matching(/\h{40}/)) expect(result[:squash_sha]).not_to eq(merge_request.diff_head_sha) end it 'cleans up the temporary directory' do service.execute expect(File.exist?(squash_dir_path)).to be(false) end it 'does not keep the branch push event' do expect { service.execute }.not_to change { Event.count } end context 'when there is a single commit in the merge request' do before do expect(merge_request).to receive(:commits_count).at_least(:once).and_return(1) end it 'will still perform the squash' do expect(merge_request.target_project.repository).to receive(:squash).and_return('sha') service.execute end context 'when squash message matches commit message' do let(:commit_message) { merge_request.first_commit.safe_message } it 'returns that commit SHA' do result = service.execute expect(result).to match(status: :success, squash_sha: merge_request.diff_head_sha) end it 'does not perform any git actions' do expect(repository).not_to receive(:squash) service.execute end end context 'when squash message matches commit message but without trailing new line' do let(:commit_message) { merge_request.first_commit.safe_message.strip } it 'returns that commit SHA' do result = service.execute expect(result).to match(status: :success, squash_sha: merge_request.diff_head_sha) end it 'does not perform any git actions' do expect(repository).not_to receive(:squash) service.execute end end end describe 'the squashed commit' do let(:squash_sha) { service.execute[:squash_sha] } let(:squash_commit) { project.repository.commit(squash_sha) } it 'copies the author info from the merge request' do expect(squash_commit.author_name).to eq(merge_request.author.name) expect(squash_commit.author_email).to eq(merge_request.author.email) end it 'sets the current user as the committer' do expect(squash_commit.committer_name).to eq(user.name.chomp('.')) expect(squash_commit.committer_email).to eq(user.email) end it 'has the same diff as the merge request, but a different SHA' do mr_diff = project.repository.diff(merge_request.diff_base_sha, merge_request.diff_head_sha) squash_diff = project.repository.diff(merge_request.diff_start_sha, squash_sha) expect(squash_diff.size).to eq(mr_diff.size) expect(squash_commit.sha).not_to eq(merge_request.diff_head_sha) end it 'has a default squash commit message if no message was provided' do expect(squash_commit.message.chomp).to eq(merge_request.default_squash_commit_message.chomp) end context 'if a message was provided' do let(:commit_message) { message } let(:message) { 'My custom message' } let(:squash_sha) { service.execute[:squash_sha] } it 'has the same message as the message provided' do expect(squash_commit.message.chomp).to eq(message) end end end end describe '#execute' do context 'when there is only one commit in the merge request' do let(:merge_request) { merge_request_with_one_commit } include_examples 'the squash succeeds' end context 'when squashing only new files' do let(:merge_request) { merge_request_with_only_new_files } include_examples 'the squash succeeds' end context 'when squashing is disabled by default on the project' do # Squashing is disabled by default, but it should still allow you # to squash-and-merge if selected through the UI let(:merge_request) { merge_request_with_only_new_files } before do merge_request.project.project_setting.squash_default_off! end include_examples 'the squash succeeds' end context 'when squashing is forbidden on the project' do let(:merge_request) { merge_request_with_only_new_files } before do merge_request.project.project_setting.squash_never! end it 'raises a squash error' do expect(service.execute).to match( status: :error, message: a_string_including('allow you to squash commits when merging')) end end context 'when squashing is enabled by default on the project' do let(:merge_request) { merge_request_with_only_new_files } before do merge_request.project.project_setting.squash_always! end include_examples 'the squash succeeds' end context 'when squashing with files too large to display' do let(:merge_request) { merge_request_with_large_files } include_examples 'the squash succeeds' end describe 'git errors' do let(:merge_request) { merge_request_with_only_new_files } let(:error) { 'A test error' } context 'with an error in Gitaly UserSquash RPC' do before do allow(repository.gitaly_operation_client).to receive(:user_squash) .and_raise(Gitlab::Git::Repository::GitError, error) end it 'logs the error' do expect(service).to receive(:log_error).with(exception: an_instance_of(Gitlab::Git::Repository::GitError), message: 'Failed to squash merge request') service.execute end it 'returns an error' do expect(service.execute).to match(status: :error, message: a_string_including('Squash')) end end end context 'when any other exception is thrown' do let(:merge_request) { merge_request_with_only_new_files } let(:merge_request_ref) { merge_request.to_reference(full: true) } let(:exception) { RuntimeError.new('A test error') } before do allow(merge_request.target_project.repository).to receive(:squash).and_raise(exception) end it 'logs the error' do expect(service).to receive(:log_error).with(exception: exception, message: 'Failed to squash merge request').and_call_original expect(Gitlab::ErrorTracking).to receive(:track_exception).with(exception, { class: described_class.to_s, merge_request: merge_request_ref, merge_request_id: merge_request.id, message: 'Failed to squash merge request', save_message_on_model: false }).and_call_original service.execute end it 'returns an error' do expect(service.execute).to match(status: :error, message: a_string_including('Squash')) end it 'cleans up the temporary directory' do service.execute expect(File.exist?(squash_dir_path)).to be(false) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class DeleteNonLatestDiffsService BATCH_SIZE = 10 def initialize(merge_request) @merge_request = merge_request end def execute diffs = @merge_request.non_latest_diffs.with_files diffs.each_batch(of: BATCH_SIZE) do |relation, index| ids = relation.pluck_primary_key.map { |id| [id] } DeleteDiffFilesWorker.bulk_perform_in(index * 5.minutes, ids) # rubocop:disable Scalability/BulkPerformWithContext end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::DeleteNonLatestDiffsService, :clean_gitlab_redis_shared_state, feature_category: :code_review_workflow do let(:merge_request) { create(:merge_request) } let!(:subject) { described_class.new(merge_request) } describe '#execute' do before do stub_const("#{described_class.name}::BATCH_SIZE", 2) 3.times { merge_request.create_merge_request_diff } merge_request.create_merge_head_diff merge_request.reset end it 'schedules non-latest merge request diffs removal', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/426807' do diffs = merge_request.merge_request_diffs expect(diffs.count).to eq(4) freeze_time do expect(DeleteDiffFilesWorker) .to receive(:bulk_perform_in) .with(5.minutes, [[diffs.first.id], [diffs.second.id]]) expect(DeleteDiffFilesWorker) .to receive(:bulk_perform_in) .with(10.minutes, [[diffs.third.id]]) subject.execute end end it 'schedules no removal if it is already cleaned' do merge_request.merge_request_diffs.each(&:clean!) expect(DeleteDiffFilesWorker).not_to receive(:bulk_perform_in) subject.execute end it 'schedules no removal if it is empty' do merge_request.merge_request_diffs.each { |diff| diff.update!(state: :empty) } expect(DeleteDiffFilesWorker).not_to receive(:bulk_perform_in) subject.execute end it 'schedules no removal if there is no non-latest diffs' do # rubocop: disable Cop/DestroyAll merge_request .merge_request_diffs .where.not(id: merge_request.latest_merge_request_diff_id) .destroy_all # rubocop: enable Cop/DestroyAll expect(DeleteDiffFilesWorker).not_to receive(:bulk_perform_in) subject.execute end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class AddSpentTimeService < UpdateService def execute(merge_request) old_associations = { total_time_spent: merge_request.total_time_spent } merge_request.spend_time(params[:spend_time]) merge_request_saved = merge_request.with_transaction_returning_status do merge_request.save end if merge_request_saved create_system_notes(merge_request) # track usage track_time_spend_edits(merge_request, old_associations[:total_time_spent]) execute_hooks(merge_request, 'update', old_associations: old_associations) end merge_request end private def track_time_spend_edits(merge_request, old_total_time_spent) if old_total_time_spent != merge_request.total_time_spent merge_request_activity_counter.track_time_spent_changed_action(user: current_user) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::AddSpentTimeService, feature_category: :code_review_workflow do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, :public, :repository) } let_it_be_with_reload(:merge_request) { create(:merge_request, :simple, :unique_branches, source_project: project) } let(:duration) { 1500 } let(:params) { { spend_time: { duration: duration, summary: 'summary', user_id: user.id } } } let(:service) { described_class.new(project: project, current_user: user, params: params) } describe '#execute' do before do project.add_developer(user) end it 'creates a new timelog with the specified duration and summary' do expect { service.execute(merge_request) }.to change { Timelog.count }.from(0).to(1) timelog = merge_request.timelogs.last expect(timelog).not_to be_nil expect(timelog.time_spent).to eq(1500) expect(timelog.summary).to eq('summary') end it 'creates a system note with the time added' do expect { service.execute(merge_request) }.to change { Note.count }.from(0).to(1) system_note = merge_request.notes.last expect(system_note).not_to be_nil expect(system_note.note_html).to include('added 25m of time spent') end it 'saves usage data' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_time_spent_changed_action).once.with(user: user) service.execute(merge_request) end it 'is more efficient than using the full update-service' do other_mr = create(:merge_request, :simple, :unique_branches, source_project: project) update_service = ::MergeRequests::UpdateService.new(project: project, current_user: user, params: params) other_mr.reload expect { service.execute(merge_request) } .to issue_fewer_queries_than { update_service.execute(other_mr) } end context 'when duration is nil' do let(:duration) { nil } it 'does not create a timelog with the specified duration' do expect { service.execute(merge_request) }.not_to change { Timelog.count } expect(merge_request).not_to be_valid end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class UpdateReviewersService < UpdateService def execute(merge_request) return merge_request unless current_user&.can?(:update_merge_request, merge_request) old_reviewers = merge_request.reviewers.to_a old_ids = old_reviewers.map(&:id) new_ids = new_user_ids(merge_request, update_attrs[:reviewer_ids], :reviewers) return merge_request if merge_request.errors.any? return merge_request if new_ids.size != update_attrs[:reviewer_ids].size return merge_request if old_ids.to_set == new_ids.to_set # no-change merge_request.update!(update_attrs.merge(reviewer_ids: new_ids)) handle_reviewers_change(merge_request, old_reviewers) resolve_todos_for(merge_request) execute_reviewers_hooks(merge_request, old_reviewers) merge_request end private def reviewer_ids filter_sentinel_values(params.fetch(:reviewer_ids)).first(1) end def update_attrs @attrs ||= { updated_by: current_user, reviewer_ids: reviewer_ids } end def execute_reviewers_hooks(merge_request, old_reviewers) execute_hooks( merge_request, 'update', old_associations: { reviewers: old_reviewers } ) end end end MergeRequests::UpdateReviewersService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::UpdateReviewersService, feature_category: :code_review_workflow do include AfterNextHelpers let_it_be(:group) { create(:group, :public) } let_it_be(:project) { create(:project, :private, :repository, group: group) } let_it_be(:user) { create(:user) } let_it_be(:user2) { create(:user) } let_it_be(:user3) { create(:user) } let_it_be_with_reload(:merge_request) do create( :merge_request, :simple, :unique_branches, title: 'Old title', description: "FYI #{user2.to_reference}", reviewer_ids: [user3.id], source_project: project, target_project: project, author: create(:user) ) end before do project.add_maintainer(user) project.add_developer(user2) project.add_developer(user3) merge_request.errors.clear end let(:service) { described_class.new(project: project, current_user: user, params: opts) } let(:opts) { { reviewer_ids: [user2.id] } } describe 'execute' do def set_reviewers service.execute(merge_request) end def find_note(starting_with) merge_request.notes.find do |note| note && note.note.start_with?(starting_with) end end shared_examples 'removing all reviewers' do it 'removes all reviewers' do expect(set_reviewers).to have_attributes(reviewers: be_empty, errors: be_none) end end context 'when the parameters are valid' do context 'when using sentinel values' do let(:opts) { { reviewer_ids: [0] } } it_behaves_like 'removing all reviewers' end context 'when the reviewer_ids parameter is the empty list' do let(:opts) { { reviewer_ids: [] } } it_behaves_like 'removing all reviewers' end it 'updates the MR' do expect { set_reviewers } .to change { merge_request.reload.reviewers }.from([user3]).to([user2]) .and change(merge_request, :updated_at) .and change(merge_request, :updated_by).to(user) end it 'creates system note about merge_request review request' do set_reviewers note = find_note('requested review from') expect(note).not_to be_nil expect(note.note).to include "requested review from #{user2.to_reference}" end it 'creates a pending todo for new review request' do set_reviewers attributes = { project: project, author: user, user: user2, target_id: merge_request.id, target_type: merge_request.class.name, action: Todo::REVIEW_REQUESTED, state: :pending } expect(Todo.where(attributes).count).to eq 1 end it 'sends email reviewer change notifications to old and new reviewers', :sidekiq_inline, :mailer do perform_enqueued_jobs do set_reviewers end should_email(user2) should_email(user3) end it 'updates open merge request counter for reviewers', :use_clean_rails_memory_store_caching do # Cache them to ensure the cache gets invalidated on update expect(user2.review_requested_open_merge_requests_count).to eq(0) expect(user3.review_requested_open_merge_requests_count).to eq(1) set_reviewers expect(user2.review_requested_open_merge_requests_count).to eq(1) expect(user3.review_requested_open_merge_requests_count).to eq(0) end it 'updates the tracking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_users_review_requested) .with(users: [user2]) set_reviewers end it 'tracks reviewers changed event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_reviewers_changed_action).once.with(user: user) set_reviewers end it_behaves_like 'triggers GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { set_reviewers } end it 'calls MergeRequest::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end set_reviewers end it 'executes hooks with update action' do expect(service).to receive(:execute_hooks) .with( merge_request, 'update', old_associations: { reviewers: [user3] } ) set_reviewers end context 'when reviewers did not change' do let(:opts) { { reviewer_ids: merge_request.reviewer_ids } } it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { set_reviewers } end end it 'does not update the reviewers if they do not have access' do opts[:reviewer_ids] = [create(:user).id] expect(set_reviewers).to have_attributes( reviewers: [user3], errors: be_any ) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class PushOptionsHandlerService < ::BaseProjectService LIMIT = 10 attr_reader :errors, :changes, :push_options, :target_project def initialize(project:, current_user:, changes:, push_options:, params: {}) super(project: project, current_user: current_user, params: params) @target_project = if push_options[:target_project] Project.find_by_full_path(push_options[:target_project]) else @project.default_merge_request_target end @changes = Gitlab::ChangesList.new(changes) @push_options = push_options @errors = [] end def execute validate_service return self if errors.present? branches.each do |branch| execute_for_branch(branch) rescue Gitlab::Access::AccessDeniedError errors << 'User access was denied' rescue StandardError => e Gitlab::AppLogger.error(e) errors << 'An unknown error occurred' end self end private def branches changes_by_branch.keys end def changes_by_branch @changes_by_branch ||= changes.each_with_object({}) do |changes, result| next unless Gitlab::Git.branch_ref?(changes[:ref]) # Deleted branch next if Gitlab::Git.blank_ref?(changes[:newrev]) # Default branch branch_name = Gitlab::Git.branch_name(changes[:ref]) next if branch_name == target_project.default_branch result[branch_name] = changes end end def validate_service if current_user.nil? errors << 'User is required' return end unless current_user&.can?(:read_code, target_project) errors << 'User access was denied' return end unless project == target_project || project.in_fork_network_of?(target_project) errors << "Projects #{project.full_path} and #{target_project.full_path} are not in the same network" end unless target_project.merge_requests_enabled? errors << "Merge requests are not enabled for project #{target_project.full_path}" end if branches.size > LIMIT errors << "Too many branches pushed (#{branches.size} were pushed, limit is #{LIMIT})" end if push_options[:target] && !target_project.repository.branch_exists?(push_options[:target]) errors << "Target branch #{target_project.full_path}:#{push_options[:target]} does not exist" end end # Returns a Hash of branch => MergeRequest def merge_requests @merge_requests ||= MergeRequest.from_project(target_project) .opened .from_source_branches(branches) .index_by(&:source_branch) end def execute_for_branch(branch) merge_request = merge_requests[branch] if merge_request update!(merge_request) else create!(branch) end end def create!(branch) unless push_options[:create] errors << "A merge_request.create push option is required to create a merge request for branch #{branch}" return end # Use BuildService to assign the standard attributes of a merge request merge_request = ::MergeRequests::BuildService.new( project: project, current_user: current_user, params: create_params(branch) ).execute unless merge_request.errors.present? merge_request = ::MergeRequests::CreateService.new( project: project, current_user: current_user, params: merge_request.attributes.merge( assignee_ids: merge_request.assignee_ids, label_ids: merge_request.label_ids ) ).execute end collect_errors_from_merge_request(merge_request) unless merge_request.persisted? end def update!(merge_request) merge_request = ::MergeRequests::UpdateService.new( project: target_project, current_user: current_user, params: update_params(merge_request) ).execute(merge_request) collect_errors_from_merge_request(merge_request) unless merge_request.valid? end def base_params params = { title: push_options[:title], description: push_options[:description], draft: push_options[:draft], target_branch: push_options[:target], force_remove_source_branch: push_options[:remove_source_branch], label: push_options[:label], unlabel: push_options[:unlabel], assign: push_options[:assign], unassign: push_options[:unassign] } params.compact! params[:add_labels] = params.delete(:label).keys if params.has_key?(:label) params[:remove_labels] = params.delete(:unlabel).keys if params.has_key?(:unlabel) params[:add_assignee_ids] = convert_to_user_ids(params.delete(:assign).keys) if params.has_key?(:assign) params[:remove_assignee_ids] = convert_to_user_ids(params.delete(:unassign).keys) if params.has_key?(:unassign) if push_options[:milestone] milestone = Milestone.for_projects_and_groups(@project, @project.ancestors_upto)&.find_by_name(push_options[:milestone]) params[:milestone_id] = milestone.id if milestone end if params.key?(:description) params[:description] = params[:description].gsub('\n', "\n") end params end def merge_params(branch) return {} unless push_options.key?(:merge_when_pipeline_succeeds) { merge_when_pipeline_succeeds: push_options[:merge_when_pipeline_succeeds], merge_user: current_user, sha: changes_by_branch.dig(branch, :newrev) } end def create_params(branch) params = base_params params.merge!( assignee_ids: [current_user.id], source_branch: branch, source_project: project, target_project: target_project ) params.merge!(merge_params(branch)) params[:target_branch] ||= target_project.default_branch params end def update_params(merge_request) base_params.merge(merge_params(merge_request.source_branch)) end def convert_to_user_ids(ids_or_usernames) ids, usernames = ids_or_usernames.partition { |id_or_username| id_or_username.is_a?(Numeric) || id_or_username.match?(/\A\d+\z/) } ids += User.by_username(usernames).pluck(:id) unless usernames.empty? # rubocop:disable CodeReuse/ActiveRecord ids end def collect_errors_from_merge_request(merge_request) merge_request.errors.full_messages.each do |error| errors << error end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::PushOptionsHandlerService, feature_category: :source_code_management do include ProjectForksHelper let_it_be(:parent_group) { create(:group, :public) } let_it_be(:child_group) { create(:group, :public, parent: parent_group) } let_it_be(:project) { create(:project, :public, :repository, group: child_group) } let_it_be(:user1) { create(:user, developer_projects: [project]) } let_it_be(:user2) { create(:user, developer_projects: [project]) } let_it_be(:user3) { create(:user, developer_projects: [project]) } let_it_be(:forked_project) { fork_project(project, user1, repository: true) } let_it_be(:parent_group_milestone) { create(:milestone, group: parent_group, title: 'ParentGroupMilestone1.0') } let_it_be(:child_group_milestone) { create(:milestone, group: child_group, title: 'ChildGroupMilestone1.0') } let_it_be(:project_milestone) { create(:milestone, project: project, title: 'ProjectMilestone1.0') } let(:service) { described_class.new(project: project, current_user: user1, changes: changes, push_options: push_options) } let(:source_branch) { 'fix' } let(:target_branch) { 'feature' } let(:title) { 'my title' } let(:draft_title) { 'Draft: my title' } let(:draft) { true } let(:description) { 'my description' } let(:multiline_description) do <<~MD.chomp Line 1 Line 2 Line 3 MD end let(:label1) { 'mylabel1' } let(:label2) { 'mylabel2' } let(:label3) { 'mylabel3' } let(:new_branch_changes) { "#{Gitlab::Git::BLANK_SHA} 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/#{source_branch}" } let(:existing_branch_changes) { "d14d6c0abdd253381df51a723d58691b2ee1ab08 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/#{source_branch}" } let(:deleted_branch_changes) { "d14d6c0abdd253381df51a723d58691b2ee1ab08 #{Gitlab::Git::BLANK_SHA} refs/heads/#{source_branch}" } let(:default_branch_changes) { "d14d6c0abdd253381df51a723d58691b2ee1ab08 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/#{project.default_branch}" } let(:error_mr_required) { "A merge_request.create push option is required to create a merge request for branch #{source_branch}" } before do stub_licensed_features(multiple_merge_request_assignees: false) end shared_examples_for 'a service that can set the target of a merge request' do subject(:last_mr) { MergeRequest.last } it 'sets the target_branch' do service.execute expect(last_mr.target_branch).to eq(target_branch) end end shared_examples_for 'a service that can set the target project of a merge request' do subject(:last_mr) { MergeRequest.last } it 'creates a merge request with the correct target project' do project_path = push_options[:target_project] || project.default_merge_request_target.full_path expect { service.execute }.to change { MergeRequest.count }.by(1) expect(last_mr.target_project.full_path).to eq(project_path) end end shared_examples_for 'a service that can set the title of a merge request' do subject(:last_mr) { MergeRequest.last } it 'sets the title' do service.execute expect(last_mr.title).to eq(title) end end shared_examples_for 'a service that can set the description of a merge request' do subject(:last_mr) { MergeRequest.last } it 'sets the description' do service.execute expect(last_mr.description).to eq(description) end end shared_examples_for 'a service that can set the multiline description of a merge request' do subject(:last_mr) { MergeRequest.last } it 'sets the multiline description' do service.execute expect(last_mr.description).to eq(multiline_description) end end shared_examples_for 'a service that can set the draft of a merge request' do subject(:last_mr) { MergeRequest.last } it 'sets the draft' do service.execute expect(last_mr.draft).to eq(draft) end end shared_examples_for 'a service that can set the milestone of a merge request' do subject(:last_mr) { MergeRequest.last } it 'sets the milestone' do service.execute expect(last_mr.milestone&.title).to eq(expected_milestone) end end shared_examples_for 'a service that can set the merge request to merge when pipeline succeeds' do subject(:last_mr) { MergeRequest.last } let(:change) { Gitlab::ChangesList.new(changes).changes.first } it 'sets auto_merge_enabled' do service.execute expect(last_mr.auto_merge_enabled).to eq(true) expect(last_mr.auto_merge_strategy).to eq(AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS) expect(last_mr.merge_user).to eq(user1) expect(last_mr.merge_params['sha']).to eq(change[:newrev]) end end shared_examples_for 'a service that can remove the source branch when it is merged' do subject(:last_mr) { MergeRequest.last } it 'returns true to force_remove_source_branch?' do service.execute expect(last_mr.force_remove_source_branch?).to eq(true) end end shared_examples_for 'a service that can change labels of a merge request' do |count| subject(:last_mr) { MergeRequest.last } it 'changes label count' do service.execute expect(last_mr.label_ids.count).to eq(count) end end shared_examples_for 'a service that does not update a merge request' do it do expect { service.execute }.not_to change { MergeRequest.maximum(:updated_at) } end end shared_examples_for 'a service that does nothing' do include_examples 'a service that does not create a merge request' include_examples 'a service that does not update a merge request' end shared_examples 'with a deleted branch' do let(:changes) { deleted_branch_changes } it_behaves_like 'a service that does nothing' end shared_examples 'with the project default branch' do let(:changes) { default_branch_changes } it_behaves_like 'a service that does nothing' end describe '`create` push option' do let(:push_options) { { create: true } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that can create a merge request' end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that can create a merge request' end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`merge_when_pipeline_succeeds` push option' do let(:push_options) { { merge_when_pipeline_succeeds: true } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, merge_when_pipeline_succeeds: true } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the merge request to merge when pipeline succeeds' end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, merge_when_pipeline_succeeds: true } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the merge request to merge when pipeline succeeds' end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can set the merge request to merge when pipeline succeeds' end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`remove_source_branch` push option' do let(:push_options) { { remove_source_branch: true } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, remove_source_branch: true } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can remove the source branch when it is merged' end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, remove_source_branch: true } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can remove the source branch when it is merged' end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can remove the source branch when it is merged' end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`target` push option' do let(:push_options) { { target: target_branch } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, target: target_branch } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the target of a merge request' end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, target: target_branch } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the target of a merge request' end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can set the target of a merge request' end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`target_project` push option' do let(:changes) { new_branch_changes } let(:double_forked_project) { fork_project(forked_project, user1, repository: true) } let(:service) { described_class.new(project: double_forked_project, current_user: user1, changes: changes, push_options: push_options) } let(:push_options) { { create: true, target_project: target_project.full_path } } context 'to self' do let(:target_project) { double_forked_project } it_behaves_like 'a service that can set the target project of a merge request' end context 'to intermediate project' do let(:target_project) { forked_project } it_behaves_like 'a service that can set the target project of a merge request' end context 'to base project' do let(:target_project) { project } it_behaves_like 'a service that can set the target project of a merge request' end end describe '`title` push option' do let(:push_options) { { title: title } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, title: title } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the title of a merge request' end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, title: title } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the title of a merge request' end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can set the title of a merge request' end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`description` push option' do let(:push_options) { { description: description } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, description: description } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the description of a merge request' end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, description: description } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the description of a merge request' end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can set the description of a merge request' context 'with a multiline description' do let(:push_options) { { description: "Line 1\\nLine 2\\nLine 3" } } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can set the multiline description of a merge request' end end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`draft` push option' do let(:push_options) { { draft: draft } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, draft: draft } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the draft of a merge request' end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, draft: draft } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the draft of a merge request' end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can set the draft of a merge request' end context 'draft title provided while `draft` push option is set to false' do let(:push_options) { { create: true, draft: false, title: draft_title } } let(:changes) { new_branch_changes } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the draft of a merge request' end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`label` push option' do let(:push_options) { { label: { label1 => 1, label2 => 1 } } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, label: { label1 => 1, label2 => 1 } } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can change labels of a merge request', 2 end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, label: { label1 => 1, label2 => 1 } } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can change labels of a merge request', 2 end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can change labels of a merge request', 2 end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`unlabel` push option' do let(:push_options) { { label: { label1 => 1, label2 => 1 }, unlabel: { label1 => 1, label3 => 1 } } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, label: { label1 => 1, label2 => 1 }, unlabel: { label1 => 1, label3 => 1 } } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can change labels of a merge request', 1 end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, label: { label1 => 1, label2 => 1 }, unlabel: { label1 => 1, label3 => 1 } } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can change labels of a merge request', 1 end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can change labels of a merge request', 1 end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end describe '`milestone` push option' do context 'with a valid milestone' do let(:expected_milestone) { project_milestone.title } let(:push_options) { { milestone: project_milestone.title } } context 'with a new branch' do let(:changes) { new_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, milestone: project_milestone.title } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the milestone of a merge request' end end context 'with an existing branch but no open MR' do let(:changes) { existing_branch_changes } it_behaves_like 'a service that does not create a merge request' it 'adds an error to the service' do service.execute expect(service.errors).to include(error_mr_required) end context 'when coupled with the `create` push option' do let(:push_options) { { create: true, milestone: project_milestone.title } } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the milestone of a merge request' end end context 'with an existing branch that has a merge request open' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can set the milestone of a merge request' end it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' end context 'with invalid milestone' do let(:expected_milestone) { nil } let(:changes) { new_branch_changes } let(:push_options) { { create: true, milestone: 'invalid_milestone' } } it_behaves_like 'a service that can set the milestone of a merge request' end context 'with an ancestor milestone' do let(:changes) { existing_branch_changes } context 'with immediate parent milestone' do let(:push_options) { { create: true, milestone: child_group_milestone.title } } let(:expected_milestone) { child_group_milestone.title } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the milestone of a merge request' end context 'with multi-level ancestor milestone' do let(:push_options) { { create: true, milestone: parent_group_milestone.title } } let(:expected_milestone) { parent_group_milestone.title } it_behaves_like 'a service that can create a merge request' it_behaves_like 'a service that can set the milestone of a merge request' end end end shared_examples 'with an existing branch that has a merge request open in foss' do let(:changes) { existing_branch_changes } let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } it_behaves_like 'a service that does not create a merge request' it_behaves_like 'a service that can change assignees of a merge request', 1 end describe '`assign` push option' do let(:assigned) { { user2.id => 1, user3.id => 1 } } let(:unassigned) { nil } let(:push_options) { { assign: assigned, unassign: unassigned } } it_behaves_like 'with a new branch', 1 it_behaves_like 'with an existing branch but no open MR', 1 it_behaves_like 'with an existing branch that has a merge request open in foss' it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' context 'when passing in usernames' do # makes sure that usernames starting with numbers aren't treated as IDs let(:user2) { create(:user, username: '123user', developer_projects: [project]) } let(:user3) { create(:user, username: '999user', developer_projects: [project]) } let(:assigned) { { user2.username => 1, user3.username => 1 } } it_behaves_like 'with an existing branch that has a merge request open in foss' end end describe '`unassign` push option' do let(:assigned) { { user2.id => 1, user3.id => 1 } } let(:unassigned) { { user1.id => 1, user3.id => 1 } } let(:push_options) { { assign: assigned, unassign: unassigned } } it_behaves_like 'with a new branch', 1 it_behaves_like 'with an existing branch but no open MR', 1 it_behaves_like 'with an existing branch that has a merge request open in foss' it_behaves_like 'with a deleted branch' it_behaves_like 'with the project default branch' context 'when passing in usernames' do let(:assigned) { { user2.username => 1, user3.username => 1 } } let(:unassigned) { { user1.username => 1, user3.username => 1 } } it_behaves_like 'with an existing branch that has a merge request open in foss' end end describe 'multiple pushed branches' do let(:push_options) { { create: true } } let(:changes) do [ new_branch_changes, "#{Gitlab::Git::BLANK_SHA} 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/feature_conflict" ] end it 'creates a merge request per branch' do expect { service.execute }.to change { MergeRequest.count }.by(2) end context 'when there are too many pushed branches' do let(:limit) { MergeRequests::PushOptionsHandlerService::LIMIT } let(:changes) do TestEnv::BRANCH_SHA.to_a[0..limit].map do |x| "#{Gitlab::Git::BLANK_SHA} #{x.first} refs/heads/#{x.last}" end end it 'records an error' do service.execute expect(service.errors).to eq(["Too many branches pushed (#{limit + 1} were pushed, limit is #{limit})"]) end end end describe 'no push options' do let(:push_options) { {} } let(:changes) { new_branch_changes } it_behaves_like 'a service that does nothing' end describe 'no user' do let(:user1) { nil } let(:user2) { nil } let(:user3) { nil } let(:push_options) { { create: true } } let(:changes) { new_branch_changes } it 'records an error' do service.execute expect(service.errors).to eq(['User is required']) end end describe 'unauthorized user' do let(:push_options) { { create: true } } let(:changes) { new_branch_changes } it 'records an error', :sidekiq_inline do Members::DestroyService.new(user1).execute(ProjectMember.find_by!(user_id: user1.id)) service.execute expect(service.errors).to eq(['User access was denied']) end end describe 'handling unexpected exceptions' do let(:push_options) { { create: true } } let(:changes) { new_branch_changes } let(:exception) { StandardError.new('My standard error') } def run_service_with_exception allow_next_instance_of(MergeRequests::BuildService) do |instance| allow(instance).to receive(:execute).and_raise(exception) end service.execute end it 'records an error' do run_service_with_exception expect(service.errors).to eq(['An unknown error occurred']) end it 'writes to Gitlab::AppLogger' do expect(Gitlab::AppLogger).to receive(:error).with(exception) run_service_with_exception end end describe 'when target is not a valid branch name' do let(:push_options) { { create: true, target: 'my-branch' } } let(:changes) { new_branch_changes } it 'records an error' do service.execute expect(service.errors).to eq(["Target branch #{project.full_path}:my-branch does not exist"]) end end describe 'when the target project does not exist' do let(:push_options) { { create: true, target: 'my-branch', target_project: 'does-not-exist' } } let(:changes) { default_branch_changes } it 'records an error', :sidekiq_inline do service.execute expect(service.errors).to eq(["User access was denied"]) end end describe 'when user does not have access to target project' do let(:push_options) { { create: true, target: 'my-branch' } } let(:changes) { default_branch_changes } before do allow(user1).to receive(:can?).with(:read_code, project).and_return(false) end it 'records an error', :sidekiq_inline do service.execute expect(service.errors).to eq(["User access was denied"]) end end describe 'when MRs are not enabled' do let(:project) { create(:project, :public, :repository).tap { |pr| pr.add_developer(user1) } } let(:push_options) { { create: true } } let(:changes) { new_branch_changes } it 'records an error' do expect(project).to receive(:merge_requests_enabled?).and_return(false) service.execute expect(service.errors).to eq(["Merge requests are not enabled for project #{project.full_path}"]) end end describe 'when projects are unrelated' do let(:unrelated_project) { create(:project, :public, :repository, group: child_group) } let(:push_options) { { create: true, target_project: unrelated_project.full_path } } let(:changes) { new_branch_changes } it 'records an error' do service.execute expect(service.errors).to eq(["Projects #{project.full_path} and #{unrelated_project.full_path} are not in the same network"]) end end describe 'when MR has ActiveRecord errors' do let(:push_options) { { create: true } } let(:changes) { new_branch_changes } it 'adds the error to its errors property' do invalid_merge_request = MergeRequest.new invalid_merge_request.errors.add(:base, 'my error') expect_next_instance_of(MergeRequests::CreateService) do |instance| expect(instance).to receive(:execute).and_return(invalid_merge_request) end service.execute expect(service.errors).to eq(['my error']) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class BaseService < ::IssuableBaseService extend ::Gitlab::Utils::Override include MergeRequests::AssignsMergeParams include MergeRequests::ErrorLogger delegate :repository, to: :project def initialize(project:, current_user: nil, params: {}) super(container: project, current_user: current_user, params: params) end def create_note(merge_request, state = merge_request.state) SystemNoteService.change_status(merge_request, merge_request.target_project, current_user, state, nil) end def hook_data(merge_request, action, old_rev: nil, old_associations: {}) hook_data = merge_request.to_hook_data(current_user, old_associations: old_associations) hook_data[:object_attributes][:action] = action if old_rev && !Gitlab::Git.blank_ref?(old_rev) hook_data[:object_attributes][:oldrev] = old_rev end hook_data end def execute_hooks(merge_request, action = 'open', old_rev: nil, old_associations: {}) # NOTE: Due to the async merge request diffs generation, we need to skip this for CreateService and execute it in # AfterCreateService instead so that the webhook consumers receive the update when diffs are ready. return if merge_request.skip_ensure_merge_request_diff merge_data = Gitlab::Lazy.new { hook_data(merge_request, action, old_rev: old_rev, old_associations: old_associations) } merge_request.project.execute_hooks(merge_data, :merge_request_hooks) merge_request.project.execute_integrations(merge_data, :merge_request_hooks) execute_external_hooks(merge_request, merge_data) execute_group_mention_hooks(merge_request, merge_data) if action == 'open' enqueue_jira_connect_messages_for(merge_request) end def execute_external_hooks(merge_request, merge_data) # Implemented in EE end def execute_group_mention_hooks(merge_request, merge_data) return unless merge_request.instance_of?(MergeRequest) args = { mentionable_type: 'MergeRequest', mentionable_id: merge_request.id, hook_data: merge_data, is_confidential: false } merge_request.run_after_commit_or_now do Integrations::GroupMentionWorker.perform_async(args) end end def handle_changes(merge_request, options) old_associations = options.fetch(:old_associations, {}) old_assignees = old_associations.fetch(:assignees, []) old_reviewers = old_associations.fetch(:reviewers, []) handle_assignees_change(merge_request, old_assignees) if merge_request.assignees != old_assignees handle_reviewers_change(merge_request, old_reviewers) if merge_request.reviewers != old_reviewers end def handle_assignees_change(merge_request, old_assignees) MergeRequests::HandleAssigneesChangeService .new(project: project, current_user: current_user) .async_execute(merge_request, old_assignees) end def handle_reviewers_change(merge_request, old_reviewers) affected_reviewers = (old_reviewers + merge_request.reviewers) - (old_reviewers & merge_request.reviewers) create_reviewer_note(merge_request, old_reviewers) notification_service.async.changed_reviewer_of_merge_request(merge_request, current_user, old_reviewers) todo_service.reassigned_reviewable(merge_request, current_user, old_reviewers) invalidate_cache_counts(merge_request, users: affected_reviewers.compact) new_reviewers = merge_request.reviewers - old_reviewers merge_request_activity_counter.track_users_review_requested(users: new_reviewers) merge_request_activity_counter.track_reviewers_changed_action(user: current_user) trigger_merge_request_reviewers_updated(merge_request) capture_suggested_reviewers_accepted(merge_request) end def cleanup_environments(merge_request) Environments::StopService.new(merge_request.source_project, current_user) .execute_for_merge_request_pipeline(merge_request) end def cancel_review_app_jobs!(merge_request) environments = merge_request.environments_in_head_pipeline.in_review_folder.available environments.each { |environment| environment.cancel_deployment_jobs! } end def source_project @source_project ||= merge_request.source_project end def target_project @target_project ||= merge_request.target_project end # Don't try to print expensive instance variables. def inspect return "#<#{self.class}>" unless respond_to?(:merge_request) && merge_request "#<#{self.class} #{merge_request.to_reference(full: true)}>" end def merge_request_activity_counter Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter end def deactivate_pages_deployments(merge_request) Pages::DeactivateMrDeploymentsWorker.perform_async(merge_request) end private def self.constructor_container_arg(value) { project: value } end def refresh_pipelines_on_merge_requests(merge_request, allow_duplicate: false) create_pipeline_for(merge_request, current_user, async: true, allow_duplicate: allow_duplicate) end def enqueue_jira_connect_messages_for(merge_request) return unless project.jira_subscription_exists? if Atlassian::JiraIssueKeyExtractor.has_keys?(merge_request.title, merge_request.description) JiraConnect::SyncMergeRequestWorker.perform_async(merge_request.id, Atlassian::JiraConnect::Client.generate_update_sequence_id) end end def create(merge_request) self.params = assign_allowed_merge_params(merge_request, params) super end def update(merge_request) self.params = assign_allowed_merge_params(merge_request, params) super end override :handle_quick_actions def handle_quick_actions(merge_request) super handle_draft_event(merge_request) end def handle_draft_event(merge_request) if draft_event = params.delete(:wip_event) # We update the title that is provided in the params or we use the mr title title = params[:title] || merge_request.title params[:title] = case draft_event when 'draft' then MergeRequest.draft_title(title) when 'ready' then MergeRequest.draftless_title(title) end end end def filter_params(merge_request) super unless merge_request.can_allow_collaboration?(current_user) params.delete(:allow_collaboration) end filter_reviewer(merge_request) filter_suggested_reviewers end def filter_reviewer(merge_request) return if params[:reviewer_ids].blank? unless can_admin_issuable?(merge_request) params.delete(:reviewer_ids) return end unless merge_request.allows_multiple_reviewers? params[:reviewer_ids] = params[:reviewer_ids].first(1) end reviewer_ids = params[:reviewer_ids].select { |reviewer_id| user_can_read?(merge_request, reviewer_id) } if params[:reviewer_ids].map(&:to_s) == [IssuableFinder::Params::NONE] params[:reviewer_ids] = [] elsif reviewer_ids.any? params[:reviewer_ids] = reviewer_ids else params.delete(:reviewer_ids) end end def filter_suggested_reviewers # Implemented in EE end def merge_request_metrics_service(merge_request) MergeRequestMetricsService.new(merge_request.metrics) end def create_assignee_note(merge_request, old_assignees) SystemNoteService.change_issuable_assignees( merge_request, merge_request.project, current_user, old_assignees) end def create_reviewer_note(merge_request, old_reviewers) SystemNoteService.change_issuable_reviewers( merge_request, merge_request.project, current_user, old_reviewers) end def create_pipeline_for(merge_request, user, async: false, allow_duplicate: false) create_pipeline_params = params.slice(:push_options).merge(allow_duplicate: allow_duplicate) if async MergeRequests::CreatePipelineWorker.perform_async( project.id, user.id, merge_request.id, create_pipeline_params.deep_stringify_keys) else MergeRequests::CreatePipelineService .new(project: project, current_user: user, params: create_pipeline_params) .execute(merge_request) end end def abort_auto_merge(merge_request, reason) AutoMergeService.new(project, current_user).abort(merge_request, reason) end # Returns all origin and fork merge requests from `@project` satisfying passed arguments. # rubocop: disable CodeReuse/ActiveRecord def merge_requests_for(source_branch, mr_states: [:opened]) @project.source_of_merge_requests .with_state(mr_states) .where(source_branch: source_branch) .preload(:source_project) # we don't need #includes since we're just preloading for the #select .select(&:source_project) end # rubocop: enable CodeReuse/ActiveRecord def pipeline_merge_requests(pipeline) pipeline.all_merge_requests.opened.each do |merge_request| next unless pipeline.id == merge_request.head_pipeline_id yield merge_request end end def trigger_merge_request_reviewers_updated(merge_request) GraphqlTriggers.merge_request_reviewers_updated(merge_request) end def trigger_merge_request_merge_status_updated(merge_request) GraphqlTriggers.merge_request_merge_status_updated(merge_request) end def trigger_merge_request_approval_state_updated(merge_request) GraphqlTriggers.merge_request_approval_state_updated(merge_request) end def capture_suggested_reviewers_accepted(merge_request) # Implemented in EE end end end MergeRequests::BaseService.prepend_mod_with('MergeRequests::BaseService') ```
# frozen_string_literal: true require 'spec_helper' module MergeRequests class ExampleService < MergeRequests::BaseService def execute(merge_request, async: false, allow_duplicate: false) create_pipeline_for(merge_request, current_user, async: async, allow_duplicate: allow_duplicate) end end end RSpec.describe MergeRequests::BaseService, feature_category: :code_review_workflow do include ProjectForksHelper let_it_be(:project) { create(:project, :repository) } let(:user) { project.first_owner } let(:title) { 'Awesome merge_request' } let(:params) do { title: title, description: 'please fix', source_branch: 'feature', target_branch: 'master' } end describe '#execute_hooks' do subject { MergeRequests::CreateService.new(project: project, current_user: user, params: params).execute } shared_examples 'enqueues Jira sync worker' do specify :aggregate_failures do expect(JiraConnect::SyncMergeRequestWorker).to receive(:perform_async).with(kind_of(Numeric), kind_of(Numeric)).and_call_original Sidekiq::Testing.fake! do expect { subject }.to change(JiraConnect::SyncMergeRequestWorker.jobs, :size).by(1) end end end shared_examples 'does not enqueue Jira sync worker' do it do Sidekiq::Testing.fake! do expect { subject }.not_to change(JiraConnect::SyncMergeRequestWorker.jobs, :size) end end end context 'with a Jira subscription' do before do create(:jira_connect_subscription, namespace: project.namespace) end context 'MR contains Jira issue key' do let(:title) { 'Awesome merge_request with issue JIRA-123' } it_behaves_like 'does not enqueue Jira sync worker' context 'for UpdateService' do subject { MergeRequests::UpdateService.new(project: project, current_user: user, params: params).execute(merge_request) } let(:merge_request) do create(:merge_request, :simple, title: 'Old title', assignee_ids: [user.id], source_project: project, author: user) end it_behaves_like 'enqueues Jira sync worker' end end context 'MR does not contain Jira issue key' do it_behaves_like 'does not enqueue Jira sync worker' end end context 'without a Jira subscription' do it_behaves_like 'does not enqueue Jira sync worker' end end describe `#create_pipeline_for` do let_it_be(:merge_request) { create(:merge_request) } subject { MergeRequests::ExampleService.new(project: project, current_user: user, params: params) } context 'async: false' do it 'creates a pipeline directly' do expect(MergeRequests::CreatePipelineService) .to receive(:new) .with(hash_including(project: project, current_user: user, params: { allow_duplicate: false })) .and_call_original expect(MergeRequests::CreatePipelineWorker).not_to receive(:perform_async) subject.execute(merge_request, async: false) end context 'allow_duplicate: true' do it 'passes :allow_duplicate as true' do expect(MergeRequests::CreatePipelineService) .to receive(:new) .with(hash_including(project: project, current_user: user, params: { allow_duplicate: true })) .and_call_original expect(MergeRequests::CreatePipelineWorker).not_to receive(:perform_async) subject.execute(merge_request, async: false, allow_duplicate: true) end end end context 'async: true' do it 'enques a CreatePipelineWorker' do expect(MergeRequests::CreatePipelineService).not_to receive(:new) expect(MergeRequests::CreatePipelineWorker) .to receive(:perform_async) .with(project.id, user.id, merge_request.id, { "allow_duplicate" => false }) .and_call_original Sidekiq::Testing.fake! do expect { subject.execute(merge_request, async: true) }.to change(MergeRequests::CreatePipelineWorker.jobs, :size).by(1) end end context 'allow_duplicate: true' do it 'passes :allow_duplicate as true' do expect(MergeRequests::CreatePipelineService).not_to receive(:new) expect(MergeRequests::CreatePipelineWorker) .to receive(:perform_async) .with(project.id, user.id, merge_request.id, { "allow_duplicate" => true }) .and_call_original Sidekiq::Testing.fake! do expect { subject.execute(merge_request, async: true, allow_duplicate: true) }.to change(MergeRequests::CreatePipelineWorker.jobs, :size).by(1) end end end end end describe '#constructor_container_arg' do it { expect(described_class.constructor_container_arg("some-value")).to eq({ project: "some-value" }) } end describe '#inspect' do context 'when #merge_request is defined' do let(:klass) do Class.new(described_class) do def merge_request params[:merge_request] end end end let(:params) { {} } subject do klass .new(project: nil, current_user: nil, params: params) .inspect end it { is_expected.to eq "#<#{klass}>" } context 'when merge request is present' do let(:params) { { merge_request: build(:merge_request) } } it { is_expected.to eq "#<#{klass} #{params[:merge_request].to_reference(full: true)}>" } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class RequestReviewService < MergeRequests::BaseService def execute(merge_request, user) return error("Invalid permissions") unless can?(current_user, :update_merge_request, merge_request) reviewer = merge_request.find_reviewer(user) if reviewer return error("Failed to update reviewer") unless reviewer.update(state: :unreviewed) notify_reviewer(merge_request, user) trigger_merge_request_reviewers_updated(merge_request) success else error("Reviewer not found") end end private def notify_reviewer(merge_request, reviewer) notification_service.async.review_requested_of_merge_request(merge_request, current_user, reviewer) todo_service.create_request_review_todo(merge_request, current_user, reviewer) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::RequestReviewService, feature_category: :code_review_workflow do let(:current_user) { create(:user) } let(:user) { create(:user) } let(:merge_request) { create(:merge_request, reviewers: [user]) } let(:reviewer) { merge_request.find_reviewer(user) } let(:project) { merge_request.project } let(:service) { described_class.new(project: project, current_user: current_user) } let(:result) { service.execute(merge_request, user) } let(:todo_service) { spy('todo service') } let(:notification_service) { spy('notification service') } before do allow(NotificationService).to receive(:new) { notification_service } allow(service).to receive(:todo_service).and_return(todo_service) allow(service).to receive(:notification_service).and_return(notification_service) reviewer.update!(state: MergeRequestReviewer.states[:reviewed]) project.add_developer(current_user) project.add_developer(user) end describe '#execute' do shared_examples_for 'failed service execution' do it 'returns an error' do expect(result[:status]).to eq :error end it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { result } end end describe 'invalid permissions' do let(:service) { described_class.new(project: project, current_user: create(:user)) } it_behaves_like 'failed service execution' end describe 'reviewer does not exist' do let(:result) { service.execute(merge_request, create(:user)) } it_behaves_like 'failed service execution' end describe 'reviewer exists' do it 'returns success' do expect(result[:status]).to eq :success end it 'updates reviewers state' do service.execute(merge_request, user) reviewer.reload expect(reviewer.state).to eq 'unreviewed' end it 'sends email to reviewer' do expect(notification_service).to receive_message_chain(:async, :review_requested_of_merge_request).with(merge_request, current_user, user) service.execute(merge_request, user) end it 'creates a new todo for the reviewer' do expect(todo_service).to receive(:create_request_review_todo).with(merge_request, current_user, user) service.execute(merge_request, user) end it_behaves_like 'triggers GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { result } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class GetUrlsService < BaseProjectService def execute(changes) return [] unless project&.printing_merge_request_link_enabled branches = get_branches(changes) merge_requests_map = opened_merge_requests_from_source_branches(branches) branches.map do |branch| existing_merge_request = merge_requests_map[branch] if existing_merge_request url_for_existing_merge_request(existing_merge_request) else url_for_new_merge_request(branch) end end end private def opened_merge_requests_from_source_branches(branches) merge_requests = MergeRequest.from_project(project).opened.from_source_branches(branches) merge_requests.index_by(&:source_branch) end def get_branches(changes) return [] if project.empty_repo? return [] unless project.merge_requests_enabled? changes_list = Gitlab::ChangesList.new(changes) changes_list.map do |change| next unless Gitlab::Git.branch_ref?(change[:ref]) # Deleted branch next if Gitlab::Git.blank_ref?(change[:newrev]) # Default branch branch_name = Gitlab::Git.branch_name(change[:ref]) next if branch_name == project.default_branch branch_name end.compact end def url_for_new_merge_request(branch_name) merge_request_params = { source_branch: branch_name } url = Gitlab::Routing.url_helpers.project_new_merge_request_url(project, merge_request: merge_request_params) { branch_name: branch_name, url: url, new_merge_request: true } end def url_for_existing_merge_request(merge_request) target_project = merge_request.target_project url = Gitlab::Routing.url_helpers.project_merge_request_url(target_project, merge_request) { branch_name: merge_request.source_branch, url: url, new_merge_request: false } end end end ```
# frozen_string_literal: true require "spec_helper" RSpec.describe MergeRequests::GetUrlsService, feature_category: :code_review_workflow do include ProjectForksHelper let(:project) { create(:project, :public, :repository) } let(:service) { described_class.new(project: project) } let(:source_branch) { "merge-test" } let(:new_merge_request_url) { "http://#{Gitlab.config.gitlab.host}/#{project.full_path}/-/merge_requests/new?merge_request%5Bsource_branch%5D=#{source_branch}" } let(:show_merge_request_url) { "http://#{Gitlab.config.gitlab.host}/#{project.full_path}/-/merge_requests/#{merge_request.iid}" } let(:new_branch_changes) { "#{Gitlab::Git::BLANK_SHA} 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/#{source_branch}" } let(:deleted_branch_changes) { "d14d6c0abdd253381df51a723d58691b2ee1ab08 #{Gitlab::Git::BLANK_SHA} refs/heads/#{source_branch}" } let(:existing_branch_changes) { "d14d6c0abdd253381df51a723d58691b2ee1ab08 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/#{source_branch}" } let(:default_branch_changes) { "d14d6c0abdd253381df51a723d58691b2ee1ab08 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/master" } describe "#execute" do shared_examples 'new_merge_request_link' do it 'returns url to create new merge request' do result = service.execute(changes) expect(result).to match([{ branch_name: source_branch, url: new_merge_request_url, new_merge_request: true }]) end end shared_examples 'show_merge_request_url' do it 'returns url to view merge request' do result = service.execute(changes) expect(result).to match([{ branch_name: source_branch, url: show_merge_request_url, new_merge_request: false }]) end end shared_examples 'no_merge_request_url' do it 'returns no URL' do result = service.execute(changes) expect(result).to be_empty end end context 'when project is nil' do let(:project) { nil } let(:changes) { default_branch_changes } it_behaves_like 'no_merge_request_url' end context 'pushing to default branch' do let(:changes) { default_branch_changes } it_behaves_like 'no_merge_request_url' end context 'pushing to project with MRs disabled' do let(:changes) { new_branch_changes } before do project.project_feature.update_attribute(:merge_requests_access_level, ProjectFeature::DISABLED) end it_behaves_like 'no_merge_request_url' end context 'pushing one completely new branch' do let(:changes) { new_branch_changes } it_behaves_like 'new_merge_request_link' end context 'pushing to existing branch but no merge request' do let(:changes) { existing_branch_changes } it_behaves_like 'new_merge_request_link' end context 'pushing to deleted branch' do let(:changes) { deleted_branch_changes } it_behaves_like 'no_merge_request_url' end context 'pushing to existing branch and merge request opened' do let!(:merge_request) { create(:merge_request, source_project: project, source_branch: source_branch) } let(:changes) { existing_branch_changes } it_behaves_like 'show_merge_request_url' end context 'pushing to existing branch and merge request is reopened' do let!(:merge_request) { create(:merge_request, :opened, source_project: project, source_branch: source_branch) } let(:changes) { existing_branch_changes } it_behaves_like 'show_merge_request_url' end context 'pushing to existing branch from forked project' do let(:user) { create(:user) } let!(:forked_project) { fork_project(project, user, repository: true) } let!(:merge_request) { create(:merge_request, source_project: forked_project, target_project: project, source_branch: source_branch) } let(:changes) { existing_branch_changes } # Source project is now the forked one let(:service) { described_class.new(project: forked_project) } before do allow(forked_project).to receive(:empty_repo?).and_return(false) end it_behaves_like 'show_merge_request_url' end context 'pushing to existing branch and merge request is closed' do let!(:merge_request) { create(:merge_request, :closed, source_project: project, source_branch: source_branch) } let(:changes) { existing_branch_changes } it_behaves_like 'new_merge_request_link' end context 'pushing to existing branch and merge request is merged' do let!(:merge_request) { create(:merge_request, :merged, source_project: project, source_branch: source_branch) } let(:changes) { existing_branch_changes } it_behaves_like 'new_merge_request_link' end context 'pushing new branch and existing branch (with merge request created) at once' do let!(:merge_request) { create(:merge_request, source_project: project, source_branch: "markdown") } let(:new_branch_changes) { "#{Gitlab::Git::BLANK_SHA} 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/new_branch" } let(:existing_branch_changes) { "d14d6c0abdd253381df51a723d58691b2ee1ab08 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/markdown" } let(:changes) { "#{new_branch_changes}\n#{existing_branch_changes}" } let(:new_merge_request_url) { "http://#{Gitlab.config.gitlab.host}/#{project.full_path}/-/merge_requests/new?merge_request%5Bsource_branch%5D=new_branch" } it 'returns 2 urls for both creating new and showing merge request' do result = service.execute(changes) expect(result).to match([{ branch_name: "new_branch", url: new_merge_request_url, new_merge_request: true }, { branch_name: "markdown", url: show_merge_request_url, new_merge_request: false }]) end end context 'when printing_merge_request_link_enabled is false' do it 'returns empty array' do project.update!(printing_merge_request_link_enabled: false) result = service.execute(existing_branch_changes) expect(result).to eq([]) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests # PostMergeService class # # Mark existing merge request as merged # and execute all hooks and notifications # class PostMergeService < MergeRequests::BaseService include RemovesRefs MAX_RETARGET_MERGE_REQUESTS = 4 def execute(merge_request) return if merge_request.merged? # Mark the merge request as merged, everything that happens afterwards is # executed once merge_request.mark_as_merged create_event(merge_request) todo_service.merge_merge_request(merge_request, current_user) merge_request_activity_counter.track_merge_mr_action(user: current_user) create_note(merge_request) close_issues(merge_request) notification_service.merge_mr(merge_request, current_user) invalidate_cache_counts(merge_request, users: merge_request.assignees | merge_request.reviewers) merge_request.update_project_counter_caches delete_non_latest_diffs(merge_request) cancel_review_app_jobs!(merge_request) cleanup_environments(merge_request) cleanup_refs(merge_request) deactivate_pages_deployments(merge_request) execute_hooks(merge_request, 'merge') end private def close_issues(merge_request) return unless merge_request.target_branch == project.default_branch closed_issues = merge_request.visible_closing_issues_for(current_user) closed_issues.each do |issue| # We are intentionally only closing Issues asynchronously (excluding ExternalIssues) # as the worker only supports finding an Issue. We are also only experiencing # SQL timeouts when closing an Issue. if issue.is_a?(Issue) MergeRequests::CloseIssueWorker.perform_async( project.id, current_user.id, issue.id, merge_request.id ) else Issues::CloseService.new(container: project, current_user: current_user).execute(issue, commit: merge_request) end end end def delete_non_latest_diffs(merge_request) DeleteNonLatestDiffsService.new(merge_request).execute end def create_merge_event(merge_request, current_user) EventCreateService.new.merge_mr(merge_request, current_user) end def create_event(merge_request) # Making sure MergeRequest::Metrics updates are in sync with # Event creation. Event.transaction do merge_event = create_merge_event(merge_request, current_user) merge_request_metrics_service(merge_request).merge(merge_event) end end end end MergeRequests::PostMergeService.prepend_mod_with('MergeRequests::PostMergeService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::PostMergeService, feature_category: :code_review_workflow do include ProjectForksHelper let_it_be(:user) { create(:user) } let_it_be(:merge_request, reload: true) { create(:merge_request, assignees: [user]) } let_it_be(:project) { merge_request.project } subject { described_class.new(project: project, current_user: user).execute(merge_request) } before do project.add_maintainer(user) end describe '#execute' do it_behaves_like 'cache counters invalidator' it_behaves_like 'merge request reviewers cache counters invalidator' it 'refreshes the number of open merge requests for a valid MR', :use_clean_rails_memory_store_caching do # Cache the counter before the MR changed state. project.open_merge_requests_count expect do subject BatchLoader::Executor.clear_current end.to change { project.open_merge_requests_count }.from(1).to(0) end it 'updates metrics' do metrics = merge_request.metrics metrics_service = double(MergeRequestMetricsService) allow(MergeRequestMetricsService) .to receive(:new) .with(metrics) .and_return(metrics_service) expect(metrics_service).to receive(:merge) subject end it 'calls the merge request activity counter' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_merge_mr_action) .with(user: user) subject end it 'deletes non-latest diffs' do diff_removal_service = instance_double(MergeRequests::DeleteNonLatestDiffsService, execute: nil) expect(MergeRequests::DeleteNonLatestDiffsService) .to receive(:new).with(merge_request) .and_return(diff_removal_service) subject expect(diff_removal_service).to have_received(:execute) end it 'clean up environments for the merge request' do expect_next_instance_of(::Environments::StopService) do |stop_environment_service| expect(stop_environment_service).to receive(:execute_for_merge_request_pipeline).with(merge_request) end subject end it 'schedules CleanupRefsService' do expect(MergeRequests::CleanupRefsService).to receive(:schedule).with(merge_request) subject end context 'when there are issues to be closed' do let_it_be(:issue) { create(:issue, project: project) } before do merge_request.update!(target_branch: 'foo') allow(project).to receive(:default_branch).and_return('foo') allow(merge_request).to receive(:visible_closing_issues_for).and_return([issue]) end it 'performs MergeRequests::CloseIssueWorker asynchronously' do expect(MergeRequests::CloseIssueWorker) .to receive(:perform_async) .with(project.id, user.id, issue.id, merge_request.id) subject expect(merge_request.reload).to be_merged end context 'when issue is an external issue' do let_it_be(:issue) { ExternalIssue.new('JIRA-123', project) } it 'executes Issues::CloseService' do expect_next_instance_of(Issues::CloseService) do |close_service| expect(close_service).to receive(:execute).with(issue, commit: merge_request) end subject expect(merge_request.reload).to be_merged end end end context 'when the merge request has review apps' do it 'cancels all review app deployments' do pipeline = create(:ci_pipeline, source: :merge_request_event, merge_request: merge_request, project: project, sha: merge_request.diff_head_sha, merge_requests_as_head_pipeline: [merge_request]) review_env_a = create(:environment, project: project, state: :available, name: 'review/a') review_env_b = create(:environment, project: project, state: :available, name: 'review/b') review_env_c = create(:environment, project: project, state: :stopped, name: 'review/c') deploy_env = create(:environment, project: project, state: :available, name: 'deploy') review_job_a1 = create(:ci_build, :with_deployment, :start_review_app, pipeline: pipeline, project: project, environment: review_env_a.name) review_job_a2 = create(:ci_build, :with_deployment, :start_review_app, pipeline: pipeline, project: project, environment: review_env_a.name) finished_review_job_a = create(:ci_build, :with_deployment, :start_review_app, pipeline: pipeline, project: project, status: :success, environment: review_env_a.name) review_job_b1 = create(:ci_build, :with_deployment, :start_review_app, pipeline: pipeline, project: project, environment: review_env_b.name) review_job_b2 = create(:ci_build, :start_review_app, pipeline: pipeline, project: project, environment: review_env_b.name) review_job_c1 = create(:ci_build, :with_deployment, :start_review_app, pipeline: pipeline, project: project, environment: review_env_c.name) deploy_job = create(:ci_build, :with_deployment, :deploy_to_production, pipeline: pipeline, project: project, environment: deploy_env.name) subject expect(review_job_a1.reload.canceled?).to be true expect(review_job_a2.reload.canceled?).to be true expect(finished_review_job_a.reload.status).to eq "success" expect(finished_review_job_a.reload.canceled?).to be false expect(review_job_b1.reload.canceled?).to be true expect(review_job_b2.reload.canceled?).to be false expect(review_job_c1.reload.canceled?).to be false expect(deploy_job.reload.canceled?).to be false end end context 'when the merge request has a pages deployment' do it 'performs Pages::DeactivateMrDeploymentWorker asynchronously' do expect(Pages::DeactivateMrDeploymentsWorker) .to receive(:perform_async) .with(merge_request) subject expect(merge_request.reload).to be_merged end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ResolvedDiscussionNotificationService < MergeRequests::BaseService def execute(merge_request) return unless merge_request.discussions_resolved? SystemNoteService.resolve_all_discussions(merge_request, project, current_user) execute_hooks(merge_request, 'update') notification_service.async.resolve_all_discussions(merge_request, current_user) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ResolvedDiscussionNotificationService, feature_category: :code_review_workflow do let(:merge_request) { create(:merge_request) } let(:user) { create(:user) } let(:project) { merge_request.project } subject { described_class.new(project: project, current_user: user) } describe "#execute" do context "when not all discussions are resolved" do before do allow(merge_request).to receive(:discussions_resolved?).and_return(false) end it "doesn't add a system note" do expect(SystemNoteService).not_to receive(:resolve_all_discussions) subject.execute(merge_request) end it "doesn't send a notification email" do expect_any_instance_of(NotificationService).not_to receive(:resolve_all_discussions) subject.execute(merge_request) end it "doesn't send a webhook" do expect_any_instance_of(MergeRequests::BaseService).not_to receive(:execute_hooks) subject.execute(merge_request) end end context "when all discussions are resolved" do before do allow(merge_request).to receive(:discussions_resolved?).and_return(true) end it "adds a system note" do expect(SystemNoteService).to receive(:resolve_all_discussions).with(merge_request, project, user) subject.execute(merge_request) end it "sends a notification email", :sidekiq_might_not_need_inline do expect_any_instance_of(NotificationService).to receive(:resolve_all_discussions).with(merge_request, user) subject.execute(merge_request) end it "sends a webhook" do expect_any_instance_of(MergeRequests::BaseService).to receive(:execute_hooks).with(merge_request, 'update') subject.execute(merge_request) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class RemoveApprovalService < MergeRequests::BaseService # rubocop: disable CodeReuse/ActiveRecord def execute(merge_request) return unless merge_request.approved_by?(current_user) # paranoid protection against running wrong deletes return unless merge_request.id && current_user.id approval = merge_request.approvals.where(user: current_user) trigger_approval_hooks(merge_request) do next unless approval.destroy_all # rubocop: disable Cop/DestroyAll reset_approvals_cache(merge_request) create_note(merge_request) merge_request_activity_counter.track_unapprove_mr_action(user: current_user) trigger_merge_request_merge_status_updated(merge_request) trigger_merge_request_reviewers_updated(merge_request) trigger_merge_request_approval_state_updated(merge_request) end success end # rubocop: enable CodeReuse/ActiveRecord private def reset_approvals_cache(merge_request) merge_request.approvals.reset end def trigger_approval_hooks(merge_request) yield notification_service.async.unapprove_mr(merge_request, current_user) execute_hooks(merge_request, 'unapproved') end def create_note(merge_request) SystemNoteService.unapprove_mr(merge_request, current_user) end end end MergeRequests::RemoveApprovalService.prepend_mod_with('MergeRequests::RemoveApprovalService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::RemoveApprovalService, feature_category: :code_review_workflow do describe '#execute' do let(:user) { create(:user) } let(:project) { create(:project) } let(:merge_request) { create(:merge_request, source_project: project) } let!(:existing_approval) { create(:approval, merge_request: merge_request) } subject(:service) { described_class.new(project: project, current_user: user) } def execute! service.execute(merge_request) end before do project.add_developer(user) end context 'with a user who has approved' do let!(:approval) { create(:approval, user: user, merge_request: merge_request) } let(:notification_service) { NotificationService.new } before do allow(service).to receive(:notification_service).and_return(notification_service) end it 'removes the approval' do expect { execute! }.to change { merge_request.approvals.size }.from(2).to(1) end it 'creates an unapproval note, triggers a web hook, and sends a notification' do expect(service).to receive(:execute_hooks).with(merge_request, 'unapproved') expect(SystemNoteService).to receive(:unapprove_mr) expect(notification_service).to receive_message_chain(:async, :unapprove_mr).with(merge_request, user) execute! end it 'tracks merge request unapprove action' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_unapprove_mr_action).with(user: user) execute! end it_behaves_like 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { execute! } end it_behaves_like 'triggers GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { execute! } end it_behaves_like 'triggers GraphQL subscription mergeRequestApprovalStateUpdated' do let(:action) { execute! } end end context 'with a user who has not approved' do it 'does not create an unapproval note and triggers web hook' do expect(service).not_to receive(:execute_hooks) expect(SystemNoteService).not_to receive(:unapprove_mr) execute! end it 'does not track merge request unapprove action' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_unapprove_mr_action).with(user: user) execute! end it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { execute! } end it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { execute! } end it_behaves_like 'does not trigger GraphQL subscription mergeRequestApprovalStateUpdated' do let(:action) { execute! } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ApprovalService < MergeRequests::BaseService def execute(merge_request) return unless eligible_for_approval?(merge_request) approval = merge_request.approvals.new( user: current_user, patch_id_sha: merge_request.current_patch_id_sha ) return success unless save_approval(approval) reset_approvals_cache(merge_request) merge_request_activity_counter.track_approve_mr_action(user: current_user, merge_request: merge_request) trigger_merge_request_merge_status_updated(merge_request) trigger_merge_request_reviewers_updated(merge_request) trigger_merge_request_approval_state_updated(merge_request) # Approval side effects (things not required to be done immediately but # should happen after a successful approval) should be done asynchronously # utilizing the `Gitlab::EventStore`. # # Workers can subscribe to the `MergeRequests::ApprovedEvent`. Gitlab::EventStore.publish( MergeRequests::ApprovedEvent.new( data: { current_user_id: current_user.id, merge_request_id: merge_request.id } ) ) success end private def eligible_for_approval?(merge_request) merge_request.eligible_for_approval_by?(current_user) end def save_approval(approval) Approval.safe_ensure_unique do approval.save end end def reset_approvals_cache(merge_request) merge_request.approvals.reset end end end MergeRequests::ApprovalService.prepend_mod_with('MergeRequests::ApprovalService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ApprovalService, feature_category: :code_review_workflow do describe '#execute' do let(:user) { create(:user) } let(:merge_request) { create(:merge_request, reviewers: [user]) } let(:project) { merge_request.project } let!(:todo) { create(:todo, user: user, project: project, target: merge_request) } subject(:service) { described_class.new(project: project, current_user: user) } before do project.add_developer(user) stub_feature_flags ff_require_saml_auth_to_approve: false end context 'with invalid approval' do before do allow(merge_request.approvals).to receive(:new).and_return(double(save: false)) end it 'does not reset approvals' do expect(merge_request.approvals).not_to receive(:reset) service.execute(merge_request) end it 'does not track merge request approve action' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_approve_mr_action).with(user: user) service.execute(merge_request) end it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { service.execute(merge_request) } end it 'does not publish MergeRequests::ApprovedEvent' do expect { service.execute(merge_request) }.not_to publish_event(MergeRequests::ApprovedEvent) end it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { service.execute(merge_request) } end end context 'with an already approved MR' do before do merge_request.approvals.create!(user: user) end it 'does not create an approval' do expect { service.execute(merge_request) }.not_to change { merge_request.approvals.size } end it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { service.execute(merge_request) } end it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { service.execute(merge_request) } end end context 'with valid approval' do it 'resets approvals' do expect(merge_request.approvals).to receive(:reset) service.execute(merge_request) end it 'tracks merge request approve action' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_approve_mr_action).with(user: user, merge_request: merge_request) service.execute(merge_request) end context 'when generating a patch_id_sha' do it 'records a value' do service.execute(merge_request) expect(merge_request.approvals.last.patch_id_sha).to eq(merge_request.current_patch_id_sha) end context 'when MergeRequest#current_patch_id_sha is nil' do it 'records patch_id_sha as nil' do expect(merge_request).to receive(:current_patch_id_sha).and_return(nil) service.execute(merge_request) expect(merge_request.approvals.last.patch_id_sha).to be_nil end end end it 'publishes MergeRequests::ApprovedEvent' do expect { service.execute(merge_request) } .to publish_event(MergeRequests::ApprovedEvent) .with(current_user_id: user.id, merge_request_id: merge_request.id) end it_behaves_like 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { service.execute(merge_request) } end it_behaves_like 'triggers GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { service.execute(merge_request) } end it_behaves_like 'triggers GraphQL subscription mergeRequestApprovalStateUpdated' do let(:action) { service.execute(merge_request) } end end context 'user cannot update the merge request' do before do project.add_guest(user) end it 'does not update approvals' do expect { service.execute(merge_request) }.not_to change { merge_request.approvals.size } end it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { service.execute(merge_request) } end it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { service.execute(merge_request) } end it_behaves_like 'does not trigger GraphQL subscription mergeRequestApprovalStateUpdated' do let(:action) { service.execute(merge_request) } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class AddTodoWhenBuildFailsService < MergeRequests::BaseService # Adds a todo to the parent merge_request when a CI build fails # def execute(commit_status) return if commit_status.allow_failure? || commit_status.retried? pipeline_merge_requests(commit_status.pipeline) do |merge_request| todo_service.merge_request_build_failed(merge_request) end end # Closes any pending build failed todos for the parent MRs when a # build is retried # def close(commit_status) close_all(commit_status.pipeline) end def close_all(pipeline) pipeline_merge_requests(pipeline) do |merge_request| todo_service.merge_request_build_retried(merge_request) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::MergeRequests::AddTodoWhenBuildFailsService, feature_category: :code_review_workflow do let(:user) { create(:user) } let(:project) { create(:project, :repository) } let(:sha) { '1234567890abcdef1234567890abcdef12345678' } let(:ref) { merge_request.source_branch } let(:service) do described_class.new(project: project, current_user: user, params: { commit_message: 'Awesome message' }) end let(:todo_service) { spy('todo service') } let(:merge_request) do create(:merge_request, :with_detached_merge_request_pipeline, :opened, merge_user: user) end let(:pipeline) do merge_request.all_pipelines.take end before do allow_any_instance_of(MergeRequest) .to receive(:head_pipeline_id) .and_return(pipeline.id) allow(service).to receive(:todo_service).and_return(todo_service) end describe '#execute' do context 'commit status with ref' do let(:commit_status) do create(:generic_commit_status, ref: ref, pipeline: pipeline) end it 'notifies the todo service' do expect(todo_service).to receive(:merge_request_build_failed).with(merge_request) service.execute(commit_status) end end context 'commit status with non-HEAD ref' do let(:commit_status) { create(:generic_commit_status, ref: ref) } it 'does not notify the todo service' do expect(todo_service).not_to receive(:merge_request_build_failed) service.execute(commit_status) end end context 'commit status without ref' do let(:commit_status) { create(:generic_commit_status) } it 'does not notify the todo service' do expect(todo_service).not_to receive(:merge_request_build_failed) service.execute(commit_status) end end context 'when commit status is a build allowed to fail' do let(:commit_status) do create(:ci_build, :allowed_to_fail, ref: ref, pipeline: pipeline) end it 'does not create todo' do expect(todo_service).not_to receive(:merge_request_build_failed) service.execute(commit_status) end end context 'when build belongs to a merge request pipeline' do let(:pipeline) do create( :ci_pipeline, source: :merge_request_event, ref: merge_request.merge_ref_path, merge_request: merge_request, merge_requests_as_head_pipeline: [merge_request] ) end let(:commit_status) { create(:ci_build, ref: merge_request.merge_ref_path, pipeline: pipeline) } it 'notifies the todo service' do expect(todo_service).to receive(:merge_request_build_failed).with(merge_request) service.execute(commit_status) end end end describe '#close' do context 'commit status with ref' do let(:commit_status) { create(:generic_commit_status, ref: merge_request.source_branch, pipeline: pipeline) } it 'notifies the todo service' do expect(todo_service).to receive(:merge_request_build_retried).with(merge_request) service.close(commit_status) end end context 'commit status with non-HEAD ref' do let(:commit_status) { create(:generic_commit_status, ref: merge_request.source_branch) } it 'does not notify the todo service' do expect(todo_service).not_to receive(:merge_request_build_retried) service.close(commit_status) end end context 'commit status without ref' do let(:commit_status) { create(:generic_commit_status) } it 'does not notify the todo service' do expect(todo_service).not_to receive(:merge_request_build_retried) service.close(commit_status) end end context 'when build belongs to a merge request pipeline' do let(:pipeline) do create( :ci_pipeline, source: :merge_request_event, ref: merge_request.merge_ref_path, merge_request: merge_request, merge_requests_as_head_pipeline: [merge_request] ) end let(:commit_status) { create(:ci_build, ref: merge_request.merge_ref_path, pipeline: pipeline) } it 'notifies the todo service' do expect(todo_service).to receive(:merge_request_build_retried).with(merge_request) service.close(commit_status) end end end describe '#close_all' do context 'when using pipeline that belongs to merge request' do it 'resolves todos about failed builds for pipeline' do service.close_all(pipeline) expect(todo_service) .to have_received(:merge_request_build_retried) .with(merge_request) end end context 'when pipeline is not related to merge request' do let(:pipeline) { create(:ci_empty_pipeline) } it 'does not resolve any todos about failed builds' do service.close_all(pipeline) expect(todo_service) .not_to have_received(:merge_request_build_retried) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class BuildService < MergeRequests::BaseService include Gitlab::Utils::StrongMemoize def execute @params_issue_iid = params.delete(:issue_iid) self.merge_request = MergeRequest.new # TODO: this should handle all quick actions that don't have side effects # https://gitlab.com/gitlab-org/gitlab-foss/issues/53658 merge_quick_actions_into_params!(merge_request, only: [:target_branch]) # Assign the projects first so we can use policies for `filter_params` merge_request.author = current_user merge_request.source_project = find_source_project merge_request.target_project = find_target_project initialize_callbacks!(merge_request) process_params merge_request.compare_commits = [] set_merge_request_target_branch merge_request.can_be_created = projects_and_branches_valid? # compare branches only if branches are valid, otherwise # compare_branches may raise an error if merge_request.can_be_created compare_branches assign_title_and_description assign_labels assign_milestone end merge_request end private attr_accessor :merge_request delegate :target_branch, :target_branch_ref, :target_project, :source_branch, :source_branch_ref, :source_project, :compare_commits, :draft_title, :description, :first_multiline_commit, :errors, to: :merge_request def force_remove_source_branch if params.key?(:force_remove_source_branch) params.delete(:force_remove_source_branch) else merge_request.source_project.remove_source_branch_after_merge? end end def filter_id_params # merge_request.assign_attributes(...) below is a Rails # method that only work if all the params it is passed have # corresponding fields in the database. As there are no fields # in the database for :add_label_ids, :remove_label_ids, # :add_assignee_ids and :remove_assignee_ids, we # need to remove them from the params before the call to # merge_request.assign_attributes(...) # # IssuableBaseService#process_label_ids and # IssuableBaseService#process_assignee_ids take care # of the removal. params[:label_ids] = process_label_ids(params, issuable: merge_request, extra_label_ids: merge_request.label_ids.to_a) params[:assignee_ids] = process_assignee_ids(params, extra_assignee_ids: merge_request.assignee_ids.to_a) merge_request.assign_attributes(params.to_h.compact) end def process_params # Force remove the source branch? merge_request.merge_params['force_remove_source_branch'] = force_remove_source_branch # Only assign merge requests params that are allowed self.params = assign_allowed_merge_params(merge_request, params) # Filter out params that are either not allowed or invalid filter_params(merge_request) # Filter out the following from params: # - :add_label_ids and :remove_label_ids # - :add_assignee_ids and :remove_assignee_ids filter_id_params end def find_source_project source_project = project_from_params(:source_project) return source_project if source_project.present? && can?(current_user, :create_merge_request_from, source_project) project end def find_target_project target_project = project_from_params(:target_project) return target_project if target_project.present? && can?(current_user, :create_merge_request_in, target_project) target_project = project.default_merge_request_target return target_project if target_project.present? && can?(current_user, :create_merge_request_in, target_project) project end def project_from_params(param_name) project_from_params = params.delete(param_name) id_param_name = :"#{param_name}_id" if project_from_params.nil? && params[id_param_name] project_from_params = Project.find_by_id(params.delete(id_param_name)) end project_from_params end def set_merge_request_target_branch if source_branch_default? && !target_branch_specified? merge_request.target_branch = nil else merge_request.target_branch ||= get_target_branch end end def get_target_branch target_project.default_branch end def source_branch_specified? params[:source_branch].present? end def target_branch_specified? params[:target_branch].present? end def projects_and_branches_valid? return false if source_project.nil? || target_project.nil? return false unless source_branch_specified? || target_branch_specified? validate_projects_and_branches errors.blank? end def compare_branches compare = CompareService.new( source_project, source_branch_ref ).execute( target_project, target_branch_ref ) if compare merge_request.compare_commits = compare.commits merge_request.compare = compare end end def validate_projects_and_branches merge_request.validate_target_project merge_request.validate_fork return if errors.any? add_error('You must select source and target branch') unless branches_present? add_error('You must select different branches') if same_source_and_target? add_error("Source branch \"#{source_branch}\" does not exist") unless source_branch_exists? add_error("Target branch \"#{target_branch}\" does not exist") unless target_branch_exists? end def add_error(message) errors.add(:base, message) end def branches_present? target_branch.present? && source_branch.present? end def same_source_and_target? same_source_and_target_project? && target_branch == source_branch end def source_branch_default? same_source_and_target_project? && source_branch == target_project.default_branch end def same_source_and_target_project? source_project == target_project end def source_branch_exists? source_branch.blank? || source_project.commit(source_branch) end def target_branch_exists? target_branch.blank? || target_project.commit(target_branch) end def set_draft_title_if_needed return unless compare_commits.empty? || Gitlab::Utils.to_boolean(params[:draft]) merge_request.title = draft_title end # When your branch name starts with an iid followed by a dash this pattern will be # interpreted as the user wants to close that issue on this project. # # For example: # - Issue 112 exists # - title: Emoji don't show up in commit title # - Source branch is: 112-fix-mep-mep # # Will lead to: # - Appending `Closes #112` to the description # - Setting the title as 'Resolves "Emoji don't show up in commit title"' if there is # more than one commit in the MR # def assign_title_and_description assign_description_from_repository_template replace_variables_in_description assign_title_and_description_from_commits merge_request.title ||= title_from_issue if target_project.issues_enabled? || target_project.external_issue_tracker merge_request.title ||= source_branch.titleize.humanize set_draft_title_if_needed append_closes_description end def assign_labels return unless target_project.issues_enabled? && issue return if merge_request.label_ids&.any? merge_request.label_ids = issue.try(:label_ids) end def assign_milestone return unless target_project.issues_enabled? && issue return if merge_request.milestone_id.present? merge_request.milestone_id = issue.try(:milestone_id) end def append_closes_description return unless issue&.to_reference.present? closes_issue = "#{target_project.autoclose_referenced_issues ? 'Closes' : 'Related to'} #{issue.to_reference}" if description.present? descr_parts = [merge_request.description, closes_issue] merge_request.description = descr_parts.join("\n\n") else merge_request.description = closes_issue end end def assign_title_and_description_from_commits commits = compare_commits if commits&.count == 1 commit = commits.first else commit = first_multiline_commit return unless commit end merge_request.title ||= commit.title merge_request.description ||= commit.description.try(:strip) end def title_from_issue return unless issue return "Resolve \"#{issue.title}\"" if issue.is_a?(Issue) return if issue_iid.blank? title_parts = ["Resolve #{issue.to_reference}"] branch_title = source_branch.downcase.remove(issue_iid.downcase).titleize.humanize title_parts << "\"#{branch_title}\"" if branch_title.present? title_parts.join(' ') end def assign_description_from_repository_template return unless merge_request.description.blank? # Use TemplateFinder to load the default template. We need this mainly for # the project_id, in case it differs from the target project. Conveniently, # since the underlying merge_request_template_names_hash is cached, this # should also be relatively cheap and allows us to bail early if the project # does not have a default template. templates = TemplateFinder.all_template_names(target_project, :merge_requests) template = templates.values.flatten.find { |tmpl| tmpl[:name].casecmp?('default') } return unless template begin repository_template = TemplateFinder.build( :merge_requests, target_project, { name: template[:name], source_template_project_id: template[:project_id] } ).execute rescue ::Gitlab::Template::Finders::RepoTemplateFinder::FileNotFoundError return end return unless repository_template.present? merge_request.description = repository_template.content end def replace_variables_in_description return unless merge_request.description.present? merge_request.description = ::Gitlab::MergeRequests::MessageGenerator.new( merge_request: merge_request, current_user: current_user ).new_mr_description end def issue_iid strong_memoize(:issue_iid) do @params_issue_iid || begin id = if target_project.external_issue_tracker target_project.external_issue_reference_pattern.match(source_branch).try(:[], 0) end id || source_branch.match(/\A(\d+)-/).try(:[], 1) end end end def issue strong_memoize(:issue) do target_project.get_issue(issue_iid, current_user) end end end end MergeRequests::BuildService.prepend_mod_with('MergeRequests::BuildService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::BuildService, feature_category: :code_review_workflow do using RSpec::Parameterized::TableSyntax include RepoHelpers include ProjectForksHelper let(:project) { create(:project, :repository) } let(:source_project) { nil } let(:target_project) { nil } let(:user) { create(:user) } let(:issue_confidential) { false } let(:issue) { create(:issue, project: project, title: 'A bug', confidential: issue_confidential) } let(:description) { nil } let(:source_branch) { 'feature-branch' } let(:target_branch) { 'master' } let(:milestone_id) { nil } let(:label_ids) { [] } let(:merge_request) { service.execute } let(:compare) { double(:compare, commits: commits) } let(:commit_1) do double(:commit_1, sha: 'f00ba6', safe_message: 'Initial commit', gitaly_commit?: false, id: 'f00ba6', parent_ids: ['f00ba5'], author_email: '[email protected]', author_name: 'Tom Example') end let(:commit_2) do double(:commit_2, sha: 'f00ba7', safe_message: "Closes #1234 Second commit\n\nCreate the app", gitaly_commit?: false, id: 'f00ba7', parent_ids: ['f00ba6'], author_email: '[email protected]', author_name: 'Alice Example') end let(:commit_3) do double(:commit_3, sha: 'f00ba8', safe_message: 'This is a bad commit message!', gitaly_commit?: false, id: 'f00ba8', parent_ids: ['f00ba7'], author_email: '[email protected]', author_name: 'Jo Example') end let(:commits) { nil } let(:params) do { description: description, source_branch: source_branch, target_branch: target_branch, source_project: source_project, target_project: target_project, milestone_id: milestone_id, label_ids: label_ids } end let(:service) do described_class.new(project: project, current_user: user, params: params) end before do project.add_guest(user) end def stub_compare allow(CompareService).to receive_message_chain(:new, :execute).and_return(compare) allow(project).to receive(:commit).and_return(commit_1) allow(project).to receive(:commit).and_return(commit_2) allow(project).to receive(:commit).and_return(commit_3) end shared_examples 'allows the merge request to be created' do it do expect(merge_request.can_be_created).to eq(true) end end shared_examples 'forbids the merge request from being created' do it 'returns that the merge request cannot be created' do expect(merge_request.can_be_created).to eq(false) end it 'adds an error message to the merge request' do expect(merge_request.errors).to contain_exactly(*Array(error_message)) end end shared_examples 'with a Default.md template' do let(:files) { { '.gitlab/merge_request_templates/Default.md' => 'Default template contents' } } let(:project) { create(:project, :custom_repo, files: files) } it 'the template description is preferred' do expect(merge_request.description).to eq('Default template contents') end end describe '#execute' do it 'calls the compare service with the correct arguments' do allow_any_instance_of(described_class).to receive(:projects_and_branches_valid?).and_return(true) expect(CompareService).to receive(:new) .with(project, Gitlab::Git::BRANCH_REF_PREFIX + source_branch) .and_call_original expect_any_instance_of(CompareService).to receive(:execute) .with(project, Gitlab::Git::BRANCH_REF_PREFIX + target_branch) .and_call_original merge_request end it 'does not assign force_remove_source_branch' do expect(merge_request.force_remove_source_branch?).to be_truthy end context 'with force_remove_source_branch parameter when the user is authorized' do let(:mr_params) { params.merge(force_remove_source_branch: '1') } let(:source_project) { fork_project(project, user) } let(:merge_request) { described_class.new(project: project, current_user: user, params: mr_params).execute } before do project.add_reporter(user) end it 'assigns force_remove_source_branch' do expect(merge_request.force_remove_source_branch?).to be_truthy end context 'with project setting remove_source_branch_after_merge false' do before do project.remove_source_branch_after_merge = false end it 'assigns force_remove_source_branch' do expect(merge_request.force_remove_source_branch?).to be_truthy end end end context 'with project setting remove_source_branch_after_merge true' do before do project.remove_source_branch_after_merge = true end it 'assigns force_remove_source_branch' do expect(merge_request.force_remove_source_branch?).to be_truthy end context 'with force_remove_source_branch parameter false' do before do params[:force_remove_source_branch] = '0' end it 'does not assign force_remove_source_branch' do expect(merge_request.force_remove_source_branch?).to be(false) end end end context 'missing source branch' do let(:source_branch) { '' } it_behaves_like 'forbids the merge request from being created' do let(:error_message) { 'You must select source and target branch' } end end context 'when target branch is missing' do let(:target_branch) { nil } let(:commits) { Commit.decorate([commit_2], project) } before do stub_compare end context 'when source branch' do context 'is not the repository default branch' do it 'creates compare object with target branch as default branch' do expect(merge_request.compare).to be_present expect(merge_request.target_branch).to eq(project.default_branch) end it_behaves_like 'allows the merge request to be created' end context 'the repository default branch' do let(:source_branch) { 'master' } it_behaves_like 'forbids the merge request from being created' do let(:error_message) { 'You must select source and target branch' } end context 'when source project is different from the target project' do let(:target_project) { create(:project, :public, :repository) } let!(:project) { fork_project(target_project, user, namespace: user.namespace, repository: true) } let(:source_project) { project } it 'creates compare object with target branch as default branch', :sidekiq_might_not_need_inline do expect(merge_request.compare).to be_present expect(merge_request.target_branch).to eq(project.default_branch) end it_behaves_like 'allows the merge request to be created' end end end end context 'same source and target branch' do let(:source_branch) { 'master' } it_behaves_like 'forbids the merge request from being created' do let(:error_message) { 'You must select different branches' } end end context 'no commits in the diff' do let(:commits) { [] } before do stub_compare end it_behaves_like 'allows the merge request to be created' it 'adds a Draft prefix to the merge request title' do expect(merge_request.title).to eq('Draft: Feature branch') end end context 'one commit in the diff' do let(:commits) { Commit.decorate([commit_2], project) } let(:commit_description) { commit_2.safe_message.split(/\n+/, 2).last } before do stub_compare end it_behaves_like 'allows the merge request to be created' it_behaves_like 'with a Default.md template' it 'uses the title of the commit as the title of the merge request' do expect(merge_request.title).to eq(commit_2.safe_message.split("\n").first) end it 'uses the description of the commit as the description of the merge request' do expect(merge_request.description).to eq(commit_description) end context 'merge request already has a description set' do let(:description) { 'Merge request description' } it 'keeps the description from the initial params' do expect(merge_request.description).to eq(description) end end context 'commit has no description' do let(:commits) { Commit.decorate([commit_3], project) } it_behaves_like 'with a Default.md template' it 'uses the title of the commit as the title of the merge request' do expect(merge_request.title).to eq(commit_3.safe_message) end it 'sets the description to nil' do expect(merge_request.description).to be_nil end end context 'when the source branch matches an issue' do where(:factory, :source_branch, :closing_message) do :jira_integration | 'FOO-123-fix-issue' | 'Closes FOO-123' :jira_integration | 'fix-issue' | nil :custom_issue_tracker_integration | '123-fix-issue' | 'Closes #123' :custom_issue_tracker_integration | 'fix-issue' | nil nil | '123-fix-issue' | 'Closes #123' nil | 'fix-issue' | nil end with_them do before do if factory create(factory, project: project) project.reload else issue.update!(iid: 123) end end it 'uses the title of the commit as the title of the merge request' do expect(merge_request.title).to eq('Closes #1234 Second commit') end it 'appends the closing description' do expected_description = [commit_description, closing_message].compact.join("\n\n") expect(merge_request.description).to eq(expected_description) end context 'a Default.md template is defined' do let(:files) { { '.gitlab/merge_request_templates/Default.md' => 'Default template contents' } } let(:project) { create(:project, :custom_repo, files: files) } it 'appends the closing description to a Default.md template' do expected_description = ['Default template contents', closing_message].compact.join("\n\n") expect(merge_request.description).to eq(expected_description) end end end context 'when the source branch matches an internal issue' do let(:label) { create(:label, project: project) } let(:milestone) { create(:milestone, project: project) } let(:source_branch) { '123-fix-issue' } before do issue.update!(iid: 123, labels: [label], milestone: milestone) end it 'assigns the issue label and milestone' do expect(merge_request.milestone).to eq(milestone) expect(merge_request.labels).to match_array([label]) end context 'when milestone_id and label_ids are shared in the params' do let(:label2) { create(:label, project: project) } let(:milestone2) { create(:milestone, project: project) } let(:label_ids) { [label2.id] } let(:milestone_id) { milestone2.id } before do # Guests are not able to assign labels or milestones to an issue project.add_developer(user) end it 'assigns milestone_id and label_ids instead of issue labels and milestone' do expect(merge_request.milestone).to eq(milestone2) expect(merge_request.labels).to match_array([label2]) end end end context 'when a milestone is from another project' do let(:milestone) { create(:milestone, project: create(:project)) } let(:milestone_id) { milestone.id } it 'sets milestone to nil' do expect(merge_request.milestone).to be_nil end end end end context 'no multi-line commit messages in the diff' do let(:commits) { Commit.decorate([commit_1, commit_3], project) } before do stub_compare end it_behaves_like 'allows the merge request to be created' it_behaves_like 'with a Default.md template' it 'uses the title of the branch as the merge request title' do expect(merge_request.title).to eq('Feature branch') end it 'does not add a description' do expect(merge_request.description).to be_nil end context 'merge request already has a description set' do let(:description) { 'Merge request description' } it 'keeps the description from the initial params' do expect(merge_request.description).to eq(description) end context 'a Default.md template is defined' do let(:files) { { '.gitlab/merge_request_templates/Default.md' => 'Default template contents' } } let(:project) { create(:project, :custom_repo, files: files) } it 'keeps the description from the initial params' do expect(merge_request.description).to eq(description) end end end context 'when the source branch matches an issue' do where(:factory, :source_branch, :title, :closing_message) do :jira_integration | 'FOO-123-fix-issue' | 'Resolve FOO-123 "Fix issue"' | 'Closes FOO-123' :jira_integration | 'fix-issue' | 'Fix issue' | nil :custom_issue_tracker_integration | '123-fix-issue' | 'Resolve #123 "Fix issue"' | 'Closes #123' :custom_issue_tracker_integration | 'fix-issue' | 'Fix issue' | nil nil | '123-fix-issue' | 'Resolve "A bug"' | 'Closes #123' nil | 'fix-issue' | 'Fix issue' | nil nil | '124-fix-issue' | '124 fix issue' | nil end with_them do before do if factory create(factory, project: project) project.reload else issue.update!(iid: 123) end end it 'sets the correct title' do expect(merge_request.title).to eq(title) end it 'sets the closing description' do expect(merge_request.description).to eq(closing_message) end context 'a Default.md template is defined' do let(:files) { { '.gitlab/merge_request_templates/Default.md' => 'Default template contents' } } let(:project) { create(:project, :custom_repo, files: files) } it 'appends the closing description to a Default.md template' do expected_description = ['Default template contents', closing_message].compact.join("\n\n") expect(merge_request.description).to eq(expected_description) end end end end end context 'a multi-line commit message in the diff' do let(:commits) { Commit.decorate([commit_1, commit_2, commit_3], project) } before do stub_compare end it_behaves_like 'allows the merge request to be created' it_behaves_like 'with a Default.md template' it 'uses the first line of the first multi-line commit message as the title' do expect(merge_request.title).to eq('Closes #1234 Second commit') end it 'adds the remaining lines of the first multi-line commit message as the description' do expect(merge_request.description).to eq('Create the app') end context 'when the source branch matches an issue' do where(:factory, :source_branch, :title, :closing_message) do :jira_integration | 'FOO-123-fix-issue' | 'Resolve FOO-123 "Fix issue"' | 'Closes FOO-123' :jira_integration | 'fix-issue' | 'Fix issue' | nil :custom_issue_tracker_integration | '123-fix-issue' | 'Resolve #123 "Fix issue"' | 'Closes #123' :custom_issue_tracker_integration | 'fix-issue' | 'Fix issue' | nil nil | '123-fix-issue' | 'Resolve "A bug"' | 'Closes #123' nil | 'fix-issue' | 'Fix issue' | nil nil | '124-fix-issue' | '124 fix issue' | nil end with_them do before do if factory create(factory, project: project) project.reload else issue.update!(iid: 123) end end it 'sets the correct title' do expect(merge_request.title).to eq('Closes #1234 Second commit') end it 'sets the closing description' do expect(merge_request.description).to eq("Create the app#{closing_message ? "\n\n" + closing_message : ''}") end context 'a Default.md template is defined' do let(:files) { { '.gitlab/merge_request_templates/Default.md' => 'Default template contents' } } let(:project) { create(:project, :custom_repo, files: files) } it 'appends the closing description to a Default.md template' do expected_description = ['Default template contents', closing_message].compact.join("\n\n") expect(merge_request.description).to eq(expected_description) end end end end context 'when the issue is not accessible to user' do let(:source_branch) { "#{issue.iid}-fix-issue" } before do project.team.truncate end it 'uses the first line of the first multi-line commit message as the title' do expect(merge_request.title).to eq('Closes #1234 Second commit') end it 'adds the remaining lines of the first multi-line commit message as the description', :sidekiq_inline do expect(merge_request.description).to eq('Create the app') end end context 'when the issue is confidential' do let(:source_branch) { "#{issue.iid}-fix-issue" } let(:issue_confidential) { true } it 'uses the first line of the first multi-line commit message as the title' do expect(merge_request.title).to eq('Closes #1234 Second commit') end it 'adds the remaining lines of the first multi-line commit message as the description' do expect(merge_request.description).to eq('Create the app') end end end context 'source branch does not exist' do before do allow(project).to receive(:commit).with(source_branch).and_return(nil) allow(project).to receive(:commit).with(target_branch).and_return(commit_2) end it_behaves_like 'forbids the merge request from being created' do let(:error_message) { 'Source branch "feature-branch" does not exist' } end end context 'target branch does not exist' do before do allow(project).to receive(:commit).with(source_branch).and_return(commit_2) allow(project).to receive(:commit).with(target_branch).and_return(nil) end it_behaves_like 'forbids the merge request from being created' do let(:error_message) { 'Target branch "master" does not exist' } end end context 'both source and target branches do not exist' do before do allow(project).to receive(:commit).and_return(nil) end it_behaves_like 'forbids the merge request from being created' do let(:error_message) do ['Source branch "feature-branch" does not exist', 'Target branch "master" does not exist'] end end end context 'upstream project has disabled merge requests' do let(:upstream_project) { create(:project, :merge_requests_disabled) } let(:project) { create(:project, forked_from_project: upstream_project) } let(:commits) { Commit.decorate([commit_2], project) } it 'sets target project correctly' do expect(merge_request.target_project).to eq(project) end end context 'target_project is set and accessible by current_user' do let(:target_project) { create(:project, :public, :repository) } let(:commits) { Commit.decorate([commit_2], project) } it 'sets target project correctly' do expect(merge_request.target_project).to eq(target_project) end end context 'target_project is set but not accessible by current_user' do let(:target_project) { create(:project, :private, :repository) } let(:commits) { Commit.decorate([commit_2], project) } it 'sets target project correctly' do expect(merge_request.target_project).to eq(project) end end context 'target_project is set but repo is not accessible by current_user' do let(:target_project) do create(:project, :public, :repository, repository_access_level: ProjectFeature::PRIVATE) end it 'sets target project correctly' do expect(merge_request.target_project).to eq(project) end end context 'source_project is set and accessible by current_user' do let(:source_project) { create(:project, :public, :repository) } let(:commits) { Commit.decorate([commit_2], project) } before do # To create merge requests _from_ a project the user needs at least # developer access source_project.add_developer(user) end it 'sets source project correctly' do expect(merge_request.source_project).to eq(source_project) end end context 'source_project is set but not accessible by current_user' do let(:source_project) { create(:project, :private, :repository) } let(:commits) { Commit.decorate([commit_2], project) } it 'sets source project correctly' do expect(merge_request.source_project).to eq(project) end end context 'source_project is set but the user cannot create merge requests from the project' do let(:source_project) do create(:project, :public, :repository, merge_requests_access_level: ProjectFeature::PRIVATE) end it 'sets the source_project correctly' do expect(merge_request.source_project).to eq(project) end end context 'target_project is not in the fork network of source_project' do let(:target_project) { create(:project, :public, :repository) } it 'adds an error to the merge request' do expect(merge_request.errors[:validate_fork]).to contain_exactly('Source project is not a fork of the target project') end end context 'target_project is in the fork network of source project but no longer accessible' do let!(:project) { fork_project(target_project, user, namespace: user.namespace, repository: true) } let(:source_project) { project } let(:target_project) { create(:project, :public, :repository) } before do target_project.update!(visibility_level: Gitlab::VisibilityLevel::PRIVATE) end it 'sets the target_project correctly' do expect(merge_request.target_project).to eq(project) end end context 'when specifying target branch in the description' do let(:description) { "A merge request targeting another branch\n\n/target_branch with-codeowners" } it 'sets the attribute from the quick actions' do expect(merge_request.target_branch).to eq('with-codeowners') end end end context 'when assigning labels' do let(:label_ids) { [create(:label, project: project).id] } context 'for members with less than developer access' do it 'is not allowed' do expect(merge_request.label_ids).to be_empty end end context 'for users allowed to assign labels' do before do project.add_developer(user) end context 'for labels in the project' do it 'is allowed for developers' do expect(merge_request.label_ids).to contain_exactly(*label_ids) end end context 'for unrelated labels' do let(:project_label) { create(:label, project: project) } let(:label_ids) { [create(:label).id, project_label.id] } it 'only assigns related labels' do expect(merge_request.label_ids).to contain_exactly(project_label.id) end end end end describe '#assign_description_from_repository_template' do subject { service.send(:assign_description_from_repository_template) } it 'performs no action if the merge request description is not blank' do merge_request.description = 'foo' subject expect(merge_request.description).to eq 'foo' end context 'when a Default template is not found' do it 'does not modify the merge request description' do merge_request.description = nil subject expect(merge_request.description).to be_nil end end context 'when a Default template is found' do context 'when its contents cannot be retrieved' do let(:files) { { '.gitlab/merge_request_templates/OtherTemplate.md' => 'Other template contents' } } let(:project) { create(:project, :custom_repo, files: files) } it 'does not modify the merge request description' do allow(TemplateFinder).to receive(:all_template_names).and_return({ merge_requests: [ { name: 'Default', id: 'default', key: 'default', project_id: project.id } ] }) merge_request.description = nil subject expect(merge_request.description).to be_nil end end context 'when its contents can be retrieved' do let(:files) { { '.gitlab/merge_request_templates/Default.md' => 'Default template contents' } } let(:project) { create(:project, :custom_repo, files: files) } it 'modifies the merge request description' do merge_request.description = nil subject expect(merge_request.description).to eq 'Default template contents' end end end end describe '#replace_variables_in_description' do context 'when the merge request description is blank' do let(:description) { nil } it 'does not update the description' do expect(merge_request.description).to eq(nil) end end context 'when the merge request description contains template variables' do let(:description) { <<~MSG.rstrip } source_branch:%{source_branch} target_branch:%{target_branch} title:%{title} issues:%{issues} description:%{description} first_commit:%{first_commit} first_multiline_commit:%{first_multiline_commit} url:%{url} approved_by:%{approved_by} merged_by:%{merged_by} co_authored_by:%{co_authored_by} all_commits:%{all_commits} MSG context 'when there are multiple commits in the diff' do let(:commits) { Commit.decorate([commit_1, commit_2, commit_3], project) } before do stub_compare end it 'replaces the variables in the description' do expect(merge_request.description).to eq <<~MSG.rstrip source_branch:feature-branch target_branch:master title: issues: description: first_commit:Initial commit first_multiline_commit:Closes #1234 Second commit Create the app url: approved_by: merged_by: co_authored_by:Co-authored-by: Jo Example <[email protected]> Co-authored-by: Alice Example <[email protected]> Co-authored-by: Tom Example <[email protected]> all_commits:* This is a bad commit message! * Closes #1234 Second commit Create the app * Initial commit MSG end end context 'when there are no commits in the diff' do let(:commits) { [] } before do stub_compare end it 'replaces the variables in the description' do expect(merge_request.description).to eq <<~MSG.rstrip source_branch:feature-branch target_branch:master title: issues: description: first_commit: first_multiline_commit: url: approved_by: merged_by: co_authored_by: all_commits: MSG end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ResolveTodosService include BaseServiceUtility def initialize(merge_request, user) @merge_request = merge_request @user = user end def async_execute MergeRequests::ResolveTodosWorker.perform_async(merge_request.id, user.id) end def execute todo_service.resolve_todos_for_target(merge_request, user) end private attr_reader :merge_request, :user end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ResolveTodosService, feature_category: :code_review_workflow do let_it_be(:merge_request) { create(:merge_request) } let_it_be(:user) { create(:user) } let(:service) { described_class.new(merge_request, user) } describe '#async_execute' do def async_execute service.async_execute end it 'performs MergeRequests::ResolveTodosWorker asynchronously' do expect(MergeRequests::ResolveTodosWorker) .to receive(:perform_async) .with( merge_request.id, user.id ) async_execute end end describe '#execute' do it 'marks pending todo as done' do pending_todo = create(:todo, :pending, user: user, project: merge_request.project, target: merge_request) service.execute expect(pending_todo.reload).to be_done end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class CloseService < MergeRequests::BaseService include RemovesRefs def execute(merge_request, commit = nil) return merge_request unless can?(current_user, :update_merge_request, merge_request) # If we close MergeRequest we want to ignore validation # so we can close broken one (Ex. fork project removed) merge_request.allow_broken = true if merge_request.close expire_unapproved_key(merge_request) create_event(merge_request) merge_request_activity_counter.track_close_mr_action(user: current_user) create_note(merge_request) notification_service.async.close_mr(merge_request, current_user) todo_service.close_merge_request(merge_request, current_user) execute_hooks(merge_request, 'close') invalidate_cache_counts(merge_request, users: merge_request.assignees | merge_request.reviewers) merge_request.update_project_counter_caches cleanup_environments(merge_request) deactivate_pages_deployments(merge_request) abort_auto_merge(merge_request, 'merge request was closed') cleanup_refs(merge_request) trigger_merge_request_merge_status_updated(merge_request) end merge_request end private def create_event(merge_request) # Making sure MergeRequest::Metrics updates are in sync with # Event creation. Event.transaction do close_event = event_service.close_mr(merge_request, current_user) merge_request_metrics_service(merge_request).close(close_event) end end def expire_unapproved_key(merge_request) nil end def trigger_merge_request_merge_status_updated(merge_request) GraphqlTriggers.merge_request_merge_status_updated(merge_request) end end end MergeRequests::CloseService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::CloseService, feature_category: :code_review_workflow do let(:user) { create(:user) } let(:user2) { create(:user) } let(:guest) { create(:user) } let(:merge_request) { create(:merge_request, assignees: [user2], author: create(:user)) } let(:project) { merge_request.project } let!(:todo) { create(:todo, :assigned, user: user, project: project, target: merge_request, author: user2) } let(:service) { described_class.new(project: project, current_user: user) } before do project.add_maintainer(user) project.add_developer(user2) project.add_guest(guest) end def execute service.execute(merge_request) end describe '#execute' do it_behaves_like 'cache counters invalidator' it_behaves_like 'merge request reviewers cache counters invalidator' context 'valid params' do before do allow(service).to receive(:execute_hooks) perform_enqueued_jobs do @merge_request = execute end end it { expect(@merge_request).to be_valid } it { expect(@merge_request).to be_closed } it 'executes hooks with close action' do expect(service).to have_received(:execute_hooks) .with(@merge_request, 'close') end it 'sends email to user2 about assign of new merge_request', :sidekiq_inline do email = ActionMailer::Base.deliveries.last expect(email.to.first).to eq(user2.email) expect(email.subject).to include(merge_request.title) end it 'creates a resource event' do event = @merge_request.resource_state_events.last expect(event.state).to eq('closed') end it 'marks todos as done' do expect(todo.reload).to be_done end context 'when auto merge is enabled' do let(:merge_request) { create(:merge_request, :merge_when_pipeline_succeeds) } it 'cancels the auto merge' do expect(@merge_request).not_to be_auto_merge_enabled end end end it 'updates metrics' do metrics = merge_request.metrics metrics_service = double(MergeRequestMetricsService) allow(MergeRequestMetricsService) .to receive(:new) .with(metrics) .and_return(metrics_service) expect(metrics_service).to receive(:close) execute end it 'calls the merge request activity counter' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_close_mr_action) .with(user: user) execute end it 'refreshes the number of open merge requests for a valid MR', :use_clean_rails_memory_store_caching do expect do execute BatchLoader::Executor.clear_current end .to change { project.open_merge_requests_count }.from(1).to(0) end it 'clean up environments for the merge request' do expect_next_instance_of(::Environments::StopService) do |service| expect(service).to receive(:execute_for_merge_request_pipeline).with(merge_request) end execute end it 'schedules CleanupRefsService' do expect(MergeRequests::CleanupRefsService).to receive(:schedule).with(merge_request) execute end it 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do expect(GraphqlTriggers).to receive(:merge_request_merge_status_updated).with(merge_request) execute end context 'current user is not authorized to close merge request' do let(:user) { guest } before do perform_enqueued_jobs do @merge_request = execute end end it 'does not close the merge request' do expect(@merge_request).to be_open end it 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do expect(GraphqlTriggers).not_to receive(:merge_request_merge_status_updated) execute end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class AfterCreateService < MergeRequests::BaseService include Gitlab::Utils::StrongMemoize def execute(merge_request) merge_request.ensure_merge_request_diff logger.info(**log_payload(merge_request, 'Executing hooks')) execute_hooks(merge_request) logger.info(**log_payload(merge_request, 'Executed hooks')) prepare_for_mergeability(merge_request) prepare_merge_request(merge_request) mark_merge_request_as_prepared(merge_request) end private def prepare_for_mergeability(merge_request) logger.info(**log_payload(merge_request, 'Creating pipeline')) create_pipeline_for(merge_request, current_user) logger.info(**log_payload(merge_request, 'Pipeline created')) merge_request.update_head_pipeline check_mergeability(merge_request) end def prepare_merge_request(merge_request) event_service.open_mr(merge_request, current_user) merge_request_activity_counter.track_create_mr_action(user: current_user, merge_request: merge_request) merge_request_activity_counter.track_mr_including_ci_config(user: current_user, merge_request: merge_request) notification_service.new_merge_request(merge_request, current_user) merge_request.diffs(include_stats: false).write_cache merge_request.create_cross_references!(current_user) Onboarding::ProgressService.new(merge_request.target_project.namespace).execute(action: :merge_request_created) todo_service.new_merge_request(merge_request, current_user) merge_request.cache_merge_request_closes_issues!(current_user) Gitlab::UsageDataCounters::MergeRequestCounter.count(:create) link_lfs_objects(merge_request) end def link_lfs_objects(merge_request) LinkLfsObjectsService.new(project: merge_request.target_project).execute(merge_request) end def check_mergeability(merge_request) return unless merge_request.preparing? # Need to set to unchecked to be able to check for mergeability or else # it'll be a no-op. merge_request.mark_as_unchecked merge_request.check_mergeability(async: true) end def mark_merge_request_as_prepared(merge_request) merge_request.update!(prepared_at: Time.current) end def logger @logger ||= Gitlab::AppLogger end def log_payload(merge_request, message) Gitlab::ApplicationContext.current.merge( merge_request_id: merge_request.id, message: message ) end end end MergeRequests::AfterCreateService.prepend_mod_with('MergeRequests::AfterCreateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::AfterCreateService, feature_category: :code_review_workflow do let_it_be(:merge_request) { create(:merge_request) } let(:project) { merge_request.project } subject(:after_create_service) do described_class.new(project: merge_request.target_project, current_user: merge_request.author) end describe '#execute' do let(:event_service) { instance_double('EventCreateService', open_mr: true) } let(:notification_service) { instance_double('NotificationService', new_merge_request: true) } before do allow(after_create_service).to receive(:event_service).and_return(event_service) allow(after_create_service).to receive(:notification_service).and_return(notification_service) end subject(:execute_service) { after_create_service.execute(merge_request) } it 'creates a merge request open event' do expect(event_service) .to receive(:open_mr).with(merge_request, merge_request.author) execute_service end it 'calls the merge request activity counter' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_create_mr_action) .with(user: merge_request.author, merge_request: merge_request) expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_mr_including_ci_config) .with(user: merge_request.author, merge_request: merge_request) execute_service end it 'creates a new merge request notification' do expect(notification_service) .to receive(:new_merge_request).with(merge_request, merge_request.author) execute_service end it 'writes diffs to the cache' do expect(merge_request) .to receive_message_chain(:diffs, :write_cache) execute_service end it 'creates cross references' do expect(merge_request) .to receive(:create_cross_references!).with(merge_request.author) execute_service end it 'creates a pipeline and updates the HEAD pipeline' do expect(after_create_service) .to receive(:create_pipeline_for).with(merge_request, merge_request.author) expect(merge_request).to receive(:update_head_pipeline) execute_service end it 'executes hooks with default action' do expect(project).to receive(:execute_hooks) execute_service end it 'calls GroupMentionWorker' do expect(Integrations::GroupMentionWorker).to receive(:perform_async) execute_service end it_behaves_like 'records an onboarding progress action', :merge_request_created do let(:namespace) { merge_request.target_project.namespace } end context 'when merge request is in unchecked state' do before do merge_request.mark_as_unchecked! execute_service end it 'does not change its state' do expect(merge_request.reload).to be_unchecked end end context 'when merge request is in preparing state' do before do merge_request.mark_as_unchecked! unless merge_request.unchecked? merge_request.mark_as_preparing! end it 'checks for mergeability' do expect(merge_request).to receive(:check_mergeability).with(async: true) execute_service end context 'when preparing for mergeability fails' do before do # This is only one of the possible cases that can fail. This is to # simulate a failure that happens during the service call. allow(merge_request) .to receive(:update_head_pipeline) .and_raise(StandardError) end it 'does not mark the merge request as unchecked' do expect { execute_service }.to raise_error(StandardError) expect(merge_request.reload).to be_preparing end end context 'when preparing merge request fails' do before do # This is only one of the possible cases that can fail. This is to # simulate a failure that happens during the service call. allow(merge_request) .to receive_message_chain(:diffs, :write_cache) .and_raise(StandardError) end it 'still checks for mergeability' do expect(merge_request).to receive(:check_mergeability).with(async: true) expect { execute_service }.to raise_error(StandardError) end end end it 'updates the prepared_at' do # Need to reset the `prepared_at` since it can be already set in preceding tests. merge_request.update!(prepared_at: nil) freeze_time do expect { execute_service }.to change { merge_request.prepared_at } .from(nil) .to(Time.current) end end it 'increments the usage data counter of create event' do counter = Gitlab::UsageDataCounters::MergeRequestCounter expect { execute_service }.to change { counter.read(:create) }.by(1) end context 'todos' do it 'does not creates todos' do attributes = { project: merge_request.target_project, target_id: merge_request.id, target_type: merge_request.class.name } expect { execute_service }.not_to change { Todo.where(attributes).count } end context 'when merge request is assigned to someone' do let_it_be(:assignee) { create(:user) } let_it_be(:merge_request) { create(:merge_request, assignees: [assignee]) } it 'creates a todo for new assignee' do attributes = { project: merge_request.target_project, author: merge_request.author, user: assignee, target_id: merge_request.id, target_type: merge_request.class.name, action: Todo::ASSIGNED, state: :pending } expect { execute_service }.to change { Todo.where(attributes).count }.by(1) end end context 'when reviewer is assigned' do let_it_be(:reviewer) { create(:user) } let_it_be(:merge_request) { create(:merge_request, reviewers: [reviewer]) } it 'creates a todo for new reviewer' do attributes = { project: merge_request.target_project, author: merge_request.author, user: reviewer, target_id: merge_request.id, target_type: merge_request.class.name, action: Todo::REVIEW_REQUESTED, state: :pending } expect { execute_service }.to change { Todo.where(attributes).count }.by(1) end end end context 'when saving references to issues that the created merge request closes' do let_it_be(:first_issue) { create(:issue, project: merge_request.target_project) } let_it_be(:second_issue) { create(:issue, project: merge_request.target_project) } it 'creates a `MergeRequestsClosingIssues` record for each issue' do merge_request.description = "Closes #{first_issue.to_reference} and #{second_issue.to_reference}" merge_request.source_branch = "feature" merge_request.target_branch = merge_request.target_project.default_branch merge_request.save! execute_service issue_ids = MergeRequestsClosingIssues.where(merge_request: merge_request).pluck(:issue_id) expect(issue_ids).to match_array([first_issue.id, second_issue.id]) end end it 'tracks merge request creation in usage data' do expect(Gitlab::UsageDataCounters::MergeRequestCounter).to receive(:count).with(:create) execute_service end it 'calls MergeRequests::LinkLfsObjectsService#execute' do service = instance_spy(MergeRequests::LinkLfsObjectsService) allow(MergeRequests::LinkLfsObjectsService).to receive(:new).with(project: merge_request.target_project).and_return(service) execute_service expect(service).to have_received(:execute).with(merge_request) end describe 'logging' do it 'logs specific events' do ::Gitlab::ApplicationContext.push(caller_id: 'NewMergeRequestWorker') allow(Gitlab::AppLogger).to receive(:info).and_call_original [ 'Executing hooks', 'Executed hooks', 'Creating pipeline', 'Pipeline created' ].each do |message| expect(Gitlab::AppLogger).to receive(:info).with( hash_including( 'meta.caller_id' => 'NewMergeRequestWorker', message: message, merge_request_id: merge_request.id ) ).and_call_original end execute_service end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class CreatePipelineService < MergeRequests::BaseService def execute(merge_request) return cannot_create_pipeline_error unless can_create_pipeline_for?(merge_request) create_detached_merge_request_pipeline(merge_request) end def create_detached_merge_request_pipeline(merge_request) Ci::CreatePipelineService .new(pipeline_project(merge_request), current_user, ref: pipeline_ref_for_detached_merge_request_pipeline(merge_request), push_options: params[:push_options]) .execute(:merge_request_event, merge_request: merge_request) end def can_create_pipeline_for?(merge_request) ## # UpdateMergeRequestsWorker could be retried by an exception. # pipelines for merge request should not be recreated in such case. return false if !allow_duplicate && merge_request.find_actual_head_pipeline&.merge_request? return false if merge_request.has_no_commits? true end def allow_duplicate params[:allow_duplicate] end private def pipeline_project(merge_request) if can_create_pipeline_in_target_project?(merge_request) merge_request.target_project else merge_request.source_project end end def pipeline_ref_for_detached_merge_request_pipeline(merge_request) if can_create_pipeline_in_target_project?(merge_request) merge_request.ref_path else merge_request.source_branch end end def can_create_pipeline_in_target_project?(merge_request) merge_request.target_project.ci_allow_fork_pipelines_to_run_in_parent_project? && can?(current_user, :create_pipeline, merge_request.target_project) && can_update_source_branch_in_target_project?(merge_request) end def can_update_source_branch_in_target_project?(merge_request) ::Gitlab::UserAccess.new(current_user, container: merge_request.target_project) .can_update_branch?(merge_request.source_branch_ref) end def cannot_create_pipeline_error ServiceResponse.error(message: 'Cannot create a pipeline for this merge request.', payload: nil) end end end MergeRequests::CreatePipelineService.prepend_mod_with('MergeRequests::CreatePipelineService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::CreatePipelineService, :clean_gitlab_redis_cache, feature_category: :code_review_workflow do include ProjectForksHelper let_it_be(:project, refind: true) { create(:project, :repository) } let_it_be(:user) { create(:user) } let(:service) { described_class.new(project: project, current_user: actor, params: params) } let(:actor) { user } let(:params) { {} } before do project.add_developer(user) end describe '#execute' do subject(:response) { service.execute(merge_request) } before do stub_ci_pipeline_yaml_file(YAML.dump(config)) end let(:config) do { rspec: { script: 'echo', only: ['merge_requests'] } } end let(:merge_request) do create(:merge_request, source_branch: 'feature', source_project: source_project, target_branch: 'master', target_project: project) end let(:source_project) { project } it 'creates a detached merge request pipeline' do expect { response }.to change { Ci::Pipeline.count }.by(1) expect(response).to be_success expect(response.payload).to be_persisted expect(response.payload).to be_detached_merge_request_pipeline end it 'defaults to merge_request_event' do expect(response.payload.source).to eq('merge_request_event') end context 'when push options contain ci.skip' do let(:params) { { push_options: { ci: { skip: true } } } } it 'creates a skipped pipeline' do expect { response }.to change { Ci::Pipeline.count }.by(1) expect(response).to be_success expect(response.payload).to be_persisted expect(response.payload.builds).to be_empty expect(response.payload).to be_skipped end end context 'with fork merge request' do let_it_be(:forked_project) { fork_project(project, nil, repository: true, target_project: create(:project, :private, :repository)) } let(:source_project) { forked_project } context 'when actor has permission to create pipelines in target project' do let(:actor) { user } it 'creates a pipeline in the target project' do expect(response.payload.project).to eq(project) end context 'when the feature is disabled in CI/CD settings' do before do project.update!(ci_allow_fork_pipelines_to_run_in_parent_project: false) end it 'creates a pipeline in the source project' do expect(response.payload.project).to eq(source_project) end end context 'when source branch is protected' do context 'when actor does not have permission to update the protected branch in target project' do let!(:protected_branch) { create(:protected_branch, name: '*', project: project) } it 'creates a pipeline in the source project' do expect(response.payload.project).to eq(source_project) end end context 'when actor has permission to update the protected branch in target project' do let!(:protected_branch) { create(:protected_branch, :developers_can_merge, name: '*', project: project) } it 'creates a pipeline in the target project' do expect(response.payload.project).to eq(project) end end end end context 'when actor has permission to create pipelines in forked project' do let(:actor) { fork_user } let(:fork_user) { create(:user) } before do source_project.add_developer(fork_user) end it 'creates a pipeline in the source project' do expect(response.payload.project).to eq(source_project) end end context 'when actor does not have permission to create pipelines' do let(:actor) { create(:user) } it 'responds with error' do expect(response).to be_error expect(response.message).to include('Insufficient permissions to create a new pipeline') end end end context 'when service is called multiple times' do it 'creates a pipeline once' do expect do service.execute(merge_request) service.execute(merge_request) end.to change { Ci::Pipeline.count }.by(1) end context 'when allow_duplicate option is true' do let(:params) { { allow_duplicate: true } } it 'creates pipelines multiple times' do expect do service.execute(merge_request) service.execute(merge_request) end.to change { Ci::Pipeline.count }.by(2) end end end context 'when .gitlab-ci.yml does not use workflow:rules' do context 'without only: [merge_requests] keyword' do let(:config) do { rspec: { script: 'echo' } } end it 'does not create a pipeline' do expect { response }.not_to change { Ci::Pipeline.count } end end context 'with rules that specify creation on a tag' do let(:config) do { rspec: { script: 'echo', rules: [{ if: '$CI_COMMIT_TAG' }] } } end it 'does not create a pipeline' do expect { response }.not_to change { Ci::Pipeline.count } end end end context 'when workflow:rules are specified' do context 'when rules request creation on merge request' do let(:config) do { workflow: { rules: [{ if: '$CI_MERGE_REQUEST_ID' }] }, rspec: { script: 'echo' } } end it 'creates a detached merge request pipeline', :aggregate_failures do expect { response }.to change { Ci::Pipeline.count }.by(1) expect(response).to be_success expect(response.payload).to be_persisted expect(response.payload).to be_detached_merge_request_pipeline end end context 'with rules do specify creation on a tag' do let(:config) do { workflow: { rules: [{ if: '$CI_COMMIT_TAG' }] }, rspec: { script: 'echo' } } end it 'does not create a pipeline', :aggregate_failures do expect { response }.not_to change { Ci::Pipeline.count } expect(response).to be_error end end end context 'when merge request has no commits' do before do allow(merge_request).to receive(:has_no_commits?).and_return(true) end it 'does not create a pipeline', :aggregate_failures do expect { response }.not_to change { Ci::Pipeline.count } expect(response).to be_error expect(response.message).to eq('Cannot create a pipeline for this merge request.') expect(response.payload).to be_nil end end context 'when merge request pipeline creates a dynamic environment' do let(:config) do { review_app: { script: 'echo', only: ['merge_requests'], environment: { name: "review/$CI_COMMIT_REF_NAME" } } } end it 'associates merge request with the environment' do expect { response }.to change { Ci::Pipeline.count }.by(1) environment = Environment.find_by_name('review/feature') expect(response).to be_success expect(environment).to be_present expect(environment.merge_request).to eq(merge_request) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class MergeOrchestrationService < ::BaseService def execute(merge_request) return unless can_merge?(merge_request) merge_request.update(merge_error: nil) if can_merge_automatically?(merge_request) auto_merge_service.execute(merge_request) else merge_request.merge_async(current_user.id, params) end end def can_merge?(merge_request) can_merge_automatically?(merge_request) || can_merge_immediately?(merge_request) end def preferred_auto_merge_strategy(merge_request) auto_merge_service.preferred_strategy(merge_request) end private def can_merge_immediately?(merge_request) merge_request.can_be_merged_by?(current_user) && merge_request.mergeable? end def can_merge_automatically?(merge_request) auto_merge_service.available_strategies(merge_request).any? end def auto_merge_service @auto_merge_service ||= AutoMergeService.new(project, current_user, params) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::MergeOrchestrationService, feature_category: :code_review_workflow do let_it_be(:maintainer) { create(:user) } let(:merge_params) { { sha: merge_request.diff_head_sha } } let(:user) { maintainer } let(:service) { described_class.new(project, user, merge_params) } let!(:merge_request) do create( :merge_request, source_project: project, source_branch: 'feature', target_project: project, target_branch: 'master' ) end shared_context 'fresh repository' do let_it_be(:project) { create(:project, :repository) } before_all do project.add_maintainer(maintainer) end end describe '#execute' do subject { service.execute(merge_request) } include_context 'fresh repository' context 'when merge request is mergeable' do context 'when merge request can be merged automatically' do before do create(:ci_pipeline, :detached_merge_request_pipeline, project: project, merge_request: merge_request) merge_request.update_head_pipeline stub_licensed_features(merge_request_approvers: true) if Gitlab.ee? end it 'schedules auto merge' do expect_next_instance_of(AutoMergeService, project, user, merge_params) do |service| expect(service).to receive(:execute).with(merge_request).and_call_original end subject expect(merge_request).to be_auto_merge_enabled if Gitlab.ee? expect(merge_request.auto_merge_strategy).to( eq(AutoMergeService::STRATEGY_MERGE_WHEN_CHECKS_PASS) ) else expect(merge_request.auto_merge_strategy).to( eq(AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS) ) end expect(merge_request).not_to be_merged end end context 'when merge request cannot be merged automatically' do it 'merges immediately', :sidekiq_inline do expect(merge_request) .to receive(:merge_async).with(user.id, merge_params) .and_call_original subject merge_request.reset expect(merge_request).to be_merged expect(merge_request).not_to be_auto_merge_enabled end end end context 'when merge request is not mergeable' do before do allow(merge_request).to receive(:mergeable?) { false } end it 'does nothing' do subject expect(merge_request).not_to be_auto_merge_enabled expect(merge_request).not_to be_merged end end end describe '#can_merge?' do subject { service.can_merge?(merge_request) } include_context 'fresh repository' context 'when merge request is mergeable' do it { is_expected.to eq(true) } end context 'when merge request is not mergeable' do before do allow(merge_request).to receive(:mergeable?) { false } end it { is_expected.to eq(false) } end end describe '#preferred_auto_merge_strategy' do subject { service.preferred_auto_merge_strategy(merge_request) } include_context 'fresh repository' context 'when merge request can be merged automatically' do before do create(:ci_pipeline, :detached_merge_request_pipeline, project: project, merge_request: merge_request) merge_request.update_head_pipeline stub_licensed_features(merge_request_approvers: true) if Gitlab.ee? end it 'fetches preferred auto merge strategy', if: Gitlab.ee? do is_expected.to eq(AutoMergeService::STRATEGY_MERGE_WHEN_CHECKS_PASS) end it 'fetches preferred auto merge strategy', unless: Gitlab.ee? do is_expected.to eq(AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS) end end context 'when merge request cannot be merged automatically' do it { is_expected.to be_nil } end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class UpdateService < MergeRequests::BaseService extend ::Gitlab::Utils::Override def initialize(project:, current_user: nil, params: {}) super @target_branch_was_deleted = @params.delete(:target_branch_was_deleted) end def execute(merge_request) if Gitlab::Utils.to_boolean(params[:draft]) merge_request.title = merge_request.draft_title end update_merge_request_with_specialized_service(merge_request) || general_fallback(merge_request) end def handle_changes(merge_request, options) super old_associations = options.fetch(:old_associations, {}) old_labels = old_associations.fetch(:labels, []) old_mentioned_users = old_associations.fetch(:mentioned_users, []) old_assignees = old_associations.fetch(:assignees, []) old_reviewers = old_associations.fetch(:reviewers, []) old_timelogs = old_associations.fetch(:timelogs, []) changed_fields = merge_request.previous_changes.keys resolve_todos(merge_request, old_labels, old_assignees, old_reviewers) if merge_request.previous_changes.include?('title') || merge_request.previous_changes.include?('description') todo_service.update_merge_request(merge_request, current_user, old_mentioned_users) end handle_target_branch_change(merge_request) handle_draft_status_change(merge_request, changed_fields) track_title_and_desc_edits(changed_fields) track_discussion_lock_toggle(merge_request, changed_fields) track_time_estimate_and_spend_edits(merge_request, old_timelogs, changed_fields) track_labels_change(merge_request, old_labels) notify_if_labels_added(merge_request, old_labels) notify_if_mentions_added(merge_request, old_mentioned_users) # Since #mark_as_unchecked triggers an update action through the MR's # state machine, we want to push this as far down in the process so we # avoid resetting #ActiveModel::Dirty # if merge_request.previous_changes.include?('target_branch') || merge_request.previous_changes.include?('source_branch') merge_request.mark_as_unchecked unless merge_request.unchecked? end end def handle_task_changes(merge_request) todo_service.resolve_todos_for_target(merge_request, current_user) todo_service.update_merge_request(merge_request, current_user) end def reopen_service MergeRequests::ReopenService end def close_service MergeRequests::CloseService end def after_update(issuable, old_associations) super issuable.cache_merge_request_closes_issues!(current_user) end private attr_reader :target_branch_was_deleted def general_fallback(merge_request) # We don't allow change of source/target projects and source branch # after merge request was created params.delete(:source_project_id) params.delete(:target_project_id) params.delete(:source_branch) if merge_request.closed_or_merged_without_fork? params.delete(:target_branch) params.delete(:force_remove_source_branch) end update_task_event(merge_request) || update(merge_request) end def track_title_and_desc_edits(changed_fields) tracked_fields = %w[title description] return unless changed_fields.any? { |field| tracked_fields.include?(field) } tracked_fields.each do |action| next unless changed_fields.include?(action) merge_request_activity_counter .public_send("track_#{action}_edit_action".to_sym, user: current_user) # rubocop:disable GitlabSecurity/PublicSend end end def track_discussion_lock_toggle(merge_request, changed_fields) return unless changed_fields.include?('discussion_locked') if merge_request.discussion_locked merge_request_activity_counter.track_discussion_locked_action(user: current_user) else merge_request_activity_counter.track_discussion_unlocked_action(user: current_user) end end def track_time_estimate_and_spend_edits(merge_request, old_timelogs, changed_fields) merge_request_activity_counter.track_time_estimate_changed_action(user: current_user) if changed_fields.include?('time_estimate') merge_request_activity_counter.track_time_spent_changed_action(user: current_user) if old_timelogs != merge_request.timelogs end def track_labels_change(merge_request, old_labels) return if Set.new(merge_request.labels) == Set.new(old_labels) merge_request_activity_counter.track_labels_changed_action(user: current_user) end def notify_if_labels_added(merge_request, old_labels) added_labels = merge_request.labels - old_labels return unless added_labels.present? notification_service.async.relabeled_merge_request( merge_request, added_labels, current_user ) end def notify_if_mentions_added(merge_request, old_mentioned_users) added_mentions = merge_request.mentioned_users(current_user) - old_mentioned_users return unless added_mentions.present? notification_service.async.new_mentions_in_merge_request( merge_request, added_mentions, current_user ) end def resolve_todos(merge_request, old_labels, old_assignees, old_reviewers) return unless has_changes?(merge_request, old_labels: old_labels, old_assignees: old_assignees, old_reviewers: old_reviewers) resolve_todos_for(merge_request) end def handle_target_branch_change(merge_request) return unless merge_request.previous_changes.include?('target_branch') create_branch_change_note( merge_request, 'target', target_branch_was_deleted ? 'delete' : 'update', merge_request.previous_changes['target_branch'].first, merge_request.target_branch ) delete_approvals_on_target_branch_change(merge_request) refresh_pipelines_on_merge_requests(merge_request, allow_duplicate: true) abort_auto_merge(merge_request, 'target branch was changed') end def handle_draft_status_change(merge_request, changed_fields) return unless changed_fields.include?("title") old_title, new_title = merge_request.previous_changes["title"] old_title_draft = MergeRequest.draft?(old_title) new_title_draft = MergeRequest.draft?(new_title) if old_title_draft || new_title_draft # notify the draft status changed. Added/removed message is handled in the # email template itself, see `change_in_merge_request_draft_status_email` template. notify_draft_status_changed(merge_request) trigger_merge_request_status_updated(merge_request) publish_draft_change_event(merge_request) if Feature.enabled?(:additional_merge_when_checks_ready, project) end if !old_title_draft && new_title_draft # Marked as Draft merge_request_activity_counter.track_marked_as_draft_action(user: current_user) elsif old_title_draft && !new_title_draft # Unmarked as Draft merge_request_activity_counter.track_unmarked_as_draft_action(user: current_user) end end def publish_draft_change_event(merge_request) Gitlab::EventStore.publish( MergeRequests::DraftStateChangeEvent.new( data: { current_user_id: current_user.id, merge_request_id: merge_request.id } ) ) end def notify_draft_status_changed(merge_request) notification_service.async.change_in_merge_request_draft_status( merge_request, current_user ) end def create_branch_change_note(issuable, branch_type, event_type, old_branch, new_branch) SystemNoteService.change_branch( issuable, issuable.project, current_user, branch_type, event_type, old_branch, new_branch) end override :before_update def before_update(merge_request, skip_spam_check: false) merge_request.check_for_spam(user: current_user, action: :update) unless skip_spam_check end override :handle_quick_actions def handle_quick_actions(merge_request) super # Ensure this parameter does not get used as an attribute rebase = params.delete(:rebase) if rebase rebase_from_quick_action(merge_request) # Ignore "/merge" if "/rebase" is used to avoid an unexpected race params.delete(:merge) end merge_from_quick_action(merge_request) if params[:merge] end def rebase_from_quick_action(merge_request) merge_request.rebase_async(current_user.id) end def merge_from_quick_action(merge_request) last_diff_sha = params.delete(:merge) ::MergeRequests::MergeOrchestrationService .new(project, current_user, { sha: last_diff_sha }) .execute(merge_request) end override :quick_action_options def quick_action_options { merge_request_diff_head_sha: params.delete(:merge_request_diff_head_sha) } end def update_merge_request_with_specialized_service(merge_request) return unless params.delete(:use_specialized_service) # If we're attempting to modify only a single attribute, look up whether # we have a specialized, targeted service we should use instead. We may # in the future extend this to include specialized services that operate # on multiple attributes, but for now limit to only single attribute # updates. # return unless params.one? attempt_specialized_update_services(merge_request, params.each_key.first.to_sym) end def attempt_specialized_update_services(merge_request, attribute) case attribute when :assignee_ids, :assignee_id assignees_service.execute(merge_request) when :spend_time add_time_spent_service.execute(merge_request) end end def assignees_service @assignees_service ||= ::MergeRequests::UpdateAssigneesService .new(project: project, current_user: current_user, params: params) end def add_time_spent_service @add_time_spent_service ||= ::MergeRequests::AddSpentTimeService.new(project: project, current_user: current_user, params: params) end def new_user_ids(merge_request, user_ids, attribute) # prime the cache - prevent N+1 lookup during authorization loop. return [] if user_ids.empty? merge_request.project.team.max_member_access_for_user_ids(user_ids) User.id_in(user_ids).map do |user| if user.can?(:read_merge_request, merge_request) user.id else merge_request.errors.add( attribute, "Cannot assign #{user.to_reference} to #{merge_request.to_reference}" ) nil end end.compact end def resolve_todos_for(merge_request) service_user = current_user merge_request.run_after_commit_or_now do ::MergeRequests::ResolveTodosService.new(merge_request, service_user).async_execute end end def filter_sentinel_values(param) param.reject { _1 == 0 } end def trigger_merge_request_status_updated(merge_request) GraphqlTriggers.merge_request_merge_status_updated(merge_request) end def delete_approvals_on_target_branch_change(_merge_request) # Overridden in EE. No-op since we only want to delete approvals in EE. end end end MergeRequests::UpdateService.prepend_mod_with('MergeRequests::UpdateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::UpdateService, :mailer, feature_category: :code_review_workflow do include ProjectForksHelper let(:group) { create(:group, :public) } let(:project) { create(:project, :private, :repository, group: group) } let(:user) { create(:user) } let(:user2) { create(:user) } let(:user3) { create(:user) } let(:label) { create(:label, title: 'a', project: project) } let(:label2) { create(:label) } let(:milestone) { create(:milestone, project: project) } let(:merge_request) do create( :merge_request, :simple, title: 'Old title', description: "FYI #{user2.to_reference}", assignee_ids: [user3.id], source_project: project, author: create(:user) ) end before do project.add_maintainer(user) project.add_developer(user2) project.add_developer(user3) end describe 'execute' do def find_note(starting_with) @merge_request.notes.find do |note| note && note.note.start_with?(starting_with) end end def find_notes(action) @merge_request .notes .joins(:system_note_metadata) .where(system_note_metadata: { action: action }) end def update_merge_request(opts) @merge_request = MergeRequests::UpdateService.new(project: project, current_user: user, params: opts).execute(merge_request) @merge_request.reload end it_behaves_like 'issuable update service updating last_edited_at values' do let(:issuable) { merge_request } subject(:update_issuable) { update_merge_request(update_params) } end context 'valid params' do let(:locked) { true } let(:opts) do { title: 'New title', description: 'Also please fix', assignee_ids: [user.id], reviewer_ids: [], state_event: 'close', label_ids: [label.id], target_branch: 'target', force_remove_source_branch: '1', discussion_locked: locked } end let(:service) { described_class.new(project: project, current_user: current_user, params: opts) } let(:current_user) { user } before do allow(service).to receive(:execute_hooks) perform_enqueued_jobs do @merge_request = service.execute(merge_request) @merge_request.reload end end it 'matches base expectations' do expect(@merge_request).to be_valid expect(@merge_request.title).to eq('New title') expect(@merge_request.assignees).to match_array([user]) expect(@merge_request.reviewers).to match_array([]) expect(@merge_request).to be_closed expect(@merge_request.labels.count).to eq(1) expect(@merge_request.labels.first.title).to eq(label.name) expect(@merge_request.target_branch).to eq('target') expect(@merge_request.merge_params['force_remove_source_branch']).to eq('1') expect(@merge_request.discussion_locked).to be_truthy end context 'usage counters' do let(:merge_request2) { create(:merge_request) } let(:draft_merge_request) { create(:merge_request, :draft_merge_request) } it 'update as expected' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_title_edit_action).once.with(user: user) expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_description_edit_action).once.with(user: user) described_class.new(project: project, current_user: user, params: opts).execute(merge_request2) end it 'tracks Draft marking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_marked_as_draft_action).once.with(user: user) opts[:title] = "Draft: #{opts[:title]}" described_class.new(project: project, current_user: user, params: opts).execute(merge_request2) end it 'tracks Draft un-marking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_unmarked_as_draft_action).once.with(user: user) opts[:title] = "Non-draft/wip title string" described_class.new(project: project, current_user: user, params: opts).execute(draft_merge_request) end context 'when MR is locked' do context 'when locked again' do it 'does not track discussion locking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_discussion_locked_action) opts[:discussion_locked] = true described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end end context 'when unlocked' do it 'tracks dicussion unlocking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_discussion_unlocked_action).once.with(user: user) opts[:discussion_locked] = false described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end end end context 'when MR is unlocked' do let(:locked) { false } context 'when unlocked again' do it 'does not track discussion unlocking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_discussion_unlocked_action) opts[:discussion_locked] = false described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end end context 'when locked' do it 'tracks dicussion locking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_discussion_locked_action).once.with(user: user) opts[:discussion_locked] = true described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end end end it 'tracks time estimate and spend time changes' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_time_estimate_changed_action).once.with(user: user) expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_time_spent_changed_action).once.with(user: user) opts[:time_estimate] = 86400 opts[:spend_time] = { duration: 3600, user_id: user.id, spent_at: Date.parse('2021-02-24') } described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end it 'tracks milestone change' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_milestone_changed_action).once.with(user: user) opts[:milestone_id] = milestone.id described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end it 'track labels change' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_labels_changed_action).once.with(user: user) opts[:label_ids] = [label2.id] described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end context 'reviewers' do context 'when reviewers changed' do it 'tracks reviewers changed event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_reviewers_changed_action).once.with(user: user) opts[:reviewers] = [user2] described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end end context 'when reviewers did not change' do it 'does not track reviewers changed event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_reviewers_changed_action) opts[:reviewers] = merge_request.reviewers described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end end end end context 'updating milestone' do context 'with milestone_id param' do let(:opts) { { milestone_id: milestone.id } } it 'sets milestone' do expect(@merge_request.milestone).to eq milestone end end context 'milestone counters cache reset' do let(:milestone_old) { create(:milestone, project: project) } let(:opts) { { milestone_id: milestone_old.id } } it 'deletes milestone counters' do expect_next_instance_of(Milestones::MergeRequestsCountService, milestone_old) do |service| expect(service).to receive(:delete_cache).and_call_original end expect_next_instance_of(Milestones::MergeRequestsCountService, milestone) do |service| expect(service).to receive(:delete_cache).and_call_original end update_merge_request(milestone_id: milestone.id) end it 'deletes milestone counters when the milestone is removed' do expect_next_instance_of(Milestones::MergeRequestsCountService, milestone_old) do |service| expect(service).to receive(:delete_cache).and_call_original end update_merge_request(milestone_id: nil) end it 'deletes milestone counters when the milestone was not set' do update_merge_request(milestone_id: nil) expect_next_instance_of(Milestones::MergeRequestsCountService, milestone) do |service| expect(service).to receive(:delete_cache).and_call_original end update_merge_request(milestone_id: milestone.id) end end end it 'executes hooks with update action' do expect(service).to have_received(:execute_hooks) .with( @merge_request, 'update', old_associations: { labels: [], mentioned_users: [user2], assignees: [user3], reviewers: [], milestone: nil, total_time_spent: 0, time_change: 0, description: "FYI #{user2.to_reference}" } ) end context 'with reviewers' do let(:opts) { { reviewer_ids: [user2.id] } } it 'creates system note about merge_request review request' do note = find_note('requested review from') expect(note).not_to be_nil expect(note.note).to include "requested review from #{user2.to_reference}" end it 'updates the tracking' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_users_review_requested) .with(users: [user]) update_merge_request(reviewer_ids: [user.id]) end end it 'creates a resource label event' do event = merge_request.resource_label_events.last expect(event).not_to be_nil expect(event.label_id).to eq label.id expect(event.user_id).to eq user.id end it 'creates system note about title change' do note = find_note('changed title') expect(note).not_to be_nil expect(note.note).to eq 'changed title from **{-Old-} title** to **{+New+} title**' end it 'creates system note about description change' do note = find_note('changed the description') expect(note).not_to be_nil expect(note.note).to eq('changed the description') end it 'creates system note about branch change' do note = find_note('changed target') expect(note).not_to be_nil expect(note.note).to eq 'changed target branch from `master` to `target`' end it 'creates system note about discussion lock' do note = find_note('locked the discussion in this merge request') expect(note).not_to be_nil expect(note.note).to eq 'locked the discussion in this merge request' end context 'when current user cannot admin issues in the project' do let(:guest) { create(:user) } let(:current_user) { guest } before do project.add_guest(guest) end it 'filters out params that cannot be set without the :admin_merge_request permission' do expect(@merge_request).to be_valid expect(@merge_request.title).to eq('New title') expect(@merge_request.assignees).to match_array([user3]) expect(@merge_request).to be_opened expect(@merge_request.labels.count).to eq(0) expect(@merge_request.target_branch).to eq('target') expect(@merge_request.discussion_locked).to be_falsey expect(@merge_request.milestone).to be_nil end context 'updating milestone' do RSpec.shared_examples 'does not update milestone' do it 'sets milestone' do expect(@merge_request.milestone).to be_nil end end context 'when milestone_id param' do let(:opts) { { milestone_id: milestone.id } } it_behaves_like 'does not update milestone' end context 'when milestone param' do let(:opts) { { milestone: milestone } } it_behaves_like 'does not update milestone' end end end context 'when not including source branch removal options' do before do opts.delete(:force_remove_source_branch) end it 'maintains the original options' do update_merge_request(opts) expect(@merge_request.merge_params["force_remove_source_branch"]).to eq("1") end end it_behaves_like 'reviewer_ids filter' do let(:opts) { {} } let(:execute) { update_merge_request(opts) } end context 'with an existing reviewer' do let(:merge_request) do create(:merge_request, :simple, source_project: project, reviewer_ids: [user2.id]) end let(:opts) { { reviewer_ids: [IssuableFinder::Params::NONE] } } it 'removes reviewers' do expect(update_merge_request(opts).reviewers).to eq [] end end describe 'checking for spam' do it 'checks for spam' do expect(merge_request).to receive(:check_for_spam).with(user: user, action: :update) update_merge_request(opts) end it 'marks the merge request invalid' do merge_request.spam! update_merge_request(title: 'New title') expect(merge_request).to be_invalid end end end context 'after_save callback to store_mentions' do let(:merge_request) { create(:merge_request, title: 'Old title', description: "simple description", source_branch: 'test', source_project: project, author: user) } let(:labels) { create_pair(:label, project: project) } let(:milestone) { create(:milestone, project: project) } let(:req_opts) { { source_branch: 'feature', target_branch: 'master' } } subject { described_class.new(project: project, current_user: user, params: opts).execute(merge_request) } context 'when mentionable attributes change' do let(:opts) { { description: "Description with #{user.to_reference}" }.merge(req_opts) } it 'saves mentions' do expect(merge_request).to receive(:store_mentions!).and_call_original expect { subject }.to change { MergeRequestUserMention.count }.by(1) expect(merge_request.referenced_users).to match_array([user]) end end context 'when mentionable attributes do not change' do let(:opts) { { label_ids: [label.id, label2.id], milestone_id: milestone.id }.merge(req_opts) } it 'does not call store_mentions' do expect(merge_request).not_to receive(:store_mentions!).and_call_original expect { subject }.not_to change { MergeRequestUserMention.count } expect(merge_request.referenced_users).to be_empty end end context 'when save fails' do let(:opts) { { title: '', label_ids: labels.map(&:id), milestone_id: milestone.id } } it 'does not call store_mentions' do expect(merge_request).not_to receive(:store_mentions!).and_call_original expect { subject }.not_to change { MergeRequestUserMention.count } expect(merge_request.referenced_users).to be_empty expect(merge_request.valid?).to be false end end end shared_examples_for "creates a new pipeline" do it "creates a new pipeline" do expect(MergeRequests::CreatePipelineWorker) .to receive(:perform_async) .with(project.id, user.id, merge_request.id, { "allow_duplicate" => true }) update_merge_request(target_branch: new_target_branch) end end shared_examples_for 'correct merge behavior' do let(:opts) do { merge: merge_request.diff_head_sha } end let(:service) { described_class.new(project: project, current_user: user, params: opts) } context 'without pipeline' do before do merge_request.merge_error = 'Error' service.execute(merge_request) @merge_request = MergeRequest.find(merge_request.id) end it 'merges the MR', :sidekiq_inline do expect(@merge_request).to be_valid expect(@merge_request.state).to eq('merged') expect(@merge_request.merge_error).to be_nil end end context 'with finished pipeline' do before do create(:ci_pipeline, project: project, ref: merge_request.source_branch, sha: merge_request.diff_head_sha, status: :success) @merge_request = service.execute(merge_request) @merge_request = MergeRequest.find(merge_request.id) end it 'merges the MR', :sidekiq_inline do expect(@merge_request).to be_valid expect(@merge_request.state).to eq('merged') end end context 'with active pipeline' do before do service_mock = double create( :ci_pipeline, project: project, ref: merge_request.source_branch, sha: merge_request.diff_head_sha, head_pipeline_of: merge_request ) strategies_count = Gitlab.ee? ? :twice : :once expect(AutoMerge::MergeWhenPipelineSucceedsService).to receive(:new).exactly(strategies_count).with(project, user, { sha: merge_request.diff_head_sha }) .and_return(service_mock) allow(service_mock).to receive(:available_for?) { true } expect(service_mock).to receive(:execute).with(merge_request) end it { service.execute(merge_request) } end context 'with a non-authorised user' do let(:visitor) { create(:user) } let(:service) { described_class.new(project: project, current_user: visitor, params: opts) } before do merge_request.update_attribute(:merge_error, 'Error') perform_enqueued_jobs do @merge_request = service.execute(merge_request) @merge_request = MergeRequest.find(merge_request.id) end end it 'does not merge the MR' do expect(@merge_request.state).to eq('opened') expect(@merge_request.merge_error).not_to be_nil end end context 'MR can not be merged when note sha != MR sha' do let(:opts) do { merge: 'other_commit' } end before do perform_enqueued_jobs do @merge_request = service.execute(merge_request) @merge_request = MergeRequest.find(merge_request.id) end end it { expect(@merge_request.state).to eq('opened') } end end describe 'merge' do it_behaves_like 'correct merge behavior' end context 'todos' do let!(:pending_todo) { create(:todo, :assigned, user: user, project: project, target: merge_request, author: user2) } context 'when the title change' do it 'calls MergeRequest::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request({ title: 'New title' }) end it 'does not create any new todos' do update_merge_request({ title: 'New title' }) expect(Todo.count).to eq(1) end end context 'when the description change' do it 'calls MergeRequest::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request({ description: "Also please fix #{user2.to_reference} #{user3.to_reference}" }) end it 'creates only 1 new todo' do update_merge_request({ description: "Also please fix #{user2.to_reference} #{user3.to_reference}" }) expect(Todo.count).to eq(2) end it 'triggers GraphQL description updated subscription' do expect(GraphqlTriggers).to receive(:issuable_description_updated).with(merge_request).and_call_original update_merge_request(description: 'updated description') end end context 'when decription is not changed' do it 'does not trigger GraphQL description updated subscription' do expect(GraphqlTriggers).not_to receive(:issuable_description_updated) update_merge_request(title: 'updated title') end end context 'when is reassigned' do it 'calls MergeRequest::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request({ assignee_ids: [user2.id] }) end end context 'when reviewers gets changed' do it 'calls MergeRequest::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request({ reviewer_ids: [user2.id] }) end it 'creates a pending todo for new review request' do update_merge_request({ reviewer_ids: [user2.id] }) attributes = { project: project, author: user, user: user2, target_id: merge_request.id, target_type: merge_request.class.name, action: Todo::REVIEW_REQUESTED, state: :pending } expect(Todo.where(attributes).count).to eq 1 end it 'sends email reviewer change notifications to old and new reviewers', :sidekiq_inline do merge_request.reviewers = [user2] perform_enqueued_jobs do update_merge_request({ reviewer_ids: [user3.id] }) end should_email(user2) should_email(user3) end it 'updates open merge request counter for reviewers', :use_clean_rails_memory_store_caching do merge_request.reviewers = [user3] # Cache them to ensure the cache gets invalidated on update expect(user2.review_requested_open_merge_requests_count).to eq(0) expect(user3.review_requested_open_merge_requests_count).to eq(1) update_merge_request(reviewer_ids: [user2.id]) expect(user2.review_requested_open_merge_requests_count).to eq(1) expect(user3.review_requested_open_merge_requests_count).to eq(0) end it_behaves_like 'triggers GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { update_merge_request({ reviewer_ids: [user2.id] }) } end end context 'when reviewers did not change' do it_behaves_like 'does not trigger GraphQL subscription mergeRequestReviewersUpdated' do let(:action) { update_merge_request({ reviewer_ids: [merge_request.reviewer_ids] }) } end end context 'when the milestone is removed' do let!(:non_subscriber) { create(:user) } let!(:subscriber) do create(:user) do |u| merge_request.toggle_subscription(u, project) project.add_developer(u) end end it 'sends notifications for subscribers of changed milestone', :sidekiq_inline do merge_request.milestone = create(:milestone, project: project) merge_request.save! perform_enqueued_jobs do update_merge_request(milestone_id: "") end should_email(subscriber) should_not_email(non_subscriber) end end context 'when the milestone is changed' do let!(:non_subscriber) { create(:user) } let!(:subscriber) do create(:user) do |u| merge_request.toggle_subscription(u, project) project.add_developer(u) end end it 'calls MergeRequests::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request(milestone_id: create(:milestone, project: project).id) end it 'sends notifications for subscribers of changed milestone', :sidekiq_inline do perform_enqueued_jobs do update_merge_request(milestone_id: create(:milestone, project: project).id) end should_email(subscriber) should_not_email(non_subscriber) end end context 'when the labels change' do it 'calls MergeRequests::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request({ label_ids: [label.id] }) end it 'updates updated_at' do travel_to(1.minute.from_now) do update_merge_request({ label_ids: [label.id] }) end expect(merge_request.reload.updated_at).to be_future end end context 'when the assignee changes' do it 'updates open merge request counter for assignees when merge request is reassigned' do update_merge_request(assignee_ids: [user2.id]) expect(user3.assigned_open_merge_requests_count).to eq 0 expect(user2.assigned_open_merge_requests_count).to eq 1 end it 'records the assignment history', :sidekiq_inline do original_assignee = merge_request.assignees.first! update_merge_request(assignee_ids: [user2.id]) expected_events = [ have_attributes({ merge_request_id: merge_request.id, user_id: original_assignee.id, action: 'remove' }), have_attributes({ merge_request_id: merge_request.id, user_id: user2.id, action: 'add' }) ] expect(merge_request.assignment_events).to match_array(expected_events) end end context 'when the target branch changes' do it 'calls MergeRequests::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request({ target_branch: 'target' }) end it "does not try to mark as unchecked if it's already unchecked" do allow(merge_request).to receive(:unchecked?).twice.and_return(true) expect(merge_request).not_to receive(:mark_as_unchecked) update_merge_request({ target_branch: "target" }) end it_behaves_like "creates a new pipeline" do let(:new_target_branch) { "target" } end end context 'when auto merge is enabled and target branch changed' do before do AutoMergeService.new(project, user, { sha: merge_request.diff_head_sha }).execute(merge_request, AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS) end it 'calls MergeRequests::ResolveTodosService#async_execute' do expect_next_instance_of(MergeRequests::ResolveTodosService, merge_request, user) do |service| expect(service).to receive(:async_execute) end update_merge_request({ target_branch: 'target' }) end it_behaves_like "creates a new pipeline" do let(:new_target_branch) { "target" } end end end context 'when the draft status is changed' do let(:title) { 'New Title' } let(:draft_title) { "Draft: #{title}" } let!(:non_subscriber) { create(:user) } let!(:subscriber) do create(:user) { |u| merge_request.toggle_subscription(u, project) } end before do project.add_developer(non_subscriber) project.add_developer(subscriber) end context 'removing draft status' do before do merge_request.update_attribute(:title, draft_title) end it 'sends notifications for subscribers', :sidekiq_inline do opts = { title: 'New title' } perform_enqueued_jobs do @merge_request = described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end should_email(subscriber) should_not_email(non_subscriber) end it 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do expect(GraphqlTriggers).to receive(:merge_request_merge_status_updated).with(merge_request) update_merge_request(title: 'New title') end context 'when additional_merge_when_checks_ready is enabled' do it 'publishes a DraftStateChangeEvent' do expected_data = { current_user_id: user.id, merge_request_id: merge_request.id } expect { update_merge_request(title: 'New title') }.to publish_event(MergeRequests::DraftStateChangeEvent).with(expected_data) end end context 'when additional_merge_when_checks_ready is disabled' do before do stub_feature_flags(additional_merge_when_checks_ready: false) end it 'does not publish a DraftStateChangeEvent' do expect { update_merge_request(title: 'New title') }.not_to publish_event(MergeRequests::DraftStateChangeEvent) end end context 'when removing through wip_event param' do it 'removes Draft from the title' do expect { update_merge_request({ wip_event: "ready" }) } .to change { merge_request.title } .from(draft_title) .to(title) end end end context 'adding draft status' do before do merge_request.update_attribute(:title, title) end it 'does not send notifications', :sidekiq_inline do opts = { title: 'Draft: New title' } perform_enqueued_jobs do @merge_request = described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end should_email(subscriber) should_not_email(non_subscriber) end context 'when additional_merge_when_checks_ready is enabled' do it 'publishes a DraftStateChangeEvent' do expected_data = { current_user_id: user.id, merge_request_id: merge_request.id } expect { update_merge_request(title: 'Draft: New title') }.to publish_event(MergeRequests::DraftStateChangeEvent).with(expected_data) end end context 'when additional_merge_when_checks_ready is disabled' do before do stub_feature_flags(additional_merge_when_checks_ready: false) end it 'does not publish a DraftStateChangeEvent' do expect { update_merge_request(title: 'Draft: New title') }.not_to publish_event(MergeRequests::DraftStateChangeEvent) end end it 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do expect(GraphqlTriggers).to receive(:merge_request_merge_status_updated).with(merge_request) update_merge_request(title: 'Draft: New title') end context 'when adding through wip_event param' do it 'adds Draft to the title' do expect { update_merge_request({ wip_event: "draft" }) } .to change { merge_request.title } .from(title) .to(draft_title) end end end end context 'when the merge request is relabeled' do let!(:non_subscriber) { create(:user) } let!(:subscriber) { create(:user) { |u| label.toggle_subscription(u, project) } } before do project.add_developer(non_subscriber) project.add_developer(subscriber) end it 'sends notifications for subscribers of newly added labels', :sidekiq_inline do opts = { label_ids: [label.id] } perform_enqueued_jobs do @merge_request = described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end should_email(subscriber) should_not_email(non_subscriber) end context 'when issue has the `label` label' do before do merge_request.labels << label end it 'does not send notifications for existing labels' do opts = { label_ids: [label.id, label2.id] } perform_enqueued_jobs do @merge_request = described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end should_not_email(subscriber) should_not_email(non_subscriber) end it 'does not send notifications for removed labels' do opts = { label_ids: [label2.id] } perform_enqueued_jobs do @merge_request = described_class.new(project: project, current_user: user, params: opts).execute(merge_request) end should_not_email(subscriber) should_not_email(non_subscriber) end end end context 'updating mentions' do let(:mentionable) { merge_request } include_examples 'updating mentions', described_class end context 'when MergeRequest has tasks' do before do update_merge_request({ description: "- [ ] Task 1\n- [ ] Task 2" }) end it { expect(@merge_request.tasks?).to eq(true) } it_behaves_like 'updating a single task' context 'when tasks are marked as completed' do before do update_merge_request({ description: "- [x] Task 1\n- [X] Task 2" }) end it 'creates system note about task status change' do note1 = find_note('marked the checklist item **Task 1** as completed') note2 = find_note('marked the checklist item **Task 2** as completed') expect(note1).not_to be_nil expect(note2).not_to be_nil description_notes = find_notes('description') expect(description_notes.length).to eq(1) end end context 'when tasks are marked as incomplete' do before do update_merge_request({ description: "- [x] Task 1\n- [X] Task 2" }) update_merge_request({ description: "- [ ] Task 1\n- [ ] Task 2" }) end it 'creates system note about task status change' do note1 = find_note('marked the checklist item **Task 1** as incomplete') note2 = find_note('marked the checklist item **Task 2** as incomplete') expect(note1).not_to be_nil expect(note2).not_to be_nil description_notes = find_notes('description') expect(description_notes.length).to eq(1) end end end context 'while saving references to issues that the updated merge request closes' do let(:first_issue) { create(:issue, project: project) } let(:second_issue) { create(:issue, project: project) } it 'creates a `MergeRequestsClosingIssues` record for each issue' do issue_closing_opts = { description: "Closes #{first_issue.to_reference} and #{second_issue.to_reference}" } service = described_class.new(project: project, current_user: user, params: issue_closing_opts) allow(service).to receive(:execute_hooks) service.execute(merge_request) issue_ids = MergeRequestsClosingIssues.where(merge_request: merge_request).pluck(:issue_id) expect(issue_ids).to match_array([first_issue.id, second_issue.id]) end it 'removes `MergeRequestsClosingIssues` records when issues are not closed anymore' do create(:merge_requests_closing_issues, issue: first_issue, merge_request: merge_request) create(:merge_requests_closing_issues, issue: second_issue, merge_request: merge_request) service = described_class.new(project: project, current_user: user, params: { description: "not closing any issues" }) allow(service).to receive(:execute_hooks) service.execute(merge_request.reload) issue_ids = MergeRequestsClosingIssues.where(merge_request: merge_request).pluck(:issue_id) expect(issue_ids).to be_empty end end context 'updating asssignee_ids' do context ':use_specialized_service' do context 'when true' do it 'passes the update action to ::MergeRequests::UpdateAssigneesService' do expect(::MergeRequests::UpdateAssigneesService) .to receive(:new).and_call_original update_merge_request({ assignee_ids: [user2.id], use_specialized_service: true }) end end context 'when false or nil' do before do expect(::MergeRequests::UpdateAssigneesService).not_to receive(:new) end it 'does not pass the update action to ::MergeRequests::UpdateAssigneesService when false' do update_merge_request({ assignee_ids: [user2.id], use_specialized_service: false }) end it 'does not pass the update action to ::MergeRequests::UpdateAssigneesService when nil' do update_merge_request({ assignee_ids: [user2.id], use_specialized_service: nil }) end end end it 'does not update assignee when assignee_id is invalid' do merge_request.update!(assignee_ids: [user.id]) expect(MergeRequests::HandleAssigneesChangeService).not_to receive(:new) update_merge_request(assignee_ids: [-1]) expect(merge_request.reload.assignees).to eq([user]) end it 'unassigns assignee when user id is 0' do merge_request.update!(assignee_ids: [user.id]) expect_next_instance_of(MergeRequests::HandleAssigneesChangeService, project: project, current_user: user) do |service| expect(service) .to receive(:async_execute) .with(merge_request, [user]) end update_merge_request(assignee_ids: [0]) expect(merge_request.assignee_ids).to be_empty end it 'saves assignee when user id is valid' do expect_next_instance_of(MergeRequests::HandleAssigneesChangeService, project: project, current_user: user) do |service| expect(service) .to receive(:async_execute) .with(merge_request, [user3]) end update_merge_request(assignee_ids: [user.id]) expect(merge_request.assignee_ids).to eq([user.id]) end it 'does not update assignee_id when user cannot read issue' do non_member = create(:user) original_assignees = merge_request.assignees expect(MergeRequests::HandleAssigneesChangeService).not_to receive(:new) update_merge_request(assignee_ids: [non_member.id]) expect(merge_request.reload.assignees).to eq(original_assignees) end context "when issuable feature is private" do levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC] levels.each do |level| it "does not update with unauthorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do assignee = create(:user) project.update!(visibility_level: level) feature_visibility_attr = :"#{merge_request.model_name.plural}_access_level" project.project_feature.update_attribute(feature_visibility_attr, ProjectFeature::PRIVATE) expect { update_merge_request(assignee_ids: [assignee]) }.not_to change(merge_request.assignees, :count) end end end end context 'when adding time spent' do let(:spend_time) { { duration: 1800, user_id: user3.id } } context ':use_specialized_service' do context 'when true' do it 'passes the update action to ::MergeRequests::AddSpentTimeService' do expect(::MergeRequests::AddSpentTimeService) .to receive(:new).and_call_original update_merge_request(spend_time: spend_time, use_specialized_service: true) end end context 'when false or nil' do before do expect(::MergeRequests::AddSpentTimeService).not_to receive(:new) end it 'does not pass the update action to ::MergeRequests::UpdateAssigneesService when false' do update_merge_request(spend_time: spend_time, use_specialized_service: false) end it 'does not pass the update action to ::MergeRequests::UpdateAssigneesService when nil' do update_merge_request(spend_time: spend_time, use_specialized_service: nil) end end end end it_behaves_like 'issuable update service' do let(:open_issuable) { merge_request } let(:closed_issuable) { create(:closed_merge_request, source_project: project) } end context 'setting `allow_collaboration`' do let(:target_project) { create(:project, :repository, :public) } let(:source_project) { fork_project(target_project, nil, repository: true) } let(:user) { create(:user) } let(:merge_request) do create( :merge_request, source_project: source_project, source_branch: 'fixes', target_project: target_project ) end before do allow(ProtectedBranch).to receive(:protected?).with(source_project, 'fixes') { false } end it 'does not allow a maintainer of the target project to set `allow_collaboration`' do target_project.add_developer(user) update_merge_request(allow_collaboration: false, title: 'Updated title') expect(merge_request.title).to eq('Updated title') expect(merge_request.allow_collaboration).to be_truthy end it 'is allowed by a user that can push to the source and can update the merge request' do merge_request.update!(assignees: [user]) source_project.add_developer(user) update_merge_request(allow_collaboration: false, title: 'Updated title') expect(merge_request.title).to eq('Updated title') expect(merge_request.allow_collaboration).to be_falsy end end context 'updating `force_remove_source_branch`' do let(:target_project) { create(:project, :repository, :public) } let(:source_project) { fork_project(target_project, nil, repository: true) } let(:user) { target_project.first_owner } let(:merge_request) do create( :merge_request, source_project: source_project, source_branch: 'fixes', target_project: target_project ) end it "cannot be done by members of the target project when they don't have access" do expect { update_merge_request(force_remove_source_branch: true) } .not_to change { merge_request.reload.force_remove_source_branch? }.from(nil) end it 'can be done by members of the target project if they can push to the source project' do source_project.add_developer(user) expect { update_merge_request(force_remove_source_branch: true) } .to change { merge_request.reload.force_remove_source_branch? }.from(nil).to(true) end end context 'updating `target_branch`' do let(:merge_request) do create( :merge_request, source_project: project, source_branch: 'mr-b', target_branch: 'mr-a' ) end it 'updates to master' do expect(SystemNoteService).to receive(:change_branch).with( merge_request, project, user, 'target', 'update', 'mr-a', 'master' ) expect { update_merge_request(target_branch: 'master') } .to change { merge_request.reload.target_branch }.from('mr-a').to('master') end it 'updates to master because of branch deletion' do expect(SystemNoteService).to receive(:change_branch).with( merge_request, project, user, 'target', 'delete', 'mr-a', 'master' ) expect { update_merge_request(target_branch: 'master', target_branch_was_deleted: true) } .to change { merge_request.reload.target_branch }.from('mr-a').to('master') end it_behaves_like "creates a new pipeline" do let(:new_target_branch) { "target" } end end it_behaves_like 'issuable record that supports quick actions' do let(:existing_merge_request) { create(:merge_request, source_project: project) } let(:issuable) { described_class.new(project: project, current_user: user, params: params).execute(existing_merge_request) } end context 'updating labels' do context 'when merge request is not merged' do let(:label_a) { label } let(:label_b) { create(:label, title: 'b', project: project) } let(:label_c) { create(:label, title: 'c', project: project) } let(:label_locked) { create(:label, title: 'locked', project: project, lock_on_merge: true) } let(:issuable) { merge_request } it_behaves_like 'updating issuable labels' it_behaves_like 'keeps issuable labels sorted after update' it_behaves_like 'broadcasting issuable labels updates' end context 'when merge request has been merged' do let(:label_a) { create(:label, title: 'a', project: project, lock_on_merge: true) } let(:label_b) { create(:label, title: 'b', project: project, lock_on_merge: true) } let(:label_c) { create(:label, title: 'c', project: project, lock_on_merge: true) } let(:label_unlocked) { create(:label, title: 'unlocked', project: project) } let(:issuable) { merge_request } before do merge_request.update!(state: 'merged') end it_behaves_like 'updating merged MR with locked labels' context 'when feature flag is disabled' do let(:label_locked) { create(:label, title: 'locked', project: project, lock_on_merge: true) } before do stub_feature_flags(enforce_locked_labels_on_merge: false) end it_behaves_like 'updating issuable labels' end end def update_issuable(update_params) update_merge_request(update_params) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class MergeabilityCheckBatchService def initialize(merge_requests, user) @merge_requests = merge_requests @user = user end def execute return unless merge_requests.present? MergeRequests::MergeabilityCheckBatchWorker.perform_async(merge_requests.map(&:id), user&.id) end private attr_reader :merge_requests, :user end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::MergeabilityCheckBatchService, feature_category: :code_review_workflow do describe '#execute' do subject { described_class.new(merge_requests, user).execute } let(:merge_requests) { [] } let_it_be(:user) { create(:user) } context 'when merge_requests are not empty' do let_it_be(:merge_request_1) { create(:merge_request) } let_it_be(:merge_request_2) { create(:merge_request) } let_it_be(:merge_requests) { [merge_request_1, merge_request_2] } it 'triggers batch mergeability checks' do expect(MergeRequests::MergeabilityCheckBatchWorker).to receive(:perform_async) .with([merge_request_1.id, merge_request_2.id], user.id) subject end context 'when user is nil' do let(:user) { nil } it 'trigger mergeability checks with nil user_id' do expect(MergeRequests::MergeabilityCheckBatchWorker).to receive(:perform_async) .with([merge_request_1.id, merge_request_2.id], nil) subject end end end context 'when merge_requests is empty' do let(:merge_requests) { MergeRequest.none } it 'does not trigger mergeability checks' do expect(MergeRequests::MergeabilityCheckBatchWorker).not_to receive(:perform_async) subject end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class RefreshService < MergeRequests::BaseService include Gitlab::Utils::StrongMemoize attr_reader :push def execute(oldrev, newrev, ref) @push = Gitlab::Git::Push.new(@project, oldrev, newrev, ref) return true unless @push.branch_push? refresh_merge_requests! end private def refresh_merge_requests! # n + 1: https://gitlab.com/gitlab-org/gitlab-foss/issues/60289 Gitlab::GitalyClient.allow_n_plus_1_calls { find_new_commits } # Be sure to close outstanding MRs before reloading them to avoid generating an # empty diff during a manual merge close_upon_missing_source_branch_ref post_merge_manually_merged link_forks_lfs_objects reload_merge_requests merge_requests_for_source_branch.each do |mr| outdate_suggestions(mr) abort_auto_merges(mr) mark_pending_todos_done(mr) end abort_ff_merge_requests_with_when_pipeline_succeeds cache_merge_requests_closing_issues merge_requests_for_source_branch.each do |mr| # Leave a system note if a branch was deleted/added if branch_added_or_removed? comment_mr_branch_presence_changed(mr) end notify_about_push(mr) mark_mr_as_draft_from_commits(mr) execute_mr_web_hooks(mr) # Run at the end of the loop to avoid any potential contention on the MR object refresh_pipelines_on_merge_requests(mr) merge_request_activity_counter.track_mr_including_ci_config(user: mr.author, merge_request: mr) end true end def branch_added_or_removed? strong_memoize(:branch_added_or_removed) do @push.branch_added? || @push.branch_removed? end end def close_upon_missing_source_branch_ref # MergeRequest#reload_diff ignores not opened MRs. This means it won't # create an `empty` diff for `closed` MRs without a source branch, keeping # the latest diff state as the last _valid_ one. merge_requests_for_source_branch.reject(&:source_branch_exists?).each do |mr| MergeRequests::CloseService .new(project: mr.target_project, current_user: @current_user) .execute(mr) end end # Collect open merge requests that target same branch we push into # and close if push to master include last commit from merge request # We need this to close(as merged) merge requests that were merged into # target branch manually # rubocop: disable CodeReuse/ActiveRecord def post_merge_manually_merged commit_ids = @commits.map(&:id) merge_requests = @project.merge_requests.opened .preload_project_and_latest_diff .preload_latest_diff_commit .where(target_branch: @push.branch_name).to_a .select(&:diff_head_commit) .select do |merge_request| commit_ids.include?(merge_request.diff_head_sha) && merge_request.merge_request_diff.state != 'empty' end merge_requests = filter_merge_requests(merge_requests) return if merge_requests.empty? analyzer = Gitlab::BranchPushMergeCommitAnalyzer.new( @commits.reverse, relevant_commit_ids: merge_requests.map(&:diff_head_sha) ) merge_requests.each do |merge_request| sha = analyzer.get_merge_commit(merge_request.diff_head_sha) merge_request.merge_commit_sha = sha merge_request.merged_commit_sha = sha MergeRequests::PostMergeService .new(project: merge_request.target_project, current_user: @current_user) .execute(merge_request) end end # rubocop: enable CodeReuse/ActiveRecord # Link LFS objects that exists in forks but does not exists in merge requests # target project def link_forks_lfs_objects return unless @push.branch_updated? merge_requests_for_forks.find_each do |mr| LinkLfsObjectsService .new(project: mr.target_project) .execute(mr, oldrev: @push.oldrev, newrev: @push.newrev) end end # Refresh merge request diff if we push to source or target branch of merge request # Note: we should update merge requests from forks too def reload_merge_requests merge_requests = @project.merge_requests.opened .by_source_or_target_branch(@push.branch_name) .preload_project_and_latest_diff merge_requests_from_forks = merge_requests_for_forks .preload_project_and_latest_diff merge_requests_array = merge_requests.to_a + merge_requests_from_forks.to_a filter_merge_requests(merge_requests_array).each do |merge_request| skip_merge_status_trigger = true if branch_and_project_match?(merge_request) || @push.force_push? merge_request.reload_diff(current_user) # Clear existing merge error if the push were directed at the # source branch. Clearing the error when the target branch # changes will hide the error from the user. merge_request.merge_error = nil # Don't skip trigger since we to update the MR's merge status in real-time # when the push if for the MR's source branch and project. skip_merge_status_trigger = false elsif merge_request.merge_request_diff.includes_any_commits?(push_commit_ids) merge_request.reload_diff(current_user) end merge_request.skip_merge_status_trigger = skip_merge_status_trigger merge_request.mark_as_unchecked end # Upcoming method calls need the refreshed version of # @source_merge_requests diffs (for MergeRequest#commit_shas for instance). merge_requests_for_source_branch(reload: true) end def push_commit_ids @push_commit_ids ||= @commits.map(&:id) end def branch_and_project_match?(merge_request) merge_request.source_project == @project && merge_request.source_branch == @push.branch_name end def outdate_suggestions(merge_request) outdate_service.execute(merge_request) end def outdate_service @outdate_service ||= Suggestions::OutdateService.new end def abort_auto_merges?(merge_request) merge_request.merge_params.with_indifferent_access[:sha] != @push.newrev end def abort_auto_merges(merge_request) return unless abort_auto_merges?(merge_request) abort_auto_merge(merge_request, 'source branch was updated') end def abort_ff_merge_requests_with_when_pipeline_succeeds return unless @project.ff_merge_must_be_possible? merge_requests_with_auto_merge_enabled_to(@push.branch_name).each do |merge_request| next unless merge_request.auto_merge_strategy == AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS next unless merge_request.should_be_rebased? abort_auto_merge_with_todo(merge_request, 'target branch was updated') end end def abort_auto_merge_with_todo(merge_request, reason) response = abort_auto_merge(merge_request, reason) response = ServiceResponse.new(**response) return unless response.success? todo_service.merge_request_became_unmergeable(merge_request) end def merge_requests_with_auto_merge_enabled_to(target_branch) @project .merge_requests .by_target_branch(target_branch) .with_auto_merge_enabled end def mark_pending_todos_done(merge_request) todo_service.merge_request_push(merge_request, @current_user) end def find_new_commits if @push.branch_added? @commits = [] merge_request = merge_requests_for_source_branch.first return unless merge_request begin # Since any number of commits could have been made to the restored branch, # find the common root to see what has been added. common_ref = @project.repository.merge_base(merge_request.diff_head_sha, @push.newrev) # If the a commit no longer exists in this repo, gitlab_git throws # a Rugged::OdbError. This is fixed in https://gitlab.com/gitlab-org/gitlab_git/merge_requests/52 @commits = @project.repository.commits_between(common_ref, @push.newrev) if common_ref rescue StandardError end elsif @push.branch_removed? # No commits for a deleted branch. @commits = [] else @commits = @project.repository.commits_between(@push.oldrev, @push.newrev) end end # Add comment about branches being deleted or added to merge requests def comment_mr_branch_presence_changed(merge_request) presence = @push.branch_added? ? :add : :delete SystemNoteService.change_branch_presence( merge_request, merge_request.project, @current_user, :source, @push.branch_name, presence) end # Add comment about pushing new commits to merge requests and send notification emails # def notify_about_push(merge_request) return unless @commits.present? mr_commit_ids = Set.new(merge_request.commit_shas) new_commits, existing_commits = @commits.partition do |commit| mr_commit_ids.include?(commit.id) end SystemNoteService.add_commits( merge_request, merge_request.project, @current_user, new_commits, existing_commits, @push.oldrev ) notification_service.push_to_merge_request(merge_request, @current_user, new_commits: new_commits, existing_commits: existing_commits) end def mark_mr_as_draft_from_commits(merge_request) return unless @commits.present? commit_shas = merge_request.commit_shas draft_commit = @commits.detect do |commit| commit.draft? && commit_shas.include?(commit.sha) end if draft_commit && !merge_request.draft? merge_request.update(title: merge_request.draft_title) SystemNoteService.add_merge_request_draft_from_commit( merge_request, merge_request.project, @current_user, draft_commit ) end end # Call merge request webhook with update branches def execute_mr_web_hooks(merge_request) execute_hooks(merge_request, 'update', old_rev: @push.oldrev) end # If the merge requests closes any issues, save this information in the # `MergeRequestsClosingIssues` model (as a performance optimization). # rubocop: disable CodeReuse/ActiveRecord def cache_merge_requests_closing_issues @project.merge_requests.where(source_branch: @push.branch_name).each do |merge_request| merge_request.cache_merge_request_closes_issues!(@current_user) end end # rubocop: enable CodeReuse/ActiveRecord def filter_merge_requests(merge_requests) merge_requests.uniq.select(&:source_project) end def merge_requests_for_source_branch(reload: false) @source_merge_requests = nil if reload @source_merge_requests ||= merge_requests_for(@push.branch_name) end def merge_requests_for_forks @merge_requests_for_forks ||= MergeRequest .opened .from_project(project) .from_source_branches(@push.branch_name) .from_fork end end end MergeRequests::RefreshService.prepend_mod_with('MergeRequests::RefreshService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::RefreshService, feature_category: :code_review_workflow do include ProjectForksHelper include UserHelpers let(:project) { create(:project, :repository) } let(:user) { create(:user) } let(:service) { described_class } describe '#execute' do before do @user = create(:user) group = create(:group) group.add_owner(@user) @project = create(:project, :repository, namespace: group) @fork_project = fork_project(@project, @user, repository: true) @merge_request = create( :merge_request, source_project: @project, source_branch: 'master', target_branch: 'feature', target_project: @project, auto_merge_enabled: true, auto_merge_strategy: AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS, merge_user: @user ) @another_merge_request = create( :merge_request, source_project: @project, source_branch: 'master', target_branch: 'test', target_project: @project, auto_merge_enabled: true, auto_merge_strategy: AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS, merge_user: @user ) @fork_merge_request = create( :merge_request, source_project: @fork_project, source_branch: 'master', target_branch: 'feature', target_project: @project ) @build_failed_todo = create( :todo, :build_failed, user: @user, project: @project, target: @merge_request, author: @user ) @fork_build_failed_todo = create( :todo, :build_failed, user: @user, project: @project, target: @merge_request, author: @user ) @commits = @merge_request.commits @oldrev = @commits.last.id @newrev = @commits.first.id end context 'push to origin repo source branch' do let(:refresh_service) { service.new(project: @project, current_user: @user) } let(:notification_service) { spy('notification_service') } before do allow(refresh_service).to receive(:execute_hooks) allow(NotificationService).to receive(:new) { notification_service } end context 'query count' do it 'does not execute a lot of queries' do # Hardcoded the query limit since the queries can also be reduced even # if there are the same number of merge requests (e.g. by preloading # associations). This should also fail in case additional queries are # added elsewhere that affected this service. # # The limit is based on the number of queries executed at the current # state of the service. As we reduce the number of queries executed in # this service, the limit should be reduced as well. expect { refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') } .not_to exceed_query_limit(260) end end it 'executes hooks with update action' do refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') reload_mrs expect(refresh_service).to have_received(:execute_hooks) .with(@merge_request, 'update', old_rev: @oldrev) expect(notification_service).to have_received(:push_to_merge_request) .with(@merge_request, @user, new_commits: anything, existing_commits: anything) expect(notification_service).to have_received(:push_to_merge_request) .with(@another_merge_request, @user, new_commits: anything, existing_commits: anything) expect(@merge_request.notes).not_to be_empty expect(@merge_request).to be_open expect(@merge_request.auto_merge_enabled).to be_falsey expect(@merge_request.diff_head_sha).to eq(@newrev) expect(@fork_merge_request).to be_open expect(@fork_merge_request.notes).to be_empty expect(@build_failed_todo).to be_done expect(@fork_build_failed_todo).to be_done end it 'triggers mergeRequestMergeStatusUpdated GraphQL subscription conditionally' do expect(GraphqlTriggers).to receive(:merge_request_merge_status_updated).with(@merge_request) expect(GraphqlTriggers).to receive(:merge_request_merge_status_updated).with(@another_merge_request) expect(GraphqlTriggers).not_to receive(:merge_request_merge_status_updated).with(@fork_merge_request) refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') end context 'when a merge error exists' do let(:error_message) { 'This is a merge error' } before do @merge_request = create(:merge_request, source_project: @project, source_branch: 'feature', target_branch: 'master', target_project: @project, merge_error: error_message) end it 'clears merge errors when pushing to the source branch' do expect { refresh_service.execute(@oldrev, @newrev, 'refs/heads/feature') } .to change { @merge_request.reload.merge_error } .from(error_message) .to(nil) end it 'does not clear merge errors when pushing to the target branch' do expect { refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') } .not_to change { @merge_request.reload.merge_error } end end it 'reloads source branch MRs memoization' do refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') expect { refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') }.to change { refresh_service.instance_variable_get(:@source_merge_requests).first.merge_request_diff } end it 'outdates MR suggestions' do expect_next_instance_of(Suggestions::OutdateService) do |service| expect(service).to receive(:execute).with(@merge_request).and_call_original expect(service).to receive(:execute).with(@another_merge_request).and_call_original end refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') end context 'when source branch ref does not exists' do before do ::Branches::DeleteService.new(@project, @user).execute(@merge_request.source_branch) end it 'closes MRs without source branch ref' do expect { refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') } .to change { @merge_request.reload.state } .from('opened') .to('closed') expect(@fork_merge_request.reload).to be_open end it 'does not change the merge request diff' do expect { refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') } .not_to change { @merge_request.reload.merge_request_diff } end end it 'calls the merge request activity counter' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_mr_including_ci_config) .with(user: @merge_request.author, merge_request: @merge_request) expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_mr_including_ci_config) .with(user: @another_merge_request.author, merge_request: @another_merge_request) refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') end end context 'when pipeline exists for the source branch' do let!(:pipeline) { create(:ci_empty_pipeline, ref: @merge_request.source_branch, project: @project, sha: @commits.first.sha) } subject { service.new(project: @project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/master') } it 'updates the head_pipeline_id for @merge_request', :sidekiq_inline do expect { subject }.to change { @merge_request.reload.head_pipeline_id }.from(nil).to(pipeline.id) end it 'does not update the head_pipeline_id for @fork_merge_request' do expect { subject }.not_to change { @fork_merge_request.reload.head_pipeline_id } end end context 'Pipelines for merge requests', :sidekiq_inline do before do stub_ci_pipeline_yaml_file(config) end subject { service.new(project: project, current_user: @user).execute(@oldrev, @newrev, ref) } let(:ref) { 'refs/heads/master' } let(:project) { @project } context "when .gitlab-ci.yml has merge_requests keywords" do let(:config) do YAML.dump({ test: { stage: 'test', script: 'echo', only: ['merge_requests'] } }) end it 'create detached merge request pipeline with commits' do expect { subject } .to change { @merge_request.pipelines_for_merge_request.count }.by(1) .and change { @another_merge_request.pipelines_for_merge_request.count }.by(0) expect(@merge_request.has_commits?).to be_truthy expect(@another_merge_request.has_commits?).to be_falsy end context 'when "push_options: nil" is passed' do let(:service_instance) { service.new(project: project, current_user: @user, params: { push_options: nil }) } subject { service_instance.execute(@oldrev, @newrev, ref) } it 'creates a detached merge request pipeline with commits' do expect { subject } .to change { @merge_request.pipelines_for_merge_request.count }.by(1) .and change { @another_merge_request.pipelines_for_merge_request.count }.by(0) expect(@merge_request.has_commits?).to be_truthy expect(@another_merge_request.has_commits?).to be_falsy end end context 'when ci.skip push_options are passed' do let(:params) { { push_options: { ci: { skip: true } } } } let(:service_instance) { service.new(project: project, current_user: @user, params: params) } subject { service_instance.execute(@oldrev, @newrev, ref) } it 'creates a skipped detached merge request pipeline with commits' do expect { subject } .to change { @merge_request.pipelines_for_merge_request.count }.by(1) .and change { @another_merge_request.pipelines_for_merge_request.count }.by(0) expect(@merge_request.has_commits?).to be_truthy expect(@another_merge_request.has_commits?).to be_falsy pipeline = @merge_request.pipelines_for_merge_request.last expect(pipeline).to be_skipped end end it 'does not create detached merge request pipeline for forked project' do expect { subject } .not_to change { @fork_merge_request.pipelines_for_merge_request.count } end it 'create detached merge request pipeline for non-fork merge request' do subject expect(@merge_request.pipelines_for_merge_request.first) .to be_detached_merge_request_pipeline end context 'when service is hooked by target branch' do let(:ref) { 'refs/heads/feature' } it 'does not create detached merge request pipeline' do expect { subject } .not_to change { @merge_request.pipelines_for_merge_request.count } end end context 'when service runs on forked project' do let(:project) { @fork_project } it 'creates detached merge request pipeline for fork merge request' do expect { subject } .to change { @fork_merge_request.pipelines_for_merge_request.count }.by(1) merge_request_pipeline = @fork_merge_request.pipelines_for_merge_request.first expect(merge_request_pipeline).to be_detached_merge_request_pipeline expect(merge_request_pipeline.project).to eq(@project) end end context "when branch pipeline was created before a detaced merge request pipeline has been created" do before do create( :ci_pipeline, project: @merge_request.source_project, sha: @merge_request.diff_head_sha, ref: @merge_request.source_branch, tag: false ) subject end it 'sets the latest detached merge request pipeline as a head pipeline' do @merge_request.reload expect(@merge_request.actual_head_pipeline).to be_merge_request_event end it 'returns pipelines in correct order' do @merge_request.reload expect(@merge_request.all_pipelines.first).to be_merge_request_event expect(@merge_request.all_pipelines.second).to be_push end end context "when MergeRequestUpdateWorker is retried by an exception" do it 'does not re-create a duplicate detached merge request pipeline' do expect do service.new(project: @project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/master') end.to change { @merge_request.pipelines_for_merge_request.count }.by(1) expect do service.new(project: @project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/master') end.not_to change { @merge_request.pipelines_for_merge_request.count } end end context 'when the pipeline should be skipped' do it 'saves a skipped detached merge request pipeline' do project.repository.create_file( @user, 'new-file.txt', 'A new file', message: '[skip ci] This is a test', branch_name: 'master' ) expect { subject } .to change { @merge_request.pipelines_for_merge_request.count }.by(1) expect(@merge_request.pipelines_for_merge_request.last).to be_skipped end end end context "when .gitlab-ci.yml does not have merge_requests keywords" do let(:config) do YAML.dump({ test: { stage: 'test', script: 'echo' } }) end it 'does not create a detached merge request pipeline' do expect { subject } .not_to change { @merge_request.pipelines_for_merge_request.count } end end context 'when .gitlab-ci.yml is invalid' do let(:config) { 'invalid yaml file' } it 'persists a pipeline with config error' do expect { subject } .to change { @merge_request.pipelines_for_merge_request.count }.by(1) expect(@merge_request.pipelines_for_merge_request.last).to be_failed expect(@merge_request.pipelines_for_merge_request.last).to be_config_error end end context 'when .gitlab-ci.yml file is valid but has a logical error' do let(:config) do YAML.dump({ build: { script: 'echo "Valid yaml syntax, but..."', only: ['master'] }, test: { script: 'echo "... I depend on build, which does not run."', only: ['merge_request'], needs: ['build'] } }) end it 'persists a pipeline with config error' do expect { subject } .to change { @merge_request.pipelines_for_merge_request.count }.by(1) expect(@merge_request.pipelines_for_merge_request.last).to be_failed expect(@merge_request.pipelines_for_merge_request.last).to be_config_error end end end context 'push to origin repo source branch' do let(:refresh_service) { service.new(project: @project, current_user: @user) } let(:notification_service) { spy('notification_service') } before do allow(refresh_service).to receive(:execute_hooks) allow(NotificationService).to receive(:new) { notification_service } refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') reload_mrs end it 'executes hooks with update action' do expect(refresh_service).to have_received(:execute_hooks) .with(@merge_request, 'update', old_rev: @oldrev) expect(notification_service).to have_received(:push_to_merge_request) .with(@merge_request, @user, new_commits: anything, existing_commits: anything) expect(notification_service).to have_received(:push_to_merge_request) .with(@another_merge_request, @user, new_commits: anything, existing_commits: anything) expect(@merge_request.notes).not_to be_empty expect(@merge_request).to be_open expect(@merge_request.auto_merge_enabled).to be_falsey expect(@merge_request.diff_head_sha).to eq(@newrev) expect(@fork_merge_request).to be_open expect(@fork_merge_request.notes).to be_empty expect(@build_failed_todo).to be_done expect(@fork_build_failed_todo).to be_done end end context 'push to origin repo target branch' do context 'when all MRs to the target branch had diffs' do before do service.new(project: @project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/feature') reload_mrs end it 'updates the merge state' do expect(@merge_request).to be_merged expect(@fork_merge_request).to be_merged expect(@build_failed_todo).to be_done expect(@fork_build_failed_todo).to be_done expect(@merge_request.resource_state_events.last.state).to eq('merged') expect(@fork_merge_request.resource_state_events.last.state).to eq('merged') end end context 'when an MR to be closed was empty already' do let!(:empty_fork_merge_request) do create( :merge_request, source_project: @fork_project, source_branch: 'master', target_branch: 'master', target_project: @project ) end before do # This spec already has a fake push, so pretend that we were targeting # feature all along. empty_fork_merge_request.update_columns(target_branch: 'feature') service.new(project: @project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/feature') reload_mrs empty_fork_merge_request.reload end it 'only updates the non-empty MRs' do expect(@merge_request).to be_merged expect(@fork_merge_request).to be_merged expect(empty_fork_merge_request).to be_open expect(empty_fork_merge_request.merge_request_diff.state).to eq('empty') expect(empty_fork_merge_request.notes).to be_empty expect(@merge_request.resource_state_events.last.state).to eq('merged') expect(@fork_merge_request.resource_state_events.last.state).to eq('merged') end end context 'manual merge of source branch' do before do # Merge master -> feature branch @project.repository.merge(@user, @merge_request.diff_head_sha, @merge_request, 'Test message') commit = @project.repository.commit('feature') service.new(project: @project, current_user: @user).execute(@oldrev, commit.id, 'refs/heads/feature') reload_mrs end it 'updates the merge state' do expect(@merge_request.resource_state_events.last.state).to eq('merged') expect(@fork_merge_request.resource_state_events.last.state).to eq('merged') expect(@merge_request).to be_merged expect(@merge_request.diffs.size).to be > 0 expect(@fork_merge_request).to be_merged expect(@build_failed_todo).to be_done expect(@fork_build_failed_todo).to be_done end end end context 'push to fork repo source branch' do let(:refresh_service) { service.new(project: @fork_project, current_user: @user) } def refresh allow(refresh_service).to receive(:execute_hooks) refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') reload_mrs end context 'open fork merge request' do it 'calls MergeRequests::LinkLfsObjectsService#execute' do expect_next_instance_of(MergeRequests::LinkLfsObjectsService) do |svc| expect(svc).to receive(:execute).with(@fork_merge_request, oldrev: @oldrev, newrev: @newrev) end refresh end it 'executes hooks with update action' do refresh expect(refresh_service).to have_received(:execute_hooks) .with(@fork_merge_request, 'update', old_rev: @oldrev) expect(@merge_request.notes).to be_empty expect(@merge_request).to be_open expect(@fork_merge_request.notes.last.note).to include('added 28 commits') expect(@fork_merge_request).to be_open expect(@build_failed_todo).to be_pending expect(@fork_build_failed_todo).to be_pending end it 'outdates opened forked MR suggestions' do expect_next_instance_of(Suggestions::OutdateService) do |service| expect(service).to receive(:execute).with(@fork_merge_request).and_call_original end refresh end end context 'closed fork merge request' do before do @fork_merge_request.close! end it 'do not execute hooks with update action' do refresh expect(refresh_service).not_to have_received(:execute_hooks) end it 'updates merge request to closed state' do refresh expect(@merge_request.notes).to be_empty expect(@merge_request).to be_open expect(@fork_merge_request.notes).to be_empty expect(@fork_merge_request).to be_closed expect(@build_failed_todo).to be_pending expect(@fork_build_failed_todo).to be_pending end end end context 'push to fork repo target branch' do describe 'changes to merge requests' do before do service.new(project: @fork_project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/feature') reload_mrs end it 'updates the merge request state' do expect(@merge_request.notes).to be_empty expect(@merge_request).to be_open expect(@fork_merge_request.notes).to be_empty expect(@fork_merge_request).to be_open expect(@build_failed_todo).to be_pending expect(@fork_build_failed_todo).to be_pending end end describe 'merge request diff' do it 'does not reload the diff of the merge request made from fork' do expect do service.new(project: @fork_project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/feature') end.not_to change { @fork_merge_request.reload.merge_request_diff } end end end context 'forked projects with the same source branch name as target branch' do let!(:first_commit) do @fork_project.repository.create_file( @user, 'test1.txt', 'Test data', message: 'Test commit', branch_name: 'master' ) end let!(:second_commit) do @fork_project.repository.create_file( @user, 'test2.txt', 'More test data', message: 'Second test commit', branch_name: 'master' ) end let!(:forked_master_mr) do create( :merge_request, source_project: @fork_project, source_branch: 'master', target_branch: 'master', target_project: @project ) end let(:force_push_commit) { @project.commit('feature').id } it 'reloads a new diff for a push to the forked project' do expect do service.new(project: @fork_project, current_user: @user).execute(@oldrev, first_commit, 'refs/heads/master') reload_mrs end.to change { forked_master_mr.merge_request_diffs.count }.by(1) end it 'reloads a new diff for a force push to the source branch' do expect do service.new(project: @fork_project, current_user: @user).execute(@oldrev, force_push_commit, 'refs/heads/master') reload_mrs end.to change { forked_master_mr.merge_request_diffs.count }.by(1) end it 'reloads a new diff for a force push to the target branch' do expect do service.new(project: @project, current_user: @user).execute(@oldrev, force_push_commit, 'refs/heads/master') reload_mrs end.to change { forked_master_mr.merge_request_diffs.count }.by(1) end it 'reloads a new diff for a push to the target project that contains a commit in the MR' do expect do service.new(project: @project, current_user: @user).execute(@oldrev, first_commit, 'refs/heads/master') reload_mrs end.to change { forked_master_mr.merge_request_diffs.count }.by(1) end it 'does not increase the diff count for a new push to target branch' do new_commit = @project.repository.create_file( @user, 'new-file.txt', 'A new file', message: 'This is a test', branch_name: 'master' ) expect do service.new(project: @project, current_user: @user).execute(@newrev, new_commit, 'refs/heads/master') reload_mrs end.not_to change { forked_master_mr.merge_request_diffs.count } end end context 'push to origin repo target branch after fork project was removed' do before do @fork_project.destroy! service.new(project: @project, current_user: @user).execute(@oldrev, @newrev, 'refs/heads/feature') reload_mrs end it 'updates the merge request state' do expect(@merge_request.resource_state_events.last.state).to eq('merged') expect(@merge_request).to be_merged expect(@fork_merge_request).to be_open expect(@fork_merge_request.notes).to be_empty expect(@build_failed_todo).to be_done expect(@fork_build_failed_todo).to be_done end end context 'push new branch that exists in a merge request' do let(:refresh_service) { service.new(project: @fork_project, current_user: @user) } it 'refreshes the merge request' do expect(refresh_service).to receive(:execute_hooks) .with(@fork_merge_request, 'update', old_rev: Gitlab::Git::BLANK_SHA) allow_any_instance_of(Repository).to receive(:merge_base).and_return(@oldrev) refresh_service.execute(Gitlab::Git::BLANK_SHA, @newrev, 'refs/heads/master') reload_mrs expect(@merge_request.notes).to be_empty expect(@merge_request).to be_open notes = @fork_merge_request.notes.reorder(:created_at).map(&:note) expect(notes[0]).to include('restored source branch `master`') expect(notes[1]).to include('added 28 commits') expect(@fork_merge_request).to be_open end end context 'merge request metrics' do let(:user) { create(:user) } let(:project) { create(:project, :repository) } let(:issue) { create(:issue, project: project) } let(:commit) { project.commit } before do project.add_developer(user) allow(commit).to receive_messages( safe_message: "Closes #{issue.to_reference}", references: [issue], author_name: user.name, author_email: user.email, committed_date: Time.current ) end context 'when the merge request is sourced from the same project' do it 'creates a `MergeRequestsClosingIssues` record for each issue closed by a commit' do allow_any_instance_of(MergeRequest).to receive(:commits).and_return( CommitCollection.new(project, [commit], 'close-by-commit') ) merge_request = create( :merge_request, target_branch: 'master', source_branch: 'close-by-commit', source_project: project ) refresh_service = service.new(project: project, current_user: user) allow(refresh_service).to receive(:execute_hooks) refresh_service.execute(@oldrev, @newrev, 'refs/heads/close-by-commit') issue_ids = MergeRequestsClosingIssues.where(merge_request: merge_request).pluck(:issue_id) expect(issue_ids).to eq([issue.id]) end end context 'when the merge request is sourced from a different project' do it 'creates a `MergeRequestsClosingIssues` record for each issue closed by a commit' do forked_project = fork_project(project, user, repository: true) allow_any_instance_of(MergeRequest).to receive(:commits).and_return( CommitCollection.new(forked_project, [commit], 'close-by-commit') ) merge_request = create( :merge_request, target_branch: 'master', target_project: project, source_branch: 'close-by-commit', source_project: forked_project ) refresh_service = service.new(project: forked_project, current_user: user) allow(refresh_service).to receive(:execute_hooks) refresh_service.execute(@oldrev, @newrev, 'refs/heads/close-by-commit') issue_ids = MergeRequestsClosingIssues.where(merge_request: merge_request).pluck(:issue_id) expect(issue_ids).to eq([issue.id]) end end end context 'marking the merge request as draft' do let(:refresh_service) { service.new(project: @project, current_user: @user) } before do allow(refresh_service).to receive(:execute_hooks) end it 'marks the merge request as draft from fixup commits' do fixup_merge_request = create( :merge_request, source_project: @project, source_branch: 'wip', target_branch: 'master', target_project: @project ) commits = fixup_merge_request.commits oldrev = commits.last.id newrev = commits.first.id refresh_service.execute(oldrev, newrev, 'refs/heads/wip') fixup_merge_request.reload expect(fixup_merge_request.draft?).to eq(true) expect(fixup_merge_request.notes.last.note).to match( /marked this merge request as \*\*draft\*\* from #{Commit.reference_pattern}/ ) end it 'references the commit that caused the draft status' do draft_merge_request = create( :merge_request, source_project: @project, source_branch: 'wip', target_branch: 'master', target_project: @project ) commits = draft_merge_request.commits oldrev = commits.last.id newrev = commits.first.id draft_commit = draft_merge_request.commits.find(&:draft?) refresh_service.execute(oldrev, newrev, 'refs/heads/wip') expect(draft_merge_request.reload.notes.last.note).to eq( "marked this merge request as **draft** from #{draft_commit.id}" ) end it 'does not mark as draft based on commits that do not belong to an MR' do allow(refresh_service).to receive(:find_new_commits) refresh_service.instance_variable_set(:@commits, [ double( id: 'aaaaaaa', sha: 'aaaaaaa', short_id: 'aaaaaaa', title: 'Fix issue', draft?: false ), double( id: 'bbbbbbb', sha: 'bbbbbbbb', short_id: 'bbbbbbb', title: 'fixup! Fix issue', draft?: true, to_reference: 'bbbbbbb' ) ]) refresh_service.execute(@oldrev, @newrev, 'refs/heads/master') reload_mrs expect(@merge_request.draft?).to be_falsey end end def reload_mrs @merge_request.reload @fork_merge_request.reload @build_failed_todo.reload @fork_build_failed_todo.reload end end describe 'updating merge_commit' do let(:service) { described_class.new(project: project, current_user: user) } let(:user) { create(:user) } let(:project) { create(:project, :repository) } let(:oldrev) { TestEnv::BRANCH_SHA['merge-commit-analyze-before'] } let(:newrev) { TestEnv::BRANCH_SHA['merge-commit-analyze-after'] } # Pretend branch is now updated let!(:merge_request) do create( :merge_request, source_project: project, source_branch: 'merge-commit-analyze-after', target_branch: 'merge-commit-analyze-before', target_project: project, merge_user: user ) end let!(:merge_request_side_branch) do create( :merge_request, source_project: project, source_branch: 'merge-commit-analyze-side-branch', target_branch: 'merge-commit-analyze-before', target_project: project, merge_user: user ) end subject { service.execute(oldrev, newrev, 'refs/heads/merge-commit-analyze-before') } context 'feature enabled' do it "updates merge requests' merge_commit and merged_commit values", :aggregate_failures do expect(Gitlab::BranchPushMergeCommitAnalyzer).to receive(:new).and_wrap_original do |original_method, commits| expect(commits.map(&:id)).to eq(%w[646ece5cfed840eca0a4feb21bcd6a81bb19bda3 29284d9bcc350bcae005872d0be6edd016e2efb5 5f82584f0a907f3b30cfce5bb8df371454a90051 8a994512e8c8f0dfcf22bb16df6e876be7a61036 689600b91aabec706e657e38ea706ece1ee8268f db46a1c5a5e474aa169b6cdb7a522d891bc4c5f9]) original_method.call(commits) end subject merge_request.reload merge_request_side_branch.reload expect(merge_request.merge_commit.id).to eq('646ece5cfed840eca0a4feb21bcd6a81bb19bda3') expect(merge_request_side_branch.merge_commit.id).to eq('29284d9bcc350bcae005872d0be6edd016e2efb5') # we need to use read_attribute to bypass the overridden # #merged_commit_sha method, which contains a fallback to # #merge_commit_sha expect(merge_request.read_attribute(:merged_commit_sha)).to eq('646ece5cfed840eca0a4feb21bcd6a81bb19bda3') expect(merge_request_side_branch.read_attribute(:merged_commit_sha)).to eq('29284d9bcc350bcae005872d0be6edd016e2efb5') end end end describe '#abort_ff_merge_requests_with_when_pipeline_succeeds' do let_it_be(:project) { create(:project, :repository) } let_it_be(:source_project) { project } let_it_be(:target_project) { project } let_it_be(:author) { create_user_from_membership(target_project, :developer) } let_it_be(:user) { create(:user) } let_it_be(:forked_project) do fork_project(target_project, author, repository: true) end let_it_be(:merge_request, refind: true) do create( :merge_request, author: author, source_project: source_project, source_branch: 'feature', target_branch: 'master', target_project: target_project, auto_merge_enabled: true, auto_merge_strategy: AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS, merge_user: user ) end let_it_be(:newrev) do target_project.repository.create_file( user, 'test1.txt', 'Test data', message: 'Test commit', branch_name: 'master' ) end let_it_be(:oldrev) do target_project .repository .commit(newrev) .parent_id end let(:auto_merge_strategy) { AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS } let(:refresh_service) { service.new(project: project, current_user: user) } before do target_project.merge_method = merge_method target_project.save! merge_request.auto_merge_strategy = auto_merge_strategy merge_request.save! refresh_service.execute(oldrev, newrev, 'refs/heads/master') merge_request.reload end context 'when Project#merge_method is set to FF' do let(:merge_method) { :ff } it_behaves_like 'aborted merge requests for MWPS' context 'with forked project' do let(:source_project) { forked_project } it_behaves_like 'aborted merge requests for MWPS' end context 'with bogus auto merge strategy' do let(:auto_merge_strategy) { 'bogus' } it_behaves_like 'maintained merge requests for MWPS' end end context 'when Project#merge_method is set to rebase_merge' do let(:merge_method) { :rebase_merge } it_behaves_like 'aborted merge requests for MWPS' context 'with forked project' do let(:source_project) { forked_project } it_behaves_like 'aborted merge requests for MWPS' end end context 'when Project#merge_method is set to merge' do let(:merge_method) { :merge } it_behaves_like 'maintained merge requests for MWPS' context 'with forked project' do let(:source_project) { forked_project } it_behaves_like 'maintained merge requests for MWPS' end end end describe '#abort_auto_merges' do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } let_it_be(:author) { user } let_it_be(:merge_request, refind: true) do create( :merge_request, source_project: project, target_project: project, merge_user: user, auto_merge_enabled: true, auto_merge_strategy: AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS ) end let(:service) { described_class.new(project: project, current_user: user) } let(:oldrev) { merge_request.diff_refs.base_sha } let(:newrev) { merge_request.diff_refs.head_sha } let(:merge_sha) { oldrev } before do merge_request.merge_params[:sha] = merge_sha merge_request.save! service.execute(oldrev, newrev, "refs/heads/#{merge_request.source_branch}") merge_request.reload end it 'aborts MWPS for merge requests' do expect(merge_request.auto_merge_enabled?).to be_falsey expect(merge_request.merge_user).to be_nil end context 'when merge params contains up-to-date sha' do let(:merge_sha) { newrev } it 'maintains MWPS for merge requests' do expect(merge_request.auto_merge_enabled?).to be_truthy expect(merge_request.merge_user).to eq(user) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class ExecuteApprovalHooksService < MergeRequests::BaseService def execute(merge_request) # Only one approval is required for a merge request to be approved notification_service.async.approve_mr(merge_request, current_user) execute_hooks(merge_request, 'approved') end end end MergeRequests::ExecuteApprovalHooksService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::ExecuteApprovalHooksService, feature_category: :code_review_workflow do let(:user) { create(:user) } let(:merge_request) { create(:merge_request) } let(:project) { merge_request.project } subject(:service) { described_class.new(project: project, current_user: user) } describe '#execute' do let(:notification_service) { NotificationService.new } before do allow(service).to receive(:notification_service).and_return(notification_service) end it 'sends a notification when approving' do expect(notification_service).to receive_message_chain(:async, :approve_mr) .with(merge_request, user) service.execute(merge_request) end context 'with remaining approvals' do it 'fires an approval webhook' do expect(service).to receive(:execute_hooks).with(merge_request, 'approved') service.execute(merge_request) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class CreateService < MergeRequests::BaseService def execute set_projects! set_default_attributes! merge_request = MergeRequest.new merge_request.target_project = @project merge_request.source_project = @source_project merge_request.source_branch = params[:source_branch] create(merge_request) end def after_create(issuable) current_user_id = current_user.id issuable.run_after_commit do # Add new items to MergeRequests::AfterCreateService if they can # be performed in Sidekiq NewMergeRequestWorker.perform_async(issuable.id, current_user_id) end issuable.mark_as_preparing super end # expose issuable create method so it can be called from email # handler CreateMergeRequestHandler public :create private def before_create(merge_request) # If the fetching of the source branch occurs in an ActiveRecord # callback (e.g. after_create), a database transaction will be # open while the Gitaly RPC waits. To avoid an idle in transaction # timeout, we do this before we attempt to save the merge request. merge_request.skip_ensure_merge_request_diff = true merge_request.check_for_spam(user: current_user, action: :create) end def set_projects! # @project is used to determine whether the user can set the merge request's # assignee, milestone and labels. Whether they can depends on their # permissions on the target project. @source_project = @project @project = Project.find(params[:target_project_id]) if params[:target_project_id] # make sure that source/target project ids are not in # params so it can't be overridden later when updating attributes # from params when applying quick actions params.delete(:source_project_id) params.delete(:target_project_id) unless can?(current_user, :create_merge_request_from, @source_project) && can?(current_user, :create_merge_request_in, @project) raise Gitlab::Access::AccessDeniedError end end def set_default_attributes! # Implemented in EE end end end MergeRequests::CreateService.prepend_mod_with('MergeRequests::CreateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::CreateService, :clean_gitlab_redis_shared_state, feature_category: :code_review_workflow do include ProjectForksHelper include AfterNextHelpers let(:project) { create(:project, :repository) } let(:user) { create(:user) } let(:user2) { create(:user) } describe '#execute' do context 'valid params' do let(:opts) do { title: 'Awesome merge_request', description: 'please fix', source_branch: 'feature', target_branch: 'master', force_remove_source_branch: '1' } end let(:service) { described_class.new(project: project, current_user: user, params: opts) } let(:merge_request) { service.execute } before do project.add_maintainer(user) project.add_developer(user2) end it 'creates an MR' do expect(merge_request).to be_valid expect(merge_request.draft?).to be(false) expect(merge_request.title).to eq('Awesome merge_request') expect(merge_request.assignees).to be_empty expect(merge_request.merge_params['force_remove_source_branch']).to eq('1') end it 'does not execute hooks' do expect(project).not_to receive(:execute_hooks) service.execute end it 'refreshes the number of open merge requests', :use_clean_rails_memory_store_caching do expect do service.execute BatchLoader::Executor.clear_current end.to change { project.open_merge_requests_count }.from(0).to(1) end it 'creates exactly 1 create MR event', :sidekiq_inline do attributes = { action: :created, target_id: merge_request.id, target_type: merge_request.class.name } expect(Event.where(attributes).count).to eq(1) end it 'sets the merge_status to preparing' do expect(merge_request.reload).to be_preparing end describe 'checking for spam' do it 'checks for spam' do expect_next_instance_of(MergeRequest) do |instance| expect(instance).to receive(:check_for_spam).with(user: user, action: :create) end service.execute end it 'does not persist when spam' do allow_next_instance_of(MergeRequest) do |instance| allow(instance).to receive(:spam?).and_return(true) end expect(merge_request).not_to be_persisted end end describe 'when marked with /draft' do context 'in title and in description' do let(:opts) do { title: 'Draft: Awesome merge_request', description: "well this is not done yet\n/draft", source_branch: 'feature', target_branch: 'master', assignees: [user2] } end it 'sets MR to draft' do expect(merge_request.draft?).to be(true) end end context 'in description only' do let(:opts) do { title: 'Awesome merge_request', description: "well this is not done yet\n/draft", source_branch: 'feature', target_branch: 'master', assignees: [user2] } end it 'sets MR to draft' do expect(merge_request.draft?).to be(true) end end end context 'when merge request is assigned to someone' do let(:opts) do { title: 'Awesome merge_request', description: 'please fix', source_branch: 'feature', target_branch: 'master', assignee_ids: [user2.id] } end it { expect(merge_request.assignees).to eq([user2]) } end context 'when reviewer is assigned' do let(:opts) do { title: 'Awesome merge_request', description: 'please fix', source_branch: 'feature', target_branch: 'master', reviewers: [user2] } end it { expect(merge_request.reviewers).to eq([user2]) } it 'invalidates counter cache for reviewers', :use_clean_rails_memory_store_caching do expect { merge_request } .to change { user2.review_requested_open_merge_requests_count } .by(1) end end context 'when head pipelines already exist for merge request source branch', :sidekiq_inline do let(:shas) { project.repository.commits(opts[:source_branch], limit: 2).map(&:id) } let!(:pipeline_1) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) } let!(:pipeline_2) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[0]) } let!(:pipeline_3) { create(:ci_pipeline, project: project, ref: "other_branch", project_id: project.id) } before do # rubocop: disable Cop/DestroyAll project.merge_requests .where(source_branch: opts[:source_branch], target_branch: opts[:target_branch]) .destroy_all # rubocop: enable Cop/DestroyAll end it 'sets head pipeline' do merge_request = service.execute expect(merge_request.reload.head_pipeline).to eq(pipeline_2) expect(merge_request).to be_persisted end context 'when the new pipeline is associated with an old sha' do let!(:pipeline_1) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[0]) } let!(:pipeline_2) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) } it 'sets an old pipeline with associated with the latest sha as the head pipeline' do merge_request = service.execute expect(merge_request.reload.head_pipeline).to eq(pipeline_1) expect(merge_request).to be_persisted end end context 'when there are no pipelines with the diff head sha' do let!(:pipeline_1) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) } let!(:pipeline_2) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) } it 'does not set the head pipeline' do merge_request = service.execute expect(merge_request.reload.head_pipeline).to be_nil expect(merge_request).to be_persisted end end end describe 'Pipelines for merge requests', :sidekiq_inline do before do stub_ci_pipeline_yaml_file(config) end context "when .gitlab-ci.yml has merge_requests keywords" do let(:config) do YAML.dump({ test: { stage: 'test', script: 'echo', only: ['merge_requests'] } }) end it 'creates a detached merge request pipeline and sets it as a head pipeline' do expect(merge_request).to be_persisted merge_request.reload expect(merge_request.pipelines_for_merge_request.count).to eq(1) expect(merge_request.actual_head_pipeline).to be_detached_merge_request_pipeline end context 'when merge request is submitted from forked project' do let(:target_project) { fork_project(project, nil, repository: true) } let(:opts) do { title: 'Awesome merge_request', source_branch: 'feature', target_branch: 'master', target_project_id: target_project.id } end before do target_project.add_developer(user2) target_project.add_maintainer(user) end it 'create detached merge request pipeline for fork merge request' do merge_request.reload head_pipeline = merge_request.actual_head_pipeline expect(head_pipeline).to be_detached_merge_request_pipeline expect(head_pipeline.project).to eq(target_project) end end context 'when there are no commits between source branch and target branch' do let(:opts) do { title: 'Awesome merge_request', description: 'please fix', source_branch: 'not-merged-branch', target_branch: 'master' } end it 'does not create a detached merge request pipeline' do expect(merge_request).to be_persisted merge_request.reload expect(merge_request.pipelines_for_merge_request.count).to eq(0) end end context "when branch pipeline was created before a merge request pipline has been created" do before do create( :ci_pipeline, project: merge_request.source_project, sha: merge_request.diff_head_sha, ref: merge_request.source_branch, tag: false ) merge_request end it 'sets the latest detached merge request pipeline as the head pipeline' do merge_request.reload expect(merge_request.actual_head_pipeline).to be_merge_request_event end end end context "when .gitlab-ci.yml does not have merge_requests keywords" do let(:config) do YAML.dump({ test: { stage: 'test', script: 'echo' } }) end it 'does not create a detached merge request pipeline' do expect(merge_request).to be_persisted merge_request.reload expect(merge_request.pipelines_for_merge_request.count).to eq(0) end end context 'when .gitlab-ci.yml is invalid' do let(:config) { 'invalid yaml file' } it 'persists a pipeline with config error' do expect(merge_request).to be_persisted merge_request.reload expect(merge_request.pipelines_for_merge_request.count).to eq(1) expect(merge_request.pipelines_for_merge_request.last).to be_failed expect(merge_request.pipelines_for_merge_request.last).to be_config_error end end end context 'after_save callback to store_mentions' do let(:labels) { create_pair(:label, project: project) } let(:milestone) { create(:milestone, project: project) } let(:req_opts) { { source_branch: 'feature', target_branch: 'master' } } context 'when mentionable attributes change' do let(:opts) { { title: 'Title', description: "Description with #{user.to_reference}" }.merge(req_opts) } it 'saves mentions' do expect_next_instance_of(MergeRequest) do |instance| expect(instance).to receive(:store_mentions!).and_call_original end expect(merge_request.user_mentions.count).to eq 1 end end context 'when mentionable attributes do not change' do let(:opts) { { label_ids: labels.map(&:id), milestone_id: milestone.id }.merge(req_opts) } it 'does not call store_mentions' do expect_next_instance_of(MergeRequest) do |instance| expect(instance).not_to receive(:store_mentions!).and_call_original end expect(merge_request.valid?).to be false expect(merge_request.user_mentions.count).to eq 0 end end context 'when save fails' do let(:opts) { { label_ids: labels.map(&:id), milestone_id: milestone.id } } it 'does not call store_mentions' do expect_next_instance_of(MergeRequest) do |instance| expect(instance).not_to receive(:store_mentions!).and_call_original end expect(merge_request.valid?).to be false end end end context 'with a milestone' do let(:milestone) { create(:milestone, project: project) } let(:opts) { { title: 'Awesome merge_request', source_branch: 'feature', target_branch: 'master', milestone_id: milestone.id } } it 'deletes the cache key for milestone merge request counter' do expect_next(Milestones::MergeRequestsCountService, milestone) .to receive(:delete_cache).and_call_original expect(merge_request).to be_persisted end end it_behaves_like 'reviewer_ids filter' do let(:execute) { service.execute } end context 'when called in a transaction' do it 'does not raise an error' do expect { MergeRequest.transaction { described_class.new(project: project, current_user: user, params: opts).execute } }.not_to raise_error end end end it_behaves_like 'issuable record that supports quick actions' do let(:default_params) do { source_branch: 'feature', target_branch: 'master' } end let(:issuable) { described_class.new(project: project, current_user: user, params: params).execute } end context 'Quick actions' do context 'with assignee and milestone in params and command' do let(:merge_request) { described_class.new(project: project, current_user: user, params: opts).execute } let(:milestone) { create(:milestone, project: project) } let(:opts) do { assignee_ids: create(:user).id, milestone_id: 1, title: 'Title', description: %(/assign @#{user2.username}\n/milestone %"#{milestone.name}"), source_branch: 'feature', target_branch: 'master' } end before do project.add_maintainer(user) project.add_maintainer(user2) end it 'assigns and sets milestone to issuable from command' do expect(merge_request).to be_persisted expect(merge_request.assignees).to eq([user2]) expect(merge_request.milestone).to eq(milestone) end end end context 'merge request create service' do context 'asssignee_id' do let(:user2) { create(:user) } before do project.add_maintainer(user) end it 'removes assignee_id when user id is invalid' do opts = { title: 'Title', description: 'Description', assignee_ids: [-1] } merge_request = described_class.new(project: project, current_user: user, params: opts).execute expect(merge_request.assignee_ids).to be_empty end it 'removes assignee_id when user id is 0' do opts = { title: 'Title', description: 'Description', assignee_ids: [0] } merge_request = described_class.new(project: project, current_user: user, params: opts).execute expect(merge_request.assignee_ids).to be_empty end it 'saves assignee when user id is valid' do project.add_maintainer(user2) opts = { title: 'Title', description: 'Description', assignee_ids: [user2.id] } merge_request = described_class.new(project: project, current_user: user, params: opts).execute expect(merge_request.assignees).to eq([user2]) end context 'when assignee is set' do let(:opts) do { title: 'Title', description: 'Description', assignee_ids: [user2.id], source_branch: 'feature', target_branch: 'master' } end before do project.add_maintainer(user2) end it 'invalidates open merge request counter for assignees when merge request is assigned' do described_class.new(project: project, current_user: user, params: opts).execute expect(user2.assigned_open_merge_requests_count).to eq 1 end it 'records the assignee assignment event', :sidekiq_inline do mr = described_class.new(project: project, current_user: user, params: opts).execute.reload expect(mr.assignment_events).to match([have_attributes(user_id: user2.id, action: 'add')]) end end context "when issuable feature is private" do before do project.project_feature.update!( issues_access_level: ProjectFeature::PRIVATE, merge_requests_access_level: ProjectFeature::PRIVATE ) end levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC] levels.each do |level| it "removes not authorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do project.update!(visibility_level: level) opts = { title: 'Title', description: 'Description', assignee_ids: [user2.id] } merge_request = described_class.new(project: project, current_user: user, params: opts).execute expect(merge_request.assignee_id).to be_nil end end end end end shared_examples 'when source and target projects are different' do let(:target_project) { fork_project(project, nil, repository: true) } let(:opts) do { title: 'Awesome merge_request', source_branch: 'feature', target_branch: 'master', target_project_id: target_project.id } end context 'when user can not access source project' do before do target_project.add_developer(user2) target_project.add_maintainer(user) end it 'raises an error' do expect { described_class.new(project: project, current_user: user, params: opts).execute } .to raise_error Gitlab::Access::AccessDeniedError end end context 'when user can not access target project' do before do target_project.add_developer(user2) target_project.add_maintainer(user) end it 'raises an error' do expect { described_class.new(project: project, current_user: user, params: opts).execute } .to raise_error Gitlab::Access::AccessDeniedError end end context 'when the user has access to both projects' do before do target_project.add_developer(user) project.add_developer(user) end it 'creates the merge request', :sidekiq_inline do merge_request = described_class.new(project: project, current_user: user, params: opts).execute expect(merge_request).to be_persisted expect(merge_request.iid).to be > 0 expect(merge_request.merge_request_diff).not_to be_empty end it 'does not create the merge request when the target project is archived' do target_project.update!(archived: true) expect { described_class.new(project: project, current_user: user, params: opts).execute } .to raise_error Gitlab::Access::AccessDeniedError end end end it_behaves_like 'when source and target projects are different' context 'when user sets source project id' do let(:another_project) { create(:project) } let(:opts) do { title: 'Awesome merge_request', source_branch: 'feature', target_branch: 'master', source_project_id: another_project.id } end before do project.add_developer(user2) project.add_maintainer(user) end it 'ignores source_project_id' do merge_request = described_class.new(project: project, current_user: user, params: opts).execute expect(merge_request.source_project_id).to eq(project.id) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class HandleAssigneesChangeService < MergeRequests::BaseService def async_execute(merge_request, old_assignees, options = {}) MergeRequests::HandleAssigneesChangeWorker .perform_async( merge_request.id, current_user.id, old_assignees.map(&:id), options.stringify_keys # see: https://gitlab.com/gitlab-com/gl-infra/scalability/-/issues/1090 ) end def execute(merge_request, old_assignees, options = {}) create_assignee_note(merge_request, old_assignees) notification_service.async.reassigned_merge_request(merge_request, current_user, old_assignees.to_a) Gitlab::ResourceEvents::AssignmentEventRecorder.new(parent: merge_request, old_assignees: old_assignees).record todo_service.reassigned_assignable(merge_request, current_user, old_assignees) new_assignees = merge_request.assignees - old_assignees merge_request_activity_counter.track_users_assigned_to_mr(users: new_assignees) merge_request_activity_counter.track_assignees_changed_action(user: current_user) execute_assignees_hooks(merge_request, old_assignees) if options['execute_hooks'] end private def execute_assignees_hooks(merge_request, old_assignees) execute_hooks( merge_request, 'update', old_associations: { assignees: old_assignees } ) end end end MergeRequests::HandleAssigneesChangeService.prepend_mod_with('MergeRequests::HandleAssigneesChangeService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::HandleAssigneesChangeService, feature_category: :code_review_workflow do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } let_it_be(:assignee) { create(:user) } let_it_be_with_reload(:merge_request) { create(:merge_request, author: user, source_project: project, assignees: [assignee]) } let_it_be(:old_assignees) { create_list(:user, 3) } let(:options) { {} } let(:service) { described_class.new(project: project, current_user: user) } before_all do project.add_maintainer(user) project.add_developer(assignee) old_assignees.each do |old_assignee| project.add_developer(old_assignee) end end describe '#async_execute' do def async_execute service.async_execute(merge_request, old_assignees, options) end it 'performs MergeRequests::HandleAssigneesChangeWorker asynchronously' do expect(MergeRequests::HandleAssigneesChangeWorker) .to receive(:perform_async) .with( merge_request.id, user.id, old_assignees.map(&:id), options ) async_execute end end describe '#execute' do def execute service.execute(merge_request, old_assignees, options) end let(:note) { merge_request.notes.system.last } let(:removed_note) { "unassigned #{old_assignees.map(&:to_reference).to_sentence}" } context 'when unassigning all users' do before do merge_request.update!(assignee_ids: []) end it 'creates assignee note' do execute expect(note).not_to be_nil expect(note.note).to eq removed_note end end it 'creates assignee note' do execute expect(note).not_to be_nil expect(note.note).to include "assigned to #{assignee.to_reference} and #{removed_note}" end it 'sends email notifications to old and new assignees', :mailer, :sidekiq_inline do perform_enqueued_jobs do execute end should_email(assignee) old_assignees.each do |old_assignee| should_email(old_assignee) end end it 'creates pending todo for assignee' do execute todo = assignee.todos.last expect(todo).to be_pending end it 'tracks users assigned event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_users_assigned_to_mr).once.with(users: [assignee]) execute end it 'tracks assignees changed event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_assignees_changed_action).once.with(user: user) execute end context 'when execute_hooks option is set to true' do let(:options) { { 'execute_hooks' => true } } it 'executes hooks and integrations' do expect(merge_request.project).to receive(:execute_hooks).with(anything, :merge_request_hooks) expect(merge_request.project).to receive(:execute_integrations).with(anything, :merge_request_hooks) expect(service).to receive(:enqueue_jira_connect_messages_for).with(merge_request) execute end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests class AddContextService < MergeRequests::BaseService def execute return error("You are not allowed to access the requested resource", 403) unless current_user&.can?(:update_merge_request, merge_request) return error("Context commits: #{duplicates} are already created", 400) unless duplicates.empty? return error("One or more context commits' sha is not valid.", 400) if commits.size != commit_ids.size context_commit_ids = [] MergeRequestContextCommit.transaction do context_commit_ids = MergeRequestContextCommit.bulk_insert(context_commit_rows, return_ids: true) MergeRequestContextCommitDiffFile.bulk_insert(diff_rows(context_commit_ids)) end commits end private def raw_repository project.repository.raw_repository end def merge_request params[:merge_request] end def commit_ids params[:commits] end def commits project.repository.commits_by(oids: commit_ids) end def context_commit_rows @context_commit_rows ||= build_context_commit_rows(merge_request.id, commits) end def diff_rows(context_commit_ids) @diff_rows ||= build_diff_rows(raw_repository, commits, context_commit_ids) end def encode_in_base64?(diff_text) (diff_text.encoding == Encoding::BINARY && !diff_text.ascii_only?) || diff_text.include?("\0") end def duplicates existing_oids = merge_request.merge_request_context_commits.map { |commit| commit.sha.to_s } existing_oids.select do |existing_oid| commit_ids.count { |commit_id| existing_oid.start_with?(commit_id) } > 0 end end def build_context_commit_rows(merge_request_id, commits) commits.map.with_index do |commit, index| # generate context commit information for given commit commit_hash = commit.to_hash.except(:parent_ids, :referenced_by) sha = Gitlab::Database::ShaAttribute.serialize(commit_hash.delete(:id)) commit_hash.merge( merge_request_id: merge_request_id, relative_order: index, sha: sha, authored_date: Gitlab::Database.sanitize_timestamp(commit_hash[:authored_date]), committed_date: Gitlab::Database.sanitize_timestamp(commit_hash[:committed_date]), trailers: Gitlab::Json.dump(commit_hash.fetch(:trailers, {})) ) end end def build_diff_rows(raw_repository, commits, context_commit_ids) diff_rows = [] diff_order = 0 commits.flat_map.with_index do |commit, index| commit_hash = commit.to_hash.except(:parent_ids, :referenced_by) sha = Gitlab::Database::ShaAttribute.serialize(commit_hash.delete(:id)) # generate context commit diff information for given commit diffs = commit.diffs compare = Gitlab::Git::Compare.new( raw_repository, diffs.diff_refs.start_sha, diffs.diff_refs.head_sha ) compare.diffs.map do |diff| diff_hash = diff.to_hash.merge( sha: sha, binary: false, merge_request_context_commit_id: context_commit_ids[index], relative_order: diff_order ) # Compatibility with old diffs created with Psych. diff_hash.tap do |hash| diff_text = hash[:diff] if encode_in_base64?(diff_text) hash[:binary] = true hash[:diff] = [diff_text].pack('m0') end end # Increase order for commit so when present the diffs we can use it to keep order diff_order += 1 diff_rows << diff_hash end end diff_rows end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::AddContextService, feature_category: :code_review_workflow do let(:project) { create(:project, :repository) } let(:admin) { create(:admin) } let(:merge_request) { create(:merge_request, source_project: project, target_project: project, author: admin) } let(:commits) { ["874797c3a73b60d2187ed6e2fcabd289ff75171e"] } let(:raw_repository) { project.repository.raw } subject(:service) { described_class.new(project: project, current_user: admin, params: { merge_request: merge_request, commits: commits }) } describe "#execute" do context "when admin mode is enabled", :enable_admin_mode do it "adds context commit" do service.execute expect(merge_request.merge_request_context_commit_diff_files.length).to eq(2) end end context "when admin mode is disabled" do it "doesn't add context commit" do subject.execute expect(merge_request.merge_request_context_commit_diff_files.length).to eq(0) end end context "when user doesn't have permission to update merge request" do let(:user) { create(:user) } let(:merge_request1) { create(:merge_request, source_project: project, author: user) } subject(:service) { described_class.new(project: project, current_user: user, params: { merge_request: merge_request, commits: commits }) } it "doesn't add context commit" do subject.execute expect(merge_request.merge_request_context_commit_diff_files.length).to eq(0) end end context "when the commits array is empty" do subject(:service) { described_class.new(project: project, current_user: admin, params: { merge_request: merge_request, commits: [] }) } it "doesn't add context commit" do subject.execute expect(merge_request.merge_request_context_commit_diff_files.length).to eq(0) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests # CreateRefService creates or overwrites a ref under "refs/merge-requests/" # with a commit for the merged result. class CreateRefService include Gitlab::Utils::StrongMemoize CreateRefError = Class.new(StandardError) def initialize( current_user:, merge_request:, target_ref:, first_parent_ref:, source_sha: nil ) @current_user = current_user @merge_request = merge_request @source_sha = source_sha @target_ref = target_ref @first_parent_ref = first_parent_ref @first_parent_sha = target_project.commit(first_parent_ref)&.sha end def execute # TODO: Update this message with the removal of FF merge_trains_create_ref_service and update tests # This is for compatibility with MergeToRefService during the rollout. return ServiceResponse.error(message: '3:Invalid merge source') unless first_parent_sha.present? result = { commit_sha: source_sha, # the SHA to be at HEAD of target_ref expected_old_oid: "", # the SHA we expect target_ref to be at prior to an update (an optimistic lock) source_sha: source_sha, # for pipeline.source_sha target_sha: first_parent_sha # for pipeline.target_sha } result = maybe_squash!(**result) result = maybe_rebase!(**result) result = maybe_merge!(**result) update_merge_request!(merge_request, result) ServiceResponse.success(payload: result) rescue CreateRefError => error ServiceResponse.error(message: error.message) end private attr_reader :current_user, :merge_request, :target_ref, :first_parent_ref, :first_parent_sha, :source_sha delegate :target_project, to: :merge_request delegate :repository, to: :target_project def maybe_squash!(commit_sha:, **rest) if merge_request.squash_on_merge? squash_result = MergeRequests::SquashService.new( merge_request: merge_request, current_user: current_user, commit_message: squash_commit_message ).execute raise CreateRefError, squash_result[:message] if squash_result[:status] == :error commit_sha = squash_result[:squash_sha] squash_commit_sha = commit_sha end # squash does not overwrite target_ref, so expected_old_oid remains the same rest.merge( commit_sha: commit_sha, squash_commit_sha: squash_commit_sha ).compact end def maybe_rebase!(commit_sha:, expected_old_oid:, squash_commit_sha: nil, **rest) if target_project.ff_merge_must_be_possible? commit_sha = safe_gitaly_operation do repository.rebase_to_ref( current_user, source_sha: commit_sha, target_ref: target_ref, first_parent_ref: first_parent_sha, expected_old_oid: expected_old_oid || "" ) end squash_commit_sha = commit_sha if squash_commit_sha # rebase rewrites commit SHAs after first_parent_sha expected_old_oid = commit_sha end rest.merge( commit_sha: commit_sha, squash_commit_sha: squash_commit_sha, expected_old_oid: expected_old_oid ).compact end def maybe_merge!(commit_sha:, expected_old_oid:, **rest) unless target_project.merge_requests_ff_only_enabled commit_sha = safe_gitaly_operation do repository.merge_to_ref( current_user, source_sha: commit_sha, target_ref: target_ref, message: merge_commit_message, first_parent_ref: first_parent_sha, branch: nil, expected_old_oid: expected_old_oid || "" ) end expected_old_oid = commit_sha merge_commit_sha = commit_sha end rest.merge( commit_sha: commit_sha, merge_commit_sha: merge_commit_sha, expected_old_oid: expected_old_oid ).compact end def update_merge_request!(merge_request, result) # overridden in EE end def safe_gitaly_operation yield rescue Gitlab::Git::PreReceiveError, Gitlab::Git::CommandError, ArgumentError => error raise CreateRefError, error.message end def squash_commit_message merge_request.merge_params['squash_commit_message'].presence || merge_request.default_squash_commit_message(user: current_user) end strong_memoize_attr :squash_commit_message def merge_commit_message merge_request.merge_params['commit_message'].presence || merge_request.default_merge_commit_message(user: current_user) end end end MergeRequests::CreateRefService.prepend_mod_with('MergeRequests::CreateRefService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::CreateRefService, feature_category: :merge_trains do using RSpec::Parameterized::TableSyntax describe '#execute' do let_it_be_with_reload(:project) { create(:project, :empty_repo) } let_it_be(:user) { project.creator } let_it_be(:first_parent_ref) { project.default_branch_or_main } let_it_be(:source_branch) { 'branch' } let(:target_ref) { "refs/merge-requests/#{merge_request.iid}/train" } let(:source_sha) { project.commit(source_branch).sha } let(:squash) { false } let(:default_commit_message) { merge_request.default_merge_commit_message(user: user) } let(:merge_request) do create( :merge_request, title: 'Merge request ref test', author: user, source_project: project, target_project: project, source_branch: source_branch, target_branch: first_parent_ref, squash: squash ) end subject(:result) do described_class.new( current_user: user, merge_request: merge_request, target_ref: target_ref, source_sha: source_sha, first_parent_ref: first_parent_ref ).execute end context 'when there is a user-caused gitaly error' do let(:source_sha) { '123' } it 'returns an error response' do expect(result[:status]).to eq :error end end context 'with valid inputs' do before_all do # ensure first_parent_ref is created before source_sha project.repository.create_file( user, 'README.md', '', message: 'Base parent commit 1', branch_name: first_parent_ref ) project.repository.create_branch(source_branch, first_parent_ref) # create two commits source_branch to test squashing project.repository.create_file( user, '.gitlab-ci.yml', '', message: 'Feature branch commit 1', branch_name: source_branch ) project.repository.create_file( user, '.gitignore', '', message: 'Feature branch commit 2', branch_name: source_branch ) # create an extra commit not present on source_branch project.repository.create_file( user, 'EXTRA', '', message: 'Base parent commit 2', branch_name: first_parent_ref ) end shared_examples_for 'writing with a merge commit' do it 'merges with a merge commit', :aggregate_failures do expect(result[:status]).to eq :success expect(result[:commit_sha]).to eq(project.repository.commit(target_ref).sha) expect(result[:source_sha]).to eq(project.repository.commit(source_branch).sha) expect(result[:target_sha]).to eq(project.repository.commit(first_parent_ref).sha) expect(result[:merge_commit_sha]).to be_present expect(result[:squash_commit_sha]).not_to be_present expect(project.repository.commits(target_ref, limit: 10, order: 'topo').map(&:message)).to( match( [ expected_merge_commit, 'Feature branch commit 2', 'Feature branch commit 1', 'Base parent commit 2', 'Base parent commit 1' ] ) ) end end shared_examples_for 'writing with a squash and merge commit' do it 'writes the squashed result', :aggregate_failures do expect(result[:status]).to eq :success expect(result[:commit_sha]).to eq(project.repository.commit(target_ref).sha) expect(result[:source_sha]).to eq(project.repository.commit(source_branch).sha) expect(result[:target_sha]).to eq(project.repository.commit(first_parent_ref).sha) expect(result[:merge_commit_sha]).to be_present expect(result[:squash_commit_sha]).to be_present expect(project.repository.commits(target_ref, limit: 10, order: 'topo').map(&:message)).to( match( [ expected_merge_commit, "#{merge_request.title}\n", 'Base parent commit 2', 'Base parent commit 1' ] ) ) end end shared_examples_for 'writing with a squash and no merge commit' do it 'writes the squashed result without a merge commit', :aggregate_failures do expect(result[:status]).to eq :success expect(result[:commit_sha]).to eq(project.repository.commit(target_ref).sha) expect(result[:source_sha]).to eq(project.repository.commit(source_branch).sha) expect(result[:target_sha]).to eq(project.repository.commit(first_parent_ref).sha) expect(result[:merge_commit_sha]).not_to be_present expect(result[:squash_commit_sha]).to be_present expect(project.repository.commits(target_ref, limit: 10, order: 'topo').map(&:message)).to( match( [ "#{merge_request.title}\n", 'Base parent commit 2', 'Base parent commit 1' ] ) ) end end shared_examples_for 'writing without a merge commit' do it 'writes the rebased merged result', :aggregate_failures do expect(result[:status]).to eq :success expect(result[:commit_sha]).to eq(project.repository.commit(target_ref).sha) expect(result[:source_sha]).to eq(project.repository.commit(source_branch).sha) expect(result[:target_sha]).to eq(project.repository.commit(first_parent_ref).sha) expect(result[:merge_commit_sha]).not_to be_present expect(result[:squash_commit_sha]).not_to be_present expect(project.repository.commits(target_ref, limit: 10, order: 'topo').map(&:message)).to( eq( [ 'Feature branch commit 2', 'Feature branch commit 1', 'Base parent commit 2', 'Base parent commit 1' ] ) ) end end shared_examples 'merge commits without squash' do context 'with a custom template' do let(:expected_merge_commit) { 'This is the merge commit' } # could also be default_commit_message before do project.project_setting.update!(merge_commit_template: expected_merge_commit) end it_behaves_like 'writing with a merge commit' end context 'with no custom template' do let(:expected_merge_commit) { default_commit_message } before do project.project_setting.update!(merge_commit_template: nil) end it_behaves_like 'writing with a merge commit' end end shared_examples 'merge commits with squash' do context 'when squash set' do let(:squash) { true } let(:expected_merge_commit) { merge_request.default_merge_commit_message(user: user) } before do project.project_setting.update!(merge_commit_template: 'This is the merge commit') end it_behaves_like 'writing with a squash and merge commit' end end context 'when the merge commit message is provided at time of merge' do let(:expected_merge_commit) { 'something custom' } before do merge_request.merge_params['commit_message'] = expected_merge_commit end it 'writes the merged result', :aggregate_failures do expect(result[:status]).to eq :success expect(project.repository.commits(target_ref, limit: 1, order: 'topo').map(&:message)).to( match([expected_merge_commit]) ) end context 'when squash set' do let(:squash) { true } it_behaves_like 'writing with a squash and merge commit' end end context 'when merged commit strategy' do include_examples 'merge commits without squash' include_examples 'merge commits with squash' end context 'when semi-linear merge strategy' do before do project.merge_method = :rebase_merge project.save! end include_examples 'merge commits without squash' include_examples 'merge commits with squash' context 'when the target ref changes between rebase and merge' do # this tests internal handling of expected_old_oid it 'returns an error', :aggregate_failures do expect_next_instance_of(described_class) do |instance| original = instance.method(:maybe_merge!) expect(instance).to receive(:maybe_merge!) do |*args, **kwargs| # Corrupt target_ref before the merge, simulating a race with # another instance of the service for the same MR. source_sha is # just an arbitrary valid commit that differs from what was just # written. project.repository.write_ref(target_ref, source_sha) original.call(*args, **kwargs) end end expect(result[:status]).to eq :error expect(result[:message]).to eq "9:Could not update #{target_ref}. Please refresh and try again." end end end context 'when fast-forward merge strategy' do before do project.merge_method = :ff project.save! end it_behaves_like 'writing without a merge commit' context 'when squash set' do let(:squash) { true } it_behaves_like 'writing with a squash and no merge commit' end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests # MergeService class # # Do git merge and in case of success # mark merge request as merged and execute all hooks and notifications # Executed when you do merge via GitLab UI # class MergeService < MergeRequests::MergeBaseService include Gitlab::Utils::StrongMemoize GENERIC_ERROR_MESSAGE = 'An error occurred while merging' LEASE_TIMEOUT = 15.minutes.to_i delegate :merge_jid, :state, to: :@merge_request def execute(merge_request, options = {}) return if merge_request.merged? return unless exclusive_lease(merge_request.id).try_obtain merge_strategy_class = options[:merge_strategy] || MergeRequests::MergeStrategies::FromSourceBranch @merge_strategy = merge_strategy_class.new(merge_request, current_user, merge_params: params, options: options) @merge_request = merge_request @options = options jid = merge_jid validate! merge_request.in_locked_state do if commit after_merge clean_merge_jid success end end log_info("Merge process finished on JID #{jid} with state #{state}") rescue MergeError, MergeRequests::MergeStrategies::StrategyError => e handle_merge_error(log_message: e.message, save_message_on_model: true) ensure exclusive_lease(merge_request.id).cancel end private def validate! authorization_check! error_check! validate_strategy! updated_check! end def authorization_check! unless @merge_request.can_be_merged_by?(current_user) raise_error('You are not allowed to merge this merge request') end end def validate_strategy! @merge_strategy.validate! end def updated_check! unless source_matches? raise_error('Branch has been updated since the merge was requested. '\ 'Please review the changes.') end end def commit log_info("Git merge started on JID #{merge_jid}") merge_result = try_merge { @merge_strategy.execute_git_merge! } commit_sha = merge_result[:commit_sha] raise_error(GENERIC_ERROR_MESSAGE) unless commit_sha log_info("Git merge finished on JID #{merge_jid} commit #{commit_sha}") new_merge_request_attributes = { merged_commit_sha: commit_sha, merge_commit_sha: merge_result[:merge_commit_sha], squash_commit_sha: merge_result[:squash_commit_sha] }.compact merge_request.update!(new_merge_request_attributes) if new_merge_request_attributes.present? commit_sha ensure merge_request.update_and_mark_in_progress_merge_commit_sha(nil) log_info("Merge request marked in progress") end def try_merge yield rescue Gitlab::Git::PreReceiveError => e raise MergeError, "Something went wrong during merge pre-receive hook. #{e.message}".strip rescue StandardError => e handle_merge_error(log_message: e.message) raise_error(GENERIC_ERROR_MESSAGE) end def after_merge log_info("Post merge started on JID #{merge_jid} with state #{state}") MergeRequests::PostMergeService.new(project: project, current_user: current_user).execute(merge_request) log_info("Post merge finished on JID #{merge_jid} with state #{state}") if delete_source_branch? MergeRequests::DeleteSourceBranchWorker.perform_async(@merge_request.id, @merge_request.source_branch_sha, branch_deletion_user.id) end merge_request_merge_param end def clean_merge_jid merge_request.update_column(:merge_jid, nil) end def branch_deletion_user @merge_request.force_remove_source_branch? ? @merge_request.author : current_user end # Verify again that the source branch can be removed, since branch may be protected, # or the source branch may have been updated, or the user may not have permission # def delete_source_branch? params.fetch('should_remove_source_branch', @merge_request.force_remove_source_branch?) && @merge_request.can_remove_source_branch?(branch_deletion_user) end def merge_request_merge_param if @merge_request.can_remove_source_branch?(branch_deletion_user) && !params.fetch('should_remove_source_branch', nil).nil? @merge_request.update(merge_params: @merge_request.merge_params.merge('should_remove_source_branch' => params['should_remove_source_branch'])) end end def handle_merge_error(log_message:, save_message_on_model: false) log_error("MergeService ERROR: #{merge_request_info}:#{merge_status} - #{log_message}") @merge_request.update(merge_error: log_message) if save_message_on_model end def log_info(message) payload = log_payload("#{merge_request_info} - #{message}") logger.info(**payload) end def log_error(message) payload = log_payload(message) logger.error(**payload) end def logger @logger ||= Gitlab::AppLogger end def log_payload(message) Gitlab::ApplicationContext.current.merge(merge_request_info: merge_request_info, message: message) end def merge_request_info @merge_request_info ||= merge_request.to_reference(full: true) end def merge_status @merge_status ||= @merge_request.merge_status end def source_matches? # params-keys are symbols coming from the controller, but when they get # loaded from the database they're strings params.with_indifferent_access[:sha] == merge_request.diff_head_sha end def exclusive_lease(merge_request_id) strong_memoize(:"exclusive_lease_#{merge_request_id}") do lease_key = ['merge_requests_merge_service', merge_request_id].join(':') Gitlab::ExclusiveLease.new(lease_key, timeout: LEASE_TIMEOUT) end end end end MergeRequests::MergeService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::MergeService, feature_category: :code_review_workflow do include ExclusiveLeaseHelpers let_it_be(:user) { create(:user) } let_it_be(:user2) { create(:user) } let(:merge_request) { create(:merge_request, :simple, author: user2, assignees: [user2]) } let(:project) { merge_request.project } before do project.add_maintainer(user) project.add_developer(user2) end describe '#execute' do let(:service) { described_class.new(project: project, current_user: user, params: merge_params) } let(:merge_params) do { commit_message: 'Awesome message', sha: merge_request.diff_head_sha } end let(:lease_key) { "merge_requests_merge_service:#{merge_request.id}" } let!(:lease) { stub_exclusive_lease(lease_key) } shared_examples 'with valid params' do before do allow(service).to receive(:execute_hooks) expect(merge_request).to receive(:update_and_mark_in_progress_merge_commit_sha).twice.and_call_original perform_enqueued_jobs do service.execute(merge_request) end end it { expect(merge_request).to be_valid } it { expect(merge_request).to be_merged } it 'does not update squash_commit_sha if it is not a squash' do expect(merge_request.squash_commit_sha).to be_nil end it 'sends email to user2 about merge of new merge_request' do email = ActionMailer::Base.deliveries.last expect(email.to.first).to eq(user2.email) expect(email.subject).to include(merge_request.title) end context 'note creation' do it 'creates resource state event about merge_request merge' do event = merge_request.resource_state_events.last expect(event.state).to eq('merged') end end end shared_examples 'squashing' do # A merge request with 5 commits let(:merge_request) do create( :merge_request, :simple, author: user2, assignees: [user2], squash: true, source_branch: 'improve/awesome', target_branch: 'fix' ) end let(:merge_params) do { commit_message: 'Merge commit message', squash_commit_message: 'Squash commit message', sha: merge_request.diff_head_sha } end before do allow(service).to receive(:execute_hooks) expect(merge_request).to receive(:update_and_mark_in_progress_merge_commit_sha).twice.and_call_original perform_enqueued_jobs do service.execute(merge_request) end end it 'merges the merge request with squashed commits' do expect(merge_request).to be_merged merge_commit = merge_request.merge_commit squash_commit = merge_request.merge_commit.parents.last expect(merge_commit.message).to eq('Merge commit message') expect(squash_commit.message).to eq("Squash commit message\n") end it 'persists squash_commit_sha' do squash_commit = merge_request.merge_commit.parents.last expect(merge_request.squash_commit_sha).to eq(squash_commit.id) end end context 'when merge strategy is merge commit' do it 'persists merge_commit_sha and merged_commit_sha and nullifies in_progress_merge_commit_sha' do service.execute(merge_request) expect(merge_request.merge_commit_sha).not_to be_nil expect(merge_request.merged_commit_sha).to eq merge_request.merge_commit_sha expect(merge_request.in_progress_merge_commit_sha).to be_nil end it_behaves_like 'with valid params' it_behaves_like 'squashing' end context 'when merge strategy is fast forward' do before do project.update!(merge_requests_ff_only_enabled: true) end let(:merge_request) do create( :merge_request, source_branch: 'flatten-dir', target_branch: 'improve/awesome', assignees: [user2], author: create(:user) ) end it 'does not create merge_commit_sha, but persists merged_commit_sha and nullifies in_progress_merge_commit_sha' do service.execute(merge_request) expect(merge_request.merge_commit_sha).to be_nil expect(merge_request.merged_commit_sha).not_to be_nil expect(merge_request.merged_commit_sha).to eq merge_request.diff_head_sha expect(merge_request.in_progress_merge_commit_sha).to be_nil end it_behaves_like 'with valid params' it 'updates squash_commit_sha and merged_commit_sha if it is a squash' do expect(merge_request).to receive(:update_and_mark_in_progress_merge_commit_sha).twice.and_call_original merge_request.update!(squash: true) expect { service.execute(merge_request) } .to change { merge_request.squash_commit_sha } .from(nil) expect(merge_request.merge_commit_sha).to be_nil expect(merge_request.merged_commit_sha).to eq merge_request.squash_commit_sha expect(merge_request.in_progress_merge_commit_sha).to be_nil end end context 'running the service once' do let(:ref) { merge_request.to_reference(full: true) } let(:jid) { SecureRandom.hex } let(:messages) do [ /#{ref} - Git merge started on JID #{jid}/, /#{ref} - Git merge finished on JID #{jid}/, /#{ref} - Post merge started on JID #{jid}/, /#{ref} - Post merge finished on JID #{jid}/, /#{ref} - Merge process finished on JID #{jid}/ ] end before do merge_request.update!(merge_jid: jid) ::Gitlab::ApplicationContext.push(caller_id: 'MergeWorker') end it 'logs status messages' do allow(Gitlab::AppLogger).to receive(:info).and_call_original messages.each do |message| expect(Gitlab::AppLogger).to receive(:info).with( hash_including( 'meta.caller_id' => 'MergeWorker', message: message, merge_request_info: ref ) ).and_call_original end service.execute(merge_request) end end context 'running the service multiple time' do it 'is idempotent' do 2.times { service.execute(merge_request) } expect(merge_request.merge_error).to be_falsey expect(merge_request).to be_valid expect(merge_request).to be_merged commit_messages = project.repository.commits('master', limit: 2).map(&:message) expect(commit_messages.uniq.size).to eq(2) expect(merge_request.in_progress_merge_commit_sha).to be_nil end end context 'when an invalid sha is passed' do let(:merge_request) do create( :merge_request, :simple, author: user2, assignees: [user2], squash: true, source_branch: 'improve/awesome', target_branch: 'fix' ) end let(:merge_params) do { sha: merge_request.commits.second.sha } end it 'does not merge the MR' do service.execute(merge_request) expect(merge_request).not_to be_merged expect(merge_request.merge_error).to match(/Branch has been updated/) end end context 'when the `sha` param is missing' do let(:merge_params) { {} } it 'returns the error' do merge_error = 'Branch has been updated since the merge was requested. '\ 'Please review the changes.' expect { service.execute(merge_request) } .to change { merge_request.merge_error } .from(nil).to(merge_error) end end context 'closes related issues' do before do allow(project).to receive(:default_branch).and_return(merge_request.target_branch) end it 'closes GitLab issue tracker issues', :sidekiq_inline do issue = create :issue, project: project commit = double('commit', safe_message: "Fixes #{issue.to_reference}", date: Time.current, authored_date: Time.current) allow(merge_request).to receive(:commits).and_return([commit]) merge_request.cache_merge_request_closes_issues! service.execute(merge_request) expect(issue.reload.closed?).to be_truthy end context 'with Jira integration' do include JiraIntegrationHelpers let(:jira_tracker) { project.create_jira_integration } let(:jira_issue) { ExternalIssue.new('JIRA-123', project) } let(:commit) { double('commit', safe_message: "Fixes #{jira_issue.to_reference}") } before do stub_jira_integration_test project.update!(has_external_issue_tracker: true) jira_integration_settings stub_jira_urls(jira_issue.id) allow(merge_request).to receive(:commits).and_return([commit]) end it 'closes issues on Jira issue tracker' do jira_issue = ExternalIssue.new('JIRA-123', project) stub_jira_urls(jira_issue) commit = double('commit', safe_message: "Fixes #{jira_issue.to_reference}") allow(merge_request).to receive(:commits).and_return([commit]) expect_any_instance_of(Integrations::Jira).to receive(:close_issue).with(merge_request, jira_issue, user).once service.execute(merge_request) end context 'wrong issue markdown' do it 'does not close issues on Jira issue tracker' do jira_issue = ExternalIssue.new('#JIRA-123', project) stub_jira_urls(jira_issue) commit = double('commit', safe_message: "Fixes #{jira_issue.to_reference}") allow(merge_request).to receive(:commits).and_return([commit]) expect_any_instance_of(Integrations::Jira).not_to receive(:close_issue) service.execute(merge_request) end end end end context 'closes related todos' do let(:merge_request) { create(:merge_request, assignees: [user], author: user) } let(:project) { merge_request.project } let!(:todo) do create(:todo, :assigned, project: project, author: user, user: user, target: merge_request) end before do allow(service).to receive(:execute_hooks) perform_enqueued_jobs do service.execute(merge_request) todo.reload end end it { expect(todo).to be_done } end context 'source branch removal' do context 'when the source branch is protected' do let(:service) do described_class.new(project: project, current_user: user, params: merge_params.merge('should_remove_source_branch' => true)) end before do create(:protected_branch, project: project, name: merge_request.source_branch) end it 'does not delete the source branch' do expect(::Branches::DeleteService).not_to receive(:new) service.execute(merge_request) end end context 'when the source branch is the default branch' do let(:service) do described_class.new(project: project, current_user: user, params: merge_params.merge('should_remove_source_branch' => true)) end before do allow(project).to receive(:root_ref?).with(merge_request.source_branch).and_return(true) end it 'does not delete the source branch' do expect(::Branches::DeleteService).not_to receive(:new) service.execute(merge_request) end end context 'when the source branch can be removed' do context 'when MR author set the source branch to be removed' do before do merge_request.update_attribute(:merge_params, { 'force_remove_source_branch' => '1' }) end # Not a real use case. When a merger merges a MR , merge param 'should_remove_source_branch' is defined it 'removes the source branch using the author user' do expect(::MergeRequests::DeleteSourceBranchWorker).to receive(:perform_async).with(merge_request.id, merge_request.source_branch_sha, merge_request.author.id) service.execute(merge_request) expect(merge_request.reload.should_remove_source_branch?).to be nil end context 'when the merger set the source branch not to be removed' do let(:service) { described_class.new(project: project, current_user: user, params: merge_params.merge('should_remove_source_branch' => false)) } it 'does not delete the source branch' do expect(::MergeRequests::DeleteSourceBranchWorker).not_to receive(:perform_async) service.execute(merge_request) expect(merge_request.reload.should_remove_source_branch?).to be false end end end context 'when MR merger set the source branch to be removed' do let(:service) do described_class.new(project: project, current_user: user, params: merge_params.merge('should_remove_source_branch' => true)) end it 'removes the source branch using the current user' do expect(::MergeRequests::DeleteSourceBranchWorker).to receive(:perform_async).with(merge_request.id, merge_request.source_branch_sha, user.id) service.execute(merge_request) expect(merge_request.reload.should_remove_source_branch?).to be true end end end end context 'error handling' do before do allow(Gitlab::AppLogger).to receive(:error) end context 'when source is missing' do it 'logs and saves error' do allow(merge_request).to receive(:diff_head_sha) { nil } error_message = 'No source for merge' service.execute(merge_request) expect(merge_request.merge_error).to eq(error_message) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end end it 'logs and saves error if there is an exception' do error_message = 'error message' allow_next_instance_of(MergeRequests::MergeStrategies::FromSourceBranch) do |strategy| allow(strategy).to receive(:execute_git_merge!).and_raise(error_message) end service.execute(merge_request) expect(merge_request.merge_error).to eq(described_class::GENERIC_ERROR_MESSAGE) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end it 'logs and saves error if user is not authorized' do stub_exclusive_lease unauthorized_user = create(:user) project.add_reporter(unauthorized_user) service = described_class.new(project: project, current_user: unauthorized_user) service.execute(merge_request) expect(merge_request.merge_error) .to eq('You are not allowed to merge this merge request') end it 'logs and saves error if there is an PreReceiveError exception' do error_message = 'error message' allow_next_instance_of(MergeRequests::MergeStrategies::FromSourceBranch) do |strategy| allow(strategy).to receive(:execute_git_merge!).and_raise(Gitlab::Git::PreReceiveError, "GitLab: #{error_message}") end service.execute(merge_request) expect(merge_request.merge_error).to include('Something went wrong during merge pre-receive hook') expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end it 'logs and saves error if commit is not created' do allow_any_instance_of(Repository).to receive(:merge).and_return(false) allow(service).to receive(:execute_hooks) service.execute(merge_request) expect(merge_request).to be_open expect(merge_request.merge_commit_sha).to be_nil expect(merge_request.merge_error).to include(described_class::GENERIC_ERROR_MESSAGE) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(described_class::GENERIC_ERROR_MESSAGE) ) ) end context 'when squashing is required' do before do merge_request.update!(source_branch: 'master', target_branch: 'feature') merge_request.target_project.project_setting.squash_always! end it 'raises an error if squashing is not done' do error_message = 'requires squashing commits' service.execute(merge_request) expect(merge_request).to be_open expect(merge_request.merge_commit_sha).to be_nil expect(merge_request.squash_commit_sha).to be_nil expect(merge_request.merge_error).to include(error_message) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end end context 'when squashing' do before do merge_request.update!(source_branch: 'master', target_branch: 'feature') end it 'logs and saves error if there is an error when squashing' do error_message = 'Squashing failed: Squash the commits locally, resolve any conflicts, then push the branch.' allow_any_instance_of(MergeRequests::SquashService).to receive(:squash!).and_return(nil) merge_request.update!(squash: true) service.execute(merge_request) expect(merge_request).to be_open expect(merge_request.merge_commit_sha).to be_nil expect(merge_request.squash_commit_sha).to be_nil expect(merge_request.merge_error).to include(error_message) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end it 'logs and saves error if there is an PreReceiveError exception' do error_message = 'error message' allow_next_instance_of(MergeRequests::MergeStrategies::FromSourceBranch) do |strategy| allow(strategy).to receive(:execute_git_merge!).and_raise(Gitlab::Git::PreReceiveError, "GitLab: #{error_message}") end merge_request.update!(squash: true) service.execute(merge_request) expect(merge_request).to be_open expect(merge_request.merge_commit_sha).to be_nil expect(merge_request.squash_commit_sha).to be_nil expect(merge_request.merge_error).to include('Something went wrong during merge pre-receive hook') expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end context 'when fast-forward merge is not allowed' do before do allow_any_instance_of(Repository).to receive(:ancestor?).and_return(nil) end %w[semi-linear ff].each do |merge_method| it "logs and saves error if merge is #{merge_method} only" do merge_method = 'rebase_merge' if merge_method == 'semi-linear' merge_request.project.update!(merge_method: merge_method) error_message = 'Only fast-forward merge is allowed for your project. Please update your source branch' allow(service).to receive(:execute_hooks) expect(lease).to receive(:cancel) service.execute(merge_request) expect(merge_request).to be_open expect(merge_request.merge_commit_sha).to be_nil expect(merge_request.squash_commit_sha).to be_nil expect(merge_request.merge_error).to include(error_message) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end end end end context 'when not mergeable' do let!(:error_message) { 'Merge request is not mergeable' } context 'with failing CI' do before do allow(merge_request.project).to receive(:only_allow_merge_if_pipeline_succeeds) { true } allow(merge_request).to receive(:mergeable_ci_state?) { false } end it 'logs and saves error' do service.execute(merge_request) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end end context 'with unresolved discussions' do before do allow(merge_request.project).to receive(:only_allow_merge_if_all_discussions_are_resolved) { true } allow(merge_request).to receive(:mergeable_discussions_state?) { false } end it 'logs and saves error' do service.execute(merge_request) expect(Gitlab::AppLogger).to have_received(:error).with( hash_including( merge_request_info: merge_request.to_reference(full: true), message: a_string_matching(error_message) ) ) end context 'when passing `skip_discussions_check: true` as `options` parameter' do it 'merges the merge request' do service.execute(merge_request, skip_discussions_check: true) expect(merge_request).to be_valid expect(merge_request).to be_merged end end end end context 'when passing `check_mergeability_retry_lease: true` as `options` parameter' do it 'call mergeable? with check_mergeability_retry_lease' do expect(merge_request).to receive(:mergeable?).with(hash_including(check_mergeability_retry_lease: true)).and_call_original service.execute(merge_request, check_mergeability_retry_lease: true) end end end context 'when the other sidekiq worker has already been running' do before do stub_exclusive_lease_taken(lease_key) end it 'does not execute service' do expect(service).not_to receive(:commit) service.execute(merge_request) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class RunChecksService include Gitlab::Utils::StrongMemoize def initialize(merge_request:, params:) @merge_request = merge_request @params = params end def execute(checks, execute_all: false) @results = checks.each_with_object([]) do |check_class, result_hash| check = check_class.new(merge_request: merge_request, params: params) next if check.skip? check_result = logger.instrument(mergeability_name: check_class.to_s.demodulize.underscore) do run_check(check) end result_hash << check_result break result_hash if check_result.failed? && !execute_all end logger.commit return ServiceResponse.success(payload: { results: results }) if all_results_success? ServiceResponse.error( message: 'Checks failed.', payload: { results: results, failed_check: failed_check } ) end private attr_reader :merge_request, :params, :results def run_check(check) return check.execute unless check.cacheable? cached_result = cached_results.read(merge_check: check) return cached_result if cached_result.respond_to?(:status) check.execute.tap do |result| cached_results.write(merge_check: check, result_hash: result.to_hash) end end def cached_results strong_memoize(:cached_results) do Gitlab::MergeRequests::Mergeability::ResultsStore.new(merge_request: merge_request) end end def logger strong_memoize(:logger) do MergeRequests::Mergeability::Logger.new(merge_request: merge_request) end end def all_results_success? results.none?(&:failed?) end def failed_check # NOTE: the identifier could be string when we retrieve it from the cache # so let's make sure we always return symbols here. results.find(&:failed?)&.payload&.fetch(:identifier)&.to_sym end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::RunChecksService, :clean_gitlab_redis_cache, feature_category: :code_review_workflow do let(:checks) { MergeRequest.all_mergeability_checks } let(:execute_all) { false } subject(:run_checks) { described_class.new(merge_request: merge_request, params: {}) } describe '#execute' do subject(:execute) { run_checks.execute(checks, execute_all: execute_all) } let_it_be(:merge_request) { create(:merge_request) } let(:params) { {} } let(:success_result) { Gitlab::MergeRequests::Mergeability::CheckResult.success } shared_examples 'checks are all executed' do context 'when all checks are set to be executed' do let(:execute_all) { true } specify do result = execute expect(result.success?).to eq(success?) expect(result.payload[:results].count).to eq(expected_count) end end end context 'when every check is skipped', :eager_load do before do MergeRequests::Mergeability::CheckBaseService.subclasses.each do |subclass| allow_next_instance_of(subclass) do |service| allow(service).to receive(:skip?).and_return(true) end end end it 'is still a success' do expect(execute.success?).to eq(true) end it_behaves_like 'checks are all executed' do let(:success?) { true } let(:expected_count) { 0 } end end context 'when a check is skipped' do before do checks.each do |check| allow_next_instance_of(check) do |service| allow(service).to receive(:skip?).and_return(false) allow(service).to receive(:execute).and_return(success_result) end end allow_next_instance_of(MergeRequests::Mergeability::CheckCiStatusService) do |service| allow(service).to receive(:skip?).and_return(true) end end it 'does not execute the check' do expect_next_instance_of(MergeRequests::Mergeability::CheckCiStatusService) do |service| expect(service).to receive(:skip?).and_return(true) expect(service).not_to receive(:execute) end expect(execute.success?).to eq(true) end it_behaves_like 'checks are all executed' do let(:success?) { true } let(:expected_count) { checks.count - 1 } end context 'when one check fails' do let(:failed_result) { Gitlab::MergeRequests::Mergeability::CheckResult.failed(payload: { identifier: 'failed' }) } before do allow_next_instance_of(MergeRequests::Mergeability::CheckOpenStatusService) do |service| allow(service).to receive(:skip?).and_return(false) allow(service).to receive(:execute).and_return(failed_result) end end it 'returns the failed check' do result = execute expect(result.success?).to eq(false) expect(execute.payload[:failed_check]).to eq(:failed) end it_behaves_like 'checks are all executed' do let(:success?) { false } let(:expected_count) { checks.count - 1 } end end context 'when one check is inactive' do let(:inactive_result) { Gitlab::MergeRequests::Mergeability::CheckResult.inactive } before do allow_next_instance_of(MergeRequests::Mergeability::CheckOpenStatusService) do |service| allow(service).to receive(:skip?).and_return(false) allow(service).to receive(:execute).and_return(inactive_result) end end it 'is still a success' do expect(execute.success?).to eq(true) end it_behaves_like 'checks are all executed' do let(:success?) { true } let(:expected_count) { checks.count - 1 } end end end context 'when a check is not skipped' do let(:cacheable) { true } let(:merge_check) { instance_double(MergeRequests::Mergeability::CheckCiStatusService) } before do checks.each do |check| allow_next_instance_of(check) do |service| allow(service).to receive(:skip?).and_return(true) end end expect(MergeRequests::Mergeability::CheckCiStatusService).to receive(:new).and_return(merge_check) expect(merge_check).to receive(:skip?).and_return(false) allow(merge_check).to receive(:cacheable?).and_return(cacheable) allow(merge_check).to receive(:execute).and_return(success_result) end context 'when the check is cacheable' do context 'when the check is cached' do before do expect_next_instance_of(Gitlab::MergeRequests::Mergeability::ResultsStore) do |service| expect(service).to receive(:read).with(merge_check: merge_check).and_return(success_result) end end it 'returns the cached result' do expect_next_instance_of(MergeRequests::Mergeability::Logger, merge_request: merge_request) do |logger| expect(logger).to receive(:instrument).with(mergeability_name: 'check_ci_status_service').and_call_original expect(logger).to receive(:commit) end expect(execute.success?).to eq(true) end it_behaves_like 'checks are all executed' do let(:success?) { true } let(:expected_count) { 1 } end end context 'when the check is not cached' do before do expect_next_instance_of(Gitlab::MergeRequests::Mergeability::ResultsStore) do |service| expect(service).to receive(:read).with(merge_check: merge_check).and_return(nil) expect(service).to receive(:write).with(merge_check: merge_check, result_hash: success_result.to_hash).and_return(true) end end it 'writes and returns the result' do expect_next_instance_of(MergeRequests::Mergeability::Logger, merge_request: merge_request) do |logger| expect(logger).to receive(:instrument).with(mergeability_name: 'check_ci_status_service').and_call_original expect(logger).to receive(:commit) end expect(execute.success?).to eq(true) end it_behaves_like 'checks are all executed' do let(:success?) { true } let(:expected_count) { 1 } end end end context 'when check is not cacheable' do let(:cacheable) { false } it 'does not call the results store' do expect(Gitlab::MergeRequests::Mergeability::ResultsStore).not_to receive(:new) expect(execute.success?).to eq(true) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class DetailedMergeStatusService include ::Gitlab::Utils::StrongMemoize def initialize(merge_request:) @merge_request = merge_request end def execute return :preparing if preparing? return :checking if checking? return :unchecked if unchecked? if check_results.success? # If everything else is mergeable, but CI is not, the frontend expects two potential states to be returned # See discussion: gitlab.com/gitlab-org/gitlab/-/merge_requests/96778#note_1093063523 if check_ci_results.failed? ci_check_failed_check else :mergeable end else check_results.payload[:failed_check] end end private attr_reader :merge_request, :checks, :ci_check def preparing? merge_request.preparing? && !merge_request.merge_request_diff.persisted? end def checking? merge_request.cannot_be_merged_rechecking? || merge_request.checking? end def unchecked? merge_request.unchecked? end def check_results strong_memoize(:check_results) do merge_request .execute_merge_checks( MergeRequest.mergeable_state_checks, params: { skip_ci_check: true } ) end end def check_ci_results strong_memoize(:check_ci_results) do ::MergeRequests::Mergeability::CheckCiStatusService.new(merge_request: merge_request, params: {}).execute end end def ci_check_failed_check if merge_request.actual_head_pipeline&.active? :ci_still_running else check_ci_results.payload.fetch(:identifier) end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::MergeRequests::Mergeability::DetailedMergeStatusService, feature_category: :code_review_workflow do subject(:detailed_merge_status) { described_class.new(merge_request: merge_request).execute } context 'when merge status is cannot_be_merged_rechecking' do let(:merge_request) { create(:merge_request, merge_status: :cannot_be_merged_rechecking) } it 'returns :checking' do expect(detailed_merge_status).to eq(:checking) end end context 'when merge status is preparing' do let(:merge_request) { create(:merge_request, merge_status: :preparing) } it 'returns :checking' do allow(merge_request.merge_request_diff).to receive(:persisted?).and_return(false) expect(detailed_merge_status).to eq(:preparing) end end context 'when merge status is preparing and merge request diff is persisted' do let(:merge_request) { create(:merge_request, merge_status: :preparing) } it 'returns :checking' do allow(merge_request.merge_request_diff).to receive(:persisted?).and_return(true) expect(detailed_merge_status).to eq(:mergeable) end end context 'when merge status is checking' do let(:merge_request) { create(:merge_request, merge_status: :checking) } it 'returns :checking' do expect(detailed_merge_status).to eq(:checking) end end context 'when merge status is unchecked' do let(:merge_request) { create(:merge_request, merge_status: :unchecked) } it 'returns :unchecked' do expect(detailed_merge_status).to eq(:unchecked) end end context 'when merge checks are a success' do let(:merge_request) { create(:merge_request) } it 'returns :mergeable' do expect(detailed_merge_status).to eq(:mergeable) end end context 'when merge status have a failure' do let(:merge_request) { create(:merge_request) } before do merge_request.close! end it 'returns the failed check' do expect(detailed_merge_status).to eq(:not_open) end end context 'when all but the ci check fails' do let(:merge_request) { create(:merge_request) } before do merge_request.project.update!(only_allow_merge_if_pipeline_succeeds: true) end context 'when pipeline does not exist' do it 'returns the failed check' do expect(detailed_merge_status).to eq(:ci_must_pass) end end context 'when pipeline exists' do before do create( :ci_pipeline, ci_status, merge_request: merge_request, project: merge_request.project, sha: merge_request.source_branch_sha, head_pipeline_of: merge_request ) end context 'when the pipeline is running' do let(:ci_status) { :running } it 'returns the failed check' do expect(detailed_merge_status).to eq(:ci_still_running) end end context 'when the pipeline is pending' do let(:ci_status) { :pending } it { expect(detailed_merge_status).to eq(:ci_still_running) } end context 'when the pipeline is not running' do let(:ci_status) { :failed } it 'returns the failed check' do expect(detailed_merge_status).to eq(:ci_must_pass) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckDraftStatusService < CheckBaseService identifier :draft_status description 'Checks whether the merge request is draft' def execute if merge_request.draft? failure else success end end def skip? params[:skip_draft_check].present? end def cacheable? false end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckDraftStatusService, feature_category: :code_review_workflow do subject(:check_draft_status) { described_class.new(merge_request: merge_request, params: params) } let_it_be(:merge_request) { build(:merge_request) } let(:params) { { skip_draft_check: skip_check } } let(:skip_check) { false } it_behaves_like 'mergeability check service', :draft_status, 'Checks whether the merge request is draft' describe '#execute' do let(:result) { check_draft_status.execute } before do expect(merge_request).to receive(:draft?).and_return(draft) end context 'when the merge request is a draft' do let(:draft) { true } it 'returns a check result with status failed' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::FAILED_STATUS expect(result.payload[:identifier]).to eq(:draft_status) end end context 'when the merge request is not a draft' do let(:draft) { false } it 'returns a check result with status success' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::SUCCESS_STATUS end end end describe '#skip?' do context 'when skip check param is true' do let(:skip_check) { true } it 'returns true' do expect(check_draft_status.skip?).to eq true end end context 'when skip check param is false' do let(:skip_check) { false } it 'returns false' do expect(check_draft_status.skip?).to eq false end end end describe '#cacheable?' do it 'returns false' do expect(check_draft_status.cacheable?).to eq false end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckRebaseStatusService < CheckBaseService identifier :need_rebase description 'Checks whether the merge request needs to be rebased' def execute return inactive unless merge_request.project.ff_merge_must_be_possible? if merge_request.should_be_rebased? failure else success end end def skip? params[:skip_rebase_check].present? end def cacheable? false end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckRebaseStatusService, feature_category: :code_review_workflow do subject(:check_rebase_status) { described_class.new(merge_request: merge_request, params: params) } let_it_be(:project) { build(:project) } let_it_be(:merge_request) { build(:merge_request, source_project: project) } let(:params) { { skip_rebase_check: skip_check } } let(:skip_check) { false } it_behaves_like 'mergeability check service', :need_rebase, 'Checks whether the merge request needs to be rebased' describe '#execute' do let(:result) { check_rebase_status.execute } before do allow(project) .to receive(:ff_merge_must_be_possible?) .and_return(ff_merge_must_be_possible?) end context 'when ff_merge_must_be_possible is true' do let(:ff_merge_must_be_possible?) { true } before do allow(merge_request).to receive(:should_be_rebased?).and_return(should_be_rebased) end context 'when the merge request should be rebased' do let(:should_be_rebased) { true } it 'returns a check result with status failed' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::FAILED_STATUS expect(result.payload[:identifier]).to eq(:need_rebase) end end context 'when the merge request should not be rebased' do let(:should_be_rebased) { false } it 'returns a check result with status success' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::SUCCESS_STATUS end end end context 'when ff_merge_must_be_possible is false' do let(:ff_merge_must_be_possible?) { false } it 'returns a check result with inactive status' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::INACTIVE_STATUS end end end describe '#skip?' do context 'when skip check is true' do let(:skip_check) { true } it 'returns true' do expect(check_rebase_status.skip?).to eq true end end context 'when skip check is false' do let(:skip_check) { false } it 'returns false' do expect(check_rebase_status.skip?).to eq false end end end describe '#cacheable?' do it 'returns false' do expect(check_rebase_status.cacheable?).to eq false end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class Logger include Gitlab::Utils::StrongMemoize def initialize(merge_request:, destination: Gitlab::AppJsonLogger) @destination = destination @merge_request = merge_request end def commit commit_logs end def instrument(mergeability_name:) raise ArgumentError, 'block not given' unless block_given? op_start_db_counters = current_db_counter_payload op_started_at = current_monotonic_time result = yield observe_result(mergeability_name, result) observe("mergeability.#{mergeability_name}.duration_s", current_monotonic_time - op_started_at) observe_sql_counters(mergeability_name, op_start_db_counters, current_db_counter_payload) result end private attr_reader :destination, :merge_request, :stored_result def observe_result(name, result) return unless result.respond_to?(:success?) observe("mergeability.#{name}.successful", result.success?) end def observe(name, value) observations[name.to_s].push(value) end def commit_logs attributes = Gitlab::ApplicationContext.current.merge({ mergeability_project_id: merge_request.project.id }) attributes[:mergeability_merge_request_id] = merge_request.id attributes.merge!(observations_hash) attributes.compact! attributes.stringify_keys! destination.info(attributes) end def observations_hash transformed = observations.transform_values do |values| next if values.empty? { 'values' => values } end.compact transformed.each_with_object({}) do |key, hash| key[1].each { |k, v| hash["#{key[0]}.#{k}"] = v } end end def observations strong_memoize(:observations) do Hash.new { |hash, key| hash[key] = [] } end end def observe_sql_counters(name, start_db_counters, end_db_counters) end_db_counters.each do |key, value| result = value - start_db_counters.fetch(key, 0) next if result == 0 observe("mergeability.#{name}.#{key}", result) end end def current_db_counter_payload ::Gitlab::Metrics::Subscribers::ActiveRecord.db_counter_payload end def current_monotonic_time ::Gitlab::Metrics::System.monotonic_time end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::Logger, :request_store, feature_category: :code_review_workflow do let_it_be(:merge_request) { create(:merge_request) } subject(:logger) { described_class.new(merge_request: merge_request) } let(:caller_id) { 'a' } before do allow(Gitlab::ApplicationContext).to receive(:current_context_attribute).with(:caller_id).and_return(caller_id) end def loggable_data(**extras) { 'mergeability.expensive_operation.duration_s.values' => a_kind_of(Array), "mergeability_merge_request_id" => merge_request.id, "correlation_id" => a_kind_of(String), "mergeability_project_id" => merge_request.project.id }.merge(extras) end describe '#instrument' do let(:operation_count) { 1 } context 'when enabled' do it "returns the block's value" do expect(logger.instrument(mergeability_name: :expensive_operation) { 123 }).to eq(123) end it 'records durations of instrumented operations' do expect_next_instance_of(Gitlab::AppJsonLogger) do |app_logger| expect(app_logger).to receive(:info).with(match(a_hash_including(loggable_data))) end expect(logger.instrument(mergeability_name: :expensive_operation) { 123 }).to eq(123) logger.commit end context 'when block value responds to #success?' do let(:success?) { true } let(:check_result) { instance_double(Gitlab::MergeRequests::Mergeability::CheckResult, success?: success?) } let(:extra_data) do { 'mergeability.expensive_operation.successful.values' => [success?] } end shared_examples_for 'success state logger' do it 'records operation success state' do expect_next_instance_of(Gitlab::AppJsonLogger) do |app_logger| expect(app_logger).to receive(:info).with(match(a_hash_including(loggable_data(**extra_data)))) end expect(logger.instrument(mergeability_name: :expensive_operation) { check_result }).to eq(check_result) logger.commit end end it_behaves_like 'success state logger' context 'when not successful' do let(:success?) { false } it_behaves_like 'success state logger' end end context 'with multiple observations' do let(:operation_count) { 2 } it 'records durations of instrumented operations' do expect_next_instance_of(Gitlab::AppJsonLogger) do |app_logger| expect(app_logger).to receive(:info).with(match(a_hash_including(loggable_data))) end 2.times do expect(logger.instrument(mergeability_name: :expensive_operation) { 123 }).to eq(123) end logger.commit end end context 'when its a query' do let(:extra_data) do { 'mergeability.expensive_operation.db_count.values' => a_kind_of(Array), 'mergeability.expensive_operation.db_main_count.values' => a_kind_of(Array), 'mergeability.expensive_operation.db_main_duration_s.values' => a_kind_of(Array), 'mergeability.expensive_operation.db_primary_count.values' => a_kind_of(Array), 'mergeability.expensive_operation.db_primary_duration_s.values' => a_kind_of(Array) } end context 'with a single query' do it 'includes SQL metrics' do expect_next_instance_of(Gitlab::AppJsonLogger) do |app_logger| expect(app_logger).to receive(:info).with(match(a_hash_including(loggable_data(**extra_data)))) end expect(logger.instrument(mergeability_name: :expensive_operation) { MergeRequest.count }).to eq(1) logger.commit end end context 'with multiple queries' do it 'includes SQL metrics' do expect_next_instance_of(Gitlab::AppJsonLogger) do |app_logger| expect(app_logger).to receive(:info).with(match(a_hash_including(loggable_data(**extra_data)))) end expect(logger.instrument(mergeability_name: :expensive_operation) { Project.count + MergeRequest.count }) .to eq(2) logger.commit end end end end it 'raises an error when block is not provided' do expect { logger.instrument(mergeability_name: :expensive_operation) } .to raise_error(ArgumentError, 'block not given') end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckCiStatusService < CheckBaseService identifier :ci_must_pass description 'Checks whether CI has passed' def execute return inactive unless merge_request.only_allow_merge_if_pipeline_succeeds? if merge_request.mergeable_ci_state? success else failure end end def skip? params[:skip_ci_check].present? end def cacheable? false end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckCiStatusService, feature_category: :code_review_workflow do subject(:check_ci_status) { described_class.new(merge_request: merge_request, params: params) } let_it_be(:project) { build(:project) } let_it_be(:merge_request) { build(:merge_request, source_project: project) } let(:params) { { skip_ci_check: skip_check } } let(:skip_check) { false } it_behaves_like 'mergeability check service', :ci_must_pass, 'Checks whether CI has passed' describe '#execute' do let(:result) { check_ci_status.execute } before do allow(merge_request) .to receive(:only_allow_merge_if_pipeline_succeeds?) .and_return(only_allow_merge_if_pipeline_succeeds?) end context 'when only_allow_merge_if_pipeline_succeeds is true' do let(:only_allow_merge_if_pipeline_succeeds?) { true } before do expect(merge_request).to receive(:mergeable_ci_state?).and_return(mergeable) end context 'when the merge request is in a mergeable state' do let(:mergeable) { true } it 'returns a check result with status success' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::SUCCESS_STATUS end end context 'when the merge request is not in a mergeable state' do let(:mergeable) { false } it 'returns a check result with status failed' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::FAILED_STATUS expect(result.payload[:identifier]).to eq :ci_must_pass end end end context 'when only_allow_merge_if_pipeline_succeeds is false' do let(:only_allow_merge_if_pipeline_succeeds?) { false } it 'returns a check result with inactive status' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::INACTIVE_STATUS end end end describe '#skip?' do context 'when skip check is true' do let(:skip_check) { true } it 'returns true' do expect(check_ci_status.skip?).to eq true end end context 'when skip check is false' do let(:skip_check) { false } it 'returns false' do expect(check_ci_status.skip?).to eq false end end end describe '#cacheable?' do it 'returns false' do expect(check_ci_status.cacheable?).to eq false end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckOpenStatusService < CheckBaseService identifier :not_open description 'Checks whether the merge request is open' def execute if merge_request.open? success else failure end end def skip? false end def cacheable? false end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckOpenStatusService, feature_category: :code_review_workflow do subject(:check_open_status) { described_class.new(merge_request: merge_request, params: {}) } let(:merge_request) { build(:merge_request) } it_behaves_like 'mergeability check service', :not_open, 'Checks whether the merge request is open' describe '#execute' do let(:result) { check_open_status.execute } before do expect(merge_request).to receive(:open?).and_return(open) end context 'when the merge request is open' do let(:open) { true } it 'returns a check result with status success' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::SUCCESS_STATUS end end context 'when the merge request is not open' do let(:open) { false } it 'returns a check result with status failed' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::FAILED_STATUS expect(result.payload[:identifier]).to eq(:not_open) end end end describe '#skip?' do it 'returns false' do expect(check_open_status.skip?).to eq false end end describe '#cacheable?' do it 'returns false' do expect(check_open_status.cacheable?).to eq false end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckBrokenStatusService < CheckBaseService identifier :broken_status description 'Checks whether the merge request is broken' def execute if merge_request.broken? failure else success end end def skip? false end def cacheable? false end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckBrokenStatusService, feature_category: :code_review_workflow do subject(:check_broken_status) { described_class.new(merge_request: merge_request, params: {}) } let(:merge_request) { build(:merge_request) } it_behaves_like 'mergeability check service', :broken_status, 'Checks whether the merge request is broken' describe '#execute' do let(:result) { check_broken_status.execute } before do expect(merge_request).to receive(:broken?).and_return(broken) end context 'when the merge request is broken' do let(:broken) { true } it 'returns a check result with status failed' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::FAILED_STATUS expect(result.payload[:identifier]).to eq(:broken_status) end end context 'when the merge request is not broken' do let(:broken) { false } it 'returns a check result with status success' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::SUCCESS_STATUS end end end describe '#skip?' do it 'returns false' do expect(check_broken_status.skip?).to eq false end end describe '#cacheable?' do it 'returns false' do expect(check_broken_status.cacheable?).to eq false end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckConflictStatusService < CheckBaseService identifier :conflict description 'Checks whether the merge request has a conflict' def execute if merge_request.can_be_merged? success else failure end end def skip? false end def cacheable? false end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckConflictStatusService, feature_category: :code_review_workflow do subject(:check_conflict_status) { described_class.new(merge_request: merge_request, params: {}) } let(:merge_request) { build(:merge_request) } it_behaves_like 'mergeability check service', :conflict, 'Checks whether the merge request has a conflict' describe '#execute' do let(:result) { check_conflict_status.execute } before do allow(merge_request).to receive(:can_be_merged?).and_return(can_be_merged) end context 'when MergeRequest#can_be_merged is true' do let(:can_be_merged) { true } it 'returns a check result with status success' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::SUCCESS_STATUS end end context 'when MergeRequest#can_be_merged is false' do let(:can_be_merged) { false } it 'returns a check result with status failed' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::FAILED_STATUS expect(result.payload[:identifier]).to eq(:conflict) end end end describe '#skip?' do it 'returns false' do expect(check_conflict_status.skip?).to eq false end end describe '#cacheable?' do it 'returns false' do expect(check_conflict_status.cacheable?).to eq false end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckDiscussionsStatusService < CheckBaseService identifier :discussions_not_resolved description 'Checks whether the merge request has open discussions' def execute return inactive unless merge_request.only_allow_merge_if_all_discussions_are_resolved? if merge_request.mergeable_discussions_state? success else failure end end def skip? params[:skip_discussions_check].present? end def cacheable? false end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckDiscussionsStatusService, feature_category: :code_review_workflow do subject(:check_discussions_status) { described_class.new(merge_request: merge_request, params: params) } let_it_be(:project) { build(:project) } let_it_be(:merge_request) { build(:merge_request, source_project: project) } let(:params) { { skip_discussions_check: skip_check } } let(:skip_check) { false } it_behaves_like 'mergeability check service', :discussions_not_resolved, 'Checks whether the merge request has open discussions' describe '#execute' do let(:result) { check_discussions_status.execute } before do allow(merge_request) .to receive(:only_allow_merge_if_all_discussions_are_resolved?) .and_return(only_allow_merge_if_all_discussions_are_resolved?) end context 'when only_allow_merge_if_all_discussions_are_resolved is true' do let(:only_allow_merge_if_all_discussions_are_resolved?) { true } before do allow(merge_request).to receive(:mergeable_discussions_state?).and_return(mergeable) end context 'when the merge request is in a mergable state' do let(:mergeable) { true } it 'returns a check result with status success' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::SUCCESS_STATUS end end context 'when the merge request is not in a mergeable state' do let(:mergeable) { false } it 'returns a check result with status failed' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::FAILED_STATUS expect(result.payload[:identifier]).to eq(:discussions_not_resolved) end end end context 'when only_allow_merge_if_all_discussions_are_resolved is false' do let(:only_allow_merge_if_all_discussions_are_resolved?) { false } it 'returns a check result with inactive status' do expect(result.status).to eq Gitlab::MergeRequests::Mergeability::CheckResult::INACTIVE_STATUS end end end describe '#skip?' do context 'when skip check is true' do let(:skip_check) { true } it 'returns true' do expect(check_discussions_status.skip?).to eq true end end context 'when skip check is false' do let(:skip_check) { false } it 'returns false' do expect(check_discussions_status.skip?).to eq false end end end describe '#cacheable?' do it 'returns false' do expect(check_discussions_status.cacheable?).to eq false end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Mergeability class CheckBaseService attr_reader :merge_request, :params class_attribute :identifier, :description def self.identifier(new_identifier) self.identifier = new_identifier end def self.description(new_description) self.description = new_description end def initialize(merge_request:, params:) @merge_request = merge_request @params = params end def skip? raise NotImplementedError end # When this method is true, we need to implement a cache_key def cacheable? raise NotImplementedError end def cache_key raise NotImplementedError end private def success(**args) Gitlab::MergeRequests::Mergeability::CheckResult .success(payload: default_payload(args)) end def failure(**args) Gitlab::MergeRequests::Mergeability::CheckResult .failed(payload: default_payload(args)) end def inactive(**args) Gitlab::MergeRequests::Mergeability::CheckResult .inactive(payload: default_payload(args)) end def default_payload(args) args.merge(identifier: self.class.identifier) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Mergeability::CheckBaseService, feature_category: :code_review_workflow do subject(:check_base_service) { described_class.new(merge_request: merge_request, params: params) } let(:merge_request) { double } let(:params) { double } describe '.identifier' do it 'sets the identifier' do described_class.identifier("test") expect(described_class.identifier).to eq("test") end end describe '.description' do it 'sets the description' do described_class.description("test") expect(described_class.description).to eq("test") end end describe '#merge_request' do it 'returns the merge_request' do expect(check_base_service.merge_request).to eq merge_request end end describe '#params' do it 'returns the params' do expect(check_base_service.params).to eq params end end describe '#skip?' do it 'raises NotImplementedError' do expect { check_base_service.skip? }.to raise_error(NotImplementedError) end end describe '#cacheable?' do it 'raises NotImplementedError' do expect { check_base_service.skip? }.to raise_error(NotImplementedError) end end describe '#cache_key?' do it 'raises NotImplementedError' do expect { check_base_service.skip? }.to raise_error(NotImplementedError) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module MergeStrategies # FromSourceBranch performs a git merge from a merge request's source branch # to the target branch, including a squash if needed. class FromSourceBranch include Gitlab::Utils::StrongMemoize delegate :repository, to: :project def initialize(merge_request, current_user, merge_params: {}, options: {}) @merge_request = merge_request @current_user = current_user @project = merge_request.project @merge_params = merge_params @options = options end def validate! error_message = if source_sha.blank? 'No source for merge' elsif merge_request.should_be_rebased? 'Only fast-forward merge is allowed for your project. Please update your source branch' elsif !merge_request.mergeable?( skip_discussions_check: @options[:skip_discussions_check], check_mergeability_retry_lease: @options[:check_mergeability_retry_lease] ) 'Merge request is not mergeable' elsif merge_request.missing_required_squash? 'This project requires squashing commits when merge requests are accepted.' end raise_error(error_message) if error_message end def execute_git_merge! result = if project.merge_requests_ff_only_enabled fast_forward! else merge_commit! end result[:squash_commit_sha] = source_sha if merge_request.squash_on_merge? result end private attr_reader :merge_request, :current_user, :merge_params, :options, :project def source_sha if merge_request.squash_on_merge? squash_sha! else merge_request.diff_head_sha end end strong_memoize_attr :source_sha def squash_sha! squash_result = ::MergeRequests::SquashService .new( merge_request: merge_request, current_user: current_user, commit_message: merge_params[:squash_commit_message] ).execute case squash_result[:status] when :success squash_result[:squash_sha] when :error raise_error(squash_result[:message]) end end def fast_forward! commit_sha = repository.ff_merge( current_user, source_sha, merge_request.target_branch, merge_request: merge_request ) { commit_sha: commit_sha } end def merge_commit! commit_sha = repository.merge( current_user, source_sha, merge_request, merge_commit_message ) { commit_sha: commit_sha, merge_commit_sha: commit_sha } end def merge_commit_message merge_params[:commit_message] || merge_request.default_merge_commit_message(user: current_user) end def raise_error(message) raise ::MergeRequests::MergeStrategies::StrategyError, message end end end end ::MergeRequests::MergeStrategies::FromSourceBranch.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::MergeStrategies::FromSourceBranch, feature_category: :code_review_workflow do let_it_be(:user) { create(:user) } let_it_be(:user2) { create(:user) } let(:merge_request) { create(:merge_request, :simple, author: user2, assignees: [user2]) } let(:project) { merge_request.project } subject(:strategy) { described_class.new(merge_request, user) } before do project.add_maintainer(user) end describe '#validate!' do context 'when source is missing' do before do allow(merge_request).to receive(:diff_head_sha).and_return(nil) end it 'raises source error when source is missing' do error_message = 'No source for merge' expect { strategy.validate! } .to raise_exception(MergeRequests::MergeStrategies::StrategyError, error_message) end end context 'when merge request should be rebased' do before do allow(merge_request).to receive(:should_be_rebased?).and_return(true) end it 'raises needs rebase error' do error_message = 'Only fast-forward merge is allowed for your project. Please update your source branch' expect { strategy.validate! } .to raise_exception(MergeRequests::MergeStrategies::StrategyError, error_message) end end context 'when merge request should be squashed but is not' do before do merge_request.target_project.project_setting.squash_always! merge_request.update!(squash: false) end it 'raises squashing error' do error_message = 'This project requires squashing commits when merge requests are accepted.' expect { strategy.validate! } .to raise_exception(MergeRequests::MergeStrategies::StrategyError, error_message) end end end describe '#execute_git_merge!' do context 'when fast-forward is required' do before do project.merge_method = :ff project.save! end it 'performs a fast-forward merge' do expect(merge_request.target_project.repository).to receive(:ff_merge).and_return('1234') strategy.execute_git_merge! end end context 'when a merge commit is required' do before do project.merge_method = :merge project.save! end it 'performs standard merge' do expect(merge_request.target_project.repository).to receive(:merge).and_return('1234') strategy.execute_git_merge! end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Conflicts class ResolveService < MergeRequests::Conflicts::BaseService def execute(current_user, params) conflicts = Gitlab::Conflict::FileCollection.new(merge_request) conflicts.resolve(current_user, params[:commit_message], params[:files]) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Conflicts::ResolveService, feature_category: :code_review_workflow do include ProjectForksHelper let(:user) { create(:user) } let(:project) { create(:project, :public, :repository) } let(:forked_project) do fork_project_with_submodules(project, user) end let(:merge_request) do create( :merge_request, source_branch: 'conflict-resolvable', source_project: project, target_branch: 'conflict-start' ) end let(:merge_request_from_fork) do create( :merge_request, source_branch: 'conflict-resolvable-fork', source_project: forked_project, target_branch: 'conflict-start', target_project: project ) end describe '#execute' do let(:service) { described_class.new(merge_request) } def blob_content(project, ref, path) project.repository.blob_at(ref, path).data end context 'with section params' do let(:params) do { files: [ { old_path: 'files/ruby/popen.rb', new_path: 'files/ruby/popen.rb', sections: { '2f6fcd96b88b36ce98c38da085c795a27d92a3dd_14_14' => 'head' } }, { old_path: 'files/ruby/regex.rb', new_path: 'files/ruby/regex.rb', sections: { '6eb14e00385d2fb284765eb1cd8d420d33d63fc9_9_9' => 'head', '6eb14e00385d2fb284765eb1cd8d420d33d63fc9_21_21' => 'origin', '6eb14e00385d2fb284765eb1cd8d420d33d63fc9_49_49' => 'origin' } } ], commit_message: 'This is a commit message!' } end context 'when the source and target project are the same' do before do service.execute(user, params) end it 'creates a commit with the message' do expect(merge_request.source_branch_head.message).to eq(params[:commit_message]) end it 'creates a commit with the correct parents' do expect(merge_request.source_branch_head.parents.map(&:id)) .to eq(%w[1450cd639e0bc6721eb02800169e464f212cde06 824be604a34828eb682305f0d963056cfac87b2d]) end end context 'when some files have trailing newlines' do let!(:source_head) do branch = 'conflict-resolvable' path = 'files/ruby/popen.rb' popen_content = blob_content(project, branch, path) project.repository.update_file( user, path, popen_content.chomp("\n"), message: 'Remove trailing newline from popen.rb', branch_name: branch ) end before do service.execute(user, params) end it 'preserves trailing newlines from our side of the conflicts' do head_sha = merge_request.source_branch_head.sha popen_content = blob_content(project, head_sha, 'files/ruby/popen.rb') regex_content = blob_content(project, head_sha, 'files/ruby/regex.rb') expect(popen_content).not_to end_with("\n") expect(regex_content).to end_with("\n") end end context 'when the source project is a fork and does not contain the HEAD of the target branch' do let!(:target_head) do project.repository.create_file( user, 'new-file-in-target', '', message: 'Add new file in target', branch_name: 'conflict-start') end subject do described_class.new(merge_request_from_fork).execute(user, params) end it 'creates a commit with the message' do subject expect(merge_request_from_fork.source_branch_head.message).to eq(params[:commit_message]) end it 'creates a commit with the correct parents' do subject expect(merge_request_from_fork.source_branch_head.parents.map(&:id)) .to eq(['404fa3fc7c2c9b5dacff102f353bdf55b1be2813', target_head]) end end end context 'with content and sections params' do let(:popen_content) { "class Popen\nend" } let(:params) do { files: [ { old_path: 'files/ruby/popen.rb', new_path: 'files/ruby/popen.rb', content: popen_content }, { old_path: 'files/ruby/regex.rb', new_path: 'files/ruby/regex.rb', sections: { '6eb14e00385d2fb284765eb1cd8d420d33d63fc9_9_9' => 'head', '6eb14e00385d2fb284765eb1cd8d420d33d63fc9_21_21' => 'origin', '6eb14e00385d2fb284765eb1cd8d420d33d63fc9_49_49' => 'origin' } } ], commit_message: 'This is a commit message!' } end before do service.execute(user, params) end it 'creates a commit with the message' do expect(merge_request.source_branch_head.message).to eq(params[:commit_message]) end it 'creates a commit with the correct parents' do expect(merge_request.source_branch_head.parents.map(&:id)) .to eq(%w[1450cd639e0bc6721eb02800169e464f212cde06 824be604a34828eb682305f0d963056cfac87b2d]) end it 'sets the content to the content given' do blob = blob_content( merge_request.source_project, merge_request.source_branch_head.sha, 'files/ruby/popen.rb' ) expect(blob).to eq(popen_content) end end context 'when a resolution section is missing' do let(:invalid_params) do { files: [ { old_path: 'files/ruby/popen.rb', new_path: 'files/ruby/popen.rb', content: '' }, { old_path: 'files/ruby/regex.rb', new_path: 'files/ruby/regex.rb', sections: { '6eb14e00385d2fb284765eb1cd8d420d33d63fc9_9_9' => 'head' } } ], commit_message: 'This is a commit message!' } end it 'raises a ResolutionError error' do expect { service.execute(user, invalid_params) } .to raise_error(Gitlab::Git::Conflict::Resolver::ResolutionError) end end context 'when the content of a file is unchanged' do let(:resolver) do MergeRequests::Conflicts::ListService.new(merge_request).conflicts.resolver end let(:regex_conflict) do resolver.conflict_for_path(resolver.conflicts, 'files/ruby/regex.rb', 'files/ruby/regex.rb') end let(:invalid_params) do { files: [ { old_path: 'files/ruby/popen.rb', new_path: 'files/ruby/popen.rb', content: '' }, { old_path: 'files/ruby/regex.rb', new_path: 'files/ruby/regex.rb', content: regex_conflict.content } ], commit_message: 'This is a commit message!' } end it 'raises a ResolutionError error' do expect { service.execute(user, invalid_params) } .to raise_error(Gitlab::Git::Conflict::Resolver::ResolutionError) end end context 'when a file is missing' do let(:invalid_params) do { files: [ { old_path: 'files/ruby/popen.rb', new_path: 'files/ruby/popen.rb', content: '' } ], commit_message: 'This is a commit message!' } end it 'raises a ResolutionError error' do expect { service.execute(user, invalid_params) } .to raise_error(Gitlab::Git::Conflict::Resolver::ResolutionError) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module MergeRequests module Conflicts class ListService < MergeRequests::Conflicts::BaseService delegate :file_for_path, :to_json, to: :conflicts def can_be_resolved_by?(user) return false unless merge_request.source_project access = ::Gitlab::UserAccess.new(user, container: merge_request.source_project) access.can_push_to_branch?(merge_request.source_branch) end def can_be_resolved_in_ui? return @conflicts_can_be_resolved_in_ui if defined?(@conflicts_can_be_resolved_in_ui) return @conflicts_can_be_resolved_in_ui = false unless merge_request.cannot_be_merged? return @conflicts_can_be_resolved_in_ui = false unless merge_request.has_complete_diff_refs? return @conflicts_can_be_resolved_in_ui = false if merge_request.branch_missing? @conflicts_can_be_resolved_in_ui = conflicts.can_be_resolved_in_ui? end def conflicts @conflicts ||= Gitlab::Conflict::FileCollection.new( merge_request, allow_tree_conflicts: params[:allow_tree_conflicts] ) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe MergeRequests::Conflicts::ListService, feature_category: :code_review_workflow do describe '#can_be_resolved_in_ui?' do def create_merge_request(source_branch, target_branch = 'conflict-start') create(:merge_request, source_branch: source_branch, target_branch: target_branch, merge_status: :unchecked) do |mr| mr.mark_as_unmergeable end end def conflicts_service(merge_request) described_class.new(merge_request) end it 'returns a falsey value when the MR can be merged without conflicts' do merge_request = create_merge_request('master') merge_request.mark_as_mergeable expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when the MR is marked as having conflicts, but has none' do merge_request = create_merge_request('master') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when one of the MR branches is missing' do merge_request = create_merge_request('conflict-resolvable') merge_request.project.repository.rm_branch(merge_request.author, 'conflict-resolvable') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when the MR does not support new diff notes' do merge_request = create_merge_request('conflict-resolvable') merge_request.merge_request_diff.update!(start_commit_sha: nil) expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when the conflicts contain a large file' do merge_request = create_merge_request('conflict-too-large') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when the conflicts contain a binary file' do merge_request = create_merge_request('conflict-binary-file') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when the conflicts contain a file edited in one branch and deleted in another' do merge_request = create_merge_request('conflict-missing-side') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end it 'returns a truthy value when the conflicts are resolvable in the UI' do merge_request = create_merge_request('conflict-resolvable') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_truthy end it 'returns a truthy value when the conflicts have to be resolved in an editor' do merge_request = create_merge_request('conflict-contains-conflict-markers') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_truthy end it 'returns a falsey value when the MR has a missing ref after a force push' do merge_request = create_merge_request('conflict-resolvable') service = conflicts_service(merge_request) allow_next_instance_of(Gitlab::GitalyClient::ConflictsService) do |instance| allow(instance).to receive(:list_conflict_files).and_raise(GRPC::Unknown) end expect(service.can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when the MR has a missing revision after a force push' do merge_request = create_merge_request('conflict-resolvable') service = conflicts_service(merge_request) allow(merge_request).to receive_message_chain(:target_branch_head, :raw, :id).and_return(Gitlab::Git::BLANK_SHA) expect(service.can_be_resolved_in_ui?).to be_falsey end it 'returns a falsey value when the conflict is in a submodule revision' do merge_request = create_merge_request('update-gitlab-shell-v-6-0-3', 'update-gitlab-shell-v-6-0-1') expect(conflicts_service(merge_request).can_be_resolved_in_ui?).to be_falsey end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Captcha ## # Encapsulates logic of checking captchas. # class CaptchaVerificationService include Recaptcha::Adapters::ControllerMethods # Currently the only value that is used out of the request by the reCAPTCHA library # is 'remote_ip'. Therefore, we just create a struct to avoid passing the full request # object through all the service layer objects, and instead just rely on passing only # the required remote_ip value. This eliminates the need to couple the service layer # to the HTTP request (for the purpose of this service, at least). RequestStruct = Struct.new(:remote_ip) def initialize(spam_params:) @spam_params = spam_params end ## # Performs verification of a captcha response. # # NOTE: Currently only supports reCAPTCHA, and is not yet used in all places of the app in which # captchas are verified, but these can be addressed in future MRs. See: # https://gitlab.com/gitlab-org/gitlab/-/issues/273480 def execute return false unless spam_params.captcha_response @request = RequestStruct.new(spam_params.ip_address) Gitlab::Recaptcha.load_configurations! # NOTE: We could pass the model and let the recaptcha gem automatically add errors to it, # but we do not, for two reasons: # # 1. We want control over when the errors are added # 2. We want control over the wording and i18n of the message # 3. We want a consistent interface and behavior when adding support for other captcha # libraries which may not support automatically adding errors to the model. verify_recaptcha(response: spam_params.captcha_response) end private attr_reader :spam_params # The recaptcha library's Recaptcha::Adapters::ControllerMethods#verify_recaptcha method requires that # 'request' be a readable attribute - it doesn't support passing it as an options argument. attr_reader :request end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Captcha::CaptchaVerificationService, feature_category: :team_planning do describe '#execute' do let(:captcha_response) { 'abc123' } let(:fake_ip) { '1.2.3.4' } let(:spam_params) do ::Spam::SpamParams.new( captcha_response: captcha_response, spam_log_id: double, ip_address: fake_ip, user_agent: double, referer: double ) end let(:service) { described_class.new(spam_params: spam_params) } subject { service.execute } context 'when there is no captcha_response' do let(:captcha_response) { nil } it 'returns false' do expect(subject).to eq(false) end end context 'when there is a captcha_response' do before do expect(Gitlab::Recaptcha).to receive(:load_configurations!) end it 'returns false' do expect(service).to receive(:verify_recaptcha).with(response: captcha_response) { true } expect(subject).to eq(true) end it 'has a request method which returns an object with the ip address #remote_ip' do subject request_struct = service.send(:request) expect(request_struct).to respond_to(:remote_ip) expect(request_struct.remote_ip).to eq(fake_ip) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module JiraImport class ServerUsersMapperService < UsersMapperService private def url "/rest/api/2/user/search?username=''&maxResults=#{MAX_USERS}&startAt=#{start_at.to_i}" end def jira_user_id(jira_user) jira_user['key'] end def jira_user_name(jira_user) jira_user['name'] end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe JiraImport::ServerUsersMapperService, feature_category: :integrations do let(:start_at) { 7 } let(:url) { "/rest/api/2/user/search?username=''&maxResults=50&startAt=#{start_at}" } let_it_be(:user_1) { create(:user, username: 'randomuser', name: 'USER-name1', email: '[email protected]') } let_it_be(:user_2) { create(:user, username: 'username-2') } let_it_be(:user_5) { create(:user, username: 'username-5') } let_it_be(:user_4) { create(:user, email: '[email protected]') } let_it_be(:user_6) { create(:user, email: '[email protected]') } let_it_be(:user_7) { create(:user, username: 'username-7') } let_it_be(:user_8) do create(:user).tap { |user| create(:email, user: user, email: '[email protected]') } end let_it_be(:current_user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, group: group) } let(:jira_users) do [ { 'key' => 'abcd', 'name' => 'User-Name1' }, # matched by name { 'key' => 'efg', 'name' => 'username-2' }, # matcher by username { 'key' => 'hij' }, # no match { 'key' => '123', 'name' => 'user-4', 'emailAddress' => '[email protected]' }, # matched by email { 'key' => '456', 'name' => 'username5foo', 'emailAddress' => '[email protected]' }, # no match { 'key' => '789', 'name' => 'user-6', 'emailAddress' => '[email protected]' }, # matched by email, no project member { 'key' => 'xyz', 'name' => 'username-7', 'emailAddress' => '[email protected]' }, # matched by username, no project member { 'key' => 'vhk', 'name' => 'user-8', 'emailAddress' => '[email protected]' }, # matched by secondary email { 'key' => 'uji', 'name' => 'user-9', 'emailAddress' => '[email protected]' } # matched by email, same as user_1 ] end describe '#execute' do before do project.add_developer(current_user) project.add_developer(user_1) project.add_developer(user_2) group.add_developer(user_4) group.add_guest(user_8) end it_behaves_like 'mapping jira users' end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module JiraImport class CloudUsersMapperService < UsersMapperService private def url "/rest/api/2/users?maxResults=#{MAX_USERS}&startAt=#{start_at.to_i}" end def jira_user_id(jira_user) jira_user['accountId'] end def jira_user_name(jira_user) jira_user['displayName'] end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe JiraImport::CloudUsersMapperService, feature_category: :integrations do let(:start_at) { 7 } let(:url) { "/rest/api/2/users?maxResults=50&startAt=#{start_at}" } let_it_be(:user_1) { create(:user, username: 'randomuser', name: 'USER-name1', email: '[email protected]') } let_it_be(:user_2) { create(:user, username: 'username-2') } let_it_be(:user_5) { create(:user, username: 'username-5') } let_it_be(:user_4) { create(:user, email: '[email protected]') } let_it_be(:user_6) { create(:user, email: '[email protected]') } let_it_be(:user_7) { create(:user, username: 'username-7') } let_it_be(:user_8) do create(:user).tap { |user| create(:email, user: user, email: '[email protected]') } end let_it_be(:current_user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, group: group) } let(:jira_users) do [ { 'accountId' => 'abcd', 'displayName' => 'User-Name1' }, # matched by name { 'accountId' => 'efg', 'displayName' => 'username-2' }, # matcher by username { 'accountId' => 'hij' }, # no match { 'accountId' => '123', 'displayName' => 'user-4', 'emailAddress' => '[email protected]' }, # matched by email { 'accountId' => '456', 'displayName' => 'username5foo', 'emailAddress' => '[email protected]' }, # no match { 'accountId' => '789', 'displayName' => 'user-6', 'emailAddress' => '[email protected]' }, # matched by email, no project member { 'accountId' => 'xyz', 'displayName' => 'username-7', 'emailAddress' => '[email protected]' }, # matched by username, no project member { 'accountId' => 'vhk', 'displayName' => 'user-8', 'emailAddress' => '[email protected]' }, # matched by secondary email { 'accountId' => 'uji', 'displayName' => 'user-9', 'emailAddress' => '[email protected]' } # matched by email, same as user_1 ] end describe '#execute' do before do project.add_developer(current_user) project.add_developer(user_1) project.add_developer(user_2) group.add_developer(user_4) group.add_guest(user_8) end it_behaves_like 'mapping jira users' end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module JiraImport class UsersImporter def initialize(user, project, start_at) @project = project @start_at = start_at @user = user end def execute Gitlab::JiraImport.validate_project_settings!(project, user: user) ServiceResponse.success(payload: mapped_users) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, URI::InvalidURIError, JIRA::HTTPError, OpenSSL::SSL::SSLError => error Gitlab::ErrorTracking.log_exception(error, project_id: project.id) ServiceResponse.error(message: "There was an error when communicating to Jira") rescue Projects::ImportService::Error => error ServiceResponse.error(message: error.message) end private attr_reader :user, :project, :start_at def mapped_users users_mapper_service.execute end def users_mapper_service @users_mapper_service ||= user_mapper_service_factory end def user_mapper_service_factory if project.jira_integration.data_fields.deployment_server? ServerUsersMapperService.new(user, project, start_at) elsif project.jira_integration.data_fields.deployment_cloud? CloudUsersMapperService.new(user, project, start_at) else raise ArgumentError end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe JiraImport::UsersImporter, feature_category: :integrations do include JiraIntegrationHelpers let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project, reload: true) { create(:project, group: group) } let_it_be(:start_at) { 7 } let(:importer) { described_class.new(user, project, start_at) } subject { importer.execute } describe '#execute' do let(:mapped_users) do [ { jira_account_id: 'acc1', jira_display_name: 'user-name1', jira_email: '[email protected]', gitlab_id: project_member.id }, { jira_account_id: 'acc2', jira_display_name: 'user-name2', jira_email: nil, gitlab_id: group_member.id } ] end before do stub_jira_integration_test project.add_maintainer(user) end context 'when Jira import is not configured properly' do it 'returns an error' do expect(subject.errors).to eq(['Jira integration not configured.']) end end RSpec.shared_examples 'maps Jira users to GitLab users' do |users_mapper_service:| context 'when Jira import is configured correctly' do let_it_be(:jira_integration) { create(:jira_integration, project: project, active: true, url: "http://jira.example.net") } context 'when users mapper service raises an error' do let(:error) { Timeout::Error.new } it 'returns an error response' do expect_next_instance_of(users_mapper_service) do |instance| expect(instance).to receive(:execute).and_raise(error) end expect(Gitlab::ErrorTracking).to receive(:log_exception).with(error, project_id: project.id) expect(subject.error?).to be_truthy expect(subject.message).to include('There was an error when communicating to Jira') end end context 'when users mapper service returns result' do context 'when users mapper service returns an empty array' do it 'returns nil payload' do expect_next_instance_of(users_mapper_service) do |instance| expect(instance).to receive(:execute).and_return([]) end expect(subject.success?).to be_truthy expect(subject.payload).to be_empty end end context 'when Jira client returns any users' do let_it_be(:project_member) { create(:user, email: '[email protected]') } let_it_be(:group_member) { create(:user, name: 'user-name2') } let_it_be(:other_user) { create(:user) } before do project.add_developer(project_member) group.add_developer(group_member) end it 'returns the mapped users' do expect_next_instance_of(users_mapper_service) do |instance| expect(instance).to receive(:execute).and_return(mapped_users) end expect(subject.success?).to be_truthy expect(subject.payload).to eq(mapped_users) end end end end end context 'when Jira instance is of Server deployment type' do before do allow(project).to receive(:jira_integration).and_return(jira_integration) jira_integration.data_fields.deployment_server! end it_behaves_like 'maps Jira users to GitLab users', users_mapper_service: JiraImport::ServerUsersMapperService end context 'when Jira instance is of Cloud deployment type' do before do allow(project).to receive(:jira_integration).and_return(jira_integration) jira_integration.data_fields.deployment_cloud! end it_behaves_like 'maps Jira users to GitLab users', users_mapper_service: JiraImport::CloudUsersMapperService end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module JiraImport class StartImportService attr_reader :user, :project, :jira_project_key, :users_mapping def initialize(user, project, jira_project_key, users_mapping) @user = user @project = project @jira_project_key = jira_project_key @users_mapping = users_mapping end def execute validation_response = validate return validation_response if validation_response&.error? store_users_mapping create_and_schedule_import end private def store_users_mapping return if users_mapping.blank? mapping = users_mapping.map do |map| next if !map[:jira_account_id] || !map[:gitlab_id] [map[:jira_account_id], map[:gitlab_id]] end.compact.to_h return if mapping.blank? Gitlab::JiraImport.cache_users_mapping(project.id, mapping) end def create_and_schedule_import jira_import = build_jira_import project.import_type = 'jira' project.save! && jira_import.schedule! ServiceResponse.success(payload: { import_data: jira_import }) rescue StandardError => ex # in case project.save! raises an error Gitlab::ErrorTracking.track_exception(ex, project_id: project.id) jira_import&.do_fail!(error_message: ex.message) build_error_response(ex.message) end def build_jira_import label = create_import_label(project) project.jira_imports.build( user: user, label: label, jira_project_key: jira_project_key, # we do not have the jira_project_name or jira_project_xid yet so just set a mock value, # we will once https://gitlab.com/gitlab-org/gitlab/-/merge_requests/28190 jira_project_name: jira_project_key, jira_project_xid: 0 ) end def create_import_label(project) label = ::Labels::CreateService.new(build_label_attrs(project)).execute(project: project) raise Projects::ImportService::Error, _('Failed to create import label for jira import.') if label.blank? label end def build_label_attrs(project) import_start_time = Time.zone.now jira_imports_for_project = project.jira_imports.by_jira_project_key(jira_project_key).size + 1 title = "jira-import::#{jira_project_key}-#{jira_imports_for_project}" description = "Label for issues that were imported from Jira on #{import_start_time.strftime('%Y-%m-%d %H:%M:%S')}" color = ::Gitlab::Color.color_for(title).to_s { title: title, description: description, color: color } end def validate Gitlab::JiraImport.validate_project_settings!(project, user: user) return build_error_response(_('Unable to find Jira project to import data from.')) if jira_project_key.blank? return build_error_response(_('Jira import is already running.')) if import_in_progress? rescue Projects::ImportService::Error => e build_error_response(e.message) end def build_error_response(message) ServiceResponse.error(message: message, http_status: 400) end def import_in_progress? project.latest_jira_import&.in_progress? end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe JiraImport::StartImportService, feature_category: :integrations do include JiraIntegrationHelpers let_it_be(:user) { create(:user) } let_it_be(:project, reload: true) { create(:project) } let(:key) { 'KEY' } let(:mapping) do [ { jira_account_id: 'abc', gitlab_id: 12 }, { jira_account_id: 'def', gitlab_id: nil }, { jira_account_id: nil, gitlab_id: 1 } ] end subject { described_class.new(user, project, key, mapping).execute } context 'when an error is returned from the project validation' do before do allow(Gitlab::JiraImport).to receive(:validate_project_settings!) .and_raise(Projects::ImportService::Error, 'Jira import feature is disabled.') end it_behaves_like 'responds with error', 'Jira import feature is disabled.' end context 'when project validation is ok' do let!(:jira_integration) { create(:jira_integration, project: project, active: true) } before do stub_jira_integration_test allow(Gitlab::JiraImport).to receive(:validate_project_settings!) end context 'when Jira project key is not provided' do let(:key) { '' } it_behaves_like 'responds with error', 'Unable to find Jira project to import data from.' end context 'when correct data provided' do let(:fake_key) { 'some-key' } subject { described_class.new(user, project, fake_key, mapping).execute } context 'when import is already running' do let_it_be(:jira_import_state) { create(:jira_import_state, :started, project: project) } it_behaves_like 'responds with error', 'Jira import is already running.' end context 'when an error is raised while scheduling import' do before do expect_next_instance_of(JiraImportState) do |jira_impport| expect(jira_impport).to receive(:schedule!).and_raise(Projects::ImportService::Error, 'Unexpected failure.') end end it_behaves_like 'responds with error', 'Unexpected failure.' it 'saves the error message' do subject expect(JiraImportState.last.error_message).to eq('Unexpected failure.') end end context 'when everything is ok' do context 'with complete mapping' do before do expect(Gitlab::JiraImport).to receive(:cache_users_mapping).with(project.id, { 'abc' => 12 }) end it 'returns success response' do expect(subject).to be_a(ServiceResponse) expect(subject).to be_success end it 'schedules Jira import' do subject expect(project.latest_jira_import).to be_scheduled end it 'creates Jira import data', :aggregate_failures do jira_import = subject.payload[:import_data] expect(jira_import.jira_project_xid).to eq(0) expect(jira_import.jira_project_name).to eq(fake_key) expect(jira_import.jira_project_key).to eq(fake_key) expect(jira_import.user).to eq(user) end it 'creates Jira import label' do expect { subject }.to change { Label.count }.by(1) end it 'creates Jira label title with correct number' do jira_import = subject.payload[:import_data] label_title = "jira-import::#{jira_import.jira_project_key}-1" expect(jira_import.label.title).to eq(label_title) end end context 'when mapping is nil' do let(:mapping) { nil } it 'returns success response' do expect(Gitlab::JiraImport).not_to receive(:cache_users_mapping) expect(subject).to be_a(ServiceResponse) expect(subject).to be_success end end context 'when no mapping value is complete' do let(:mapping) do [ { jira_account_id: 'def', gitlab_id: nil }, { jira_account_id: nil, gitlab_id: 1 } ] end it 'returns success response' do expect(Gitlab::JiraImport).not_to receive(:cache_users_mapping) expect(subject).to be_a(ServiceResponse) expect(subject).to be_success end end end context 'when multiple Jira imports for same Jira project' do let!(:jira_imports) { create_list(:jira_import_state, 3, :finished, project: project, jira_project_key: fake_key) } it 'creates Jira label title with correct number' do jira_import = subject.payload[:import_data] label_title = "jira-import::#{jira_import.jira_project_key}-4" expect(jira_import.label.title).to eq(label_title) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Tags class DestroyService < BaseService def execute(tag_name) repository = project.repository tag = repository.find_tag(tag_name) unless tag return error('No such tag', 404) end if repository.rm_tag(current_user, tag_name) ## # When a tag in a repository is destroyed, # release assets will be destroyed too. Releases::DestroyService .new(project, current_user, tag: tag_name) .execute unlock_artifacts(tag_name) success('Tag was removed') else error('Failed to remove tag') end rescue Gitlab::Git::PreReceiveError => ex error(ex.message) end def error(message, return_code = 400) super(message).merge(return_code: return_code) end def success(message) super().merge(message: message) end private def unlock_artifacts(tag_name) Ci::RefDeleteUnlockArtifactsWorker.perform_async(project.id, current_user.id, "#{::Gitlab::Git::TAG_REF_PREFIX}#{tag_name}") end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Tags::DestroyService, feature_category: :source_code_management do let(:project) { create(:project, :repository) } let(:repository) { project.repository } let(:user) { create(:user) } let(:service) { described_class.new(project, user) } describe '#execute' do subject { service.execute(tag_name) } before do allow(Ci::RefDeleteUnlockArtifactsWorker).to receive(:perform_async) end it 'removes the tag' do expect(repository).to receive(:before_remove_tag) expect(service).to receive(:success) service.execute('v1.1.0') end it 'calls the RefDeleteUnlockArtifactsWorker' do expect(Ci::RefDeleteUnlockArtifactsWorker).to receive(:perform_async).with(project.id, user.id, 'refs/tags/v1.1.0') service.execute('v1.1.0') end context 'when there is an associated release on the tag' do let(:tag) { repository.tags.first } let(:tag_name) { tag.name } before do project.add_maintainer(user) create(:release, tag: tag_name, project: project) end it 'destroys the release' do expect { subject }.to change { project.releases.count }.by(-1) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Tags class CreateService < BaseService def execute(tag_name, target, message) return error('Target is empty', 400) if target.blank? valid_tag = Gitlab::GitRefValidator.validate(tag_name) return error('Tag name invalid', 400) unless valid_tag repository = project.repository message = message&.strip new_tag = nil begin new_tag = repository.add_tag(current_user, tag_name, target, message) rescue Gitlab::Git::Repository::TagExistsError return error("Tag #{tag_name} already exists", 409) rescue Gitlab::Git::PreReceiveError => ex return error(ex.message) end if new_tag repository.expire_tags_cache success.merge(tag: new_tag) else error("Target #{target} is invalid", 400) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Tags::CreateService, feature_category: :source_code_management do let(:project) { create(:project, :repository) } let(:repository) { project.repository } let(:user) { create(:user) } let(:service) { described_class.new(project, user) } describe '#execute' do it 'creates the tag and returns success' do response = service.execute('v42.42.42', 'master', 'Foo') expect(response[:status]).to eq(:success) expect(response[:tag]).to be_a Gitlab::Git::Tag expect(response[:tag].name).to eq('v42.42.42') end context 'when target is invalid' do it 'returns an error' do response = service.execute('v1.1.0', 'foo', 'Foo') expect(response[:status]).to eq(:error) expect(response[:http_status]).to eq(400) expect(response[:message]).to eq('Target foo is invalid') end end context 'when tag_name is empty' do it 'returns an error' do response = service.execute('', 'foo', 'Foo') expect(response[:status]).to eq(:error) expect(response[:http_status]).to eq(400) expect(response[:message]).to eq('Tag name invalid') end end context 'when target is empty' do it 'returns an error' do response = service.execute('v1.1.0', '', 'Foo') expect(response[:status]).to eq(:error) expect(response[:http_status]).to eq(400) expect(response[:message]).to eq('Target is empty') end end context 'when tag already exists' do it 'returns an error' do expect(repository).to receive(:add_tag) .with(user, 'v1.1.0', 'master', 'Foo') .and_raise(Gitlab::Git::Repository::TagExistsError) response = service.execute('v1.1.0', 'master', 'Foo') expect(response[:status]).to eq(:error) expect(response[:http_status]).to eq(409) expect(response[:message]).to eq('Tag v1.1.0 already exists') end end context 'when tag name is invalid' do it 'returns an error' do response = service.execute('HEAD', 'master', 'Foo') expect(response[:status]).to eq(:error) expect(response[:http_status]).to eq(400) expect(response[:message]).to eq('Tag name invalid') end end context 'when pre-receive hook fails' do it 'returns an error' do expect(repository).to receive(:add_tag) .with(user, 'v1.1.0', 'master', 'Foo') .and_raise(Gitlab::Git::PreReceiveError, 'GitLab: something went wrong') response = service.execute('v1.1.0', 'master', 'Foo') expect(response[:status]).to eq(:error) expect(response[:message]).to eq('something went wrong') end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Search class GlobalService include Search::Filter include Gitlab::Utils::StrongMemoize DEFAULT_SCOPE = 'projects' ALLOWED_SCOPES = %w[projects issues merge_requests milestones users].freeze attr_accessor :current_user, :params def initialize(user, params) @current_user = user @params = params.dup end def execute Gitlab::SearchResults.new(current_user, params[:search], projects, order_by: params[:order_by], sort: params[:sort], filters: filters) end # rubocop: disable CodeReuse/ActiveRecord def projects @projects ||= ProjectsFinder.new(current_user: current_user).execute.preload(:topics, :project_topics) end def allowed_scopes ALLOWED_SCOPES end def scope strong_memoize(:scope) do allowed_scopes.include?(params[:scope]) ? params[:scope] : DEFAULT_SCOPE end end end end Search::GlobalService.prepend_mod_with('Search::GlobalService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Search::GlobalService, feature_category: :global_search do let_it_be(:user) { create(:user) } let_it_be(:internal_user) { create(:user) } let_it_be(:found_project) { create(:project, :private, name: 'searchable_project') } let_it_be(:unfound_project) { create(:project, :private, name: 'unfound_project') } let_it_be(:internal_project) { create(:project, :internal, name: 'searchable_internal_project') } let_it_be(:public_project) { create(:project, :public, name: 'searchable_public_project') } let_it_be(:archived_project) { create(:project, :public, archived: true, name: 'archived_project') } before do found_project.add_maintainer(user) end describe '#execute' do context 'unauthenticated' do it 'returns public projects only' do results = described_class.new(nil, search: "searchable").execute expect(results.objects('projects')).to match_array [public_project] end end context 'authenticated' do it 'returns public, internal and private projects' do results = described_class.new(user, search: "searchable").execute expect(results.objects('projects')).to match_array [public_project, found_project, internal_project] end it 'returns only public & internal projects' do results = described_class.new(internal_user, search: "searchable").execute expect(results.objects('projects')).to match_array [internal_project, public_project] end it 'project name is searchable' do results = described_class.new(user, search: found_project.name).execute expect(results.objects('projects')).to match_array [found_project] end it 'does not return archived projects' do results = described_class.new(user, search: "archived").execute expect(results.objects('projects')).not_to include(archived_project) end it 'returns archived projects if the include_archived option is passed' do results = described_class.new(user, { include_archived: true, search: "archived" }).execute expect(results.objects('projects')).to include(archived_project) end end end context 'issues' do let(:scope) { 'issues' } context 'sorting' do let_it_be(:project) { create(:project, :public) } let!(:old_result) { create(:issue, project: project, title: 'sorted old', created_at: 1.month.ago) } let!(:new_result) { create(:issue, project: project, title: 'sorted recent', created_at: 1.day.ago) } let!(:very_old_result) { create(:issue, project: project, title: 'sorted very old', created_at: 1.year.ago) } let!(:old_updated) { create(:issue, project: project, title: 'updated old', updated_at: 1.month.ago) } let!(:new_updated) { create(:issue, project: project, title: 'updated recent', updated_at: 1.day.ago) } let!(:very_old_updated) { create(:issue, project: project, title: 'updated very old', updated_at: 1.year.ago) } include_examples 'search results sorted' do let(:results_created) { described_class.new(nil, search: 'sorted', sort: sort).execute } let(:results_updated) { described_class.new(nil, search: 'updated', sort: sort).execute } end end end context 'merge_request' do let(:scope) { 'merge_requests' } context 'sorting' do let!(:project) { create(:project, :public) } let!(:old_result) { create(:merge_request, :opened, source_project: project, source_branch: 'old-1', title: 'sorted old', created_at: 1.month.ago) } let!(:new_result) { create(:merge_request, :opened, source_project: project, source_branch: 'new-1', title: 'sorted recent', created_at: 1.day.ago) } let!(:very_old_result) { create(:merge_request, :opened, source_project: project, source_branch: 'very-old-1', title: 'sorted very old', created_at: 1.year.ago) } let!(:old_updated) { create(:merge_request, :opened, source_project: project, source_branch: 'updated-old-1', title: 'updated old', updated_at: 1.month.ago) } let!(:new_updated) { create(:merge_request, :opened, source_project: project, source_branch: 'updated-new-1', title: 'updated recent', updated_at: 1.day.ago) } let!(:very_old_updated) { create(:merge_request, :opened, source_project: project, source_branch: 'updated-very-old-1', title: 'updated very old', updated_at: 1.year.ago) } include_examples 'search results sorted' do let(:results_created) { described_class.new(nil, search: 'sorted', sort: sort).execute } let(:results_updated) { described_class.new(nil, search: 'updated', sort: sort).execute } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Search class SnippetService < Search::GlobalService def execute Gitlab::SnippetSearchResults.new(current_user, params[:search]) end def scope @scope ||= 'snippet_titles' end end end Search::SnippetService.prepend_mod_with('Search::SnippetService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Search::SnippetService, feature_category: :global_search do let_it_be(:author) { create(:author) } let_it_be(:project) { create(:project, :public) } let_it_be(:public_snippet) { create(:snippet, :public, title: 'Foo Bar Title') } let_it_be(:internal_snippet) { create(:snippet, :internal, title: 'Foo Bar Title') } let_it_be(:private_snippet) { create(:snippet, :private, title: 'Foo Bar Title', author: author) } let_it_be(:project_public_snippet) { create(:snippet, :public, project: project, title: 'Foo Bar Title') } let_it_be(:project_internal_snippet) { create(:snippet, :internal, project: project, title: 'Foo Bar Title') } let_it_be(:project_private_snippet) { create(:snippet, :private, project: project, title: 'Foo Bar Title') } let_it_be(:user) { create(:user) } describe '#execute' do context 'unauthenticated' do it 'returns public snippets only' do search = described_class.new(nil, search: 'bar') results = search.execute expect(results.objects('snippet_titles')).to match_array [public_snippet, project_public_snippet] end end context 'authenticated' do it 'returns only public & internal snippets for regular users' do search = described_class.new(user, search: 'bar') results = search.execute expect(results.objects('snippet_titles')).to match_array [public_snippet, internal_snippet, project_public_snippet, project_internal_snippet] end it 'returns public, internal snippets and project private snippets for project members' do project.add_developer(user) search = described_class.new(user, search: 'bar') results = search.execute expect(results.objects('snippet_titles')).to match_array [public_snippet, internal_snippet, project_public_snippet, project_internal_snippet, project_private_snippet] end it 'returns public, internal and private snippets where user is the author' do search = described_class.new(author, search: 'bar') results = search.execute expect(results.objects('snippet_titles')).to match_array [public_snippet, internal_snippet, private_snippet, project_public_snippet, project_internal_snippet] end context 'when admin mode is enabled', :enable_admin_mode do it 'returns all snippets when user is admin' do admin = create(:admin) search = described_class.new(admin, search: 'bar') results = search.execute expect(results.objects('snippet_titles')).to match_array [public_snippet, internal_snippet, private_snippet, project_public_snippet, project_internal_snippet, project_private_snippet] end end context 'when admin mode is disabled' do it 'returns only public & internal snippets when user is admin' do admin = create(:admin) search = described_class.new(admin, search: 'bar') results = search.execute expect(results.objects('snippet_titles')).to match_array [public_snippet, internal_snippet, project_public_snippet, project_internal_snippet] end end end end describe '#scope' do it 'always scopes to snippet_titles' do search = described_class.new(user, search: 'bar') expect(search.scope).to eq 'snippet_titles' end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Search class GroupService < Search::GlobalService attr_accessor :group def initialize(user, group, params) super(user, params) @group = group end def execute Gitlab::GroupSearchResults.new( current_user, params[:search], projects, group: group, order_by: params[:order_by], sort: params[:sort], filters: filters ) end def projects return Project.none unless group return @projects if defined? @projects @projects = super.inside_path(group.full_path) end end end Search::GroupService.prepend_mod_with('Search::GroupService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Search::GroupService, feature_category: :global_search do shared_examples_for 'group search' do context 'finding projects by name' do let(:user) { create(:user) } let(:term) { "Project Name" } let(:nested_group) { create(:group, :nested) } # These projects shouldn't be found let!(:outside_project) { create(:project, :public, name: "Outside #{term}") } let!(:private_project) { create(:project, :private, namespace: nested_group, name: "Private #{term}") } let!(:other_project) { create(:project, :public, namespace: nested_group, name: term.reverse) } # These projects should be found let!(:project1) { create(:project, :internal, namespace: nested_group, name: "Inner #{term} 1") } let!(:project2) { create(:project, :internal, namespace: nested_group, name: "Inner #{term} 2") } let!(:project3) { create(:project, :internal, namespace: nested_group.parent, name: "Outer #{term}") } let(:results) { described_class.new(user, search_group, search: term).execute } subject { results.objects('projects') } context 'in parent group' do let(:search_group) { nested_group.parent } it { is_expected.to match_array([project1, project2, project3]) } end context 'in subgroup' do let(:search_group) { nested_group } it { is_expected.to match_array([project1, project2]) } end end end describe 'basic search' do include_examples 'group search' end context 'issues' do let(:scope) { 'issues' } context 'sorting' do let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, :public, group: group) } let!(:old_result) { create(:issue, project: project, title: 'sorted old', created_at: 1.month.ago) } let!(:new_result) { create(:issue, project: project, title: 'sorted recent', created_at: 1.day.ago) } let!(:very_old_result) { create(:issue, project: project, title: 'sorted very old', created_at: 1.year.ago) } let!(:old_updated) { create(:issue, project: project, title: 'updated old', updated_at: 1.month.ago) } let!(:new_updated) { create(:issue, project: project, title: 'updated recent', updated_at: 1.day.ago) } let!(:very_old_updated) { create(:issue, project: project, title: 'updated very old', updated_at: 1.year.ago) } include_examples 'search results sorted' do let(:results_created) { described_class.new(nil, group, search: 'sorted', sort: sort).execute } let(:results_updated) { described_class.new(nil, group, search: 'updated', sort: sort).execute } end end end context 'merge requests' do let(:scope) { 'merge_requests' } context 'sorting' do let!(:group) { create(:group) } let!(:project) { create(:project, :public, group: group) } let!(:old_result) { create(:merge_request, :opened, source_project: project, source_branch: 'old-1', title: 'sorted old', created_at: 1.month.ago) } let!(:new_result) { create(:merge_request, :opened, source_project: project, source_branch: 'new-1', title: 'sorted recent', created_at: 1.day.ago) } let!(:very_old_result) { create(:merge_request, :opened, source_project: project, source_branch: 'very-old-1', title: 'sorted very old', created_at: 1.year.ago) } let!(:old_updated) { create(:merge_request, :opened, source_project: project, source_branch: 'updated-old-1', title: 'updated old', updated_at: 1.month.ago) } let!(:new_updated) { create(:merge_request, :opened, source_project: project, source_branch: 'updated-new-1', title: 'updated recent', updated_at: 1.day.ago) } let!(:very_old_updated) { create(:merge_request, :opened, source_project: project, source_branch: 'updated-very-old-1', title: 'updated very old', updated_at: 1.year.ago) } include_examples 'search results sorted' do let(:results_created) { described_class.new(nil, group, search: 'sorted', sort: sort).execute } let(:results_updated) { described_class.new(nil, group, search: 'updated', sort: sort).execute } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Issuable class DestroyLabelLinksService BATCH_SIZE = 100 def initialize(target_id, target_type) @target_id = target_id @target_type = target_type end def execute inner_query = LabelLink .select(:id) .for_target(target_id, target_type) .limit(BATCH_SIZE) delete_query = <<~SQL DELETE FROM "#{LabelLink.table_name}" WHERE id IN (#{inner_query.to_sql}) SQL loop do result = LabelLink.connection.execute(delete_query) break if result.cmd_tuples == 0 end end private attr_reader :target_id, :target_type end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::DestroyLabelLinksService, feature_category: :team_planning do describe '#execute' do context 'when target is an Issue' do let_it_be(:target) { create(:issue) } it_behaves_like 'service deleting label links of an issuable' end context 'when target is a MergeRequest' do let_it_be(:target) { create(:merge_request) } it_behaves_like 'service deleting label links of an issuable' end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Issuable class CommonSystemNotesService < ::BaseProjectService attr_reader :issuable def execute(issuable, old_labels: [], old_milestone: nil, is_update: true) @issuable = issuable # We disable touch so that created system notes do not update # the noteable's updated_at field ApplicationRecord.no_touching do if is_update if issuable.previous_changes.include?('title') create_title_change_note(issuable.previous_changes['title'].first) end handle_description_change_note handle_time_tracking_note if issuable.is_a?(TimeTrackable) create_discussion_lock_note if issuable.previous_changes.include?('discussion_locked') end handle_start_date_or_due_date_change_note create_milestone_change_event(old_milestone) if issuable.previous_changes.include?('milestone_id') create_labels_note(old_labels) if old_labels && issuable.labels != old_labels end end private def handle_start_date_or_due_date_change_note # Type check needed as some issuables do their own date change handling for date fields other than due_date change_date_fields = issuable.is_a?(Issue) ? %w[due_date start_date] : %w[due_date] changed_dates = issuable.previous_changes.slice(*change_date_fields) create_start_date_or_due_date_note(changed_dates) end def handle_time_tracking_note if issuable.previous_changes.include?('time_estimate') create_time_estimate_note end if issuable.time_spent? create_time_spent_note end end def handle_description_change_note if issuable.previous_changes.include?('description') if issuable.tasks? && issuable.updated_tasks.any? create_task_status_note else # TODO: Show this note if non-task content was modified. # https://gitlab.com/gitlab-org/gitlab-foss/issues/33577 create_description_change_note end end end def create_draft_note(old_title) return unless issuable.is_a?(MergeRequest) if MergeRequest.draft?(old_title) != issuable.draft? SystemNoteService.handle_merge_request_draft(issuable, issuable.project, current_user) end end def create_labels_note(old_labels) added_labels = issuable.labels - old_labels removed_labels = old_labels - issuable.labels ResourceEvents::ChangeLabelsService .new(issuable, current_user) .execute(added_labels: added_labels, removed_labels: removed_labels) end def create_title_change_note(old_title) create_draft_note(old_title) if issuable.draftless_title_changed(old_title) SystemNoteService.change_title(issuable, issuable.project, current_user, old_title) end end def create_description_change_note SystemNoteService.change_description(issuable, issuable.project, current_user) end def create_task_status_note issuable.updated_tasks.each do |task| SystemNoteService.change_task_status(issuable, issuable.project, current_user, task) end end def create_time_estimate_note SystemNoteService.change_time_estimate(issuable, issuable.project, current_user) end def create_time_spent_note SystemNoteService.change_time_spent(issuable, issuable.project, issuable.time_spent_user) end def create_milestone_change_event(old_milestone) ResourceEvents::ChangeMilestoneService.new(issuable, current_user, old_milestone: old_milestone) .execute end def create_start_date_or_due_date_note(changed_dates) return if changed_dates.blank? SystemNoteService.change_start_date_or_due_date(issuable, issuable.project, current_user, changed_dates) end def create_discussion_lock_note SystemNoteService.discussion_lock(issuable, current_user) end end end Issuable::CommonSystemNotesService.prepend_mod_with('Issuable::CommonSystemNotesService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::CommonSystemNotesService, feature_category: :team_planning do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let(:issuable) { create(:issue, project: project) } shared_examples 'system note for issuable date changes' do it 'creates a system note for due_date set' do issuable.update!(due_date: Date.today) expect { subject }.to change(issuable.notes, :count).from(0).to(1) expect(issuable.notes.last.note).to match('changed due date to') end it 'creates a system note for start_date set' do issuable.update!(start_date: Date.today) expect { subject }.to change(issuable.notes, :count).from(0).to(1) expect(issuable.notes.last.note).to match('changed start date to') end it 'creates a note when both start and due date are changed' do issuable.update!(start_date: Date.today, due_date: 1.week.from_now) expect { subject }.to change { issuable.notes.count }.from(0).to(1) expect(issuable.notes.last.note).to match(/changed start date to.+and changed due date to/) end it 'does not call SystemNoteService if no dates are changed' do issuable.update!(title: 'new title') expect(SystemNoteService).not_to receive(:change_start_date_or_due_date) subject end end context 'on issuable update' do it_behaves_like 'system note creation', { title: 'New title' }, 'changed title' it_behaves_like 'system note creation', { description: 'New description' }, 'changed the description' it_behaves_like 'system note creation', { discussion_locked: true }, 'locked the discussion in this issue' it_behaves_like 'system note creation', { time_estimate: 5 }, 'changed time estimate' context 'when new label is added' do let(:label) { create(:label, project: project) } before do issuable.labels << label issuable.save! end it 'creates a resource label event' do described_class.new(project: project, current_user: user).execute(issuable, old_labels: []) event = issuable.reload.resource_label_events.last expect(event).not_to be_nil expect(event.label_id).to eq label.id expect(event.user_id).to eq user.id end end context 'with merge requests Draft note' do context 'adding Draft note' do let(:issuable) { create(:merge_request, title: "merge request") } it_behaves_like 'system note creation', { title: "Draft: merge request" }, 'marked this merge request as **draft**' context 'and changing title' do before do issuable.update_attribute(:title, "Draft: changed title") end it_behaves_like 'draft notes creation', 'draft' end end context 'removing Draft note' do let(:issuable) { create(:merge_request, title: "Draft: merge request") } it_behaves_like 'system note creation', { title: "merge request" }, 'marked this merge request as **ready**' context 'and changing title' do before do issuable.update_attribute(:title, "changed title") end it_behaves_like 'draft notes creation', 'ready' end end end context 'when changing dates' do it_behaves_like 'system note for issuable date changes' do subject { described_class.new(project: project, current_user: user).execute(issuable) } end end end context 'on issuable create' do let(:issuable) { build(:issue, project: project) } subject { described_class.new(project: project, current_user: user).execute(issuable, old_labels: [], is_update: false) } it 'does not create system note for title and description' do issuable.save! expect { subject }.not_to change { issuable.notes.count } end it 'creates a resource label event for labels added' do label = create(:label, project: project) issuable.labels << label issuable.save! expect { subject }.to change { issuable.resource_label_events.count }.from(0).to(1) event = issuable.reload.resource_label_events.last expect(event).not_to be_nil expect(event.label_id).to eq label.id expect(event.user_id).to eq user.id end context 'when changing milestones' do let_it_be(:milestone) { create(:milestone, project: project) } let_it_be(:issuable) { create(:issue, project: project, milestone: milestone) } it 'does not create a system note for milestone set' do expect { subject }.not_to change { issuable.notes.count } end it 'creates a milestone change event' do expect { subject }.to change { ResourceMilestoneEvent.count }.from(0).to(1) end end context 'when changing dates' do it_behaves_like 'system note for issuable date changes' end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Issuable class DestroyService < IssuableBaseService # TODO: this is to be removed once we get to rename the IssuableBaseService project param to container def initialize(container:, current_user: nil, params: {}) super(container: container, current_user: current_user, params: params) end def execute(issuable) before_destroy(issuable) after_destroy(issuable) if issuable.destroy end private # overriden in EE def before_destroy(issuable); end def after_destroy(issuable) delete_associated_records(issuable) issuable.update_project_counter_caches issuable.assignees.each(&:invalidate_cache_counts) end def group_for(issuable) issuable.resource_parent.group end def delete_associated_records(issuable) actor = group_for(issuable) delete_todos(actor, issuable) delete_label_links(actor, issuable) end def delete_todos(actor, issuable) issuable.run_after_commit_or_now do TodosDestroyer::DestroyedIssuableWorker.perform_async(issuable.id, issuable.class.name) end end def delete_label_links(actor, issuable) issuable.run_after_commit_or_now do Issuable::LabelLinksDestroyWorker.perform_async(issuable.id, issuable.class.name) end end end end Issuable::DestroyService.prepend_mod_with('Issuable::DestroyService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::DestroyService, feature_category: :team_planning do let(:user) { create(:user) } let(:group) { create(:group, :public) } let(:project) { create(:project, :public, group: group) } subject(:service) { described_class.new(container: project, current_user: user) } describe '#execute' do context 'when issuable is an issue' do let!(:issue) { create(:issue, project: project, author: user, assignees: [user]) } it 'destroys the issue' do expect { service.execute(issue) }.to change { project.issues.count }.by(-1) end it 'updates open issues count cache' do expect_any_instance_of(Projects::OpenIssuesCountService).to receive(:refresh_cache) service.execute(issue) end it 'invalidates the issues count cache for the assignees' do expect_any_instance_of(User).to receive(:invalidate_cache_counts).once service.execute(issue) end it_behaves_like 'service deleting todos' do let(:issuable) { issue } end it_behaves_like 'service deleting label links' do let(:issuable) { issue } end end context 'when issuable is a merge request' do let!(:merge_request) { create(:merge_request, target_project: project, source_project: project, author: user, assignees: [user]) } it 'destroys the merge request' do expect { service.execute(merge_request) }.to change { project.merge_requests.count }.by(-1) end it 'updates open merge requests count cache' do expect_any_instance_of(Projects::OpenMergeRequestsCountService).to receive(:refresh_cache) service.execute(merge_request) end it 'invalidates the merge request caches for the MR assignee' do expect_any_instance_of(User).to receive(:invalidate_cache_counts).once service.execute(merge_request) end it_behaves_like 'service deleting todos' do let(:issuable) { merge_request } end it_behaves_like 'service deleting label links' do let(:issuable) { merge_request } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # This service return notes grouped by discussion ID and paginated per discussion. # System notes also have a discussion ID assigned including Synthetic system notes. module Issuable class DiscussionsListService include Gitlab::Utils::StrongMemoize attr_reader :current_user, :issuable, :params def initialize(current_user, issuable, params = {}) @current_user = current_user @issuable = issuable @params = params.dup end def execute return Note.none unless can_read_issuable_notes? notes = NotesFinder.new(current_user, params.merge({ target: issuable, project: issuable.project })) .execute.with_web_entity_associations.inc_relations_for_view(issuable).fresh if paginator paginated_discussions_by_type = paginator.records.group_by(&:table_name) notes = if paginated_discussions_by_type['notes'].present? notes.id_in(paginated_discussions_by_type['notes'].flat_map(&:ids)) else notes.none end end if params[:notes_filter] != UserPreference::NOTES_FILTERS[:only_comments] notes = ResourceEvents::MergeIntoNotesService.new( issuable, current_user, paginated_notes: paginated_discussions_by_type ).execute(notes) end # Here we assume all notes belong to the same project as the work item project = notes.first&.project notes = ::Preloaders::Projects::NotesPreloader.new(project, current_user).call(notes) # we need to check the permission on every note, because some system notes for instance can have references to # resources that some user do not have read access, so those notes are filtered out from the list of notes. # see Note#all_referenced_mentionables_allowed? notes = notes.select { |n| n.readable_by?(current_user) } Discussion.build_collection(notes, issuable) end def paginator return if params[:per_page].blank? strong_memoize(:paginator) do issuable .discussion_root_note_ids(notes_filter: params[:notes_filter]) .keyset_paginate(cursor: params[:cursor], per_page: params[:per_page].to_i) end end def can_read_issuable_notes? return Ability.allowed?(current_user, :read_security_resource, issuable) if issuable.is_a?(Vulnerability) Ability.allowed?(current_user, :"read_#{issuable.to_ability_name}", issuable) && Ability.allowed?(current_user, :read_note, issuable) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::DiscussionsListService, feature_category: :team_planning do let_it_be(:current_user) { create(:user) } let_it_be(:group) { create(:group, :private) } let_it_be(:project) { create(:project, :repository, :private, group: group) } let_it_be(:milestone) { create(:milestone, project: project) } let_it_be(:label) { create(:label, project: project) } let_it_be(:label_2) { create(:label, project: project) } let(:finder_params_for_issuable) { {} } subject(:discussions_service) { described_class.new(current_user, issuable, finder_params_for_issuable) } describe 'fetching notes for issue' do let_it_be(:issuable) { create(:issue, project: project) } it_behaves_like 'listing issuable discussions', :guest, 1, 7 context 'without notes widget' do let_it_be(:issuable) { create(:work_item, project: project) } before do WorkItems::Type.default_by_type(:issue).widget_definitions.find_by_widget_type(:notes).update!(disabled: true) end it "returns no notes" do expect(discussions_service.execute).to be_empty end end context 'when issue exists at the group level' do let_it_be(:issuable) { create(:issue, :group_level, namespace: group) } it_behaves_like 'listing issuable discussions', :guest, 1, 7 end end describe 'fetching notes for merge requests' do let_it_be(:issuable) { create(:merge_request, source_project: project, target_project: project) } it_behaves_like 'listing issuable discussions', :reporter, 0, 6 end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # This follows the rules specified in the specs. # See spec/requests/api/graphql/mutations/merge_requests/set_assignees_spec.rb module Issuable class ProcessAssignees def initialize(assignee_ids:, add_assignee_ids:, remove_assignee_ids:, existing_assignee_ids: nil, extra_assignee_ids: nil) @assignee_ids = assignee_ids&.map(&:to_i) @add_assignee_ids = add_assignee_ids&.map(&:to_i) @remove_assignee_ids = remove_assignee_ids&.map(&:to_i) @existing_assignee_ids = existing_assignee_ids&.map(&:to_i) || [] @extra_assignee_ids = extra_assignee_ids&.map(&:to_i) || [] end def execute updated_new_assignees = new_assignee_ids if add_assignee_ids.blank? && remove_assignee_ids.blank? updated_new_assignees = assignee_ids if assignee_ids else updated_new_assignees |= add_assignee_ids if add_assignee_ids updated_new_assignees -= remove_assignee_ids if remove_assignee_ids end updated_new_assignees.uniq end private attr_accessor :assignee_ids, :add_assignee_ids, :remove_assignee_ids, :existing_assignee_ids, :extra_assignee_ids def new_assignee_ids existing_assignee_ids | extra_assignee_ids end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::ProcessAssignees, feature_category: :team_planning do describe '#execute' do it 'returns assignee_ids when add_assignee_ids and remove_assignee_ids are not specified' do process = described_class.new( assignee_ids: %w[5 7 9], add_assignee_ids: nil, remove_assignee_ids: nil, existing_assignee_ids: %w[1 3 9], extra_assignee_ids: %w[2 5 12] ) result = process.execute expect(result).to contain_exactly(5, 7, 9) end it 'combines other ids when assignee_ids is nil' do process = described_class.new( assignee_ids: nil, add_assignee_ids: nil, remove_assignee_ids: nil, existing_assignee_ids: %w[1 3 11], extra_assignee_ids: %w[2 5 12] ) result = process.execute expect(result).to contain_exactly(1, 2, 3, 5, 11, 12) end it 'combines other ids when both add_assignee_ids and remove_assignee_ids are not empty' do process = described_class.new( assignee_ids: %w[5 7 9], add_assignee_ids: %w[2 4 6], remove_assignee_ids: %w[4 7 11], existing_assignee_ids: %w[1 3 11], extra_assignee_ids: %w[2 5 12] ) result = process.execute expect(result).to contain_exactly(1, 2, 3, 5, 6, 12) end it 'combines other ids when remove_assignee_ids is not empty' do process = described_class.new( assignee_ids: %w[5 7 9], add_assignee_ids: nil, remove_assignee_ids: %w[4 7 11], existing_assignee_ids: %w[1 3 11], extra_assignee_ids: %w[2 5 12] ) result = process.execute expect(result).to contain_exactly(1, 2, 3, 5, 12) end it 'combines other ids when add_assignee_ids is not empty' do process = described_class.new( assignee_ids: %w[5 7 9], add_assignee_ids: %w[2 4 6], remove_assignee_ids: nil, existing_assignee_ids: %w[1 3 11], extra_assignee_ids: %w[2 5 12] ) result = process.execute expect(result).to contain_exactly(1, 2, 4, 3, 5, 6, 11, 12) end it 'combines ids when existing_assignee_ids and extra_assignee_ids are omitted' do process = described_class.new( assignee_ids: %w[5 7 9], add_assignee_ids: %w[2 4 6], remove_assignee_ids: %w[4 7 11] ) result = process.execute expect(result.sort).to eq([2, 6].sort) end it 'handles mixed string and integer arrays' do process = described_class.new( assignee_ids: %w[5 7 9], add_assignee_ids: [2, 4, 6], remove_assignee_ids: %w[4 7 11], existing_assignee_ids: [1, 3, 11], extra_assignee_ids: %w[2 5 12] ) result = process.execute expect(result).to contain_exactly(1, 2, 3, 5, 6, 12) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Issuable class BulkUpdateService include Gitlab::Allowable attr_accessor :parent, :current_user, :params def initialize(parent, user = nil, params = {}) @parent = parent @current_user = user @params = params.dup end def execute(type) model_ids = ids_from_params(params.delete(:issuable_ids)) set_update_params(type) updated_issuables = update_issuables(type, model_ids) if updated_issuables.present? && requires_count_cache_reset?(type) schedule_group_issues_count_reset(updated_issuables) end response_success(payload: { count: updated_issuables.size }) rescue ArgumentError => e response_error(e.message, 422) end private def ids_from_params(issuable_ids) return issuable_ids if issuable_ids.is_a?(Array) issuable_ids.split(',') end def set_update_params(type) params.slice!(*permitted_attrs(type)) if params[:assignee_ids] == [IssuableFinder::Params::NONE.to_s] params[:assignee_ids] = [] end end def permitted_attrs(type) attrs = %i[state_event milestone_id add_label_ids remove_label_ids subscription_event] if type == 'issue' attrs.push(:assignee_ids, :confidential) elsif type == 'merge_request' attrs.push(:assignee_ids) else attrs.push(:assignee_id) end end def update_issuables(type, ids) model_class = type.classify.constantize update_class = type.classify.pluralize.constantize::UpdateService items = find_issuables(parent, model_class, ids) authorized_issuables = [] items.each do |issuable| next unless can?(current_user, :"update_#{type}", issuable) authorized_issuables << issuable update_class.new( **update_class.constructor_container_arg(issuable.issuing_parent), current_user: current_user, params: dup_params ).execute(issuable) end authorized_issuables end def find_issuables(parent, model_class, ids) issuables = model_class.id_in(ids) case parent when Project issuables = issuables.of_projects(parent) when Group issuables = issuables.of_projects(parent.all_projects) else raise ArgumentError, _('A parent must be provided when bulk updating issuables') end issuables.includes_for_bulk_update end # Duplicates params and its top-level values # We cannot use deep_dup because ActiveRecord objects will result # to new records with no id assigned def dup_params dup = HashWithIndifferentAccess.new params.each do |key, value| dup[key] = value.is_a?(ActiveRecord::Base) ? value : value.dup end dup end def response_success(message: nil, payload: nil) ServiceResponse.success(message: message, payload: payload) end def response_error(message, http_status) ServiceResponse.error(message: message, http_status: http_status) end def requires_count_cache_reset?(type) type.to_sym == :issue && params.include?(:state_event) end def schedule_group_issues_count_reset(updated_issuables) group_ids = updated_issuables.map(&:project).map(&:namespace_id) return if group_ids.empty? Issuables::ClearGroupsIssueCounterWorker.perform_async(group_ids) end end end Issuable::BulkUpdateService.prepend_mod_with('Issuable::BulkUpdateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::BulkUpdateService, feature_category: :team_planning do let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project, :repository, namespace: user.namespace) } def bulk_update(issuables, extra_params = {}) bulk_update_params = extra_params .reverse_merge(issuable_ids: Array(issuables).map(&:id).join(',')) type = Array(issuables).first.model_name.param_key Issuable::BulkUpdateService.new(parent, user, bulk_update_params).execute(type) end shared_examples 'updates milestones' do it 'succeeds' do result = bulk_update(issuables, milestone_id: milestone.id) expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(issuables.count) end it 'updates the issuables milestone' do bulk_update(issuables, milestone_id: milestone.id) issuables.each do |issuable| expect(issuable.reload.milestone).to eq(milestone) end end end shared_examples 'updates confidentiality' do it 'succeeds' do result = bulk_update(issuables, confidential: true) expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(issuables.count) end it 'updates the issuables confidentiality' do bulk_update(issuables, confidential: true) issuables.each do |issuable| expect(issuable.reload.confidential).to be(true) end end end shared_examples 'updating labels' do def create_issue_with_labels(labels) create(:labeled_issue, project: project, labels: labels) end let(:issue_all_labels) { create_issue_with_labels([bug, regression, merge_requests]) } let(:issue_bug_and_regression) { create_issue_with_labels([bug, regression]) } let(:issue_bug_and_merge_requests) { create_issue_with_labels([bug, merge_requests]) } let(:issue_no_labels) { create(:issue, project: project) } let(:issues) { [issue_all_labels, issue_bug_and_regression, issue_bug_and_merge_requests, issue_no_labels] } let(:add_labels) { [] } let(:remove_labels) { [] } let(:bulk_update_params) do { add_label_ids: add_labels.map(&:id), remove_label_ids: remove_labels.map(&:id) } end before do bulk_update(issues, bulk_update_params) end context 'when add_label_ids are passed' do let(:issues) { [issue_all_labels, issue_bug_and_merge_requests, issue_no_labels] } let(:add_labels) { [bug, regression, merge_requests] } it 'adds those label IDs to all issues passed' do expect(issues.map(&:reload).map(&:label_ids)).to all(include(*add_labels.map(&:id))) end it 'does not update issues not passed in' do expect(issue_bug_and_regression.label_ids).to contain_exactly(bug.id, regression.id) end end context 'when remove_label_ids are passed' do let(:issues) { [issue_all_labels, issue_bug_and_merge_requests, issue_no_labels] } let(:remove_labels) { [bug, regression, merge_requests] } it 'removes those label IDs from all issues passed' do expect(issues.map(&:reload).map(&:label_ids)).to all(be_empty) end it 'does not update issues not passed in' do expect(issue_bug_and_regression.label_ids).to contain_exactly(bug.id, regression.id) end end context 'when add_label_ids and remove_label_ids are passed' do let(:issues) { [issue_all_labels, issue_bug_and_merge_requests, issue_no_labels] } let(:add_labels) { [bug] } let(:remove_labels) { [merge_requests] } it 'adds the label IDs to all issues passed' do expect(issues.map(&:reload).map(&:label_ids)).to all(include(bug.id)) end it 'removes the label IDs from all issues passed' do expect(issues.map(&:reload).flat_map(&:label_ids)).not_to include(merge_requests.id) end it 'does not update issues not passed in' do expect(issue_bug_and_regression.label_ids).to contain_exactly(bug.id, regression.id) end end end shared_examples 'scheduling cached group count clear' do it 'schedules worker' do expect(Issuables::ClearGroupsIssueCounterWorker).to receive(:perform_async) bulk_update(issuables, params) end end shared_examples 'not scheduling cached group count clear' do it 'does not schedule worker' do expect(Issuables::ClearGroupsIssueCounterWorker).not_to receive(:perform_async) bulk_update(issuables, params) end end shared_examples 'bulk update service' do it 'result count only includes authorized issuables' do all_issues = issues + [create(:issue, project: create(:project, :private))] result = bulk_update(all_issues, { assignee_ids: [user.id] }) expect(result[:count]).to eq(issues.count) end context 'when issuable_ids are passed as an array' do it 'updates assignees' do expect do described_class.new( parent, user, { issuable_ids: issues.map(&:id), assignee_ids: [user.id] } ).execute('issue') issues.each(&:reset) end.to change { issues.flat_map(&:assignee_ids) }.from([]).to([user.id] * 2) end end end context 'with issuables at a project level' do let_it_be_with_reload(:issues) { create_list(:issue, 2, project: project) } let(:parent) { project } it_behaves_like 'bulk update service' context 'with unpermitted attributes' do let(:label) { create(:label, project: project) } it 'does not update the issues' do bulk_update(issues, label_ids: [label.id]) expect(issues.map(&:reload).map(&:label_ids)).not_to include(label.id) end end context 'when issuable update service raises an ArgumentError' do before do allow_next_instance_of(Issues::UpdateService) do |update_service| allow(update_service).to receive(:execute).and_raise(ArgumentError, 'update error') end end it 'returns an error response' do result = bulk_update(issues, add_label_ids: []) expect(result).to be_error expect(result.errors).to contain_exactly('update error') expect(result.http_status).to eq(422) end end describe 'close issues' do it 'succeeds and returns the correct number of issues updated' do result = bulk_update(issues, state_event: 'close') expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(issues.count) end it 'closes all the issues passed' do bulk_update(issues, state_event: 'close') expect(project.issues.opened).to be_empty expect(project.issues.closed).not_to be_empty end it_behaves_like 'scheduling cached group count clear' do let(:issuables) { issues } let(:params) { { state_event: 'close' } } end end describe 'reopen issues' do let_it_be_with_reload(:closed_issues) { create_list(:closed_issue, 2, project: project) } it 'succeeds and returns the correct number of issues updated' do result = bulk_update(closed_issues, state_event: 'reopen') expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(closed_issues.count) end it 'reopens all the issues passed' do bulk_update(closed_issues, state_event: 'reopen') expect(project.issues.closed).to be_empty expect(project.issues.opened).not_to be_empty end it_behaves_like 'scheduling cached group count clear' do let(:issuables) { closed_issues } let(:params) { { state_event: 'reopen' } } end end describe 'updating merge request assignee' do let(:merge_request) { create(:merge_request, target_project: project, source_project: project, assignees: [user]) } context 'when the new assignee ID is a valid user' do it 'succeeds' do new_assignee = create(:user) project.add_developer(new_assignee) result = bulk_update(merge_request, assignee_ids: [user.id, new_assignee.id]) expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(1) end it 'updates the assignee to the user ID passed' do assignee = create(:user) project.add_developer(assignee) expect { bulk_update(merge_request, assignee_ids: [assignee.id]) } .to change { merge_request.reload.assignee_ids }.from([user.id]).to([assignee.id]) end end context "when the new assignee ID is #{IssuableFinder::Params::NONE}" do it 'unassigns the issues' do expect { bulk_update(merge_request, assignee_ids: [IssuableFinder::Params::NONE]) } .to change { merge_request.reload.assignee_ids }.to([]) end end context 'when the new assignee IDs array is empty' do it 'removes all assignees' do expect { bulk_update(merge_request, assignee_ids: []) } .to change(merge_request.assignees, :count).by(-1) end end end describe 'updating issue assignee' do let(:issue) { create(:issue, project: project, assignees: [user]) } context 'when the new assignee ID is a valid user' do it 'succeeds' do new_assignee = create(:user) project.add_developer(new_assignee) result = bulk_update(issue, assignee_ids: [new_assignee.id]) expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(1) end it 'updates the assignee to the user ID passed' do assignee = create(:user) project.add_developer(assignee) expect { bulk_update(issue, assignee_ids: [assignee.id]) } .to change { issue.reload.assignees.first }.from(user).to(assignee) end end context "when the new assignee ID is #{IssuableFinder::Params::NONE}" do it "unassigns the issues" do expect { bulk_update(issue, assignee_ids: [IssuableFinder::Params::NONE.to_s]) } .to change { issue.reload.assignees.count }.from(1).to(0) end end context 'when the new assignee IDs array is empty' do it 'removes all assignees' do expect { bulk_update(issue, assignee_ids: []) } .to change(issue.assignees, :count).by(-1) end end end describe 'updating milestones' do let(:issuables) { [create(:issue, project: project)] } let(:milestone) { create(:milestone, project: project) } it_behaves_like 'updates milestones' it_behaves_like 'not scheduling cached group count clear' do let(:params) { { milestone_id: milestone.id } } end end describe 'updating confidentiality' do let(:issuables) { create_list(:issue, 2, project: project) } it_behaves_like 'updates confidentiality' it_behaves_like 'not scheduling cached group count clear' do let(:params) { { confidential: true } } end end describe 'updating labels' do let(:bug) { create(:label, project: project) } let(:regression) { create(:label, project: project) } let(:merge_requests) { create(:label, project: project) } it_behaves_like 'updating labels' end describe 'subscribe to issues' do let(:issues) { create_list(:issue, 2, project: project) } it 'subscribes the given user' do bulk_update(issues, subscription_event: 'subscribe') expect(issues).to all(be_subscribed(user, project)) end end describe 'unsubscribe from issues' do let(:issues) do create_list(:closed_issue, 2, project: project) do |issue| issue.subscriptions.create!(user: user, project: project, subscribed: true) end end it 'unsubscribes the given user' do bulk_update(issues, subscription_event: 'unsubscribe') issues.each do |issue| expect(issue).not_to be_subscribed(user, project) end end end describe 'updating issues from external project' do it 'updates only issues that belong to the parent project' do issue1 = create(:issue, project: project) issue2 = create(:issue, project: create(:project)) result = bulk_update([issue1, issue2], assignee_ids: [user.id]) expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(1) expect(issue1.reload.assignees).to eq([user]) expect(issue2.reload.assignees).to be_empty end end end context 'with issuables at a group level' do let_it_be(:group) { create(:group) } let(:parent) { group } before do group.add_reporter(user) end it_behaves_like 'bulk update service' do let_it_be_with_reload(:issues) { create_list(:issue, 2, project: create(:project, group: group)) } end describe 'updating milestones' do let(:milestone) { create(:milestone, group: group) } let(:project) { create(:project, :repository, group: group) } before do group.add_maintainer(user) end context 'when issues' do let(:issue1) { create(:issue, project: project) } let(:issue2) { create(:issue, project: project) } let(:issuables) { [issue1, issue2] } it_behaves_like 'updates milestones' end context 'when merge requests' do let(:merge_request1) { create(:merge_request, source_project: project, source_branch: 'branch-1') } let(:merge_request2) { create(:merge_request, source_project: project, source_branch: 'branch-2') } let(:issuables) { [merge_request1, merge_request2] } it_behaves_like 'updates milestones' end end describe 'updating confidentiality' do let_it_be(:project) { create(:project, :repository, group: group) } before do group.add_maintainer(user) end context 'with issues' do let(:issuables) { create_list(:issue, 2, project: project) } it_behaves_like 'updates confidentiality' end context 'with merge requests' do let(:issuables) { [create(:merge_request, source_project: project, target_project: project)] } it 'does not throw an error' do result = bulk_update(issuables, confidential: true) expect(result.success?).to be_truthy end end end describe 'updating labels' do let(:project) { create(:project, :repository, group: group) } let(:bug) { create(:group_label, group: group) } let(:regression) { create(:group_label, group: group) } let(:merge_requests) { create(:group_label, group: group) } it_behaves_like 'updating labels' end describe 'with issues from external group' do it 'updates issues that belong to the parent group or descendants' do issue1 = create(:issue, project: create(:project, group: group)) issue2 = create(:issue, project: create(:project, group: create(:group))) issue3 = create(:issue, project: create(:project, group: create(:group, parent: group))) milestone = create(:milestone, group: group) result = bulk_update([issue1, issue2, issue3], milestone_id: milestone.id) expect(result.success?).to be_truthy expect(result.payload[:count]).to eq(2) expect(issue1.reload.milestone).to eq(milestone) expect(issue2.reload.milestone).to be_nil expect(issue3.reload.milestone).to eq(milestone) end end end context 'when no parent is provided' do it 'returns an unscoped update error' do result = described_class.new(nil, user, { assignee_ids: [user.id], issuable_ids: [] }).execute('issue') expect(result).to be_error expect(result.errors).to contain_exactly(_('A parent must be provided when bulk updating issuables')) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Issuable module ImportCsv class BaseService < ::ImportCsv::BaseService extend ::Gitlab::Utils::Override private override :attributes_for def attributes_for(row) { title: row[:title], description: row[:description], due_date: row[:due_date], milestone_id: find_milestone_by_title(row[:milestone]) } end override :validate_headers_presence! def validate_headers_presence!(headers) headers.downcase! if headers return if headers && headers.include?('title') && headers.include?('description') raise CSV::MalformedCSVError.new('Invalid CSV format - missing required headers.', 1) end def preprocess! preprocess_milestones! raise PreprocessError if results[:preprocess_errors].any? end def preprocess_milestones! # Pre-Process Milestone if header is present return unless csv_data.lines.first.downcase.include?('milestone') provided_titles = with_csv_lines.filter_map { |row| row[:milestone]&.strip }.uniq result = ::ImportCsv::PreprocessMilestonesService.new(user, project, provided_titles).execute @available_milestones = result.payload return if result.success? # collate errors here and throw errors results[:preprocess_errors][:milestone_errors] = result.payload end def find_milestone_by_title(title) return unless title @available_milestones.find { |milestone| milestone.title == title.to_s.strip } if @available_milestones end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::ImportCsv::BaseService, feature_category: :importers do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, group: group) } let_it_be(:csv_io) { double } let(:importer_klass) do Class.new(described_class) do def email_results_to_user # no-op end end end let(:service) do uploader = FileUploader.new(project) uploader.store!(file) importer_klass.new(user, project, uploader) end subject { service.execute } describe '#preprocess_milestones' do let(:utility_class) { ImportCsv::PreprocessMilestonesService } let(:file) { fixture_file_upload('spec/fixtures/csv_missing_milestones.csv') } let(:mocked_object) { double } before do allow(service).to receive(:create_object).and_return(mocked_object) allow(mocked_object).to receive(:persisted?).and_return(true) end context 'with csv that has milestone heading' do before do allow(utility_class).to receive(:new).and_return(utility_class) allow(utility_class).to receive(:execute).and_return(ServiceResponse.success) end it 'calls PreprocessMilestonesService' do subject expect(utility_class).to have_received(:new) end it 'calls PreprocessMilestonesService with unique milestone titles' do subject expect(utility_class).to have_received(:new).with(user, project, %w[15.10 10.1]) expect(utility_class).to have_received(:execute) end end context 'with csv that does not have milestone heading' do let(:file) { fixture_file_upload('spec/fixtures/work_items_valid_types.csv') } before do allow(utility_class).to receive(:new).and_return(utility_class) end it 'does not call PreprocessMilestonesService' do subject expect(utility_class).not_to have_received(:new) end end context 'when one or more milestones do not exist' do it 'returns the expected error in results payload' do results = subject expect(results[:success]).to eq(0) expect(results[:preprocess_errors]).to match({ milestone_errors: { missing: { header: 'Milestone', titles: %w[15.10 10.1] } } }) end end context 'when all milestones exist' do let!(:group_milestone) { create(:milestone, group: group, title: '10.1') } let!(:project_milestone) { create(:milestone, project: project, title: '15.10') } it 'returns a successful response' do results = subject expect(results[:preprocess_errors]).to be_empty expect(results[:success]).to eq(4) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Issuable module Callbacks class Milestone < Base ALLOWED_PARAMS = %i[milestone milestone_id skip_milestone_email].freeze def after_initialize params[:milestone_id] = nil if excluded_in_new_type? return unless params.key?(:milestone_id) && has_permission?(:"set_#{issuable.to_ability_name}_metadata") @old_milestone = issuable.milestone if params[:milestone_id].blank? || params[:milestone_id].to_s == IssuableFinder::Params::NONE issuable.milestone = nil return end resource_group = issuable.project&.group || issuable.try(:namespace) project_ids = [issuable.project&.id].compact milestone = MilestonesFinder.new({ project_ids: project_ids, group_ids: resource_group&.self_and_ancestors&.select(:id), ids: [params[:milestone_id]] }).execute.first issuable.milestone = milestone if milestone end def after_update_commit return unless issuable.previous_changes.include?('milestone_id') update_usage_data_counters send_milestone_change_notification GraphqlTriggers.issuable_milestone_updated(issuable) end def after_save_commit return unless issuable.previous_changes.include?('milestone_id') invalidate_milestone_counters end private def invalidate_milestone_counters [@old_milestone, issuable.milestone].compact.each do |milestone| case issuable when Issue ::Milestones::ClosedIssuesCountService.new(milestone).delete_cache ::Milestones::IssuesCountService.new(milestone).delete_cache when MergeRequest ::Milestones::MergeRequestsCountService.new(milestone).delete_cache end end end def update_usage_data_counters return unless issuable.is_a?(MergeRequest) Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter .track_milestone_changed_action(user: current_user) end def send_milestone_change_notification return if params[:skip_milestone_email] notification_service = NotificationService.new.async if issuable.milestone.nil? notification_service.removed_milestone(issuable, current_user) else notification_service.changed_milestone(issuable, issuable.milestone, current_user) end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Issuable::Callbacks::Milestone, feature_category: :team_planning do let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, :private, group: group) } let_it_be(:project_milestone) { create(:milestone, project: project) } let_it_be(:group_milestone) { create(:milestone, group: group) } let_it_be(:reporter) do create(:user).tap { |u| project.add_reporter(u) } end let(:issuable) { build(:issue, project: project) } let(:current_user) { reporter } let(:params) { { milestone_id: project_milestone.id } } let(:callback) { described_class.new(issuable: issuable, current_user: current_user, params: params) } describe '#after_initialize' do it "sets the issuable's milestone" do expect { callback.after_initialize }.to change { issuable.milestone }.from(nil).to(project_milestone) end context 'when assigning a group milestone' do let(:params) { { milestone_id: group_milestone.id } } it "sets the issuable's milestone" do expect { callback.after_initialize }.to change { issuable.milestone }.from(nil).to(group_milestone) end end context 'when assigning a group milestone outside the project ancestors' do let(:another_group_milestone) { create(:milestone, group: create(:group)) } let(:params) { { milestone_id: another_group_milestone.id } } it "does not change the issuable's milestone" do expect { callback.after_initialize }.not_to change { issuable.milestone } end end context 'when user is not allowed to set issuable metadata' do let(:current_user) { create(:user) } it "does not change the issuable's milestone" do expect { callback.after_initialize }.not_to change { issuable.milestone } end end context 'when unsetting a milestone' do let(:issuable) { create(:issue, project: project, milestone: project_milestone) } context 'when milestone_id is nil' do let(:params) { { milestone_id: nil } } it "unsets the issuable's milestone" do expect { callback.after_initialize }.to change { issuable.milestone }.from(project_milestone).to(nil) end end context 'when milestone_id is an empty string' do let(:params) { { milestone_id: '' } } it "unsets the issuable's milestone" do expect { callback.after_initialize }.to change { issuable.milestone }.from(project_milestone).to(nil) end end context 'when milestone_id is 0' do let(:params) { { milestone_id: '0' } } it "unsets the issuable's milestone" do expect { callback.after_initialize }.to change { issuable.milestone }.from(project_milestone).to(nil) end end context "when milestone_id is '0'" do let(:params) { { milestone_id: 0 } } it "unsets the issuable's milestone" do expect { callback.after_initialize }.to change { issuable.milestone }.from(project_milestone).to(nil) end end context 'when milestone_id is not given' do let(:params) { {} } it "does not unset the issuable's milestone" do expect { callback.after_initialize }.not_to change { issuable.milestone } end end context 'when new type does not support milestones' do let(:params) { { excluded_in_new_type: true } } it "unsets the issuable's milestone" do expect { callback.after_initialize }.to change { issuable.milestone }.from(project_milestone).to(nil) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Namespaces class StatisticsRefresherService RefresherError = Class.new(StandardError) def execute(root_namespace) root_namespace = root_namespace.root_ancestor # just in case the true root isn't passed root_storage_statistics = find_or_create_root_storage_statistics(root_namespace.id) root_storage_statistics.recalculate! rescue ActiveRecord::ActiveRecordError => e raise RefresherError, e.message end private def find_or_create_root_storage_statistics(root_namespace_id) Namespace::RootStorageStatistics .safe_find_or_create_by!(namespace_id: root_namespace_id) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Namespaces::StatisticsRefresherService, '#execute', feature_category: :groups_and_projects do let(:group) { create(:group) } let(:subgroup) { create(:group, parent: group) } let(:projects) { create_list(:project, 5, namespace: group) } let(:service) { described_class.new } context 'without a root storage statistics relation' do it 'creates one' do expect do service.execute(group) end.to change(Namespace::RootStorageStatistics, :count).by(1) expect(group.reload.root_storage_statistics).to be_present end it 'recalculate the namespace statistics' do expect_next_instance_of(Namespace::RootStorageStatistics) do |instance| expect(instance).to receive(:recalculate!).once end service.execute(group) end context 'when given a subgroup' do it 'does not create statistics for the subgroup' do service.execute(subgroup) expect(subgroup.reload.root_storage_statistics).not_to be_present end end end context 'with a root storage statistics relation', :sidekiq_might_not_need_inline do before do Namespace::AggregationSchedule.safe_find_or_create_by!(namespace_id: group.id) end it 'does not create one' do expect do service.execute(group) end.not_to change(Namespace::RootStorageStatistics, :count) end it 'recalculate the namespace statistics' do expect(Namespace::RootStorageStatistics) .to receive(:safe_find_or_create_by!).with({ namespace_id: group.id }) .and_return(group.root_storage_statistics) service.execute(group) end context 'when given a subgroup' do it "recalculates the root namespace's statistics" do expect(Namespace::RootStorageStatistics) .to receive(:safe_find_or_create_by!).with({ namespace_id: group.id }) .and_return(group.root_storage_statistics) service.execute(subgroup) end end end context 'when something goes wrong' do before do allow_next_instance_of(Namespace::RootStorageStatistics) do |instance| allow(instance).to receive(:recalculate!).and_raise(ActiveRecord::ActiveRecordError) end end it 'raises RefreshError' do expect do service.execute(group) end.to raise_error(Namespaces::StatisticsRefresherService::RefresherError) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Namespaces module PackageSettings class UpdateService < BaseContainerService include Gitlab::Utils::StrongMemoize ALLOWED_ATTRIBUTES = %i[maven_duplicates_allowed maven_duplicate_exception_regex generic_duplicates_allowed generic_duplicate_exception_regex maven_package_requests_forwarding nuget_duplicates_allowed nuget_duplicate_exception_regex npm_package_requests_forwarding pypi_package_requests_forwarding lock_maven_package_requests_forwarding lock_npm_package_requests_forwarding lock_pypi_package_requests_forwarding].freeze def execute return ServiceResponse.error(message: 'Access Denied', http_status: 403) unless allowed? if package_settings.update(package_settings_params) ServiceResponse.success(payload: { package_settings: package_settings }) else ServiceResponse.error( message: package_settings.errors.full_messages.to_sentence || 'Bad request', http_status: 400 ) end end private def package_settings strong_memoize(:package_settings) do @container.package_settings end end def allowed? Ability.allowed?(current_user, :admin_package, @container) end def package_settings_params @params.slice(*ALLOWED_ATTRIBUTES) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Namespaces::PackageSettings::UpdateService, feature_category: :package_registry do using RSpec::Parameterized::TableSyntax let_it_be_with_reload(:namespace) { create(:group) } let_it_be(:user) { create(:user) } let_it_be(:params) { {} } describe '#execute' do subject { described_class.new(container: namespace, current_user: user, params: params).execute } shared_examples 'returning a success' do it 'returns a success' do result = subject expect(result.payload[:package_settings]).to be_present expect(result.success?).to be_truthy end end shared_examples 'returning an error' do |message, http_status| it 'returns an error' do result = subject expect(result.message).to eq(message) expect(result.status).to eq(:error) expect(result.http_status).to eq(http_status) end end shared_examples 'updating the namespace package setting' do it_behaves_like 'updating the namespace package setting attributes', from: { maven_duplicates_allowed: true, maven_duplicate_exception_regex: 'SNAPSHOT', generic_duplicates_allowed: true, generic_duplicate_exception_regex: 'foo', nuget_duplicates_allowed: true, nuget_duplicate_exception_regex: 'foo', maven_package_requests_forwarding: true, lock_maven_package_requests_forwarding: false, npm_package_requests_forwarding: nil, lock_npm_package_requests_forwarding: false, pypi_package_requests_forwarding: nil, lock_pypi_package_requests_forwarding: false }, to: { maven_duplicates_allowed: false, maven_duplicate_exception_regex: 'RELEASE', generic_duplicates_allowed: false, generic_duplicate_exception_regex: 'bar', nuget_duplicates_allowed: false, nuget_duplicate_exception_regex: 'bar', maven_package_requests_forwarding: true, lock_maven_package_requests_forwarding: true, npm_package_requests_forwarding: true, lock_npm_package_requests_forwarding: true, pypi_package_requests_forwarding: true, lock_pypi_package_requests_forwarding: true } it_behaves_like 'returning a success' context 'with invalid params' do let_it_be(:params) { { maven_duplicates_allowed: nil } } it_behaves_like 'not creating the namespace package setting' it "doesn't update the maven_duplicates_allowed" do expect { subject } .not_to change { package_settings.reload.maven_duplicates_allowed } end it_behaves_like 'returning an error', 'Maven duplicates allowed is not included in the list', 400 end end shared_examples 'denying access to namespace package setting' do context 'with existing namespace package setting' do it_behaves_like 'not creating the namespace package setting' it_behaves_like 'returning an error', 'Access Denied', 403 end end # To be removed when raise_group_admin_package_permission_to_owner FF is removed shared_examples 'disabling admin_package feature flag' do |action:| before do stub_feature_flags(raise_group_admin_package_permission_to_owner: false) end it_behaves_like "#{action} the namespace package setting" end context 'with existing namespace package setting' do let_it_be(:package_settings) { create(:namespace_package_setting, namespace: namespace) } let_it_be(:params) do { maven_duplicates_allowed: false, maven_duplicate_exception_regex: 'RELEASE', generic_duplicates_allowed: false, generic_duplicate_exception_regex: 'bar', nuget_duplicates_allowed: false, nuget_duplicate_exception_regex: 'bar', maven_package_requests_forwarding: true, lock_maven_package_requests_forwarding: true, npm_package_requests_forwarding: true, lock_npm_package_requests_forwarding: true, pypi_package_requests_forwarding: true, lock_pypi_package_requests_forwarding: true } end where(:user_role, :shared_examples_name) do :owner | 'updating the namespace package setting' :maintainer | 'denying access to namespace package setting' :developer | 'denying access to namespace package setting' :reporter | 'denying access to namespace package setting' :guest | 'denying access to namespace package setting' :anonymous | 'denying access to namespace package setting' end with_them do before do namespace.send("add_#{user_role}", user) unless user_role == :anonymous end it_behaves_like params[:shared_examples_name] it_behaves_like 'disabling admin_package feature flag', action: :updating if params[:user_role] == :maintainer end end context 'without existing namespace package setting' do let_it_be(:package_settings) { namespace.package_settings } where(:user_role, :shared_examples_name) do :owner | 'creating the namespace package setting' :maintainer | 'denying access to namespace package setting' :developer | 'denying access to namespace package setting' :reporter | 'denying access to namespace package setting' :guest | 'denying access to namespace package setting' :anonymous | 'denying access to namespace package setting' end with_them do before do namespace.send("add_#{user_role}", user) unless user_role == :anonymous end it_behaves_like params[:shared_examples_name] it_behaves_like 'disabling admin_package feature flag', action: :creating if params[:user_role] == :maintainer end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module TestHooks class ProjectService < TestHooks::BaseService include Integrations::ProjectTestData include Gitlab::Utils::StrongMemoize attr_writer :project def project @project ||= hook.project end private def data strong_memoize(:data) do case trigger when 'push_events', 'tag_push_events' push_events_data when 'note_events' note_events_data when 'issues_events', 'confidential_issues_events' issues_events_data when 'merge_requests_events' merge_requests_events_data when 'job_events' job_events_data when 'pipeline_events' pipeline_events_data when 'wiki_page_events' wiki_page_events_data when 'releases_events' releases_events_data when 'emoji_events' emoji_events_data end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe TestHooks::ProjectService, feature_category: :code_testing do include AfterNextHelpers let(:current_user) { create(:user) } describe '#execute' do let_it_be(:project) { create(:project, :repository) } let(:hook) { create(:project_hook, project: project) } let(:trigger) { 'not_implemented_events' } let(:service) { described_class.new(hook, current_user, trigger) } let(:sample_data) { { data: 'sample' } } let(:success_result) { { status: :success, http_status: 200, message: 'ok' } } it 'allows to set a custom project' do project = double service.project = project expect(service.project).to eq(project) end context 'hook with not implemented test' do it 'returns error message' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Testing not available for this hook') end end context 'push_events' do let(:trigger) { 'push_events' } let(:trigger_key) { :push_hooks } it 'executes hook' do allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'tag_push_events' do let(:trigger) { 'tag_push_events' } let(:trigger_key) { :tag_push_hooks } it 'executes hook' do allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'note_events' do let(:trigger) { 'note_events' } let(:trigger_key) { :note_hooks } it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the project has notes.') end it 'executes hook' do create(:note, project: project) allow(Gitlab::DataBuilder::Note).to receive(:build).and_return(sample_data) allow_next(NotesFinder).to receive(:execute).and_return(Note.all) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end shared_examples_for 'a test webhook that operates on issues' do let(:issue) { build(:issue) } it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the project has issues.') end it 'executes hook' do allow(issue).to receive(:to_hook_data).and_return(sample_data) allow_next(IssuesFinder).to receive(:execute).and_return([issue]) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'issues_events' do let(:trigger) { 'issues_events' } let(:trigger_key) { :issue_hooks } it_behaves_like 'a test webhook that operates on issues' end context 'confidential_issues_events' do let(:trigger) { 'confidential_issues_events' } let(:trigger_key) { :confidential_issue_hooks } it_behaves_like 'a test webhook that operates on issues' end context 'merge_requests_events' do let(:trigger) { 'merge_requests_events' } let(:trigger_key) { :merge_request_hooks } let(:merge_request) { build(:merge_request) } it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the project has merge requests.') end it 'executes hook' do allow(merge_request).to receive(:to_hook_data).and_return(sample_data) allow_next(MergeRequestsFinder).to receive(:execute).and_return([merge_request]) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'job_events' do let(:trigger) { 'job_events' } let(:trigger_key) { :job_hooks } let(:ci_job) { build(:ci_build) } it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the project has CI jobs.') end it 'executes hook' do allow(Gitlab::DataBuilder::Build).to receive(:build).and_return(sample_data) allow_next(Ci::JobsFinder).to receive(:execute).and_return([ci_job]) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'pipeline_events' do let(:trigger) { 'pipeline_events' } let(:trigger_key) { :pipeline_hooks } let(:pipeline) { build(:ci_empty_pipeline) } it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the project has CI pipelines.') end it 'executes hook' do allow(Gitlab::DataBuilder::Pipeline).to receive(:build).and_return(sample_data) allow_next(Ci::PipelinesFinder).to receive(:execute).and_return([pipeline]) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'wiki_page_events' do let_it_be(:project) { create(:project, :wiki_repo) } let(:trigger) { 'wiki_page_events' } let(:trigger_key) { :wiki_page_hooks } it 'returns error message if wiki disabled' do allow(project).to receive(:wiki_enabled?).and_return(false) expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the wiki is enabled and has pages.') end it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the wiki is enabled and has pages.') end it 'executes hook' do create(:wiki_page, wiki: project.wiki) allow(Gitlab::DataBuilder::WikiPage).to receive(:build).and_return(sample_data) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'releases_events' do let(:trigger) { 'releases_events' } let(:trigger_key) { :release_hooks } let(:release) { build(:release) } it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the project has releases.') end it 'executes hook' do allow(release).to receive(:to_hook_data).and_return(sample_data) allow_next(ReleasesFinder).to receive(:execute).and_return([release]) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'emoji' do let(:trigger) { 'emoji_events' } let(:trigger_key) { :emoji_hooks } it 'returns error message if not enough data' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure the project has notes.') end it 'executes hook' do note = create(:note) allow(project).to receive_message_chain(:notes, :any?).and_return(true) allow(project).to receive_message_chain(:notes, :last).and_return(note) allow(Gitlab::DataBuilder::Emoji).to receive(:build).with(anything, current_user, 'award') .and_return(sample_data) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module TestHooks class SystemService < TestHooks::BaseService include Gitlab::Utils::StrongMemoize private def data strong_memoize(:data) do case trigger when 'push_events', 'tag_push_events' Gitlab::DataBuilder::Push.sample_data when 'repository_update_events' Gitlab::DataBuilder::Repository.sample_data when 'merge_requests_events' merge_requests_events_data end end end def merge_requests_events_data merge_request = MergeRequest.of_projects(current_user.projects.select(:id)).last return { error: s_('TestHooks|Ensure one of your projects has merge requests.') } unless merge_request.present? merge_request.to_hook_data(current_user) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe TestHooks::SystemService, feature_category: :code_testing do include AfterNextHelpers describe '#execute' do let_it_be(:project) { create(:project, :repository) } let(:hook) { create(:system_hook) } let(:service) { described_class.new(hook, project.first_owner, trigger) } let(:success_result) { { status: :success, http_status: 200, message: 'ok' } } before do allow(Project).to receive(:first).and_return(project) end context 'hook with not implemented test' do let(:trigger) { 'not_implemented_events' } it 'returns error message' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Testing not available for this hook') end end context 'push_events' do let(:trigger) { 'push_events' } let(:trigger_key) { :push_hooks } it 'executes hook' do expect(Gitlab::DataBuilder::Push).to receive(:sample_data).and_call_original expect(hook).to receive(:execute).with(Gitlab::DataBuilder::Push::SAMPLE_DATA, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'tag_push_events' do let(:trigger) { 'tag_push_events' } let(:trigger_key) { :tag_push_hooks } it 'executes hook' do allow(project.repository).to receive(:tags).and_return(['tag']) expect(Gitlab::DataBuilder::Push).to receive(:sample_data).and_call_original expect(hook).to receive(:execute).with(Gitlab::DataBuilder::Push::SAMPLE_DATA, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'repository_update_events' do let(:trigger) { 'repository_update_events' } let(:trigger_key) { :repository_update_hooks } it 'executes hook' do expect(Gitlab::DataBuilder::Repository).to receive(:sample_data).and_call_original expect(hook).to receive(:execute).with(Gitlab::DataBuilder::Repository::SAMPLE_DATA, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end context 'merge_requests_events' do let(:trigger) { 'merge_requests_events' } let(:trigger_key) { :merge_request_hooks } let(:merge_request) { build(:merge_request) } let(:sample_data) { { data: 'sample' } } it 'returns error message if the user does not have any repository with a merge request' do expect(hook).not_to receive(:execute) expect(service.execute).to have_attributes(status: :error, message: 'Ensure one of your projects has merge requests.') end it 'executes hook' do expect(MergeRequest).to receive(:of_projects).and_return([merge_request]) expect(merge_request).to receive(:to_hook_data).and_return(sample_data) expect(hook).to receive(:execute).with(sample_data, trigger_key, force: true).and_return(success_result) expect(service.execute).to include(success_result) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # GroupMentionService class # # Used for sending group mention notifications # # Ex. # Integrations::GroupMentionService.new(mentionable, hook_data: data, is_confidential: true).execute # module Integrations class GroupMentionService def initialize(mentionable, hook_data:, is_confidential:) @mentionable = mentionable @hook_data = hook_data @is_confidential = is_confidential end def execute return ServiceResponse.success if mentionable.nil? || hook_data.nil? @hook_data = hook_data.clone # Fake a "group_mention" object kind so integrations can handle this as a separate class of event hook_data[:object_attributes][:object_kind] = hook_data[:object_kind] hook_data[:object_kind] = 'group_mention' if confidential? hook_data[:event_type] = 'group_confidential_mention' hook_scope = :group_confidential_mention_hooks else hook_data[:event_type] = 'group_mention' hook_scope = :group_mention_hooks end groups = mentionable.referenced_groups(mentionable.author) groups.each do |group| group_hook_data = hook_data.merge( mentioned: { object_kind: 'group', name: group.full_path, url: group.web_url } ) group.execute_integrations(group_hook_data, hook_scope) end ServiceResponse.success end private attr_reader :mentionable, :hook_data, :is_confidential def confidential? return is_confidential if is_confidential.present? mentionable.project.visibility_level != Gitlab::VisibilityLevel::PUBLIC end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::GroupMentionService, feature_category: :integrations do subject(:execute) { described_class.new(mentionable, hook_data: hook_data, is_confidential: is_confidential).execute } let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } before do allow(mentionable).to receive(:referenced_groups).with(user).and_return([group]) end shared_examples 'group_mention_hooks' do specify do expect(group).to receive(:execute_integrations).with(anything, :group_mention_hooks) expect(execute).to be_success end end shared_examples 'group_confidential_mention_hooks' do specify do expect(group).to receive(:execute_integrations).with(anything, :group_confidential_mention_hooks) expect(execute).to be_success end end context 'for issue descriptions' do let(:hook_data) { mentionable.to_hook_data(user) } let(:is_confidential) { mentionable.confidential? } context 'in public projects' do let_it_be(:project) { create(:project, :public) } context 'in public issues' do let(:mentionable) do create(:issue, confidential: false, project: project, author: user, description: "@#{group.full_path}") end it_behaves_like 'group_mention_hooks' end context 'in confidential issues' do let(:mentionable) do create(:issue, confidential: true, project: project, author: user, description: "@#{group.full_path}") end it_behaves_like 'group_confidential_mention_hooks' end end context 'in private projects' do let_it_be(:project) { create(:project, :private) } context 'in public issues' do let(:mentionable) do create(:issue, confidential: false, project: project, author: user, description: "@#{group.full_path}") end it_behaves_like 'group_confidential_mention_hooks' end context 'in confidential issues' do let(:mentionable) do create(:issue, confidential: true, project: project, author: user, description: "@#{group.full_path}") end it_behaves_like 'group_confidential_mention_hooks' end end end context 'for merge request descriptions' do let(:hook_data) { mentionable.to_hook_data(user) } let(:is_confidential) { false } let(:mentionable) do create(:merge_request, source_project: project, target_project: project, author: user, description: "@#{group.full_path}") end context 'in public projects' do let_it_be(:project) { create(:project, :public) } it_behaves_like 'group_mention_hooks' end context 'in private projects' do let_it_be(:project) { create(:project, :private) } it_behaves_like 'group_confidential_mention_hooks' end end context 'for issue notes' do let(:hook_data) { Gitlab::DataBuilder::Note.build(mentionable, mentionable.author) } let(:is_confidential) { mentionable.confidential?(include_noteable: true) } context 'in public projects' do let_it_be(:project) { create(:project, :public) } context 'in public issues' do let(:issue) do create(:issue, confidential: false, project: project, author: user, description: "@#{group.full_path}") end context 'for public notes' do let(:mentionable) { create(:note_on_issue, noteable: issue, project: project, author: user) } it_behaves_like 'group_mention_hooks' end context 'for internal notes' do let(:mentionable) { create(:note_on_issue, :confidential, noteable: issue, project: project, author: user) } it_behaves_like 'group_confidential_mention_hooks' end end end context 'in private projects' do let_it_be(:project) { create(:project, :private) } context 'in public issues' do let(:issue) do create(:issue, confidential: false, project: project, author: user, description: "@#{group.full_path}") end context 'for public notes' do let(:mentionable) { create(:note_on_issue, noteable: issue, project: project, author: user) } it_behaves_like 'group_confidential_mention_hooks' end context 'for internal notes' do let(:mentionable) { create(:note_on_issue, :confidential, noteable: issue, project: project, author: user) } it_behaves_like 'group_confidential_mention_hooks' end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations class SlackOptionService UnknownOptionError = Class.new(StandardError) OPTIONS = { 'assignee' => SlackOptions::UserSearchHandler, 'labels' => SlackOptions::LabelSearchHandler }.freeze def initialize(params) @params = params @search_type = params.delete(:action_id) @selected_value = params.delete(:value) @view_id = params.dig(:view, :id) end def execute raise UnknownOptionError, "Unable to handle option: '#{search_type}'" \ unless option?(search_type) handler_class = OPTIONS[search_type] handler_class.new(current_user, selected_value, view_id).execute end private def current_user ChatNames::FindUserService.new( params.dig(:team, :id), params.dig(:user, :id) ).execute end def option?(option) OPTIONS.key?(option) end attr_reader :params, :search_type, :selected_value, :view_id end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackOptionService, feature_category: :integrations do describe '#execute' do subject(:execute) { described_class.new(params).execute } let_it_be(:slack_installation) { create(:slack_integration) } let_it_be(:user) { create(:user) } let_it_be(:chat_name) do create(:chat_name, user: user, team_id: slack_installation.team_id, chat_id: slack_installation.user_id ) end let(:params) do { action_id: action_id, view: { id: 'VHDFR54DSA' }, value: 'Search value', team: { id: slack_installation.team_id }, user: { id: slack_installation.user_id } } end context 'when action_id is assignee' do let(:action_id) { 'assignee' } it 'executes the user search handler' do user_search_handler = described_class::OPTIONS['assignee'] expect_next_instance_of(user_search_handler, chat_name, 'Search value', 'VHDFR54DSA') do |service| expect(service).to receive(:execute).and_return(ServiceResponse.success) end execute end end context 'when action_id is labels' do let(:action_id) { 'labels' } it 'executes the label search handler' do label_search_handler = described_class::OPTIONS['labels'] expect_next_instance_of(label_search_handler, chat_name, 'Search value', 'VHDFR54DSA') do |service| expect(service).to receive(:execute).and_return(ServiceResponse.success) end execute end end context 'when action_id is unknown' do let(:action_id) { 'foo' } it 'raises an error and does not execute a service class' do described_class::OPTIONS.each_value do |service_class| expect(service_class).not_to receive(:new) end expect { execute }.to raise_error(described_class::UnknownOptionError) end end end end