INSTRUCTION
stringlengths
202
35.5k
RESPONSE
stringlengths
75
161k
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Performs the initial handling of event payloads sent from Slack to GitLab. # See `API::Integrations::Slack::Events` which calls this service. module Integrations class SlackEventService URL_VERIFICATION_EVENT = 'url_verification' UnknownEventError = Class.new(StandardError) def initialize(params) # When receiving URL verification events, params[:type] is 'url_verification'. # For all other events we subscribe to, params[:type] is 'event_callback' and # the specific type of the event will be in params[:event][:type]. # Remove both of these from the params before they are passed to the services. type = params.delete(:type) type = params[:event].delete(:type) if type == 'event_callback' @slack_event = type @params = params end def execute raise UnknownEventError, "Unable to handle event type: '#{slack_event}'" unless routable_event? payload = route_event ServiceResponse.success(payload: payload) end private # The `url_verification` slack_event response must be returned to Slack in-request, # so for this event we call the service directly instead of through a worker. # # All other events must be handled asynchronously in order to return a 2xx response # immediately to Slack in the request. See https://api.slack.com/apis/connections/events-api. def route_in_request? slack_event == URL_VERIFICATION_EVENT end def routable_event? route_in_request? || route_to_event_worker? end def route_to_event_worker? SlackEventWorker.event?(slack_event) end # Returns a payload for the service response. def route_event return SlackEvents::UrlVerificationService.new(params).execute if route_in_request? SlackEventWorker.perform_async(slack_event: slack_event, params: params) {} end attr_reader :slack_event, :params end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackEventService, feature_category: :integrations do describe '#execute' do subject(:execute) { described_class.new(params).execute } let(:params) do { type: 'event_callback', event: { type: 'app_home_opened', foo: 'bar' } } end it 'queues a worker and returns success response' do expect(Integrations::SlackEventWorker).to receive(:perform_async) .with( { slack_event: 'app_home_opened', params: { event: { foo: 'bar' } } } ) expect(execute.payload).to eq({}) is_expected.to be_success end context 'when event a url verification request' do let(:params) { { type: 'url_verification', foo: 'bar' } } it 'executes the service instead of queueing a worker and returns success response' do expect(Integrations::SlackEventWorker).not_to receive(:perform_async) expect_next_instance_of(Integrations::SlackEvents::UrlVerificationService, { foo: 'bar' }) do |service| expect(service).to receive(:execute).and_return({ baz: 'qux' }) end expect(execute.payload).to eq({ baz: 'qux' }) is_expected.to be_success end end context 'when event is unknown' do let(:params) { super().merge(event: { type: 'foo' }) } it 'raises an error' do expect { execute }.to raise_error(described_class::UnknownEventError) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations class PropagateService BATCH_SIZE = 10_000 def initialize(integration) @integration = integration end def propagate if integration.instance_level? update_inherited_integrations create_integration_for_groups_without_integration create_integration_for_projects_without_integration else update_inherited_descendant_integrations create_integration_for_groups_without_integration_belonging_to_group create_integration_for_projects_without_integration_belonging_to_group end end def self.propagate(integration) new(integration).propagate end private attr_reader :integration def create_integration_for_projects_without_integration propagate_integrations( Project.without_integration(integration), PropagateIntegrationProjectWorker ) end def update_inherited_integrations propagate_integrations( Integration.by_type(integration.type).inherit_from_id(integration.id), PropagateIntegrationInheritWorker ) end def update_inherited_descendant_integrations propagate_integrations( Integration.inherited_descendants_from_self_or_ancestors_from(integration), PropagateIntegrationInheritDescendantWorker ) end def create_integration_for_groups_without_integration propagate_integrations( Group.without_integration(integration), PropagateIntegrationGroupWorker ) end def create_integration_for_groups_without_integration_belonging_to_group propagate_integrations( integration.group.descendants.without_integration(integration), PropagateIntegrationGroupWorker ) end def create_integration_for_projects_without_integration_belonging_to_group propagate_integrations( Project.without_integration(integration).in_namespace(integration.group.self_and_descendants), PropagateIntegrationProjectWorker ) end def propagate_integrations(relation, worker_class) relation.each_batch(of: BATCH_SIZE) do |records| min_id, max_id = records.pick("MIN(#{relation.table_name}.id), MAX(#{relation.table_name}.id)") worker_class.perform_async(integration.id, min_id, max_id) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::PropagateService, feature_category: :integrations do describe '.propagate' do include JiraIntegrationHelpers before do stub_jira_integration_test end let(:group) { create(:group) } let_it_be(:project) { create(:project) } let_it_be(:instance_integration) { create(:jira_integration, :instance) } let_it_be(:not_inherited_integration) { create(:jira_integration, project: project) } let_it_be(:inherited_integration) do create(:jira_integration, project: create(:project), inherit_from_id: instance_integration.id) end let_it_be(:different_type_inherited_integration) do create(:redmine_integration, project: project, inherit_from_id: instance_integration.id) end context 'with inherited integration' do let(:integration) { inherited_integration } it 'calls to PropagateIntegrationProjectWorker' do expect(PropagateIntegrationInheritWorker).to receive(:perform_async) .with(instance_integration.id, inherited_integration.id, inherited_integration.id) described_class.propagate(instance_integration) end end context 'with a project without integration' do let(:another_project) { create(:project) } it 'calls to PropagateIntegrationProjectWorker' do expect(PropagateIntegrationProjectWorker).to receive(:perform_async) .with(instance_integration.id, another_project.id, another_project.id) described_class.propagate(instance_integration) end end context 'with a group without integration' do it 'calls to PropagateIntegrationProjectWorker' do expect(PropagateIntegrationGroupWorker).to receive(:perform_async) .with(instance_integration.id, group.id, group.id) described_class.propagate(instance_integration) end end context 'for a group-level integration' do let(:group_integration) { create(:jira_integration, :group, group: group) } context 'with a project without integration' do let(:another_project) { create(:project, group: group) } it 'calls to PropagateIntegrationProjectWorker' do expect(PropagateIntegrationProjectWorker).to receive(:perform_async) .with(group_integration.id, another_project.id, another_project.id) described_class.propagate(group_integration) end end context 'with a subgroup without integration' do let(:subgroup) { create(:group, parent: group) } it 'calls to PropagateIntegrationGroupWorker' do expect(PropagateIntegrationGroupWorker).to receive(:perform_async) .with(group_integration.id, subgroup.id, subgroup.id) described_class.propagate(group_integration) end end context 'with a subgroup with integration' do let(:subgroup) { create(:group, parent: group) } let(:subgroup_integration) { create(:jira_integration, :group, group: subgroup, inherit_from_id: group_integration.id) } it 'calls to PropagateIntegrationInheritDescendantWorker' do expect(PropagateIntegrationInheritDescendantWorker).to receive(:perform_async) .with(group_integration.id, subgroup_integration.id, subgroup_integration.id) described_class.propagate(group_integration) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations class SlackInteractionService UnknownInteractionError = Class.new(StandardError) INTERACTIONS = { 'view_closed' => SlackInteractions::IncidentManagement::IncidentModalClosedService, 'view_submission' => SlackInteractions::IncidentManagement::IncidentModalSubmitService, 'block_actions' => SlackInteractions::BlockActionService }.freeze def initialize(params) @interaction_type = params.delete(:type) @params = params end def execute raise UnknownInteractionError, "Unable to handle interaction type: '#{interaction_type}'" \ unless interaction?(interaction_type) service_class = INTERACTIONS[interaction_type] service_class.new(params).execute ServiceResponse.success end private attr_reader :interaction_type, :params def interaction?(type) INTERACTIONS.key?(type) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackInteractionService, feature_category: :integrations do describe '#execute' do subject(:execute) { described_class.new(params).execute } let(:params) do { type: slack_interaction, foo: 'bar' } end context 'when view is closed' do let(:slack_interaction) { 'view_closed' } it 'executes the correct service' do view_closed_service = described_class::INTERACTIONS['view_closed'] expect_next_instance_of(view_closed_service, { foo: 'bar' }) do |service| expect(service).to receive(:execute).and_return(ServiceResponse.success) end execute end end context 'when view is submitted' do let(:slack_interaction) { 'view_submission' } it 'executes the submission service' do view_submission_service = described_class::INTERACTIONS['view_submission'] expect_next_instance_of(view_submission_service, { foo: 'bar' }) do |service| expect(service).to receive(:execute).and_return(ServiceResponse.success) end execute end end context 'when block action service is submitted' do let(:slack_interaction) { 'block_actions' } it 'executes the block actions service' do block_action_service = described_class::INTERACTIONS['block_actions'] expect_next_instance_of(block_action_service, { foo: 'bar' }) do |service| expect(service).to receive(:execute).and_return(ServiceResponse.success) end execute end end context 'when slack_interaction is not known' do let(:slack_interaction) { 'foo' } it 'raises an error and does not execute a service class' do described_class::INTERACTIONS.each_value do |service_class| expect(service_class).not_to receive(:new) end expect { execute }.to raise_error(described_class::UnknownInteractionError) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module SlackOptions class UserSearchHandler # rubocop:disable Search/NamespacedClass include Gitlab::Utils::StrongMemoize def initialize(current_user, search_value, view_id) @current_user = current_user.user @search_value = search_value @view_id = view_id end def execute return ServiceResponse.success(payload: []) unless current_user.can?(:read_project_member, project) members = MembersFinder.new(project, current_user, params: { search: search_value }).execute ServiceResponse.success(payload: build_user_list(members)) end private def project project_id = SlackInteractions::IncidentManagement::IncidentModalOpenedService .cache_read(view_id) return unless project_id Project.find(project_id) end strong_memoize_attr :project def build_user_list(members) return [] unless members user_list = members.map do |member| { text: { type: "plain_text", text: "#{member.user.name} - #{member.user.username}" }, value: member.user.id.to_s } end { options: user_list } end attr_reader :current_user, :search_value, :view_id end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackOptions::UserSearchHandler, feature_category: :integrations do describe '#execute' do let_it_be(:project) { create(:project, :private) } let_it_be(:current_user) { create(:user) } let_it_be(:chat_name) { create(:chat_name, user: current_user) } let_it_be(:user1) { create(:user, name: 'Rajendra Kadam') } let_it_be(:user2) { create(:user, name: 'Rajesh K') } let_it_be(:user3) { create(:user) } let_it_be(:view_id) { 'VXHD54DR' } let(:search_value) { 'Raj' } subject(:execute) { described_class.new(chat_name, search_value, view_id).execute } context 'when user has permissions to read project members' do before do project.add_developer(current_user) project.add_guest(user1) project.add_reporter(user2) project.add_maintainer(user3) end it 'returns the user matching the search term' do expect(Rails.cache).to receive(:read).and_return(project.id) members = execute.payload[:options] user_names = members.map { |member| member.dig(:text, :text) } expect(members.count).to eq(2) expect(user_names).to contain_exactly( "#{user1.name} - #{user1.username}", "#{user2.name} - #{user2.username}" ) end end context 'when user does not have permissions to read project members' do it 'returns empty array' do expect(Rails.cache).to receive(:read).and_return(project.id) expect(MembersFinder).not_to receive(:execute) members = execute.payload expect(members).to be_empty end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module SlackOptions class LabelSearchHandler # rubocop:disable Search/NamespacedClass include Gitlab::Utils::StrongMemoize def initialize(current_user, search_value, view_id) @current_user = current_user.user @search_value = search_value @view_id = view_id end def execute return ServiceResponse.success(payload: []) unless current_user.can?(:read_label, project) labels = LabelsFinder.new( current_user, { project: project, search: search_value } ).execute ServiceResponse.success(payload: build_label_list(labels)) end private def project project_id = Integrations::SlackInteractions::IncidentManagement::IncidentModalOpenedService .cache_read(view_id) return unless project_id Project.find(project_id) end strong_memoize_attr :project def build_label_list(labels) return [] unless labels label_list = labels.map do |label| { text: { type: "plain_text", text: label.name }, value: label.id.to_s } end { options: label_list } end attr_accessor :current_user, :search_value, :view_id end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackOptions::LabelSearchHandler, feature_category: :integrations do describe '#execute' do let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, :private, namespace: group) } let_it_be(:current_user) { create(:user) } let_it_be(:chat_name) { create(:chat_name, user: current_user) } let_it_be(:project_label1) { create(:label, project: project, title: 'Label 1') } let_it_be(:project_label2) { create(:label, project: project, title: 'Label 2') } let_it_be(:group_label1) { create(:group_label, group: group, title: 'LabelG 1') } let_it_be(:group_label2) { create(:group_label, group: group, title: 'glb 2') } let_it_be(:view_id) { 'VXHD54DR' } let(:search_value) { 'Lab' } subject(:execute) { described_class.new(chat_name, search_value, view_id).execute } context 'when user has permission to read project and group labels' do before do allow(Rails.cache).to receive(:read).and_return(project.id) project.add_developer(current_user) end it 'returns the labels matching the search term' do labels = execute.payload[:options] label_names = labels.map { |label| label.dig(:text, :text) } expect(label_names).to contain_exactly( project_label1.name, project_label2.name, group_label1.name ) end end context 'when user does not have permissions to read project/group labels' do it 'returns empty array' do expect(LabelsFinder).not_to receive(:execute) expect(execute.payload).to be_empty end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module Test class ProjectService < Integrations::Test::BaseService include Integrations::ProjectTestData include Gitlab::Utils::StrongMemoize def project strong_memoize(:project) do integration.project end end private def data strong_memoize(:data) do case event || integration.default_test_event when 'push', 'tag_push' push_events_data when 'note', 'confidential_note' note_events_data when 'issue', 'confidential_issue' issues_events_data when 'merge_request' merge_requests_events_data when 'job' job_events_data when 'pipeline' pipeline_events_data when 'wiki_page' wiki_page_events_data when 'deployment' deployment_events_data when 'release' releases_events_data when 'award_emoji' emoji_events_data end end end end end end Integrations::Test::ProjectService.prepend_mod_with('Integrations::Test::ProjectService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::Test::ProjectService, feature_category: :integrations do include AfterNextHelpers describe '#execute' do let_it_be(:project) { create(:project) } let(:integration) { create(:integrations_slack, project: project) } let(:user) { project.first_owner } let(:event) { nil } let(:sample_data) { { data: 'sample' } } let(:success_result) { { success: true, result: {} } } subject { described_class.new(integration, user, event).execute } context 'without event specified' do it 'tests the integration with default data' do allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end context 'with Integrations::PipelinesEmail' do let(:integration) { create(:pipelines_email_integration, project: project) } it_behaves_like 'tests for integration with pipeline data' end end context 'with event specified' do context 'event not supported by integration' do let(:integration) { create(:jira_integration, project: project) } let(:event) { 'push' } it 'returns error message' do expect(subject).to include({ status: :error, message: 'Testing not available for this event' }) end end context 'push' do let(:event) { 'push' } it 'executes integration' do allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end end context 'tag_push' do let(:event) { 'tag_push' } it 'executes integration' do allow(Gitlab::DataBuilder::Push).to receive(:build_sample).and_return(sample_data) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end end context 'note' do let(:event) { 'note' } it 'returns error message if not enough data' do expect(integration).not_to receive(:test) expect(subject).to include({ status: :error, message: 'Ensure the project has notes.' }) end it 'executes integration' 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(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end end shared_examples_for 'a test of an integration that operates on issues' do let(:issue) { build(:issue) } it 'returns error message if not enough data' do expect(integration).not_to receive(:test) expect(subject).to include({ status: :error, message: 'Ensure the project has issues.' }) end it 'executes integration' do allow(project).to receive(:issues).and_return([issue]) allow(issue).to receive(:to_hook_data).and_return(sample_data) allow_next(IssuesFinder).to receive(:execute).and_return([issue]) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end end context 'issue' do let(:event) { 'issue' } it_behaves_like 'a test of an integration that operates on issues' end context 'confidential_issue' do let(:event) { 'confidential_issue' } it_behaves_like 'a test of an integration that operates on issues' end context 'merge_request' do let(:event) { 'merge_request' } let(:merge_request) { build(:merge_request) } it 'returns error message if not enough data' do expect(integration).not_to receive(:test) expect(subject).to include({ status: :error, message: 'Ensure the project has merge requests.' }) end it 'executes integration' do allow(merge_request).to receive(:to_hook_data).and_return(sample_data) allow_next(MergeRequestsFinder).to receive(:execute).and_return([merge_request]) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to include(success_result) end end context 'deployment' do let_it_be(:project) { create(:project, :test_repo) } let(:deployment) { build(:deployment) } let(:event) { 'deployment' } it 'returns error message if not enough data' do expect(integration).not_to receive(:test) expect(subject).to include({ status: :error, message: 'Ensure the project has deployments.' }) end it 'executes integration' do allow(Gitlab::DataBuilder::Deployment).to receive(:build).and_return(sample_data) allow_next(DeploymentsFinder).to receive(:execute).and_return([deployment]) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end end context 'pipeline' do let(:event) { 'pipeline' } let(:pipeline) { build(:ci_pipeline) } it 'returns error message if not enough data' do expect(integration).not_to receive(:test) expect(subject).to include({ status: :error, message: 'Ensure the project has CI pipelines.' }) end it 'executes integration' do allow(Gitlab::DataBuilder::Pipeline).to receive(:build).and_return(sample_data) allow_next(Ci::PipelinesFinder).to receive(:execute).and_return([pipeline]) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end end context 'wiki_page' do let_it_be(:project) { create(:project, :wiki_repo) } let(:event) { 'wiki_page' } it 'returns error message if wiki disabled' do allow(project).to receive(:wiki_enabled?).and_return(false) expect(integration).not_to receive(:test) expect(subject).to include({ status: :error, message: 'Ensure the wiki is enabled and has pages.' }) end it 'returns error message if not enough data' do expect(integration).not_to receive(:test) expect(subject).to include({ status: :error, message: 'Ensure the wiki is enabled and has pages.' }) end it 'executes integration' do create(:wiki_page, wiki: project.wiki) allow(Gitlab::DataBuilder::WikiPage).to receive(:build).and_return(sample_data) expect(integration).to receive(:test).with(sample_data).and_return(success_result) expect(subject).to eq(success_result) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Handles the Slack `app_home_opened` event sent from Slack to GitLab. # Responds with a POST to the Slack API 'views.publish' method. # # See: # - https://api.slack.com/methods/views.publish # - https://api.slack.com/events/app_home_opened module Integrations module SlackEvents class AppHomeOpenedService include Gitlab::Utils::StrongMemoize def initialize(params) @slack_user_id = params.dig(:event, :user) @slack_workspace_id = params[:team_id] end def execute # Legacy Slack App integrations will not yet have a token we can use # to call the Slack API. Do nothing, and consider the service successful. unless slack_installation logger.info( slack_user_id: slack_user_id, slack_workspace_id: slack_workspace_id, message: 'SlackInstallation record has no bot token' ) return ServiceResponse.success end begin response = ::Slack::API.new(slack_installation).post( 'views.publish', payload ) rescue *Gitlab::HTTP::HTTP_ERRORS => e return ServiceResponse .error(message: 'HTTP exception when calling Slack API') .track_exception( as: e.class, slack_user_id: slack_user_id, slack_workspace_id: slack_workspace_id ) end return ServiceResponse.success if response['ok'] # For a list of errors, see: # https://api.slack.com/methods/views.publish#errors ServiceResponse.error( message: 'Slack API returned an error', payload: response ).track_exception( slack_user_id: slack_user_id, slack_workspace_id: slack_workspace_id, response: response.to_h ) end private def slack_installation SlackIntegration.with_bot.find_by_team_id(slack_workspace_id) end strong_memoize_attr :slack_installation def slack_gitlab_user_connection ChatNames::FindUserService.new(slack_workspace_id, slack_user_id).execute end strong_memoize_attr :slack_gitlab_user_connection def payload { user_id: slack_user_id, view: ::Slack::BlockKit::AppHomeOpened.new( slack_user_id, slack_workspace_id, slack_gitlab_user_connection, slack_installation ).build } end def logger Gitlab::IntegrationsLogger end attr_reader :slack_user_id, :slack_workspace_id end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackEvents::AppHomeOpenedService, feature_category: :integrations do describe '#execute' do let_it_be(:slack_installation) { create(:slack_integration) } let(:slack_workspace_id) { slack_installation.team_id } let(:slack_user_id) { 'U0123ABCDEF' } let(:api_url) { "#{Slack::API::BASE_URL}/views.publish" } let(:api_response) { { ok: true } } let(:params) do { team_id: slack_workspace_id, event: { user: slack_user_id }, event_id: 'Ev03SA75UJKB' } end subject(:execute) { described_class.new(params).execute } before do stub_request(:post, api_url) .to_return( status: 200, body: api_response.to_json, headers: { 'Content-Type' => 'application/json' } ) end shared_examples 'there is no bot token' do it 'does not call the Slack API, logs info, and returns a success response' do expect(Gitlab::IntegrationsLogger).to receive(:info).with( { slack_user_id: slack_user_id, slack_workspace_id: slack_workspace_id, message: 'SlackInstallation record has no bot token' } ) is_expected.to be_success end end it 'calls the Slack API correctly and returns a success response' do mock_view = { type: 'home', blocks: [] } expect_next_instance_of(Slack::BlockKit::AppHomeOpened) do |ui| expect(ui).to receive(:build).and_return(mock_view) end is_expected.to be_success expect(WebMock).to have_requested(:post, api_url).with( body: { user_id: slack_user_id, view: mock_view }, headers: { 'Authorization' => "Bearer #{slack_installation.bot_access_token}", 'Content-Type' => 'application/json; charset=utf-8' }) end context 'when the slack installation is a legacy record' do let_it_be(:slack_installation) { create(:slack_integration, :legacy) } it_behaves_like 'there is no bot token' end context 'when the slack installation cannot be found' do let(:slack_workspace_id) { non_existing_record_id } it_behaves_like 'there is no bot token' end context 'when the Slack API call raises an HTTP exception' do before do allow(Gitlab::HTTP).to receive(:post).and_raise(Errno::ECONNREFUSED, 'error message') end it 'tracks the exception and returns an error response' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( Errno::ECONNREFUSED.new('HTTP exception when calling Slack API'), { slack_user_id: slack_user_id, slack_workspace_id: slack_workspace_id } ) is_expected.to be_error end end context 'when the Slack API returns an error' do let(:api_response) { { ok: false, foo: 'bar' } } it 'tracks the exception and returns an error response' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( StandardError.new('Slack API returned an error'), { slack_user_id: slack_user_id, slack_workspace_id: slack_workspace_id, response: api_response.with_indifferent_access } ) is_expected.to be_error end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Returns the special URL verification response expected by Slack when the # GitLab Slack app is first configured to receive Slack events. # # Slack will issue the challenge request to the endpoint that receives events # and expect it to respond with same the `challenge` param back. # # See https://api.slack.com/apis/connections/events-api. module Integrations module SlackEvents class UrlVerificationService def initialize(params) @challenge = params[:challenge] end def execute { challenge: challenge } end private attr_reader :challenge end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackEvents::UrlVerificationService, feature_category: :integrations do describe '#execute' do it 'returns the challenge' do expect(described_class.new({ challenge: 'foo' }).execute).to eq({ challenge: 'foo' }) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module SlackInteractions class BlockActionService ALLOWED_UPDATES_HANDLERS = { 'incident_management_project' => SlackInteractions::SlackBlockActions::IncidentManagement::ProjectUpdateHandler }.freeze def initialize(params) @params = params end def execute actions.each do |action| action_id = action[:action_id] action_handler_class = ALLOWED_UPDATES_HANDLERS[action_id] action_handler_class.new(params, action).execute end end private def actions params[:actions].select { |action| ALLOWED_UPDATES_HANDLERS[action[:action_id]] } end attr_accessor :params end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackInteractions::BlockActionService, feature_category: :integrations do describe '#execute' do let_it_be(:slack_installation) { create(:slack_integration) } let(:params) do { view: { team_id: slack_installation.team_id }, actions: [{ action_id: action_id }] } end subject(:execute) { described_class.new(params).execute } context 'when action_id is incident_management_project' do let(:action_id) { 'incident_management_project' } it 'executes the correct handler' do project_handler = described_class::ALLOWED_UPDATES_HANDLERS['incident_management_project'] expect_next_instance_of(project_handler, params, params[:actions].first) do |handler| expect(handler).to receive(:execute).and_return(ServiceResponse.success) end execute end end context 'when action_id is not known' do let(:action_id) { 'random' } it 'does not execute the handlers' do described_class::ALLOWED_UPDATES_HANDLERS.each_value do |handler_class| expect(handler_class).not_to receive(:new) end execute end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module SlackInteractions module IncidentManagement class IncidentModalSubmitService include GitlabRoutingHelper include Gitlab::Routing IssueCreateError = Class.new(StandardError) def initialize(params) @params = params @values = params.dig(:view, :state, :values) @team_id = params.dig(:team, :id) @user_id = params.dig(:user, :id) @additional_message = '' end def execute create_response = Issues::CreateService.new( container: project, current_user: find_user.user, params: incident_params, perform_spam_check: false ).execute raise IssueCreateError, create_response.errors.to_sentence if create_response.error? incident = create_response.payload[:issue] incident_link = incident_link_text(incident) response = send_to_slack(incident_link) return ServiceResponse.success(payload: { incident: incident }) if response['ok'] ServiceResponse.error( message: _('Something went wrong when sending the incident link to Slack.'), payload: response ).track_exception( response: response.to_h, slack_workspace_id: team_id, slack_user_id: user_id ) rescue StandardError => e send_to_slack(_('There was a problem creating the incident. Please try again.')) ServiceResponse .error( message: e.message ).track_exception( slack_workspace_id: team_id, slack_user_id: user_id, as: e.class ) end private attr_accessor :params, :values, :team_id, :user_id, :additional_message def incident_params { title: values.dig(:title_input, :title, :value), severity: severity, confidential: confidential?, description: description, escalation_status: { status: status }, issue_type: "incident", assignee_ids: [assignee], label_ids: labels } end def strip_markup(string) SlackMarkdownSanitizer.sanitize(string) end def send_to_slack(text) response_url = params.dig(:view, :private_metadata) body = { replace_original: 'true', text: text } Gitlab::HTTP.post( response_url, body: Gitlab::Json.dump(body), headers: { 'Content-Type' => 'application/json' } ) end def incident_link_text(incident) "#{_('New incident has been created')}: " \ "<#{issue_url(incident)}|#{incident.to_reference} " \ "- #{strip_markup(incident.title)}>. #{@additional_message}" end def project project_id = values.dig( :project_and_severity_selector, :incident_management_project, :selected_option, :value) Project.find(project_id) end def find_user ChatNames::FindUserService.new(team_id, user_id).execute end def description description = values.dig(:incident_description, :description, :value) || values.dig(project.id.to_s.to_sym, :description, :value) zoom_link = values.dig(:zoom, :link, :value) return description if zoom_link.blank? "#{description} \n/zoom #{zoom_link}" end def confidential? values.dig(:confidentiality, :confidential, :selected_options).present? end def severity values.dig(:project_and_severity_selector, :severity, :selected_option, :value) || 'unknown' end def status values.dig(:status_and_assignee_selector, :status, :selected_option, :value) end def assignee assignee_id = values.dig(:status_and_assignee_selector, :assignee, :selected_option, :value) return unless assignee_id user = User.find_by_id(assignee_id) member = project.member(user) unless member @additional_message = "However, " \ "#{user.name} was not assigned to the incident as they are not a member in #{project.name}." return end member.user_id end def labels values.dig(:label_selector, :labels, :selected_options)&.pluck(:value) end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackInteractions::IncidentManagement::IncidentModalSubmitService, feature_category: :incident_management do include Gitlab::Routing describe '#execute' do let_it_be(:slack_installation) { create(:slack_integration) } let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:api_url) { 'https://api.slack.com/id/1234' } let_it_be(:chat_name) do create(:chat_name, user: user, team_id: slack_installation.team_id, chat_id: slack_installation.user_id ) end # Setting below params as they are optional, have added values wherever required in specs let(:zoom_link) { '' } let(:severity) { {} } let(:status) { '' } let(:assignee_id) { nil } let(:selected_label_ids) { [] } let(:label_ids) { { selected_options: selected_label_ids } } let(:confidential_selected_options) { [] } let(:confidential) { { selected_options: confidential_selected_options } } let(:title) { 'Incident title' } let(:zoom) do { link: { value: zoom_link } } end let(:params) do { team: { id: slack_installation.team_id }, user: { id: slack_installation.user_id }, view: { private_metadata: api_url, state: { values: { title_input: { title: { value: title } }, incident_description: { description: { value: 'Incident description' } }, project_and_severity_selector: { incident_management_project: { selected_option: { value: project.id.to_s } }, severity: severity }, confidentiality: { confidential: confidential }, zoom: zoom, status_and_assignee_selector: { status: { selected_option: { value: status } }, assignee: { selected_option: { value: assignee_id } } }, label_selector: { labels: label_ids } } } } } end subject(:execute_service) { described_class.new(params).execute } shared_examples 'error in creation' do |error_message| it 'returns error and raises exception' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( described_class::IssueCreateError.new(error_message), { slack_workspace_id: slack_installation.team_id, slack_user_id: slack_installation.user_id } ) expect(Gitlab::HTTP).to receive(:post) .with( api_url, body: Gitlab::Json.dump( { replace_original: 'true', text: 'There was a problem creating the incident. Please try again.' } ), headers: { 'Content-Type' => 'application/json' } ) response = execute_service expect(response).to be_error expect(response.message).to eq(error_message) end end context 'when user has permissions to create incidents' do let(:api_response) { '{"ok":true}' } before do project.add_developer(user) stub_request(:post, api_url) .to_return(body: api_response, headers: { 'Content-Type' => 'application/json' }) end context 'with markup string in title' do let(:title) { '<a href="url">incident title</a>' } let(:incident) { create(:incident, title: title, project: project) } before do allow_next_instance_of(Issues::CreateService) do |service| allow(service).to receive(:execute).and_return( ServiceResponse.success(payload: { issue: incident, error: [] }) ) end end it 'strips the markup and saves sends the title' do expect(Gitlab::HTTP).to receive(:post) .with( api_url, body: Gitlab::Json.dump( { replace_original: 'true', text: "New incident has been created: " \ "<#{issue_url(incident)}|#{incident.to_reference} - a href=\"url\"incident title/a>. " } ), headers: { 'Content-Type' => 'application/json' } ).and_return(api_response) execute_service end end context 'with non-optional params' do it 'creates incident' do response = execute_service incident = response[:incident] expect(response).to be_success expect(incident).not_to be_nil expect(incident.description).to eq('Incident description') expect(incident.author).to eq(user) expect(incident.severity).to eq('unknown') expect(incident.confidential).to be_falsey expect(incident.escalation_status).to be_triggered end it 'sends incident link to slack' do execute_service expect(WebMock).to have_requested(:post, api_url) end end context 'with zoom_link' do let(:zoom_link) { 'https://gitlab.zoom.us/j/1234' } it 'sets zoom link as quick action' do incident = execute_service[:incident] zoom_meeting = ZoomMeeting.find_by_issue_id(incident.id) expect(incident.description).to eq("Incident description") expect(zoom_meeting.url).to eq(zoom_link) end end context 'with confidential and severity' do let(:confidential_selected_options) { ['confidential'] } let(:severity) do { selected_option: { value: 'high' } } end it 'sets confidential and severity' do incident = execute_service[:incident] expect(incident.confidential).to be_truthy expect(incident.severity).to eq('high') end end context 'with incident status' do let(:status) { 'resolved' } it 'sets the incident status' do incident = execute_service[:incident] expect(incident.escalation_status).to be_resolved end end context 'with assignee id' do let(:assignee_id) { user.id.to_s } it 'assigns the incident to user' do incident = execute_service[:incident] expect(incident.assignees).to contain_exactly(user) end context 'when user is not a member of the project' do let(:assignee_id) { create(:user).id.to_s } it 'does not assign the user' do incident = execute_service[:incident] expect(incident.assignees).to be_empty end end end context 'with label ids' do let_it_be(:project_label1) { create(:label, project: project, title: 'Label 1') } let_it_be(:project_label2) { create(:label, project: project, title: 'Label 2') } let(:selected_label_ids) do [ { value: project_label1.id.to_s }, { value: project_label2.id.to_s } ] end it 'assigns the label to the incident' do incident = execute_service[:incident] expect(incident.labels).to contain_exactly(project_label1, project_label2) end end context 'when response is not ok' do let(:api_response) { '{"ok":false}' } it 'returns error response and tracks the exception' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( StandardError.new('Something went wrong when sending the incident link to Slack.'), { response: { 'ok' => false }, slack_workspace_id: slack_installation.team_id, slack_user_id: slack_installation.user_id } ) execute_service end end context 'when incident creation fails' do let(:title) { '' } it_behaves_like 'error in creation', "Title can't be blank" end end context 'when user does not have permission to create incidents' do it_behaves_like 'error in creation', 'Operation not allowed' end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module SlackInteractions module IncidentManagement class IncidentModalOpenedService MAX_PROJECTS = 100 CACHE_EXPIRES_IN = 5.minutes def initialize(slack_installation, current_user, params) @slack_installation = slack_installation @current_user = current_user @team_id = params[:team_id] @response_url = params[:response_url] @trigger_id = params[:trigger_id] end def execute if user_projects.empty? return ServiceResponse.error(message: _('You do not have access to any projects for creating incidents.')) end post_modal end def self.cache_write(view_id, project_id) Rails.cache.write(cache_build_key(view_id), project_id, expires_in: CACHE_EXPIRES_IN) end def self.cache_read(view_id) Rails.cache.read(cache_build_key(view_id)) end private attr_reader :slack_installation, :current_user, :team_id, :response_url, :trigger_id def self.cache_build_key(view_id) "slack:incident_modal_opened:#{view_id}" end def user_projects current_user.projects_where_can_admin_issues.limit(MAX_PROJECTS) end def post_modal begin response = ::Slack::API.new(slack_installation).post( 'views.open', modal_view ) rescue *Gitlab::HTTP::HTTP_ERRORS => e return ServiceResponse .error(message: 'HTTP exception when calling Slack API') .track_exception( as: e.class, slack_workspace_id: team_id ) end if response['ok'] self.class.cache_write(view_id(response), project_id(response)) return ServiceResponse.success(message: _('Please complete the incident creation form.')) end ServiceResponse.error( message: _('Something went wrong while opening the incident form.'), payload: response ).track_exception( response: response.to_h, slack_workspace_id: team_id, slack_user_id: slack_installation.user_id ) end def modal_view { trigger_id: trigger_id, view: modal_payload } end def modal_payload ::Slack::BlockKit::IncidentManagement::IncidentModalOpened.new( user_projects, response_url ).build end def project_id(response) response.dig( 'view', 'state', 'values', 'project_and_severity_selector', 'incident_management_project', 'selected_option', 'value') end def view_id(response) response.dig('view', 'id') end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackInteractions::IncidentManagement::IncidentModalOpenedService, feature_category: :incident_management do describe '#execute' do let_it_be(:slack_installation) { create(:slack_integration) } let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user, developer_projects: [project]) } let_it_be(:trigger_id) { '12345.98765.abcd2358fdea' } let(:slack_workspace_id) { slack_installation.team_id } let(:response_url) { 'https://api.slack.com/id/123' } let(:api_url) { "#{Slack::API::BASE_URL}/views.open" } let(:mock_modal) { { type: 'modal', blocks: [] } } let(:params) do { team_id: slack_workspace_id, response_url: response_url, trigger_id: trigger_id } end before do response = { id: '123', state: { values: { project_and_severity_selector: { incident_management_project: { selected_option: { value: project.id.to_s } } } } } } stub_request(:post, api_url) .to_return( status: 200, body: Gitlab::Json.dump({ ok: true, view: response }), headers: { 'Content-Type' => 'application/json' } ) end subject { described_class.new(slack_installation, user, params) } context 'when triggered' do it 'opens the modal' do expect_next_instance_of(Slack::BlockKit::IncidentManagement::IncidentModalOpened) do |ui| expect(ui).to receive(:build).and_return(mock_modal) end expect(Rails.cache).to receive(:write).with( 'slack:incident_modal_opened:123', project.id.to_s, { expires_in: 5.minutes }) response = subject.execute expect(WebMock).to have_requested(:post, api_url).with( body: { trigger_id: trigger_id, view: mock_modal }, headers: { 'Authorization' => "Bearer #{slack_installation.bot_access_token}", 'Content-Type' => 'application/json; charset=utf-8' }) expect(response.message).to eq('Please complete the incident creation form.') end end context 'when there are no projects with slack integration' do let(:params) do { team_id: 'some_random_id', response_url: response_url, trigger_id: trigger_id } end let(:user) { create(:user) } it 'does not open the modal' do response = subject.execute expect(Rails.cache).not_to receive(:write) expect(response.message).to be('You do not have access to any projects for creating incidents.') end end context 'when Slack API call raises an HTTP exception' do before do allow(Gitlab::HTTP).to receive(:post).and_raise(Errno::ECONNREFUSED, 'error message') end it 'tracks the exception and returns an error response' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( Errno::ECONNREFUSED.new('HTTP exception when calling Slack API'), { slack_workspace_id: slack_workspace_id } ) expect(Rails.cache).not_to receive(:write) expect(subject.execute).to be_error end end context 'when api returns an error' do before do stub_request(:post, api_url) .to_return( status: 404, body: Gitlab::Json.dump({ ok: false }), headers: { 'Content-Type' => 'application/json' } ) end it 'returns error when called' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( StandardError.new('Something went wrong while opening the incident form.'), { response: { "ok" => false }, slack_workspace_id: slack_workspace_id, slack_user_id: slack_installation.user_id } ) expect(Rails.cache).not_to receive(:write) response = subject.execute expect(response.message).to eq('Something went wrong while opening the incident form.') end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module SlackInteractions module IncidentManagement class IncidentModalClosedService def initialize(params) @params = params end def execute begin response = close_modal rescue *Gitlab::HTTP::HTTP_ERRORS => e return ServiceResponse .error(message: 'HTTP exception when calling Slack API') .track_exception( params: params, as: e.class ) end return ServiceResponse.success if response['ok'] ServiceResponse.error( message: _('Something went wrong while closing the incident form.'), payload: response ).track_exception( response: response.to_h, params: params ) end private attr_accessor :params def close_modal request_body = Gitlab::Json.dump(close_request_body) response_url = params.dig(:view, :private_metadata) Gitlab::HTTP.post(response_url, body: request_body, headers: headers) end def close_request_body { replace_original: 'true', text: _('Incident creation cancelled.') } end def headers { 'Content-Type' => 'application/json' } end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackInteractions::IncidentManagement::IncidentModalClosedService, feature_category: :integrations do describe '#execute' do let_it_be(:request_body) do { replace_original: 'true', text: 'Incident creation cancelled.' } end let(:params) do { view: { private_metadata: 'https://api.slack.com/id/1234' } } end let(:service) { described_class.new(params) } before do allow(Gitlab::HTTP).to receive(:post).and_return({ ok: true }) end context 'when executed' do it 'makes the POST call and closes the modal' do expect(Gitlab::HTTP).to receive(:post).with( 'https://api.slack.com/id/1234', body: Gitlab::Json.dump(request_body), headers: { 'Content-Type' => 'application/json' } ) service.execute end end context 'when the POST call raises an HTTP exception' do before do allow(Gitlab::HTTP).to receive(:post).and_raise(Errno::ECONNREFUSED, 'error message') end it 'tracks the exception and returns an error response' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( Errno::ECONNREFUSED.new('HTTP exception when calling Slack API'), { params: params } ) service.execute end end context 'when response is not ok' do before do allow(Gitlab::HTTP).to receive(:post).and_return({ ok: false }) end it 'returns error response and tracks the exception' do expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( StandardError.new('Something went wrong while closing the incident form.'), { response: { ok: false }, params: params } ) service.execute end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Integrations module SlackInteractions module SlackBlockActions module IncidentManagement class ProjectUpdateHandler include Gitlab::Utils::StrongMemoize def initialize(params, action) @view = params[:view] @action = action @team_id = params.dig(:view, :team_id) @user_id = params.dig(:user, :id) end def execute return if project_unchanged? return unless allowed? post_updated_modal end private def allowed? return false unless current_user current_user.can?(:read_project, old_project) && current_user.can?(:read_project, new_project) end def current_user ChatNames::FindUserService.new(team_id, user_id).execute&.user end strong_memoize_attr :current_user def slack_installation SlackIntegration.with_bot.find_by_team_id(team_id) end strong_memoize_attr :slack_installation def post_updated_modal modal = update_modal begin response = ::Slack::API.new(slack_installation).post( 'views.update', { view_id: view[:id], view: modal } ) rescue *::Gitlab::HTTP::HTTP_ERRORS => e return ServiceResponse .error(message: 'HTTP exception when calling Slack API') .track_exception( as: e.class, slack_workspace_id: view[:team_id] ) end return ServiceResponse.success(message: _('Modal updated')) if response['ok'] ServiceResponse.error( message: _('Something went wrong while updating the modal.'), payload: response ).track_exception( response: response.to_h, slack_workspace_id: view[:team_id], slack_user_id: slack_installation.user_id ) end def update_modal updated_view = update_incident_template cleanup(updated_view) end def update_incident_template updated_view = view.dup incident_description_blocks = updated_view[:blocks].select do |block| block[:block_id] == 'incident_description' || block[:block_id] == old_project.id.to_s end incident_description_blocks.first[:element][:initial_value] = read_template_content incident_description_blocks.first[:block_id] = new_project.id.to_s Integrations::SlackInteractions::IncidentManagement::IncidentModalOpenedService .cache_write(view[:id], new_project.id.to_s) updated_view end def new_project Project.find(action.dig(:selected_option, :value)) end strong_memoize_attr :new_project def old_project old_project_id = Integrations::SlackInteractions::IncidentManagement::IncidentModalOpenedService .cache_read(view[:id]) Project.find(old_project_id) if old_project_id end strong_memoize_attr :old_project def project_unchanged? old_project == new_project end def read_template_content new_project.incident_management_setting&.issue_template_content.to_s end def cleanup(view) view.except!( :id, :team_id, :state, :hash, :previous_view_id, :root_view_id, :app_id, :app_installed_team_id, :bot_id) end attr_accessor :view, :action, :team_id, :user_id end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Integrations::SlackInteractions::SlackBlockActions::IncidentManagement::ProjectUpdateHandler, feature_category: :incident_management do describe '#execute' do let_it_be(:slack_installation) { create(:slack_integration) } let_it_be(:old_project) { create(:project) } let_it_be(:new_project) { create(:project) } let_it_be(:user) { create(:user, developer_projects: [old_project, new_project]) } let_it_be(:chat_name) { create(:chat_name, user: user) } let_it_be(:api_url) { "#{Slack::API::BASE_URL}/views.update" } let(:block) do { block_id: 'incident_description', element: { initial_value: '' } } end let(:view) do { id: 'V04EQH1SP27', team_id: slack_installation.team_id, blocks: [block] } end let(:action) do { selected_option: { value: new_project.id.to_s } } end let(:params) do { view: view, user: { id: slack_installation.user_id } } end before do allow_next_instance_of(ChatNames::FindUserService) do |user_service| allow(user_service).to receive(:execute).and_return(chat_name) end stub_request(:post, api_url) .to_return( status: 200, body: Gitlab::Json.dump({ ok: true }), headers: { 'Content-Type' => 'application/json' } ) end shared_examples 'does not make api call' do it 'does not make the api call and returns nil' do expect(Rails.cache).to receive(:read).and_return(project.id.to_s) expect(Rails.cache).not_to receive(:write) expect(execute).to be_nil expect(WebMock).not_to have_requested(:post, api_url) end end subject(:execute) { described_class.new(params, action).execute } context 'when project is updated' do it 'returns success response and updates cache' do expect(Rails.cache).to receive(:read).and_return(old_project.id.to_s) expect(Rails.cache).to receive(:write).with( "slack:incident_modal_opened:#{view[:id]}", new_project.id.to_s, expires_in: 5.minutes ) expect(execute.message).to eq('Modal updated') updated_block = block.dup updated_block[:block_id] = new_project.id.to_s view[:blocks] = [updated_block] expect(WebMock).to have_requested(:post, api_url).with( body: { view_id: view[:id], view: view.except!(:team_id, :id) }, headers: { 'Authorization' => "Bearer #{slack_installation.bot_access_token}", 'Content-Type' => 'application/json; charset=utf-8' }) end end context 'when project is unchanged' do it_behaves_like 'does not make api call' do let(:project) { new_project } end end context 'when user does not have permission to read a project' do it_behaves_like 'does not make api call' do let(:project) { create(:project) } end end context 'when api response is not ok' do before do stub_request(:post, api_url) .to_return( status: 404, body: Gitlab::Json.dump({ ok: false }), headers: { 'Content-Type' => 'application/json' } ) end it 'returns error response' do expect(Rails.cache).to receive(:read).and_return(old_project.id.to_s) expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( StandardError.new('Something went wrong while updating the modal.'), { response: { "ok" => false }, slack_workspace_id: slack_installation.team_id, slack_user_id: slack_installation.user_id } ) expect(execute.message).to eq('Something went wrong while updating the modal.') end end context 'when Slack API call raises an HTTP exception' do before do allow(Gitlab::HTTP).to receive(:post).and_raise(Errno::ECONNREFUSED, 'error message') end it 'tracks the exception and returns an error message' do expect(Rails.cache).to receive(:read).and_return(old_project.id.to_s) expect(::Gitlab::ErrorTracking).to receive(:track_exception) .with( Errno::ECONNREFUSED.new('HTTP exception when calling Slack API'), { slack_workspace_id: slack_installation.team_id } ) expect(execute).to be_error end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GpgKeys class DestroyService < Keys::BaseService BATCH_SIZE = 1000 def execute(key) nullify_signatures(key) key.destroy end private # When a GPG key is deleted, the related signatures have their gpg_key_id column nullified # However, when the number of signatures is large, then a timeout may happen # The signatures are processed in batches before GPG key delete is attempted in order to # avoid timeouts def nullify_signatures(key) key.gpg_signatures.each_batch(of: BATCH_SIZE) do |batch| batch.update_all(gpg_key_id: nil) end end end end GpgKeys::DestroyService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GpgKeys::DestroyService, feature_category: :source_code_management do let_it_be(:user) { create(:user) } let_it_be(:gpg_key) { create(:gpg_key) } subject { described_class.new(user) } it 'destroys the GPG key' do expect { subject.execute(gpg_key) }.to change(GpgKey, :count).by(-1) end it 'nullifies the related signatures in batches' do stub_const("#{described_class}::BATCH_SIZE", 1) first_signature = create(:gpg_signature, gpg_key: gpg_key) second_signature = create(:gpg_signature, gpg_key: gpg_key) third_signature = create(:gpg_signature, gpg_key: create(:another_gpg_key)) control = ActiveRecord::QueryRecorder.new { subject.execute(gpg_key) } expect(control.count).to eq(5) expect(first_signature.reload.gpg_key).to be_nil expect(second_signature.reload.gpg_key).to be_nil expect(third_signature.reload.gpg_key).not_to be_nil end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GpgKeys class CreateService < Keys::BaseService def execute key = create(params) notification_service.new_gpg_key(key) if key.persisted? key end private def create(params) user.gpg_keys.create(params) end end end GpgKeys::CreateService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GpgKeys::CreateService, feature_category: :source_code_management do let(:user) { create(:user) } let(:params) { attributes_for(:gpg_key) } subject { described_class.new(user, params) } context 'notification', :mailer do it 'sends a notification' do perform_enqueued_jobs do subject.execute end should_email(user) end end it 'creates a gpg key' do expect { subject.execute }.to change { user.gpg_keys.where(params).count }.by(1) end context 'when the public key contains subkeys' do let(:params) { attributes_for(:gpg_key_with_subkeys) } it 'generates the gpg subkeys' do gpg_key = subject.execute expect(gpg_key.subkeys.count).to eq(2) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class EnableVisionAiService < ::GoogleCloud::BaseService def execute gcp_project_ids = unique_gcp_project_ids if gcp_project_ids.empty? error("No GCP projects found. Configure a service account or GCP_PROJECT_ID ci variable.") else gcp_project_ids.each do |gcp_project_id| google_api_client.enable_vision_api(gcp_project_id) end success({ gcp_project_ids: gcp_project_ids }) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::EnableVisionAiService, feature_category: :deployment_management do describe 'when a project does not have any gcp projects' do let_it_be(:project) { create(:project) } it 'returns error' do result = described_class.new(project).execute message = 'No GCP projects found. Configure a service account or GCP_PROJECT_ID ci variable.' expect(result[:status]).to eq(:error) expect(result[:message]).to eq(message) end end describe 'when a project has 3 gcp projects' do let_it_be(:project) { create(:project) } before do project.variables.build(environment_scope: 'production', key: 'GCP_PROJECT_ID', value: 'prj-prod') project.variables.build(environment_scope: 'staging', key: 'GCP_PROJECT_ID', value: 'prj-staging') project.save! end it 'enables cloud run, artifacts registry and cloud build', :aggregate_failures do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |instance| expect(instance).to receive(:enable_vision_api).with('prj-prod') expect(instance).to receive(:enable_vision_api).with('prj-staging') end result = described_class.new(project).execute expect(result[:status]).to eq(:success) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class GcpRegionAddOrReplaceService < ::GoogleCloud::BaseService def execute(environment, region) gcp_region_key = Projects::GoogleCloud::GcpRegionsController::GCP_REGION_CI_VAR_KEY change_params = { variable_params: { key: gcp_region_key, value: region, environment_scope: environment } } filter_params = { key: gcp_region_key, filter: { environment_scope: environment } } existing_variable = ::Ci::VariablesFinder.new(project, filter_params).execute.first if existing_variable change_params[:action] = :update change_params[:variable] = existing_variable else change_params[:action] = :create end ::Ci::ChangeVariableService.new(container: project, current_user: current_user, params: change_params).execute end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::GcpRegionAddOrReplaceService, feature_category: :deployment_management do it 'adds and replaces GCP region vars' do project = create(:project, :public) service = described_class.new(project) service.execute('env_1', 'loc_1') service.execute('env_2', 'loc_2') service.execute('env_1', 'loc_3') list = project.variables.reload.filter { |variable| variable.key == Projects::GoogleCloud::GcpRegionsController::GCP_REGION_CI_VAR_KEY } list = list.sort_by(&:environment_scope) aggregate_failures 'testing list of gcp regions' do expect(list.length).to eq(2) # asserting that the first region is replaced expect(list.first.environment_scope).to eq('env_1') expect(list.first.value).to eq('loc_3') expect(list.second.environment_scope).to eq('env_2') expect(list.second.value).to eq('loc_2') end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class SetupCloudsqlInstanceService < ::GoogleCloud::BaseService INSTANCE_STATE_RUNNABLE = 'RUNNABLE' OPERATION_STATE_DONE = 'DONE' DEFAULT_DATABASE_NAME = 'main_db' DEFAULT_DATABASE_USER = 'main_user' def execute return error('Unauthorized user') unless Ability.allowed?(current_user, :admin_project_google_cloud, project) get_instance_response = google_api_client.get_cloudsql_instance(gcp_project_id, instance_name) if get_instance_response.state != INSTANCE_STATE_RUNNABLE return error("CloudSQL instance not RUNNABLE: #{Gitlab::Json.dump(get_instance_response)}") end save_instance_ci_vars(get_instance_response) list_database_response = google_api_client.list_cloudsql_databases(gcp_project_id, instance_name) list_user_response = google_api_client.list_cloudsql_users(gcp_project_id, instance_name) existing_database = list_database_response.items.find { |database| database.name == database_name } existing_user = list_user_response.items.find { |user| user.name == username } if existing_database && existing_user save_database_ci_vars save_user_ci_vars(existing_user) return success end database_response = execute_database_setup(existing_database) return database_response if database_response[:status] == :error save_database_ci_vars user_response = execute_user_setup(existing_user) return user_response if user_response[:status] == :error save_user_ci_vars(existing_user) success rescue Google::Apis::Error => err error(message: Gitlab::Json.dump(err)) end private def instance_name @params[:instance_name] end def database_version @params[:database_version] end def database_name @params.fetch(:database_name, DEFAULT_DATABASE_NAME) end def username @params.fetch(:username, DEFAULT_DATABASE_USER) end def password @password ||= SecureRandom.hex(16) end def save_ci_var(key, value, is_masked = false) create_or_replace_project_vars(environment_name, key, value, @params[:is_protected], is_masked) end def save_instance_ci_vars(cloudsql_instance) primary_ip_address = cloudsql_instance.ip_addresses.first.ip_address connection_name = cloudsql_instance.connection_name save_ci_var('GCP_PROJECT_ID', gcp_project_id) save_ci_var('GCP_CLOUDSQL_INSTANCE_NAME', instance_name) save_ci_var('GCP_CLOUDSQL_CONNECTION_NAME', connection_name) save_ci_var('GCP_CLOUDSQL_PRIMARY_IP_ADDRESS', primary_ip_address) save_ci_var('GCP_CLOUDSQL_VERSION', database_version) end def save_database_ci_vars save_ci_var('GCP_CLOUDSQL_DATABASE_NAME', database_name) end def save_user_ci_vars(user_exists) save_ci_var('GCP_CLOUDSQL_DATABASE_USER', username) save_ci_var('GCP_CLOUDSQL_DATABASE_PASS', user_exists ? user_exists.password : password, true) end def execute_database_setup(database_exists) return success if database_exists database_response = google_api_client.create_cloudsql_database(gcp_project_id, instance_name, database_name) if database_response.status != OPERATION_STATE_DONE return error("Database creation failed: #{Gitlab::Json.dump(database_response)}") end success end def execute_user_setup(existing_user) return success if existing_user user_response = google_api_client.create_cloudsql_user(gcp_project_id, instance_name, username, password) if user_response.status != OPERATION_STATE_DONE return error("User creation failed: #{Gitlab::Json.dump(user_response)}") end success end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::SetupCloudsqlInstanceService, feature_category: :deployment_management do let(:random_user) { create(:user) } let(:project) { create(:project) } let(:list_databases_empty) { Google::Apis::SqladminV1beta4::ListDatabasesResponse.new(items: []) } let(:list_users_empty) { Google::Apis::SqladminV1beta4::ListUsersResponse.new(items: []) } let(:list_databases) do Google::Apis::SqladminV1beta4::ListDatabasesResponse.new( items: [ Google::Apis::SqladminV1beta4::Database.new(name: 'postgres'), Google::Apis::SqladminV1beta4::Database.new(name: 'main_db') ]) end let(:list_users) do Google::Apis::SqladminV1beta4::ListUsersResponse.new( items: [ Google::Apis::SqladminV1beta4::User.new(name: 'postgres'), Google::Apis::SqladminV1beta4::User.new(name: 'main_user') ]) end context 'when unauthorized user triggers worker' do subject do params = { gcp_project_id: :gcp_project_id, instance_name: :instance_name, database_version: :database_version, environment_name: :environment_name, is_protected: :is_protected } described_class.new(project, random_user, params).execute end it 'raises unauthorized error' do message = subject[:message] status = subject[:status] expect(status).to eq(:error) expect(message).to eq('Unauthorized user') end end context 'when authorized user triggers worker' do subject do user = project.creator params = { gcp_project_id: :gcp_project_id, instance_name: :instance_name, database_version: :database_version, environment_name: :environment_name, is_protected: :is_protected } described_class.new(project, user, params).execute end context 'when instance is not RUNNABLE' do let(:get_instance_response_pending) do Google::Apis::SqladminV1beta4::DatabaseInstance.new(state: 'PENDING') end it 'raises error' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_pending) end message = subject[:message] status = subject[:status] expect(status).to eq(:error) expect(message).to eq('CloudSQL instance not RUNNABLE: {"state":"PENDING"}') end end context 'when instance is RUNNABLE' do let(:get_instance_response_runnable) do Google::Apis::SqladminV1beta4::DatabaseInstance.new( connection_name: 'mock-connection-name', ip_addresses: [Struct.new(:ip_address).new('1.2.3.4')], state: 'RUNNABLE' ) end let(:operation_fail) { Google::Apis::SqladminV1beta4::Operation.new(status: 'FAILED') } let(:operation_done) { Google::Apis::SqladminV1beta4::Operation.new(status: 'DONE') } context 'when database creation fails' do it 'raises error' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_runnable) expect(google_api_client).to receive(:create_cloudsql_database).and_return(operation_fail) expect(google_api_client).to receive(:list_cloudsql_databases).and_return(list_databases_empty) expect(google_api_client).to receive(:list_cloudsql_users).and_return(list_users_empty) end message = subject[:message] status = subject[:status] expect(status).to eq(:error) expect(message).to eq('Database creation failed: {"status":"FAILED"}') end end context 'when user creation fails' do it 'raises error' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_runnable) expect(google_api_client).to receive(:create_cloudsql_database).and_return(operation_done) expect(google_api_client).to receive(:create_cloudsql_user).and_return(operation_fail) expect(google_api_client).to receive(:list_cloudsql_databases).and_return(list_databases_empty) expect(google_api_client).to receive(:list_cloudsql_users).and_return(list_users_empty) end message = subject[:message] status = subject[:status] expect(status).to eq(:error) expect(message).to eq('User creation failed: {"status":"FAILED"}') end end context 'when database and user already exist' do it 'does not try to create a database or user' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_runnable) expect(google_api_client).not_to receive(:create_cloudsql_database) expect(google_api_client).not_to receive(:create_cloudsql_user) expect(google_api_client).to receive(:list_cloudsql_databases).and_return(list_databases) expect(google_api_client).to receive(:list_cloudsql_users).and_return(list_users) end status = subject[:status] expect(status).to eq(:success) end end context 'when database already exists' do it 'does not try to create a database' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_runnable) expect(google_api_client).not_to receive(:create_cloudsql_database) expect(google_api_client).to receive(:create_cloudsql_user).and_return(operation_done) expect(google_api_client).to receive(:list_cloudsql_databases).and_return(list_databases) expect(google_api_client).to receive(:list_cloudsql_users).and_return(list_users_empty) end status = subject[:status] expect(status).to eq(:success) end end context 'when user already exists' do it 'does not try to create a user' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_runnable) expect(google_api_client).to receive(:create_cloudsql_database).and_return(operation_done) expect(google_api_client).not_to receive(:create_cloudsql_user) expect(google_api_client).to receive(:list_cloudsql_databases).and_return(list_databases_empty) expect(google_api_client).to receive(:list_cloudsql_users).and_return(list_users) end status = subject[:status] expect(status).to eq(:success) end end context 'when database and user creation succeeds' do it 'stores project CI vars' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_runnable) expect(google_api_client).to receive(:create_cloudsql_database).and_return(operation_done) expect(google_api_client).to receive(:create_cloudsql_user).and_return(operation_done) expect(google_api_client).to receive(:list_cloudsql_databases).and_return(list_databases_empty) expect(google_api_client).to receive(:list_cloudsql_users).and_return(list_users_empty) end subject aggregate_failures 'test generated vars' do variables = project.reload.variables expect(variables.count).to eq(8) expect(variables.find_by(key: 'GCP_PROJECT_ID').value).to eq("gcp_project_id") expect(variables.find_by(key: 'GCP_CLOUDSQL_INSTANCE_NAME').value).to eq("instance_name") expect(variables.find_by(key: 'GCP_CLOUDSQL_CONNECTION_NAME').value).to eq("mock-connection-name") expect(variables.find_by(key: 'GCP_CLOUDSQL_PRIMARY_IP_ADDRESS').value).to eq("1.2.3.4") expect(variables.find_by(key: 'GCP_CLOUDSQL_VERSION').value).to eq("database_version") expect(variables.find_by(key: 'GCP_CLOUDSQL_DATABASE_NAME').value).to eq("main_db") expect(variables.find_by(key: 'GCP_CLOUDSQL_DATABASE_USER').value).to eq("main_user") expect(variables.find_by(key: 'GCP_CLOUDSQL_DATABASE_PASS').value).to be_present end end context 'when the ci variable already exists' do before do create( :ci_variable, project: project, key: 'GCP_PROJECT_ID', value: 'previous_gcp_project_id', environment_scope: :environment_name ) end it 'overwrites existing GCP_PROJECT_ID var' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |google_api_client| expect(google_api_client).to receive(:get_cloudsql_instance).and_return(get_instance_response_runnable) expect(google_api_client).to receive(:create_cloudsql_database).and_return(operation_done) expect(google_api_client).to receive(:create_cloudsql_user).and_return(operation_done) expect(google_api_client).to receive(:list_cloudsql_databases).and_return(list_databases_empty) expect(google_api_client).to receive(:list_cloudsql_users).and_return(list_users_empty) end subject variables = project.reload.variables value = variables.find_by(key: 'GCP_PROJECT_ID', environment_scope: :environment_name).value expect(value).to eq("gcp_project_id") end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class GetCloudsqlInstancesService < ::GoogleCloud::BaseService CLOUDSQL_KEYS = %w[GCP_PROJECT_ID GCP_CLOUDSQL_INSTANCE_NAME GCP_CLOUDSQL_VERSION].freeze def execute group_vars_by_environment(CLOUDSQL_KEYS).map do |environment_scope, value| { ref: environment_scope, gcp_project: value['GCP_PROJECT_ID'], instance_name: value['GCP_CLOUDSQL_INSTANCE_NAME'], version: value['GCP_CLOUDSQL_VERSION'] } end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::GetCloudsqlInstancesService, feature_category: :deployment_management do let(:service) { described_class.new(project) } let(:project) { create(:project) } context 'when project has no registered cloud sql instances' do it 'result is empty' do expect(service.execute.length).to eq(0) end end context 'when project has registered cloud sql instance' do before do keys = %w[ GCP_PROJECT_ID GCP_CLOUDSQL_INSTANCE_NAME GCP_CLOUDSQL_CONNECTION_NAME GCP_CLOUDSQL_PRIMARY_IP_ADDRESS GCP_CLOUDSQL_VERSION GCP_CLOUDSQL_DATABASE_NAME GCP_CLOUDSQL_DATABASE_USER GCP_CLOUDSQL_DATABASE_PASS ] envs = %w[ * STG PRD ] keys.each do |key| envs.each do |env| project.variables.build(protected: false, environment_scope: env, key: key, value: "value-#{key}-#{env}") end end end it 'result is grouped by environment', :aggregate_failures do expect(service.execute).to contain_exactly( { ref: '*', gcp_project: 'value-GCP_PROJECT_ID-*', instance_name: 'value-GCP_CLOUDSQL_INSTANCE_NAME-*', version: 'value-GCP_CLOUDSQL_VERSION-*' }, { ref: 'STG', gcp_project: 'value-GCP_PROJECT_ID-STG', instance_name: 'value-GCP_CLOUDSQL_INSTANCE_NAME-STG', version: 'value-GCP_CLOUDSQL_VERSION-STG' }, { ref: 'PRD', gcp_project: 'value-GCP_PROJECT_ID-PRD', instance_name: 'value-GCP_CLOUDSQL_INSTANCE_NAME-PRD', version: 'value-GCP_CLOUDSQL_VERSION-PRD' } ) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class FetchGoogleIpListService include BaseServiceUtility GOOGLE_IP_RANGES_URL = 'https://www.gstatic.com/ipranges/cloud.json' RESPONSE_BODY_LIMIT = 1.megabyte EXPECTED_CONTENT_TYPE = 'application/json' IpListNotRetrievedError = Class.new(StandardError) def execute # Prevent too many workers from hitting the same HTTP endpoint if ::Gitlab::ApplicationRateLimiter.throttled?(:fetch_google_ip_list, scope: nil) return error("#{self.class} was rate limited") end subnets = fetch_and_update_cache! Gitlab::AppJsonLogger.info( class: self.class.name, message: 'Successfully retrieved Google IP list', subnet_count: subnets.count ) success({ subnets: subnets }) rescue IpListNotRetrievedError => err Gitlab::ErrorTracking.log_exception(err) error('Google IP list not retrieved') end private # Attempts to retrieve and parse the list of IPs from Google. Updates # the internal cache so that the data is accessible. # # Returns an array of IPAddr objects consisting of subnets. def fetch_and_update_cache! parsed_response = fetch_google_ip_list parse_google_prefixes(parsed_response).tap do |subnets| ::ObjectStorage::CDN::GoogleIpCache.update!(subnets) end end def fetch_google_ip_list response = Gitlab::HTTP.get(GOOGLE_IP_RANGES_URL, follow_redirects: false, allow_local_requests: false) validate_response!(response) response.parsed_response end def validate_response!(response) raise IpListNotRetrievedError, "response was #{response.code}" unless response.code == 200 raise IpListNotRetrievedError, "response was nil" unless response.body parsed_response = response.parsed_response unless response.content_type == EXPECTED_CONTENT_TYPE && parsed_response.is_a?(Hash) raise IpListNotRetrievedError, "response was not JSON" end if response.body&.bytesize.to_i > RESPONSE_BODY_LIMIT raise IpListNotRetrievedError, "response was too large: #{response.body.bytesize}" end prefixes = parsed_response['prefixes'] raise IpListNotRetrievedError, "JSON was type #{prefixes.class}, expected Array" unless prefixes.is_a?(Array) raise IpListNotRetrievedError, "#{GOOGLE_IP_RANGES_URL} did not return any IP ranges" if prefixes.empty? response.parsed_response end def parse_google_prefixes(parsed_response) ranges = parsed_response['prefixes'].map do |prefix| ip_range = prefix['ipv4Prefix'] || prefix['ipv6Prefix'] next unless ip_range IPAddr.new(ip_range) end.compact raise IpListNotRetrievedError, "#{GOOGLE_IP_RANGES_URL} did not return any IP ranges" if ranges.empty? ranges end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::FetchGoogleIpListService, :use_clean_rails_memory_store_caching, :clean_gitlab_redis_rate_limiting, feature_category: :build_artifacts do include StubRequests let(:google_cloud_ips) { File.read(Rails.root.join('spec/fixtures/cdn/google_cloud.json')) } let(:headers) { { 'Content-Type' => 'application/json' } } subject { described_class.new.execute } before do WebMock.stub_request(:get, described_class::GOOGLE_IP_RANGES_URL) .to_return(status: 200, body: google_cloud_ips, headers: headers) end describe '#execute' do it 'returns a list of IPAddr subnets and caches the result' do expect(::ObjectStorage::CDN::GoogleIpCache).to receive(:update!).and_call_original expect(subject[:subnets]).to be_an(Array) expect(subject[:subnets]).to all(be_an(IPAddr)) end shared_examples 'IP range retrieval failure' do it 'does not cache the result and logs an error' do expect(Gitlab::ErrorTracking).to receive(:log_exception).and_call_original expect(::ObjectStorage::CDN::GoogleIpCache).not_to receive(:update!) expect(subject[:subnets]).to be_nil end end context 'with rate limit in effect' do before do 10.times { described_class.new.execute } end it 'returns rate limit error' do expect(subject[:status]).to eq(:error) expect(subject[:message]).to eq("#{described_class} was rate limited") end end context 'when the URL returns a 404' do before do WebMock.stub_request(:get, described_class::GOOGLE_IP_RANGES_URL).to_return(status: 404) end it_behaves_like 'IP range retrieval failure' end context 'when the URL returns too large of a payload' do before do stub_const("#{described_class}::RESPONSE_BODY_LIMIT", 300) end it_behaves_like 'IP range retrieval failure' end context 'when the URL returns HTML' do let(:headers) { { 'Content-Type' => 'text/html' } } it_behaves_like 'IP range retrieval failure' end context 'when the URL returns empty results' do let(:google_cloud_ips) { '{}' } it_behaves_like 'IP range retrieval failure' end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class GeneratePipelineService < ::GoogleCloud::BaseService ACTION_DEPLOY_TO_CLOUD_RUN = 'DEPLOY_TO_CLOUD_RUN' ACTION_DEPLOY_TO_CLOUD_STORAGE = 'DEPLOY_TO_CLOUD_STORAGE' ACTION_VISION_AI_PIPELINE = 'VISION_AI_PIPELINE' def execute commit_attributes = generate_commit_attributes create_branch_response = ::Branches::CreateService.new(project, current_user) .execute(commit_attributes[:branch_name], project.default_branch) if create_branch_response[:status] == :error return create_branch_response end branch = create_branch_response[:branch] service = default_branch_gitlab_ci_yml.present? ? ::Files::UpdateService : ::Files::CreateService commit_response = service.new(project, current_user, commit_attributes).execute if commit_response[:status] == :error return commit_response end success({ branch_name: branch.name, commit: commit_response }) end private def action @params[:action] end def generate_commit_attributes case action when ACTION_DEPLOY_TO_CLOUD_RUN branch_name = "deploy-to-cloud-run-#{SecureRandom.hex(8)}" { commit_message: 'Enable Cloud Run deployments', file_path: '.gitlab-ci.yml', file_content: pipeline_content('gcp/cloud-run.gitlab-ci.yml'), branch_name: branch_name, start_branch: branch_name } when ACTION_DEPLOY_TO_CLOUD_STORAGE branch_name = "deploy-to-cloud-storage-#{SecureRandom.hex(8)}" { commit_message: 'Enable Cloud Storage deployments', file_path: '.gitlab-ci.yml', file_content: pipeline_content('gcp/cloud-storage.gitlab-ci.yml'), branch_name: branch_name, start_branch: branch_name } when ACTION_VISION_AI_PIPELINE branch_name = "vision-ai-pipeline-#{SecureRandom.hex(8)}" { commit_message: 'Enable Vision AI Pipeline', file_path: '.gitlab-ci.yml', file_content: pipeline_content('gcp/vision-ai.gitlab-ci.yml'), branch_name: branch_name, start_branch: branch_name } end end def default_branch_gitlab_ci_yml @default_branch_gitlab_ci_yml ||= project.ci_config_for(project.default_branch) end def pipeline_content(include_path) gitlab_ci_yml = ::Gitlab::Ci::Config::Yaml::Loader.new(default_branch_gitlab_ci_yml || '{}').load append_remote_include( gitlab_ci_yml.content, "https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/#{include_path}" ) end def append_remote_include(gitlab_ci_yml, include_url) stages = gitlab_ci_yml['stages'] || [] gitlab_ci_yml['stages'] = if action == ACTION_VISION_AI_PIPELINE (stages + %w[validate detect render]).uniq else (stages + %w[build test deploy]).uniq end includes = gitlab_ci_yml['include'] || [] includes = Array.wrap(includes) includes << { 'remote' => include_url } gitlab_ci_yml['include'] = includes.uniq gitlab_ci_yml.deep_stringify_keys.to_yaml end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::GeneratePipelineService, feature_category: :deployment_management do describe 'for cloud-run' do describe 'when there is no existing pipeline' do let_it_be(:project) { create(:project, :repository) } let_it_be(:maintainer) { create(:user) } let_it_be(:service_params) { { action: described_class::ACTION_DEPLOY_TO_CLOUD_RUN } } let_it_be(:service) { described_class.new(project, maintainer, service_params) } before do project.add_maintainer(maintainer) end it 'creates a new branch with commit for cloud-run deployment' do response = service.execute branch_name = response[:branch_name] commit = response[:commit] local_branches = project.repository.local_branches created_branch = local_branches.find { |branch| branch.name == branch_name } expect(response[:status]).to eq(:success) expect(branch_name).to start_with('deploy-to-cloud-run-') expect(created_branch).to be_present expect(created_branch.target).to eq(commit[:result]) end it 'generated pipeline includes cloud-run deployment' do response = service.execute ref = response[:commit][:result] gitlab_ci_yml = project.ci_config_for(ref) expect(response[:status]).to eq(:success) expect(gitlab_ci_yml).to include('https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/gcp/cloud-run.gitlab-ci.yml') end context 'simulate errors' do it 'fails to create branch' do allow_next_instance_of(Branches::CreateService) do |create_service| allow(create_service).to receive(:execute) .and_return({ status: :error }) end response = service.execute expect(response[:status]).to eq(:error) end it 'fails to commit changes' do allow_next_instance_of(Files::CreateService) do |create_service| allow(create_service).to receive(:execute) .and_return({ status: :error }) end response = service.execute expect(response[:status]).to eq(:error) end end end describe 'when there is an existing pipeline without `deploy` stage' do let_it_be(:project) { create(:project, :repository) } let_it_be(:maintainer) { create(:user) } let_it_be(:service_params) { { action: GoogleCloud::GeneratePipelineService::ACTION_DEPLOY_TO_CLOUD_RUN } } let_it_be(:service) { described_class.new(project, maintainer, service_params) } before_all do project.add_maintainer(maintainer) file_name = '.gitlab-ci.yml' file_content = <<EOF stages: - build - test build-java: stage: build script: mvn clean install test-java: stage: test script: mvn clean test EOF project.repository.create_file( maintainer, file_name, file_content, message: 'Pipeline with three stages and two jobs', branch_name: project.default_branch ) end it 'introduces a `deploy` stage and includes the deploy-to-cloud-run job' do response = service.execute branch_name = response[:branch_name] gitlab_ci_yml = project.ci_config_for(branch_name) pipeline = Gitlab::Config::Loader::Yaml.new(gitlab_ci_yml).load! expect(response[:status]).to eq(:success) expect(pipeline[:stages]).to eq(%w[build test deploy]) expect(pipeline[:include]).to be_present expect(gitlab_ci_yml).to include('https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/gcp/cloud-run.gitlab-ci.yml') end it 'stringifies keys from the existing pipelines' do response = service.execute branch_name = response[:branch_name] gitlab_ci_yml = project.ci_config_for(branch_name) expect(YAML.safe_load(gitlab_ci_yml).keys).to eq(%w[stages build-java test-java include]) end end describe 'when there is an existing pipeline with `deploy` stage' do let_it_be(:project) { create(:project, :repository) } let_it_be(:maintainer) { create(:user) } let_it_be(:service_params) { { action: GoogleCloud::GeneratePipelineService::ACTION_DEPLOY_TO_CLOUD_RUN } } let_it_be(:service) { described_class.new(project, maintainer, service_params) } before do project.add_maintainer(maintainer) file_name = '.gitlab-ci.yml' file_content = <<EOF stages: - build - test - deploy build-java: stage: build script: mvn clean install test-java: stage: test script: mvn clean test EOF project.repository.create_file( maintainer, file_name, file_content, message: 'Pipeline with three stages and two jobs', branch_name: project.default_branch ) end it 'includes the deploy-to-cloud-run job' do response = service.execute branch_name = response[:branch_name] gitlab_ci_yml = project.ci_config_for(branch_name) pipeline = Gitlab::Config::Loader::Yaml.new(gitlab_ci_yml).load! expect(response[:status]).to eq(:success) expect(pipeline[:stages]).to eq(%w[build test deploy]) expect(pipeline[:include]).to be_present expect(gitlab_ci_yml).to include('https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/gcp/cloud-run.gitlab-ci.yml') end end describe 'when there is an existing pipeline with `includes`' do let_it_be(:project) { create(:project, :repository) } let_it_be(:maintainer) { create(:user) } let_it_be(:service_params) { { action: GoogleCloud::GeneratePipelineService::ACTION_DEPLOY_TO_CLOUD_RUN } } let_it_be(:service) { described_class.new(project, maintainer, service_params) } before do project.add_maintainer(maintainer) file_name = '.gitlab-ci.yml' file_content = <<EOF stages: - build - test - deploy include: local: 'some-pipeline.yml' EOF project.repository.create_file( maintainer, file_name, file_content, message: 'Pipeline with three stages and two jobs', branch_name: project.default_branch ) end it 'includes the deploy-to-cloud-run job' do response = service.execute branch_name = response[:branch_name] gitlab_ci_yml = project.ci_config_for(branch_name) pipeline = Gitlab::Config::Loader::Yaml.new(gitlab_ci_yml).load! expect(response[:status]).to eq(:success) expect(pipeline[:stages]).to eq(%w[build test deploy]) expect(pipeline[:include]).to be_present expect(gitlab_ci_yml).to include('https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/gcp/cloud-run.gitlab-ci.yml') end end end describe 'for cloud-storage' do describe 'when there is no existing pipeline' do let_it_be(:project) { create(:project, :repository) } let_it_be(:maintainer) { create(:user) } let_it_be(:service_params) { { action: GoogleCloud::GeneratePipelineService::ACTION_DEPLOY_TO_CLOUD_STORAGE } } let_it_be(:service) { described_class.new(project, maintainer, service_params) } before do project.add_maintainer(maintainer) end it 'creates a new branch with commit for cloud-storage deployment' do response = service.execute branch_name = response[:branch_name] commit = response[:commit] local_branches = project.repository.local_branches search_for_created_branch = local_branches.find { |branch| branch.name == branch_name } expect(response[:status]).to eq(:success) expect(branch_name).to start_with('deploy-to-cloud-storage-') expect(search_for_created_branch).to be_present expect(search_for_created_branch.target).to eq(commit[:result]) end it 'generated pipeline includes cloud-storage deployment' do response = service.execute ref = response[:commit][:result] gitlab_ci_yml = project.ci_config_for(ref) expect(response[:status]).to eq(:success) expect(gitlab_ci_yml).to include('https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/gcp/cloud-storage.gitlab-ci.yml') end end end describe 'for vision ai' do let_it_be(:project) { create(:project, :repository) } let_it_be(:maintainer) { create(:user) } let_it_be(:service_params) { { action: described_class::ACTION_VISION_AI_PIPELINE } } let_it_be(:service) { described_class.new(project, maintainer, service_params) } describe 'when there is no existing pipeline' do before do project.add_maintainer(maintainer) end it 'creates a new branch with commit for cloud-run deployment' do response = service.execute branch_name = response[:branch_name] commit = response[:commit] local_branches = project.repository.local_branches created_branch = local_branches.find { |branch| branch.name == branch_name } expect(response[:status]).to eq(:success) expect(branch_name).to start_with('vision-ai-pipeline-') expect(created_branch).to be_present expect(created_branch.target).to eq(commit[:result]) end it 'generated pipeline includes vision ai deployment' do response = service.execute ref = response[:commit][:result] gitlab_ci_yml = project.ci_config_for(ref) expect(response[:status]).to eq(:success) expect(gitlab_ci_yml).to include('https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/gcp/vision-ai.gitlab-ci.yml') end context 'simulate errors' do it 'fails to create branch' do allow_next_instance_of(Branches::CreateService) do |create_service| allow(create_service).to receive(:execute) .and_return({ status: :error }) end response = service.execute expect(response[:status]).to eq(:error) end it 'fails to commit changes' do allow_next_instance_of(Files::CreateService) do |create_service| allow(create_service).to receive(:execute) .and_return({ status: :error }) end response = service.execute expect(response[:status]).to eq(:error) end end end describe 'when there is an existing pipeline with `includes`' do before do project.add_maintainer(maintainer) file_name = '.gitlab-ci.yml' file_content = <<EOF stages: - validate - detect - render include: local: 'some-pipeline.yml' EOF project.repository.create_file( maintainer, file_name, file_content, message: 'Pipeline with three stages and two jobs', branch_name: project.default_branch ) end it 'includes the vision ai pipeline' do response = service.execute branch_name = response[:branch_name] gitlab_ci_yml = project.ci_config_for(branch_name) pipeline = Gitlab::Config::Loader::Yaml.new(gitlab_ci_yml).load! expect(response[:status]).to eq(:success) expect(pipeline[:stages]).to eq(%w[validate detect render]) expect(pipeline[:include]).to be_present expect(gitlab_ci_yml).to include('https://gitlab.com/gitlab-org/incubation-engineering/five-minute-production/library/-/raw/main/gcp/vision-ai.gitlab-ci.yml') end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class EnableCloudRunService < ::GoogleCloud::BaseService def execute gcp_project_ids = unique_gcp_project_ids if gcp_project_ids.empty? error("No GCP projects found. Configure a service account or GCP_PROJECT_ID ci variable.") else gcp_project_ids.each do |gcp_project_id| google_api_client.enable_cloud_run(gcp_project_id) google_api_client.enable_artifacts_registry(gcp_project_id) google_api_client.enable_cloud_build(gcp_project_id) end success({ gcp_project_ids: gcp_project_ids }) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::EnableCloudRunService, feature_category: :deployment_management do describe 'when a project does not have any gcp projects' do let_it_be(:project) { create(:project) } it 'returns error' do result = described_class.new(project).execute expect(result[:status]).to eq(:error) expect(result[:message]).to eq('No GCP projects found. Configure a service account or GCP_PROJECT_ID ci variable.') end end describe 'when a project has 3 gcp projects' do let_it_be(:project) { create(:project) } before do project.variables.build(environment_scope: 'production', key: 'GCP_PROJECT_ID', value: 'prj-prod') project.variables.build(environment_scope: 'staging', key: 'GCP_PROJECT_ID', value: 'prj-staging') project.save! end it 'enables cloud run, artifacts registry and cloud build', :aggregate_failures do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |instance| expect(instance).to receive(:enable_cloud_run).with('prj-prod') expect(instance).to receive(:enable_artifacts_registry).with('prj-prod') expect(instance).to receive(:enable_cloud_build).with('prj-prod') expect(instance).to receive(:enable_cloud_run).with('prj-staging') expect(instance).to receive(:enable_artifacts_registry).with('prj-staging') expect(instance).to receive(:enable_cloud_build).with('prj-staging') end result = described_class.new(project).execute expect(result[:status]).to eq(:success) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class EnableCloudsqlService < ::GoogleCloud::BaseService def execute create_or_replace_project_vars(environment_name, 'GCP_PROJECT_ID', gcp_project_id, ci_var_protected?) unique_gcp_project_ids.each do |gcp_project_id| google_api_client.enable_cloud_sql_admin(gcp_project_id) google_api_client.enable_compute(gcp_project_id) google_api_client.enable_service_networking(gcp_project_id) end success({ gcp_project_ids: unique_gcp_project_ids }) rescue Google::Apis::Error => err error(err.message) end private def ci_var_protected? ProtectedBranch.protected?(project, environment_name) || ProtectedTag.protected?(project, environment_name) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::EnableCloudsqlService, feature_category: :deployment_management do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:params) do { google_oauth2_token: 'mock-token', gcp_project_id: 'mock-gcp-project-id', environment_name: 'main' } end subject(:result) { described_class.new(project, user, params).execute } context 'when a project does not have any GCP_PROJECT_IDs configured' do it 'creates GCP_PROJECT_ID project var' do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |instance| expect(instance).to receive(:enable_cloud_sql_admin).with('mock-gcp-project-id') expect(instance).to receive(:enable_compute).with('mock-gcp-project-id') expect(instance).to receive(:enable_service_networking).with('mock-gcp-project-id') end expect(result[:status]).to eq(:success) expect(project.variables.count).to eq(1) expect(project.variables.first.key).to eq('GCP_PROJECT_ID') expect(project.variables.first.value).to eq('mock-gcp-project-id') end end context 'when a project has GCP_PROJECT_IDs configured' do before do project.variables.build(environment_scope: 'production', key: 'GCP_PROJECT_ID', value: 'prj-prod') project.variables.build(environment_scope: 'staging', key: 'GCP_PROJECT_ID', value: 'prj-staging') project.save! end after do project.variables.destroy_all # rubocop:disable Cop/DestroyAll project.save! end it 'enables cloudsql, compute and service networking Google APIs', :aggregate_failures do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |instance| expect(instance).to receive(:enable_cloud_sql_admin).with('mock-gcp-project-id') expect(instance).to receive(:enable_compute).with('mock-gcp-project-id') expect(instance).to receive(:enable_service_networking).with('mock-gcp-project-id') expect(instance).to receive(:enable_cloud_sql_admin).with('prj-prod') expect(instance).to receive(:enable_compute).with('prj-prod') expect(instance).to receive(:enable_service_networking).with('prj-prod') expect(instance).to receive(:enable_cloud_sql_admin).with('prj-staging') expect(instance).to receive(:enable_compute).with('prj-staging') expect(instance).to receive(:enable_service_networking).with('prj-staging') end expect(result[:status]).to eq(:success) end context 'when Google APIs raise an error' do it 'returns error result' do allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |instance| allow(instance).to receive(:enable_cloud_sql_admin).with('mock-gcp-project-id') allow(instance).to receive(:enable_compute).with('mock-gcp-project-id') allow(instance).to receive(:enable_service_networking).with('mock-gcp-project-id') allow(instance).to receive(:enable_cloud_sql_admin).with('prj-prod') allow(instance).to receive(:enable_compute).with('prj-prod') allow(instance).to receive(:enable_service_networking).with('prj-prod') allow(instance).to receive(:enable_cloud_sql_admin).with('prj-staging') allow(instance).to receive(:enable_compute).with('prj-staging') allow(instance).to receive(:enable_service_networking).with('prj-staging') .and_raise(Google::Apis::Error.new('error')) end expect(result[:status]).to eq(:error) expect(result[:message]).to eq('error') end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud class CreateServiceAccountsService < ::GoogleCloud::BaseService def execute service_account = google_api_client.create_service_account(gcp_project_id, service_account_name, service_account_desc) service_account_key = google_api_client.create_service_account_key(gcp_project_id, service_account.unique_id) google_api_client.grant_service_account_roles(gcp_project_id, service_account.email) service_accounts_service.add_for_project( environment_name, service_account.project_id, Gitlab::Json.dump(service_account), Gitlab::Json.dump(service_account_key), ProtectedBranch.protected?(project, environment_name) || ProtectedTag.protected?(project, environment_name) ) ServiceResponse.success(message: _('Service account generated successfully'), payload: { service_account: service_account, service_account_key: service_account_key }) end private def service_accounts_service GoogleCloud::ServiceAccountsService.new(project) end def service_account_name "GitLab :: #{project.name} :: #{environment_name}" end def service_account_desc "GitLab generated service account for project '#{project.name}' and environment '#{environment_name}'" end end end GoogleCloud::CreateServiceAccountsService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::CreateServiceAccountsService, feature_category: :deployment_management do describe '#execute' do before do mock_google_oauth2_creds = Struct.new(:app_id, :app_secret) .new('mock-app-id', 'mock-app-secret') allow(Gitlab::Auth::OAuth::Provider).to receive(:config_for) .with('google_oauth2') .and_return(mock_google_oauth2_creds) allow_next_instance_of(GoogleApi::CloudPlatform::Client) do |client| mock_service_account = Struct.new(:project_id, :unique_id, :email) .new('mock-project-id', 'mock-unique-id', 'mock-email') allow(client).to receive(:create_service_account) .and_return(mock_service_account) allow(client).to receive(:create_service_account_key) .and_return('mock-key') allow(client) .to receive(:grant_service_account_roles) end end it 'creates unprotected vars', :aggregate_failures do allow(ProtectedBranch).to receive(:protected?).and_return(false) project = create(:project) service = described_class.new( project, nil, google_oauth2_token: 'mock-token', gcp_project_id: 'mock-gcp-project-id', environment_name: '*' ) response = service.execute expect(response.status).to eq(:success) expect(response.message).to eq('Service account generated successfully') expect(project.variables.count).to eq(3) expect(project.variables.first.protected).to eq(false) expect(project.variables.second.protected).to eq(false) expect(project.variables.third.protected).to eq(false) end it 'creates protected vars', :aggregate_failures do allow(ProtectedBranch).to receive(:protected?).and_return(true) project = create(:project) service = described_class.new( project, nil, google_oauth2_token: 'mock-token', gcp_project_id: 'mock-gcp-project-id', environment_name: '*' ) response = service.execute expect(response.status).to eq(:success) expect(response.message).to eq('Service account generated successfully') expect(project.variables.count).to eq(3) expect(project.variables.first.protected).to eq(true) expect(project.variables.second.protected).to eq(true) expect(project.variables.third.protected).to eq(true) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud DEFAULT_REGION = 'us-east1' class CreateCloudsqlInstanceService < ::GoogleCloud::BaseService WORKER_INTERVAL = 30.seconds def execute create_cloud_instance trigger_instance_setup_worker success rescue Google::Apis::Error => err error(err.message) end private def create_cloud_instance google_api_client.create_cloudsql_instance( gcp_project_id, instance_name, root_password, database_version, region, tier ) end def trigger_instance_setup_worker GoogleCloud::CreateCloudsqlInstanceWorker.perform_in( WORKER_INTERVAL, current_user.id, project.id, { 'google_oauth2_token': google_oauth2_token, 'gcp_project_id': gcp_project_id, 'instance_name': instance_name, 'database_version': database_version, 'environment_name': environment_name, 'is_protected': protected? } ) end def protected? project.protected_for?(environment_name) end def instance_name # Generates an `instance_name` for the to-be-created Cloud SQL instance # Example: `gitlab-34647-postgres-14-staging` environment_alias = environment_name == '*' ? 'ALL' : environment_name name = "gitlab-#{project.id}-#{database_version}-#{environment_alias}" name.tr("_", "-").downcase end def root_password SecureRandom.hex(16) end def database_version params[:database_version] end def region region = ::Ci::VariablesFinder .new(project, { key: Projects::GoogleCloud::GcpRegionsController::GCP_REGION_CI_VAR_KEY, environment_scope: environment_name }) .execute.first region&.value || DEFAULT_REGION end def tier params[:tier] end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::CreateCloudsqlInstanceService, feature_category: :deployment_management do let(:project) { create(:project) } let(:user) { create(:user) } let(:gcp_project_id) { 'gcp_project_120' } let(:environment_name) { 'test_env_42' } let(:database_version) { 'POSTGRES_8000' } let(:tier) { 'REIT_TIER' } let(:service) do described_class.new(project, user, { gcp_project_id: gcp_project_id, environment_name: environment_name, database_version: database_version, tier: tier }) end describe '#execute' do before do allow_next_instance_of(::Ci::VariablesFinder) do |variable_finder| allow(variable_finder).to receive(:execute).and_return([]) end end it 'triggers creation of a cloudsql instance' do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |client| expected_instance_name = "gitlab-#{project.id}-postgres-8000-test-env-42" expect(client).to receive(:create_cloudsql_instance).with( gcp_project_id, expected_instance_name, String, database_version, 'us-east1', tier ) end result = service.execute expect(result[:status]).to be(:success) end it 'triggers worker to manage cloudsql instance creation operation results' do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |client| expect(client).to receive(:create_cloudsql_instance) end expect(GoogleCloud::CreateCloudsqlInstanceWorker).to receive(:perform_in) result = service.execute expect(result[:status]).to be(:success) end context 'when google APIs fail' do it 'returns error' do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |client| expect(client).to receive(:create_cloudsql_instance).and_raise(Google::Apis::Error.new('mock-error')) end result = service.execute expect(result[:status]).to eq(:error) end end context 'when project has GCP_REGION defined' do let(:gcp_region) { instance_double(::Ci::Variable, key: 'GCP_REGION', value: 'user-defined-region') } before do allow_next_instance_of(::Ci::VariablesFinder) do |variable_finder| allow(variable_finder).to receive(:execute).and_return([gcp_region]) end end it 'uses defined region' do expect_next_instance_of(GoogleApi::CloudPlatform::Client) do |client| expect(client).to receive(:create_cloudsql_instance).with( gcp_project_id, String, String, database_version, 'user-defined-region', tier ) end service.execute end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module GoogleCloud ## # GCP keys used to store Google Cloud Service Accounts GCP_KEYS = %w[GCP_PROJECT_ID GCP_SERVICE_ACCOUNT GCP_SERVICE_ACCOUNT_KEY].freeze ## # This service deals with GCP Service Accounts in GitLab class ServiceAccountsService < ::GoogleCloud::BaseService ## # Find GCP Service Accounts in a GitLab project # # This method looks up GitLab project's CI vars # and returns Google Cloud Service Accounts combinations # aligning GitLab project and ref to GCP projects def find_for_project group_vars_by_environment(GCP_KEYS).map do |environment_scope, value| { ref: environment_scope, gcp_project: value['GCP_PROJECT_ID'], service_account_exists: value['GCP_SERVICE_ACCOUNT'].present?, service_account_key_exists: value['GCP_SERVICE_ACCOUNT_KEY'].present? } end end def add_for_project(ref, gcp_project_id, service_account, service_account_key, is_protected) create_or_replace_project_vars( ref, 'GCP_PROJECT_ID', gcp_project_id, is_protected ) create_or_replace_project_vars( ref, 'GCP_SERVICE_ACCOUNT', service_account, is_protected ) create_or_replace_project_vars( ref, 'GCP_SERVICE_ACCOUNT_KEY', service_account_key, is_protected ) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe GoogleCloud::ServiceAccountsService, feature_category: :deployment_management do let(:service) { described_class.new(project) } describe 'find_for_project' do let_it_be(:project) { create(:project) } context 'when a project does not have GCP service account vars' do before do project.variables.build(key: 'blah', value: 'foo', environment_scope: 'world') project.save! end it 'returns an empty list' do expect(service.find_for_project.length).to eq(0) end end context 'when a project has GCP service account ci vars' do before do project.variables.build(protected: true, environment_scope: '*', key: 'GCP_PROJECT_ID', value: 'prj1') project.variables.build(protected: true, environment_scope: '*', key: 'GCP_SERVICE_ACCOUNT_KEY', value: 'mock') project.variables.build(protected: true, environment_scope: 'staging', key: 'GCP_PROJECT_ID', value: 'prj2') project.variables.build(protected: true, environment_scope: 'staging', key: 'GCP_SERVICE_ACCOUNT', value: 'mock') project.variables.build(protected: true, environment_scope: 'production', key: 'GCP_PROJECT_ID', value: 'prj3') project.variables.build(protected: true, environment_scope: 'production', key: 'GCP_SERVICE_ACCOUNT', value: 'mock') project.variables.build(protected: true, environment_scope: 'production', key: 'GCP_SERVICE_ACCOUNT_KEY', value: 'mock') project.save! end it 'returns a list of service accounts' do list = service.find_for_project aggregate_failures 'testing list of service accounts' do expect(list.length).to eq(3) expect(list.first[:ref]).to eq('*') expect(list.first[:gcp_project]).to eq('prj1') expect(list.first[:service_account_exists]).to eq(false) expect(list.first[:service_account_key_exists]).to eq(true) expect(list.second[:ref]).to eq('staging') expect(list.second[:gcp_project]).to eq('prj2') expect(list.second[:service_account_exists]).to eq(true) expect(list.second[:service_account_key_exists]).to eq(false) expect(list.third[:ref]).to eq('production') expect(list.third[:gcp_project]).to eq('prj3') expect(list.third[:service_account_exists]).to eq(true) expect(list.third[:service_account_key_exists]).to eq(true) end end end end describe 'add_for_project' do let_it_be(:project) { create(:project) } it 'saves GCP creds as project CI vars' do service.add_for_project('env_1', 'gcp_prj_id_1', 'srv_acc_1', 'srv_acc_key_1', true) service.add_for_project('env_2', 'gcp_prj_id_2', 'srv_acc_2', 'srv_acc_key_2', false) list = service.find_for_project aggregate_failures 'testing list of service accounts' do expect(list.length).to eq(2) expect(list.first[:ref]).to eq('env_1') expect(list.first[:gcp_project]).to eq('gcp_prj_id_1') expect(list.first[:service_account_exists]).to eq(true) expect(list.first[:service_account_key_exists]).to eq(true) expect(list.second[:ref]).to eq('env_2') expect(list.second[:gcp_project]).to eq('gcp_prj_id_2') expect(list.second[:service_account_exists]).to eq(true) expect(list.second[:service_account_key_exists]).to eq(true) end end it 'replaces previously stored CI vars with new CI vars' do service.add_for_project('env_1', 'new_project', 'srv_acc_1', 'srv_acc_key_1', false) list = service.find_for_project aggregate_failures 'testing list of service accounts' do expect(list.length).to eq(2) # asserting that the first service account is replaced expect(list.first[:ref]).to eq('env_1') expect(list.first[:gcp_project]).to eq('new_project') expect(list.first[:service_account_exists]).to eq(true) expect(list.first[:service_account_key_exists]).to eq(true) expect(list.second[:ref]).to eq('env_2') expect(list.second[:gcp_project]).to eq('gcp_prj_id_2') expect(list.second[:service_account_exists]).to eq(true) expect(list.second[:service_account_key_exists]).to eq(true) end end it 'underlying project CI vars must be protected as per value' do service.add_for_project('env_1', 'gcp_prj_id_1', 'srv_acc_1', 'srv_acc_key_1', true) service.add_for_project('env_2', 'gcp_prj_id_2', 'srv_acc_2', 'srv_acc_key_2', false) expect(project.variables[0].protected).to eq(true) expect(project.variables[1].protected).to eq(true) expect(project.variables[2].protected).to eq(true) expect(project.variables[3].protected).to eq(false) expect(project.variables[4].protected).to eq(false) expect(project.variables[5].protected).to eq(false) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ResourceEvents class ChangeMilestoneService < BaseChangeTimeboxService attr_reader :milestone, :old_milestone def initialize(resource, user, old_milestone:) super(resource, user) @milestone = resource&.milestone @old_milestone = old_milestone end private def track_event return unless resource.is_a?(WorkItem) Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter.track_work_item_milestone_changed_action(author: user) end def create_event ResourceMilestoneEvent.create(build_resource_args) end def build_resource_args action = milestone.blank? ? :remove : :add super.merge({ state: ResourceMilestoneEvent.states[resource.state], action: ResourceTimeboxEvent.actions[action], milestone_id: milestone.blank? ? old_milestone&.id : milestone&.id }) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ResourceEvents::ChangeMilestoneService, feature_category: :team_planning do let_it_be(:timebox) { create(:milestone) } let(:created_at_time) { Time.utc(2019, 12, 30) } let(:add_timebox_args) { { old_milestone: nil } } let(:remove_timebox_args) { { old_milestone: timebox } } [:issue, :merge_request].each do |issuable| it_behaves_like 'timebox(milestone or iteration) resource events creator', ResourceMilestoneEvent do let_it_be(:resource) { create(issuable) } # rubocop:disable Rails/SaveBang end end describe 'events tracking' do let_it_be(:user) { create(:user) } let(:resource) { create(resource_type, milestone: timebox, project: timebox.project) } subject(:service_instance) { described_class.new(resource, user, old_milestone: nil) } context 'when the resource is a work item' do let(:resource_type) { :work_item } it 'tracks work item usage data counters' do expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter) .to receive(:track_work_item_milestone_changed_action) .with(author: user) service_instance.execute end end context 'when the resource is not a work item' do let(:resource_type) { :issue } it 'does not track work item usage data counters' do expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter) .not_to receive(:track_work_item_milestone_changed_action) service_instance.execute end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # We store events about issuable label changes and weight changes in separate tables (not as # other system notes), but we still want to display notes about label and weight changes # as classic system notes in UI. This service merges synthetic label and weight notes # with classic notes and sorts them by creation time. module ResourceEvents class MergeIntoNotesService include Gitlab::Utils::StrongMemoize SYNTHETIC_NOTE_BUILDER_SERVICES = [ SyntheticLabelNotesBuilderService, SyntheticMilestoneNotesBuilderService, SyntheticStateNotesBuilderService ].freeze attr_reader :resource, :current_user, :params def initialize(resource, current_user, params = {}) @resource = resource @current_user = current_user @params = params end def execute(notes = []) (notes + synthetic_notes).sort_by(&:created_at) end private def synthetic_notes SYNTHETIC_NOTE_BUILDER_SERVICES.flat_map do |service| service.new(resource, current_user, params).execute end end end end ResourceEvents::MergeIntoNotesService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ResourceEvents::MergeIntoNotesService, feature_category: :team_planning do def create_event(params) event_params = { action: :add, label: label, issue: resource, user: user } create(:resource_label_event, event_params.merge(params)) end def create_note(params) opts = { noteable: resource, project: project } create(:note_on_issue, opts.merge(params)) end let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:resource) { create(:issue, project: project) } let_it_be(:label) { create(:label, project: project) } let_it_be(:label2) { create(:label, project: project) } let(:time) { Time.current } describe '#execute' do it 'merges label events into notes in order of created_at' do note1 = create_note(created_at: 4.days.ago) note2 = create_note(created_at: 2.days.ago) event1 = create_event(created_at: 3.days.ago) event2 = create_event(created_at: 1.day.ago) notes = described_class.new(resource, user).execute([note1, note2]) expected = [note1, event1, note2, event2].map(&:reload).map(&:discussion_id) expect(notes.map(&:discussion_id)).to eq expected end it 'squashes events with same time and author into single note' do user2 = create(:user) create_event(created_at: time) create_event(created_at: time, label: label2, action: :remove) create_event(created_at: time, user: user2) create_event(created_at: 1.day.ago, label: label2) notes = described_class.new(resource, user).execute expected = [ "added #{label.to_reference} label and removed #{label2.to_reference} label", "added #{label.to_reference} label", "added #{label2.to_reference} label" ] expect(notes.count).to eq 3 expect(notes.map(&:note)).to match_array expected end it 'fetches only notes created after last_fetched_at' do create_event(created_at: 4.days.ago) event = create_event(created_at: 1.day.ago) notes = described_class.new(resource, user, last_fetched_at: 2.days.ago).execute expect(notes.count).to eq 1 expect(notes.first.discussion_id).to eq event.reload.discussion_id end it "preloads the note author's status" do event = create_event(created_at: time) create(:user_status, user: event.user) notes = described_class.new(resource, user).execute expect(notes.first.author.association(:status)).to be_loaded end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ResourceEvents class ChangeLabelsService attr_reader :resource, :user def initialize(resource, user) @resource = resource @user = user end def execute(added_labels: [], removed_labels: []) label_hash = { resource_column(resource) => resource.id, user_id: user.id, created_at: resource.system_note_timestamp } labels = added_labels.map do |label| label_hash.merge(label_id: label.id, action: ResourceLabelEvent.actions['add']) end labels += removed_labels.map do |label| label_hash.merge(label_id: label.id, action: ResourceLabelEvent.actions['remove']) end ids = ApplicationRecord.legacy_bulk_insert(ResourceLabelEvent.table_name, labels, return_ids: true) # rubocop:disable Gitlab/BulkInsert if resource.is_a?(Issue) events = ResourceLabelEvent.id_in(ids) events.first.trigger_note_subscription_create(events: events.to_a) if events.any? end create_timeline_events_from(added_labels: added_labels, removed_labels: removed_labels) resource.broadcast_notes_changed return unless resource.is_a?(Issue) Gitlab::UsageDataCounters::IssueActivityUniqueCounter.track_issue_label_changed_action( author: user, project: resource.project) events end private def resource_column(resource) case resource when Issue :issue_id when MergeRequest :merge_request_id else raise ArgumentError, "Unknown resource type #{resource.class.name}" end end def create_timeline_events_from(added_labels: [], removed_labels: []) return unless resource.incident_type_issue? IncidentManagement::TimelineEvents::CreateService.change_labels( resource, user, added_labels: added_labels, removed_labels: removed_labels ) end end end ResourceEvents::ChangeLabelsService.prepend_mod_with('ResourceEvents::ChangeLabelsService') ```
# frozen_string_literal: true require 'spec_helper' # feature category is shared among plan(issues, epics), monitor(incidents), create(merge request) stages RSpec.describe ResourceEvents::ChangeLabelsService, feature_category: :team_planning do let_it_be(:project) { create(:project) } let_it_be(:author) { create(:user) } let_it_be(:issue) { create(:issue, project: project) } let_it_be(:incident) { create(:incident, project: project) } let(:resource) { issue } describe '#execute' do shared_examples 'creating timeline events' do context 'when resource is not an incident' do let(:resource) { issue } it 'does not call create timeline events service' do expect(IncidentManagement::TimelineEvents::CreateService).not_to receive(:change_labels) change_labels end end context 'when resource is an incident' do let(:resource) { incident } it 'calls create timeline events service with correct attributes' do expect(IncidentManagement::TimelineEvents::CreateService) .to receive(:change_labels) .with(resource, author, added_labels: added, removed_labels: removed) .and_call_original change_labels end end end subject(:change_labels) do described_class.new(resource, author).execute(added_labels: added, removed_labels: removed) end let_it_be(:labels) { create_list(:label, 2, project: project) } def expect_label_event(event, label, action) expect(event.user).to eq(author) expect(event.label).to eq(label) expect(event.action).to eq(action) end it 'broadcasts resource note change' do expect(resource).to receive(:broadcast_notes_changed) described_class.new(resource, author).execute(added_labels: [labels[0]]) end context 'when adding a label' do let(:added) { [labels[0]] } let(:removed) { [] } it 'creates new label event' do expect { change_labels }.to change { resource.resource_label_events.count }.from(0).to(1) expect_label_event(resource.resource_label_events.first, labels[0], 'add') end it_behaves_like 'creating timeline events' end context 'when removing a label' do let(:added) { [] } let(:removed) { [labels[1]] } it 'creates new label event' do expect { change_labels }.to change { resource.resource_label_events.count }.from(0).to(1) expect_label_event(resource.resource_label_events.first, labels[1], 'remove') end it_behaves_like 'creating timeline events' end context 'when both adding and removing labels' do let(:added) { [labels[0]] } let(:removed) { [labels[1]] } it_behaves_like 'creating timeline events' it 'creates all label events in a single query' do expect(ApplicationRecord).to receive(:legacy_bulk_insert).once.and_call_original expect { change_labels }.to change { resource.resource_label_events.count }.from(0).to(2) end context 'when resource is a work item' do it 'triggers note created subscription' do expect(GraphqlTriggers).to receive(:work_item_note_created) change_labels end end context 'when resource is an MR' do let(:resource) { create(:merge_request, source_project: project) } it 'does not trigger note created subscription' do expect(GraphqlTriggers).not_to receive(:work_item_note_created) change_labels end end end describe 'usage data' do let(:added) { [labels[0]] } let(:removed) { [labels[1]] } subject(:counter_class) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter } context 'when resource is an issue' do it 'tracks changed labels' do expect(counter_class).to receive(:track_issue_label_changed_action) change_labels end it_behaves_like 'internal event tracking' do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_LABEL_CHANGED } let(:user) { author } let(:namespace) { project.namespace } subject(:service_action) { change_labels } end end context 'when resource is a merge request' do let(:resource) { create(:merge_request, source_project: project) } it 'does not track changed labels' do expect(counter_class).not_to receive(:track_issue_label_changed_action) change_labels end it 'does not emit snowplow event', :snowplow do expect_no_snowplow_event change_labels end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ResourceEvents class ChangeStateService attr_reader :resource, :user def initialize(user:, resource:) @user = user @resource = resource end def execute(params) @params = params ResourceStateEvent.create( user: user, resource.noteable_target_type_name => resource, source_commit: commit_id_of(mentionable_source), source_merge_request_id: merge_request_id_of(mentionable_source), state: ResourceStateEvent.states[state], close_after_error_tracking_resolve: close_after_error_tracking_resolve, close_auto_resolve_prometheus_alert: close_auto_resolve_prometheus_alert, created_at: resource.system_note_timestamp ) resource.broadcast_notes_changed end private attr_reader :params def close_auto_resolve_prometheus_alert params[:close_auto_resolve_prometheus_alert] || false end def close_after_error_tracking_resolve params[:close_after_error_tracking_resolve] || false end def state params[:status] end def mentionable_source params[:mentionable_source] end def commit_id_of(mentionable_source) return unless mentionable_source.is_a?(Commit) mentionable_source.id[0...40] end def merge_request_id_of(mentionable_source) return unless mentionable_source.is_a?(MergeRequest) mentionable_source.id end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ResourceEvents::ChangeStateService, feature_category: :team_planning do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let(:issue) { create(:issue, project: project) } let(:merge_request) { create(:merge_request, source_project: project) } let(:source_commit) { create(:commit, project: project) } let(:source_merge_request) { create(:merge_request, source_project: project, target_project: project, target_branch: 'foo') } shared_examples 'a state event' do %w[opened reopened closed locked].each do |state| it "creates the expected event if resource has #{state} state" do described_class.new(user: user, resource: resource).execute(status: state, mentionable_source: source) event = resource.resource_state_events.last case resource when Issue expect(event.issue).to eq(resource) expect(event.merge_request).to be_nil when MergeRequest expect(event.issue).to be_nil expect(event.merge_request).to eq(resource) end expect(event.state).to eq(state) expect_event_source(event, source) end it "sets the created_at timestamp from the system_note_timestamp" do resource.system_note_timestamp = Time.at(43).utc described_class.new(user: user, resource: resource).execute(status: state, mentionable_source: source) event = resource.resource_state_events.last expect(event.created_at).to eq(Time.at(43).utc) end end end describe '#execute' do context 'when resource is an Issue' do context 'when no source is given' do it_behaves_like 'a state event' do let(:resource) { issue } let(:source) { nil } end end context 'when source commit is given' do it_behaves_like 'a state event' do let(:resource) { issue } let(:source) { source_commit } end end context 'when source merge request is given' do it_behaves_like 'a state event' do let(:resource) { issue } let(:source) { source_merge_request } end end end context 'when resource is a MergeRequest' do context 'when no source is given' do it_behaves_like 'a state event' do let(:resource) { merge_request } let(:source) { nil } end end context 'when source commit is given' do it_behaves_like 'a state event' do let(:resource) { merge_request } let(:source) { source_commit } end end context 'when source merge request is given' do it_behaves_like 'a state event' do let(:resource) { merge_request } let(:source) { source_merge_request } end end end end def expect_event_source(event, source) case source when MergeRequest expect(event.source_commit).to be_nil expect(event.source_merge_request).to eq(source) when Commit expect(event.source_commit).to eq(source.id) expect(event.source_merge_request).to be_nil else expect(event.source_merge_request).to be_nil expect(event.source_commit).to be_nil end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # We store events about resource milestone changes in a separate table, # but we still want to display notes about milestone changes # as classic system notes in UI. This service generates "synthetic" notes for # milestone event changes. module ResourceEvents class SyntheticMilestoneNotesBuilderService < BaseSyntheticNotesBuilderService private def synthetic_notes milestone_change_events.map do |event| MilestoneNote.from_event(event, resource: resource, resource_parent: resource_parent) end end def milestone_change_events return [] unless resource.respond_to?(:resource_milestone_events) events = resource.resource_milestone_events.includes(:milestone, user: :status) # rubocop: disable CodeReuse/ActiveRecord apply_common_filters(events) end def table_name 'resource_milestone_events' end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ResourceEvents::SyntheticMilestoneNotesBuilderService, feature_category: :team_planning do describe '#execute' do let_it_be(:user) { create(:user) } let_it_be(:issue) { create(:issue, author: user) } let_it_be(:milestone) { create(:milestone, project: issue.project) } let_it_be(:events) do [ create(:resource_milestone_event, issue: issue, milestone: milestone, action: :add, created_at: '2020-01-01 04:00'), create(:resource_milestone_event, issue: issue, milestone: milestone, action: :remove, created_at: '2020-01-02 08:00'), create(:resource_milestone_event, issue: issue, milestone: nil, action: :remove, created_at: '2020-01-02 08:00') ] end it 'builds milestone notes for resource milestone events' do notes = described_class.new(issue, user).execute expect(notes.map(&:created_at)).to eq(events.map(&:created_at)) expect(notes.map(&:note)).to eq( [ "changed milestone to %#{milestone.iid}", "removed milestone %#{milestone.iid}", "removed milestone " ]) end it_behaves_like 'filters by paginated notes', :resource_milestone_event end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # We store events about issuable label changes in a separate table (not as # other system notes), but we still want to display notes about label changes # as classic system notes in UI. This service generates "synthetic" notes for # label event changes. module ResourceEvents class SyntheticLabelNotesBuilderService < BaseSyntheticNotesBuilderService private def synthetic_notes label_events_by_discussion_id.map do |discussion_id, events| LabelNote.from_events(events, resource: resource, resource_parent: resource_parent) end end def label_events_by_discussion_id return [] unless resource.respond_to?(:resource_label_events) events = resource.resource_label_events.includes(:label, user: :status) # rubocop: disable CodeReuse/ActiveRecord events = apply_common_filters(events) events.group_by { |event| event.discussion_id } end def table_name 'resource_label_events' end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ResourceEvents::SyntheticLabelNotesBuilderService, feature_category: :team_planning do describe '#execute' do let_it_be(:user) { create(:user) } let_it_be(:issue) { create(:issue, author: user) } let_it_be(:event1) { create(:resource_label_event, issue: issue) } let_it_be(:event2) { create(:resource_label_event, issue: issue) } let_it_be(:event3) { create(:resource_label_event, issue: issue) } it 'returns the expected synthetic notes' do notes = described_class.new(issue, user).execute expect(notes.size).to eq(3) end it_behaves_like 'filters by paginated notes', :resource_label_event end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ResourceEvents class SyntheticStateNotesBuilderService < BaseSyntheticNotesBuilderService private def synthetic_notes state_change_events.map do |event| StateNote.from_event(event, resource: resource, resource_parent: resource_parent) end end def state_change_events return [] unless resource.respond_to?(:resource_state_events) events = resource.resource_state_events.includes(user: :status) # rubocop: disable CodeReuse/ActiveRecord apply_common_filters(events) end def table_name 'resource_state_events' end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ResourceEvents::SyntheticStateNotesBuilderService, feature_category: :team_planning do describe '#execute' do let_it_be(:user) { create(:user) } it_behaves_like 'filters by paginated notes', :resource_state_event end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DraftNotes class PublishService < DraftNotes::BaseService def execute(draft = nil) return error('Not allowed to create notes') unless can?(current_user, :create_note, merge_request) if draft publish_draft_note(draft) else publish_draft_notes merge_request_activity_counter.track_publish_review_action(user: current_user) end success rescue ActiveRecord::RecordInvalid => e message = "Unable to save #{e.record.class.name}: #{e.record.errors.full_messages.join(", ")} " error(message) end private def publish_draft_note(draft) create_note_from_draft(draft) draft.delete MergeRequests::ResolvedDiscussionNotificationService.new(project: project, current_user: current_user).execute(merge_request) end def publish_draft_notes return if draft_notes.empty? review = Review.create!(author: current_user, merge_request: merge_request, project: project) created_notes = draft_notes.map do |draft_note| draft_note.review = review create_note_from_draft( draft_note, skip_capture_diff_note_position: true, skip_keep_around_commits: true, skip_merge_status_trigger: true ) end capture_diff_note_positions(created_notes) keep_around_commits(created_notes) draft_notes.delete_all set_reviewed notification_service.async.new_review(review) MergeRequests::ResolvedDiscussionNotificationService.new(project: project, current_user: current_user).execute(merge_request) GraphqlTriggers.merge_request_merge_status_updated(merge_request) after_publish(review) end def create_note_from_draft(draft, skip_capture_diff_note_position: false, skip_keep_around_commits: false, skip_merge_status_trigger: false) # Make sure the diff file is unfolded in order to find the correct line # codes. draft.diff_file&.unfold_diff_lines(draft.original_position) note_params = draft.publish_params.merge(skip_keep_around_commits: skip_keep_around_commits) note = Notes::CreateService.new(draft.project, draft.author, note_params).execute( skip_capture_diff_note_position: skip_capture_diff_note_position, skip_merge_status_trigger: skip_merge_status_trigger, skip_set_reviewed: true ) set_discussion_resolve_status(note, draft) note end def set_discussion_resolve_status(note, draft_note) return unless draft_note.discussion_id.present? discussion = note.discussion if draft_note.resolve_discussion && discussion.can_resolve?(current_user) discussion.resolve!(current_user) else discussion.unresolve! end end def set_reviewed return if Feature.enabled?(:mr_request_changes, current_user) ::MergeRequests::UpdateReviewerStateService.new(project: project, current_user: current_user).execute(merge_request, "reviewed") end def capture_diff_note_positions(notes) paths = notes.flat_map do |note| note.diff_file&.paths if note.diff_note? end return if paths.empty? capture_service = Discussions::CaptureDiffNotePositionService.new(merge_request, paths.compact) notes.each do |note| capture_service.execute(note.discussion) if note.diff_note? && note.start_of_discussion? end end def keep_around_commits(notes) shas = notes.flat_map do |note| note.shas if note.diff_note? end.uniq # We are allowing this since gitaly call will be created for each sha and # even though they're unique, there will still be multiple Gitaly calls. Gitlab::GitalyClient.allow_n_plus_1_calls do project.repository.keep_around(*shas) end end def after_publish(review) # Overridden in EE end end end DraftNotes::PublishService.prepend_mod ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DraftNotes::PublishService, feature_category: :code_review_workflow do include RepoHelpers let_it_be(:merge_request) { create(:merge_request, reviewers: create_list(:user, 1)) } let(:project) { merge_request.target_project } let(:user) { merge_request.author } let(:commit) { project.commit(sample_commit.id) } let(:position) do Gitlab::Diff::Position.new( old_path: "files/ruby/popen.rb", new_path: "files/ruby/popen.rb", old_line: nil, new_line: 14, diff_refs: commit.diff_refs ) end def publish(draft: nil) DraftNotes::PublishService.new(merge_request, user).execute(draft) end context 'single draft note' do let(:commit_id) { nil } let!(:drafts) { create_list(:draft_note, 2, merge_request: merge_request, author: user, commit_id: commit_id, position: position) } it 'publishes' do expect { publish(draft: drafts.first) }.to change { DraftNote.count }.by(-1).and change { Note.count }.by(1) expect(DraftNote.count).to eq(1) end it 'does not skip notification', :sidekiq_might_not_need_inline do note_params = drafts.first.publish_params.merge(skip_keep_around_commits: false) expect(Notes::CreateService).to receive(:new).with(project, user, note_params).and_call_original expect_next_instance_of(NotificationService) do |notification_service| expect(notification_service).to receive(:new_note) end result = publish(draft: drafts.first) expect(result[:status]).to eq(:success) end it 'does not track the publish event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_publish_review_action) publish(draft: drafts.first) end context 'commit_id is set' do let(:commit_id) { commit.id } it 'creates note from draft with commit_id' do result = publish(draft: drafts.first) expect(result[:status]).to eq(:success) expect(merge_request.notes.first.commit_id).to eq(commit_id) end end end context 'multiple draft notes' do let(:commit_id) { nil } before do create(:draft_note_on_text_diff, merge_request: merge_request, author: user, note: 'first note', commit_id: commit_id, position: position) create(:draft_note_on_text_diff, merge_request: merge_request, author: user, note: 'second note', commit_id: commit_id, position: position) end context 'when review fails to create' do before do expect_next_instance_of(Review) do |review| allow(review).to receive(:save!).and_raise(ActiveRecord::RecordInvalid.new(review)) end end it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { publish } end it 'does not publish any draft note' do expect { publish }.not_to change { DraftNote.count } end it 'does not track the publish event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_publish_review_action) publish end it 'returns an error' do result = publish expect(result[:status]).to eq(:error) expect(result[:message]).to match(/Unable to save Review/) end end it_behaves_like 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { publish } end it 'returns success' do result = publish expect(result[:status]).to eq(:success) end it 'publishes all draft notes for a user in a merge request' do expect { publish }.to change { DraftNote.count }.by(-2).and change { Note.count }.by(2).and change { Review.count }.by(1) expect(DraftNote.count).to eq(0) notes = merge_request.notes.order(id: :asc) expect(notes.first.note).to eq('first note') expect(notes.last.note).to eq('second note') end it 'sends batch notification' do expect_next_instance_of(NotificationService) do |notification_service| expect(notification_service).to receive_message_chain(:async, :new_review).with(kind_of(Review)) end publish end it 'tracks the publish event' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_publish_review_action) .with(user: user) publish end context 'capturing diff notes positions and keeping around commits' do before do # Need to execute this to ensure that we'll be able to test creation of # DiffNotePosition records as that only happens when the `MergeRequest#merge_ref_head` # is present. This service creates that for the specified merge request. MergeRequests::MergeToRefService.new(project: project, current_user: user).execute(merge_request) # Need to re-stub this and call original as we are stubbing # `Gitlab::Git::KeepAround#execute` in spec_helper for performance reason. # Enabling it here so we can test the Gitaly calls it makes. allow(Gitlab::Git::KeepAround).to receive(:execute).and_call_original end it 'creates diff_note_positions for diff notes' do publish notes = merge_request.notes.order(id: :asc) expect(notes.first.diff_note_positions).to be_any expect(notes.last.diff_note_positions).to be_any end it 'keeps around the commits of each published note' do publish repository = project.repository notes = merge_request.notes.order(id: :asc) notes.first.shas.each do |sha| expect(repository.ref_exists?("refs/keep-around/#{sha}")).to be_truthy end notes.last.shas.each do |sha| expect(repository.ref_exists?("refs/keep-around/#{sha}")).to be_truthy end end it 'does not request a lot from Gitaly', :request_store, :clean_gitlab_redis_cache do merge_request position Gitlab::GitalyClient.reset_counts # NOTE: This should be reduced as we work on reducing Gitaly calls. # Gitaly requests shouldn't go above this threshold as much as possible # as it may add more to the Gitaly N+1 issue we are experiencing. expect { publish }.to change { Gitlab::GitalyClient.get_request_count }.by(19) end end context 'commit_id is set' do let(:commit_id) { commit.id } it 'creates note from draft with commit_id' do result = publish expect(result[:status]).to eq(:success) merge_request.notes.each do |note| expect(note.commit_id).to eq(commit_id) end end end it 'does not call UpdateReviewerStateService' do publish expect(MergeRequests::UpdateReviewerStateService).not_to receive(:new) end context 'when `mr_request_changes` feature flag is disabled' do before do stub_feature_flags(mr_request_changes: false) end it 'calls UpdateReviewerStateService' do expect_next_instance_of( MergeRequests::UpdateReviewerStateService, project: project, current_user: user ) do |service| expect(service).to receive(:execute).with(merge_request, "reviewed") end publish end end end context 'draft notes with suggestions' do let(:project) { create(:project, :repository) } let(:merge_request) { create(:merge_request, source_project: project, target_project: project) } let(:suggestion_note) do <<-MARKDOWN.strip_heredoc ```suggestion foo ``` MARKDOWN end let!(:draft) { create(:draft_note_on_text_diff, note: suggestion_note, merge_request: merge_request, author: user) } it 'creates a suggestion with correct content' do expect { publish(draft: draft) }.to change { Suggestion.count }.by(1) .and change { DiffNote.count }.from(0).to(1) suggestion = Suggestion.last expect(suggestion.from_line).to eq(14) expect(suggestion.to_line).to eq(14) expect(suggestion.from_content).to eq(" vars = {\n") expect(suggestion.to_content).to eq(" foo\n") end context 'when the diff is changed' do let(:file_path) { 'files/ruby/popen.rb' } let(:branch_name) { project.default_branch } let(:commit) { project.repository.commit } def update_file(file_path, new_content) params = { file_path: file_path, commit_message: "Update File", file_content: new_content, start_project: project, start_branch: project.default_branch, branch_name: branch_name } Files::UpdateService.new(project, user, params).execute end before do project.add_developer(user) end it 'creates a suggestion based on the latest diff content and positions' do diff_file = merge_request.diffs(paths: [file_path]).diff_files.first raw_data = diff_file.new_blob.data # Add a line break to the beginning of the file result = update_file(file_path, raw_data.prepend("\n")) oldrev = merge_request.diff_head_sha newrev = result[:result] expect(newrev).to be_present # Generates new MR revision at DB level refresh = MergeRequests::RefreshService.new(project: project, current_user: user) refresh.execute(oldrev, newrev, merge_request.source_branch_ref) expect { publish(draft: draft) }.to change { Suggestion.count }.by(1) .and change { DiffNote.count }.from(0).to(1) suggestion = Suggestion.last expect(suggestion.from_line).to eq(15) expect(suggestion.to_line).to eq(15) expect(suggestion.from_content).to eq(" vars = {\n") expect(suggestion.to_content).to eq(" foo\n") end end end it 'only publishes the draft notes belonging to the current user' do other_user = create(:user) project.add_maintainer(other_user) create_list(:draft_note, 2, merge_request: merge_request, author: user) create_list(:draft_note, 2, merge_request: merge_request, author: other_user) expect { publish }.to change { DraftNote.count }.by(-2).and change { Note.count }.by(2) expect(DraftNote.count).to eq(2) end context 'with quick actions', :sidekiq_inline do it 'performs quick actions' do other_user = create(:user) project.add_developer(other_user) create( :draft_note, merge_request: merge_request, author: user, note: "thanks\n/assign #{other_user.to_reference}" ) expect { publish }.to change { DraftNote.count }.by(-1).and change { Note.count }.by(2) expect(merge_request.reload.assignees).to match_array([other_user]) expect(merge_request.notes.last).to be_system end it 'does not create a note if it only contains quick actions' do create(:draft_note, merge_request: merge_request, author: user, note: "/assign #{user.to_reference}") expect { publish }.to change { DraftNote.count }.by(-1).and change { Note.count }.by(1) expect(merge_request.reload.assignees).to eq([user]) expect(merge_request.notes.last).to be_system end end context 'with drafts that resolve threads' do let!(:note) { create(:discussion_note_on_merge_request, noteable: merge_request, project: project) } let!(:draft_note) { create(:draft_note, merge_request: merge_request, author: user, resolve_discussion: true, discussion_id: note.discussion.reply_id) } it 'resolves the thread' do publish(draft: draft_note) # discussion is memoized and reload doesn't clear the memoization expect(Note.find(note.id).discussion.resolved?).to be true end it 'sends notifications if all threads are resolved' do expect_next_instance_of(MergeRequests::ResolvedDiscussionNotificationService) do |instance| expect(instance).to receive(:execute).with(merge_request) end publish end end context 'user cannot create notes' do before do allow(Ability).to receive(:allowed?).with(user, :create_note, merge_request).and_return(false) end it 'returns an error' do expect(publish[:status]).to eq(:error) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DraftNotes class DestroyService < DraftNotes::BaseService # If no `draft` is given it fallsback to all # draft notes of the given merge request and user. def execute(draft = nil) drafts = draft || draft_notes clear_highlight_diffs_cache(Array.wrap(drafts)) drafts.is_a?(DraftNote) ? drafts.destroy! : drafts.delete_all end private def clear_highlight_diffs_cache(drafts) if drafts.any? { |draft| draft.diff_file&.unfolded? } merge_request.diffs.clear_cache end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DraftNotes::DestroyService, feature_category: :code_review_workflow do let(:merge_request) { create(:merge_request) } let(:project) { merge_request.target_project } let(:user) { merge_request.author } def destroy(draft_note = nil) DraftNotes::DestroyService.new(merge_request, user).execute(draft_note) end it 'destroys a single draft note' do drafts = create_list(:draft_note, 2, merge_request: merge_request, author: user) expect { destroy(drafts.first) } .to change { DraftNote.count }.by(-1) expect(DraftNote.count).to eq(1) end it 'destroys all draft notes for a user in a merge request' do create_list(:draft_note, 2, merge_request: merge_request, author: user) expect { destroy }.to change { DraftNote.count }.by(-2) # rubocop:disable Rails/SaveBang expect(DraftNote.count).to eq(0) end context 'diff highlight cache clearing' do context 'when destroying all draft notes of a user' do it 'clears highlighting cache if unfold required for any' do drafts = create_list(:draft_note, 2, merge_request: merge_request, author: user) allow_any_instance_of(DraftNote).to receive_message_chain(:diff_file, :unfolded?) { true } expect(merge_request).to receive_message_chain(:diffs, :clear_cache) destroy(drafts.first) end end context 'when destroying one draft note' do it 'clears highlighting cache if unfold required' do create_list(:draft_note, 2, merge_request: merge_request, author: user) allow_any_instance_of(DraftNote).to receive_message_chain(:diff_file, :unfolded?) { true } expect(merge_request).to receive_message_chain(:diffs, :clear_cache) destroy # rubocop:disable Rails/SaveBang end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DraftNotes class CreateService < DraftNotes::BaseService attr_accessor :in_draft_mode, :in_reply_to_discussion_id def initialize(merge_request, current_user, params = nil) @in_reply_to_discussion_id = params.delete(:in_reply_to_discussion_id) super end def execute if in_reply_to_discussion_id.present? unless discussion return base_error(_('Thread to reply to cannot be found')) end params[:discussion_id] = discussion.reply_id end if params[:resolve_discussion] && !can_resolve_discussion? return base_error(_('User is not allowed to resolve thread')) end draft_note = DraftNote.new(params) draft_note.merge_request = merge_request draft_note.author = current_user return draft_note unless draft_note.save if in_reply_to_discussion_id.blank? && draft_note.diff_file&.unfolded? merge_request.diffs.clear_cache end if draft_note.persisted? merge_request_activity_counter.track_create_review_note_action(user: current_user) end draft_note end private def base_error(text) DraftNote.new.tap do |draft| draft.errors.add(:base, text) end end def discussion @discussion ||= merge_request.notes.find_discussion(in_reply_to_discussion_id) end def can_resolve_discussion? note = discussion&.notes&.first return false unless note current_user && Ability.allowed?(current_user, :resolve_note, note) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DraftNotes::CreateService, feature_category: :code_review_workflow do let(:merge_request) { create(:merge_request) } let(:project) { merge_request.target_project } let(:user) { merge_request.author } def create_draft(params) described_class.new(merge_request, user, params).execute end it 'creates a simple draft note' do draft = create_draft(note: 'This is a test') expect(draft).to be_an_instance_of(DraftNote) expect(draft.note).to eq('This is a test') expect(draft.author).to eq(user) expect(draft.project).to eq(merge_request.target_project) expect(draft.discussion_id).to be_nil end it 'tracks the start event when the draft is persisted' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .to receive(:track_create_review_note_action) .with(user: user) draft = create_draft(note: 'This is a test') expect(draft).to be_persisted end it 'does not track the start event when the draft is not persisted' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter) .not_to receive(:track_create_review_note_action) draft = create_draft(note: 'Not a reply!', resolve_discussion: true) expect(draft).not_to be_persisted end it 'cannot resolve when there is nothing to resolve' do draft = create_draft(note: 'Not a reply!', resolve_discussion: true) expect(draft.errors[:base]).to include('User is not allowed to resolve thread') expect(draft).not_to be_persisted end context 'in a thread' do it 'creates a draft note with discussion_id' do discussion = create(:discussion_note_on_merge_request, noteable: merge_request, project: project).discussion draft = create_draft(note: 'A reply!', in_reply_to_discussion_id: discussion.reply_id) expect(draft.note).to eq('A reply!') expect(draft.discussion_id).to eq(discussion.reply_id) expect(draft.resolve_discussion).to be_falsey end it 'creates a draft that resolves the thread' do discussion = create(:discussion_note_on_merge_request, noteable: merge_request, project: project).discussion draft = create_draft(note: 'A reply!', in_reply_to_discussion_id: discussion.reply_id, resolve_discussion: true) expect(draft.note).to eq('A reply!') expect(draft.discussion_id).to eq(discussion.reply_id) expect(draft.resolve_discussion).to be true end end it 'creates a draft note with a position in a diff' do diff_refs = project.commit(RepoHelpers.sample_commit.id).try(:diff_refs) position = Gitlab::Diff::Position.new( old_path: "files/ruby/popen.rb", new_path: "files/ruby/popen.rb", old_line: nil, new_line: 14, diff_refs: diff_refs ) draft = create_draft(note: 'Comment on diff', position: position.to_json) expect(draft.note).to eq('Comment on diff') expect(draft.original_position.to_json).to eq(position.to_json) end context 'diff highlight cache clearing' do context 'when diff file is unfolded and it is not a reply' do it 'clears diff highlighting cache' do expect_next_instance_of(DraftNote) do |draft| allow(draft).to receive_message_chain(:diff_file, :unfolded?) { true } end expect(merge_request).to receive_message_chain(:diffs, :clear_cache) create_draft(note: 'This is a test', line_code: '123') end end context 'when diff file is not unfolded and it is not a reply' do it 'clears diff highlighting cache' do expect_next_instance_of(DraftNote) do |draft| allow(draft).to receive_message_chain(:diff_file, :unfolded?) { false } end expect(merge_request).not_to receive(:diffs) create_draft(note: 'This is a test', line_code: '123') end end end context 'when the draft note is invalid' do before do allow_next_instance_of(DraftNote) do |draft| allow(draft).to receive(:valid?).and_return(false) end end it 'does not create the note' do draft_note = create_draft(note: 'invalid note') expect(draft_note).not_to be_persisted end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Markup class RenderingService def initialize(text, file_name: nil, context: {}, postprocess_context: {}) @text = text @file_name = file_name @context = context @postprocess_context = postprocess_context end def execute return '' unless text.present? return context.delete(:rendered) if context.has_key?(:rendered) html = markup_unsafe return '' unless html.present? postprocess_context ? postprocess(html) : html end private def markup_unsafe return markdown_unsafe unless file_name if Gitlab::MarkupHelper.gitlab_markdown?(file_name) markdown_unsafe elsif Gitlab::MarkupHelper.asciidoc?(file_name) asciidoc_unsafe elsif Gitlab::MarkupHelper.plain?(file_name) plain_unsafe else other_markup_unsafe end end def markdown_unsafe Banzai.render(text, context) end def asciidoc_unsafe Gitlab::Asciidoc.render(text, context) end def plain_unsafe ActionController::Base.helpers.content_tag :pre, class: 'plain-readme' do text end end def other_markup_unsafe Gitlab::OtherMarkup.render(file_name, text, context) rescue GitHub::Markup::CommandError ActionController::Base.helpers.simple_format(text) end def postprocess(html) Banzai.post_process(html, context.reverse_merge(postprocess_context)) end attr_reader :text, :file_name, :context, :postprocess_context end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Markup::RenderingService, feature_category: :groups_and_projects do describe '#execute' do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) do user = create(:user, username: 'gfm') project.add_maintainer(user) user end let_it_be(:context) { { project: project } } let_it_be(:postprocess_context) { { current_user: user } } let(:file_name) { nil } let(:text) { 'Noël' } subject do described_class .new(text, file_name: file_name, context: context, postprocess_context: postprocess_context) .execute end context 'when text is missing' do let(:text) { nil } it 'returns an empty string' do is_expected.to eq('') end end context 'when file_name is missing' do it 'returns html (rendered by Banzai)' do expected_html = '<p data-sourcepos="1:1-1:5" dir="auto">Noël</p>' expect(Banzai).to receive(:render).with(text, context) { expected_html } is_expected.to eq(expected_html) end end context 'when postprocess_context is missing' do let(:file_name) { 'foo.txt' } let(:postprocess_context) { nil } it 'returns html (rendered by Banzai)' do expected_html = '<pre class="plain-readme">Noël</pre>' expect(Banzai).not_to receive(:post_process) { expected_html } is_expected.to eq(expected_html) end end context 'when rendered context is present' do let(:rendered) { 'rendered text' } let(:file_name) { 'foo.md' } it 'returns an empty string' do context[:rendered] = rendered is_expected.to eq(rendered) end end context 'when file is a markdown file' do let(:file_name) { 'foo.md' } it 'returns html (rendered by Banzai)' do expected_html = '<p data-sourcepos="1:1-1:5" dir="auto">Noël</p>' expect(Banzai).to receive(:render).with(text, context) { expected_html } is_expected.to eq(expected_html) end end context 'when file is asciidoc file' do let(:file_name) { 'foo.adoc' } it 'returns html (rendered by Gitlab::Asciidoc)' do expected_html = "<div>\n<p>Noël</p>\n</div>" expect(Gitlab::Asciidoc).to receive(:render).with(text, context) { expected_html } is_expected.to eq(expected_html) end end context 'when file is a regular text file' do let(:file_name) { 'foo.txt' } let(:text) { 'Noël <form>' } it 'returns html (rendered by ActionView::TagHelper)' do expect(ActionController::Base.helpers).to receive(:content_tag).and_call_original is_expected.to eq('<pre class="plain-readme">Noël &lt;form&gt;</pre>') end end context 'when file has an unknown type' do let(:file_name) { 'foo.tex' } it 'returns html (rendered by Gitlab::OtherMarkup)' do expected_html = 'Noël' expect(Gitlab::OtherMarkup).to receive(:render).with(file_name, text, context) { expected_html } is_expected.to eq(expected_html) end end context 'with reStructuredText' do let(:file_name) { 'foo.rst' } let(:text) { "####\nPART\n####" } it 'returns rendered html' do is_expected.to eq("<h1>PART</h1>\n\n") end context 'when input has an invalid syntax' do let(:text) { "####\nPART\n##" } it 'uses a simple formatter for html' do is_expected.to eq("<p>####\n<br>PART\n<br>##</p>") end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ServiceDesk module CustomEmailVerifications class UpdateService < BaseService EMAIL_TOKEN_REGEXP = /Verification token: ([A-Za-z0-9_-]{12})/ def execute return error_parameter_missing if settings.blank? || verification.blank? return error_already_finished if verification.finished? return error_already_failed if already_failed_and_no_mail? verification_error = verify settings.update!(custom_email_enabled: false) if settings.custom_email_enabled? notify_project_owners_and_user_about_result(user: verification.triggerer) if verification_error.present? verification.mark_as_failed!(verification_error) error_not_verified(verification_error) else verification.mark_as_finished! log_info ServiceResponse.success end end private def mail params[:mail] end def verification @verification ||= settings.custom_email_verification end def already_failed_and_no_mail? verification.failed? && mail.blank? end def verify return :mail_not_received_within_timeframe if mail_not_received_within_timeframe? return :incorrect_from if incorrect_from? return :incorrect_token if incorrect_token? nil end def mail_not_received_within_timeframe? # (For completeness) also raise if no email provided mail.blank? || !verification.in_timeframe? end def incorrect_from? # Does the email forwarder preserve the FROM header? mail.from.first != settings.custom_email end def incorrect_token? message, _stripped_text = Gitlab::Email::ReplyParser.new(mail).execute scan_result = message.scan(EMAIL_TOKEN_REGEXP) return true if scan_result.empty? scan_result.first.first != verification.token end def error_parameter_missing error_response(s_('ServiceDesk|Service Desk setting or verification object missing')) end def error_already_finished error_response(s_('ServiceDesk|Custom email address has already been verified.')) end def error_already_failed error_response(s_('ServiceDesk|Custom email address verification has already been processed and failed.')) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ServiceDesk::CustomEmailVerifications::UpdateService, feature_category: :service_desk do describe '#execute' do let_it_be_with_reload(:project) { create(:project) } let_it_be(:user) { create(:user) } let!(:credential) { create(:service_desk_custom_email_credential, project: project) } let(:settings) { create(:service_desk_setting, project: project, custom_email: '[email protected]') } let(:mail_object) { nil } let(:message_delivery) { instance_double(ActionMailer::MessageDelivery) } let(:service) { described_class.new(project: settings.project, params: { mail: mail_object }) } let(:error_parameter_missing) { s_('ServiceDesk|Service Desk setting or verification object missing') } let(:error_already_finished) { s_('ServiceDesk|Custom email address has already been verified.') } let(:error_already_failed) do s_('ServiceDesk|Custom email address verification has already been processed and failed.') end let(:expected_error_message) { error_parameter_missing } let(:expected_custom_email_enabled) { false } let(:logger_params) { { category: 'custom_email_verification' } } before do allow(message_delivery).to receive(:deliver_later) allow(Notify).to receive(:service_desk_verification_result_email).and_return(message_delivery) end shared_examples 'a failing verification process' do |expected_error_identifier| it 'refuses to verify and sends result emails', :aggregate_failures do expect(Notify).to receive(:service_desk_verification_result_email).twice expect(Gitlab::AppLogger).to receive(:info).with(logger_params.merge( error_message: expected_error_identifier.to_s )).once response = described_class.new(project: settings.project, params: { mail: mail_object }).execute settings.reset verification.reset expect(response).to be_error expect(settings).not_to be_custom_email_enabled expect(verification).to be_failed expect(response.reason).to eq expected_error_identifier expect(verification.error).to eq expected_error_identifier end end shared_examples 'an early exit from the verification process' do |expected_state| it 'exits early', :aggregate_failures do expect(Notify).to receive(:service_desk_verification_result_email).exactly(0).times expect(Gitlab::AppLogger).to receive(:warn).with(logger_params.merge( error_message: expected_error_message )).once response = service.execute settings.reset verification.reset expect(response).to be_error expect(settings.custom_email_enabled).to eq expected_custom_email_enabled expect(verification.state).to eq expected_state end end it 'exits early' do expect(Notify).to receive(:service_desk_verification_result_email).exactly(0).times expect(Gitlab::AppLogger).to receive(:warn).with(logger_params.merge( error_message: expected_error_message )).once response = service.execute settings.reset expect(response).to be_error expect(settings).not_to be_custom_email_enabled end context 'when verification exists' do let!(:verification) { create(:service_desk_custom_email_verification, project: project) } context 'when we do not have a verification email' do # Raise if verification started but no email provided it_behaves_like 'a failing verification process', 'mail_not_received_within_timeframe' context 'when already verified' do let(:expected_error_message) { error_already_finished } before do verification.mark_as_finished! end it_behaves_like 'an early exit from the verification process', 'finished' end context 'when we already have an error' do let(:expected_error_message) { error_already_failed } before do verification.mark_as_failed!(:smtp_host_issue) end it_behaves_like 'an early exit from the verification process', 'failed' end end context 'when we have a verification email' do before do verification.update!(token: 'ZROT4ZZXA-Y6') # token from email fixture end let(:email_raw) { email_fixture('emails/service_desk_custom_email_address_verification.eml') } let(:mail_object) { Mail::Message.new(email_raw) } it 'verifies and sends result emails' do expect(Notify).to receive(:service_desk_verification_result_email).twice expect(Gitlab::AppLogger).to receive(:info).with(logger_params).once response = service.execute settings.reset verification.reset expect(response).to be_success expect(settings).not_to be_custom_email_enabled expect(verification).to be_finished end context 'and verification tokens do not match' do before do verification.update!(token: 'XXXXXXZXA-XX') end it_behaves_like 'a failing verification process', 'incorrect_token' end context 'and from address does not match with custom email' do before do settings.update!(custom_email: '[email protected]') end it_behaves_like 'a failing verification process', 'incorrect_from' end context 'and timeframe for receiving the email is over' do before do verification.update!(triggered_at: 40.minutes.ago) end it_behaves_like 'a failing verification process', 'mail_not_received_within_timeframe' end context 'when already verified' do let(:expected_error_message) { error_already_finished } before do verification.mark_as_finished! end it_behaves_like 'an early exit from the verification process', 'finished' context 'when enabled' do let(:expected_custom_email_enabled) { true } before do settings.update!(custom_email_enabled: true) end it_behaves_like 'an early exit from the verification process', 'finished' end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ServiceDesk module CustomEmailVerifications class CreateService < BaseService attr_reader :ramp_up_error def execute return error_settings_missing unless settings.present? return error_user_not_authorized unless can?(current_user, :admin_project, project) update_settings notify_project_owners_and_user_about_verification_start send_verification_email_and_catch_delivery_errors if ramp_up_error handle_error_case else log_info ServiceResponse.success end end private def verification @verification ||= settings.custom_email_verification || ServiceDesk::CustomEmailVerification.new(project_id: settings.project_id) end def update_settings settings.update!(custom_email_enabled: false) if settings.custom_email_enabled? verification.mark_as_started!(current_user) # We use verification association from project, to use it in email, we need to reset it here. project.reset end def notify_project_owners_and_user_about_verification_start notify_project_owners_and_user_with_email( email_method_name: :service_desk_verification_triggered_email, user: current_user ) end def send_verification_email_and_catch_delivery_errors # Send this synchronously as we need to get direct feedback on delivery errors. Notify.service_desk_custom_email_verification_email(settings).deliver rescue SocketError, OpenSSL::SSL::SSLError # e.g. host not found or host certificate issues @ramp_up_error = :smtp_host_issue rescue Net::SMTPAuthenticationError # incorrect username or password @ramp_up_error = :invalid_credentials rescue Net::ReadTimeout # Server is slow to respond @ramp_up_error = :read_timeout end def handle_error_case notify_project_owners_and_user_about_result(user: current_user) verification.mark_as_failed!(ramp_up_error) error_not_verified(ramp_up_error) end def error_settings_missing error_response(s_('ServiceDesk|Service Desk setting missing')) end def error_user_not_authorized error_response(s_('ServiceDesk|User cannot manage project.')) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ServiceDesk::CustomEmailVerifications::CreateService, feature_category: :service_desk do describe '#execute' do let_it_be_with_reload(:project) { create(:project) } let_it_be(:user) { create(:user) } let!(:credential) { create(:service_desk_custom_email_credential, project: project) } let(:message_delivery) { instance_double(ActionMailer::MessageDelivery) } let(:message) { instance_double(Mail::Message) } let(:service) { described_class.new(project: project, current_user: user) } let(:error_user_not_authorized) { s_('ServiceDesk|User cannot manage project.') } let(:error_settings_missing) { s_('ServiceDesk|Service Desk setting missing') } let(:expected_error_message) { error_settings_missing } let(:logger_params) { { category: 'custom_email_verification' } } before do allow(message_delivery).to receive(:deliver_later) allow(Notify).to receive(:service_desk_verification_triggered_email).and_return(message_delivery) # We send verification email directly allow(message).to receive(:deliver) allow(Notify).to receive(:service_desk_custom_email_verification_email).and_return(message) end shared_examples 'a verification process that exits early' do it 'aborts verification process and exits early', :aggregate_failures do # Because we exit early it should not send any verification or notification emails expect(service).to receive(:setup_and_deliver_verification_email).exactly(0).times expect(Notify).to receive(:service_desk_verification_triggered_email).exactly(0).times expect(Gitlab::AppLogger).to receive(:warn).with(logger_params.merge( error_message: expected_error_message )).once response = service.execute expect(response).to be_error end end shared_examples 'a verification process with ramp up error' do it 'aborts verification process', :aggregate_failures do allow(message).to receive(:deliver).and_raise(error) # Creates one verification email expect(Notify).to receive(:service_desk_custom_email_verification_email).once # Correct amount of notification emails were sent expect(Notify).to receive(:service_desk_verification_triggered_email).exactly(project.owners.size + 1).times # Correct amount of result notification emails were sent expect(Notify).to receive(:service_desk_verification_result_email).exactly(project.owners.size + 1).times expect(Gitlab::AppLogger).to receive(:info).with(logger_params.merge( error_message: error_identifier.to_s )).once response = service.execute expect(response).to be_error expect(response.reason).to eq error_identifier expect(settings).not_to be_custom_email_enabled expect(settings.custom_email_verification.triggered_at).not_to be_nil expect(settings.custom_email_verification).to have_attributes( token: nil, triggerer: user, error: error_identifier, state: 'failed' ) end end it_behaves_like 'a verification process that exits early' context 'when service desk setting exists' do let(:settings) { create(:service_desk_setting, project: project, custom_email: '[email protected]') } let(:service) { described_class.new(project: settings.project, current_user: user) } let(:expected_error_message) { error_user_not_authorized } it 'aborts verification process and exits early', :aggregate_failures do # Because we exit early it should not send any verification or notification emails expect(service).to receive(:setup_and_deliver_verification_email).exactly(0).times expect(Notify).to receive(:service_desk_verification_triggered_email).exactly(0).times expect(Gitlab::AppLogger).to receive(:warn).with(logger_params.merge( error_message: expected_error_message )).once response = service.execute settings.reload expect(response).to be_error expect(settings.custom_email_enabled).to be false # Because service should normally add initial verification object expect(settings.custom_email_verification).to be nil end context 'when user has maintainer role in project' do before_all do project.add_maintainer(user) end it 'initiates verification process successfully', :aggregate_failures do # Creates one verification email expect(Notify).to receive(:service_desk_custom_email_verification_email).once # Check whether the correct amount of notification emails were sent expect(Notify).to receive(:service_desk_verification_triggered_email).exactly(project.owners.size + 1).times expect(Gitlab::AppLogger).to receive(:info).with(logger_params).once response = service.execute settings.reload verification = settings.custom_email_verification expect(response).to be_success expect(settings.custom_email_enabled).to be false expect(verification).to be_started expect(verification.token).not_to be_nil expect(verification.triggered_at).not_to be_nil expect(verification).to have_attributes( triggerer: user, error: nil ) end context 'when providing invalid SMTP credentials' do before do allow(Notify).to receive(:service_desk_verification_result_email).and_return(message_delivery) end it_behaves_like 'a verification process with ramp up error' do let(:error) { SocketError } let(:error_identifier) { 'smtp_host_issue' } end it_behaves_like 'a verification process with ramp up error' do let(:error) { OpenSSL::SSL::SSLError } let(:error_identifier) { 'smtp_host_issue' } end it_behaves_like 'a verification process with ramp up error' do let(:error) { Net::SMTPAuthenticationError.new('Invalid username or password') } let(:error_identifier) { 'invalid_credentials' } end it_behaves_like 'a verification process with ramp up error' do let(:error) { Net::ReadTimeout } let(:error_identifier) { 'read_timeout' } end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ServiceDesk module CustomEmails class DestroyService < BaseService def execute return error_user_not_authorized unless legitimate_user? return error_does_not_exist unless verification? || credential? || setting? project.service_desk_custom_email_verification&.destroy project.service_desk_custom_email_credential&.destroy project.reset project.service_desk_setting&.update!(custom_email: nil, custom_email_enabled: false) log_info ServiceResponse.success end private def error_does_not_exist error_response(s_('ServiceDesk|Custom email does not exist')) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ServiceDesk::CustomEmails::DestroyService, feature_category: :service_desk do describe '#execute' do let_it_be_with_reload(:project) { create(:project) } let(:user) { build_stubbed(:user) } let(:service) { described_class.new(project: project, current_user: user) } let(:error_user_not_authorized) { s_('ServiceDesk|User cannot manage project.') } let(:error_does_not_exist) { s_('ServiceDesk|Custom email does not exist') } let(:expected_error_message) { nil } let(:logger_params) { { category: 'custom_email' } } shared_examples 'a service that exits with error' do it 'exits early' do expect(Gitlab::AppLogger).to receive(:warn).with(logger_params.merge( error_message: expected_error_message )).once response = service.execute expect(response).to be_error expect(response.message).to eq(expected_error_message) end end shared_examples 'a successful service that destroys all custom email records' do it 'ensures no custom email records exist' do expect(Gitlab::AppLogger).to receive(:info).with(logger_params).once project.reset response = service.execute expect(response).to be_success expect(project.service_desk_custom_email_verification).to be nil expect(project.service_desk_custom_email_credential).to be nil expect(project.service_desk_setting).to have_attributes( custom_email: nil, custom_email_enabled: false ) end end context 'with illegitimate user' do let(:expected_error_message) { error_user_not_authorized } before do stub_member_access_level(project, developer: user) end it_behaves_like 'a service that exits with error' end context 'with legitimate user' do let(:expected_error_message) { error_does_not_exist } before do stub_member_access_level(project, maintainer: user) end it_behaves_like 'a service that exits with error' context 'when service desk setting exists' do let!(:settings) { create(:service_desk_setting, project: project) } it_behaves_like 'a successful service that destroys all custom email records' context 'when custom email is present' do let!(:settings) { create(:service_desk_setting, project: project, custom_email: '[email protected]') } it_behaves_like 'a successful service that destroys all custom email records' context 'when credential exists' do let!(:credential) { create(:service_desk_custom_email_credential, project: project) } it_behaves_like 'a successful service that destroys all custom email records' context 'when verification exists' do let!(:verification) { create(:service_desk_custom_email_verification, project: project) } it_behaves_like 'a successful service that destroys all custom email records' end end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ServiceDesk module CustomEmails class CreateService < BaseService def execute return error_user_not_authorized unless legitimate_user? return error_params_missing unless has_required_params? return error_custom_email_exists if credential? || verification? return error_cannot_create_custom_email unless create_credential if update_settings.error? # We don't warp everything in a single transaction here and roll it back # because ServiceDeskSettings::UpdateService uses safe_find_or_create_by! rollback_credential return error_cannot_create_custom_email end project.reset # The create service may return an error response if the verification fails early. # Here We want to indicate whether adding a custom email address was successful, so # we don't use its response here. create_verification log_info ServiceResponse.success end private def update_settings ServiceDeskSettings::UpdateService.new(project, current_user, create_setting_params).execute end def rollback_credential ::ServiceDesk::CustomEmailCredential.find_by_project_id(project.id)&.destroy end def create_credential credential = ::ServiceDesk::CustomEmailCredential.new(create_credential_params.merge(project: project)) credential.save rescue ArgumentError false end def create_verification ::ServiceDesk::CustomEmailVerifications::CreateService.new(project: project, current_user: current_user).execute end def create_setting_params ensure_params.permit(:custom_email) end def create_credential_params ensure_params.permit(:smtp_address, :smtp_port, :smtp_username, :smtp_password, :smtp_authentication) end def ensure_params return params if params.is_a?(ActionController::Parameters) ActionController::Parameters.new(params) end def has_required_params? required_keys.all? { |key| params.key?(key) && params[key].present? } end def required_keys %i[custom_email smtp_address smtp_port smtp_username smtp_password] end def error_custom_email_exists error_response(s_('ServiceDesk|Custom email already exists')) end def error_params_missing error_response(s_('ServiceDesk|Parameters missing')) end def error_cannot_create_custom_email error_response(s_('ServiceDesk|Cannot create custom email')) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ServiceDesk::CustomEmails::CreateService, feature_category: :service_desk do describe '#execute' do let_it_be_with_reload(:project) { create(:project) } let_it_be(:user) { create(:user) } let(:service) { described_class.new(project: project, current_user: user, params: params) } let(:error_user_not_authorized) { s_('ServiceDesk|User cannot manage project.') } let(:error_cannot_create_custom_email) { s_('ServiceDesk|Cannot create custom email') } let(:error_custom_email_exists) { s_('ServiceDesk|Custom email already exists') } let(:error_params_missing) { s_('ServiceDesk|Parameters missing') } let(:expected_error_message) { nil } let(:params) { {} } let(:message_delivery) { instance_double(ActionMailer::MessageDelivery) } let(:message) { instance_double(Mail::Message) } let(:logger_params) { { category: 'custom_email' } } shared_examples 'a service that exits with error' do it 'exits early' do expect(Gitlab::AppLogger).to receive(:warn).with(logger_params.merge( error_message: expected_error_message )).once response = service.execute expect(response).to be_error expect(response.message).to eq(expected_error_message) end end shared_examples 'a failing service that does not create records' do it 'exits with error and does not create records' do expect(Gitlab::AppLogger).to receive(:warn).with(logger_params.merge( error_message: expected_error_message )).once response = service.execute project.reset expect(response).to be_error expect(response.message).to eq(expected_error_message) expect(project.service_desk_custom_email_verification).to be nil expect(project.service_desk_custom_email_credential).to be nil expect(project.service_desk_setting).to have_attributes( custom_email: nil, custom_email_enabled: false ) end end context 'with illegitimate user' do let(:expected_error_message) { error_user_not_authorized } before do stub_member_access_level(project, developer: user) end it_behaves_like 'a service that exits with error' end context 'with legitimate user' do let!(:settings) { create(:service_desk_setting, project: project) } let(:expected_error_message) { error_params_missing } before do stub_member_access_level(project, maintainer: user) # We send verification email directly and it will fail with # smtp.example.com because it expects a valid DNS record allow(message).to receive(:deliver) allow(Notify).to receive(:service_desk_custom_email_verification_email).and_return(message) end it_behaves_like 'a service that exits with error' context 'with params but custom_email missing' do let(:params) do { smtp_address: 'smtp.example.com', smtp_port: '587', smtp_username: '[email protected]', smtp_password: 'supersecret' } end it_behaves_like 'a failing service that does not create records' end context 'with params but smtp username empty' do let(:params) do { custom_email: '[email protected]', smtp_address: 'smtp.example.com', smtp_port: '587', smtp_username: nil, smtp_password: 'supersecret' } end it_behaves_like 'a failing service that does not create records' end context 'with params but smtp password is too short' do let(:expected_error_message) { error_cannot_create_custom_email } let(:params) do { custom_email: '[email protected]', smtp_address: 'smtp.example.com', smtp_port: '587', smtp_username: '[email protected]', smtp_password: '2short' } end it_behaves_like 'a failing service that does not create records' end context 'with params but custom_email is invalid' do let(:expected_error_message) { error_cannot_create_custom_email } let(:params) do { custom_email: 'useratexampledotcom', smtp_address: 'smtp.example.com', smtp_port: '587', smtp_username: '[email protected]', smtp_password: 'supersecret' } end it_behaves_like 'a failing service that does not create records' end context 'with full set of params' do let(:params) do { custom_email: '[email protected]', smtp_address: 'smtp.example.com', smtp_port: '587', smtp_username: '[email protected]', smtp_password: 'supersecret' } end it 'creates all records and returns a successful response' do # Because we also log in ServiceDesk::CustomEmailVerifications::CreateService expect(Gitlab::AppLogger).to receive(:info).with({ category: 'custom_email_verification' }).once expect(Gitlab::AppLogger).to receive(:info).with(logger_params).once response = service.execute project.reset expect(response).to be_success expect(project.service_desk_setting).to have_attributes( custom_email: params[:custom_email], custom_email_enabled: false ) expect(project.service_desk_custom_email_credential).to have_attributes( smtp_address: params[:smtp_address], smtp_port: params[:smtp_port].to_i, smtp_username: params[:smtp_username], smtp_password: params[:smtp_password], smtp_authentication: nil ) expect(project.service_desk_custom_email_verification).to have_attributes( state: 'started', triggerer: user, error: nil ) end context 'with optional smtp_authentication parameter' do before do params[:smtp_authentication] = 'login' end it 'sets authentication and returns a successful response' do response = service.execute project.reset expect(response).to be_success expect(project.service_desk_custom_email_credential.smtp_authentication).to eq 'login' end context 'with unsupported value' do let(:expected_error_message) { error_cannot_create_custom_email } before do params[:smtp_authentication] = 'unsupported' end it_behaves_like 'a failing service that does not create records' end end context 'when custom email aready exists' do let!(:settings) { create(:service_desk_setting, project: project, custom_email: '[email protected]') } let!(:credential) { create(:service_desk_custom_email_credential, project: project) } let!(:verification) { create(:service_desk_custom_email_verification, project: project) } let(:expected_error_message) { error_custom_email_exists } it_behaves_like 'a service that exits with error' end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DependencyProxy class AuthTokenService < DependencyProxy::BaseService attr_reader :token def initialize(token) @token = token end def execute JSONWebToken::HMACToken.decode(token, ::Auth::DependencyProxyAuthenticationService.secret).first end def self.user_or_deploy_token_from_jwt(raw_jwt) token_payload = self.new(raw_jwt).execute if token_payload['user_id'] User.find(token_payload['user_id']) elsif token_payload['deploy_token'] DeployToken.active.find_by_token(token_payload['deploy_token']) end rescue JWT::DecodeError, JWT::ExpiredSignature, JWT::ImmatureSignature nil end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DependencyProxy::AuthTokenService, feature_category: :dependency_proxy do include DependencyProxyHelpers let_it_be(:user) { create(:user) } let_it_be(:deploy_token) { create(:deploy_token) } describe '.user_or_deploy_token_from_jwt' do subject { described_class.user_or_deploy_token_from_jwt(token.encoded) } shared_examples 'handling token errors' do context 'with a decoding error' do before do allow(JWT).to receive(:decode).and_raise(JWT::DecodeError) end it { is_expected.to eq(nil) } end context 'with an immature signature error' do before do allow(JWT).to receive(:decode).and_raise(JWT::ImmatureSignature) end it { is_expected.to eq(nil) } end context 'with an expired signature error' do it 'returns nil' do travel_to(Time.zone.now + Auth::DependencyProxyAuthenticationService.token_expire_at + 1.minute) do expect(subject).to eq(nil) end end end end context 'with a user' do let_it_be(:token) { build_jwt(user) } it { is_expected.to eq(user) } context 'with an invalid user id' do let_it_be(:token) { build_jwt { |jwt| jwt['user_id'] = 'this_is_not_a_user_id' } } it 'raises an not found error' do expect { subject }.to raise_error(ActiveRecord::RecordNotFound) end end it_behaves_like 'handling token errors' end context 'with a deploy token' do let_it_be(:token) { build_jwt(deploy_token) } it { is_expected.to eq(deploy_token) } context 'with an invalid token' do let_it_be(:token) { build_jwt { |jwt| jwt['deploy_token'] = 'this_is_not_a_token' } } it { is_expected.to eq(nil) } end it_behaves_like 'handling token errors' end context 'with an empty token payload' do let_it_be(:token) { build_jwt(nil) } it { is_expected.to eq(nil) } end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DependencyProxy class RequestTokenService < DependencyProxy::BaseService def initialize(image) @image = image end def execute response = Gitlab::HTTP.get(auth_url) if response.success? success(token: Gitlab::Json.parse(response.body)['token']) else error('Expected 200 response code for an access token', response.code) end rescue Timeout::Error => exception error(exception.message, 599) rescue JSON::ParserError error('Failed to parse a response body for an access token', 500) end private def auth_url registry.auth_url(@image) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DependencyProxy::RequestTokenService, feature_category: :dependency_proxy do include DependencyProxyHelpers let(:image) { 'alpine:3.9' } let(:token) { Digest::SHA256.hexdigest('123') } subject { described_class.new(image).execute } context 'remote request is successful' do before do stub_registry_auth(image, token) end it { expect(subject[:status]).to eq(:success) } it { expect(subject[:token]).to eq(token) } end context 'remote request is not found' do before do stub_registry_auth(image, token, 404) end it { expect(subject[:status]).to eq(:error) } it { expect(subject[:http_status]).to eq(404) } it { expect(subject[:message]).to eq('Expected 200 response code for an access token') } end context 'failed to parse response body' do before do stub_registry_auth(image, token, 200, 'dasd1321: wow') end it { expect(subject[:status]).to eq(:error) } it { expect(subject[:http_status]).to eq(500) } it { expect(subject[:message]).to eq('Failed to parse a response body for an access token') } end context 'net timeout exception' do before do auth_link = DependencyProxy::Registry.auth_url(image) stub_full_request(auth_link, method: :any).to_timeout end it { expect(subject[:status]).to eq(:error) } it { expect(subject[:http_status]).to eq(599) } it { expect(subject[:message]).to eq('execution expired') } end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DependencyProxy class HeadManifestService < DependencyProxy::BaseService ACCEPT_HEADERS = DependencyProxy::Manifest::ACCEPTED_TYPES.join(',') def initialize(image, tag, token) @image = image @tag = tag @token = token end def execute response = Gitlab::HTTP.head(manifest_url, headers: auth_headers.merge(Accept: ACCEPT_HEADERS)) if response.success? success( digest: response.headers[DependencyProxy::Manifest::DIGEST_HEADER], content_type: response.headers['content-type'] ) else error(response.body, response.code) end rescue Timeout::Error => exception error(exception.message, 599) end private def manifest_url registry.manifest_url(@image, @tag) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DependencyProxy::HeadManifestService, feature_category: :dependency_proxy do include DependencyProxyHelpers let(:image) { 'alpine' } let(:tag) { 'latest' } let(:token) { Digest::SHA256.hexdigest('123') } let(:digest) { '12345' } let(:content_type) { 'foo' } let(:headers) do { DependencyProxy::Manifest::DIGEST_HEADER => digest, 'content-type' => content_type } end subject { described_class.new(image, tag, token).execute } context 'remote request is successful' do before do stub_manifest_head(image, tag, headers: headers) end it { expect(subject[:status]).to eq(:success) } it { expect(subject[:digest]).to eq(digest) } end context 'remote request is not found' do before do stub_manifest_head(image, tag, status: 404, body: 'Not found') end it { expect(subject[:status]).to eq(:error) } it { expect(subject[:http_status]).to eq(404) } it { expect(subject[:message]).to eq('Not found') } end context 'net timeout exception' do before do manifest_link = DependencyProxy::Registry.manifest_url(image, tag) stub_full_request(manifest_link, method: :head).to_timeout end it { expect(subject[:status]).to eq(:error) } it { expect(subject[:http_status]).to eq(599) } it { expect(subject[:message]).to eq('execution expired') } end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DependencyProxy class FindCachedManifestService < DependencyProxy::BaseService def initialize(group, image, tag, token) @group = group @image = image @tag = tag @token = token @file_name = "#{@image}:#{@tag}.json" @manifest = nil end def execute @manifest = @group.dependency_proxy_manifests .active .find_by_file_name_or_digest(file_name: @file_name, digest: @tag) head_result = DependencyProxy::HeadManifestService.new(@image, @tag, @token).execute return respond if cached_manifest_matches?(head_result) return respond if @manifest && head_result[:status] == :error success(manifest: nil, from_cache: false) rescue Timeout::Error, *Gitlab::HTTP::HTTP_ERRORS respond end private def cached_manifest_matches?(head_result) return false if head_result[:status] == :error @manifest && @manifest.digest == head_result[:digest] && @manifest.content_type == head_result[:content_type] end def respond(from_cache: true) if @manifest @manifest.read! success(manifest: @manifest, from_cache: from_cache) else error('Failed to download the manifest from the external registry', 503) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DependencyProxy::FindCachedManifestService, feature_category: :dependency_proxy do include DependencyProxyHelpers let_it_be(:image) { 'alpine' } let_it_be(:tag) { 'latest' } let_it_be(:dependency_proxy_manifest) { create(:dependency_proxy_manifest, file_name: "#{image}:#{tag}.json") } let(:manifest) { dependency_proxy_manifest.file.read } let(:group) { dependency_proxy_manifest.group } let(:token) { Digest::SHA256.hexdigest('123') } let(:headers) do { DependencyProxy::Manifest::DIGEST_HEADER => dependency_proxy_manifest.digest, 'content-type' => dependency_proxy_manifest.content_type } end describe '#execute' do subject { described_class.new(group, image, tag, token).execute } shared_examples 'downloading the manifest' do it 'downloads manifest from remote registry if there is no cached one', :aggregate_failures do expect { subject }.to change { group.dependency_proxy_manifests.count }.by(1) expect(subject[:status]).to eq(:success) expect(subject[:manifest]).to be_a(DependencyProxy::Manifest) expect(subject[:manifest]).to be_persisted expect(subject[:from_cache]).to eq false end end shared_examples 'returning no manifest' do it 'returns a nil manifest' do expect(subject[:status]).to eq(:success) expect(subject[:from_cache]).to eq false expect(subject[:manifest]).to be_nil end end shared_examples 'returning an error' do it 'returns an error', :aggregate_failures do expect(subject[:status]).to eq(:error) expect(subject[:http_status]).to eq(503) expect(subject[:message]).to eq('Failed to download the manifest from the external registry') end end context 'when no manifest exists' do let_it_be(:image) { 'new-image' } context 'successful head request' do before do stub_manifest_head(image, tag, headers: headers) stub_manifest_download(image, tag, headers: headers) end it_behaves_like 'returning no manifest' end context 'failed head request' do before do stub_manifest_head(image, tag, status: :error) stub_manifest_download(image, tag, headers: headers) end it_behaves_like 'returning no manifest' end end context 'when manifest exists' do before do stub_manifest_head(image, tag, headers: headers) end shared_examples 'using the cached manifest' do it 'uses cached manifest instead of downloading one', :aggregate_failures do expect { subject }.to change { dependency_proxy_manifest.reload.read_at } expect(subject[:status]).to eq(:success) expect(subject[:manifest]).to be_a(DependencyProxy::Manifest) expect(subject[:manifest]).to eq(dependency_proxy_manifest) expect(subject[:from_cache]).to eq true end end it_behaves_like 'using the cached manifest' context 'when digest is stale' do let(:digest) { 'new-digest' } let(:content_type) { 'new-content-type' } before do stub_manifest_head(image, tag, headers: { DependencyProxy::Manifest::DIGEST_HEADER => digest, 'content-type' => content_type }) stub_manifest_download(image, tag, headers: { DependencyProxy::Manifest::DIGEST_HEADER => digest, 'content-type' => content_type }) end it_behaves_like 'returning no manifest' end context 'when the cached manifest is pending destruction' do before do dependency_proxy_manifest.update_column(:status, DependencyProxy::Manifest.statuses[:pending_destruction]) stub_manifest_head(image, tag, headers: headers) stub_manifest_download(image, tag, headers: headers) end it_behaves_like 'returning no manifest' end context 'when the connection fails' do before do expect(DependencyProxy::HeadManifestService).to receive(:new).and_raise(Net::OpenTimeout) end it_behaves_like 'using the cached manifest' context 'and no manifest is cached' do let_it_be(:image) { 'new-image' } it_behaves_like 'returning an error' end end context 'when the connection is successful but with error in result' do before do allow_next_instance_of(DependencyProxy::HeadManifestService) do |service| allow(service).to receive(:execute).and_return(status: :error, http_status: 401, message: "Not found") end end it_behaves_like 'using the cached manifest' context 'and no manifest is cached' do let_it_be(:image) { 'new-image' } it_behaves_like 'returning no manifest' end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DependencyProxy module ImageTtlGroupPolicies class UpdateService < BaseContainerService include Gitlab::Utils::StrongMemoize ALLOWED_ATTRIBUTES = %i[enabled ttl].freeze def execute return ServiceResponse.error(message: 'Access Denied', http_status: 403) unless allowed? return ServiceResponse.error(message: 'Dependency proxy image TTL Policy not found', http_status: 404) unless dependency_proxy_image_ttl_policy if dependency_proxy_image_ttl_policy.update(dependency_proxy_image_ttl_policy_params) ServiceResponse.success(payload: { dependency_proxy_image_ttl_policy: dependency_proxy_image_ttl_policy }) else ServiceResponse.error( message: dependency_proxy_image_ttl_policy.errors.full_messages.to_sentence || 'Bad request', http_status: 400 ) end end private def dependency_proxy_image_ttl_policy strong_memoize(:dependency_proxy_image_ttl_policy) do container.dependency_proxy_image_ttl_policy end end def allowed? Ability.allowed?(current_user, :admin_dependency_proxy, container) end def dependency_proxy_image_ttl_policy_params params.slice(*ALLOWED_ATTRIBUTES) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::DependencyProxy::ImageTtlGroupPolicies::UpdateService, feature_category: :dependency_proxy do using RSpec::Parameterized::TableSyntax let_it_be_with_reload(:group) { create(:group) } let_it_be(:user) { create(:user) } let_it_be(:params) { {} } describe '#execute' do subject { described_class.new(container: group, current_user: user, params: params).execute } shared_examples 'returning a success' do it 'returns a success' do result = subject expect(result.payload[:dependency_proxy_image_ttl_policy]).to be_present expect(result).to be_success end end shared_examples 'returning an error' do |message, http_status| it 'returns an error' do result = subject expect(result).to have_attributes( message: message, status: :error, http_status: http_status ) end end shared_examples 'updating the dependency proxy image ttl policy' do it_behaves_like 'updating the dependency proxy image ttl policy attributes', from: { enabled: true, ttl: 90 }, to: { enabled: false, ttl: 2 } it_behaves_like 'returning a success' context 'with invalid params' do let_it_be(:params) { { enabled: nil } } it_behaves_like 'not creating the dependency proxy image ttl policy' it "doesn't update" do expect { subject } .not_to change { ttl_policy.reload.enabled } end it_behaves_like 'returning an error', 'Enabled is not included in the list', 400 end end shared_examples 'denying access to dependency proxy image ttl policy' do context 'with existing dependency proxy image ttl policy' do it_behaves_like 'not creating the dependency proxy image ttl policy' 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 dependency proxy image ttl policy" end before do stub_config(dependency_proxy: { enabled: true }) end context 'with existing dependency proxy image ttl policy' do let_it_be(:ttl_policy) { create(:image_ttl_group_policy, group: group) } let_it_be(:params) { { enabled: false, ttl: 2 } } where(:user_role, :shared_examples_name) do :owner | 'updating the dependency proxy image ttl policy' :maintainer | 'denying access to dependency proxy image ttl policy' :developer | 'denying access to dependency proxy image ttl policy' :reporter | 'denying access to dependency proxy image ttl policy' :guest | 'denying access to dependency proxy image ttl policy' :anonymous | 'denying access to dependency proxy image ttl policy' end with_them do before do group.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 dependency proxy image ttl policy' do let_it_be(:ttl_policy) { group.dependency_proxy_image_ttl_policy } where(:user_role, :shared_examples_name) do :owner | 'creating the dependency proxy image ttl policy' :maintainer | 'denying access to dependency proxy image ttl policy' :developer | 'denying access to dependency proxy image ttl policy' :reporter | 'denying access to dependency proxy image ttl policy' :guest | 'denying access to dependency proxy image ttl policy' :anonymous | 'denying access to dependency proxy image ttl policy' end with_them do before do group.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 context 'when the policy is not found' do %i[owner maintainer].each do |role| context "when user is #{role}" do before do group.send("add_#{role}", user) stub_feature_flags(raise_group_admin_package_permission_to_owner: false) expect(group).to receive(:dependency_proxy_image_ttl_policy).and_return nil end it_behaves_like 'returning an error', 'Dependency proxy image TTL Policy not found', 404 end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DependencyProxy module GroupSettings class UpdateService < BaseContainerService ALLOWED_ATTRIBUTES = %i[enabled].freeze def execute return ServiceResponse.error(message: 'Access Denied', http_status: 403) unless allowed? return ServiceResponse.error(message: 'Dependency proxy setting not found', http_status: 404) unless dependency_proxy_setting if dependency_proxy_setting.update(dependency_proxy_setting_params) ServiceResponse.success(payload: { dependency_proxy_setting: dependency_proxy_setting }) else ServiceResponse.error( message: dependency_proxy_setting.errors.full_messages.to_sentence || 'Bad request', http_status: 400 ) end end private def dependency_proxy_setting container.dependency_proxy_setting end def allowed? Ability.allowed?(current_user, :admin_dependency_proxy, container) end def dependency_proxy_setting_params params.slice(*ALLOWED_ATTRIBUTES) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::DependencyProxy::GroupSettings::UpdateService, feature_category: :dependency_proxy do using RSpec::Parameterized::TableSyntax let_it_be_with_reload(:group) { create(:group) } let_it_be_with_reload(:group_settings) { create(:dependency_proxy_group_setting, group: group) } let_it_be(:user) { create(:user) } let_it_be(:params) { { enabled: false } } describe '#execute' do subject { described_class.new(container: group, current_user: user, params: params).execute } shared_examples 'updating the dependency proxy group settings' do it_behaves_like 'updating the dependency proxy group settings attributes', from: { enabled: true }, to: { enabled: false } it 'returns a success' do result = subject expect(result.payload[:dependency_proxy_setting]).to be_present expect(result).to be_success end end shared_examples 'denying access to dependency proxy group settings' do context 'with existing dependency proxy group settings' do it 'returns an error' do result = subject expect(result).to have_attributes( message: 'Access Denied', status: :error, http_status: 403 ) end end end where(:user_role, :shared_examples_name) do :owner | 'updating the dependency proxy group settings' :maintainer | 'denying access to dependency proxy group settings' :developer | 'denying access to dependency proxy group settings' :reporter | 'denying access to dependency proxy group settings' :guest | 'denying access to dependency proxy group settings' :anonymous | 'denying access to dependency proxy group settings' end with_them do before do stub_config(dependency_proxy: { enabled: true }) group.send("add_#{user_role}", user) unless user_role == :anonymous end it_behaves_like params[:shared_examples_name] context 'with disabled admin_package feature flag' do before do stub_feature_flags(raise_group_admin_package_permission_to_owner: false) end it_behaves_like 'updating the dependency proxy group settings' if params[:user_role] == :maintainer end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Jira module Requests module Projects class ListService < Base extend ::Gitlab::Utils::Override def initialize(jira_integration, params = {}) super(jira_integration, params) @query = params[:query] end private attr_reader :query override :url def url "#{base_api_url}/project" end override :build_service_response def build_service_response(response) return ServiceResponse.success(payload: empty_payload) unless response.present? ServiceResponse.success(payload: { projects: map_projects(response), is_last: true }) end def map_projects(response) response .map { |v| JIRA::Resource::Project.build(client, v) } .select { |jira_project| match_query?(jira_project) } end def match_query?(jira_project) downcase_query = query.to_s.downcase jira_project&.key&.downcase&.include?(downcase_query) || jira_project&.name&.downcase&.include?(downcase_query) end def empty_payload { projects: [], is_last: true } end end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Jira::Requests::Projects::ListService, feature_category: :groups_and_projects do include AfterNextHelpers let(:jira_integration) { create(:jira_integration) } let(:params) { {} } describe '#execute' do let(:service) { described_class.new(jira_integration, params) } subject { service.execute } context 'without jira_integration' do before do jira_integration.update!(active: false) end it 'returns an error response' do expect(subject.error?).to be_truthy expect(subject.message).to eq('Jira service not configured.') end end context 'when jira_integration is nil' do let(:jira_integration) { nil } it 'returns an error response' do expect(subject.error?).to be_truthy expect(subject.message).to eq('Jira service not configured.') end end context 'with jira_integration' do context 'when validations and params are ok' do let(:response_headers) { { 'content-type' => 'application/json' } } let(:response_body) { [].to_json } let(:expected_url_pattern) { %r{.*jira.example.com/rest/api/2/project} } before do stub_request(:get, expected_url_pattern).to_return(status: 200, body: response_body, headers: response_headers) end it_behaves_like 'a service that handles Jira API errors' context 'when jira runs on a subpath' do let(:jira_integration) { create(:jira_integration, url: 'http://jira.example.com/jira') } let(:expected_url_pattern) { %r{.*jira.example.com/jira/rest/api/2/project} } it 'takes the subpath into account' do expect(subject.success?).to be_truthy end end context 'when the request does not return any values' do let(:response_body) { [].to_json } it 'returns a paylod with no projects returned' do payload = subject.payload expect(subject.success?).to be_truthy expect(payload[:projects]).to be_empty expect(payload[:is_last]).to be_truthy end end context 'when the request returns values' do let(:response_body) { [{ 'key' => 'pr1', 'name' => 'First Project' }, { 'key' => 'pr2', 'name' => 'Second Project' }].to_json } it 'returns a paylod with Jira projects' do payload = subject.payload expect(subject.success?).to be_truthy expect(payload[:projects].map(&:key)).to eq(%w[pr1 pr2]) expect(payload[:is_last]).to be_truthy end context 'when filtering projects by name' do let(:params) { { query: 'first' } } it 'returns a paylod with Jira procjets' do payload = subject.payload expect(subject.success?).to be_truthy expect(payload[:projects].map(&:key)).to eq(%w[pr1]) expect(payload[:is_last]).to be_truthy end end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ContainerExpirationPolicies class CleanupService attr_reader :repository SERVICE_RESULT_FIELDS = %i[original_size before_truncate_size after_truncate_size before_delete_size deleted_size cached_tags_count].freeze def initialize(repository) @repository = repository end def execute return ServiceResponse.error(message: 'no repository') unless repository unless policy.valid? disable_policy! return ServiceResponse.error(message: 'invalid policy') end schedule_next_run_if_needed begin service_result = Projects::ContainerRepository::CleanupTagsService .new(container_repository: repository, params: policy_params.merge('container_expiration_policy' => true)) .execute rescue StandardError repository.cleanup_unfinished! raise end if service_result[:status] == :success repository.update!( expiration_policy_cleanup_status: :cleanup_unscheduled, expiration_policy_completed_at: Time.zone.now, last_cleanup_deleted_tags_count: service_result[:deleted_size] ) success(:finished, service_result) else repository.cleanup_unfinished! success(:unfinished, service_result) end end private def schedule_next_run_if_needed return if policy.next_run_at.future? repos_before_next_run = ::ContainerRepository.for_project_id(policy.project_id) .expiration_policy_started_at_nil_or_before(policy.next_run_at) return if repos_before_next_run.exists? policy.schedule_next_run! end def disable_policy! policy.disable! repository.cleanup_unscheduled! Gitlab::ErrorTracking.log_exception( ::ContainerExpirationPolicyWorker::InvalidPolicyError.new, container_expiration_policy_id: policy.id ) end def success(cleanup_status, service_result) payload = { cleanup_status: cleanup_status, container_repository_id: repository.id } SERVICE_RESULT_FIELDS.each do |field| payload["cleanup_tags_service_#{field}".to_sym] = service_result[field] end ServiceResponse.success(message: "cleanup #{cleanup_status}", payload: payload) end def policy_params return {} unless policy policy.policy_params end def policy project.container_expiration_policy end def project repository&.project end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ContainerExpirationPolicies::CleanupService, feature_category: :container_registry do let_it_be(:repository, reload: true) { create(:container_repository, expiration_policy_started_at: 30.minutes.ago) } let_it_be(:project) { repository.project } let(:service) { described_class.new(repository) } describe '#execute' do let(:policy) { repository.project.container_expiration_policy } subject { service.execute } before do policy.update!(enabled: true) policy.update_column(:next_run_at, 5.minutes.ago) end context 'with a successful cleanup tags service execution' do let(:cleanup_tags_service_params) { project.container_expiration_policy.policy_params.merge('container_expiration_policy' => true) } let(:cleanup_tags_service) { instance_double(Projects::ContainerRepository::CleanupTagsService) } it 'completely clean up the repository' do expect(Projects::ContainerRepository::CleanupTagsService) .to receive(:new).with(container_repository: repository, params: cleanup_tags_service_params).and_return(cleanup_tags_service) expect(cleanup_tags_service).to receive(:execute).and_return(status: :success, deleted_size: 1) response = subject aggregate_failures "checking the response and container repositories" do expect(response.success?).to eq(true) expect(response.payload).to include(cleanup_status: :finished, container_repository_id: repository.id) expect(ContainerRepository.waiting_for_cleanup.count).to eq(0) expect(repository.reload.cleanup_unscheduled?).to be_truthy expect(repository.expiration_policy_completed_at).not_to eq(nil) expect(repository.expiration_policy_started_at).not_to eq(nil) expect(repository.last_cleanup_deleted_tags_count).to eq(1) end end end context 'without a successful cleanup tags service execution' do let(:cleanup_tags_service_response) { { status: :error, message: 'timeout' } } before do expect(Projects::ContainerRepository::CleanupTagsService) .to receive(:new).and_return(double(execute: cleanup_tags_service_response)) end it 'partially clean up the repository' do response = subject aggregate_failures "checking the response and container repositories" do expect(response.success?).to eq(true) expect(response.payload).to include(cleanup_status: :unfinished, container_repository_id: repository.id) expect(ContainerRepository.waiting_for_cleanup.count).to eq(1) expect(repository.reload.cleanup_unfinished?).to be_truthy expect(repository.expiration_policy_started_at).not_to eq(nil) expect(repository.expiration_policy_completed_at).to eq(nil) expect(repository.last_cleanup_deleted_tags_count).to eq(nil) end end context 'with a truncated cleanup tags service response' do let(:cleanup_tags_service_response) do { status: :error, original_size: 1000, before_truncate_size: 800, after_truncate_size: 200, before_delete_size: 100, cached_tags_count: 0, deleted_size: 100 } end it 'partially clean up the repository' do response = subject aggregate_failures "checking the response and container repositories" do expect(response.success?).to eq(true) expect(response.payload) .to include( cleanup_status: :unfinished, container_repository_id: repository.id, cleanup_tags_service_original_size: 1000, cleanup_tags_service_before_truncate_size: 800, cleanup_tags_service_after_truncate_size: 200, cleanup_tags_service_before_delete_size: 100, cleanup_tags_service_cached_tags_count: 0, cleanup_tags_service_deleted_size: 100 ) expect(ContainerRepository.waiting_for_cleanup.count).to eq(1) expect(repository.reload.cleanup_unfinished?).to be_truthy expect(repository.expiration_policy_started_at).not_to eq(nil) expect(repository.expiration_policy_completed_at).to eq(nil) expect(repository.last_cleanup_deleted_tags_count).to eq(nil) end end end end context 'with no repository' do let(:service) { described_class.new(nil) } it 'returns an error response' do expect(subject.success?).to eq(false) expect(subject.message).to eq('no repository') end end context 'with an invalid policy' do let(:policy) { repository.project.container_expiration_policy } before do policy.name_regex = nil policy.enabled = true repository.expiration_policy_cleanup_status = :cleanup_ongoing end it 'returns an error response' do expect { subject }.to change { repository.expiration_policy_cleanup_status }.from('cleanup_ongoing').to('cleanup_unscheduled') expect(subject.success?).to eq(false) expect(subject.message).to eq('invalid policy') expect(policy).not_to be_enabled end end context 'with a network error' do before do expect(Projects::ContainerRepository::CleanupTagsService) .to receive(:new).and_raise(Faraday::TimeoutError) end it 'raises an error' do expect { subject }.to raise_error(Faraday::TimeoutError) expect(ContainerRepository.waiting_for_cleanup.count).to eq(1) expect(repository.reload.cleanup_unfinished?).to be_truthy expect(repository.expiration_policy_started_at).not_to eq(nil) expect(repository.expiration_policy_completed_at).to eq(nil) expect(repository.last_cleanup_deleted_tags_count).to eq(nil) end end context 'next run scheduling' do let_it_be_with_reload(:repository2) { create(:container_repository, project: project) } let_it_be_with_reload(:repository3) { create(:container_repository, project: project) } before do cleanup_tags_service = instance_double(Projects::ContainerRepository::CleanupTagsService) allow(Projects::ContainerRepository::CleanupTagsService) .to receive(:new).and_return(cleanup_tags_service) allow(cleanup_tags_service).to receive(:execute).and_return(status: :success) end shared_examples 'not scheduling the next run' do it 'does not scheduled the next run' do expect(policy).not_to receive(:schedule_next_run!) expect { subject }.not_to change { policy.reload.next_run_at } end end shared_examples 'scheduling the next run' do it 'schedules the next run' do expect(policy).to receive(:schedule_next_run!).and_call_original expect { subject }.to change { policy.reload.next_run_at } end end context 'with cleanups started_at before policy next_run_at' do before do ContainerRepository.update_all(expiration_policy_started_at: 10.minutes.ago) end it_behaves_like 'not scheduling the next run' end context 'with cleanups started_at around policy next_run_at' do before do repository3.update!(expiration_policy_started_at: policy.next_run_at + 10.minutes.ago) end it_behaves_like 'not scheduling the next run' end context 'with only the current repository started_at before the policy next_run_at' do before do repository.update!(expiration_policy_started_at: policy.next_run_at + 9.minutes) repository2.update!(expiration_policy_started_at: policy.next_run_at + 10.minutes) repository3.update!(expiration_policy_started_at: policy.next_run_at + 12.minutes) end it_behaves_like 'scheduling the next run' end context 'with cleanups started_at after policy next_run_at' do before do ContainerRepository.update_all(expiration_policy_started_at: policy.next_run_at + 10.minutes) end it_behaves_like 'scheduling the next run' end context 'with a future policy next_run_at' do before do policy.update_column(:next_run_at, 5.minutes.from_now) end it_behaves_like 'not scheduling the next run' end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ContainerExpirationPolicies class UpdateService < BaseContainerService include Gitlab::Utils::StrongMemoize ALLOWED_ATTRIBUTES = %i[enabled cadence older_than keep_n name_regex name_regex_keep].freeze def execute return ServiceResponse.error(message: 'Access Denied', http_status: 403) unless allowed? if container_expiration_policy.update(container_expiration_policy_params) ServiceResponse.success(payload: { container_expiration_policy: container_expiration_policy }) else ServiceResponse.error( message: container_expiration_policy.errors.full_messages.to_sentence || 'Bad request', http_status: 400 ) end end private def container_expiration_policy strong_memoize(:container_expiration_policy) do @container.container_expiration_policy || @container.build_container_expiration_policy end end def allowed? Ability.allowed?(current_user, :admin_container_image, @container) end def container_expiration_policy_params @params.slice(*ALLOWED_ATTRIBUTES) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ContainerExpirationPolicies::UpdateService, feature_category: :container_registry do using RSpec::Parameterized::TableSyntax let_it_be(:project, reload: true) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:params) { { cadence: '3month', keep_n: 100, older_than: '14d', extra_key: 'will_not_be_processed' } } let(:container_expiration_policy) { project.container_expiration_policy } describe '#execute' do subject { described_class.new(container: project, current_user: user, params: params).execute } RSpec.shared_examples 'returning a success' do it 'returns a success' do result = subject expect(result.payload[:container_expiration_policy]).to be_present expect(result.success?).to be_truthy end end RSpec.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 RSpec.shared_examples 'updating the container expiration policy' do it_behaves_like 'updating the container expiration policy attributes', mode: :update, from: { cadence: '1d', keep_n: 10, older_than: '90d' }, to: { cadence: '3month', keep_n: 100, older_than: '14d' } it_behaves_like 'returning a success' context 'with invalid params' do let_it_be(:params) { { cadence: '20d' } } it_behaves_like 'not creating the container expiration policy' it "doesn't update the cadence" do expect { subject } .not_to change { container_expiration_policy.reload.cadence } end it_behaves_like 'returning an error', 'Cadence is not included in the list', 400 end end RSpec.shared_examples 'denying access to container expiration policy' do context 'with existing container expiration policy' do it_behaves_like 'not creating the container expiration policy' it_behaves_like 'returning an error', 'Access Denied', 403 end end context 'with existing container expiration policy' do where(:user_role, :shared_examples_name) do :maintainer | 'updating the container expiration policy' :developer | 'denying access to container expiration policy' :reporter | 'denying access to container expiration policy' :guest | 'denying access to container expiration policy' :anonymous | 'denying access to container expiration policy' end with_them do before do project.send("add_#{user_role}", user) unless user_role == :anonymous end it_behaves_like params[:shared_examples_name] end end context 'without existing container expiration policy' do let_it_be(:project, reload: true) { create(:project, :without_container_expiration_policy) } where(:user_role, :shared_examples_name) do :maintainer | 'creating the container expiration policy' :developer | 'denying access to container expiration policy' :reporter | 'denying access to container expiration policy' :guest | 'denying access to container expiration policy' :anonymous | 'denying access to container expiration policy' end with_them do before do project.send("add_#{user_role}", user) unless user_role == :anonymous end it_behaves_like params[:shared_examples_name] end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notes class ResolveService < ::BaseService def execute(note) note.resolve!(current_user) ::MergeRequests::ResolvedDiscussionNotificationService.new(project: project, current_user: current_user).execute(note.noteable) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::ResolveService, feature_category: :team_planning do let(:merge_request) { create(:merge_request) } let(:note) { create(:diff_note_on_merge_request, noteable: merge_request, project: merge_request.project) } let(:user) { merge_request.author } describe '#execute' do it "resolves the note" do described_class.new(merge_request.project, user).execute(note) note.reload expect(note.resolved?).to be true expect(note.resolved_by).to eq(user) end it "sends notifications if all discussions are resolved" do expect_next_instance_of(MergeRequests::ResolvedDiscussionNotificationService) do |instance| expect(instance).to receive(:execute).with(merge_request) end described_class.new(merge_request.project, user).execute(note) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # This service copies Notes from one Noteable to another. # # It expects the calling code to have performed the necessary authorization # checks in order to allow the copy to happen. module Notes class CopyService def initialize(current_user, from_noteable, to_noteable) raise ArgumentError, 'Noteables must be different' if from_noteable == to_noteable @current_user = current_user @from_noteable = from_noteable @to_noteable = to_noteable @from_project = from_noteable.project @new_discussion_ids = {} end def execute from_noteable.notes_with_associations.find_each do |note| copy_note(note) end ServiceResponse.success end private attr_reader :from_noteable, :to_noteable, :from_project, :current_user, :new_discussion_ids def copy_note(note) new_note = note.dup new_params = params_from_note(note, new_note) new_note.update!(new_params) copy_award_emoji(note, new_note) end def params_from_note(note, new_note) new_discussion_ids[note.discussion_id] ||= Discussion.discussion_id(new_note) new_params = sanitized_note_params(note) new_params.merge!( project: to_noteable.project, noteable: to_noteable, discussion_id: new_discussion_ids[note.discussion_id], created_at: note.created_at, updated_at: note.updated_at ) if note.system_note_metadata new_params[:system_note_metadata] = note.system_note_metadata.dup # TODO: Implement copying of description versions when an issue is moved # https://gitlab.com/gitlab-org/gitlab/issues/32300 new_params[:system_note_metadata].description_version = nil end new_params end # Skip copying cached markdown HTML if text # does not contain references or uploads. def sanitized_note_params(note) MarkdownContentRewriterService .new(current_user, note, :note, from_project, to_noteable.resource_parent) .execute end def copy_award_emoji(from_note, to_note) AwardEmojis::CopyService.new(from_note, to_note).execute end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::CopyService, feature_category: :team_planning do describe '#initialize' do let_it_be(:noteable) { create(:issue) } it 'validates that we cannot copy notes to the same Noteable' do expect { described_class.new(nil, noteable, noteable) }.to raise_error(ArgumentError) end end describe '#execute' do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:from_project) { create(:project, :public, group: group) } let_it_be(:to_project) { create(:project, :public, group: group) } let_it_be(:from_noteable) { create(:issue, project: from_project) } let_it_be(:to_noteable) { create(:issue, project: to_project) } subject(:execute_service) { described_class.new(user, from_noteable, to_noteable).execute } context 'rewriting the note body' do context 'simple notes' do let!(:notes) do [ create( :note, noteable: from_noteable, project: from_noteable.project, created_at: 2.weeks.ago, updated_at: 1.week.ago ), create(:note, noteable: from_noteable, project: from_noteable.project), create(:note, system: true, noteable: from_noteable, project: from_noteable.project) ] end it 'rewrites existing notes in valid order' do execute_service expect(to_noteable.notes.order('id ASC').pluck(:note).first(3)).to eq(notes.map(&:note)) end it 'copies all the issue notes' do execute_service expect(to_noteable.notes.count).to eq(3) end it 'does not change the note attributes' do execute_service new_note = to_noteable.notes.first expect(new_note).to have_attributes( note: notes.first.note, author: notes.first.author ) end it 'copies the award emojis' do create(:award_emoji, awardable: notes.first, name: 'thumbsup') execute_service new_award_emoji = to_noteable.notes.first.award_emoji.first expect(new_award_emoji.name).to eq('thumbsup') end it 'copies system_note_metadata for system note' do system_note_metadata = create(:system_note_metadata, note: notes.last) execute_service new_note = to_noteable.notes.last aggregate_failures do expect(new_note.system_note_metadata.action).to eq(system_note_metadata.action) expect(new_note.system_note_metadata.id).not_to eq(system_note_metadata.id) end end it 'returns success' do aggregate_failures do expect(execute_service).to be_kind_of(ServiceResponse) expect(execute_service).to be_success end end it 'copies rendered markdown from note_html' do expect(Banzai::Renderer).not_to receive(:cacheless_render_field) execute_service new_note = to_noteable.notes.first expect(new_note.note_html).to eq(notes.first.note_html) end end context 'notes with mentions' do let!(:note_with_mention) { create(:note, noteable: from_noteable, author: from_noteable.author, project: from_noteable.project, note: "note with mention #{user.to_reference}") } let!(:note_with_no_mention) { create(:note, noteable: from_noteable, author: from_noteable.author, project: from_noteable.project, note: "note without mention") } it 'saves user mentions with actual mentions for new issue' do execute_service aggregate_failures do expect(to_noteable.user_mentions.first.mentioned_users_ids).to match_array([user.id]) expect(to_noteable.user_mentions.count).to eq(1) end end end context 'notes with reference' do let(:other_issue) { create(:issue, project: from_noteable.project) } let(:merge_request) { create(:merge_request) } let(:text) { "See ##{other_issue.iid} and #{merge_request.project.full_path}!#{merge_request.iid}" } let!(:note) { create(:note, noteable: from_noteable, note: text, project: from_noteable.project) } it 'rewrites the references correctly' do execute_service new_note = to_noteable.notes.first expected_text = "See #{other_issue.project.path}##{other_issue.iid} and #{merge_request.project.full_path}!#{merge_request.iid}" aggregate_failures do expect(new_note.note).to eq(expected_text) expect(new_note.author).to eq(note.author) end end it 'does not copy rendered markdown from note_html' do execute_service new_note = to_noteable.notes.first expect(new_note.note_html).not_to eq(note.note_html) end end context 'notes with upload' do let(:uploader) { build(:file_uploader, project: from_noteable.project) } let(:text) { "Simple text with image: #{uploader.markdown_link} " } let!(:note) { create(:note, noteable: from_noteable, note: text, project: from_noteable.project) } it 'rewrites note content correctly' do execute_service new_note = to_noteable.notes.first aggregate_failures do expect(note.note).to match(/Simple text with image:/o) expect(FileUploader::MARKDOWN_PATTERN.match(note.note)).not_to be_nil expect(new_note.note).to match(/Simple text with image:/o) expect(FileUploader::MARKDOWN_PATTERN.match(new_note.note)).not_to be_nil expect(note.note).not_to eq(new_note.note) expect(note.note_html).not_to eq(new_note.note_html) end end it 'does not copy rendered markdown from note_html' do execute_service new_note = to_noteable.notes.first expect(new_note.note_html).not_to eq(note.note_html) end end context 'discussion notes' do let(:note) { create(:note, noteable: from_noteable, note: 'sample note', project: from_noteable.project) } let!(:discussion) { create(:discussion_note_on_issue, in_reply_to: note, note: 'reply to sample note') } it 'rewrites discussion correctly' do execute_service aggregate_failures do expect(to_noteable.notes.count).to eq(from_noteable.notes.count) expect(to_noteable.notes.where(discussion_id: discussion.discussion_id).count).to eq(0) expect(from_noteable.notes.where(discussion_id: discussion.discussion_id).count).to eq(1) end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notes class PostProcessService attr_accessor :note def initialize(note) @note = note end def execute # Skip system notes, like status changes and cross-references and awards unless note.system? EventCreateService.new.leave_note(note, note.author) return if note.for_personal_snippet? note.create_cross_references! ::SystemNoteService.design_discussion_added(note) if create_design_discussion_system_note? execute_note_hooks end end private def create_design_discussion_system_note? note && note.for_design? && note.start_of_discussion? end def hook_data Gitlab::DataBuilder::Note.build(note, note.author) end def execute_note_hooks return unless note.project note_data = hook_data is_confidential = note.confidential?(include_noteable: true) hooks_scope = is_confidential ? :confidential_note_hooks : :note_hooks note.project.execute_hooks(note_data, hooks_scope) note.project.execute_integrations(note_data, hooks_scope) execute_group_mention_hooks(note, note_data, is_confidential) end def execute_group_mention_hooks(note, note_data, is_confidential) Integrations::GroupMentionService.new(note, hook_data: note_data, is_confidential: is_confidential).execute end end end Notes::PostProcessService.prepend_mod_with('Notes::PostProcessService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::PostProcessService, feature_category: :team_planning do let(:project) { create(:project) } let(:issue) { create(:issue, project: project) } let(:user) { create(:user) } describe '#execute' do before do project.add_maintainer(user) note_opts = { note: 'Awesome comment', noteable_type: 'Issue', noteable_id: issue.id } @note = Notes::CreateService.new(project, user, note_opts).execute end it do expect(project).to receive(:execute_hooks) expect(project).to receive(:execute_integrations) expect_next_instance_of(Integrations::GroupMentionService) do |group_mention_service| expect(group_mention_service).to receive(:execute) end described_class.new(@note).execute end context 'with a confidential issue' do let(:issue) { create(:issue, :confidential, project: project) } it "doesn't call note hooks/integrations" do expect(project).not_to receive(:execute_hooks).with(anything, :note_hooks) expect(project).not_to receive(:execute_integrations).with(anything, :note_hooks) described_class.new(@note).execute end it "calls confidential-note hooks/integrations" do expect(project).to receive(:execute_hooks).with(anything, :confidential_note_hooks) expect(project).to receive(:execute_integrations).with(anything, :confidential_note_hooks) described_class.new(@note).execute end end context 'when the noteable is a design' do let_it_be(:noteable) { create(:design, :with_file) } let_it_be(:discussion_note) { create_note } subject { described_class.new(note).execute } def create_note(in_reply_to: nil) create(:diff_note_on_design, noteable: noteable, in_reply_to: in_reply_to) end context 'when the note is the start of a new discussion' do let(:note) { discussion_note } it 'creates a new system note' do expect { subject }.to change { Note.system.count }.by(1) end end context 'when the note is a reply within a discussion' do let_it_be(:note) { create_note(in_reply_to: discussion_note) } it 'does not create a new system note' do expect { subject }.not_to change { Note.system.count } end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # QuickActionsService class # # Executes quick actions commands extracted from note text # # Most commands returns parameters to be applied later # using QuickActionService#apply_updates # module Notes class QuickActionsService < BaseService attr_reader :interpret_service delegate :commands_executed_count, to: :interpret_service, allow_nil: true SUPPORTED_NOTEABLES = %w[WorkItem Issue MergeRequest Commit].freeze private_constant :SUPPORTED_NOTEABLES def self.supported_noteables SUPPORTED_NOTEABLES end def self.supported?(note) return true if note.for_work_item? supported_noteables.include? note.noteable_type end def supported?(note) self.class.supported?(note) end def execute(note, options = {}) return [note.note, {}] unless supported?(note) @interpret_service = QuickActions::InterpretService.new(project, current_user, options) interpret_service.execute(note.note, note.noteable) end # Applies updates extracted to note#noteable # The update parameters are extracted on self#execute def apply_updates(update_params, note) return if update_params.empty? return unless supported?(note) # We need the `id` after the note is persisted if update_params[:spend_time] update_params[:spend_time][:note_id] = note.id end execute_update_service(note, update_params) end private def execute_update_service(note, params) service_response = noteable_update_service(note, params).execute(note.noteable) service_errors = if service_response.respond_to?(:errors) service_response.errors.full_messages elsif service_response.respond_to?(:[]) && service_response[:status] == :error Array.wrap(service_response[:message]) end service_errors.blank? ? ServiceResponse.success : ServiceResponse.error(message: service_errors) end def noteable_update_service(note, update_params) if note.for_work_item? parsed_params = note.noteable.transform_quick_action_params(update_params) WorkItems::UpdateService.new( container: note.resource_parent, current_user: current_user, params: parsed_params[:common], widget_params: parsed_params[:widgets] ) elsif note.for_issue? Issues::UpdateService.new(container: note.resource_parent, current_user: current_user, params: update_params) elsif note.for_merge_request? MergeRequests::UpdateService.new( project: note.resource_parent, current_user: current_user, params: update_params ) elsif note.for_commit? Commits::TagService.new(note.resource_parent, current_user, update_params) end end end end Notes::QuickActionsService.prepend_mod_with('Notes::QuickActionsService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::QuickActionsService, feature_category: :team_planning do shared_context 'note on noteable' do let_it_be(:project) { create(:project, :repository) } let_it_be(:maintainer) { create(:user).tap { |u| project.add_maintainer(u) } } let_it_be(:assignee) { create(:user) } before do project.add_maintainer(assignee) end end shared_examples 'note on noteable that supports quick actions' do include_context 'note on noteable' before do note.note = note_text end let!(:milestone) { create(:milestone, project: project) } let!(:labels) { create_pair(:label, project: project) } describe 'note with only command' do describe '/close, /label, /assign & /milestone' do let(:note_text) do %(/close\n/label ~#{labels.first.name} ~#{labels.last.name}\n/assign @#{assignee.username}\n/milestone %"#{milestone.name}") end it 'closes noteable, sets labels, assigns, and sets milestone to noteable, and leave no note' do content = execute(note) expect(content).to be_empty expect(note.noteable).to be_closed expect(note.noteable.labels).to match_array(labels) expect(note.noteable.assignees).to eq([assignee]) expect(note.noteable.milestone).to eq(milestone) end end context '/relate' do let_it_be(:issue) { create(:issue, project: project) } let_it_be(:other_issue) { create(:issue, project: project) } let(:note_text) { "/relate #{other_issue.to_reference}" } let(:note) { create(:note_on_issue, noteable: issue, project: project, note: note_text) } context 'user cannot relate issues', :sidekiq_inline do before do project.team.find_member(maintainer.id).destroy! project.update!(visibility: Gitlab::VisibilityLevel::PUBLIC) end it 'does not create issue relation' do expect { execute(note) }.not_to change { IssueLink.count } end end context 'user is allowed to relate issues' do it 'creates issue relation' do expect { execute(note) }.to change { IssueLink.count }.by(1) end end end describe '/reopen' do before do note.noteable.close! expect(note.noteable).to be_closed end let(:note_text) { '/reopen' } it 'opens the noteable, and leave no note' do content = execute(note) expect(content).to be_empty expect(note.noteable).to be_open end end describe '/spend' do context 'when note is not persisted' do let(:note_text) { '/spend 1h' } it 'adds time to noteable, adds timelog with nil note_id and has no content' do content = execute(note) expect(content).to be_empty expect(note.noteable.time_spent).to eq(3600) expect(Timelog.last.note_id).to be_nil end end context 'when note is persisted' do let(:note_text) { "a note \n/spend 1h" } it 'updates the spent time and populates timelog with note_id' do new_content, update_params = service.execute(note) note.update!(note: new_content) service.apply_updates(update_params, note) expect(Timelog.last.note_id).to eq(note.id) end end context 'adds a system note' do context 'when not specifying a date' do let(:note_text) { "/spend 1h" } it 'does not include the date' do _, update_params = service.execute(note) service.apply_updates(update_params, note) expect(Note.last.note).to eq('added 1h of time spent') end end context 'when specifying a date' do let(:note_text) { "/spend 1h 2020-01-01" } it 'does include the date' do _, update_params = service.execute(note) service.apply_updates(update_params, note) expect(Note.last.note).to eq('added 1h of time spent at 2020-01-01') end end end end end describe '/estimate' do before do # reset to 10 minutes before each test note.noteable.update!(time_estimate: 600) end shared_examples 'does not update time_estimate and displays the correct error message' do it 'shows validation error message' do content = execute(note) expect(content).to be_empty expect(note.noteable.errors[:time_estimate]).to include('must have a valid format and be greater than or equal to zero.') expect(note.noteable.reload.time_estimate).to eq(600) end end context 'when the time estimate is valid' do let(:note_text) { '/estimate 1h' } it 'adds time estimate to noteable' do content = execute(note) expect(content).to be_empty expect(note.noteable.reload.time_estimate).to eq(3600) end end context 'when the time estimate is 0' do let(:note_text) { '/estimate 0' } it 'adds time estimate to noteable' do content = execute(note) expect(content).to be_empty expect(note.noteable.reload.time_estimate).to eq(0) end end context 'when the time estimate is invalid' do let(:note_text) { '/estimate a' } include_examples "does not update time_estimate and displays the correct error message" end context 'when the time estimate is partially invalid' do let(:note_text) { '/estimate 1d 3id' } include_examples "does not update time_estimate and displays the correct error message" end context 'when the time estimate is negative' do let(:note_text) { '/estimate -1h' } include_examples "does not update time_estimate and displays the correct error message" end end describe '/confidential' do let_it_be_with_reload(:noteable) { create(:work_item, :issue, project: project) } let_it_be(:note_text) { '/confidential' } let_it_be(:note) { create(:note, noteable: noteable, project: project, note: note_text) } context 'when work item does not have children' do it 'leaves the note empty' do expect(execute(note)).to be_empty end it 'marks work item as confidential' do expect { execute(note) }.to change { noteable.reload.confidential }.from(false).to(true) end end context 'when work item has children' do before do create(:parent_link, work_item: task, work_item_parent: noteable) end context 'when children are not confidential' do let(:task) { create(:work_item, :task, project: project) } it 'does not mark parent work item as confidential' do expect { execute(note) }.to not_change { noteable.reload.confidential }.from(false) expect(noteable.errors[:base]).to include('A confidential work item cannot have a parent that already has non-confidential children.') end end context 'when children are confidential' do let(:task) { create(:work_item, :confidential, :task, project: project) } it 'marks parent work item as confidential' do expect { execute(note) }.to change { noteable.reload.confidential }.from(false).to(true) end end end end describe 'note with command & text' do describe '/close, /label, /assign & /milestone' do let(:note_text) do %(HELLO\n/close\n/label ~#{labels.first.name} ~#{labels.last.name}\n/assign @#{assignee.username}\n/milestone %"#{milestone.name}"\nWORLD) end it 'closes noteable, sets labels, assigns, and sets milestone to noteable' do content = execute(note) expect(content).to eq "HELLO\nWORLD" expect(note.noteable).to be_closed expect(note.noteable.labels).to match_array(labels) expect(note.noteable.assignees).to eq([assignee]) expect(note.noteable.milestone).to eq(milestone) end end describe '/reopen' do before do note.noteable.close expect(note.noteable).to be_closed end let(:note_text) { "HELLO\n/reopen\nWORLD" } it 'opens the noteable' do content = execute(note) expect(content).to eq "HELLO\nWORLD" expect(note.noteable).to be_open end end end describe '/milestone' do let(:issue) { create(:issue, project: project) } let(:note_text) { %(/milestone %"#{milestone.name}") } let(:note) { create(:note_on_issue, noteable: issue, project: project, note: note_text) } context 'on an incident' do before do issue.update!(work_item_type: WorkItems::Type.default_by_type(:incident)) end it 'leaves the note empty' do expect(execute(note)).to be_empty end it 'assigns the milestone' do expect { execute(note) }.to change { issue.reload.milestone }.from(nil).to(milestone) end end context 'on a merge request' do let(:note_mr) { create(:note_on_merge_request, project: project, note: note_text) } it 'leaves the note empty' do expect(execute(note_mr)).to be_empty end it 'assigns the milestone' do expect { execute(note) }.to change { issue.reload.milestone }.from(nil).to(milestone) end end end describe '/remove_milestone' do let(:issue) { create(:issue, project: project, milestone: milestone) } let(:note_text) { '/remove_milestone' } let(:note) { create(:note_on_issue, noteable: issue, project: project, note: note_text) } context 'on an issue' do it 'leaves the note empty' do expect(execute(note)).to be_empty end it 'removes the milestone' do expect { execute(note) }.to change { issue.reload.milestone }.from(milestone).to(nil) end end context 'on an incident' do before do issue.update!(work_item_type: WorkItems::Type.default_by_type(:incident)) end it 'leaves the note empty' do expect(execute(note)).to be_empty end it 'removes the milestone' do expect { execute(note) }.to change { issue.reload.milestone }.from(milestone).to(nil) end end context 'on a merge request' do let(:note_mr) { create(:note_on_merge_request, project: project, note: note_text) } it 'leaves the note empty' do expect(execute(note_mr)).to be_empty end it 'removes the milestone' do expect { execute(note) }.to change { issue.reload.milestone }.from(milestone).to(nil) end end end describe '/add_child' do let_it_be_with_reload(:noteable) { create(:work_item, :objective, project: project) } let_it_be_with_reload(:child) { create(:work_item, :objective, project: project) } let_it_be_with_reload(:second_child) { create(:work_item, :objective, project: project) } let_it_be(:note_text) { "/add_child #{child.to_reference}, #{second_child.to_reference}" } let_it_be(:note) { create(:note, noteable: noteable, project: project, note: note_text) } let_it_be(:children) { [child, second_child] } shared_examples 'adds child work items' do it 'leaves the note empty' do expect(execute(note)).to be_empty end it 'adds child work items' do execute(note) expect(noteable.valid?).to be_truthy expect(noteable.work_item_children).to eq(children) end end context 'when using work item reference' do let_it_be(:note_text) { "/add_child #{child.to_reference(full: true)},#{second_child.to_reference(full: true)}" } it_behaves_like 'adds child work items' end context 'when using work item iid' do it_behaves_like 'adds child work items' end context 'when using work item URL' do let_it_be(:project_path) { "#{Gitlab.config.gitlab.url}/#{project.full_path}" } let_it_be(:url) { "#{project_path}/work_items/#{child.iid},#{project_path}/work_items/#{second_child.iid}" } let_it_be(:note_text) { "/add_child #{url}" } it_behaves_like 'adds child work items' end end describe '/set_parent' do let_it_be_with_reload(:noteable) { create(:work_item, :objective, project: project) } let_it_be_with_reload(:parent) { create(:work_item, :objective, project: project) } let_it_be(:note_text) { "/set_parent #{parent.to_reference}" } let_it_be(:note) { create(:note, noteable: noteable, project: project, note: note_text) } shared_examples 'sets work item parent' do it 'leaves the note empty' do expect(execute(note)).to be_empty end it 'sets work item parent' do execute(note) expect(parent.valid?).to be_truthy expect(noteable.work_item_parent).to eq(parent) end end context 'when using work item reference' do let_it_be(:note_text) { "/set_parent #{project.full_path}#{parent.to_reference}" } it_behaves_like 'sets work item parent' end context 'when using work item iid' do let_it_be(:note_text) { "/set_parent #{parent.to_reference}" } it_behaves_like 'sets work item parent' end context 'when using work item URL' do let_it_be(:url) { "#{Gitlab.config.gitlab.url}/#{project.full_path}/work_items/#{parent.iid}" } let_it_be(:note_text) { "/set_parent #{url}" } it_behaves_like 'sets work item parent' end end describe '/promote_to' do shared_examples 'promotes work item' do |from:, to:| it 'leaves the note empty' do expect(execute(note)).to be_empty end it 'promotes to provided type' do expect { execute(note) }.to change { noteable.work_item_type.base_type }.from(from).to(to) end end context 'on a task' do let_it_be_with_reload(:noteable) { create(:work_item, :task, project: project) } let_it_be(:note_text) { '/promote_to Issue' } let_it_be(:note) { create(:note, noteable: noteable, project: project, note: note_text) } it_behaves_like 'promotes work item', from: 'task', to: 'issue' context 'when type name is lower case' do let_it_be(:note_text) { '/promote_to issue' } it_behaves_like 'promotes work item', from: 'task', to: 'issue' end end context 'on an issue' do let_it_be_with_reload(:noteable) { create(:work_item, :issue, project: project) } let_it_be(:note_text) { '/promote_to Incident' } let_it_be(:note) { create(:note, noteable: noteable, project: project, note: note_text) } it_behaves_like 'promotes work item', from: 'issue', to: 'incident' context 'when type name is lower case' do let_it_be(:note_text) { '/promote_to incident' } it_behaves_like 'promotes work item', from: 'issue', to: 'incident' end end end end describe '.supported?' do include_context 'note on noteable' let(:note) { create(:note_on_issue, project: project) } context 'with a note on an issue' do it 'returns true' do expect(described_class.supported?(note)).to be_truthy end end context 'with a note on a commit' do let(:note) { create(:note_on_commit, project: project) } it 'returns false' do expect(described_class.supported?(note)).to be_truthy end end end describe '#supported?' do include_context 'note on noteable' it 'delegates to the class method' do service = described_class.new(project, maintainer) note = create(:note_on_issue, project: project) expect(described_class).to receive(:supported?).with(note) service.supported?(note) end end describe '#execute' do let(:service) { described_class.new(project, maintainer) } it_behaves_like 'note on noteable that supports quick actions' do let_it_be(:issue, reload: true) { create(:issue, project: project) } let(:note) { build(:note_on_issue, project: project, noteable: issue) } end it_behaves_like 'note on noteable that supports quick actions' do let_it_be(:incident, reload: true) { create(:incident, project: project) } let(:note) { build(:note_on_issue, project: project, noteable: incident) } end it_behaves_like 'note on noteable that supports quick actions' do let(:merge_request) { create(:merge_request, source_project: project) } let(:note) { build(:note_on_merge_request, project: project, noteable: merge_request) } end context 'note on work item that supports quick actions' do include_context 'note on noteable' let_it_be(:work_item, reload: true) { create(:work_item, project: project) } let(:note) { build(:note_on_work_item, project: project, noteable: work_item) } let!(:labels) { create_pair(:label, project: project) } before do note.note = note_text end describe 'note with only command' do describe '/close, /label & /assign' do let(:note_text) do %(/close\n/label ~#{labels.first.name} ~#{labels.last.name}\n/assign @#{assignee.username}\n) end it 'closes noteable, sets labels, assigns and leave no note' do content = execute(note) expect(content).to be_empty expect(note.noteable).to be_closed expect(note.noteable.labels).to match_array(labels) expect(note.noteable.assignees).to eq([assignee]) end end describe '/reopen' do before do note.noteable.close! expect(note.noteable).to be_closed end let(:note_text) { '/reopen' } it 'opens the noteable, and leave no note' do content = execute(note) expect(content).to be_empty expect(note.noteable).to be_open end end end describe 'note with command & text' do describe '/close, /label, /assign' do let(:note_text) do %(HELLO\n/close\n/label ~#{labels.first.name} ~#{labels.last.name}\n/assign @#{assignee.username}\nWORLD) end it 'closes noteable, sets labels, assigns, and sets milestone to noteable' do content = execute(note) expect(content).to eq "HELLO\nWORLD" expect(note.noteable).to be_closed expect(note.noteable.labels).to match_array(labels) expect(note.noteable.assignees).to eq([assignee]) end end describe '/reopen' do before do note.noteable.close expect(note.noteable).to be_closed end let(:note_text) { "HELLO\n/reopen\nWORLD" } it 'opens the noteable' do content = execute(note) expect(content).to eq "HELLO\nWORLD" expect(note.noteable).to be_open end end end end end describe '#apply_updates' do include_context 'note on noteable' let_it_be(:issue) { create(:issue, project: project) } let_it_be(:work_item, reload: true) { create(:work_item, :issue, project: project) } let_it_be(:merge_request) { create(:merge_request, source_project: project) } let_it_be(:issue_note) { create(:note_on_issue, project: project, noteable: issue) } let_it_be(:work_item_note) { create(:note, project: project, noteable: work_item) } let_it_be(:mr_note) { create(:note_on_merge_request, project: project, noteable: merge_request) } let_it_be(:commit_note) { create(:note_on_commit, project: project) } let(:update_params) { {} } subject(:apply_updates) { described_class.new(project, maintainer).apply_updates(update_params, note) } context 'with a note on an issue' do let(:note) { issue_note } it 'returns successful service response if update returned no errors' do update_params[:confidential] = true expect(apply_updates.success?).to be true end it 'returns service response with errors if update failed' do update_params[:title] = "" expect(apply_updates.success?).to be false expect(apply_updates.message).to include("Title can't be blank") end end context 'with a note on a merge request' do let(:note) { mr_note } it 'returns successful service response if update returned no errors' do update_params[:title] = 'New title' expect(apply_updates.success?).to be true end it 'returns service response with errors if update failed' do update_params[:title] = "" expect(apply_updates.success?).to be false expect(apply_updates.message).to include("Title can't be blank") end end context 'with a note on a work item' do let(:note) { work_item_note } before do update_params[:confidential] = true end it 'returns successful service response if update returned no errors' do expect(apply_updates.success?).to be true end it 'returns service response with errors if update failed' do task = create(:work_item, :task, project: project) create(:parent_link, work_item: task, work_item_parent: work_item) expect(apply_updates.success?).to be false expect(apply_updates.message) .to include("A confidential work item cannot have a parent that already has non-confidential children.") end end context 'with a note on a commit' do let(:note) { commit_note } it 'returns successful service response if update returned no errors' do update_params[:tag_name] = 'test' expect(apply_updates.success?).to be true end it 'returns service response with errors if update failed' do update_params[:tag_name] = '-test' expect(apply_updates.success?).to be false expect(apply_updates.message).to include('Tag name invalid') end end end context 'CE restriction for issue assignees' do describe '/assign' do let(:project) { create(:project) } let(:assignee) { create(:user) } let(:maintainer) { create(:user) } let(:service) { described_class.new(project, maintainer) } let(:note) { create(:note_on_issue, note: note_text, project: project) } let(:note_text) do %(/assign @#{assignee.username} @#{maintainer.username}\n") end before do stub_licensed_features(multiple_issue_assignees: false) project.add_maintainer(maintainer) project.add_maintainer(assignee) end it 'adds only one assignee from the list' do execute(note) expect(note.noteable.assignees.count).to eq(1) end end end def execute(note) content, update_params = service.execute(note) service.apply_updates(update_params, note) content end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notes class BuildService < ::BaseService def execute in_reply_to_discussion_id = params.delete(:in_reply_to_discussion_id) external_author = params.delete(:external_author) discussion = nil if external_author.present? note_metadata = Notes::NoteMetadata.new(email_participant: external_author) params[:note_metadata] = note_metadata end if in_reply_to_discussion_id.present? discussion = find_discussion(in_reply_to_discussion_id) return discussion_not_found unless discussion && can?(current_user, :create_note, discussion.noteable) discussion = discussion.convert_to_discussion! if discussion.can_convert_to_discussion? params.merge!(discussion.reply_attributes) end # The `confidential` param for notes is deprecated with 15.3 # and renamed to `internal`. # We still accept `confidential` until the param gets removed from the API. # Until we have not migrated the database column to `internal` we need to rename # the parameter. Issue: https://gitlab.com/gitlab-org/gitlab/-/issues/367923. params[:confidential] = params[:internal] || params[:confidential] params.delete(:internal) new_note(params, discussion) end private def new_note(params, discussion) note = Note.new(params) note.project = project note.author = current_user parent_confidential = discussion&.confidential? can_set_confidential = can?(current_user, :mark_note_as_internal, note) return discussion_not_found if parent_confidential && !can_set_confidential note.confidential = (parent_confidential.nil? && can_set_confidential ? params.delete(:confidential) : parent_confidential) note.resolve_without_save(current_user) if discussion&.resolved? note end def find_discussion(discussion_id) if project project.notes.find_discussion(discussion_id) else Note.find_discussion(discussion_id) end end def discussion_not_found note = Note.new note.errors.add(:base, _('Discussion to reply to cannot be found')) note end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::BuildService, feature_category: :team_planning do include AdminModeHelper let_it_be(:project) { create(:project, :repository) } let_it_be(:note) { create(:discussion_note_on_issue, project: project) } let_it_be(:author) { note.author } let_it_be(:user) { author } let_it_be(:noteable_author) { create(:user) } let_it_be(:other_user) { create(:user) } let_it_be(:external) { create(:user, :external) } let(:base_params) { { note: 'Test' } } let(:params) { {} } subject(:new_note) { described_class.new(project, user, base_params.merge(params)).execute } describe '#execute' do context 'when in_reply_to_discussion_id is specified' do let(:params) { { in_reply_to_discussion_id: note.discussion_id } } context 'when a note with that original discussion ID exists' do it 'sets the note up to be in reply to that note' do expect(new_note).to be_valid expect(new_note.in_reply_to?(note)).to be_truthy expect(new_note.resolved?).to be_falsey end context 'when discussion is resolved' do let_it_be(:merge_request) { create(:merge_request, source_project: project) } let_it_be(:mr_note) { create(:discussion_note_on_merge_request, :resolved, noteable: merge_request, project: project, author: author) } let(:params) { { in_reply_to_discussion_id: mr_note.discussion_id } } it 'resolves the note' do expect(new_note).to be_valid expect(new_note.resolved?).to be_truthy end end end context 'when a note with that discussion ID exists' do it 'sets the note up to be in reply to that note' do expect(new_note).to be_valid expect(new_note.in_reply_to?(note)).to be_truthy end end context 'when no note with that discussion ID exists' do let(:params) { { in_reply_to_discussion_id: 'foo' } } it 'sets an error' do expect(new_note.errors[:base]).to include('Discussion to reply to cannot be found') end end context 'when user has no access to discussion' do let(:user) { other_user } it 'sets an error' do expect(new_note.errors[:base]).to include('Discussion to reply to cannot be found') end end context 'personal snippet note' do def reply(note, user = other_user) described_class.new( nil, user, note: 'Test', in_reply_to_discussion_id: note.discussion_id ).execute end let_it_be(:snippet_author) { noteable_author } context 'when a snippet is public' do it 'creates a reply note' do snippet = create(:personal_snippet, :public) note = create(:discussion_note_on_personal_snippet, noteable: snippet) new_note = reply(note) expect(new_note).to be_valid expect(new_note.in_reply_to?(note)).to be_truthy end end context 'when a snippet is private' do let_it_be(:snippet) { create(:personal_snippet, :private, author: snippet_author) } let_it_be(:note) { create(:discussion_note_on_personal_snippet, noteable: snippet) } it 'creates a reply note when the author replies' do new_note = reply(note, snippet_author) expect(new_note).to be_valid expect(new_note.in_reply_to?(note)).to be_truthy end it 'sets an error when another user replies' do new_note = reply(note) expect(new_note.errors[:base]).to include('Discussion to reply to cannot be found') end end context 'when a snippet is internal' do let_it_be(:snippet) { create(:personal_snippet, :internal, author: snippet_author) } let_it_be(:note) { create(:discussion_note_on_personal_snippet, noteable: snippet) } it 'creates a reply note when the author replies' do new_note = reply(note, snippet_author) expect(new_note).to be_valid expect(new_note.in_reply_to?(note)).to be_truthy end it 'creates a reply note when a regular user replies' do new_note = reply(note) expect(new_note).to be_valid expect(new_note.in_reply_to?(note)).to be_truthy end it 'sets an error when an external user replies' do new_note = reply(note, external) expect(new_note.errors[:base]).to include('Discussion to reply to cannot be found') end end end end context 'when replying to individual note' do let_it_be(:note) { create(:note_on_issue, project: project) } let(:params) { { in_reply_to_discussion_id: note.discussion_id } } it 'sets the note up to be in reply to that note' do expect(new_note).to be_valid expect(new_note).to be_a(DiscussionNote) expect(new_note.discussion_id).to eq(note.discussion_id) end context 'when noteable does not support replies' do let_it_be(:note) { create(:note_on_commit, project: project) } it 'builds another individual note' do expect(new_note).to be_valid expect(new_note).to be_a(Note) expect(new_note.discussion_id).not_to eq(note.discussion_id) end end end context 'confidential comments' do let_it_be(:project) { create(:project, :public) } let_it_be(:guest) { create(:user) } let_it_be(:reporter) { create(:user) } let_it_be(:admin) { create(:admin) } let_it_be(:issuable_assignee) { other_user } let_it_be(:issue) do create(:issue, project: project, author: noteable_author, assignees: [issuable_assignee]) end before do project.add_guest(guest) project.add_reporter(reporter) end context 'when creating a new confidential comment' do let(:params) { { internal: true, noteable: issue } } shared_examples 'user allowed to set comment as confidential' do it { expect(new_note.confidential).to be_truthy } end shared_examples 'user not allowed to set comment as confidential' do it { expect(new_note.confidential).to be_falsey } end context 'reporter' do let(:user) { reporter } it_behaves_like 'user allowed to set comment as confidential' end context 'issuable author' do let(:user) { noteable_author } it_behaves_like 'user not allowed to set comment as confidential' end context 'issuable assignee' do let(:user) { issuable_assignee } it_behaves_like 'user not allowed to set comment as confidential' end context 'admin' do before do enable_admin_mode!(admin) end let(:user) { admin } it_behaves_like 'user allowed to set comment as confidential' end context 'external' do let(:user) { external } it_behaves_like 'user not allowed to set comment as confidential' end context 'guest' do let(:user) { guest } it_behaves_like 'user not allowed to set comment as confidential' end context 'when using the deprecated `confidential` parameter' do let(:params) { { internal: true, noteable: issue } } shared_examples 'user allowed to set comment as confidential' do it { expect(new_note.confidential).to be_truthy } end end end context 'when replying to a confidential comment' do let_it_be(:note) { create(:note_on_issue, confidential: true, noteable: issue, project: project) } let(:params) { { in_reply_to_discussion_id: note.discussion_id, confidential: false } } shared_examples 'returns `Discussion to reply to cannot be found` error' do it do expect(new_note.errors.added?(:base, "Discussion to reply to cannot be found")).to be true end end shared_examples 'confidential set to `true`' do it '`confidential` param is ignored to match the parent note confidentiality' do expect(new_note.confidential).to be_truthy end end context 'with reporter access' do let(:user) { reporter } it_behaves_like 'confidential set to `true`' end context 'with admin access' do let(:user) { admin } before do enable_admin_mode!(admin) end it_behaves_like 'confidential set to `true`' end context 'with noteable author' do let(:user) { note.noteable.author } it_behaves_like 'returns `Discussion to reply to cannot be found` error' end context 'with noteable assignee' do let(:user) { issuable_assignee } it_behaves_like 'returns `Discussion to reply to cannot be found` error' end context 'with guest access' do let(:user) { guest } it_behaves_like 'returns `Discussion to reply to cannot be found` error' end context 'with external user' do let(:user) { external } it_behaves_like 'returns `Discussion to reply to cannot be found` error' end end context 'when replying to a public comment' do let_it_be(:note) { create(:note_on_issue, confidential: false, noteable: issue, project: project) } let(:params) { { in_reply_to_discussion_id: note.discussion_id, confidential: true } } it '`confidential` param is ignored and set to `false`' do expect(new_note.confidential).to be_falsey end end end context 'when noteable is not set' do let(:params) { { noteable_type: note.noteable_type, noteable_id: note.noteable_id } } it 'builds a note without saving it' do expect(new_note).to be_valid expect(new_note).not_to be_persisted end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notes class DestroyService < ::Notes::BaseService def execute(note) TodoService.new.destroy_target(note) do |note| note.destroy end clear_noteable_diffs_cache(note) track_note_removal_usage_for_issues(note) if note.for_issue? track_note_removal_usage_for_merge_requests(note) if note.for_merge_request? track_note_removal_usage_for_design(note) if note.for_design? end private def track_note_removal_usage_for_issues(note) Gitlab::UsageDataCounters::IssueActivityUniqueCounter.track_issue_comment_removed_action( author: note.author, project: project ) end def track_note_removal_usage_for_merge_requests(note) Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter.track_remove_comment_action(note: note) end def track_note_removal_usage_for_design(note) Gitlab::UsageDataCounters::IssueActivityUniqueCounter.track_issue_design_comment_removed_action( author: note.author, project: project ) end end end Notes::DestroyService.prepend_mod_with('Notes::DestroyService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::DestroyService, feature_category: :team_planning do let_it_be(:project) { create(:project, :public) } let_it_be(:issue) { create(:issue, project: project) } let(:user) { issue.author } describe '#execute' do it 'deletes a note' do note = create(:note, project: project, noteable: issue) described_class.new(project, user).execute(note) expect(project.issues.find(issue.id).notes).not_to include(note) end it 'updates the todo counts for users with todos for the note' do note = create(:note, project: project, noteable: issue) create(:todo, note: note, target: issue, user: user, author: user, project: project) expect { described_class.new(project, user).execute(note) } .to change { user.todos_pending_count }.from(1).to(0) end describe 'comment removed event tracking', :snowplow do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_COMMENT_REMOVED } let(:note) { create(:note, project: project, noteable: issue) } let(:service_action) { described_class.new(project, user).execute(note) } it 'tracks issue comment removal usage data', :clean_gitlab_redis_shared_state do counter = Gitlab::UsageDataCounters::HLLRedisCounter expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_comment_removed_action) .with(author: user, project: project) .and_call_original expect do service_action end.to change { counter.unique_events(event_names: event, start_date: Date.today.beginning_of_week, end_date: 1.week.from_now) }.by(1) end it_behaves_like 'internal event tracking' do let(:namespace) { project.namespace } subject(:execute_service_action) { service_action } end end it 'tracks merge request usage data' do mr = create(:merge_request, source_project: project) note = create(:note, project: project, noteable: mr) expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter).to receive(:track_remove_comment_action).with(note: note) described_class.new(project, user).execute(note) end context 'in a merge request' do let_it_be(:repo_project) { create(:project, :repository) } let_it_be(:merge_request) do create(:merge_request, source_project: repo_project, target_project: repo_project) end let_it_be(:note) do create(:diff_note_on_merge_request, project: repo_project, noteable: merge_request) end it 'does not track issue comment removal usage data' do expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_comment_removed_action) described_class.new(repo_project, user).execute(note) end context 'noteable highlight cache clearing' do before do allow(note.position).to receive(:unfolded_diff?) { true } end it 'clears noteable diff cache when it was unfolded for the note position' do expect(merge_request).to receive_message_chain(:diffs, :clear_cache) described_class.new(repo_project, user).execute(note) end it 'does not clear cache when note is not the first of the discussion' do reply_note = create(:diff_note_on_merge_request, in_reply_to: note, project: repo_project, noteable: merge_request) expect(merge_request).not_to receive(:diffs) described_class.new(repo_project, user).execute(reply_note) end end end it 'tracks design comment removal' do note = create(:note_on_design, project: project) expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive( :track_issue_design_comment_removed_action ).with( author: note.author, project: project ) described_class.new(project, user).execute(note) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notes class UpdateService < BaseService def execute(note) return note unless note.editable? && params.present? old_mentioned_users = note.mentioned_users(current_user).to_a note.assign_attributes(params) return note unless note.valid? track_note_edit_usage_for_issues(note) if note.for_issue? track_note_edit_usage_for_merge_requests(note) if note.for_merge_request? only_commands = false quick_actions_service = QuickActionsService.new(project, current_user) if quick_actions_service.supported?(note) content, update_params, message = quick_actions_service.execute(note, {}) only_commands = content.empty? note.note = content end update_note(note, only_commands) note.save unless only_commands || note.for_personal_snippet? note.create_new_cross_references!(current_user) update_todos(note, old_mentioned_users) update_suggestions(note) end if quick_actions_service.commands_executed_count.to_i > 0 if update_params.present? quick_actions_service.apply_updates(update_params, note) note.commands_changes = update_params end if only_commands delete_note(note, message) else note.save end end note end private def update_note(note, only_commands) return unless note.note_changed? note.assign_attributes(last_edited_at: Time.current, updated_by: current_user) note.check_for_spam(action: :update, user: current_user) unless only_commands end def delete_note(note, message) # We must add the error after we call #save because errors are reset # when #save is called note.errors.add(:commands_only, message.presence || _('Commands did not apply')) # Allow consumers to detect problems applying commands note.errors.add(:commands, _('Commands did not apply')) unless message.present? Notes::DestroyService.new(project, current_user).execute(note) end def update_suggestions(note) return unless note.supports_suggestion? Suggestion.transaction do note.suggestions.delete_all Suggestions::CreateService.new(note).execute end # We need to refresh the previous suggestions call cache # in order to get the new records. note.reset end def update_todos(note, old_mentioned_users) return unless note.previous_changes.include?('note') TodoService.new.update_note(note, current_user, old_mentioned_users) end def track_note_edit_usage_for_issues(note) Gitlab::UsageDataCounters::IssueActivityUniqueCounter.track_issue_comment_edited_action( author: note.author, project: project ) end def track_note_edit_usage_for_merge_requests(note) Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter.track_edit_comment_action(note: note) end end end Notes::UpdateService.prepend_mod_with('Notes::UpdateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::UpdateService, feature_category: :team_planning do let(:group) { create(:group, :public) } let(:project) { create(:project, :public, group: group) } let(:private_group) { create(:group, :private) } let(:private_project) { create(:project, :private, group: private_group) } let(:user) { create(:user) } let(:user2) { create(:user) } let(:user3) { create(:user) } let(:issue) { create(:issue, project: project) } let(:issue2) { create(:issue, project: private_project) } let(:note) { create(:note, project: project, noteable: issue, author: user, note: "Old note #{user2.to_reference}") } let(:markdown) do <<-MARKDOWN.strip_heredoc ```suggestion foo ``` ```suggestion bar ``` MARKDOWN end before do project.add_maintainer(user) project.add_developer(user2) project.add_developer(user3) group.add_developer(user3) private_group.add_developer(user) private_group.add_developer(user2) private_project.add_developer(user3) end describe '#execute' do def update_note(opts) @note = Notes::UpdateService.new(project, user, opts).execute(note) @note.reload end it 'does not update the note when params is blank' do travel_to(1.day.from_now) do expect { update_note({}) }.not_to change { note.reload.updated_at } end end context 'when the note is invalid' do let(:edit_note_text) { { note: 'new text' } } before do allow(note).to receive(:valid?).and_return(false) end it 'does not update the note' do travel_to(1.day.from_now) do expect { update_note(edit_note_text) }.not_to change { note.reload.updated_at } end end it 'returns the note' do expect(update_note(edit_note_text)).to eq(note) end end describe 'event tracking', :snowplow do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_COMMENT_EDITED } it 'does not track usage data when params is blank' do expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_comment_edited_action) expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter).not_to receive(:track_edit_comment_action) update_note({}) end it_behaves_like 'internal event tracking' do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_COMMENT_EDITED } let(:namespace) { project.namespace } subject(:service_action) { update_note(note: 'new text') } end it 'tracks issue usage data', :clean_gitlab_redis_shared_state do counter = Gitlab::UsageDataCounters::HLLRedisCounter expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_comment_edited_action) .with(author: user, project: project) .and_call_original expect do update_note(note: 'new text') end.to change { counter.unique_events(event_names: event, start_date: Date.today.beginning_of_week, end_date: 1.week.from_now) }.by(1) end end context 'when note text was changed' do let!(:note) { create(:note, project: project, noteable: issue, author: user2, note: "Old note #{user3.to_reference}") } let(:edit_note_text) { update_note({ note: 'new text' }) } it 'update last_edited_at' do travel_to(1.day.from_now) do expect { edit_note_text }.to change { note.reload.last_edited_at } end end it 'update updated_by' do travel_to(1.day.from_now) do expect { edit_note_text }.to change { note.reload.updated_by } end end it 'checks for spam' do expect(note).to receive(:check_for_spam).with(action: :update, user: user) edit_note_text end context 'when quick action only update' do it "delete note and return commands_only error" do updated_note = described_class.new(project, user, { note: "/close\n" }).execute(note) expect(updated_note.destroyed?).to eq(true) expect(updated_note.errors).to match_array([ "Note can't be blank", "Commands only Closed this issue." ]) end end end context 'when note text was not changed' do let!(:note) { create(:note, project: project, noteable: issue, author: user2, note: "Old note #{user3.to_reference}") } let(:does_not_edit_note_text) { update_note({}) } it 'does not update last_edited_at' do travel_to(1.day.from_now) do expect { does_not_edit_note_text }.not_to change { note.reload.last_edited_at } end end it 'does not update updated_by' do travel_to(1.day.from_now) do expect { does_not_edit_note_text }.not_to change { note.reload.updated_by } end end it 'does not check for spam' do expect(note).not_to receive(:check_for_spam) does_not_edit_note_text end end context 'when the notable is a merge request' do let(:merge_request) { create(:merge_request, source_project: project) } let(:note) { create(:note, project: project, noteable: merge_request, author: user, note: "Old note #{user2.to_reference}") } it 'tracks merge request usage data' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter).to receive(:track_edit_comment_action).with(note: note) update_note(note: 'new text') end end context 'with system note' do before do note.update_column(:system, true) end it 'does not update the note' do expect { update_note(note: 'new text') }.not_to change { note.reload.note } end it 'does not track usage data' do expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_comment_edited_action) update_note(note: 'new text') end end context 'suggestions' do it 'refreshes note suggestions' do suggestion = create(:suggestion) note = suggestion.note expect { described_class.new(project, user, note: markdown).execute(note) } .to change { note.suggestions.count }.from(1).to(2) expect(note.suggestions.order(:relative_order).map(&:to_content)) .to eq([" foo\n", " bar\n"]) end end context 'todos' do shared_examples 'does not update todos' do it 'keep todos' do expect(todo.reload).to be_pending end it 'does not create any new todos' do expect(Todo.count).to eq(1) end end shared_examples 'creates one todo' do it 'marks todos as done' do expect(todo.reload).to be_done end it 'creates only 1 new todo' do expect(Todo.count).to eq(2) end end context 'when note includes a user mention' do let!(:todo) { create(:todo, :assigned, user: user, project: project, target: issue, author: user2) } context 'when the note does not change mentions' do before do update_note({ note: "Old note #{user2.to_reference}" }) end it_behaves_like 'does not update todos' end context 'when the note changes to include one more user mention' do before do update_note({ note: "New note #{user2.to_reference} #{user3.to_reference}" }) end it_behaves_like 'creates one todo' end context 'when the note changes to include a group mentions' do before do update_note({ note: "New note #{private_group.to_reference}" }) end it_behaves_like 'creates one todo' end end context 'when note includes a group mention' do context 'when the group is public' do let(:note) { create(:note, project: project, noteable: issue, author: user, note: "Old note #{group.to_reference}") } let!(:todo) { create(:todo, :assigned, user: user, project: project, target: issue, author: user2) } context 'when the note does not change mentions' do before do update_note({ note: "Old note #{group.to_reference}" }) end it_behaves_like 'does not update todos' end context 'when the note changes mentions' do before do update_note({ note: "New note #{user2.to_reference} #{user3.to_reference}" }) end it_behaves_like 'creates one todo' end end context 'when the group is private' do let(:note) { create(:note, project: project, noteable: issue, author: user, note: "Old note #{private_group.to_reference}") } let!(:todo) { create(:todo, :assigned, user: user, project: project, target: issue, author: user2) } context 'when the note does not change mentions' do before do update_note({ note: "Old note #{private_group.to_reference}" }) end it_behaves_like 'does not update todos' end context 'when the note changes mentions' do before do update_note({ note: "New note #{user2.to_reference} #{user3.to_reference}" }) end it_behaves_like 'creates one todo' end end end end context 'for a personal snippet' do let_it_be(:snippet) { create(:personal_snippet, :public) } let(:note) { create(:note, project: nil, noteable: snippet, author: user, note: "Note on a snippet with reference #{issue.to_reference}") } it 'does not create todos' do expect { update_note({ note: "Mentioning user #{user2}" }) }.not_to change { note.todos.count } end it 'does not create suggestions' do expect { update_note({ note: "Updated snippet with markdown suggestion #{markdown}" }) } .not_to change { note.suggestions.count } end it 'does not create mentions' do expect(note).not_to receive(:create_new_cross_references!) update_note({ note: "Updated with new reference: #{issue.to_reference}" }) end it 'does not track usage data' do expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_comment_edited_action) update_note(note: 'new text') end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notes class RenderService < BaseRenderer # Renders a collection of Note instances. # # notes - The notes to render. # # Possible options: # # requested_path - The request path. # project_wiki - The project's wiki. # ref - The current Git reference. # only_path - flag to turn relative paths into absolute ones. # xhtml - flag to save the html in XHTML def execute(notes, options = {}) Banzai::ObjectRenderer .new(user: current_user, redaction_context: options) .render(notes, :note) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::RenderService, feature_category: :team_planning do describe '#execute' do it 'renders a Note' do note = double(:note) wiki = double(:wiki) user = double(:user) expect(Banzai::ObjectRenderer) .to receive(:new) .with( user: user, redaction_context: { requested_path: 'foo', project_wiki: wiki, ref: 'bar', only_path: nil, xhtml: false } ) .and_call_original expect_any_instance_of(Banzai::ObjectRenderer) .to receive(:render) .with([note], :note) described_class.new(user).execute( [note], requested_path: 'foo', project_wiki: wiki, ref: 'bar', only_path: nil, xhtml: false ) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notes class CreateService < ::Notes::BaseService include IncidentManagement::UsageData def execute(skip_capture_diff_note_position: false, skip_merge_status_trigger: false, skip_set_reviewed: false) note = Notes::BuildService.new(project, current_user, params.except(:merge_request_diff_head_sha)).execute # n+1: https://gitlab.com/gitlab-org/gitlab-foss/issues/37440 note_valid = Gitlab::GitalyClient.allow_n_plus_1_calls do # We may set errors manually in Notes::BuildService for this reason # we also need to check for already existing errors. note.errors.empty? && note.valid? end return note unless note_valid # We execute commands (extracted from `params[:note]`) on the noteable # **before** we save the note because if the note consists of commands # only, there is no need be create a note! execute_quick_actions(note) do |only_commands| note.check_for_spam(action: :create, user: current_user) unless only_commands note.run_after_commit do # Finish the harder work in the background NewNoteWorker.perform_async(note.id) end note_saved = note.with_transaction_returning_status do break false if only_commands note.save.tap do update_discussions(note) end end if note_saved when_saved( note, skip_capture_diff_note_position: skip_capture_diff_note_position, skip_merge_status_trigger: skip_merge_status_trigger, skip_set_reviewed: skip_set_reviewed ) end end note end private def execute_quick_actions(note) return yield(false) unless quick_actions_supported?(note) content, update_params, message, command_names = quick_actions_service.execute(note, quick_action_options) only_commands = content.empty? note.note = content note.command_names = command_names yield(only_commands) do_commands(note, update_params, message, command_names, only_commands) end def quick_actions_supported?(note) quick_actions_service.supported?(note) end def quick_actions_service @quick_actions_service ||= QuickActionsService.new(project, current_user) end def update_discussions(note) # Ensure that individual notes that are promoted into discussions are # updated in a transaction with the note creation to avoid inconsistencies: # https://gitlab.com/gitlab-org/gitlab/-/issues/301237 if note.part_of_discussion? && note.discussion.can_convert_to_discussion? note.discussion.convert_to_discussion!.save note.clear_memoization(:discussion) end end def when_saved( note, skip_capture_diff_note_position: false, skip_merge_status_trigger: false, skip_set_reviewed: false) todo_service.new_note(note, current_user) clear_noteable_diffs_cache(note) Suggestions::CreateService.new(note).execute increment_usage_counter(note) track_event(note, current_user) if note.for_merge_request? && note.start_of_discussion? set_reviewed(note) unless skip_set_reviewed if !skip_capture_diff_note_position && note.diff_note? Discussions::CaptureDiffNotePositionService.new(note.noteable, note.diff_file&.paths).execute(note.discussion) end if !skip_merge_status_trigger && note.to_be_resolved? GraphqlTriggers.merge_request_merge_status_updated(note.noteable) end end end def do_commands(note, update_params, message, command_names, only_commands) return if quick_actions_service.commands_executed_count.to_i == 0 update_error = quick_actions_update_errors(note, update_params) if update_error note.errors.add(:validation, update_error) message = update_error end # We must add the error after we call #save because errors are reset # when #save is called if only_commands note.errors.add(:commands_only, message.presence || _('Failed to apply commands.')) note.errors.add(:command_names, command_names.flatten) # Allow consumers to detect problems applying commands note.errors.add(:commands, _('Failed to apply commands.')) unless message.present? end end def quick_actions_update_errors(note, params) return unless params.present? invalid_message = validate_commands(note, params) return invalid_message if invalid_message service_response = quick_actions_service.apply_updates(params, note) note.commands_changes = params return if service_response.success? service_response.message.join(', ') end def quick_action_options { merge_request_diff_head_sha: params[:merge_request_diff_head_sha], review_id: params[:review_id] } end def validate_commands(note, update_params) if invalid_reviewers?(update_params) "Reviewers #{note.noteable.class.max_number_of_assignees_or_reviewers_message}" elsif invalid_assignees?(update_params) "Assignees #{note.noteable.class.max_number_of_assignees_or_reviewers_message}" end end def invalid_reviewers?(update_params) if update_params.key?(:reviewer_ids) possible_reviewers = update_params[:reviewer_ids]&.uniq&.size possible_reviewers > ::Issuable::MAX_NUMBER_OF_ASSIGNEES_OR_REVIEWERS else false end end def invalid_assignees?(update_params) if update_params.key?(:assignee_ids) possible_assignees = update_params[:assignee_ids]&.uniq&.size possible_assignees > ::Issuable::MAX_NUMBER_OF_ASSIGNEES_OR_REVIEWERS else false end end def track_event(note, user) track_note_creation_usage_for_issues(note) if note.for_issue? track_note_creation_usage_for_merge_requests(note) if note.for_merge_request? track_incident_action(user, note.noteable, 'incident_comment') if note.for_issue? track_note_creation_in_ipynb(note) track_note_creation_visual_review(note) metric_key_path = 'counts.commit_comment' Gitlab::Tracking.event( 'Notes::CreateService', 'create_commit_comment', project: project, namespace: project&.namespace, user: user, label: metric_key_path, context: [Gitlab::Usage::MetricDefinition.context_for(metric_key_path).to_context] ) end def tracking_data_for(note) label = Gitlab.ee? && note.author == Users::Internal.visual_review_bot ? 'anonymous_visual_review_note' : 'note' { label: label, value: note.id } end def track_note_creation_usage_for_issues(note) Gitlab::UsageDataCounters::IssueActivityUniqueCounter.track_issue_comment_added_action( author: note.author, project: project ) end def track_note_creation_usage_for_merge_requests(note) Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter.track_create_comment_action(note: note) end def should_track_ipynb_notes?(note) note.respond_to?(:diff_file) && note.diff_file&.ipynb? end def track_note_creation_in_ipynb(note) return unless should_track_ipynb_notes?(note) Gitlab::UsageDataCounters::IpynbDiffActivityCounter.note_created(note) end def track_note_creation_visual_review(note) Gitlab::Tracking.event('Notes::CreateService', 'execute', **tracking_data_for(note)) end def set_reviewed(note) return if Feature.enabled?(:mr_request_changes, current_user) ::MergeRequests::UpdateReviewerStateService.new(project: project, current_user: current_user) .execute(note.noteable, "reviewed") end end end Notes::CreateService.prepend_mod_with('Notes::CreateService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Notes::CreateService, feature_category: :team_planning do let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, :repository, group: group) } let_it_be(:issue) { create(:issue, project: project) } let_it_be(:user) { create(:user) } let(:base_opts) { { note: 'Awesome comment', noteable_type: 'Issue', noteable_id: issue.id } } let(:opts) { base_opts.merge(confidential: true) } describe '#execute' do subject(:note) { described_class.new(project, user, opts).execute } before_all do group.add_maintainer(user) end context "valid params" do context 'when noteable is an issue that belongs directly to a group' do it 'creates a note without a project and correct namespace', :aggregate_failures do group_issue = create(:issue, :group_level, namespace: group) note_params = { note: 'test note', noteable: group_issue } expect do described_class.new(nil, user, note_params).execute end.to change { Note.count }.by(1) created_note = Note.last expect(created_note.namespace).to eq(group) expect(created_note.project).to be_nil end end context 'when noteable is a work item that belongs directly to a group' do it 'creates a note without a project and correct namespace', :aggregate_failures do group_work_item = create(:work_item, :group_level, namespace: group) note_params = { note: 'test note', noteable: group_work_item } expect do described_class.new(nil, user, note_params).execute end.to change { Note.count }.by(1) created_note = Note.last expect(created_note.namespace).to eq(group) expect(created_note.project).to be_nil end end it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { note } end it 'returns a valid note' do expect(note).to be_valid end it 'returns a persisted note' do expect(note).to be_persisted end it 'checks for spam' do expect_next_instance_of(Note) do |instance| expect(instance).to receive(:check_for_spam).with(action: :create, user: user) end note end it 'does not persist when spam' do expect_next_instance_of(Note) do |instance| expect(instance).to receive(:check_for_spam).with(action: :create, user: user) do instance.spam! end end expect(note).not_to be_persisted end context 'with internal parameter' do context 'when confidential' do let(:opts) { base_opts.merge(internal: true) } it 'returns a confidential note' do expect(note).to be_confidential end end context 'when not confidential' do let(:opts) { base_opts.merge(internal: false) } it 'returns a confidential note' do expect(note).not_to be_confidential end end end context 'with confidential parameter' do context 'when confidential' do let(:opts) { base_opts.merge(confidential: true) } it 'returns a confidential note' do expect(note).to be_confidential end end context 'when not confidential' do let(:opts) { base_opts.merge(confidential: false) } it 'returns a confidential note' do expect(note).not_to be_confidential end end end context 'with confidential and internal parameter set' do let(:opts) { base_opts.merge(internal: true, confidential: false) } it 'prefers the internal parameter' do expect(note).to be_confidential end end it 'note has valid content' do expect(note.note).to eq(opts[:note]) end it 'note belongs to the correct project' do expect(note.project).to eq(project) end it 'TodoService#new_note is called' do note = build(:note, project: project, noteable: issue) allow(Note).to receive(:new).with(opts) { note } expect_any_instance_of(TodoService).to receive(:new_note).with(note, user) described_class.new(project, user, opts).execute end it 'enqueues NewNoteWorker' do note = build(:note, id: non_existing_record_id, project: project, noteable: issue) allow(Note).to receive(:new).with(opts) { note } expect(NewNoteWorker).to receive(:perform_async).with(note.id) described_class.new(project, user, opts).execute end context 'issue is an incident' do let(:issue) { create(:incident, project: project) } it_behaves_like 'an incident management tracked event', :incident_management_incident_comment do let(:current_user) { user } end it_behaves_like 'Snowplow event tracking with RedisHLL context' do let(:namespace) { issue.namespace } let(:category) { described_class.to_s } let(:action) { 'incident_management_incident_comment' } let(:label) { 'redis_hll_counters.incident_management.incident_management_total_unique_counts_monthly' } end end context 'in a commit', :snowplow do let_it_be(:commit) { create(:commit, project: project) } let(:opts) { { note: 'Awesome comment', noteable_type: 'Commit', commit_id: commit.id } } let(:counter) { Gitlab::UsageDataCounters::NoteCounter } let(:execute_create_service) { described_class.new(project, user, opts).execute } it 'tracks commit comment usage data', :clean_gitlab_redis_shared_state do expect(counter).to receive(:count).with(:create, 'Commit').and_call_original expect do execute_create_service end.to change { counter.read(:create, 'Commit') }.by(1) end it_behaves_like 'Snowplow event tracking with Redis context' do let(:category) { described_class.name } let(:action) { 'create_commit_comment' } let(:label) { 'counts.commit_comment' } let(:namespace) { project.namespace } end end describe 'event tracking', :snowplow do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_COMMENT_ADDED } let(:execute_create_service) { described_class.new(project, user, opts).execute } it 'tracks issue comment usage data', :clean_gitlab_redis_shared_state do counter = Gitlab::UsageDataCounters::HLLRedisCounter expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_comment_added_action) .with(author: user, project: project) .and_call_original expect do execute_create_service end.to change { counter.unique_events(event_names: event, start_date: Date.today.beginning_of_week, end_date: 1.week.from_now) }.by(1) end it 'does not track merge request usage data' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter).not_to receive(:track_create_comment_action) execute_create_service end it_behaves_like 'internal event tracking' do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_COMMENT_ADDED } let(:namespace) { project.namespace } subject(:service_action) { execute_create_service } end end context 'in a merge request' do let_it_be(:project_with_repo) { create(:project, :repository) } let_it_be(:merge_request) do create(:merge_request, source_project: project_with_repo, target_project: project_with_repo) end let(:new_opts) { opts.merge(noteable_type: 'MergeRequest', noteable_id: merge_request.id) } context 'when mr_request_changes feature flag is disabled' do before do stub_feature_flags(mr_request_changes: false) end it 'calls MergeRequests::UpdateReviewerStateService service' do expect_next_instance_of( MergeRequests::UpdateReviewerStateService, project: project_with_repo, current_user: user ) do |service| expect(service).to receive(:execute).with(merge_request, "reviewed") end described_class.new(project_with_repo, user, new_opts).execute end it 'does not call MergeRequests::UpdateReviewerStateService service when skip_set_reviewed is true' do expect(MergeRequests::UpdateReviewerStateService).not_to receive(:new) described_class.new(project_with_repo, user, new_opts).execute(skip_set_reviewed: true) end end context 'when mr_request_changes feature flag is enabled' do it 'does not call MergeRequests::UpdateReviewerStateService service when skip_set_reviewed is true' do expect(MergeRequests::UpdateReviewerStateService).not_to receive(:new) described_class.new(project_with_repo, user, new_opts).execute(skip_set_reviewed: true) end end context 'noteable highlight cache clearing' do let(:position) do Gitlab::Diff::Position.new( old_path: "files/ruby/popen.rb", new_path: "files/ruby/popen.rb", old_line: nil, new_line: 14, diff_refs: merge_request.diff_refs ) end let(:new_opts) do opts.merge( in_reply_to_discussion_id: nil, type: 'DiffNote', noteable_type: 'MergeRequest', noteable_id: merge_request.id, position: position.to_h, confidential: false ) end before do allow_any_instance_of(Gitlab::Diff::Position) .to receive(:unfolded_diff?) { true } end it 'does not track issue comment usage data' do expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_comment_added_action) described_class.new(project_with_repo, user, new_opts).execute end it 'tracks merge request usage data' do expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter).to receive(:track_create_comment_action).with(note: kind_of(Note)) described_class.new(project_with_repo, user, new_opts).execute end it 'clears noteable diff cache when it was unfolded for the note position' do expect_any_instance_of(Gitlab::Diff::HighlightCache).to receive(:clear) described_class.new(project_with_repo, user, new_opts).execute end it 'does not clear cache when note is not the first of the discussion' do prev_note = create(:diff_note_on_merge_request, noteable: merge_request, project: project_with_repo) reply_opts = opts.merge( in_reply_to_discussion_id: prev_note.discussion_id, type: 'DiffNote', noteable_type: 'MergeRequest', noteable_id: merge_request.id, position: position.to_h, confidential: false ) expect(merge_request).not_to receive(:diffs) described_class.new(project_with_repo, user, reply_opts).execute end end context 'note diff file' do let(:line_number) { 14 } let(:position) do Gitlab::Diff::Position.new( old_path: "files/ruby/popen.rb", new_path: "files/ruby/popen.rb", old_line: nil, new_line: line_number, diff_refs: merge_request.diff_refs ) end let(:previous_note) do create(:diff_note_on_merge_request, noteable: merge_request, project: project_with_repo) end before do project_with_repo.add_maintainer(user) end context 'when eligible to have a note diff file' do let(:new_opts) do opts.merge( in_reply_to_discussion_id: nil, type: 'DiffNote', noteable_type: 'MergeRequest', noteable_id: merge_request.id, position: position.to_h, confidential: false ) end it_behaves_like 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) { described_class.new(project_with_repo, user, new_opts).execute } end it 'note is associated with a note diff file' do MergeRequests::MergeToRefService.new(project: merge_request.project, current_user: merge_request.author).execute(merge_request) note = described_class.new(project_with_repo, user, new_opts).execute expect(note).to be_persisted expect(note.note_diff_file).to be_present expect(note.diff_note_positions).to be_present end context 'when skip_capture_diff_note_position execute option is set to true' do it 'does not execute Discussions::CaptureDiffNotePositionService' do expect(Discussions::CaptureDiffNotePositionService).not_to receive(:new) described_class.new(project_with_repo, user, new_opts).execute(skip_capture_diff_note_position: true) end end context 'when skip_merge_status_trigger execute option is set to true' do it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do let(:action) do described_class .new(project_with_repo, user, new_opts) .execute(skip_merge_status_trigger: true) end end end it 'does not track ipynb note usage data' do expect(::Gitlab::UsageDataCounters::IpynbDiffActivityCounter).not_to receive(:note_created) described_class.new(project_with_repo, user, new_opts).execute end context 'is ipynb file' do before do allow_any_instance_of(::Gitlab::Diff::File).to receive(:ipynb?).and_return(true) end it 'tracks ipynb diff note creation' do expect(::Gitlab::UsageDataCounters::IpynbDiffActivityCounter).to receive(:note_created) described_class.new(project_with_repo, user, new_opts).execute end end end context 'when DiffNote is a reply' do let(:new_opts) do opts.merge( in_reply_to_discussion_id: previous_note.discussion_id, type: 'DiffNote', noteable_type: 'MergeRequest', noteable_id: merge_request.id, position: position.to_h, confidential: false ) end it 'note is not associated with a note diff file' do expect(Discussions::CaptureDiffNotePositionService).not_to receive(:new) note = described_class.new(project_with_repo, user, new_opts).execute expect(note).to be_persisted expect(note.note_diff_file).to be_nil end context 'when DiffNote from an image' do let(:image_position) do Gitlab::Diff::Position.new( old_path: "files/images/6049019_460s.jpg", new_path: "files/images/6049019_460s.jpg", width: 100, height: 100, x: 1, y: 100, diff_refs: merge_request.diff_refs, position_type: 'image' ) end let(:new_opts) do opts.merge( in_reply_to_discussion_id: nil, type: 'DiffNote', noteable_type: 'MergeRequest', noteable_id: merge_request.id, position: image_position.to_h, confidential: false ) end it 'note is not associated with a note diff file' do note = described_class.new(project_with_repo, user, new_opts).execute expect(note).to be_persisted expect(note.note_diff_file).to be_nil end end end end end end context 'note with commands' do context 'all quick actions' do let_it_be(:milestone) { create(:milestone, project: project, title: "sprint") } let_it_be(:bug_label) { create(:label, project: project, title: 'bug') } let_it_be(:to_be_copied_label) { create(:label, project: project, title: 'to be copied') } let_it_be(:feature_label) { create(:label, project: project, title: 'feature') } let_it_be(:issue, reload: true) { create(:issue, project: project, labels: [bug_label], due_date: '2019-01-01') } let_it_be(:issue_2) { create(:issue, project: project, labels: [bug_label, to_be_copied_label]) } context 'for issues' do let(:issuable) { issue } let(:note_params) { opts } let(:issue_quick_actions) do [ QuickAction.new( action_text: '/confidential', expectation: ->(noteable, can_use_quick_action) { if can_use_quick_action expect(noteable).to be_confidential else expect(noteable).not_to be_confidential end } ), QuickAction.new( action_text: '/due 2016-08-28', expectation: ->(noteable, can_use_quick_action) { expect(noteable.due_date == Date.new(2016, 8, 28)).to eq(can_use_quick_action) } ), QuickAction.new( action_text: '/remove_due_date', expectation: ->(noteable, can_use_quick_action) { if can_use_quick_action expect(noteable.due_date).to be_nil else expect(noteable.due_date).not_to be_nil end } ), QuickAction.new( action_text: "/duplicate #{issue_2.to_reference}", before_action: -> { issuable.reopen }, expectation: ->(noteable, can_use_quick_action) { expect(noteable.closed?).to eq(can_use_quick_action) } ) ] end it_behaves_like 'issuable quick actions' do let(:quick_actions) { issuable_quick_actions + issue_quick_actions } end end context 'for merge requests', feature_category: :code_review_workflow do let_it_be(:merge_request) { create(:merge_request, source_project: project, labels: [bug_label]) } let(:issuable) { merge_request } let(:note_params) { opts.merge(noteable_type: 'MergeRequest', noteable_id: merge_request.id, confidential: false) } let(:merge_request_quick_actions) do [ QuickAction.new( action_text: "/target_branch fix", expectation: ->(noteable, can_use_quick_action) { expect(noteable.target_branch == "fix").to eq(can_use_quick_action) } ), # Set Draft status QuickAction.new( action_text: "/draft", before_action: -> { issuable.reload.update!(title: "title") }, expectation: ->(issuable, can_use_quick_action) { expect(issuable.draft?).to eq(can_use_quick_action) } ), # Remove draft (set ready) status QuickAction.new( action_text: "/ready", before_action: -> { issuable.reload.update!(title: "Draft: title") }, expectation: ->(noteable, can_use_quick_action) { expect(noteable.draft?).not_to eq(can_use_quick_action) } ) ] end it_behaves_like 'issuable quick actions' do let(:quick_actions) { issuable_quick_actions + merge_request_quick_actions } end end end context 'when note only has commands' do it 'adds commands applied message to note errors' do note_text = %(/close) service = double(:service) allow(Issues::UpdateService).to receive(:new).and_return(service) expect(service).to receive(:execute) note = described_class.new(project, user, opts.merge(note: note_text)).execute expect(note.errors[:commands_only]).to be_present end it 'adds commands failed message to note errors' do note_text = %(/reopen) note = described_class.new(project, user, opts.merge(note: note_text)).execute expect(note.errors[:commands_only]).to contain_exactly('Could not apply reopen command.') end it 'generates success and failed error messages' do note_text = %(/close\n/reopen) service = double(:service) allow(Issues::UpdateService).to receive(:new).and_return(service) expect(service).to receive(:execute) note = described_class.new(project, user, opts.merge(note: note_text)).execute expect(note.errors[:commands_only]).to contain_exactly('Closed this issue. Could not apply reopen command.') end it 'does not check for spam' do expect_next_instance_of(Note) do |instance| expect(instance).not_to receive(:check_for_spam).with(action: :create, user: user) end note_text = %(/close) described_class.new(project, user, opts.merge(note: note_text)).execute end it 'generates failed update error messages' do note_text = %(/confidential) service = double(:service) issue.errors.add(:confidential, 'an error occurred') allow(Issues::UpdateService).to receive(:new).and_return(service) allow_next_instance_of(Issues::UpdateService) do |service_instance| allow(service_instance).to receive(:execute).and_return(issue) end note = described_class.new(project, user, opts.merge(note: note_text)).execute expect(note.errors[:commands_only]).to contain_exactly('Confidential an error occurred') end end end context 'personal snippet note', feature_category: :source_code_management do subject { described_class.new(nil, user, params).execute } let(:snippet) { create(:personal_snippet) } let(:params) do { note: 'comment', noteable_type: 'Snippet', noteable_id: snippet.id } end it 'returns a valid note' do expect(subject).to be_valid end it 'returns a persisted note' do expect(subject).to be_persisted end it 'note has valid content' do expect(subject.note).to eq(params[:note]) end end context 'design note', feature_category: :design_management do subject(:service) { described_class.new(project, user, params) } let_it_be(:design) { create(:design, :with_file) } let_it_be(:project) { design.project } let_it_be(:user) { project.first_owner } let_it_be(:params) do { type: 'DiffNote', noteable: design, note: "A message", position: { old_path: design.full_path, new_path: design.full_path, position_type: 'image', width: '100', height: '100', x: '50', y: '50', base_sha: design.diff_refs.base_sha, start_sha: design.diff_refs.base_sha, head_sha: design.diff_refs.head_sha } } end it 'can create diff notes for designs' do note = service.execute expect(note).to be_a(DiffNote) expect(note).to be_persisted expect(note.noteable).to eq(design) end it 'sends a notification about this note', :sidekiq_might_not_need_inline do notifier = double allow(::NotificationService).to receive(:new).and_return(notifier) expect(notifier) .to receive(:new_note) .with have_attributes(noteable: design) service.execute end it 'correctly builds the position of the note' do note = service.execute expect(note.position.new_path).to eq(design.full_path) expect(note.position.old_path).to eq(design.full_path) expect(note.position.diff_refs).to eq(design.diff_refs) end end context 'note with emoji only' do it 'creates regular note' do opts = { note: ':smile: ', noteable_type: 'Issue', noteable_id: issue.id } note = described_class.new(project, user, opts).execute expect(note).to be_valid expect(note.note).to eq(':smile:') end end context 'reply to individual note' do let(:existing_note) { create(:note_on_issue, noteable: issue, project: project) } let(:reply_opts) { opts.merge(in_reply_to_discussion_id: existing_note.discussion_id) } subject { described_class.new(project, user, reply_opts).execute } it 'creates a DiscussionNote in reply to existing note' do expect(subject).to be_a(DiscussionNote) expect(subject.discussion_id).to eq(existing_note.discussion_id) end it 'converts existing note to DiscussionNote' do expect do existing_note travel_to(Time.current + 1.minute) { subject } existing_note.reload end.to change { existing_note.type }.from(nil).to('DiscussionNote') .and change { existing_note.updated_at } end context 'failure in when_saved' do let(:service) { described_class.new(project, user, reply_opts) } it 'converts existing note to DiscussionNote' do expect do existing_note allow(service).to receive(:when_saved).and_raise(ActiveRecord::StatementInvalid) travel_to(Time.current + 1.minute) do service.execute rescue ActiveRecord::StatementInvalid end existing_note.reload end.to change { existing_note.type }.from(nil).to('DiscussionNote') .and change { existing_note.updated_at } end end it 'returns a DiscussionNote with its parent discussion refreshed correctly' do discussion_notes = subject.discussion.notes expect(discussion_notes.size).to eq(2) expect(discussion_notes.first).to be_a(DiscussionNote) end context 'discussion to reply cannot be found' do before do existing_note.delete end it 'returns an note with errors' do note = subject expect(note.errors).not_to be_empty expect(note.errors[:base]).to eq(['Discussion to reply to cannot be found']) end end end describe "usage counter" do let(:counter) { Gitlab::UsageDataCounters::NoteCounter } context 'snippet note' do let(:snippet) { create(:project_snippet, project: project) } let(:opts) { { note: 'reply', noteable_type: 'Snippet', noteable_id: snippet.id, project: project } } it 'increments usage counter' do expect do note = described_class.new(project, user, opts).execute expect(note).to be_valid end.to change { counter.read(:create, opts[:noteable_type]) }.by 1 end it 'does not increment usage counter when creation fails' do expect do note = described_class.new(project, user, { note: '' }).execute expect(note).to be_invalid end.not_to change { counter.read(:create, opts[:noteable_type]) } end end context 'issue note' do let(:issue) { create(:issue, project: project) } let(:opts) { { note: 'reply', noteable_type: 'Issue', noteable_id: issue.id, project: project } } it 'does not increment usage counter' do expect do note = described_class.new(project, user, opts).execute expect(note).to be_valid end.not_to change { counter.read(:create, opts[:noteable_type]) } end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ProtectedTags class DestroyService < BaseService def execute(protected_tag) protected_tag.destroy end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ProtectedTags::DestroyService, feature_category: :compliance_management do let(:protected_tag) { create(:protected_tag) } let(:project) { protected_tag.project } let(:user) { project.first_owner } describe '#execute' do subject(:service) { described_class.new(project, user) } it 'destroy a protected tag' do service.execute(protected_tag) expect(protected_tag).to be_destroyed end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ProtectedTags class UpdateService < ::BaseService def execute(protected_tag) raise Gitlab::Access::AccessDeniedError unless can?(current_user, :admin_project, project) protected_tag.update(params) protected_tag end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ProtectedTags::UpdateService, feature_category: :compliance_management do let(:protected_tag) { create(:protected_tag) } let(:project) { protected_tag.project } let(:user) { project.first_owner } let(:params) { { name: new_name } } describe '#execute' do let(:new_name) { 'new protected tag name' } let(:result) { service.execute(protected_tag) } subject(:service) { described_class.new(project, user, params) } it 'updates a protected tag' do expect(result.reload.name).to eq(params[:name]) end context 'when updating protected tag with a name that contains HTML tags' do let(:new_name) { 'foo<b>bar<\b>' } let(:result) { service.execute(protected_tag) } subject(:service) { described_class.new(project, user, params) } it 'updates a protected tag' do expect(result.reload.name).to eq(new_name) end end context 'without admin_project permissions' do let(:user) { create(:user) } it "raises error" do expect { service.execute(protected_tag) }.to raise_error(Gitlab::Access::AccessDeniedError) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module ProtectedTags class CreateService < ::BaseService attr_reader :protected_tag def execute raise Gitlab::Access::AccessDeniedError unless can?(current_user, :admin_project, project) project.protected_tags.create(params) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ProtectedTags::CreateService, feature_category: :compliance_management do let(:project) { create(:project) } let(:user) { project.first_owner } let(:params) do { name: name, create_access_levels_attributes: [{ access_level: Gitlab::Access::MAINTAINER }] } end describe '#execute' do let(:name) { 'tag' } subject(:service) { described_class.new(project, user, params) } it 'creates a new protected tag' do expect { service.execute }.to change(ProtectedTag, :count).by(1) expect(project.protected_tags.last.create_access_levels.map(&:access_level)).to eq([Gitlab::Access::MAINTAINER]) end context 'protecting a tag with a name that contains HTML tags' do let(:name) { 'foo<b>bar<\b>' } subject(:service) { described_class.new(project, user, params) } it 'creates a new protected tag' do expect { service.execute }.to change(ProtectedTag, :count).by(1) expect(project.protected_tags.last.name).to eq(name) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class CreateCandidateService def initialize(experiment, params = {}) @experiment = experiment @name = params[:name] @user = params[:user] @start_time = params[:start_time] @model_version = params[:model_version] end def execute Ml::Candidate.create!( experiment: experiment, project: experiment.project, name: candidate_name, start_time: start_time || 0, user: user, model_version: model_version ) end private def candidate_name name.presence || random_candidate_name end def random_candidate_name parts = Array.new(3).map { FFaker::Animal.common_name.downcase.delete(' ') } << rand(10000) parts.join('-').truncate(255) end attr_reader :name, :user, :experiment, :start_time, :model_version end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::CreateCandidateService, feature_category: :mlops do describe '#execute' do let_it_be(:model_version) { create(:ml_model_versions, candidate: nil) } let_it_be(:experiment) { create(:ml_experiments, project: model_version.project) } let(:params) { {} } subject(:candidate) { described_class.new(experiment, params).execute } context 'with default parameters' do it 'creates a candidate' do expect { candidate }.to change { experiment.candidates.count }.by(1) end it 'gives a fake name' do expect(candidate.name).to match(/[a-z]+-[a-z]+-[a-z]+-\d+/) end it 'sets the correct values', :aggregate_failures do expect(candidate.start_time).to eq(0) expect(candidate.experiment).to be(experiment) expect(candidate.project).to be(experiment.project) expect(candidate.user).to be_nil end end context 'when parameters are passed' do let(:params) do { start_time: 1234, name: 'candidate_name', model_version: model_version, user: experiment.user } end context 'with default parameters' do it 'creates a candidate' do expect { candidate }.to change { experiment.candidates.count }.by(1) end it 'sets the correct values', :aggregate_failures do expect(candidate.start_time).to eq(1234) expect(candidate.experiment).to be(experiment) expect(candidate.project).to be(experiment.project) expect(candidate.user).to be(experiment.user) expect(candidate.name).to eq('candidate_name') expect(candidate.model_version_id).to eq(model_version.id) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class CreateModelVersionService def initialize(model, params = {}) @model = model @version = params[:version] @package = params[:package] @description = params[:description] @user = params[:user] end def execute ApplicationRecord.transaction do @version ||= Ml::IncrementVersionService.new(@model.latest_version.try(:version)).execute package = @package || find_or_create_package(@model.name, @version) model_version = Ml::ModelVersion.create!(model: @model, project: @model.project, version: @version, package: package, description: @description) model_version.candidate = ::Ml::CreateCandidateService.new( @model.default_experiment, { model_version: model_version } ).execute model_version end end private def find_or_create_package(model_name, model_version) package_params = { name: model_name, version: model_version } ::Packages::MlModel::FindOrCreatePackageService .new(@model.project, @user, package_params) .execute end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::CreateModelVersionService, feature_category: :mlops do let(:model) { create(:ml_models) } let(:params) { {} } subject(:service) { described_class.new(model, params).execute } context 'when no versions exist' do it 'creates a model version', :aggregate_failures do expect { service }.to change { Ml::ModelVersion.count }.by(1).and change { Ml::Candidate.count }.by(1) expect(model.reload.latest_version.version).to eq('1.0.0') end end context 'when a version exist' do before do create(:ml_model_versions, model: model, version: '3.0.0') end it 'creates another model version and increments the version number', :aggregate_failures do expect { service }.to change { Ml::ModelVersion.count }.by(1).and change { Ml::Candidate.count }.by(1) expect(model.reload.latest_version.version).to eq('4.0.0') end end context 'when a version is created' do it 'creates a package' do expect { service }.to change { Ml::ModelVersion.count }.by(1).and change { Packages::MlModel::Package.count }.by(1) expect(model.reload.latest_version.package.name).to eq(model.name) expect(model.latest_version.package.version).to eq(model.latest_version.version) end end context 'when a version is created and the package already exists' do it 'does not creates a package' do next_version = Ml::IncrementVersionService.new(model.latest_version.try(:version)).execute create(:ml_model_package, name: model.name, version: next_version, project: model.project) expect { service }.to change { Ml::ModelVersion.count }.by(1).and not_change { Packages::MlModel::Package.count } expect(model.reload.latest_version.package.name).to eq(model.name) expect(model.latest_version.package.version).to eq(model.latest_version.version) end end context 'when a version is created and an existing package supplied' do it 'does not creates a package' do next_version = Ml::IncrementVersionService.new(model.latest_version.try(:version)).execute package = create(:ml_model_package, name: model.name, version: next_version, project: model.project) service = described_class.new(model, { package: package }) expect { service.execute }.to change { Ml::ModelVersion.count }.by(1).and not_change { Packages::MlModel::Package.count } expect(model.reload.latest_version.package.name).to eq(model.name) expect(model.latest_version.package.version).to eq(model.latest_version.version) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class FindOrCreateExperimentService def initialize(project, experiment_name, user = nil) @project = project @name = experiment_name @user = user end def execute Ml::Experiment.find_or_create(project, name, user) end private attr_reader :project, :name, :user end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::FindOrCreateExperimentService, feature_category: :mlops do let_it_be(:project) { create(:project) } let_it_be(:user) { project.first_owner } let_it_be(:existing_experiment) { create(:ml_experiments, project: project, user: user) } let(:name) { 'new_experiment' } subject(:new_experiment) { described_class.new(project, name, user).execute } describe '#execute' do it 'creates an experiment using Ml::Experiment.find_or_create', :aggregate_failures do expect(Ml::Experiment).to receive(:find_or_create).and_call_original expect(new_experiment.name).to eq('new_experiment') expect(new_experiment.project).to eq(project) expect(new_experiment.user).to eq(user) end context 'when experiment already exists' do let(:name) { existing_experiment.name } it 'fetches existing experiment', :aggregate_failures do expect { new_experiment }.not_to change { Ml::Experiment.count } expect(new_experiment).to eq(existing_experiment) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class DestroyModelService def initialize(model, user) @model = model @user = user end def execute return unless @model.destroy ::Packages::MarkPackagesForDestructionService.new( packages: @model.all_packages, current_user: @user ).execute end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::DestroyModelService, feature_category: :mlops do let_it_be(:user) { create(:user) } let_it_be(:model) { create(:ml_models, :with_latest_version_and_package) } let(:service) { described_class.new(model, user) } describe '#execute' do context 'when model name does not exist in the project' do it 'returns nil' do allow(model).to receive(:destroy).and_return(false) expect(service.execute).to be nil end end context 'when a model exists' do it 'destroys the model' do expect(Packages::MarkPackagesForDestructionService).to receive(:new).with(packages: model.all_packages, current_user: user).and_return(instance_double('Packages::MarkPackagesForDestructionService').tap do |service| expect(service).to receive(:execute) end) expect { service.execute }.to change { Ml::Model.count }.by(-1).and change { Ml::ModelVersion.count }.by(-1) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class CreateModelService def initialize(project, name, user = nil, description = nil, metadata = []) @project = project @name = name @description = description @metadata = metadata @user = user end def execute ApplicationRecord.transaction do model = Ml::Model.create!( project: @project, name: @name, user: (@user.is_a?(User) ? @user : nil), description: @description, default_experiment: default_experiment ) add_metadata(model, @metadata) model end end private def default_experiment @default_experiment ||= Ml::FindOrCreateExperimentService.new(@project, @name).execute end def add_metadata(model, metadata_key_value) return unless model.present? && metadata_key_value.present? entities = metadata_key_value.map do |d| { model_id: model.id, name: d[:key], value: d[:value] } end entities.each do |entry| ::Ml::ModelMetadata.create!(entry) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::CreateModelService, feature_category: :mlops do let_it_be(:user) { create(:user) } let_it_be(:existing_model) { create(:ml_models) } let_it_be(:another_project) { create(:project) } let_it_be(:description) { 'description' } let_it_be(:metadata) { [] } subject(:create_model) { described_class.new(project, name, user, description, metadata).execute } describe '#execute' do context 'when model name does not exist in the project' do let(:name) { 'new_model' } let(:project) { existing_model.project } it 'creates a model', :aggregate_failures do expect { create_model }.to change { Ml::Model.count }.by(1) expect(create_model.name).to eq(name) end end context 'when model name exists but project is different' do let(:name) { existing_model.name } let(:project) { another_project } it 'creates a model', :aggregate_failures do expect { create_model }.to change { Ml::Model.count }.by(1) expect(create_model.name).to eq(name) end end context 'when model with name exists' do let(:name) { existing_model.name } let(:project) { existing_model.project } it 'raises an error', :aggregate_failures do expect { create_model }.to raise_error(ActiveRecord::RecordInvalid) end end context 'when metadata are supplied, add them as metadata' do let(:name) { 'new_model' } let(:project) { existing_model.project } let(:metadata) { [{ key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2' }] } it 'creates metadata records', :aggregate_failures do expect { create_model }.to change { Ml::Model.count }.by(1) expect(create_model.name).to eq(name) expect(create_model.metadata.count).to be 2 end end # TODO: Ensure consisted error responses https://gitlab.com/gitlab-org/gitlab/-/issues/429731 context 'for metadata with duplicate keys, it does not create duplicate records' do let(:name) { 'new_model' } let(:project) { existing_model.project } let(:metadata) { [{ key: 'key1', value: 'value1' }, { key: 'key1', value: 'value2' }] } it 'raises an error', :aggregate_failures do expect { create_model }.to raise_error(ActiveRecord::RecordInvalid) end end # TODO: Ensure consisted error responses https://gitlab.com/gitlab-org/gitlab/-/issues/429731 context 'for metadata with invalid keys, it does not create invalid records' do let(:name) { 'new_model' } let(:project) { existing_model.project } let(:metadata) { [{ key: 'key1', value: 'value1' }, { key: '', value: 'value2' }] } it 'raises an error', :aggregate_failures do expect { create_model }.to raise_error(ActiveRecord::RecordInvalid) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class UpdateModelService def initialize(model, description) @model = model @description = description end def execute @model.update!(description: @description) @model end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::UpdateModelService, feature_category: :mlops do let_it_be(:model) { create(:ml_models) } let_it_be(:description) { 'updated model description' } let(:service) { described_class.new(model, description) } describe '#execute' do context 'when supplied with a non-model object' do let(:model) { nil } it 'returns nil' do expect { service.execute }.to raise_error(NoMethodError) end end context 'with an existing model' do it 'updates the description' do updated = service.execute expect(updated.class).to be(Ml::Model) expect(updated.description).to eq(description) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml INITIAL_VERSION = '1.0.0' ALLOWED_INCREMENT_TYPES = [:patch, :minor, :major].freeze class IncrementVersionService def initialize(version, increment_type = nil) @version = version @increment_type = increment_type || :major @parsed_version = Packages::SemVer.parse(@version.to_s) raise "Version must be in a valid SemVer format" unless @parsed_version || @version.nil? return if ALLOWED_INCREMENT_TYPES.include?(@increment_type) raise "Increment type must be one of :patch, :minor, or :major" end def execute return INITIAL_VERSION if @version.nil? case @increment_type when :patch @parsed_version.patch += 1 when :minor @parsed_version.minor += 1 when :major @parsed_version.major += 1 end @parsed_version.to_s end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::IncrementVersionService, feature_category: :mlops do describe '#execute' do let(:increment_type) { nil } let(:finder) { described_class.new(version, increment_type) } context 'when given an invalid version format' do let(:version) { 'foo' } it 'raises an error' do expect { finder.execute }.to raise_error(RuntimeError, "Version must be in a valid SemVer format") end end context 'when given a non-semver version format' do let(:version) { 1 } it 'raises an error' do expect { finder.execute }.to raise_error(RuntimeError, "Version must be in a valid SemVer format") end end context 'when given an unsupported increment type' do let(:version) { '1.2.3' } let(:increment_type) { 'foo' } it 'raises an error' do expect do finder.execute end.to raise_error(RuntimeError, "Increment type must be one of :patch, :minor, or :major") end end context 'when valid inputs are provided' do using RSpec::Parameterized::TableSyntax where(:version, :increment_type, :result) do nil | nil | '1.0.0' '0.0.1' | nil | '1.0.1' '1.0.0' | nil | '2.0.0' '1.0.0' | :major | '2.0.0' '1.0.0' | :minor | '1.1.0' '1.0.0' | :patch | '1.0.1' end with_them do subject { finder.execute } it { is_expected.to eq(result) } end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class FindOrCreateModelService def initialize(project, name, user = nil, description = nil, metadata = []) @project = project @name = name @description = description @metadata = metadata @user = user end def execute FindModelService.new(@project, @name).execute || CreateModelService.new(@project, @name, @user, @description, @metadata).execute end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::FindOrCreateModelService, feature_category: :mlops do let_it_be(:user) { create(:user) } let_it_be(:existing_model) { create(:ml_models) } let_it_be(:another_project) { create(:project) } let_it_be(:description) { 'description' } let_it_be(:metadata) { [] } subject(:create_model) { described_class.new(project, name, user, description, metadata).execute } describe '#execute' do context 'when model name does not exist in the project' do let(:name) { 'new_model' } let(:project) { existing_model.project } it 'creates a model', :aggregate_failures do expect { create_model }.to change { Ml::Model.count }.by(1) expect(create_model.name).to eq(name) end end context 'when model name exists but project is different' do let(:name) { existing_model.name } let(:project) { another_project } it 'creates a model', :aggregate_failures do expect { create_model }.to change { Ml::Model.count }.by(1) expect(create_model.name).to eq(name) end end context 'when model with name exists' do let(:name) { existing_model.name } let(:project) { existing_model.project } it 'fetches existing model', :aggregate_failures do expect { create_model }.to change { Ml::Model.count }.by(0) expect(create_model).to eq(existing_model) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class FindOrCreateModelVersionService def initialize(project, params = {}) @project = project @name = params[:model_name] @version = params[:version] @package = params[:package] @description = params[:description] end def execute model = Ml::FindOrCreateModelService.new(@project, @name).execute model_version = Ml::ModelVersion.find_or_create!(model, @version, @package, @description) unless model_version.candidate model_version.candidate = ::Ml::CreateCandidateService.new( model.default_experiment, { model_version: model_version } ).execute end model_version end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::FindOrCreateModelVersionService, feature_category: :mlops do let_it_be(:existing_version) { create(:ml_model_versions) } let_it_be(:another_project) { create(:project) } let_it_be(:user) { create(:user) } let(:package) { nil } let(:description) { nil } let(:params) do { model_name: name, version: version, package: package, description: description, user: user } end subject(:model_version) { described_class.new(project, params).execute } describe '#execute' do context 'when model version exists' do let(:name) { existing_version.name } let(:version) { existing_version.version } let(:project) { existing_version.project } it 'returns existing model version', :aggregate_failures do expect { model_version }.to change { Ml::ModelVersion.count }.by(0) expect { model_version }.to change { Ml::Candidate.count }.by(0) expect(model_version).to eq(existing_version) end end context 'when model version does not exist' do let(:project) { existing_version.project } let(:name) { 'a_new_model' } let(:version) { '2.0.0' } let(:description) { 'A model version' } let(:package) { create(:ml_model_package, project: project, name: name, version: version) } it 'creates a new model version', :aggregate_failures do expect { model_version }.to change { Ml::ModelVersion.count }.by(1).and change { Ml::Candidate.count }.by(1) expect(model_version.name).to eq(name) expect(model_version.version).to eq(version) expect(model_version.package).to eq(package) expect(model_version.candidate.model_version_id).to eq(model_version.id) expect(model_version.description).to eq(description) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml class FindModelService def initialize(project, name) @project = project @name = name end def execute Ml::Model.by_project_id_and_name(@project.id, @name) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::FindModelService, feature_category: :mlops do let_it_be(:user) { create(:user) } let_it_be(:existing_model) { create(:ml_models) } let(:finder) { described_class.new(project, name) } describe '#execute' do context 'when model name does not exist in the project' do let(:name) { 'new_model' } let(:project) { existing_model.project } it 'reutrns nil' do expect(finder.execute).to be nil end end context 'when model with name exists' do let(:name) { existing_model.name } let(:project) { existing_model.project } it 'returns the existing model' do expect(finder.execute).to eq(existing_model) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml module ExperimentTracking class CandidateRepository attr_accessor :project, :user, :experiment, :candidate def initialize(project, user = nil) @project = project @user = user end def by_eid(eid) ::Ml::Candidate.with_project_id_and_eid(project.id, eid) end def create!(experiment, start_time, tags = nil, name = nil) create_params = { start_time: start_time, user: user, name: candidate_name(name, tags) } candidate = Ml::CreateCandidateService.new(experiment, create_params).execute add_tags(candidate, tags) candidate end def update(candidate, status, end_time) candidate.status = status.downcase if status candidate.end_time = end_time if end_time candidate.save end def add_metric!(candidate, name, value, tracked_at, step) candidate.metrics.create!( name: name, value: value, tracked_at: tracked_at, step: step ) end def add_param!(candidate, name, value) candidate.params.create!(name: name, value: value) end def add_tag!(candidate, name, value) handle_gitlab_tags(candidate, [{ key: name, value: value }]) candidate.metadata.create!(name: name, value: value) end def add_metrics(candidate, metric_definitions) extra_keys = { tracked_at: :timestamp, step: :step } insert_many(candidate, metric_definitions, ::Ml::CandidateMetric, extra_keys) end def add_params(candidate, param_definitions) insert_many(candidate, param_definitions, ::Ml::CandidateParam) end def add_tags(candidate, tag_definitions) return unless tag_definitions.present? handle_gitlab_tags(candidate, tag_definitions) insert_many(candidate, tag_definitions, ::Ml::CandidateMetadata) end private def handle_gitlab_tags(candidate, tag_definitions) return unless tag_definitions.any? { |t| t[:key]&.starts_with?('gitlab.') } Ml::ExperimentTracking::HandleCandidateGitlabMetadataService .new(candidate, tag_definitions) .execute end def timestamps current_time = Time.zone.now { created_at: current_time, updated_at: current_time } end def insert_many(candidate, definitions, entity_class, extra_keys = {}) return unless candidate.present? && definitions.present? entities = definitions.map do |d| { candidate_id: candidate.id, name: d[:key], value: d[:value], **extra_keys.transform_values { |old_key| d[old_key] }, **timestamps } end entity_class.insert_all(entities, returning: false) unless entities.empty? end def candidate_name(name, tags) name.presence || candidate_name_from_tags(tags) end def candidate_name_from_tags(tags) tags&.detect { |t| t[:key] == 'mlflow.runName' }&.dig(:value) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::ExperimentTracking::CandidateRepository, feature_category: :activation do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:experiment) { create(:ml_experiments, user: user, project: project) } let_it_be(:candidate) { create(:ml_candidates, user: user, experiment: experiment, project: project) } let(:repository) { described_class.new(project, user) } describe '#by_eid' do let(:eid) { candidate.eid } subject { repository.by_eid(eid) } it { is_expected.to eq(candidate) } context 'when iid does not exist' do let(:eid) { non_existing_record_iid.to_s } it { is_expected.to be_nil } end context 'when iid belongs to a different project' do let(:repository) { described_class.new(create(:project), user) } it { is_expected.to be_nil } end end describe '#create!' do let(:tags) { [{ key: 'hello', value: 'world' }] } let(:name) { 'some_candidate' } subject { repository.create!(experiment, 1234, tags, name) } it 'creates the candidate' do expect(subject.start_time).to eq(1234) expect(subject.eid).not_to be_nil expect(subject.end_time).to be_nil expect(subject.name).to eq('some_candidate') end it 'creates with tag' do expect(subject.metadata.length).to eq(1) end context 'when name is passed as tag' do let(:tags) { [{ key: 'mlflow.runName', value: 'blah' }] } it 'ignores if name is not nil' do expect(subject.name).to eq('some_candidate') end context 'when name is nil' do let(:name) { nil } it 'sets the mlflow.runName as candidate name' do expect(subject.name).to eq('blah') end end context 'when name is nil and no mlflow.runName is not present' do let(:tags) { nil } let(:name) { nil } it 'gives the candidate a random name' do expect(subject.name).to match(/[a-z]+-[a-z]+-[a-z]+-\d+/) end end end end describe '#update' do let(:end_time) { 123456 } let(:status) { 'running' } subject { repository.update(candidate, status, end_time) } it { is_expected.to be_truthy } context 'when end_time is missing ' do let(:end_time) { nil } it { is_expected.to be_truthy } end context 'when status is wrong' do let(:status) { 's' } it 'fails assigning the value' do expect { subject }.to raise_error(ArgumentError) end end context 'when status is missing' do let(:status) { nil } it { is_expected.to be_truthy } end end describe '#add_metric!' do let(:props) { { name: 'abc', value: 1234, tracked: 12345678, step: 0 } } let(:metrics_before) { candidate.metrics.size } before do metrics_before end subject { repository.add_metric!(candidate, props[:name], props[:value], props[:tracked], props[:step]) } it 'adds a new metric' do expect { subject }.to change { candidate.metrics.size }.by(1) end context 'when name missing' do let(:props) { { value: 1234, tracked: 12345678, step: 0 } } it 'does not add metric' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid) end end end describe '#add_param!' do let(:props) { { name: 'abc', value: 'def' } } subject { repository.add_param!(candidate, props[:name], props[:value]) } it 'adds a new param' do expect { subject }.to change { candidate.params.size }.by(1) end context 'when name missing' do let(:props) { { value: 1234 } } it 'throws RecordInvalid' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid) end end context 'when param was already added' do it 'throws RecordInvalid' do repository.add_param!(candidate, 'new', props[:value]) expect { repository.add_param!(candidate, 'new', props[:value]) }.to raise_error(ActiveRecord::RecordInvalid) end end end describe '#add_tag!' do let(:props) { { name: 'abc', value: 'def' } } subject { repository.add_tag!(candidate, props[:name], props[:value]) } it 'adds a new tag' do expect { subject }.to change { candidate.reload.metadata.size }.by(1) end context 'when name missing' do let(:props) { { value: 1234 } } it 'throws RecordInvalid' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid) end end context 'when tag was already added' do it 'throws RecordInvalid' do repository.add_tag!(candidate, 'new', props[:value]) expect { repository.add_tag!(candidate, 'new', props[:value]) }.to raise_error(ActiveRecord::RecordInvalid) end end context 'when tag starts with gitlab.' do it 'calls HandleCandidateGitlabMetadataService' do expect(Ml::ExperimentTracking::HandleCandidateGitlabMetadataService).to receive(:new).and_call_original repository.add_tag!(candidate, 'gitlab.CI_USER_ID', user.id) end end end describe "#add_params" do let(:params) do [{ key: 'model_class', value: 'LogisticRegression' }, { 'key': 'pythonEnv', value: '3.10' }] end subject { repository.add_params(candidate, params) } it 'adds the parameters' do expect { subject }.to change { candidate.reload.params.size }.by(2) end context 'if parameter misses key' do let(:params) do [{ value: 'LogisticRegression' }] end it 'does not throw and does not add' do expect { subject }.to raise_error(ActiveRecord::ActiveRecordError) end end context 'if parameter misses value' do let(:params) do [{ key: 'pythonEnv2' }] end it 'does not throw and does not add' do expect { subject }.to raise_error(ActiveRecord::ActiveRecordError) end end context 'if parameter repeated do' do let(:params) do [ { 'key': 'pythonEnv0', value: '2.7' }, { 'key': 'pythonEnv1', value: '3.9' }, { 'key': 'pythonEnv1', value: '3.10' } ] end before do repository.add_param!(candidate, 'pythonEnv0', '0') end it 'does not throw and adds only the first of each kind' do expect { subject }.to change { candidate.reload.params.size }.by(1) end end end describe "#add_metrics" do let(:metrics) do [ { key: 'mae', value: 2.5, timestamp: 1552550804 }, { key: 'rmse', value: 2.7, timestamp: 1552550804 } ] end subject { repository.add_metrics(candidate, metrics) } it 'adds the metrics' do expect { subject }.to change { candidate.reload.metrics.size }.by(2) end context 'when metrics have repeated keys' do let(:metrics) do [ { key: 'mae', value: 2.5, timestamp: 1552550804 }, { key: 'rmse', value: 2.7, timestamp: 1552550804 }, { key: 'mae', value: 2.7, timestamp: 1552550805 } ] end it 'adds all of them' do expect { subject }.to change { candidate.reload.metrics.size }.by(3) end end end describe "#add_tags" do let(:tags) do [{ key: 'gitlab.tag1', value: 'hello' }, { 'key': 'gitlab.tag2', value: 'world' }] end subject { repository.add_tags(candidate, tags) } it 'adds the tags' do expect { subject }.to change { candidate.reload.metadata.size }.by(2) end context 'if tags misses key' do let(:tags) { [{ value: 'hello' }] } it 'does throw and does not add' do expect { subject }.to raise_error(ActiveRecord::ActiveRecordError) end end context 'if tag misses value' do let(:tags) { [{ key: 'gitlab.tag1' }] } it 'does throw and does not add' do expect { subject }.to raise_error(ActiveRecord::ActiveRecordError) end end context 'if tag repeated' do let(:params) do [ { 'key': 'gitlab.tag1', value: 'hello' }, { 'key': 'gitlab.tag2', value: 'world' }, { 'key': 'gitlab.tag1', value: 'gitlab' } ] end before do repository.add_tag!(candidate, 'gitlab.tag2', '0') end it 'does not throw and adds only the first of each kind' do expect { subject }.to change { candidate.reload.metadata.size }.by(1) end end context 'when tags is nil' do let(:tags) { nil } it 'does not handle gitlab tags' do expect(repository).not_to receive(:handle_gitlab_tags) subject end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml module ExperimentTracking class HandleCandidateGitlabMetadataService def initialize(candidate, metadata) @candidate = candidate @metadata = metadata.index_by { |m| m[:key] } end def execute handle_build_metadata(@metadata['gitlab.CI_JOB_ID']) @candidate.save end private def handle_build_metadata(build_metadata) return unless build_metadata build = Ci::Build.find_by_id(build_metadata[:value]) raise ArgumentError, 'gitlab.CI_JOB_ID must refer to an existing build' unless build @candidate.ci_build = build end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::ExperimentTracking::HandleCandidateGitlabMetadataService, feature_category: :activation do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { project.owner } let_it_be(:pipeline) { create(:ci_pipeline, project: project) } let_it_be(:build) { create(:ci_build, :success, pipeline: pipeline) } let(:metadata) { [] } let(:candidate) { create(:ml_candidates, project: project, user: user) } describe 'execute' do subject { described_class.new(candidate, metadata).execute } context 'when metadata includes gitlab.CI_JOB_ID', 'and gitlab.CI_JOB_ID is valid' do let(:metadata) do [ { key: 'gitlab.CI_JOB_ID', value: build.id.to_s } ] end it 'updates candidate correctly', :aggregate_failures do subject expect(candidate.ci_build).to eq(build) end end context 'when metadata includes gitlab.CI_JOB_ID and gitlab.CI_JOB_ID is invalid' do let(:metadata) { [{ key: 'gitlab.CI_JOB_ID', value: non_existing_record_id.to_s }] } it 'raises error' do expect { subject } .to raise_error(ArgumentError, 'gitlab.CI_JOB_ID must refer to an existing build') end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml module ExperimentTracking class ExperimentRepository attr_accessor :project, :user def initialize(project, user = nil) @project = project @user = user end def by_iid_or_name(iid: nil, name: nil) return ::Ml::Experiment.by_project_id_and_iid(project.id, iid) if iid ::Ml::Experiment.by_project_id_and_name(project.id, name) if name end def all ::Ml::Experiment.by_project_id(project.id) end def create!(name, tags = nil) experiment = ::Ml::Experiment.create!(name: name, user: user, project: project) add_tags(experiment, tags) experiment end def add_tag!(experiment, key, value) return unless experiment.present? experiment.metadata.create!(name: key, value: value) end private def timestamps current_time = Time.zone.now { created_at: current_time, updated_at: current_time } end def add_tags(experiment, tag_definitions) return unless experiment.present? && tag_definitions.present? entities = tag_definitions.map do |d| { experiment_id: experiment.id, name: d[:key], value: d[:value], **timestamps } end ::Ml::ExperimentMetadata.insert_all(entities, returning: false) unless entities.empty? end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::Ml::ExperimentTracking::ExperimentRepository, feature_category: :activation do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:experiment) { create(:ml_experiments, user: user, project: project) } let_it_be(:experiment2) { create(:ml_experiments, user: user, project: project) } let_it_be(:experiment3) { create(:ml_experiments, user: user, project: project) } let_it_be(:experiment4) { create(:ml_experiments, user: user) } let(:repository) { described_class.new(project, user) } describe '#by_iid_or_name' do let(:iid) { experiment.iid } let(:name) { nil } subject { repository.by_iid_or_name(iid: iid, name: name) } context 'when iid passed' do it('fetches the experiment') { is_expected.to eq(experiment) } context 'and name passed' do let(:name) { experiment2.name } it('ignores the name') { is_expected.to eq(experiment) } end context 'and does not exist' do let(:iid) { non_existing_record_iid } it { is_expected.to eq(nil) } end end context 'when iid is not passed', 'and name is passed' do let(:iid) { nil } context 'when name exists' do let(:name) { experiment2.name } it('fetches the experiment') { is_expected.to eq(experiment2) } end context 'when name does not exist' do let(:name) { non_existing_record_iid } it { is_expected.to eq(nil) } end end end describe '#all' do it 'fetches experiments for project' do expect(repository.all).to match_array([experiment, experiment2, experiment3]) end end describe '#create!' do let(:name) { 'hello' } let(:tags) { nil } subject { repository.create!(name, tags) } it 'creates the experiment' do expect { subject }.to change { repository.all.size }.by(1) end context 'when name exists' do let(:name) { experiment.name } it 'throws error' do expect { subject }.to raise_error(ActiveRecord::ActiveRecordError) end end context 'when has tags' do let(:tags) { [{ key: 'hello', value: 'world' }] } it 'creates the experiment with tag' do expect(subject.metadata.length).to eq(1) end end context 'when name is missing' do let(:name) { nil } it 'throws error' do expect { subject }.to raise_error(ActiveRecord::ActiveRecordError) end end end describe '#add_tag!' do let(:props) { { name: 'abc', value: 'def' } } subject { repository.add_tag!(experiment, props[:name], props[:value]) } it 'adds a new tag' do expect { subject }.to change { experiment.reload.metadata.size }.by(1) end context 'when name missing' do let(:props) { { value: 1234 } } it 'throws RecordInvalid' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid) end end context 'when tag was already added' do it 'throws RecordInvalid' do repository.add_tag!(experiment, 'new', props[:value]) expect { repository.add_tag!(experiment, 'new', props[:value]) }.to raise_error(ActiveRecord::RecordInvalid) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml module ModelVersions class UpdateModelVersionService def initialize(project, name, version, description) @project = project @name = name @version = version @description = description end def execute model_version = Ml::ModelVersion .by_project_id_name_and_version(@project.id, @name, @version) return ServiceResponse.error(message: 'Model not found') unless model_version.present? result = model_version.update(description: @description) return ServiceResponse.error(message: 'Model update failed') unless result ServiceResponse.success(payload: model_version) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Ml::ModelVersions::UpdateModelVersionService, feature_category: :mlops do let_it_be(:existing_version) { create(:ml_model_versions) } let(:project) { existing_version.project } let(:name) { existing_version.name } let(:version) { existing_version.version } let(:description) { 'A model version description' } subject(:execute_service) { described_class.new(project, name, version, description).execute } describe '#execute' do context 'when model version exists' do it { is_expected.to be_success } it 'updates the model version description' do execute_service expect(execute_service.payload.description).to eq(description) end end context 'when description is invalid' do let(:description) { 'a' * 501 } it { is_expected.to be_error } end context 'when model does not exist' do let(:name) { 'a_new_model' } it { is_expected.to be_error } end context 'when model version does not exist' do let(:name) { '2.0.0' } it { is_expected.to be_error } end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml module ModelVersions class GetModelVersionService def initialize(project, name, version) @project = project @name = name @version = version end def execute Ml::ModelVersion.by_project_id_name_and_version( @project.id, @name, @version ) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Ml::ModelVersions::GetModelVersionService, feature_category: :mlops do let_it_be(:existing_version) { create(:ml_model_versions) } let_it_be(:another_project) { create(:project) } subject(:model_version) { described_class.new(project, name, version).execute } describe '#execute' do context 'when model version exists' do let(:name) { existing_version.name } let(:version) { existing_version.version } let(:project) { existing_version.project } it { is_expected.to eq(existing_version) } end context 'when model version does not exist' do let(:project) { existing_version.project } let(:name) { 'a_new_model' } let(:version) { '2.0.0' } it { is_expected.to be_nil } end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Ml module ModelVersions class DeleteService def initialize(project, name, version, user) @project = project @name = name @version = version @user = user end def execute model_version = Ml::ModelVersion .by_project_id_name_and_version(@project.id, @name, @version) return ServiceResponse.error(message: 'Model not found') unless model_version if model_version.package.present? result = ::Packages::MarkPackageForDestructionService .new(container: model_version.package, current_user: @user) .execute return ServiceResponse.error(message: result.message) unless result.success? end return ServiceResponse.error(message: 'Could not destroy the model version') unless model_version.destroy ServiceResponse.success end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Ml::ModelVersions::DeleteService, feature_category: :mlops do let_it_be(:valid_model_version) do create(:ml_model_versions, :with_package) end let(:project) { valid_model_version.project } let(:user) { valid_model_version.project.owner } let(:name) { valid_model_version.name } let(:version) { valid_model_version.version } subject(:execute_service) { described_class.new(project, name, version, user).execute } describe '#execute' do context 'when model version exists' do it 'deletes the model version', :aggregate_failures do expect(execute_service).to be_success expect(Ml::ModelVersion.find_by(id: valid_model_version.id)).to be_nil end end context 'when model version does not exist' do let(:version) { 'wrong-version' } it { is_expected.to be_error.and have_attributes(message: 'Model not found') } end context 'when model version has no package' do before do valid_model_version.update!(package: nil) end it 'does not trigger destroy package service', :aggregate_failures do expect(Packages::MarkPackageForDestructionService).not_to receive(:new) expect(execute_service).to be_success end end context 'when package cannot be marked for destruction' do before do allow_next_instance_of(Packages::MarkPackageForDestructionService) do |service| allow(service).to receive(:execute).and_return(ServiceResponse.error(message: 'error')) end end it 'does not delete the model version', :aggregate_failures do is_expected.to be_error.and have_attributes(message: 'error') expect(Ml::ModelVersion.find_by(id: valid_model_version.id)).to eq(valid_model_version) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DesignManagement class MoveDesignsService < DesignService # @param user [User] The current user # @param [Hash] params # @option params [DesignManagement::Design] :current_design # @option params [DesignManagement::Design] :previous_design (nil) # @option params [DesignManagement::Design] :next_design (nil) def initialize(user, params) super(nil, user, params.merge(issue: nil)) end def execute return error(:no_focus) unless current_design.present? return error(:cannot_move) unless current_user.can?(:move_design, current_design) return error(:no_neighbors) unless neighbors.present? return error(:not_distinct) unless all_distinct? return error(:not_same_issue) unless all_same_issue? move_nulls_to_end current_design.move_between(previous_design, next_design) current_design.save! success end def error(message) ServiceResponse.error(message: message) end def success ServiceResponse.success end private delegate :issue, :project, to: :current_design def move_nulls_to_end moved_records = current_design.class.move_nulls_to_end(issue.designs.in_creation_order) return if moved_records == 0 current_design.reset next_design&.reset previous_design&.reset end def neighbors [previous_design, next_design].compact end def all_distinct? ids.uniq.size == ids.size end def all_same_issue? issue.designs.id_in(ids).count == ids.size end def ids @ids ||= [current_design, *neighbors].map(&:id) end def current_design params[:current_design] end def previous_design params[:previous_design] end def next_design params[:next_design] end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DesignManagement::MoveDesignsService, feature_category: :design_management do include DesignManagementTestHelpers let_it_be(:issue) { create(:issue) } let_it_be(:developer) { create(:user, developer_projects: [issue.project]) } let_it_be(:designs) { create_list(:design, 3, :with_relative_position, issue: issue) } let(:project) { issue.project } let(:service) { described_class.new(current_user, params) } let(:params) do { current_design: current_design, previous_design: previous_design, next_design: next_design } end let(:current_user) { developer } let(:current_design) { nil } let(:previous_design) { nil } let(:next_design) { nil } before do enable_design_management end describe '#execute' do subject { service.execute } context 'the user cannot move designs' do let(:current_design) { designs.first } let(:current_user) { build_stubbed(:user) } it 'raises cannot_move' do expect(subject).to be_error.and(have_attributes(message: :cannot_move)) end end context 'the designs are not distinct' do let(:current_design) { designs.first } let(:previous_design) { designs.first } it 'raises not_distinct' do expect(subject).to be_error.and(have_attributes(message: :not_distinct)) end end context 'the designs are not on the same issue' do let(:current_design) { designs.first } let(:previous_design) { create(:design) } it 'raises not_same_issue' do expect(subject).to be_error.and(have_attributes(message: :not_same_issue)) end end context 'no focus is passed' do let(:previous_design) { designs.second } let(:next_design) { designs.third } it 'raises no_focus' do expect(subject).to be_error.and(have_attributes(message: :no_focus)) end end context 'no neighbours are passed' do let(:current_design) { designs.first } it 'raises no_neighbors' do expect(subject).to be_error.and(have_attributes(message: :no_neighbors)) end end context 'moving a design with neighbours' do let(:current_design) { designs.first } let(:previous_design) { designs.second } let(:next_design) { designs.third } it 'repositions existing designs and correctly places the given design' do other_design1 = create(:design, issue: issue, relative_position: 10) other_design2 = create(:design, issue: issue, relative_position: 20) other_design3, other_design4 = create_list(:design, 2, issue: issue) expect(subject).to be_success expect(issue.designs.ordered).to eq( [ # Existing designs which already had a relative_position set. # These should stay at the beginning, in the same order. other_design1, other_design2, # The designs we're passing into the service. # These should be placed between the existing designs, in the correct order. previous_design, current_design, next_design, # Existing designs which didn't have a relative_position set. # These should be placed at the end, in the order of their IDs. other_design3, other_design4 ]) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DesignManagement # Service class for counting and caching the number of unresolved # notes of a Design class DesignUserNotesCountService < ::BaseCountService # The version of the cache format. This should be bumped whenever the # underlying logic changes. This removes the need for explicitly flushing # all caches. VERSION = 1 def initialize(design) @design = design end def relation_for_count design.notes.user end def raw? # Since we're storing simple integers we don't need all of the # additional Marshal data Rails includes by default. true end def cache_key ['designs', 'notes_count', VERSION, design.id] end private attr_reader :design end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DesignManagement::DesignUserNotesCountService, :use_clean_rails_memory_store_caching, feature_category: :design_management do let_it_be(:design) { create(:design, :with_file) } subject { described_class.new(design) } it_behaves_like 'a counter caching service' describe '#count' do it 'returns the count of notes' do create_list(:diff_note_on_design, 3, noteable: design) expect(subject.count).to eq(3) end end describe '#cache_key' do it 'contains the `VERSION` and `design.id`' do expect(subject.cache_key).to eq(['designs', 'notes_count', DesignManagement::DesignUserNotesCountService::VERSION, design.id]) end end describe 'cache invalidation' do it 'changes when a new note is created' do new_note_attrs = attributes_for(:diff_note_on_design, noteable: design) expect do Notes::CreateService.new(design.project, create(:user), new_note_attrs).execute end.to change { subject.count }.by(1) end it 'changes when a note is destroyed' do note = create(:diff_note_on_design, noteable: design) expect do Notes::DestroyService.new(note.project, note.author).execute(note) end.to change { subject.count }.by(-1) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DesignManagement class SaveDesignsService < DesignService include RunsDesignActions include OnSuccessCallbacks MAX_FILES = 10 def initialize(project, user, params = {}) super @files = params.fetch(:files) end def execute return error("Not allowed!") unless can_create_designs? return error("Only #{MAX_FILES} files are allowed simultaneously") if files.size > MAX_FILES return error("Duplicate filenames are not allowed!") if files.map(&:original_filename).uniq.length != files.length return error("Design copy is in progress") if design_collection.copy_in_progress? uploaded_designs, version = upload_designs! skipped_designs = designs - uploaded_designs create_events design_collection.reset_copy! success({ designs: uploaded_designs, version: version, skipped_designs: skipped_designs }) rescue ::ActiveRecord::RecordInvalid => e error(e.message) end private attr_reader :files def upload_designs! ::DesignManagement::Version.with_lock(project.id, repository) do actions = build_actions [ actions.map(&:design), actions.presence && run_actions(actions) ] end end # Returns `Design` instances that correspond with `files`. # New `Design`s will be created where a file name does not match # an existing `Design` def designs @designs ||= files.map do |file| collection.find_or_create_design!(filename: file.original_filename) end end def build_actions @actions ||= files.zip(designs).flat_map do |(file, design)| Array.wrap(build_design_action(file, design)) end end def build_design_action(file, design) content = file_content(file, design.full_path) return if design_unchanged?(design, content) action = new_file?(design) ? :create : :update on_success do track_usage_metrics(action) end DesignManagement::DesignAction.new(design, action, content) end # Returns true if the design file is the same as its latest version def design_unchanged?(design, content) content == existing_blobs[design]&.data end def create_events by_action = @actions.group_by(&:action).transform_values { |grp| grp.map(&:design) } event_create_service.save_designs(current_user, **by_action) end def event_create_service @event_create_service ||= EventCreateService.new end def commit_message <<~MSG Updated #{files.size} #{'designs'.pluralize(files.size)} #{formatted_file_list} MSG end def formatted_file_list filenames.map { |name| "- #{name}" }.join("\n") end def filenames @filenames ||= files.map(&:original_filename) end def can_create_designs? Ability.allowed?(current_user, :create_design, issue) end def new_file?(design) !existing_blobs[design] end def file_content(file, full_path) transformer = ::Lfs::FileTransformer.new(project, repository, target_branch) transformer.new_file(full_path, file.to_io, detect_content_type: Feature.enabled?(:design_management_allow_dangerous_images, project)).content end # Returns the latest blobs for the designs as a Hash of `{ Design => Blob }` def existing_blobs @existing_blobs ||= begin items = designs.map { |d| [target_branch, d.full_path] } repository.blobs_at(items).each_with_object({}) do |blob, h| design = designs.find { |d| d.full_path == blob.path } h[design] = blob end end end def track_usage_metrics(action) if action == :update ::Gitlab::UsageDataCounters::IssueActivityUniqueCounter .track_issue_designs_modified_action(author: current_user, project: project) else ::Gitlab::UsageDataCounters::IssueActivityUniqueCounter .track_issue_designs_added_action(author: current_user, project: project) end ::Gitlab::UsageDataCounters::DesignsCounter.count(action) end end end DesignManagement::SaveDesignsService.prepend_mod_with('DesignManagement::SaveDesignsService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DesignManagement::SaveDesignsService, feature_category: :design_management do include DesignManagementTestHelpers include ConcurrentHelpers let_it_be_with_reload(:issue) { create(:issue) } let_it_be(:developer) { create(:user, developer_projects: [issue.project]) } let(:project) { issue.project } let(:user) { developer } let(:files) { [rails_sample] } let(:design_repository) { project.find_or_create_design_management_repository.repository } let(:rails_sample_name) { 'rails_sample.jpg' } let(:rails_sample) { sample_image(rails_sample_name) } let(:dk_png) { sample_image('dk.png') } def sample_image(filename) fixture_file_upload("spec/fixtures/#{filename}") end def commit_count design_repository.expire_statistics_caches design_repository.expire_root_ref_cache design_repository.commit_count end before do if issue.design_collection.repository.exists? issue.design_collection.repository.expire_all_method_caches issue.design_collection.repository.raw.delete_all_refs_except([Gitlab::Git::BLANK_SHA]) end allow(::DesignManagement::NewVersionWorker) .to receive(:perform_async).with(Integer, false).and_return(nil) end def run_service(files_to_upload = nil) design_files = files_to_upload || files design_files.each(&:rewind) service = described_class.new(project, user, issue: issue, files: design_files) service.execute end # Randomly alter the content of files. # This allows the files to be updated by the service, as unmodified # files are rejected. def touch_files(files_to_touch = nil) design_files = files_to_touch || files design_files.each do |f| f.tempfile.write(SecureRandom.random_bytes) end end let(:response) { run_service } shared_examples 'a service error' do it 'returns an error', :aggregate_failures do expect(response).to match(a_hash_including(status: :error)) end end shared_examples 'an execution error' do it 'returns an error', :aggregate_failures do expect { service.execute }.to raise_error(some_error) end end describe '#execute' do context 'when the feature is not available' do before do enable_design_management(false) end it_behaves_like 'a service error' it 'does not create an event in the activity stream' do expect { run_service }.not_to change { Event.count } end end context 'when the feature is available' do before do enable_design_management(true) end describe 'repository existence' do def repository_exists # Expire the memoized value as the service creates it's own instance design_repository.expire_exists_cache design_repository.exists? end it 'is ensured when the service runs' do run_service expect(repository_exists).to be true end end it 'creates a commit, an event in the activity stream and updates the creation count', :aggregate_failures do counter = Gitlab::UsageDataCounters::DesignsCounter expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_designs_added_action) .with(author: user, project: project) expect { run_service } .to change { Event.count }.by(1) .and change { Event.for_design.created_action.count }.by(1) .and change { counter.read(:create) }.by(1) expect(design_repository.commit).to have_attributes( author: user, message: include(rails_sample_name) ) end it_behaves_like 'internal event tracking' do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_DESIGNS_ADDED } let(:namespace) { project.namespace } subject(:service_action) { run_service } end it 'can run the same command in parallel' do parellism = 4 blocks = Array.new(parellism).map do unique_files = [RenameableUpload.unique_file('rails_sample.jpg')] -> { run_service(unique_files) } end expect { run_parallel(blocks) }.to change(DesignManagement::Version, :count).by(parellism) end context 'when the design collection is in the process of being copied', :clean_gitlab_redis_shared_state do before do issue.design_collection.start_copy! end it_behaves_like 'a service error' end context 'when the design collection has a copy error', :clean_gitlab_redis_shared_state do before do issue.design_collection.copy_state = 'error' issue.design_collection.send(:set_stored_copy_state!) end it 'resets the copy state' do expect { run_service }.to change { issue.design_collection.copy_state }.from('error').to('ready') end end describe 'the response' do it 'includes designs with the expected properties' do updated_designs = response[:designs] expect(updated_designs).to all(have_attributes(diff_refs: be_present)) expect(updated_designs.size).to eq(1) expect(updated_designs.first.versions.size).to eq(1) expect(updated_designs.first.versions.first.author).to eq(user) end end describe 'saving the file to LFS' do before do expect_next_instance_of(Lfs::FileTransformer) do |transformer| expect(transformer).to receive(:lfs_file?).and_return(true) end end it 'saves the design to LFS and saves the repository_type of the LfsObjectsProject as design' do expect { run_service } .to change { LfsObject.count }.by(1) .and change { project.lfs_objects_projects.count }.from(0).to(1) expect(project.lfs_objects_projects.first.repository_type).to eq('design') end end context 'when HEAD branch is different from master' do before do stub_feature_flags(main_branch_over_master: true) end it 'does not raise an exception during update' do run_service expect { run_service }.not_to raise_error end end context 'when a design is being updated' do before do run_service touch_files end it 'creates a new version for the existing design and updates the file' do expect(issue.designs.size).to eq(1) expect(DesignManagement::Version.for_designs(issue.designs).size).to eq(1) updated_designs = response[:designs] expect(updated_designs.size).to eq(1) expect(updated_designs.first.versions.size).to eq(2) end it 'updates UsageData for changed designs' do expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_designs_modified_action) .with(author: user, project: project) run_service end it_behaves_like 'internal event tracking' do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_DESIGNS_MODIFIED } let(:namespace) { project.namespace } subject(:service_action) { run_service } end it 'records the correct events' do counter = Gitlab::UsageDataCounters::DesignsCounter expect { run_service } .to change { counter.read(:update) }.by(1) .and change { Event.count }.by(1) .and change { Event.for_design.updated_action.count }.by(1) end context 'when uploading a new design' do it 'does not link the new version to the existing design' do existing_design = issue.designs.first updated_designs = run_service([dk_png])[:designs] expect(existing_design.versions.reload.size).to eq(1) expect(updated_designs.size).to eq(1) expect(updated_designs.first.versions.size).to eq(1) end end context 'when detecting content type' do it 'detects content type when feature flag is enabled' do expect_next_instance_of(::Lfs::FileTransformer) do |file_transformer| expect(file_transformer).to receive(:new_file) .with(anything, anything, hash_including(detect_content_type: true)).and_call_original end run_service end it 'skips content type detection when feature flag is disabled' do stub_feature_flags(design_management_allow_dangerous_images: false) expect_next_instance_of(::Lfs::FileTransformer) do |file_transformer| expect(file_transformer).to receive(:new_file) .with(anything, anything, hash_including(detect_content_type: false)).and_call_original end run_service end end end context 'when a design has not changed since its previous version' do before do run_service end it 'does not create a new version, and returns the design in `skipped_designs`' do response = nil expect { response = run_service }.not_to change { issue.design_versions.count } expect(response[:designs]).to be_empty expect(response[:skipped_designs].size).to eq(1) end end context 'when doing a mixture of updates and creations' do let(:files) { [rails_sample, dk_png] } before do # Create just the first one, which we will later update. run_service([files.first]) touch_files([files.first]) end it 'has the correct side-effects' do counter = Gitlab::UsageDataCounters::DesignsCounter expect(::DesignManagement::NewVersionWorker) .to receive(:perform_async).once.with(Integer, false).and_return(nil) expect { run_service } .to change { Event.count }.by(2) .and change { Event.for_design.count }.by(2) .and change { Event.created_action.count }.by(1) .and change { Event.updated_action.count }.by(1) .and change { counter.read(:create) }.by(1) .and change { counter.read(:update) }.by(1) .and change { commit_count }.by(1) end end context 'when uploading multiple files' do let(:files) { [rails_sample, dk_png] } it 'returns information about both designs in the response' do expect(response).to include(designs: have_attributes(size: 2), status: :success) end it 'has the correct side-effects', :request_store do counter = Gitlab::UsageDataCounters::DesignsCounter service = described_class.new(project, user, issue: issue, files: files) # Some unrelated calls that are usually cached or happen only once # We expect: # - An exists? # - a check for existing blobs # - default branch # - an after_commit callback on LfsObjectsProject design_repository.create_if_not_exists design_repository.has_visible_content? expect(::DesignManagement::NewVersionWorker) .to receive(:perform_async).once.with(Integer, false).and_return(nil) expect { service.execute } .to change { issue.designs.count }.from(0).to(2) .and change { DesignManagement::Version.count }.by(1) .and change { counter.read(:create) }.by(2) .and change { Gitlab::GitalyClient.get_request_count }.by(3) .and change { commit_count }.by(1) end context 'when uploading too many files' do let(:files) { Array.new(DesignManagement::SaveDesignsService::MAX_FILES + 1) { dk_png } } it 'returns the correct error' do expect(response[:message]).to match(/only \d+ files are allowed simultaneously/i) end end context 'when uploading duplicate files' do let(:files) { [rails_sample, dk_png, rails_sample] } it 'returns the correct error' do expect(response[:message]).to match('Duplicate filenames are not allowed!') end end end context 'when the user is not allowed to upload designs' do let(:user) { build_stubbed(:user, id: non_existing_record_id) } it_behaves_like 'a service error' end describe 'failure modes' do let(:service) { described_class.new(project, user, issue: issue, files: files) } let(:response) { service.execute } before do expect(service).to receive(:run_actions).and_raise(some_error) end context 'when creating the commit fails' do let(:some_error) { Gitlab::Git::BaseError } it_behaves_like 'an execution error' end context 'when creating the versions fails' do let(:some_error) { ActiveRecord::RecordInvalid } it_behaves_like 'a service error' end end context "when a design already existed in the repo but we didn't know about it in the database" do let(:filename) { rails_sample_name } before do path = File.join(build(:design, issue: issue, filename: filename).full_path) design_repository.create_if_not_exists design_repository.create_file( user, path, 'something fake', branch_name: project.default_branch_or_main, message: 'Somehow created without being tracked in db' ) end it 'creates the design and a new version for it' do first_updated_design = response[:designs].first expect(first_updated_design.filename).to eq(filename) expect(first_updated_design.versions.size).to eq(1) end end describe 'scalability', skip: 'See: https://gitlab.com/gitlab-org/gitlab/-/issues/213169' do before do run_service([sample_image('banana_sample.gif')]) # ensure project, issue, etc are created end it 'runs the same queries for all requests, regardless of number of files' do one = [dk_png] two = [rails_sample, dk_png] baseline = ActiveRecord::QueryRecorder.new { run_service(one) } expect { run_service(two) }.not_to exceed_query_limit(baseline) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DesignManagement class DeleteDesignsService < DesignService include RunsDesignActions include OnSuccessCallbacks def initialize(project, user, params = {}) super @designs = params.fetch(:designs) end def execute return error('Forbidden!') unless can_delete_designs? version = delete_designs! EventCreateService.new.destroy_designs(designs, current_user) Gitlab::UsageDataCounters::IssueActivityUniqueCounter.track_issue_designs_removed_action( author: current_user, project: project ) TodosDestroyer::DestroyedDesignsWorker.perform_async(designs.map(&:id)) success(version: version) end def commit_message n = designs.size <<~MSG Removed #{n} #{'designs'.pluralize(n)} #{formatted_file_list} MSG end private attr_reader :designs def delete_designs! DesignManagement::Version.with_lock(project.id, repository) do run_actions(build_actions) end end def can_delete_designs? Ability.allowed?(current_user, :destroy_design, issue) end def build_actions designs.map { |d| design_action(d) } end def design_action(design) on_success do counter.count(:delete) end DesignManagement::DesignAction.new(design, :delete) end def counter ::Gitlab::UsageDataCounters::DesignsCounter end def formatted_file_list designs.map { |design| "- #{design.full_path}" }.join("\n") end end end DesignManagement::DeleteDesignsService.prepend_mod_with('DesignManagement::DeleteDesignsService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DesignManagement::DeleteDesignsService, feature_category: :design_management do include DesignManagementTestHelpers let_it_be(:project) { create(:project) } let_it_be(:issue) { create(:issue, project: project) } let_it_be(:user) { create(:user) } let(:designs) { create_designs } subject(:service) { described_class.new(project, user, issue: issue, designs: designs) } # Defined as a method so that the response is not cached. We also construct # a new service executor each time to avoid the intermediate cached values # it constructs during its execution. def run_service(delenda = nil) service = described_class.new(project, user, issue: issue, designs: delenda || designs) service.execute end let(:response) { run_service } shared_examples 'a service error' do it 'returns an error', :aggregate_failures do expect(response).to include(status: :error) end end shared_examples 'a top-level error' do let(:expected_error) { StandardError } it 'raises an en expected error', :aggregate_failures do expect { run_service }.to raise_error(expected_error) end end shared_examples 'a success' do it 'returns successfully', :aggregate_failures do expect(response).to include(status: :success) end it 'saves the user as the author' do version = response[:version] expect(version.author).to eq(user) end end before do enable_design_management(enabled) project.add_developer(user) end describe "#execute" do context "when the feature is not available" do let(:enabled) { false } it_behaves_like "a service error" it 'does not create any events in the activity stream' do expect do run_service rescue StandardError nil end.not_to change { Event.count } end end context "when the feature is available" do let(:enabled) { true } it 'is able to delete designs' do expect(service.send(:can_delete_designs?)).to be true end context 'no designs were passed' do let(:designs) { [] } it_behaves_like "a top-level error" it 'does not log any events' do counter = ::Gitlab::UsageDataCounters::DesignsCounter expect do run_service rescue StandardError nil end .not_to change { [counter.totals, Event.count] } end it 'does not log any UsageData metrics' do redis_hll = ::Gitlab::UsageDataCounters::HLLRedisCounter event = Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_DESIGNS_REMOVED expect do run_service rescue StandardError nil end .not_to change { redis_hll.unique_events(event_names: event, start_date: Date.today, end_date: 1.week.from_now) } begin run_service rescue StandardError nil end end end context 'one design is passed' do before do create_designs(2) end let!(:designs) { create_designs(1) } it 'removes that design' do expect { run_service }.to change { issue.designs.current.count }.from(3).to(2) end it 'logs a deletion event' do counter = ::Gitlab::UsageDataCounters::DesignsCounter expect { run_service }.to change { counter.read(:delete) }.by(1) end it 'updates UsageData for removed designs' do expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_designs_removed_action) .with(author: user, project: project) run_service end it 'creates an event in the activity stream' do expect { run_service } .to change { Event.count }.by(1) .and change { Event.destroyed_action.for_design.count }.by(1) end it 'informs the new-version-worker' do expect(::DesignManagement::NewVersionWorker).to receive(:perform_async).with(Integer, false) run_service end it 'creates a new version' do expect { run_service }.to change { DesignManagement::Version.where(issue: issue).count }.by(1) end it 'returns the new version' do version = response[:version] expect(version).to eq(DesignManagement::Version.for_issue(issue).ordered.first) end it_behaves_like "a success" it 'removes the design from the current design list' do run_service expect(issue.designs.current).not_to include(designs.first) end it 'marks the design as deleted' do expect { run_service } .to change { designs.first.deleted? }.from(false).to(true) end it 'schedules deleting todos for that design' do expect(TodosDestroyer::DestroyedDesignsWorker).to receive(:perform_async).with([designs.first.id]) run_service end it_behaves_like 'internal event tracking' do let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_DESIGNS_REMOVED } let(:namespace) { project.namespace } subject(:service_action) { run_service } end end context 'more than one design is passed' do before do create_designs(1) end let!(:designs) { create_designs(2) } it 'makes the correct changes' do counter = ::Gitlab::UsageDataCounters::DesignsCounter expect { run_service } .to change { issue.designs.current.count }.from(3).to(1) .and change { counter.read(:delete) }.by(2) .and change { Event.count }.by(2) .and change { Event.destroyed_action.for_design.count }.by(2) end it 'schedules deleting todos for that design' do expect(TodosDestroyer::DestroyedDesignsWorker).to receive(:perform_async).with(designs.map(&:id)) run_service end it_behaves_like "a success" context 'after executing the service' do let(:deleted_designs) { designs.map(&:reset) } let!(:version) { run_service[:version] } it 'removes the removed designs from the current design list' do expect(issue.designs.current).not_to include(*deleted_designs) end it 'does not make the designs impossible to find' do expect(issue.designs).to include(*deleted_designs) end it 'associates the new version with all the designs' do current_versions = deleted_designs.map { |d| d.most_recent_action.version } expect(current_versions).to all(eq version) end it 'marks all deleted designs as deleted' do expect(deleted_designs).to all(be_deleted) end it 'marks all deleted designs with the same deletion version' do expect(deleted_designs.map { |d| d.most_recent_action.version_id }.uniq) .to have_attributes(size: 1) end end end describe 'scalability' do before do run_service(create_designs(1)) # ensure project, issue, etc are created end it 'makes the same number of DB requests for one design as for several' do one = create_designs(1) many = create_designs(5) baseline = ActiveRecord::QueryRecorder.new { run_service(one) } expect { run_service(many) }.not_to exceed_query_limit(baseline) end end end end private def create_designs(how_many = 2) create_list(:design, how_many, :with_lfs_file, issue: issue) end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module DesignManagement # This service generates smaller image versions for `DesignManagement::Design` # records within a given `DesignManagement::Version`. class GenerateImageVersionsService < DesignService # We limit processing to only designs with file sizes that don't # exceed `MAX_DESIGN_SIZE`. # # Note, we may be able to remove checking this limit, if when we come to # implement a file size limit for designs, there are no designs that # exceed 40MB on GitLab.com # # See https://gitlab.com/gitlab-org/gitlab/-/merge_requests/22860#note_281780387 MAX_DESIGN_SIZE = 40.megabytes.freeze def initialize(version) super(version.project, version.author, issue: version.issue) @version = version end def execute # rubocop: disable CodeReuse/ActiveRecord version.actions.includes(:design).each do |action| generate_image(action) end # rubocop: enable CodeReuse/ActiveRecord success(version: version) end private attr_reader :version def generate_image(action) raw_file = get_raw_file(action) unless raw_file log_error("No design file found for Action: #{action.id}") return end # Skip attempting to process images that would be rejected by CarrierWave. return unless DesignManagement::DesignV432x230Uploader::MIME_TYPE_ALLOWLIST.include?(raw_file.content_type) # Store and process the file action.image_v432x230.store!(raw_file) action.save! rescue CarrierWave::IntegrityError => e Gitlab::ErrorTracking.log_exception(e, project_id: project.id, design_id: action.design_id, version_id: action.version_id) log_error(e.message) rescue CarrierWave::UploadError => e Gitlab::ErrorTracking.track_exception(e, project_id: project.id, design_id: action.design_id, version_id: action.version_id) log_error(e.message) end # Returns the `CarrierWave::SanitizedFile` of the original design file def get_raw_file(action) raw_files_by_path[action.design.full_path] end # Returns the `Carrierwave:SanitizedFile` instances for all of the original # design files, mapping to { design.filename => `Carrierwave::SanitizedFile` }. # # As design files are stored in Git LFS, the only way to retrieve their original # files is to first fetch the LFS pointer file data from the Git design repository. # The LFS pointer file data contains an "OID" that lets us retrieve `LfsObject` # records, which have an Uploader (`LfsObjectUploader`) for the original design file. def raw_files_by_path @raw_files_by_path ||= LfsObject.for_oids(blobs_by_oid.keys).each_with_object({}) do |lfs_object, h| blob = blobs_by_oid[lfs_object.oid] file = lfs_object.file.file # The `CarrierWave::SanitizedFile` is loaded without knowing the `content_type` # of the file, due to the file not having an extension. # # Set the content_type from the `Blob`. file.content_type = blob.content_type h[blob.path] = file end end # Returns the `Blob`s that correspond to the design files in the repository. # # All design `Blob`s are LFS Pointer files, and are therefore small amounts # of data to load. # # `Blob`s whose size are above a certain threshold: `MAX_DESIGN_SIZE` # are filtered out. def blobs_by_oid @blobs ||= begin items = version.designs.map { |design| [version.sha, design.full_path] } blobs = repository.blobs_at(items) blobs.reject! { |blob| blob.lfs_size > MAX_DESIGN_SIZE } blobs.index_by(&:lfs_oid) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DesignManagement::GenerateImageVersionsService, feature_category: :design_management do let_it_be(:project) { create(:project) } let_it_be(:issue) { create(:issue, project: project) } let_it_be(:version) { create(:design, :with_lfs_file, issue: issue).versions.first } let_it_be(:action) { version.actions.first } describe '#execute' do it 'generates the image' do expect { described_class.new(version).execute } .to change { action.reload.image_v432x230.file } .from(nil).to(CarrierWave::SanitizedFile) end it 'skips generating image versions if the mime type is not allowlisted' do stub_const('DesignManagement::DesignV432x230Uploader::MIME_TYPE_ALLOWLIST', []) described_class.new(version).execute expect(action.reload.image_v432x230.file).to eq(nil) end it 'skips generating image versions if the design file size is too large' do stub_const("#{described_class.name}::MAX_DESIGN_SIZE", 1.byte) described_class.new(version).execute expect(action.reload.image_v432x230.file).to eq(nil) end it 'returns the status' do result = described_class.new(version).execute expect(result[:status]).to eq(:success) end it 'returns the version' do result = described_class.new(version).execute expect(result[:version]).to eq(version) end it 'logs if the raw image cannot be found' do version.designs.first.update!(filename: 'foo.png') expect(Gitlab::AppLogger).to receive(:error).with("No design file found for Action: #{action.id}") described_class.new(version).execute end context 'when an error is encountered when generating the image versions' do context "CarrierWave::IntegrityError" do before do expect_next_instance_of(DesignManagement::DesignV432x230Uploader) do |uploader| expect(uploader).to receive(:cache!).and_raise(CarrierWave::IntegrityError, 'foo') end end it 'logs the exception' do expect(Gitlab::ErrorTracking).to receive(:log_exception).with( instance_of(CarrierWave::IntegrityError), project_id: project.id, version_id: version.id, design_id: version.designs.first.id ) described_class.new(version).execute end it 'logs the error' do expect(Gitlab::AppLogger).to receive(:error).with('foo') described_class.new(version).execute end end context "CarrierWave::UploadError" do before do expect_next_instance_of(DesignManagement::DesignV432x230Uploader) do |uploader| expect(uploader).to receive(:cache!).and_raise(CarrierWave::UploadError, 'foo') end end it 'logs the error' do expect(Gitlab::AppLogger).to receive(:error).with('foo') described_class.new(version).execute end it 'tracks the error' do expect(Gitlab::ErrorTracking).to receive(:track_exception).with( instance_of(CarrierWave::UploadError), project_id: project.id, version_id: version.id, design_id: version.designs.first.id ) described_class.new(version).execute end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Service to copy a DesignCollection from one Issue to another. # Copies the DesignCollection's Designs, Versions, and Notes on Designs. module DesignManagement module CopyDesignCollection class CopyService < DesignService # rubocop: disable CodeReuse/ActiveRecord def initialize(project, user, params = {}) super @target_issue = params.fetch(:target_issue) @target_project = @target_issue.project @target_repository = @target_project.design_repository @target_design_collection = @target_issue.design_collection @temporary_branch = "CopyDesignCollectionService_#{SecureRandom.hex}" # The user who triggered the copy may not have permissions to push # to the design repository. @git_user = @target_project.first_owner @designs = DesignManagement::Design.unscoped.where(issue: issue).order(:id).load @versions = DesignManagement::Version.unscoped.where(issue: issue).order(:id).includes(:designs).load @sha_attribute = Gitlab::Database::ShaAttribute.new @shas = [] @event_enum_map = DesignManagement::DesignAction::EVENT_FOR_GITALY_ACTION.invert end # rubocop: enable CodeReuse/ActiveRecord def execute return error('User cannot copy design collection to issue') unless user_can_copy? return error('Target design collection must first be queued') unless target_design_collection.copy_in_progress? return error('Design collection has no designs') if designs.empty? return error('Target design collection already has designs') unless target_design_collection.empty? with_temporary_branch do copy_commits! ApplicationRecord.transaction do design_ids = copy_designs! version_ids = copy_versions! copy_actions!(design_ids, version_ids) link_lfs_files! copy_notes!(design_ids) finalize! end end ServiceResponse.success rescue StandardError => error log_exception(error) target_design_collection.error_copy! error('Designs were unable to be copied successfully') end private attr_reader :designs, :event_enum_map, :git_user, :sha_attribute, :shas, :temporary_branch, :target_design_collection, :target_issue, :target_repository, :target_project, :versions alias_method :merge_branch, :target_branch def log_exception(exception) payload = { issue_id: issue.id, project_id: project.id, target_issue_id: target_issue.id, target_project: target_project.id } Gitlab::ErrorTracking.track_exception(exception, payload) end def error(message) ServiceResponse.error(message: message) end def user_can_copy? current_user.can?(:read_design, design_collection) && current_user.can?(:admin_issue, target_issue) end def with_temporary_branch(&block) target_repository.create_if_not_exists create_default_branch! if target_repository.empty? create_temporary_branch! yield ensure remove_temporary_branch! end # A project that does not have any designs will have a blank design # repository. To create a temporary branch from default branch we need to # create default branch first by adding a file to it. def create_default_branch! target_repository.create_file( git_user, ".CopyDesignCollectionService_#{Time.now.to_i}", '.gitlab', message: "Commit to create #{merge_branch} branch in CopyDesignCollectionService", branch_name: merge_branch ) end def create_temporary_branch! target_repository.add_branch( git_user, temporary_branch, target_repository.root_ref ) end def remove_temporary_branch! return unless target_repository.branch_exists?(temporary_branch) target_repository.rm_branch(git_user, temporary_branch) end # Merge the temporary branch containing the commits to default branch # and update the state of the target_design_collection. def finalize! source_sha = shas.last target_repository.raw.merge( git_user, source_sha: source_sha, target_branch: merge_branch, message: 'CopyDesignCollectionService finalize merge' ) { nil } target_design_collection.end_copy! end # rubocop: disable CodeReuse/ActiveRecord def copy_commits! # Execute another query to include actions and their designs DesignManagement::Version.unscoped.where(id: versions).order(:id).includes(actions: :design).find_each(batch_size: 100) do |version| gitaly_actions = version.actions.map do |action| design = action.design # Map the raw Action#event enum value to a Gitaly "action" for the # `Repository#commit_files` call. gitaly_action_name = @event_enum_map[action.event_before_type_cast] # `content` will be the LfsPointer file and not the design file, # and can be nil for deletions. content = blobs.dig(version.sha, design.filename)&.data file_path = DesignManagement::Design.build_full_path(target_issue, design) { action: gitaly_action_name, file_path: file_path, content: content }.compact end sha = target_repository.commit_files( git_user, branch_name: temporary_branch, message: commit_message(version), actions: gitaly_actions ) shas << sha end end # rubocop: enable CodeReuse/ActiveRecord def copy_designs! design_attributes = attributes_config[:design_attributes] ::DesignManagement::Design.with_project_iid_supply(target_project) do |supply| new_rows = designs.each_with_index.map do |design, i| design.attributes.slice(*design_attributes).merge( issue_id: target_issue.id, project_id: target_project.id, iid: supply.next_value ) end # TODO Replace `ApplicationRecord.legacy_bulk_insert` with `BulkInsertSafe` # once https://gitlab.com/gitlab-org/gitlab/-/issues/247718 is fixed. # When this is fixed, we can remove the call to # `with_project_iid_supply` above, since the objects will be instantiated # and callbacks (including `ensure_project_iid!`) will fire. ::ApplicationRecord.legacy_bulk_insert( # rubocop:disable Gitlab/BulkInsert DesignManagement::Design.table_name, new_rows, return_ids: true ) end end def copy_versions! version_attributes = attributes_config[:version_attributes] # `shas` are the list of Git commits made during the Git copy phase, # and will be ordered 1:1 with old versions shas_enum = shas.to_enum new_rows = versions.map do |version| version.attributes.slice(*version_attributes).merge( issue_id: target_issue.id, sha: sha_attribute.serialize(shas_enum.next) ) end # TODO Replace `ApplicationRecord.legacy_bulk_insert` with `BulkInsertSafe` # once https://gitlab.com/gitlab-org/gitlab/-/issues/247718 is fixed. ::ApplicationRecord.legacy_bulk_insert( # rubocop:disable Gitlab/BulkInsert DesignManagement::Version.table_name, new_rows, return_ids: true ) end # rubocop: disable CodeReuse/ActiveRecord def copy_actions!(new_design_ids, new_version_ids) # Create a map of <Old design id> => <New design id> design_id_map = new_design_ids.each_with_index.to_h do |design_id, i| [designs[i].id, design_id] end # Create a map of <Old version id> => <New version id> version_id_map = new_version_ids.each_with_index.to_h do |version_id, i| [versions[i].id, version_id] end actions = DesignManagement::Action.unscoped.select(:design_id, :version_id, :event).where(design: designs, version: versions) new_rows = actions.map do |action| { design_id: design_id_map[action.design_id], version_id: version_id_map[action.version_id], event: action.event_before_type_cast } end # We cannot use `BulkInsertSafe` because of the uploader mounted in `Action`. ::ApplicationRecord.legacy_bulk_insert( # rubocop:disable Gitlab/BulkInsert DesignManagement::Action.table_name, new_rows ) end # rubocop: enable CodeReuse/ActiveRecord def commit_message(version) "Copy commit #{version.sha} from issue #{issue.to_reference(full: true)}" end # rubocop: disable CodeReuse/ActiveRecord def copy_notes!(design_ids) new_designs = DesignManagement::Design.unscoped.find(design_ids) # Execute another query to filter only designs with notes DesignManagement::Design.unscoped.where(id: designs).joins(:notes).distinct.find_each(batch_size: 100) do |old_design| new_design = new_designs.find { |d| d.filename == old_design.filename } Notes::CopyService.new(current_user, old_design, new_design).execute end end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def link_lfs_files! oids = blobs.values.flat_map(&:values).map(&:lfs_oid) repository_type = LfsObjectsProject.repository_types[:design] new_rows = LfsObject.where(oid: oids).find_each(batch_size: 1000).map do |lfs_object| { project_id: target_project.id, lfs_object_id: lfs_object.id, repository_type: repository_type } end # We cannot use `BulkInsertSafe` due to the LfsObjectsProject#update_project_statistics # callback that fires after_commit. ::ApplicationRecord.legacy_bulk_insert( # rubocop:disable Gitlab/BulkInsert LfsObjectsProject.table_name, new_rows, on_conflict: :do_nothing # Upsert ) end # rubocop: enable CodeReuse/ActiveRecord # Blob data is used to find the oids for LfsObjects and to copy to Git. # Blobs are reasonably small in memory, as their data are LFS Pointer files. # # Returns all blobs for the designs as a Hash of `{ Blob#commit_id => { Design#filename => Blob } }` def blobs @blobs ||= begin items = versions.flat_map { |v| v.designs.map { |d| [v.sha, DesignManagement::Design.build_full_path(issue, d)] } } repository.blobs_at(items).each_with_object({}) do |blob, h| design = designs.find { |d| DesignManagement::Design.build_full_path(issue, d) == blob.path } h[blob.commit_id] ||= {} h[blob.commit_id][design.filename] = blob end end end def attributes_config @attributes_config ||= YAML.load_file(attributes_config_file).symbolize_keys end def attributes_config_file Rails.root.join('lib/gitlab/design_management/copy_design_collection_model_attributes.yml') end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DesignManagement::CopyDesignCollection::CopyService, :clean_gitlab_redis_shared_state, feature_category: :portfolio_management do include DesignManagementTestHelpers let_it_be(:user) { create(:user) } let_it_be(:project) { create(:project) } let_it_be(:issue, refind: true) { create(:issue, project: project) } let(:target_issue) { create(:issue) } subject { described_class.new(project, user, issue: issue, target_issue: target_issue).execute } before do enable_design_management end shared_examples 'service error' do |message:| it 'returns an error response', :aggregate_failures do expect(subject).to be_kind_of(ServiceResponse) expect(subject).to be_error expect(subject.message).to eq(message) end end shared_examples 'service success' do it 'returns a success response', :aggregate_failures do expect(subject).to be_kind_of(ServiceResponse) expect(subject).to be_success end end include_examples 'service error', message: 'User cannot copy design collection to issue' context 'when user has permission to read the design collection' do before_all do project.add_reporter(user) end include_examples 'service error', message: 'User cannot copy design collection to issue' context 'when the user also has permission to admin the target issue' do let(:target_repository) { target_issue.project.design_repository } before do target_issue.project.add_reporter(user) end include_examples 'service error', message: 'Target design collection must first be queued' context 'when the target design collection has been queued' do before do target_issue.design_collection.start_copy! end include_examples 'service error', message: 'Design collection has no designs' context 'when design collection has designs' do let_it_be(:designs) do create_list(:design, 3, :with_lfs_file, :with_relative_position, issue: issue, project: project) end context 'when target issue already has designs' do before do create(:design, issue: target_issue, project: target_issue.project) end include_examples 'service error', message: 'Target design collection already has designs' end context 'when target project already has designs' do let!(:issue_x) { create(:issue, project: target_issue.project) } let!(:existing) { create(:design, issue: issue_x, project: target_issue.project) } let(:new_designs) do target_issue.reset target_issue.designs.where.not(id: existing.id) end it 'sets IIDs for new designs above existing ones' do subject expect(new_designs).to all(have_attributes(iid: (be > existing.iid))) end it 'does not allow for IID collisions' do subject create(:design, issue: issue_x, project: target_issue.project) design_iids = target_issue.project.designs.map(&:id) expect(design_iids).to match_array(design_iids.uniq) end end include_examples 'service success' it 'creates a design repository for the target project' do expect { subject }.to change { target_repository.exists? }.from(false).to(true) end context 'when the target project already has a design repository' do before do target_repository.create_if_not_exists end include_examples 'service success' end it 'copies the designs correctly', :aggregate_failures do expect { subject }.to change { target_issue.designs.count }.by(3) old_designs = issue.designs.ordered new_designs = target_issue.designs.ordered new_designs.zip(old_designs).each do |new_design, old_design| expect(new_design).to have_attributes( filename: old_design.filename, description: old_design.description, relative_position: old_design.relative_position, issue: target_issue, project: target_issue.project ) end end it 'copies the design versions correctly', :aggregate_failures do expect { subject }.to change { target_issue.design_versions.count }.by(3) old_versions = issue.design_versions.ordered new_versions = target_issue.design_versions.ordered new_versions.zip(old_versions).each do |new_version, old_version| expect(new_version).to have_attributes( created_at: old_version.created_at, author_id: old_version.author_id ) expect(new_version.designs.pluck(:filename)).to eq(old_version.designs.pluck(:filename)) expect(new_version.actions.pluck(:event)).to eq(old_version.actions.pluck(:event)) end end it 'copies the design actions correctly', :aggregate_failures do expect { subject }.to change { DesignManagement::Action.count }.by(3) old_actions = issue.design_versions.ordered.flat_map(&:actions) new_actions = target_issue.design_versions.ordered.flat_map(&:actions) new_actions.zip(old_actions).each do |new_action, old_action| # This is a way to identify if the versions linked to the actions # are correct is to compare design filenames, as the SHA changes. new_design_filenames = new_action.version.designs.ordered.pluck(:filename) old_design_filenames = old_action.version.designs.ordered.pluck(:filename) expect(new_design_filenames).to eq(old_design_filenames) expect(new_action.event).to eq(old_action.event) expect(new_action.design.filename).to eq(old_action.design.filename) end end it 'copies design notes correctly', :aggregate_failures, :sidekiq_inline do old_notes = [ create(:diff_note_on_design, note: 'first note', noteable: designs.first, project: project, author: create(:user)), create(:diff_note_on_design, note: 'second note', noteable: designs.first, project: project, author: create(:user)) ] matchers = old_notes.map do |note| have_attributes( note.attributes.slice( :type, :author_id, :note, :position ) ) end expect { subject }.to change { Note.count }.by(2) new_notes = target_issue.designs.first.notes.fresh expect(new_notes).to match_array(matchers) end it 'links the LfsObjects' do expect { subject }.to change { target_issue.project.lfs_objects.count }.by(3) end it 'copies the Git repository data', :aggregate_failures do subject expect(commits_on_master(limit: 99)).to include(*target_issue.design_versions.ordered.pluck(:sha)) end it 'creates a default branch if none previously existed' do expect { subject }.to change { target_repository.branch_names }.from([]).to([project.design_repository.root_ref]) end it 'does not create default branch when one exists' do target_repository.create_if_not_exists target_repository.create_file(user, '.meta', '.gitlab', branch_name: 'new-branch', message: 'message') expect { subject }.not_to change { target_repository.branch_names } expect(target_repository.branch_names).to eq(['new-branch']) end it 'leaves the design collection in the correct copy state' do subject expect(target_issue.design_collection).to be_copy_ready end describe 'rollback' do before do # Ensure the very last step throws an error expect_next_instance_of(described_class) do |service| expect(service).to receive(:finalize!).and_raise end end include_examples 'service error', message: 'Designs were unable to be copied successfully' it 'rollsback all PostgreSQL data created', :aggregate_failures do expect { subject }.not_to change { [ DesignManagement::Design.count, DesignManagement::Action.count, DesignManagement::Version.count, Note.count ] } collections = [ target_issue.design_collection, target_issue.designs, target_issue.design_versions ] expect(collections).to all(be_empty) end it 'does not alter master branch', :aggregate_failures do # Add some Git data to the target_repository, so we are testing # that any original data remains issue_2 = create(:issue, project: target_issue.project) create(:design, :with_file, issue: issue_2, project: target_issue.project) expect { subject }.not_to change { commits_on_master } end it 'sets the design collection copy state' do subject expect(target_issue.design_collection).to be_copy_error end end def commits_on_master(limit: 10) target_repository.commits(target_repository.root_ref, limit: limit).map(&:id) end end end end end describe 'Alert if schema changes', :aggregate_failures do let_it_be(:config_file) { Rails.root.join('lib/gitlab/design_management/copy_design_collection_model_attributes.yml') } let_it_be(:config) { YAML.load_file(config_file).symbolize_keys } %w[Design Action Version].each do |model| specify do attributes = config["#{model.downcase}_attributes".to_sym] || [] ignored_attributes = config["ignore_#{model.downcase}_attributes".to_sym] expect(attributes + ignored_attributes).to contain_exactly( *DesignManagement.const_get(model, false).column_names ), failure_message(model) end end def failure_message(model) <<-MSG The schema of the `#{model}` model has changed. `#{described_class.name}` refers to specific lists of attributes of `#{model}` to either copy or ignore, so that we continue to copy designs correctly after schema changes. Please update: #{config_file} to reflect the latest changes to `#{model}`. See that file for more information. MSG end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Service for setting the initial copy_state on the target DesignCollection # and queuing a CopyDesignCollectionWorker. module DesignManagement module CopyDesignCollection class QueueService def initialize(current_user, issue, target_issue) @current_user = current_user @issue = issue @target_issue = target_issue @target_design_collection = target_issue.design_collection end def execute return error('User cannot copy designs to issue') unless user_can_copy? return error('Target design collection copy state must be `ready`') unless target_design_collection.can_start_copy? target_design_collection.start_copy! DesignManagement::CopyDesignCollectionWorker.perform_async(current_user.id, issue.id, target_issue.id) ServiceResponse.success end private delegate :design_collection, to: :issue attr_reader :current_user, :issue, :target_design_collection, :target_issue def error(message) ServiceResponse.error(message: message) end def user_can_copy? current_user.can?(:read_design, issue) && current_user.can?(:admin_issue, target_issue) end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe DesignManagement::CopyDesignCollection::QueueService, :clean_gitlab_redis_shared_state, feature_category: :design_management do include DesignManagementTestHelpers let_it_be(:user) { create(:user) } let_it_be(:issue) { create(:issue) } let_it_be(:target_issue, refind: true) { create(:issue) } let_it_be(:design) { create(:design, issue: issue, project: issue.project) } subject { described_class.new(user, issue, target_issue).execute } before do enable_design_management end it 'returns an error if user does not have permission' do expect(subject).to be_kind_of(ServiceResponse) expect(subject).to be_error expect(subject.message).to eq('User cannot copy designs to issue') end context 'when user has permission' do before_all do issue.project.add_reporter(user) target_issue.project.add_reporter(user) end it 'returns an error if design collection copy_state is not queuable' do target_issue.design_collection.start_copy! expect(subject).to be_kind_of(ServiceResponse) expect(subject).to be_error expect(subject.message).to eq('Target design collection copy state must be `ready`') end it 'sets the design collection copy state' do expect { subject }.to change { target_issue.design_collection.copy_state }.from('ready').to('in_progress') end it 'queues a DesignManagement::CopyDesignCollectionWorker', :clean_gitlab_redis_queues do expect { subject }.to change(DesignManagement::CopyDesignCollectionWorker.jobs, :size).by(1) end it 'returns success' do expect(subject).to be_kind_of(ServiceResponse) expect(subject).to be_success end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module UserPreferences class UpdateService < BaseService def initialize(user, params = {}) @preferences = user.user_preference @params = params.to_h.dup.with_indifferent_access end def execute if @preferences.update(@params) ServiceResponse.success( message: 'Preference was updated', payload: { preferences: @preferences }) else ServiceResponse.error(message: 'Could not update preference') end end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe UserPreferences::UpdateService, feature_category: :user_profile do let(:user) { create(:user) } let(:params) { { view_diffs_file_by_file: false, pass_user_identities_to_ci_jwt: true } } describe '#execute' do subject(:service) { described_class.new(user, params) } context 'successfully updating the record' do it 'updates the preference and returns a success' do result = service.execute expect(result.status).to eq(:success) expect(result.payload[:preferences].view_diffs_file_by_file).to eq(params[:view_diffs_file_by_file]) expect(result.payload[:preferences].pass_user_identities_to_ci_jwt ).to eq(params[:pass_user_identities_to_ci_jwt]) end end context 'unsuccessfully updating the record' do before do allow(user.user_preference).to receive(:update).and_return(false) end it 'returns an error' do result = service.execute expect(result.status).to eq(:error) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class ValidateManualOtpService < BaseService include ::Gitlab::Auth::Otp::Fortinet include ::Gitlab::Auth::Otp::DuoAuth def initialize(current_user) @current_user = current_user @strategy = if forti_authenticator_enabled?(current_user) ::Gitlab::Auth::Otp::Strategies::FortiAuthenticator::ManualOtp.new(current_user) elsif forti_token_cloud_enabled?(current_user) ::Gitlab::Auth::Otp::Strategies::FortiTokenCloud.new(current_user) elsif duo_auth_enabled?(current_user) ::Gitlab::Auth::Otp::Strategies::DuoAuth::ManualOtp.new(current_user) else ::Gitlab::Auth::Otp::Strategies::Devise.new(current_user) end end def execute(otp_code) strategy.validate(otp_code) rescue StandardError => ex Gitlab::ErrorTracking.log_exception(ex) error(ex.message) end private attr_reader :strategy end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::ValidateManualOtpService, feature_category: :user_profile do let_it_be(:user) { create(:user) } let(:otp_code) { 42 } subject(:validate) { described_class.new(user).execute(otp_code) } context 'Devise' do it 'calls Devise strategy' do expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::Devise) do |strategy| expect(strategy).to receive(:validate).with(otp_code).once end validate end end context 'FortiAuthenticator' do before do stub_feature_flags(forti_authenticator: user) allow(::Gitlab.config.forti_authenticator).to receive(:enabled).and_return(true) end it 'calls ManualOtp strategy' do expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::FortiAuthenticator::ManualOtp) do |strategy| expect(strategy).to receive(:validate).with(otp_code).once end validate end it 'handles unexpected error' do error_message = "boom!" expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::FortiAuthenticator::ManualOtp) do |strategy| expect(strategy).to receive(:validate).with(otp_code).once.and_raise(StandardError, error_message) end expect(Gitlab::ErrorTracking).to receive(:log_exception) result = validate expect(result[:status]).to eq(:error) expect(result[:message]).to eq(error_message) end end context 'FortiTokenCloud' do before do stub_feature_flags(forti_token_cloud: user) allow(::Gitlab.config.forti_token_cloud).to receive(:enabled).and_return(true) end it 'calls FortiTokenCloud strategy' do expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::FortiTokenCloud) do |strategy| expect(strategy).to receive(:validate).with(otp_code).once end validate end end context 'DuoAuth' do before do allow(::Gitlab.config.duo_auth).to receive(:enabled).and_return(true) end it 'calls DuoAuth strategy' do expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::DuoAuth::ManualOtp) do |strategy| expect(strategy).to receive(:validate).with(otp_code).once end validate end it "handles unexpected error" do error_message = "boom!" expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::DuoAuth::ManualOtp) do |strategy| expect(strategy).to receive(:validate).with(otp_code).once.and_raise(StandardError, error_message) end expect(Gitlab::ErrorTracking).to receive(:log_exception) result = validate expect(result[:status]).to eq(:error) expect(result[:message]).to eq(error_message) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class ActivityService LEASE_TIMEOUT = 1.minute.to_i def initialize(author:, namespace: nil, project: nil) @user = if author.respond_to?(:username) author elsif author.respond_to?(:user) author.user end @user = nil unless user.is_a?(User) @namespace = namespace @project = project end def execute return unless user ::Gitlab::Database::LoadBalancing::Session.without_sticky_writes { record_activity } end private attr_reader :user, :namespace, :project def record_activity return if Gitlab::Database.read_only? today = Date.today return if user.last_activity_on == today lease = Gitlab::ExclusiveLease.new("activity_service:#{user.id}", timeout: LEASE_TIMEOUT) return unless lease.try_obtain user.update_attribute(:last_activity_on, today) Gitlab::UsageDataCounters::HLLRedisCounter.track_event('unique_active_user', values: user.id) Gitlab::Tracking.event( 'Users::ActivityService', 'perform_action', user: user, namespace: namespace, project: project, label: 'redis_hll_counters.manage.unique_active_users_monthly', context: [ Gitlab::Tracking::ServicePingContext.new(data_source: :redis_hll, event: 'unique_active_user').to_context ] ) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::ActivityService, feature_category: :user_profile do include ExclusiveLeaseHelpers let(:user) { create(:user, last_activity_on: last_activity_on) } subject { described_class.new(author: user) } describe '#execute', :clean_gitlab_redis_shared_state do shared_examples 'does not update last_activity_on' do it 'does not update user attribute' do expect { subject.execute }.not_to change(user, :last_activity_on) end it 'does not track Snowplow event' do subject.execute expect_no_snowplow_event end end context 'when last activity is nil' do let(:last_activity_on) { nil } it 'updates last_activity_on for the user' do expect { subject.execute } .to change(user, :last_activity_on).from(last_activity_on).to(Date.today) end end context 'when last activity is in the past' do let(:last_activity_on) { Date.today - 1.week } it 'updates last_activity_on for the user' do expect { subject.execute } .to change(user, :last_activity_on) .from(last_activity_on) .to(Date.today) end it 'tries to obtain ExclusiveLease' do expect(Gitlab::ExclusiveLease).to receive(:new).with("activity_service:#{user.id}", anything).and_call_original subject.execute end it 'tracks RedisHLL event' do expect(Gitlab::UsageDataCounters::HLLRedisCounter) .to receive(:track_event) .with('unique_active_user', values: user.id) subject.execute end it_behaves_like 'Snowplow event tracking with RedisHLL context' do subject(:record_activity) { described_class.new(author: user, namespace: namespace, project: project).execute } let(:category) { described_class.name } let(:action) { 'perform_action' } let(:label) { 'redis_hll_counters.manage.unique_active_users_monthly' } let(:namespace) { build(:group) } let(:project) { build(:project) } let(:context) do payload = Gitlab::Tracking::ServicePingContext.new( data_source: :redis_hll, event: 'unique_active_user' ).to_context [Gitlab::Json.dump(payload)] end end end context 'when a bad object is passed' do let(:fake_object) { double(username: 'hello') } it 'does not record activity' do service = described_class.new(author: fake_object) expect(service).not_to receive(:record_activity) service.execute end end context 'when last activity is today' do let(:last_activity_on) { Date.today } it_behaves_like 'does not update last_activity_on' it 'does not try to obtain ExclusiveLease' do expect(Gitlab::ExclusiveLease).not_to receive(:new).with("activity_service:#{user.id}", anything) subject.execute end end context 'when in GitLab read-only instance' do let(:last_activity_on) { nil } before do allow(Gitlab::Database).to receive(:read_only?).and_return(true) end it_behaves_like 'does not update last_activity_on' end context 'when a lease could not be obtained' do let(:last_activity_on) { nil } before do stub_exclusive_lease_taken("activity_service:#{user.id}", timeout: 1.minute.to_i) end it_behaves_like 'does not update last_activity_on' end end context 'with DB Load Balancing' do let(:user) { create(:user, last_activity_on: last_activity_on) } context 'when last activity is in the past' do let(:user) { create(:user, last_activity_on: Date.today - 1.week) } context 'database load balancing is configured' do before do ::Gitlab::Database::LoadBalancing::Session.clear_session end let(:service) do service = described_class.new(author: user) ::Gitlab::Database::LoadBalancing::Session.clear_session service end it 'does not stick to primary' do expect(::Gitlab::Database::LoadBalancing::Session.current).not_to be_performed_write service.execute expect(user.last_activity_on).to eq(Date.today) expect(::Gitlab::Database::LoadBalancing::Session.current).to be_performed_write expect(::Gitlab::Database::LoadBalancing::Session.current).not_to be_using_primary end end context 'database load balancing is not configured' do let(:service) { described_class.new(author: user) } it 'updates user without error' do service.execute expect(user.last_activity_on).to eq(Date.today) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class SetNamespaceCommitEmailService include Gitlab::Allowable attr_reader :current_user, :target_user, :namespace, :email_id def initialize(current_user, namespace, email_id, params) @current_user = current_user @target_user = params.delete(:user) || current_user @namespace = namespace @email_id = email_id end def execute return error(_('Namespace must be provided.')) if namespace.nil? unless can?(current_user, :admin_user_email_address, target_user) return error(_("User doesn't exist or you don't have permission to change namespace commit emails.")) end unless can?(target_user, :read_namespace_via_membership, namespace) return error(_("Namespace doesn't exist or you don't have permission.")) end email = target_user.emails.find_by(id: email_id) unless email_id.nil? # rubocop: disable CodeReuse/ActiveRecord existing_namespace_commit_email = target_user.namespace_commit_email_for_namespace(namespace) if existing_namespace_commit_email.nil? return error(_('Email must be provided.')) if email.nil? create_namespace_commit_email(email) elsif email_id.nil? remove_namespace_commit_email(existing_namespace_commit_email) else update_namespace_commit_email(existing_namespace_commit_email, email) end end private def remove_namespace_commit_email(namespace_commit_email) namespace_commit_email.destroy success(nil) end def create_namespace_commit_email(email) namespace_commit_email = ::Users::NamespaceCommitEmail.new( user: target_user, namespace: namespace, email: email ) save_namespace_commit_email(namespace_commit_email) end def update_namespace_commit_email(namespace_commit_email, email) namespace_commit_email.email = email save_namespace_commit_email(namespace_commit_email) end def save_namespace_commit_email(namespace_commit_email) if !namespace_commit_email.save error_in_save(namespace_commit_email) else success(namespace_commit_email) end end def success(namespace_commit_email) ServiceResponse.success(payload: { namespace_commit_email: namespace_commit_email }) end def error(message) ServiceResponse.error(message: message) end def error_in_save(namespace_commit_email) return error(_('Failed to save namespace commit email.')) if namespace_commit_email.errors.empty? error(namespace_commit_email.errors.full_messages.to_sentence) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::SetNamespaceCommitEmailService, feature_category: :user_profile do include AfterNextHelpers let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:email) { create(:email, user: user) } let_it_be(:existing_achievement) { create(:achievement, namespace: group) } let(:namespace) { group } let(:current_user) { user } let(:target_user) { user } let(:email_id) { email.id } let(:params) { { user: target_user } } let(:service) { described_class.new(current_user, namespace, email_id, params) } before_all do group.add_reporter(user) end shared_examples 'success' do it 'creates namespace commit email' do result = service.execute expect(result.payload[:namespace_commit_email]).to be_a(Users::NamespaceCommitEmail) expect(result.payload[:namespace_commit_email]).to be_persisted end end describe '#execute' do context 'when current_user is not provided' do let(:current_user) { nil } it 'returns error message' do expect(service.execute.message) .to eq("User doesn't exist or you don't have permission to change namespace commit emails.") end end context 'when current_user does not have permission to change namespace commit emails' do let(:target_user) { create(:user) } it 'returns error message' do expect(service.execute.message) .to eq("User doesn't exist or you don't have permission to change namespace commit emails.") end end context 'when target_user does not have permission to access the namespace' do let(:namespace) { create(:group) } it 'returns error message' do expect(service.execute.message).to eq("Namespace doesn't exist or you don't have permission.") end end context 'when namespace is not provided' do let(:namespace) { nil } it 'returns error message' do expect(service.execute.message).to eq('Namespace must be provided.') end end context 'when target user is not current user' do context 'when current user is an admin' do let(:current_user) { create(:user, :admin) } context 'when admin mode is enabled', :enable_admin_mode do it 'creates namespace commit email' do result = service.execute expect(result.payload[:namespace_commit_email]).to be_a(Users::NamespaceCommitEmail) expect(result.payload[:namespace_commit_email]).to be_persisted end end context 'when admin mode is not enabled' do it 'returns error message' do expect(service.execute.message) .to eq("User doesn't exist or you don't have permission to change namespace commit emails.") end end end context 'when current user is not an admin' do let(:current_user) { create(:user) } it 'returns error message' do expect(service.execute.message) .to eq("User doesn't exist or you don't have permission to change namespace commit emails.") end end end context 'when namespace commit email does not exist' do context 'when email_id is not provided' do let(:email_id) { nil } it 'returns error message' do expect(service.execute.message).to eq('Email must be provided.') end end context 'when model save fails' do before do allow_next(::Users::NamespaceCommitEmail).to receive(:save).and_return(false) end it 'returns error message' do expect(service.execute.message).to eq('Failed to save namespace commit email.') end end context 'when namepsace is a group' do it_behaves_like 'success' end context 'when namespace is a user' do let(:namespace) { current_user.namespace } it_behaves_like 'success' end context 'when namespace is a project' do let_it_be(:project) { create(:project) } let(:namespace) { project.project_namespace } before do project.add_reporter(current_user) end it_behaves_like 'success' end end context 'when namespace commit email already exists' do let!(:existing_namespace_commit_email) do create(:namespace_commit_email, user: target_user, namespace: namespace, email: create(:email, user: target_user)) end context 'when email_id is not provided' do let(:email_id) { nil } it 'destroys the namespace commit email' do result = service.execute expect(result.message).to be_nil expect(result.payload[:namespace_commit_email]).to be_nil end end context 'and email_id is provided' do let(:email_id) { create(:email, user: current_user).id } it 'updates namespace commit email' do result = service.execute existing_namespace_commit_email.reload expect(result.payload[:namespace_commit_email]).to eq(existing_namespace_commit_email) expect(existing_namespace_commit_email.email_id).to eq(email_id) end end context 'when model save fails' do before do allow_any_instance_of(::Users::NamespaceCommitEmail).to receive(:save).and_return(false) # rubocop:disable RSpec/AnyInstanceOf end it 'returns generic error message' do expect(service.execute.message).to eq('Failed to save namespace commit email.') end context 'with model errors' do before do allow_any_instance_of(::Users::NamespaceCommitEmail).to receive_message_chain(:errors, :empty?).and_return(false) # rubocop:disable RSpec/AnyInstanceOf allow_any_instance_of(::Users::NamespaceCommitEmail).to receive_message_chain(:errors, :full_messages, :to_sentence).and_return('Model error') # rubocop:disable RSpec/AnyInstanceOf end it 'returns the model error message' do expect(service.execute.message).to eq('Model error') end end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class BannedUserBaseService < BaseService def initialize(current_user) @current_user = current_user end def execute(user) return permission_error unless allowed? return state_error(user) unless valid_state?(user) if update_user(user) log_event(user) track_event(user) success else messages = user.errors.full_messages error(messages.uniq.join('. ')) end end private attr_reader :current_user # Overridden in Users::BanService def track_event(_); end def state_error(user) error(_("You cannot %{action} %{state} users." % { action: action.to_s, state: user.state }), :forbidden) end def allowed? can?(current_user, :admin_all_resources) end def permission_error error(_("You are not allowed to %{action} a user" % { action: action.to_s }), :forbidden) end def log_event(user) Gitlab::AppLogger.info(message: "User #{action}", user: user.username.to_s, email: user.email.to_s, "#{action}_by": current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::BannedUserBaseService, feature_category: :user_management do let(:admin) { create(:admin) } let(:base_service) { described_class.new(admin) } describe '#initialize' do it 'sets the current_user instance value' do expect(base_service.instance_values["current_user"]).to eq(admin) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class TrustService < BaseService def initialize(current_user) @current_user = current_user end def execute(user) UserCustomAttribute.set_trusted_by(user: user, trusted_by: @current_user) success end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::TrustService, feature_category: :user_management do let_it_be(:current_user) { create(:admin) } subject(:service) { described_class.new(current_user) } describe '#execute' do let(:user) { create(:user) } subject(:operation) { service.execute(user) } it 'updates the custom attributes', :aggregate_failures do expect(user.custom_attributes).to be_empty operation user.reload expect(user.custom_attributes.by_key(UserCustomAttribute::TRUSTED_BY)).to be_present end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class BlockService < BaseService def initialize(current_user) @current_user = current_user end def execute(user) return error('An internal user cannot be blocked', 403) if user.internal? if user.block after_block_hook(user) success else messages = user.errors.full_messages error(messages.uniq.join('. ')) end end private # overridden by EE module def after_block_hook(user) custom_attribute = { user_id: user.id, key: UserCustomAttribute::BLOCKED_BY, value: "#{current_user.username}/#{current_user.id}+#{Time.current}" } UserCustomAttribute.upsert_custom_attributes([custom_attribute]) end end end Users::BlockService.prepend_mod_with('Users::BlockService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::BlockService, feature_category: :user_management do let_it_be(:current_user) { create(:admin) } subject(:service) { described_class.new(current_user) } describe '#execute' do subject(:operation) { service.execute(user) } context 'when successful' do let(:user) { create(:user) } it { is_expected.to eq(status: :success) } it "change the user's state" do expect { operation }.to change { user.state }.to('blocked') end it 'saves a custom attribute', :aggregate_failures, :freeze_time, feature_category: :insider_threat do operation custom_attribute = user.custom_attributes.last expect(custom_attribute.key).to eq(UserCustomAttribute::BLOCKED_BY) expect(custom_attribute.value).to eq("#{current_user.username}/#{current_user.id}+#{Time.current}") end end context 'when failed' do let(:user) { create(:user, :blocked) } it 'returns error result' do aggregate_failures 'error result' do expect(operation[:status]).to eq(:error) expect(operation[:message]).to match(/State cannot transition/) end end it "does not change the user's state" do expect { operation }.not_to change { user.state } end end context 'when internal user' do let(:user) { create(:user, :bot) } it 'returns error result' do expect(operation[:status]).to eq(:error) expect(operation[:message]).to eq('An internal user cannot be blocked') expect(operation[:http_status]).to eq(403) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users # Service for refreshing the authorized projects of a user. # # This particular service class can not be used to update data for the same # user concurrently. Doing so could lead to an incorrect state. To ensure this # doesn't happen a caller must synchronize access (e.g. using # `Gitlab::ExclusiveLease`). # # Usage: # # user = User.find_by(username: 'alice') # service = Users::RefreshAuthorizedProjectsService.new(some_user) # service.execute class RefreshAuthorizedProjectsService attr_reader :user, :source LEASE_TIMEOUT = 1.minute.to_i # user - The User for which to refresh the authorized projects. def initialize(user, source: nil, incorrect_auth_found_callback: nil, missing_auth_found_callback: nil) @user = user @source = source @incorrect_auth_found_callback = incorrect_auth_found_callback @missing_auth_found_callback = missing_auth_found_callback end def execute lease_key = "refresh_authorized_projects:#{user.id}" lease = Gitlab::ExclusiveLease.new(lease_key, timeout: LEASE_TIMEOUT) until uuid = lease.try_obtain # Keep trying until we obtain the lease. If we don't do so we may end up # not updating the list of authorized projects properly. To prevent # hammering Redis too much we'll wait for a bit between retries. sleep(0.1) end begin # We need an up to date User object that has access to all relations that # may have been created earlier. The only way to ensure this is to reload # the User object. user.reset execute_without_lease ensure Gitlab::ExclusiveLease.cancel(lease_key, uuid) end end # This method returns the updated User object. def execute_without_lease remove, add = AuthorizedProjectUpdate::FindRecordsDueForRefreshService.new( user, source: source, incorrect_auth_found_callback: incorrect_auth_found_callback, missing_auth_found_callback: missing_auth_found_callback ).execute update_authorizations(remove, add) end # Updates the list of authorizations for the current user. # # remove - The project IDs of the authorization rows to remove. # add - Rows to insert in the form `[{ user_id: user_id, project_id: project_id, access_level: access_level}, ...]` def update_authorizations(remove = [], add = []) log_refresh_details(remove, add) ProjectAuthorizations::Changes.new do |changes| changes.add(add) changes.remove_projects_for_user(user, remove) end.apply! user.update!(project_authorizations_recalculated_at: Time.zone.now) if remove.any? || add.any? # Since we batch insert authorization rows, Rails' associations may get # out of sync. As such we force a reload of the User object. user.reset end private attr_reader :incorrect_auth_found_callback, :missing_auth_found_callback def log_refresh_details(remove, add) Gitlab::AppJsonLogger.info( event: 'authorized_projects_refresh', user_id: user.id, 'authorized_projects_refresh.source': source, 'authorized_projects_refresh.rows_deleted_count': remove.length, 'authorized_projects_refresh.rows_added_count': add.length, # most often there's only a few entries in remove and add, but limit it to the first 5 # entries to avoid flooding the logs 'authorized_projects_refresh.rows_deleted_slice': remove.first(5), 'authorized_projects_refresh.rows_added_slice': add.first(5).map(&:values) ) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::RefreshAuthorizedProjectsService, feature_category: :user_management do include ExclusiveLeaseHelpers # We're using let! here so that any expectations for the service class are not # triggered twice. let!(:project) { create(:project) } let(:user) { project.namespace.first_owner } let(:service) { described_class.new(user) } describe '#execute', :clean_gitlab_redis_shared_state do it 'refreshes the authorizations using a lease' do lease_key = "refresh_authorized_projects:#{user.id}" expect_to_obtain_exclusive_lease(lease_key, 'uuid') expect_to_cancel_exclusive_lease(lease_key, 'uuid') expect(service).to receive(:execute_without_lease) service.execute end context 'callbacks' do let(:callback) { double('callback') } context 'incorrect_auth_found_callback callback' do let(:user) { create(:user) } let(:service) do described_class.new(user, incorrect_auth_found_callback: callback) end it 'is called' do access_level = Gitlab::Access::DEVELOPER create(:project_authorization, user: user, project: project, access_level: access_level) expect(callback).to receive(:call).with(project.id, access_level).once service.execute end end context 'missing_auth_found_callback callback' do let(:service) do described_class.new(user, missing_auth_found_callback: callback) end it 'is called' do ProjectAuthorization.delete_all expect(callback).to receive(:call).with(project.id, Gitlab::Access::OWNER).once service.execute end end end end describe '#execute_without_lease' do before do user.project_authorizations.delete_all end it 'updates the authorized projects of the user' do project2 = create(:project) project_authorization = user.project_authorizations .create!(project: project2, access_level: Gitlab::Access::MAINTAINER) to_be_removed = [project_authorization.project_id] to_be_added = [ { user_id: user.id, project_id: project.id, access_level: Gitlab::Access::OWNER } ] expect(service).to receive(:update_authorizations) .with(to_be_removed, to_be_added) service.execute_without_lease end it 'sets the access level of a project to the highest available level' do user.project_authorizations.delete_all project_authorization = user.project_authorizations .create!(project: project, access_level: Gitlab::Access::DEVELOPER) to_be_removed = [project_authorization.project_id] to_be_added = [ { user_id: user.id, project_id: project.id, access_level: Gitlab::Access::OWNER } ] expect(service).to receive(:update_authorizations) .with(to_be_removed, to_be_added) service.execute_without_lease end it 'updates project_authorizations_recalculated_at', :freeze_time do default_date = Time.zone.local('2010') expect do service.execute_without_lease end.to change { user.project_authorizations_recalculated_at }.from(default_date).to(Time.zone.now) end it 'returns a User' do expect(service.execute_without_lease).to be_an_instance_of(User) end end describe '#update_authorizations' do context 'when there are no rows to add and remove' do it 'does not change authorizations' do expect { service.update_authorizations([], []) }.to not_change { user.project_authorizations.count } end end it 'removes authorizations that should be removed' do authorization = user.project_authorizations.find_by(project_id: project.id) service.update_authorizations([authorization.project_id]) expect(user.project_authorizations).to be_empty end it 'inserts authorizations that should be added' do user.project_authorizations.delete_all to_be_added = [ { user_id: user.id, project_id: project.id, access_level: Gitlab::Access::MAINTAINER } ] service.update_authorizations([], to_be_added) authorizations = user.project_authorizations expect(authorizations.length).to eq(1) expect(authorizations[0].user_id).to eq(user.id) expect(authorizations[0].project_id).to eq(project.id) expect(authorizations[0].access_level).to eq(Gitlab::Access::MAINTAINER) end it 'logs the details of the refresh' do source = :foo service = described_class.new(user, source: source) user.project_authorizations.delete_all expect(Gitlab::AppJsonLogger).to( receive(:info).with( event: 'authorized_projects_refresh', user_id: user.id, 'authorized_projects_refresh.source': source, 'authorized_projects_refresh.rows_deleted_count': 0, 'authorized_projects_refresh.rows_added_count': 1, 'authorized_projects_refresh.rows_deleted_slice': [], 'authorized_projects_refresh.rows_added_slice': [[user.id, project.id, Gitlab::Access::MAINTAINER]] ) ) to_be_added = [ { user_id: user.id, project_id: project.id, access_level: Gitlab::Access::MAINTAINER } ] service.update_authorizations([], to_be_added) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # When a user is destroyed, some of their associated records are # moved to a "Ghost User", to prevent these associated records from # being destroyed. # # For example, all the issues/MRs a user has created are _not_ destroyed # when the user is destroyed. module Users class MigrateRecordsToGhostUserService extend ActiveSupport::Concern DestroyError = Class.new(StandardError) attr_reader :ghost_user, :user, :initiator_user, :hard_delete def initialize(user, initiator_user, execution_tracker) @user = user @initiator_user = initiator_user @execution_tracker = execution_tracker @ghost_user = Users::Internal.ghost end def execute(hard_delete: false) @hard_delete = hard_delete migrate_records post_migrate_records end private attr_reader :execution_tracker def migrate_records migrate_user_achievements return if hard_delete migrate_issues migrate_merge_requests migrate_notes migrate_abuse_reports migrate_award_emoji migrate_snippets migrate_reviews migrate_releases end def post_migrate_records delete_snippets # Rails attempts to load all related records into memory before # destroying: https://github.com/rails/rails/issues/22510 # This ensures we delete records in batches. user.destroy_dependent_associations_in_batches(exclude: [:snippets]) user.nullify_dependent_associations_in_batches # Destroy the namespace after destroying the user since certain methods may depend on the namespace existing user_data = user.destroy user.namespace.destroy user_data end def delete_snippets response = Snippets::BulkDestroyService.new(initiator_user, user.snippets).execute(skip_authorization: true) raise DestroyError, response.message if response.error? end def migrate_issues batched_migrate(Issue, :author_id) batched_migrate(Issue, :last_edited_by_id) end def migrate_merge_requests batched_migrate(MergeRequest, :author_id) batched_migrate(MergeRequest, :merge_user_id) end def migrate_notes batched_migrate(Note, :author_id) end def migrate_abuse_reports user.reported_abuse_reports.update_all(reporter_id: ghost_user.id) end def migrate_award_emoji user.award_emoji.update_all(user_id: ghost_user.id) end def migrate_snippets snippets = user.snippets.only_project_snippets snippets.update_all(author_id: ghost_user.id) end def migrate_reviews batched_migrate(Review, :author_id) end def migrate_releases batched_migrate(Release, :author_id) end def migrate_user_achievements batched_migrate(Achievements::UserAchievement, :awarded_by_user_id) batched_migrate(Achievements::UserAchievement, :revoked_by_user_id) end # rubocop:disable CodeReuse/ActiveRecord def batched_migrate(base_scope, column, batch_size: 50) loop do update_count = base_scope.where(column => user.id).limit(batch_size).update_all(column => ghost_user.id) break if update_count == 0 raise Gitlab::Utils::ExecutionTracker::ExecutionTimeOutError if execution_tracker.over_limit? end end # rubocop:enable CodeReuse/ActiveRecord end end Users::MigrateRecordsToGhostUserService.prepend_mod_with('Users::MigrateRecordsToGhostUserService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::MigrateRecordsToGhostUserService, feature_category: :user_management do include BatchDestroyDependentAssociationsHelper let!(:user) { create(:user) } let(:service) { described_class.new(user, admin, execution_tracker) } let(:execution_tracker) { instance_double(::Gitlab::Utils::ExecutionTracker, over_limit?: false) } let_it_be(:admin) { create(:admin) } let_it_be(:project) { create(:project, :repository) } context "when migrating a user's associated records to the ghost user" do context 'for issues' do context 'when deleted user is present as both author and edited_user' do include_examples 'migrating records to the ghost user', Issue, [:author, :last_edited_by] do let(:created_record) do create(:issue, project: project, author: user, last_edited_by: user) end end end context 'when deleted user is present only as edited_user' do include_examples 'migrating records to the ghost user', Issue, [:last_edited_by] do let(:created_record) { create(:issue, project: project, author: create(:user), last_edited_by: user) } end end context "when deleted user is the assignee" do let!(:issue) { create(:issue, project: project, assignees: [user]) } it 'migrates the issue so that it is "Unassigned"' do service.execute migrated_issue = Issue.find_by_id(issue.id) expect(migrated_issue).to be_present expect(migrated_issue.assignees).to be_empty end end end context 'for merge requests' do context 'when deleted user is present as both author and merge_user' do include_examples 'migrating records to the ghost user', MergeRequest, [:author, :merge_user] do let(:created_record) do create( :merge_request, source_project: project, author: user, merge_user: user, target_branch: "first" ) end end end context 'when deleted user is present only as both merge_user' do include_examples 'migrating records to the ghost user', MergeRequest, [:merge_user] do let(:created_record) do create( :merge_request, source_project: project, merge_user: user, target_branch: "first" ) end end end context "when deleted user is the assignee" do let!(:merge_request) { create(:merge_request, source_project: project, assignees: [user]) } it 'migrates the merge request so that it is "Unassigned"' do service.execute migrated_merge_request = MergeRequest.find_by_id(merge_request.id) expect(migrated_merge_request).to be_present expect(migrated_merge_request.assignees).to be_empty end end end context 'for notes' do include_examples 'migrating records to the ghost user', Note do let(:created_record) { create(:note, project: project, author: user) } end end context 'for abuse reports' do include_examples 'migrating records to the ghost user', AbuseReport do let(:created_record) { create(:abuse_report, reporter: user, user: create(:user)) } end end context 'for award emoji' do include_examples 'migrating records to the ghost user', AwardEmoji, [:user] do let(:created_record) { create(:award_emoji, user: user) } context "when the awardable already has an award emoji of the same name assigned to the ghost user" do let(:awardable) { create(:issue) } let!(:existing_award_emoji) do create(:award_emoji, user: Users::Internal.ghost, name: "thumbsup", awardable: awardable) end let!(:award_emoji) { create(:award_emoji, user: user, name: "thumbsup", awardable: awardable) } it "migrates the award emoji regardless" do service.execute migrated_record = AwardEmoji.find_by_id(award_emoji.id) expect(migrated_record.user).to eq(Users::Internal.ghost) end it "does not leave the migrated award emoji in an invalid state" do service.execute migrated_record = AwardEmoji.find_by_id(award_emoji.id) expect(migrated_record).to be_valid end end end end context 'for snippets' do include_examples 'migrating records to the ghost user', Snippet do let(:created_record) { create(:snippet, project: project, author: user) } end end context 'for reviews' do include_examples 'migrating records to the ghost user', Review, [:author] do let(:created_record) { create(:review, author: user) } end end context 'for releases' do include_examples 'migrating records to the ghost user', Release, [:author] do let(:created_record) { create(:release, author: user) } end end context 'for user achievements' do include_examples 'migrating records to the ghost user', Achievements::UserAchievement, [:awarded_by_user, :revoked_by_user] do let(:created_record) { create(:user_achievement, awarded_by_user: user, revoked_by_user: user) } end end end context 'on post-migrate cleanups' do it 'destroys the user and personal namespace' do namespace = user.namespace allow(user).to receive(:destroy).and_call_original service.execute expect { User.find(user.id) }.to raise_error(ActiveRecord::RecordNotFound) expect { Namespace.find(namespace.id) }.to raise_error(ActiveRecord::RecordNotFound) end it 'deletes user associations in batches' do expect(user).to receive(:destroy_dependent_associations_in_batches) service.execute end context 'for batched nullify' do # rubocop:disable Layout/LineLength def nullify_in_batches_regexp(table, column, user, batch_size: 100) %r{^UPDATE "#{table}" SET "#{column}" = NULL WHERE "#{table}"."id" IN \(SELECT "#{table}"."id" FROM "#{table}" WHERE "#{table}"."#{column}" = #{user.id} LIMIT #{batch_size}\)} end # rubocop:enable Layout/LineLength it 'nullifies related associations in batches' do expect(user).to receive(:nullify_dependent_associations_in_batches).and_call_original service.execute end it 'nullifies associations marked as `dependent: :nullify` and'\ 'destroys the associations marked as `dependent: :destroy`, in batches', :aggregate_failures do # associations to be nullified issue = create(:issue, closed_by: user, updated_by: user) resource_label_event = create(:resource_label_event, user: user) resource_state_event = create(:resource_state_event, user: user) created_project = create(:project, creator: user) # associations to be destroyed todos = create_list(:todo, 2, project: issue.project, user: user, author: user, target: issue) event = create(:event, project: issue.project, author: user) query_recorder = ActiveRecord::QueryRecorder.new do service.execute end issue.reload resource_label_event.reload resource_state_event.reload created_project.reload expect(issue.closed_by).to be_nil expect(issue.updated_by_id).to be_nil expect(resource_label_event.user_id).to be_nil expect(resource_state_event.user_id).to be_nil expect(created_project.creator_id).to be_nil expect(user.authored_todos).to be_empty expect(user.todos).to be_empty expect(user.authored_events).to be_empty expected_queries = [ nullify_in_batches_regexp(:issues, :updated_by_id, user), nullify_in_batches_regexp(:issues, :closed_by_id, user), nullify_in_batches_regexp(:resource_label_events, :user_id, user), nullify_in_batches_regexp(:resource_state_events, :user_id, user), nullify_in_batches_regexp(:projects, :creator_id, user) ] expected_queries += delete_in_batches_regexps(:todos, :user_id, user, todos) expected_queries += delete_in_batches_regexps(:todos, :author_id, user, todos) expected_queries += delete_in_batches_regexps(:events, :author_id, user, [event]) expect(query_recorder.log).to include(*expected_queries) end it 'nullifies merge request associations', :aggregate_failures do merge_request = create( :merge_request, source_project: project, target_project: project, assignee: user, updated_by: user, merge_user: user ) merge_request.metrics.update!(merged_by: user, latest_closed_by: user) merge_request.reviewers = [user] merge_request.assignees = [user] query_recorder = ActiveRecord::QueryRecorder.new do service.execute end merge_request.reload expect(merge_request.updated_by).to be_nil expect(merge_request.assignee).to be_nil expect(merge_request.assignee_id).to be_nil expect(merge_request.metrics.merged_by).to be_nil expect(merge_request.metrics.latest_closed_by).to be_nil expect(merge_request.reviewers).to be_empty expect(merge_request.assignees).to be_empty expected_queries = [ nullify_in_batches_regexp(:merge_requests, :updated_by_id, user), nullify_in_batches_regexp(:merge_requests, :assignee_id, user), nullify_in_batches_regexp(:merge_request_metrics, :merged_by_id, user), nullify_in_batches_regexp(:merge_request_metrics, :latest_closed_by_id, user) ] expected_queries += delete_in_batches_regexps( :merge_request_assignees, :user_id, user, merge_request.assignees ) expected_queries += delete_in_batches_regexps( :merge_request_reviewers, :user_id, user, merge_request.reviewers ) expect(query_recorder.log).to include(*expected_queries) end end context 'for snippets' do let(:gitlab_shell) { Gitlab::Shell.new } it 'does not include snippets when deleting in batches' do expect(user).to receive(:destroy_dependent_associations_in_batches).with({ exclude: [:snippets] }) service.execute end it 'calls the bulk snippet destroy service for the user personal snippets' do repo1 = create(:personal_snippet, :repository, author: user).snippet_repository repo2 = create(:project_snippet, :repository, project: project, author: user).snippet_repository aggregate_failures do expect(gitlab_shell.repository_exists?(repo1.shard_name, "#{repo1.disk_path}.git")).to be(true) expect(gitlab_shell.repository_exists?(repo2.shard_name, "#{repo2.disk_path}.git")).to be(true) end # Call made when destroying user personal projects expect(Snippets::BulkDestroyService).not_to( receive(:new).with(admin, project.snippets).and_call_original) # Call to remove user personal snippets and for # project snippets where projects are not user personal # ones expect(Snippets::BulkDestroyService).to( receive(:new).with(admin, user.snippets.only_personal_snippets).and_call_original) service.execute aggregate_failures do expect(gitlab_shell.repository_exists?(repo1.shard_name, "#{repo1.disk_path}.git")).to be(false) expect(gitlab_shell.repository_exists?(repo2.shard_name, "#{repo2.disk_path}.git")).to be(true) end end it 'calls the bulk snippet destroy service with hard delete option if it is present' do # this avoids getting into Projects::DestroyService as it would # call Snippets::BulkDestroyService first! allow(user).to receive(:personal_projects).and_return([]) expect_next_instance_of(Snippets::BulkDestroyService) do |bulk_destroy_service| expect(bulk_destroy_service).to receive(:execute).with({ skip_authorization: true }).and_call_original end service.execute(hard_delete: true) end it 'does not delete project snippets that the user is the author of' do repo = create(:project_snippet, :repository, author: user).snippet_repository service.execute expect(gitlab_shell.repository_exists?(repo.shard_name, "#{repo.disk_path}.git")).to be(true) expect(Users::Internal.ghost.snippets).to include(repo.snippet) end context 'when an error is raised deleting snippets' do it 'does not delete user' do snippet = create(:personal_snippet, :repository, author: user) bulk_service = double allow(Snippets::BulkDestroyService).to receive(:new).and_call_original allow(Snippets::BulkDestroyService).to receive(:new).with(admin, user.snippets).and_return(bulk_service) allow(bulk_service).to receive(:execute).and_return(ServiceResponse.error(message: 'foo')) aggregate_failures do expect { service.execute }.to( raise_error(Users::MigrateRecordsToGhostUserService::DestroyError, 'foo')) expect(snippet.reload).not_to be_nil expect( gitlab_shell.repository_exists?(snippet.repository_storage, "#{snippet.disk_path}.git") ).to be(true) end end end end context 'when hard_delete option is given' do it 'will not ghost certain records' do issue = create(:issue, author: user) service.execute(hard_delete: true) expect(Issue).not_to exist(issue.id) end it 'migrates awarded and revoked fields of user achievements' do user_achievement = create(:user_achievement, awarded_by_user: user, revoked_by_user: user) service.execute(hard_delete: true) user_achievement.reload expect(user_achievement.revoked_by_user).to eq(Users::Internal.ghost) expect(user_achievement.awarded_by_user).to eq(Users::Internal.ghost) end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class AuthorizedBuildService < BuildService extend ::Gitlab::Utils::Override private override :validate_access! def validate_access! # no-op end def signup_params super + [:skip_confirmation, :external] end end end Users::AuthorizedBuildService.prepend_mod_with('Users::AuthorizedBuildService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::AuthorizedBuildService, feature_category: :user_management do describe '#execute' do let_it_be(:current_user) { create(:user) } let(:params) { build_stubbed(:user).slice(:first_name, :last_name, :username, :email, :password) } subject(:user) { described_class.new(current_user, params).execute } it_behaves_like 'common user build items' it_behaves_like 'current user not admin build items' context 'for additional authorized build allowed params' do before do params.merge!(external: true) end it { expect(user).to be_external } end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class RejectService < BaseService def initialize(current_user) @current_user = current_user end def execute(user) return error(_('You are not allowed to reject a user'), :forbidden) unless allowed? return error(_('User does not have a pending request'), :conflict) unless user.blocked_pending_approval? user.delete_async(deleted_by: current_user, params: { hard_delete: true }) after_reject_hook(user) NotificationService.new.user_admin_rejection(user.name, user.email) log_event(user) success(message: 'Success', http_status: :ok) end private attr_reader :current_user def allowed? can?(current_user, :reject_user) end def after_reject_hook(user) # overridden by EE module end def log_event(user) Gitlab::AppLogger.info(message: "User instance access request rejected", user: user.username.to_s, email: user.email.to_s, rejected_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s) end end end Users::RejectService.prepend_mod_with('Users::RejectService') ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::RejectService, feature_category: :user_management do let_it_be(:current_user) { create(:admin) } let(:user) { create(:user, :blocked_pending_approval) } subject(:execute) { described_class.new(current_user).execute(user) } describe '#execute' do context 'failures' do context 'when the executor user is not allowed to reject users' do let(:current_user) { create(:user) } it 'returns error result' do expect(subject[:status]).to eq(:error) expect(subject[:message]).to match(/You are not allowed to reject a user/) end end context 'when the executor user is an admin in admin mode', :enable_admin_mode do context 'when user is not in pending approval state' do let(:user) { create(:user, state: 'active') } it 'returns error result' do expect(subject[:status]).to eq(:error) expect(subject[:message]) .to match(/User does not have a pending request/) end end end end context 'success' do context 'when the executor user is an admin in admin mode', :enable_admin_mode do it 'initiates user removal', :sidekiq_inline do subject expect(subject[:status]).to eq(:success) expect( Users::GhostUserMigration.where(user: user, initiator_user: current_user) ).to be_exists end it 'emails the user on rejection' do expect_next_instance_of(NotificationService) do |notification| allow(notification).to receive(:user_admin_rejection).with(user.name, user.notification_email_or_default) end subject end it 'logs rejection in application logs' do allow(Gitlab::AppLogger).to receive(:info) subject expect(Gitlab::AppLogger).to have_received(:info).with( message: "User instance access request rejected", user: user.username.to_s, email: user.email.to_s, rejected_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s ) end end end context 'audit events' do context 'when not licensed' do before do stub_licensed_features(admin_audit_log: false) end it 'does not log any audit event' do expect { subject }.not_to change(AuditEvent, :count) end end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users # Service class for caching and retrieving the last push event of a user. class LastPushEventService EXPIRATION = 2.hours def initialize(user) @user = user end # Caches the given push event for the current user in the Rails cache. # # event - An instance of PushEvent to cache. def cache_last_push_event(event) keys = [ project_cache_key(event.project), user_cache_key ] if forked_from = event.project.forked_from_project keys << project_cache_key(forked_from) end keys.each { |key| set_key(key, event.id) } end # Returns the last PushEvent for the current user. # # This method will return nil if no event was found. def last_event_for_user find_cached_event(user_cache_key) end # Returns the last PushEvent for the current user and the given project. # # project - An instance of Project for which to retrieve the PushEvent. # # This method will return nil if no event was found. def last_event_for_project(project) find_cached_event(project_cache_key(project)) end def find_cached_event(cache_key) event_id = get_key(cache_key) return unless event_id unless (event = find_event_in_database(event_id)) # We don't want to keep querying the same data over and over when a # merge request has been created, thus we remove the key if no event # (meaning an MR was created) is returned. Rails.cache.delete(cache_key) end event end private # rubocop: disable CodeReuse/ActiveRecord def find_event_in_database(id) PushEvent .without_existing_merge_requests .find_by(id: id) end # rubocop: enable CodeReuse/ActiveRecord def user_cache_key "last-push-event/#{@user.id}" end def project_cache_key(project) "last-push-event/#{@user.id}/#{project.id}" end def get_key(key) Rails.cache.read(key, raw: true) end def set_key(key, value) # We're using raw values here since this takes up less space and we don't # store complex objects. Rails.cache.write(key, value, raw: true, expires_in: EXPIRATION) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::LastPushEventService, feature_category: :source_code_management do let(:user) { build(:user, id: 1) } let(:project) { build(:project, id: 2) } let(:event) { build(:push_event, id: 3, author: user, project: project) } let(:service) { described_class.new(user) } describe '#cache_last_push_event' do it "caches the event for the event's project and current user" do expect(service).to receive(:set_key) .ordered .with('last-push-event/1/2', 3) expect(service).to receive(:set_key) .ordered .with('last-push-event/1', 3) service.cache_last_push_event(event) end it 'caches the event for the origin project when pushing to a fork' do source = build(:project, id: 5) allow(project).to receive(:forked_from_project).and_return(source) expect(service).to receive(:set_key) .ordered .with('last-push-event/1/2', 3) expect(service).to receive(:set_key) .ordered .with('last-push-event/1', 3) expect(service).to receive(:set_key) .ordered .with('last-push-event/1/5', 3) service.cache_last_push_event(event) end end describe '#last_event_for_user' do it 'returns the last push event for the current user' do expect(service).to receive(:find_cached_event) .with('last-push-event/1') .and_return(event) expect(service.last_event_for_user).to eq(event) end it 'returns nil when no push event could be found' do expect(service).to receive(:find_cached_event) .with('last-push-event/1') .and_return(nil) expect(service.last_event_for_user).to be_nil end end describe '#last_event_for_project' do it 'returns the last push event for the given project' do expect(service).to receive(:find_cached_event) .with('last-push-event/1/2') .and_return(event) expect(service.last_event_for_project(project)).to eq(event) end it 'returns nil when no push event could be found' do expect(service).to receive(:find_cached_event) .with('last-push-event/1/2') .and_return(nil) expect(service.last_event_for_project(project)).to be_nil end end describe '#find_cached_event', :use_clean_rails_memory_store_caching do context 'with a non-existing cache key' do it 'returns nil' do expect(service.find_cached_event('bla')).to be_nil end end context 'with an existing cache key' do before do service.cache_last_push_event(event) end it 'returns a PushEvent when no merge requests exist for the event' do allow(service).to receive(:find_event_in_database) .with(event.id) .and_return(event) expect(service.find_cached_event('last-push-event/1')).to eq(event) end it 'removes the cache key when no event could be found and returns nil' do allow(PushEvent).to receive(:without_existing_merge_requests) .and_return(PushEvent.none) expect(Rails.cache).to receive(:delete) .with('last-push-event/1') .and_call_original expect(service.find_cached_event('last-push-event/1')).to be_nil end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class UpsertCreditCardValidationService < BaseService attr_reader :params def initialize(params) @params = params.to_h.with_indifferent_access end def execute credit_card = Users::CreditCardValidation.find_or_initialize_by_user(user_id) credit_card_params = { credit_card_validated_at: credit_card_validated_at, last_digits: last_digits, holder_name: holder_name, network: network, expiration_date: expiration_date } credit_card.update(credit_card_params) success rescue ActiveRecord::InvalidForeignKey, ActiveRecord::NotNullViolation error rescue StandardError => e Gitlab::ErrorTracking.track_exception(e) error end private def user_id params.fetch(:user_id) end def credit_card_validated_at params.fetch(:credit_card_validated_at) end def last_digits Integer(params.fetch(:credit_card_mask_number), 10) end def holder_name params.fetch(:credit_card_holder_name) end def network params.fetch(:credit_card_type) end def expiration_date year = params.fetch(:credit_card_expiration_year) month = params.fetch(:credit_card_expiration_month) Date.new(year, month, -1) # last day of the month end def success ServiceResponse.success(message: _('Credit card validation record saved')) end def error ServiceResponse.error(message: _('Error saving credit card validation record')) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::UpsertCreditCardValidationService, feature_category: :user_profile do include CryptoHelpers let_it_be(:user) { create(:user) } let(:user_id) { user.id } let(:network) { 'American Express' } let(:holder_name) { 'John Smith' } let(:last_digits) { '1111' } let(:expiration_year) { Date.today.year + 10 } let(:expiration_month) { 1 } let(:expiration_date) { Date.new(expiration_year, expiration_month, -1) } let(:credit_card_validated_at) { Time.utc(2020, 1, 1) } let(:params) do { user_id: user_id, credit_card_validated_at: credit_card_validated_at, credit_card_expiration_year: expiration_year, credit_card_expiration_month: expiration_month, credit_card_holder_name: holder_name, credit_card_type: network, credit_card_mask_number: last_digits } end describe '#execute' do subject(:service) { described_class.new(params) } context 'successfully set credit card validation record for the user' do context 'when user does not have credit card validation record' do it 'creates the credit card validation and returns a success', :aggregate_failures do expect(user.credit_card_validated_at).to be nil service_result = service.execute expect(service_result.status).to eq(:success) expect(service_result.message).to eq(_('Credit card validation record saved')) user.reload expect(user.credit_card_validation).to have_attributes( credit_card_validated_at: credit_card_validated_at, network_hash: sha256(network.downcase), holder_name_hash: sha256(holder_name.downcase), last_digits_hash: sha256(last_digits), expiration_date_hash: sha256(expiration_date.to_s) ) end end context 'when user has credit card validation record' do let(:previous_credit_card_validated_at) { Time.utc(1999, 2, 2) } before do create(:credit_card_validation, user: user, credit_card_validated_at: previous_credit_card_validated_at) end it 'updates the credit card validation record and returns a success', :aggregate_failures do expect(user.credit_card_validated_at).to eq(previous_credit_card_validated_at) service_result = service.execute expect(service_result.status).to eq(:success) expect(service_result.message).to eq(_('Credit card validation record saved')) user.reload expect(user.credit_card_validated_at).to eq(credit_card_validated_at) end end end shared_examples 'returns an error without tracking the exception' do it 'does not send an exception to Gitlab::ErrorTracking' do expect(Gitlab::ErrorTracking).not_to receive(:track_exception) service.execute end it 'returns an error', :aggregate_failures do service_result = service.execute expect(service_result.status).to eq(:error) expect(service_result.message).to eq(_('Error saving credit card validation record')) end end shared_examples 'returns an error and tracks the exception' do it 'sends an exception to Gitlab::ErrorTracking' do expect(Gitlab::ErrorTracking).to receive(:track_exception) service.execute end it 'returns an error', :aggregate_failures do service_result = service.execute expect(service_result.status).to eq(:error) expect(service_result.message).to eq(_('Error saving credit card validation record')) end end context 'when the user_id does not exist' do let(:user_id) { non_existing_record_id } it_behaves_like 'returns an error without tracking the exception' end context 'when the request is missing the credit_card_validated_at field' do let(:params) { { user_id: user_id } } it_behaves_like 'returns an error and tracks the exception' end context 'when the request is missing the user_id field' do let(:params) { { credit_card_validated_at: credit_card_validated_at } } it_behaves_like 'returns an error and tracks the exception' end context 'when there is an unexpected error' do let(:exception) { StandardError.new } before do allow_next_instance_of(::Users::CreditCardValidation) do |instance| allow(instance).to receive(:save).and_raise(exception) end end it_behaves_like 'returns an error and tracks the exception' end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class SetStatusService include Gitlab::Allowable attr_reader :current_user, :target_user, :params def initialize(current_user, params) @current_user = current_user @params = params.dup @target_user = params.delete(:user) || current_user end def execute return false unless can?(current_user, :update_user_status, target_user) if status_cleared? remove_status else set_status end end private def set_status params[:emoji] = UserStatus::DEFAULT_EMOJI if params[:emoji].blank? params[:availability] = UserStatus.availabilities[:not_set] unless new_user_availability bump_user if user_status.update(params) end def remove_status bump_user if UserStatus.delete(target_user.id).nonzero? true end def user_status target_user.status || target_user.build_status end def status_cleared? params[:emoji].blank? && params[:message].blank? && (new_user_availability.blank? || new_user_availability == UserStatus.availabilities[:not_set]) end def new_user_availability UserStatus.availabilities[params[:availability]] end def bump_user # Intentionally not calling `touch` as that will trigger other callbacks # on target_user (e.g. after_touch, after_commit, after_rollback) and we # don't need them to happen here. target_user.update_column(:updated_at, Time.current) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::SetStatusService, feature_category: :user_management do let(:current_user) { create(:user) } subject(:service) { described_class.new(current_user, params) } describe '#execute' do shared_examples_for 'bumps user' do it 'bumps User#updated_at' do expect { service.execute }.to change { current_user.updated_at } end end shared_examples_for 'does not bump user' do it 'does not bump User#updated_at' do expect { service.execute }.not_to change { current_user.updated_at } end end context 'when params are set' do let(:params) { { emoji: 'taurus', message: 'a random status', availability: 'busy' } } it 'creates a status' do service.execute expect(current_user.status.emoji).to eq('taurus') expect(current_user.status.message).to eq('a random status') expect(current_user.status.availability).to eq('busy') end it 'updates a status if it already existed' do create(:user_status, user: current_user) expect { service.execute }.not_to change { UserStatus.count } expect(current_user.status.message).to eq('a random status') end it 'returns true' do create(:user_status, user: current_user) expect(service.execute).to be(true) end it_behaves_like 'bumps user' context 'when setting availability to not_set' do before do params[:availability] = 'not_set' create(:user_status, user: current_user, availability: 'busy') end it 'updates the availability' do expect { service.execute }.to change { current_user.status.availability }.from('busy').to('not_set') end end context 'when the given availability value is not valid' do before do params[:availability] = 'not a valid value' end it 'does not update the status' do user_status = create(:user_status, user: current_user) expect { service.execute }.not_to change { user_status.reload } end end context 'for another user' do let(:target_user) { create(:user) } let(:params) do { emoji: 'taurus', message: 'a random status', user: target_user } end context 'the current user is admin', :enable_admin_mode do let(:current_user) { create(:admin) } it 'changes the status when the current user is allowed to do that' do expect { service.execute }.to change { target_user.status } end end it 'does not update the status if the current user is not allowed' do expect { service.execute }.not_to change { target_user.status } end it_behaves_like 'does not bump user' end end context 'without params' do let(:params) { {} } shared_examples 'removes user status record' do it 'deletes the user status record' do expect { service.execute } .to change { current_user.reload.status }.from(user_status).to(nil) end it_behaves_like 'bumps user' end context 'when user has existing user status record' do let!(:user_status) { create(:user_status, user: current_user) } it_behaves_like 'removes user status record' context 'when not_set is given for availability' do let(:params) { { availability: 'not_set' } } it_behaves_like 'removes user status record' end end context 'when user has no existing user status record' do it_behaves_like 'does not bump user' end end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Users class InProductMarketingEmailRecords attr_reader :records def initialize @records = [] end def save! Users::InProductMarketingEmail.bulk_insert!(@records) @records = [] end def add(user, track: nil, series: nil) @records << Users::InProductMarketingEmail.new( user: user, track: track, series: series, created_at: Time.zone.now, updated_at: Time.zone.now ) end end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe Users::InProductMarketingEmailRecords, feature_category: :onboarding do let_it_be(:user) { create :user } subject(:records) { described_class.new } it 'initializes records' do expect(subject.records).to match_array [] end describe '#save!' do before do allow(Users::InProductMarketingEmail).to receive(:bulk_insert!) records.add(user, track: :team_short, series: 0) records.add(user, track: :create, series: 1) end it 'bulk inserts added records' do expect(Users::InProductMarketingEmail).to receive(:bulk_insert!).with(records.records) records.save! end it 'resets its records' do records.save! expect(records.records).to match_array [] end end describe '#add' do it 'adds a Users::InProductMarketingEmail record to its records', :aggregate_failures do freeze_time do records.add(user, track: :team_short, series: 0) records.add(user, track: :create, series: 1) first, second = records.records expect(first).to be_a Users::InProductMarketingEmail expect(first.track.to_sym).to eq :team_short expect(first.series).to eq 0 expect(first.created_at).to eq Time.zone.now expect(first.updated_at).to eq Time.zone.now expect(second).to be_a Users::InProductMarketingEmail expect(second.track.to_sym).to eq :create expect(second.series).to eq 1 expect(second.created_at).to eq Time.zone.now expect(second.updated_at).to eq Time.zone.now end end end end