INSTRUCTION
stringlengths 202
35.5k
| RESPONSE
stringlengths 75
161k
|
---|---|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class BulkUpdateIntegrationService
include Integrations::BulkOperationHashes
def initialize(integration, batch)
@integration = integration
@batch = batch
end
# rubocop: disable CodeReuse/ActiveRecord
def execute
Integration.transaction do
Integration.where(id: batch_ids).update_all(integration_hash(:update))
if integration.data_fields_present?
integration.data_fields.class.where(data_fields_foreign_key => batch_ids)
.update_all(
data_fields_hash(:update)
)
end
end
end
# rubocop: enable CodeReuse/ActiveRecord
private
attr_reader :integration, :batch
# service_id or integration_id
def data_fields_foreign_key
integration.data_fields.class.reflections['integration'].foreign_key
end
def batch_ids
@batch_ids ||=
if batch.is_a?(ActiveRecord::Relation)
batch.select(:id)
else
batch.map(&:id)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe BulkUpdateIntegrationService, feature_category: :integrations do
include JiraIntegrationHelpers
before_all do
stub_jira_integration_test
end
let(:excluded_attributes) do
%w[
id project_id group_id inherit_from_id instance template
created_at updated_at encrypted_properties encrypted_properties_iv
]
end
let(:batch) do
Integration.inherited_descendants_from_self_or_ancestors_from(subgroup_integration).where(id: group_integration.id..integration.id)
end
let_it_be(:group) { create(:group) }
let_it_be(:subgroup) { create(:group, parent: group) }
let_it_be(:group_integration) { create(:jira_integration, :group, group: group, url: 'http://group.jira.com') }
let_it_be(:excluded_integration) { create(:jira_integration, :group, group: create(:group), url: 'http://another.jira.com', push_events: false) }
let_it_be(:subgroup_integration) do
create(:jira_integration, :group,
group: subgroup,
inherit_from_id: group_integration.id,
url: 'http://subgroup.jira.com',
push_events: true
)
end
let_it_be(:integration) do
create(:jira_integration,
project: create(:project, group: subgroup),
inherit_from_id: subgroup_integration.id,
url: 'http://project.jira.com',
push_events: false
)
end
context 'with inherited integration' do
it 'updates the integration', :aggregate_failures do
described_class.new(subgroup_integration.reload, batch).execute
expect(integration.reload.inherit_from_id).to eq(group_integration.id)
expect(integration.reload.attributes.except(*excluded_attributes))
.to eq(subgroup_integration.reload.attributes.except(*excluded_attributes))
expect(excluded_integration.reload.inherit_from_id).not_to eq(group_integration.id)
expect(excluded_integration.reload.attributes.except(*excluded_attributes))
.not_to eq(subgroup_integration.attributes.except(*excluded_attributes))
end
it 'does not change the created_at timestamp' do
subgroup_integration.update_column(:created_at, Time.utc(2022, 1, 1))
expect do
described_class.new(subgroup_integration, batch).execute
end.not_to change { integration.reload.created_at }
end
it 'sets the updated_at timestamp to the current time', time_travel_to: Time.utc(2022, 1, 1) do
expect do
described_class.new(subgroup_integration, batch).execute
end.to change { integration.reload.updated_at }.to(Time.current)
end
context 'with integration with data fields' do
let(:excluded_attributes) do
%w[id integration_id created_at updated_at encrypted_properties encrypted_properties_iv]
end
it 'updates the data fields from the integration', :aggregate_failures do
described_class.new(subgroup_integration, batch).execute
expect(integration.reload.data_fields.attributes.except(*excluded_attributes))
.to eq(subgroup_integration.reload.data_fields.attributes.except(*excluded_attributes))
expect(integration.data_fields.attributes.except(*excluded_attributes))
.not_to eq(excluded_integration.data_fields.attributes.except(*excluded_attributes))
end
it 'does not change the created_at timestamp' do
subgroup_integration.data_fields.update_column(:created_at, Time.utc(2022, 1, 2))
expect do
described_class.new(subgroup_integration, batch).execute
end.not_to change { integration.data_fields.reload.created_at }
end
it 'sets the updated_at timestamp to the current time', time_travel_to: Time.utc(2022, 1, 1) do
expect do
described_class.new(subgroup_integration, batch).execute
end.to change { integration.data_fields.reload.updated_at }.to(Time.current)
end
end
end
it 'works with batch as an ActiveRecord::Relation' do
expect do
described_class.new(group_integration, Integration.where(id: integration.id)).execute
end.to change { integration.reload.url }.to(group_integration.url)
end
it 'works with batch as an array of ActiveRecord objects' do
expect do
described_class.new(group_integration, [integration]).execute
end.to change { integration.reload.url }.to(group_integration.url)
end
context 'with different foreign key of data_fields' do
let(:integration) { create(:zentao_integration, project: create(:project, group: group)) }
let(:group_integration) do
create(:zentao_integration, :group,
group: group,
url: 'https://group.zentao.net',
api_token: 'GROUP_TOKEN',
zentao_product_xid: '1'
)
end
it 'works with batch as an array of ActiveRecord objects' do
expect do
described_class.new(group_integration, [integration]).execute
end.to change { integration.reload.url }.to(group_integration.url)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class ServiceResponse
def self.success(message: nil, payload: {}, http_status: :ok)
new(
status: :success,
message: message,
payload: payload,
http_status: http_status
)
end
def self.error(message:, payload: {}, http_status: nil, reason: nil)
new(
status: :error,
message: message,
payload: payload,
http_status: http_status,
reason: reason
)
end
attr_reader :status, :message, :http_status, :payload, :reason
def initialize(status:, message: nil, payload: {}, http_status: nil, reason: nil)
self.status = status
self.message = message
self.payload = payload
self.http_status = http_status
self.reason = reason
end
def log_and_raise_exception(as: StandardError, **extra_data)
error_tracking(as) do |ex|
Gitlab::ErrorTracking.log_and_raise_exception(ex, extra_data)
end
end
def track_exception(as: StandardError, **extra_data)
error_tracking(as) do |ex|
Gitlab::ErrorTracking.track_exception(ex, extra_data)
end
end
def track_and_raise_exception(as: StandardError, **extra_data)
error_tracking(as) do |ex|
Gitlab::ErrorTracking.track_and_raise_exception(ex, extra_data)
end
end
def [](key)
to_h[key]
end
def to_h
(payload || {}).merge(
status: status,
message: message,
http_status: http_status,
reason: reason)
end
def deconstruct_keys(keys)
to_h.slice(*keys)
end
def success?
status == :success
end
def error?
status == :error
end
def errors
return [] unless error?
Array.wrap(message)
end
private
attr_writer :status, :message, :http_status, :payload, :reason
def error_tracking(error_klass)
if error?
ex = error_klass.new(message)
yield ex
end
self
end
end
``` | # frozen_string_literal: true
require 'fast_spec_helper'
require 're2'
require_relative '../../app/services/service_response'
require_relative '../../lib/gitlab/error_tracking'
RSpec.describe ServiceResponse, feature_category: :shared do
describe '.success' do
it 'creates a successful response without a message' do
expect(described_class.success).to be_success
end
it 'creates a successful response with a message' do
response = described_class.success(message: 'Good orange')
expect(response).to be_success
expect(response.message).to eq('Good orange')
end
it 'creates a successful response with payload' do
response = described_class.success(payload: { good: 'orange' })
expect(response).to be_success
expect(response.payload).to eq(good: 'orange')
end
it 'creates a successful response with default HTTP status' do
response = described_class.success
expect(response).to be_success
expect(response.http_status).to eq(:ok)
end
it 'creates a successful response with custom HTTP status' do
response = described_class.success(http_status: 204)
expect(response).to be_success
expect(response.http_status).to eq(204)
end
end
describe '.error' do
it 'creates an error response without HTTP status' do
response = described_class.error(message: 'Bad apple')
expect(response).to be_error
expect(response.message).to eq('Bad apple')
end
it 'creates an error response with HTTP status' do
response = described_class.error(message: 'Bad apple', http_status: 400)
expect(response).to be_error
expect(response.message).to eq('Bad apple')
expect(response.http_status).to eq(400)
end
it 'creates an error response with payload' do
response = described_class.error(message: 'Bad apple', payload: { bad: 'apple' })
expect(response).to be_error
expect(response.message).to eq('Bad apple')
expect(response.payload).to eq(bad: 'apple')
end
it 'creates an error response with a reason' do
response = described_class.error(message: 'Bad apple', reason: :permission_denied)
expect(response).to be_error
expect(response.message).to eq('Bad apple')
expect(response.reason).to eq(:permission_denied)
end
end
describe '#success?' do
it 'returns true for a successful response' do
expect(described_class.success.success?).to eq(true)
end
it 'returns false for a failed response' do
expect(described_class.error(message: 'Bad apple').success?).to eq(false)
end
end
describe '#error?' do
it 'returns false for a successful response' do
expect(described_class.success.error?).to eq(false)
end
it 'returns true for a failed response' do
expect(described_class.error(message: 'Bad apple').error?).to eq(true)
end
end
describe '#errors' do
it 'returns an empty array for a successful response' do
expect(described_class.success.errors).to be_empty
end
it 'returns an array with a correct message for an error response' do
expect(described_class.error(message: 'error message').errors).to eq(['error message'])
end
end
describe '#track_and_raise_exception' do
context 'when successful' do
let(:response) { described_class.success }
it 'returns self' do
expect(response.track_and_raise_exception).to be response
end
end
context 'when an error' do
let(:response) { described_class.error(message: 'bang') }
it 'tracks and raises' do
expect(::Gitlab::ErrorTracking).to receive(:track_and_raise_exception)
.with(StandardError.new('bang'), {})
response.track_and_raise_exception
end
it 'allows specification of error class' do
error = Class.new(StandardError)
expect(::Gitlab::ErrorTracking).to receive(:track_and_raise_exception)
.with(error.new('bang'), {})
response.track_and_raise_exception(as: error)
end
it 'allows extra data for tracking' do
expect(::Gitlab::ErrorTracking).to receive(:track_and_raise_exception)
.with(StandardError.new('bang'), { foo: 1, bar: 2 })
response.track_and_raise_exception(foo: 1, bar: 2)
end
end
end
describe '#track_exception' do
context 'when successful' do
let(:response) { described_class.success }
it 'returns self' do
expect(response.track_exception).to be response
end
end
context 'when an error' do
let(:response) { described_class.error(message: 'bang') }
it 'tracks' do
expect(::Gitlab::ErrorTracking).to receive(:track_exception)
.with(StandardError.new('bang'), {})
expect(response.track_exception).to be response
end
it 'allows specification of error class' do
error = Class.new(StandardError)
expect(::Gitlab::ErrorTracking).to receive(:track_exception)
.with(error.new('bang'), {})
expect(response.track_exception(as: error)).to be response
end
it 'allows extra data for tracking' do
expect(::Gitlab::ErrorTracking).to receive(:track_exception)
.with(StandardError.new('bang'), { foo: 1, bar: 2 })
expect(response.track_exception(foo: 1, bar: 2)).to be response
end
end
end
describe '#log_and_raise_exception' do
context 'when successful' do
let(:response) { described_class.success }
it 'returns self' do
expect(response.log_and_raise_exception).to be response
end
end
context 'when an error' do
let(:response) { described_class.error(message: 'bang') }
it 'logs' do
expect(::Gitlab::ErrorTracking).to receive(:log_and_raise_exception)
.with(StandardError.new('bang'), {})
response.log_and_raise_exception
end
it 'allows specification of error class' do
error = Class.new(StandardError)
expect(::Gitlab::ErrorTracking).to receive(:log_and_raise_exception)
.with(error.new('bang'), {})
response.log_and_raise_exception(as: error)
end
it 'allows extra data for tracking' do
expect(::Gitlab::ErrorTracking).to receive(:log_and_raise_exception)
.with(StandardError.new('bang'), { foo: 1, bar: 2 })
response.log_and_raise_exception(foo: 1, bar: 2)
end
end
end
describe '#deconstruct_keys' do
it 'supports pattern matching' do
status =
case described_class.error(message: 'Bad apple')
in { status: Symbol => status }
status
else
raise
end
expect(status).to eq(:error)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class BulkCreateIntegrationService
include Integrations::BulkOperationHashes
def initialize(integration, batch, association)
@integration = integration
@batch = batch
@association = association
end
def execute
integration_list = Integrations::IntegrationList.new(batch, integration_hash(:create), association).to_array
Integration.transaction do
results = bulk_insert(*integration_list)
if integration.data_fields_present?
data_list = DataList.new(results, data_fields_hash(:create), integration.data_fields.class).to_array
bulk_insert(*data_list)
end
end
end
private
attr_reader :integration, :batch, :association
def bulk_insert(klass, columns, values_array)
items_to_insert = values_array.map { |array| Hash[columns.zip(array)] }
klass.insert_all(items_to_insert, returning: [:id])
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe BulkCreateIntegrationService, feature_category: :integrations do
include JiraIntegrationHelpers
before_all do
stub_jira_integration_test
end
let_it_be(:excluded_group) { create(:group) }
let_it_be(:excluded_project) { create(:project, group: excluded_group) }
let(:instance_integration) { create(:jira_integration, :instance) }
let(:excluded_attributes) do
%w[
id project_id group_id inherit_from_id instance template
created_at updated_at
encrypted_properties encrypted_properties_iv
]
end
shared_examples 'creates integration successfully' do
def attributes(record)
record.reload.attributes.except(*excluded_attributes)
end
it 'updates the inherited integrations' do
described_class.new(integration, batch, association).execute
expect(attributes(created_integration)).to eq attributes(integration)
end
context 'integration with data fields' do
let(:excluded_attributes) { %w[id service_id integration_id created_at updated_at] }
it 'updates the data fields from inherited integrations' do
described_class.new(integration, batch, association).execute
expect(attributes(created_integration.data_fields))
.to eq attributes(integration.data_fields)
end
it 'sets created_at and updated_at timestamps', :freeze_time do
described_class.new(integration, batch, association).execute
expect(created_integration.data_fields.reload).to have_attributes(
created_at: eq(Time.current),
updated_at: eq(Time.current)
)
end
end
it 'updates inherit_from_id attributes' do
described_class.new(integration, batch, association).execute
expect(created_integration.reload.inherit_from_id).to eq(inherit_from_id)
end
it 'sets created_at and updated_at timestamps', :freeze_time do
described_class.new(integration, batch, association).execute
expect(created_integration.reload).to have_attributes(
created_at: eq(Time.current),
updated_at: eq(Time.current)
)
end
end
context 'passing an instance-level integration' do
let(:integration) { instance_integration }
let(:inherit_from_id) { integration.id }
context 'with a project association' do
let!(:project) { create(:project) }
let(:created_integration) { project.jira_integration }
let(:batch) { Project.where(id: project.id) }
let(:association) { 'project' }
it_behaves_like 'creates integration successfully'
end
context 'with a group association' do
let!(:group) { create(:group) }
let(:created_integration) { Integration.find_by(group: group) }
let(:batch) { Group.where(id: group.id) }
let(:association) { 'group' }
it_behaves_like 'creates integration successfully'
end
end
context 'passing a group integration' do
let_it_be(:group) { create(:group) }
context 'with a project association' do
let!(:project) { create(:project, group: group) }
let(:integration) { create(:jira_integration, :group, group: group) }
let(:created_integration) { project.jira_integration }
let(:batch) { Project.where(id: Project.minimum(:id)..Project.maximum(:id)).without_integration(integration).in_namespace(integration.group.self_and_descendants) }
let(:association) { 'project' }
let(:inherit_from_id) { integration.id }
it_behaves_like 'creates integration successfully'
context 'with different foreign key of data_fields' do
let(:integration) { create(:zentao_integration, :group, group: group) }
let(:created_integration) { project.zentao_integration }
it_behaves_like 'creates integration successfully'
end
end
context 'with a group association' do
let!(:subgroup) { create(:group, parent: group) }
let(:integration) { create(:jira_integration, :group, group: group, inherit_from_id: instance_integration.id) }
let(:created_integration) { Integration.find_by(group: subgroup) }
let(:batch) { Group.where(id: subgroup.id) }
let(:association) { 'group' }
let(:inherit_from_id) { instance_integration.id }
it_behaves_like 'creates integration successfully'
context 'with different foreign key of data_fields' do
let(:integration) { create(:zentao_integration, :group, group: group, inherit_from_id: instance_integration.id) }
it_behaves_like 'creates integration successfully'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
# PostReceiveService class
#
# Used for scheduling related jobs after a push action has been performed
class PostReceiveService
attr_reader :user, :repository, :project, :params
def initialize(user, repository, project, params)
@user = user
@repository = repository
@project = project
@params = params
end
def execute
response = Gitlab::InternalPostReceive::Response.new
push_options = Gitlab::PushOptions.new(params[:push_options])
mr_options = push_options.get(:merge_request)
response.reference_counter_decreased = Gitlab::ReferenceCounter.new(params[:gl_repository]).decrease
# The PostReceive worker will normally invalidate the cache. However, it
# runs asynchronously. If push options require us to create a new merge
# request synchronously, we can't rely on that, so invalidate the cache here
repository&.expire_branches_cache if mr_options&.fetch(:create, false)
PostReceive.perform_async(params[:gl_repository], params[:identifier],
params[:changes], push_options.as_json)
if mr_options.present?
message = process_mr_push_options(mr_options, params[:changes])
response.add_alert_message(message)
end
response.add_alert_message(broadcast_message)
response.add_merge_request_urls(merge_request_urls)
# Neither User nor Repository are guaranteed to be returned; an orphaned write deploy
# key could be used
if user && repository
redirect_message = Gitlab::Checks::ContainerMoved.fetch_message(user, repository)
project_created_message = Gitlab::Checks::ProjectCreated.fetch_message(user, repository)
response.add_basic_message(redirect_message)
response.add_basic_message(project_created_message)
record_onboarding_progress
end
response
end
def process_mr_push_options(push_options, changes)
Gitlab::QueryLimiting.disable!('https://gitlab.com/gitlab-org/gitlab/-/issues/28494')
return unless repository
unless repository.repo_type.project?
return push_options_warning('Push options are only supported for projects')
end
service = ::MergeRequests::PushOptionsHandlerService.new(
project: project, current_user: user, changes: changes, push_options: push_options
).execute
if service.errors.present?
push_options_warning(service.errors.join("\n\n"))
end
end
def push_options_warning(warning)
options = Array.wrap(params[:push_options]).map { |p| "'#{p}'" }.join(' ')
"WARNINGS:\nError encountered with push options #{options}: #{warning}"
end
def merge_request_urls
return [] unless repository&.repo_type&.project?
::MergeRequests::GetUrlsService.new(project: project).execute(params[:changes])
end
private
def broadcast_message
banner = nil
if project
scoped_messages =
System::BroadcastMessage.current_banner_messages(current_path: project.full_path).select do |message|
message.target_path.present? && message.matches_current_path(project.full_path) && message.show_in_cli?
end
banner = scoped_messages.last
end
banner ||= System::BroadcastMessage.current_show_in_cli_banner_messages.last
banner&.message
end
def record_onboarding_progress
return unless project
Onboarding::ProgressService.new(project.namespace).execute(action: :git_write)
end
end
PostReceiveService.prepend_mod_with('PostReceiveService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe PostReceiveService, feature_category: :team_planning do
include GitlabShellHelpers
include Gitlab::Routing
let_it_be(:user) { create(:user) }
let_it_be(:project) { create(:project, :repository, :wiki_repo, namespace: user.namespace) }
let_it_be(:project_snippet) { create(:project_snippet, :repository, project: project, author: user) }
let_it_be(:personal_snippet) { create(:personal_snippet, :repository, author: user) }
let(:identifier) { 'key-123' }
let(:gl_repository) { "project-#{project.id}" }
let(:branch_name) { 'feature' }
let(:reference_counter) { double('ReferenceCounter') }
let(:push_options) { ['ci.skip', 'another push option'] }
let(:repository) { project.repository }
let(:changes) do
"#{Gitlab::Git::BLANK_SHA} 570e7b2abdd848b95f2f578043fc23bd6f6fd24d refs/heads/#{branch_name}"
end
let(:params) do
{
gl_repository: gl_repository,
identifier: identifier,
changes: changes,
push_options: push_options
}
end
let(:service) { described_class.new(user, repository, project, params) }
let(:response) { service.execute }
subject { response.messages.as_json }
context 'when project is nil' do
let(:gl_repository) { "snippet-#{personal_snippet.id}" }
let(:project) { nil }
let(:repository) { personal_snippet.repository }
it 'does not return error' do
expect(subject).to be_empty
end
it_behaves_like 'does not record an onboarding progress action'
end
context 'when repository is nil' do
let(:repository) { nil }
it 'does not return error' do
expect(subject).to be_empty
end
end
context 'when both repository and project are nil' do
let(:gl_repository) { "snippet-#{personal_snippet.id}" }
let(:project) { nil }
let(:repository) { nil }
it 'does not return error' do
expect(subject).to be_empty
end
end
shared_examples 'post_receive_service actions' do
it 'enqueues a PostReceive worker job' do
expect(PostReceive).to receive(:perform_async)
.with(gl_repository, identifier, changes, { ci: { skip: true } })
subject
end
it 'decreases the reference counter and returns the result' do
expect(Gitlab::ReferenceCounter).to receive(:new).with(gl_repository)
.and_return(reference_counter)
expect(reference_counter).to receive(:decrease).and_return(true)
expect(response.reference_counter_decreased).to be(true)
end
it_behaves_like 'records an onboarding progress action', :git_write do
let(:namespace) { project.namespace }
end
end
context 'with Project' do
it_behaves_like 'post_receive_service actions'
it 'returns link to create new merge request' do
message = <<~MESSAGE.strip
To create a merge request for #{branch_name}, visit:
http://#{Gitlab.config.gitlab.host}/#{project.full_path}/-/merge_requests/new?merge_request%5Bsource_branch%5D=#{branch_name}
MESSAGE
expect(subject).to include(build_basic_message(message))
end
it 'returns the link to an existing merge request when it exists' do
merge_request = create(:merge_request, source_project: project, source_branch: branch_name, target_branch: 'master')
message = <<~MESSAGE.strip
View merge request for feature:
#{project_merge_request_url(project, merge_request)}
MESSAGE
expect(subject).to include(build_basic_message(message))
end
context 'when printing_merge_request_link_enabled is false' do
let(:project) { create(:project, printing_merge_request_link_enabled: false) }
it 'returns no merge request messages' do
expect(subject).to be_blank
end
end
it 'does not invoke MergeRequests::PushOptionsHandlerService' do
expect(MergeRequests::PushOptionsHandlerService).not_to receive(:new)
subject
end
context 'when there are merge_request push options' do
let(:params) { super().merge(push_options: ['merge_request.create']) }
before do
project.add_developer(user)
end
it 'invalidates the branch name cache' do
expect(service.repository).to receive(:expire_branches_cache).and_call_original
subject
end
it 'invokes MergeRequests::PushOptionsHandlerService' do
expect(MergeRequests::PushOptionsHandlerService).to receive(:new).and_call_original
subject
end
it 'creates a new merge request' do
expect { Sidekiq::Testing.fake! { subject } }.to change(MergeRequest, :count).by(1)
end
it 'links to the newly created merge request' do
message = <<~MESSAGE.strip
View merge request for #{branch_name}:
http://#{Gitlab.config.gitlab.host}/#{project.full_path}/-/merge_requests/1
MESSAGE
expect(subject).to include(build_basic_message(message))
end
it 'adds errors on the service instance to warnings' do
expect_any_instance_of(
MergeRequests::PushOptionsHandlerService
).to receive(:errors).at_least(:once).and_return(['my error'])
message = "WARNINGS:\nError encountered with push options 'merge_request.create': my error"
expect(subject).to include(build_alert_message(message))
end
it 'adds ActiveRecord errors on invalid MergeRequest records to warnings' do
invalid_merge_request = MergeRequest.new
invalid_merge_request.errors.add(:base, 'my error')
message = "WARNINGS:\nError encountered with push options 'merge_request.create': my error"
expect_any_instance_of(
MergeRequests::CreateService
).to receive(:execute).and_return(invalid_merge_request)
expect(subject).to include(build_alert_message(message))
end
end
end
context 'with PersonalSnippet' do
let(:gl_repository) { "snippet-#{personal_snippet.id}" }
let(:repository) { personal_snippet.repository }
it_behaves_like 'post_receive_service actions'
it 'does not return link to create new merge request' do
expect(subject).to be_empty
end
it 'does not return the link to an existing merge request when it exists' do
create(:merge_request, source_project: project, source_branch: branch_name, target_branch: 'master')
expect(subject).to be_empty
end
end
context 'with ProjectSnippet' do
let(:gl_repository) { "snippet-#{project_snippet.id}" }
let(:repository) { project_snippet.repository }
it_behaves_like 'post_receive_service actions'
it 'does not return link to create new merge request' do
expect(subject).to be_empty
end
it 'does not return the link to an existing merge request when it exists' do
create(:merge_request, source_project: project, source_branch: branch_name, target_branch: 'master')
expect(subject).to be_empty
end
end
context 'broadcast message banner exists' do
it 'outputs a broadcast message when show_in_cli is true' do
broadcast_message = create(:broadcast_message, show_in_cli: true)
expect(subject).to include(build_alert_message(broadcast_message.message))
end
it 'does not output a broadcast message when show_in_cli is false' do
create(:broadcast_message, show_in_cli: false)
expect(has_alert_messages?(subject)).to be_falsey
end
end
context 'broadcast message notification exists' do
it 'does not output a broadcast message' do
create(:broadcast_message, :notification)
expect(has_alert_messages?(subject)).to be_falsey
end
end
context 'broadcast message does not exist' do
it 'does not output a broadcast message' do
expect(has_alert_messages?(subject)).to be_falsey
end
end
context 'nil broadcast message' do
it 'does not output a broadcast message' do
allow(System::BroadcastMessage).to receive(:current).and_return(nil)
expect(has_alert_messages?(subject)).to be_falsey
end
end
context "broadcast message has a target_path" do
let!(:older_scoped_message) do
create(:broadcast_message, message: "Old top secret", target_path: "/company/sekrit-project")
end
let!(:latest_scoped_message) do
create(:broadcast_message, message: "Top secret", target_path: "/company/sekrit-project")
end
let!(:unscoped_message) do
create(:broadcast_message, message: "Hi")
end
context "no project path matches" do
it "does not output the scoped broadcast messages" do
expect(subject).not_to include(build_alert_message(older_scoped_message.message))
expect(subject).not_to include(build_alert_message(latest_scoped_message.message))
end
it "does output another message that doesn't have a target_path" do
expect(subject).to include(build_alert_message(unscoped_message.message))
end
end
context "project path matches" do
before do
allow(project).to receive(:full_path).and_return("company/sekrit-project")
end
it "does output the latest scoped broadcast message" do
expect(subject).to include(build_alert_message(latest_scoped_message.message))
end
it "does not output the older scoped broadcast message" do
expect(subject).not_to include(build_alert_message(older_scoped_message.message))
end
it "does not output another message that doesn't have a target_path" do
expect(subject).not_to include(build_alert_message(unscoped_message.message))
end
end
end
context 'with a redirected data' do
it 'returns redirected message on the response' do
project_moved = Gitlab::Checks::ContainerMoved.new(project.repository, user, 'http', 'foo/baz')
project_moved.add_message
expect(subject).to include(build_basic_message(project_moved.message))
end
end
context 'with new project data' do
it 'returns new project message on the response' do
project_created = Gitlab::Checks::ProjectCreated.new(project.repository, user, 'http')
project_created.add_message
expect(subject).to include(build_basic_message(project_created.message))
end
end
describe '#process_mr_push_options' do
context 'when repository belongs to a snippet' do
context 'with PersonalSnippet' do
let(:repository) { personal_snippet.repository }
it 'returns an error message' do
result = service.process_mr_push_options(push_options, changes)
expect(result).to match('Push options are only supported for projects')
end
end
context 'with ProjectSnippet' do
let(:repository) { project_snippet.repository }
it 'returns an error message' do
result = service.process_mr_push_options(push_options, changes)
expect(result).to match('Push options are only supported for projects')
end
end
end
end
describe '#merge_request_urls' do
context 'when repository belongs to a snippet' do
context 'with PersonalSnippet' do
let(:repository) { personal_snippet.repository }
it 'returns an empty array' do
expect(service.merge_request_urls).to be_empty
end
end
context 'with ProjectSnippet' do
let(:repository) { project_snippet.repository }
it 'returns an empty array' do
expect(service.merge_request_urls).to be_empty
end
end
end
end
def build_alert_message(message)
{ 'type' => 'alert', 'message' => message }
end
def build_basic_message(message)
{ 'type' => 'basic', 'message' => message }
end
def has_alert_messages?(messages)
messages.any? do |message|
message['type'] == 'alert'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
class PreviewMarkdownService < BaseService
def execute
text, commands = explain_quick_actions(params[:text])
users = find_user_references(text)
suggestions = find_suggestions(text)
success(
text: text,
users: users,
suggestions: suggestions,
commands: commands.join('<br>')
)
end
private
def quick_action_types
%w[Issue MergeRequest Commit WorkItem]
end
def explain_quick_actions(text)
return text, [] unless quick_action_types.include?(target_type)
quick_actions_service = QuickActions::InterpretService.new(project, current_user)
quick_actions_service.explain(text, find_commands_target, keep_actions: params[:render_quick_actions])
end
def find_user_references(text)
extractor = Gitlab::ReferenceExtractor.new(project, current_user)
extractor.analyze(text, author: current_user)
extractor.users.map(&:username)
end
def find_suggestions(text)
return [] unless preview_sugestions?
position = Gitlab::Diff::Position.new(new_path: params[:file_path],
new_line: params[:line].to_i,
base_sha: params[:base_sha],
head_sha: params[:head_sha],
start_sha: params[:start_sha])
Gitlab::Diff::SuggestionsParser.parse(text, position: position,
project: project,
supports_suggestion: params[:preview_suggestions])
end
def preview_sugestions?
params[:preview_suggestions] &&
target_type == 'MergeRequest' &&
Ability.allowed?(current_user, :download_code, project)
end
def find_commands_target
QuickActions::TargetService
.new(project, current_user, group: params[:group])
.execute(target_type, target_id)
end
def target_type
params[:target_type]
end
def target_id
params[:target_id]
end
end
PreviewMarkdownService.prepend_mod_with('PreviewMarkdownService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe PreviewMarkdownService, feature_category: :team_planning do
let(:user) { create(:user) }
let(:project) { create(:project, :repository) }
before do
project.add_developer(user)
end
describe 'user references' do
let(:params) { { text: "Take a look #{user.to_reference}" } }
let(:service) { described_class.new(project, user, params) }
it 'returns users referenced in text' do
result = service.execute
expect(result[:users]).to eq [user.username]
end
end
describe 'suggestions' do
let(:merge_request) do
create(:merge_request, target_project: project, source_project: project)
end
let(:text) { "```suggestion\nfoo\n```" }
let(:params) do
suggestion_params.merge(
text: text,
target_type: 'MergeRequest',
target_id: merge_request.iid
)
end
let(:service) { described_class.new(project, user, params) }
context 'when preview markdown param is present' do
let(:path) { "files/ruby/popen.rb" }
let(:line) { 10 }
let(:diff_refs) { merge_request.diff_refs }
let(:suggestion_params) do
{
preview_suggestions: true,
file_path: path,
line: line,
base_sha: diff_refs.base_sha,
start_sha: diff_refs.start_sha,
head_sha: diff_refs.head_sha
}
end
it 'returns suggestions referenced in text' do
position = Gitlab::Diff::Position.new(new_path: path, new_line: line, diff_refs: diff_refs)
expect(Gitlab::Diff::SuggestionsParser)
.to receive(:parse)
.with(
text,
position: position,
project: merge_request.project,
supports_suggestion: true
)
.and_call_original
result = service.execute
expect(result[:suggestions]).to all(be_a(Gitlab::Diff::Suggestion))
end
context 'when user is not authorized' do
let(:another_user) { create(:user) }
let(:service) { described_class.new(project, another_user, params) }
before do
project.add_guest(another_user)
end
it 'returns no suggestions' do
result = service.execute
expect(result[:suggestions]).to be_empty
end
end
end
context 'when preview markdown param is not present' do
let(:suggestion_params) do
{
preview_suggestions: false
}
end
it 'returns suggestions referenced in text' do
result = service.execute
expect(result[:suggestions]).to eq([])
end
end
end
context 'new note with quick actions' do
let(:issue) { create(:issue, project: project) }
let(:params) do
{
text: "Please do it\n/assign #{user.to_reference}",
target_type: 'Issue',
target_id: issue.id
}
end
let(:service) { described_class.new(project, user, params) }
it 'removes quick actions from text' do
result = service.execute
expect(result[:text]).to eq 'Please do it'
end
context 'when render_quick_actions' do
it 'keeps quick actions' do
params[:render_quick_actions] = true
result = service.execute
expect(result[:text]).to eq "Please do it\n\n/assign #{user.to_reference}"
end
end
it 'explains quick actions effect' do
result = service.execute
expect(result[:commands]).to eq "Assigns #{user.to_reference}."
end
end
context 'merge request description' do
let(:params) do
{
text: "My work\n/estimate 2y",
target_type: 'MergeRequest'
}
end
let(:service) { described_class.new(project, user, params) }
it 'removes quick actions from text' do
result = service.execute
expect(result[:text]).to eq 'My work'
end
it 'explains quick actions effect' do
result = service.execute
expect(result[:commands]).to eq 'Sets time estimate to 2y.'
end
end
context 'commit description' do
let(:project) { create(:project, :repository) }
let(:commit) { project.commit }
let(:params) do
{
text: "My work\n/tag v1.2.3 Stable release",
target_type: 'Commit',
target_id: commit.id
}
end
let(:service) { described_class.new(project, user, params) }
it 'removes quick actions from text' do
result = service.execute
expect(result[:text]).to eq 'My work'
end
it 'explains quick actions effect' do
result = service.execute
expect(result[:commands]).to eq 'Tags this commit to v1.2.3 with "Stable release".'
end
end
context 'note with multiple quick actions' do
let(:issue) { create(:issue, project: project) }
let(:params) do
{
text: "/confidential\n/due 2001-12-31\n/estimate 2y\n/assign #{user.to_reference}",
target_type: 'Issue',
target_id: issue.id
}
end
let(:service) { described_class.new(project, user, params) }
it 'renders quick actions on multiple lines' do
result = service.execute
expect(result[:commands]).to eq "Makes this issue confidential.<br>Sets the due date to Dec 31, 2001.<br>" \
"Sets time estimate to 2y.<br>Assigns #{user.to_reference}."
end
end
context 'work item quick action types' do
let(:work_item) { create(:work_item, :task, project: project) }
let(:params) do
{
text: "/title new title",
target_type: 'WorkItem',
target_id: work_item.iid
}
end
let(:result) { described_class.new(project, user, params).execute }
it 'renders the quick action preview' do
expect(result[:commands]).to eq "Changes the title to \"new title\"."
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ProtectedBranches
class CacheService < ProtectedBranches::BaseService
CACHE_ROOT_KEY = 'cache:gitlab:protected_branch'
TTL_UNSET = -1
CACHE_EXPIRE_IN = 1.day
CACHE_LIMIT = 1000
def fetch(ref_name, dry_run: false, &block)
record = OpenSSL::Digest::SHA256.hexdigest(ref_name)
with_redis do |redis|
cached_result = redis.hget(redis_key, record)
if cached_result.nil?
metrics.increment_cache_miss
else
metrics.increment_cache_hit
decoded_result = Gitlab::Redis::Boolean.decode(cached_result)
end
# If we're dry-running, don't break because we need to check against
# the real value to ensure the cache is working properly.
# If the result is nil we'll need to run the block, so don't break yet.
break decoded_result unless dry_run || decoded_result.nil?
calculated_value = metrics.observe_cache_generation(&block)
check_and_log_discrepancy(decoded_result, calculated_value, ref_name) if dry_run
redis.hset(redis_key, record, Gitlab::Redis::Boolean.encode(calculated_value))
# We don't want to extend cache expiration time
if redis.ttl(redis_key) == TTL_UNSET
redis.expire(redis_key, CACHE_EXPIRE_IN)
end
# If the cache record has too many elements, then something went wrong and
# it's better to drop the cache key.
if redis.hlen(redis_key) > CACHE_LIMIT
redis.unlink(redis_key)
end
calculated_value
end
end
def refresh
with_redis { |redis| redis.unlink(redis_key) }
end
private
def with_redis(&block)
Gitlab::Redis::Cache.with(&block) # rubocop:disable CodeReuse/ActiveRecord
end
def check_and_log_discrepancy(cached_value, real_value, ref_name)
return if cached_value.nil?
return if cached_value == real_value
encoded_ref_name = Gitlab::EncodingHelper.encode_utf8_with_replacement_character(ref_name)
log_error(
'class' => self.class.name,
'message' => "Cache mismatch '#{encoded_ref_name}': cached value: #{cached_value}, real value: #{real_value}",
'record_class' => project_or_group.class.name,
'record_id' => project_or_group.id,
'record_path' => project_or_group.full_path
)
end
def redis_key
group = project_or_group.is_a?(Group) ? project_or_group : project_or_group.group
@redis_key ||= if allow_protected_branches_for_group?(group)
[CACHE_ROOT_KEY, project_or_group.class.name, project_or_group.id].join(':')
else
[CACHE_ROOT_KEY, project_or_group.id].join(':')
end
end
def allow_protected_branches_for_group?(group)
Feature.enabled?(:group_protected_branches, group) ||
Feature.enabled?(:allow_protected_branches_for_group, group)
end
def metrics
@metrics ||= Gitlab::Cache::Metrics.new(cache_metadata)
end
def cache_metadata
Gitlab::Cache::Metadata.new(
cache_identifier: "#{self.class}#fetch",
feature_category: :source_code_management,
backing_resource: :cpu
)
end
end
end
``` | # frozen_string_literal: true
# rubocop:disable Style/RedundantFetchBlock
#
require 'spec_helper'
RSpec.describe ProtectedBranches::CacheService, :clean_gitlab_redis_cache, feature_category: :compliance_management do
shared_examples 'execute with entity' do
subject(:service) { described_class.new(entity, user) }
let(:immediate_expiration) { 0 }
describe '#fetch' do
it 'caches the value' do
expect(service.fetch('main') { true }).to eq(true)
expect(service.fetch('not-found') { false }).to eq(false)
# Uses cached values
expect(service.fetch('main') { false }).to eq(true)
expect(service.fetch('not-found') { true }).to eq(false)
end
it 'sets expiry on the key' do
stub_const("#{described_class.name}::CACHE_EXPIRE_IN", immediate_expiration)
expect(service.fetch('main') { true }).to eq(true)
expect(service.fetch('not-found') { false }).to eq(false)
expect(service.fetch('main') { false }).to eq(false)
expect(service.fetch('not-found') { true }).to eq(true)
end
it 'does not set an expiry on the key after the hash is already created' do
expect(service.fetch('main') { true }).to eq(true)
stub_const("#{described_class.name}::CACHE_EXPIRE_IN", immediate_expiration)
expect(service.fetch('not-found') { false }).to eq(false)
expect(service.fetch('main') { false }).to eq(true)
expect(service.fetch('not-found') { true }).to eq(false)
end
context 'when CACHE_LIMIT is exceeded' do
before do
stub_const("#{described_class.name}::CACHE_LIMIT", 2)
end
it 'recreates cache' do
expect(service.fetch('main') { true }).to eq(true)
expect(service.fetch('not-found') { false }).to eq(false)
# Uses cached values
expect(service.fetch('main') { false }).to eq(true)
expect(service.fetch('not-found') { true }).to eq(false)
# Overflow
expect(service.fetch('new-branch') { true }).to eq(true)
# Refreshes values
expect(service.fetch('main') { false }).to eq(false)
expect(service.fetch('not-found') { true }).to eq(true)
end
end
context 'when dry_run is on' do
it 'does not use cached value' do
expect(service.fetch('main', dry_run: true) { true }).to eq(true)
expect(service.fetch('main', dry_run: true) { false }).to eq(false)
end
context 'when cache mismatch' do
it 'logs an error' do
expect(service.fetch('main', dry_run: true) { true }).to eq(true)
expect(Gitlab::AppLogger).to receive(:error).with(
{
'class' => described_class.name,
'message' => /Cache mismatch/,
'record_class' => entity.class.name,
'record_id' => entity.id,
'record_path' => entity.full_path
}
)
expect(service.fetch('main', dry_run: true) { false }).to eq(false)
end
end
context 'when cache matches' do
it 'does not log an error' do
expect(service.fetch('main', dry_run: true) { true }).to eq(true)
expect(Gitlab::AppLogger).not_to receive(:error)
expect(service.fetch('main', dry_run: true) { true }).to eq(true)
end
end
end
end
describe '#refresh' do
it 'clears cached values' do
expect(service.fetch('main') { true }).to eq(true)
expect(service.fetch('not-found') { false }).to eq(false)
service.refresh
# Recreates cache
expect(service.fetch('main') { false }).to eq(false)
expect(service.fetch('not-found') { true }).to eq(true)
end
end
describe 'metrics' do
it 'records hit ratio metrics' do
expect_next_instance_of(Gitlab::Cache::Metrics) do |metrics|
expect(metrics).to receive(:increment_cache_miss).once
expect(metrics).to receive(:increment_cache_hit).exactly(4).times
end
5.times { service.fetch('main') { true } }
end
end
end
context 'with entity project' do
let_it_be_with_reload(:entity) { create(:project) }
let(:user) { entity.first_owner }
it_behaves_like 'execute with entity'
end
context 'with entity group' do
let_it_be_with_reload(:entity) { create(:group) }
let_it_be_with_reload(:user) { create(:user) }
before do
entity.add_owner(user)
end
context 'when feature flag enabled' do
it_behaves_like 'execute with entity'
end
context 'when feature flag disabled' do
before do
stub_feature_flags(group_protected_branches: false)
stub_feature_flags(allow_protected_branches_for_group: false)
end
it_behaves_like 'execute with entity'
end
end
end
# rubocop:enable Style/RedundantFetchBlock
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ProtectedBranches
class DestroyService < ProtectedBranches::BaseService
def execute(protected_branch)
raise Gitlab::Access::AccessDeniedError unless can?(current_user, :destroy_protected_branch, protected_branch)
protected_branch.destroy.tap do
refresh_cache
after_execute
end
end
end
end
ProtectedBranches::DestroyService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ProtectedBranches::DestroyService, feature_category: :compliance_management do
shared_examples 'execute with entity' do
subject(:service) { described_class.new(entity, user) }
describe '#execute' do
it 'destroys a protected branch' do
service.execute(protected_branch)
expect(protected_branch).to be_destroyed
end
it 'refreshes the cache' do
expect_next_instance_of(ProtectedBranches::CacheService) do |cache_service|
expect(cache_service).to receive(:refresh)
end
service.execute(protected_branch)
end
context 'when a policy restricts rule deletion' do
it "prevents deletion of the protected branch rule" do
disallow(:destroy_protected_branch, protected_branch)
expect do
service.execute(protected_branch)
end.to raise_error(Gitlab::Access::AccessDeniedError)
end
end
end
end
context 'with entity project' do
let_it_be_with_reload(:entity) { create(:project) }
let!(:protected_branch) { create(:protected_branch, project: entity) }
let(:user) { entity.first_owner }
it_behaves_like 'execute with entity'
end
context 'with entity group' do
let_it_be_with_reload(:entity) { create(:group) }
let_it_be_with_reload(:user) { create(:user) }
let!(:protected_branch) { create(:protected_branch, group: entity, project: nil) }
before do
allow(Ability).to receive(:allowed?).with(user, :destroy_protected_branch, protected_branch).and_return(true)
end
it_behaves_like 'execute with entity'
end
def disallow(ability, protected_branch)
allow(Ability).to receive(:allowed?).and_call_original
allow(Ability).to receive(:allowed?).with(user, ability, protected_branch).and_return(false)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ProtectedBranches
class UpdateService < ProtectedBranches::BaseService
def execute(protected_branch)
raise Gitlab::Access::AccessDeniedError unless can?(current_user, :update_protected_branch, protected_branch)
old_merge_access_levels = protected_branch.merge_access_levels.map(&:clone)
old_push_access_levels = protected_branch.push_access_levels.map(&:clone)
if protected_branch.update(params)
after_execute(protected_branch: protected_branch, old_merge_access_levels: old_merge_access_levels, old_push_access_levels: old_push_access_levels)
refresh_cache
end
protected_branch
end
end
end
ProtectedBranches::UpdateService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ProtectedBranches::UpdateService, feature_category: :compliance_management do
shared_examples 'execute with entity' do
let(:params) { { name: new_name } }
subject(:service) { described_class.new(entity, user, params) }
describe '#execute' do
let(:new_name) { 'new protected branch name' }
let(:result) { service.execute(protected_branch) }
it 'updates a protected branch' do
expect(result.reload.name).to eq(params[:name])
end
it 'refreshes the cache' do
expect_next_instance_of(ProtectedBranches::CacheService) do |cache_service|
expect(cache_service).to receive(:refresh)
end
result
end
context 'when updating name of a protected branch to one that contains HTML tags' do
let(:new_name) { 'foo<b>bar<\b>' }
let(:result) { service.execute(protected_branch) }
it 'updates a protected branch' do
expect(result.reload.name).to eq(new_name)
end
end
context 'when a policy restricts rule update' do
it "prevents update of the protected branch rule" do
disallow(:update_protected_branch, protected_branch)
expect { service.execute(protected_branch) }.to raise_error(Gitlab::Access::AccessDeniedError)
end
end
end
end
context 'with entity project' do
let_it_be_with_reload(:entity) { create(:project) }
let!(:protected_branch) { create(:protected_branch, project: entity) }
let(:user) { entity.first_owner }
it_behaves_like 'execute with entity'
end
context 'with entity group' do
let_it_be_with_reload(:entity) { create(:group) }
let_it_be_with_reload(:user) { create(:user) }
let!(:protected_branch) { create(:protected_branch, group: entity, project: nil) }
before do
allow(Ability).to receive(:allowed?).with(user, :update_protected_branch, protected_branch).and_return(true)
end
it_behaves_like 'execute with entity'
end
def disallow(ability, protected_branch)
allow(Ability).to receive(:allowed?).and_call_original
allow(Ability).to receive(:allowed?).with(user, ability, protected_branch).and_return(false)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ProtectedBranches
class CreateService < ProtectedBranches::BaseService
def execute(skip_authorization: false)
raise Gitlab::Access::AccessDeniedError unless skip_authorization || authorized?
save_protected_branch
refresh_cache
protected_branch
end
def authorized?
can?(current_user, :create_protected_branch, protected_branch)
end
private
def save_protected_branch
protected_branch.save
end
def protected_branch
@protected_branch ||= project_or_group.protected_branches.new(params)
end
end
end
ProtectedBranches::CreateService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ProtectedBranches::CreateService, feature_category: :compliance_management do
shared_examples 'execute with entity' do
let(:params) do
{
name: name,
merge_access_levels_attributes: [{ access_level: Gitlab::Access::MAINTAINER }],
push_access_levels_attributes: [{ access_level: Gitlab::Access::MAINTAINER }]
}
end
subject(:service) { described_class.new(entity, user, params) }
describe '#execute' do
let(:name) { 'master' }
let(:group_cache_service_double) { instance_double(ProtectedBranches::CacheService) }
let(:project_cache_service_double) { instance_double(ProtectedBranches::CacheService) }
it 'creates a new protected branch' do
expect { service.execute }.to change(ProtectedBranch, :count).by(1)
expect(entity.protected_branches.last.push_access_levels.map(&:access_level)).to match_array([Gitlab::Access::MAINTAINER])
expect(entity.protected_branches.last.merge_access_levels.map(&:access_level)).to match_array([Gitlab::Access::MAINTAINER])
end
it 'refreshes the cache' do
expect(ProtectedBranches::CacheService).to receive(:new).with(entity, user, params).and_return(group_cache_service_double)
expect(group_cache_service_double).to receive(:refresh)
if entity.is_a?(Group)
expect(ProtectedBranches::CacheService).to receive(:new).with(project, user, params).and_return(project_cache_service_double)
expect(project_cache_service_double).to receive(:refresh)
end
service.execute
end
context 'when protecting a branch with a name that contains HTML tags' do
let(:name) { 'foo<b>bar<\b>' }
it 'creates a new protected branch' do
expect { service.execute }.to change(ProtectedBranch, :count).by(1)
expect(entity.protected_branches.last.name).to eq(name)
end
end
context 'when a policy restricts rule creation' do
it "prevents creation of the protected branch rule" do
disallow(:create_protected_branch, an_instance_of(ProtectedBranch))
expect do
service.execute
end.to raise_error(Gitlab::Access::AccessDeniedError)
end
it 'creates a new protected branch if we skip authorization step' do
expect { service.execute(skip_authorization: true) }.to change(ProtectedBranch, :count).by(1)
end
end
end
end
context 'with entity project' do
let_it_be_with_reload(:entity) { create(:project) }
let(:user) { entity.first_owner }
it_behaves_like 'execute with entity'
end
context 'with entity group' do
let_it_be_with_reload(:project) { create(:project, :in_group) }
let_it_be_with_reload(:entity) { project.group }
let_it_be_with_reload(:user) { create(:user) }
before do
allow(Ability).to receive(:allowed?).with(user, :create_protected_branch, instance_of(ProtectedBranch)).and_return(true)
end
it_behaves_like 'execute with entity'
end
def disallow(ability, protected_branch)
allow(Ability).to receive(:allowed?).and_call_original
allow(Ability).to receive(:allowed?).with(user, ability, protected_branch).and_return(false)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ProtectedBranches
class ApiService < ProtectedBranches::BaseService
def create
::ProtectedBranches::CreateService.new(project_or_group, @current_user, protected_branch_params).execute
end
def update(protected_branch)
::ProtectedBranches::UpdateService.new(project_or_group, @current_user,
protected_branch_params(with_defaults: false)).execute(protected_branch)
end
private
def protected_branch_params(with_defaults: true)
params.slice(*attributes).merge(
{
push_access_levels_attributes: access_level_attributes(:push, with_defaults),
merge_access_levels_attributes: access_level_attributes(:merge, with_defaults)
}
)
end
def access_level_attributes(type, with_defaults)
::ProtectedRefs::AccessLevelParams.new(
type,
params,
with_defaults: with_defaults
).access_levels
end
def attributes
[:name, :allow_force_push]
end
end
end
ProtectedBranches::ApiService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ProtectedBranches::ApiService, feature_category: :compliance_management do
shared_examples 'execute with entity' do
it 'creates a protected branch with prefilled defaults' do
expect(::ProtectedBranches::CreateService).to receive(:new).with(
entity,
user,
hash_including(
push_access_levels_attributes: [{ access_level: Gitlab::Access::MAINTAINER }],
merge_access_levels_attributes: [{ access_level: Gitlab::Access::MAINTAINER }]
)
).and_call_original
expect(described_class.new(entity, user, { name: 'new name' }).create).to be_valid
end
it 'updates a protected branch without prefilled defaults' do
expect(::ProtectedBranches::UpdateService).to receive(:new).with(
entity,
user,
hash_including(
push_access_levels_attributes: [],
merge_access_levels_attributes: []
)
).and_call_original
expect do
expect(described_class.new(entity, user, { name: 'new name' }).update(protected_branch)).to be_valid
end.not_to change { protected_branch.reload.allow_force_push }
end
end
context 'with entity project' do
let_it_be_with_reload(:entity) { create(:project) }
let_it_be_with_reload(:protected_branch) { create(:protected_branch, project: entity, allow_force_push: true) }
let(:user) { entity.first_owner }
it_behaves_like 'execute with entity'
end
context 'with entity group' do
let_it_be_with_reload(:entity) { create(:group) }
let_it_be_with_reload(:user) { create(:user) }
let_it_be_with_reload(:protected_branch) do
create(:protected_branch, group: entity, project: nil, allow_force_push: true)
end
before do
allow(Ability).to receive(:allowed?).with(user, :update_protected_branch, protected_branch).and_return(true)
allow(Ability)
.to receive(:allowed?)
.with(user, :create_protected_branch, instance_of(ProtectedBranch))
.and_return(true)
end
it_behaves_like 'execute with entity'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AuditEvents
class BuildService
# Handle missing attributes
MissingAttributeError = Class.new(StandardError)
# @raise [MissingAttributeError] when required attributes are blank
#
# @return [BuildService]
def initialize(
author:, scope:, target:, message:,
created_at: DateTime.current, additional_details: {}, ip_address: nil, target_details: nil)
raise MissingAttributeError, "author" if author.blank?
raise MissingAttributeError, "scope" if scope.blank?
raise MissingAttributeError, "target" if target.blank?
raise MissingAttributeError, "message" if message.blank?
@author = build_author(author)
@scope = scope
@target = build_target(target)
@ip_address = ip_address || build_ip_address
@message = build_message(message)
@created_at = created_at
@additional_details = additional_details
@target_details = target_details
end
# Create an instance of AuditEvent
#
# @return [AuditEvent]
def execute
AuditEvent.new(payload)
end
private
def payload
base_payload.merge(details: base_details_payload)
end
def base_payload
{
author_id: @author.id,
author_name: @author.name,
entity_id: @scope.id,
entity_type: @scope.class.name,
created_at: @created_at
}
end
def base_details_payload
@additional_details.merge({
author_name: @author.name,
author_class: @author.class.name,
target_id: @target.id,
target_type: @target.type,
target_details: @target_details || @target.details,
custom_message: @message
})
end
def build_author(author)
author.id = -2 if author.instance_of? DeployToken
author.id = -3 if author.instance_of? DeployKey
author
end
def build_target(target)
return target if target.is_a? ::Gitlab::Audit::NullTarget
::Gitlab::Audit::Target.new(target)
end
def build_message(message)
message
end
def build_ip_address
Gitlab::RequestContext.instance.client_ip || @author.current_sign_in_ip
end
end
end
AuditEvents::BuildService.prepend_mod_with('AuditEvents::BuildService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AuditEvents::BuildService, feature_category: :audit_events do
let(:author) { build_stubbed(:author, current_sign_in_ip: '127.0.0.1') }
let(:deploy_token) { build_stubbed(:deploy_token, user: author) }
let(:scope) { build_stubbed(:group) }
let(:target) { build_stubbed(:project) }
let(:ip_address) { '192.168.8.8' }
let(:message) { 'Added an interesting field from project Gotham' }
let(:additional_details) { { action: :custom } }
subject(:service) do
described_class.new(
author: author,
scope: scope,
target: target,
message: message,
additional_details: additional_details,
ip_address: ip_address
)
end
describe '#execute', :request_store do
subject(:event) { service.execute }
before do
allow(Gitlab::RequestContext.instance).to receive(:client_ip).and_return(ip_address)
end
it 'sets correct attributes', :aggregate_failures do
freeze_time do
expect(event).to have_attributes(
author_id: author.id,
author_name: author.name,
entity_id: scope.id,
entity_type: scope.class.name)
expect(event.details).to eq(
author_name: author.name,
author_class: author.class.name,
target_id: target.id,
target_type: target.class.name,
target_details: target.name,
custom_message: message,
action: :custom)
expect(event.ip_address).to be_nil
expect(event.created_at).to eq(DateTime.current)
end
end
context 'when IP address is not provided' do
let(:ip_address) { nil }
it 'uses author current_sign_in_ip' do
expect(event.ip_address).to be_nil
end
end
context 'when overriding target details' do
subject(:service) do
described_class.new(
author: author,
scope: scope,
target: target,
message: message,
target_details: "This is my target details"
)
end
it 'uses correct target details' do
expect(event.target_details).to eq("This is my target details")
end
end
context 'when deploy token is passed as author' do
let(:service) do
described_class.new(
author: deploy_token,
scope: scope,
target: target,
message: message
)
end
it 'expect author to be user' do
expect(event.author_id).to eq(-2)
expect(event.author_name).to eq(deploy_token.name)
end
end
context 'when deploy key is passed as author' do
let(:deploy_key) { build_stubbed(:deploy_key, user: author) }
let(:service) do
described_class.new(
author: deploy_key,
scope: scope,
target: target,
message: message
)
end
it 'expect author to be deploy key' do
expect(event.author_id).to eq(-3)
expect(event.author_name).to eq(deploy_key.name)
end
end
context 'when author is passed as UnauthenticatedAuthor' do
let(:service) do
described_class.new(
author: ::Gitlab::Audit::UnauthenticatedAuthor.new,
scope: scope,
target: target,
message: message
)
end
it 'sets author as unauthenticated user' do
expect(event.author).to be_an_instance_of(::Gitlab::Audit::UnauthenticatedAuthor)
expect(event.author_name).to eq('An unauthenticated user')
end
end
context 'when attributes are missing' do
context 'when author is missing' do
let(:author) { nil }
it { expect { service }.to raise_error(described_class::MissingAttributeError, "author") }
end
context 'when scope is missing' do
let(:scope) { nil }
it { expect { service }.to raise_error(described_class::MissingAttributeError, "scope") }
end
context 'when target is missing' do
let(:target) { nil }
it { expect { service }.to raise_error(described_class::MissingAttributeError, "target") }
end
context 'when message is missing' do
let(:message) { nil }
it { expect { service }.to raise_error(described_class::MissingAttributeError, "message") }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Ide
class TerminalConfigService < ::Ide::BaseConfigService
private
def success(pass_back = {})
result = super(pass_back)
result[:terminal] = config.terminal_value
result
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Ide::TerminalConfigService, feature_category: :web_ide do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user) }
let(:sha) { 'sha' }
describe '#execute' do
subject { described_class.new(project, user, sha: sha).execute }
before do
project.add_developer(user)
allow(project.repository).to receive(:blob_data_at).with('sha', anything) do
config_content
end
end
context 'content is not valid' do
let(:config_content) { 'invalid content' }
it 'returns an error' do
is_expected.to include(
status: :error,
message: "Invalid configuration format")
end
end
context 'terminal not defined' do
let(:config_content) { '{}' }
it 'returns success' do
is_expected.to include(
status: :success,
terminal: nil)
end
end
context 'terminal enabled' do
let(:config_content) { 'terminal: {}' }
it 'returns success' do
is_expected.to include(
status: :success,
terminal: {
tag_list: [],
job_variables: [],
options: { script: ["sleep 60"] }
})
end
end
context 'custom terminal enabled' do
let(:config_content) { 'terminal: { before_script: [ls] }' }
it 'returns success' do
is_expected.to include(
status: :success,
terminal: {
tag_list: [],
job_variables: [],
options: { before_script: ["ls"], script: ["sleep 60"] }
})
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Ide
class SchemasConfigService < ::Ide::BaseConfigService
PREDEFINED_SCHEMAS = [{
uri: 'https://json.schemastore.org/gitlab-ci',
match: ['*.gitlab-ci.yml']
}].freeze
def execute
schema = predefined_schema_for(params[:filename]) || {}
success(schema: schema)
rescue StandardError => e
error(e.message)
end
private
def find_schema(filename, schemas)
match_flags = ::File::FNM_DOTMATCH | ::File::FNM_PATHNAME
schemas.each do |schema|
match = schema[:match].any? { |pattern| ::File.fnmatch?(pattern, filename, match_flags) }
return Gitlab::Json.parse(get_cached(schema[:uri])) if match
end
nil
end
def predefined_schema_for(filename)
find_schema(filename, predefined_schemas)
end
def predefined_schemas
PREDEFINED_SCHEMAS
end
def get_cached(url)
Rails.cache.fetch("services:ide:schema:#{url}", expires_in: 1.day) do
Gitlab::HTTP.get(url).body
end
end
end
end
Ide::SchemasConfigService.prepend_mod_with('Ide::SchemasConfigService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Ide::SchemasConfigService, feature_category: :web_ide do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user) }
let(:filename) { 'sample.yml' }
let(:schema_content) { double(body: '{"title":"Sample schema"}') }
describe '#execute' do
before do
project.add_developer(user)
allow(Gitlab::HTTP).to receive(:get).with(anything) do
schema_content
end
end
subject { described_class.new(project, user, filename: filename).execute }
context 'when no predefined schema exists for the given filename', unless: Gitlab.ee? do
it 'returns an empty object' do
is_expected.to include(
status: :success,
schema: {})
end
end
context 'when a predefined schema exists for the given filename' do
let(:filename) { '.gitlab-ci.yml' }
it 'uses predefined schema matches' do
expect(Gitlab::HTTP).to receive(:get).with('https://json.schemastore.org/gitlab-ci')
expect(subject[:schema]['title']).to eq "Sample schema"
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Ide
class BaseConfigService < ::BaseService
ValidationError = Class.new(StandardError)
WEBIDE_CONFIG_FILE = '.gitlab/.gitlab-webide.yml'
attr_reader :config, :config_content
def execute
check_access_and_load_config!
success
rescue ValidationError => e
error(e.message)
end
protected
def check_access_and_load_config!
check_access!
load_config_content!
load_config!
end
private
def check_access!
unless can?(current_user, :download_code, project)
raise ValidationError, 'Insufficient permissions to read configuration'
end
end
def load_config_content!
@config_content = webide_yaml_from_repo
unless config_content
raise ValidationError, "Failed to load Web IDE config file '#{WEBIDE_CONFIG_FILE}' for #{params[:sha]}"
end
end
def load_config!
@config = Gitlab::WebIde::Config.new(config_content)
unless @config.valid?
raise ValidationError, @config.errors.first
end
rescue Gitlab::WebIde::Config::ConfigError => e
raise ValidationError, e.message
end
def webide_yaml_from_repo
gitlab_webide_yml_for(params[:sha])
rescue GRPC::NotFound, GRPC::Internal
nil
end
def gitlab_webide_yml_for(sha)
project.repository.blob_data_at(sha, WEBIDE_CONFIG_FILE)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Ide::BaseConfigService, feature_category: :web_ide do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user) }
let(:sha) { 'sha' }
describe '#execute' do
subject { described_class.new(project, user, sha: sha).execute }
context 'when insufficient permission' do
it 'returns an error' do
is_expected.to include(
status: :error,
message: 'Insufficient permissions to read configuration')
end
end
context 'for developer' do
before do
project.add_developer(user)
end
context 'when file is missing' do
it 'returns an error' do
is_expected.to include(
status: :error,
message: "Failed to load Web IDE config file '.gitlab/.gitlab-webide.yml' for sha")
end
end
context 'when file is present' do
before do
allow(project.repository).to receive(:blob_data_at).with('sha', anything) do
config_content
end
end
context 'content is not valid' do
let(:config_content) { 'invalid content' }
it 'returns an error' do
is_expected.to include(
status: :error,
message: "Invalid configuration format")
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Commits
class CommitPatchService < CreateService
# Requires:
# - project: `Project` to be committed into
# - user: `User` that will be the committer
# - params:
# - branch_name: `String` the branch that will be committed into
# - start_branch: `String` the branch that will be started from
# - patches: `Gitlab::Git::Patches::Collection` that contains the patches
def initialize(*args)
super
@patches = Gitlab::Git::Patches::Collection.new(Array(params[:patches]))
end
private
def new_branch?
!repository.branch_exists?(@branch_name)
end
def create_commit!
if @start_branch && new_branch?
prepare_branch!
end
Gitlab::Git::Patches::CommitPatches
.new(current_user, project.repository, @branch_name, @patches)
.commit
end
def prepare_branch!
branch_result = ::Branches::CreateService.new(project, current_user)
.execute(@branch_name, @start_branch)
if branch_result[:status] != :success
raise ChangeError, branch_result[:message]
end
end
# Overridden from the Commits::CreateService, to skip some validations we
# don't need:
# - validate_on_branch!
# Not needed, the patches are applied on top of HEAD if the branch did not
# exist
# - validate_branch_existence!
# Not needed because we continue applying patches on the branch if it
# already existed, and create it if it did not exist.
def validate!
validate_patches!
validate_new_branch_name! if new_branch?
validate_permissions!
end
def validate_patches!
raise_error("Patches are too big") unless @patches.valid_size?
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Commits::CommitPatchService, feature_category: :source_code_management do
describe '#execute' do
let(:patches) do
patches_folder = Rails.root.join('spec/fixtures/patchfiles')
content_1 = File.read(File.join(patches_folder, "0001-This-does-not-apply-to-the-feature-branch.patch"))
content_2 = File.read(File.join(patches_folder, "0001-A-commit-from-a-patch.patch"))
[content_1, content_2]
end
let(:user) { project.creator }
let(:branch_name) { 'branch-with-patches' }
let(:project) { create(:project, :repository) }
let(:start_branch) { nil }
let(:params) { { branch_name: branch_name, patches: patches, start_branch: start_branch } }
subject(:service) do
described_class.new(project, user, params)
end
it 'returns a successful result' do
result = service.execute
branch = project.repository.find_branch(branch_name)
expect(result[:status]).to eq(:success)
expect(result[:result]).to eq(branch.target)
end
it 'is based off HEAD when no start ref is passed' do
service.execute
merge_base = project.repository.merge_base(project.repository.root_ref, branch_name)
expect(merge_base).to eq(project.repository.commit('HEAD').sha)
end
context 'when specifying a different start branch' do
let(:start_branch) { 'with-codeowners' }
it 'is based of the correct branch' do
service.execute
merge_base = project.repository.merge_base(start_branch, branch_name)
expect(merge_base).to eq(project.repository.commit(start_branch).sha)
end
end
shared_examples 'an error response' do |expected_message|
it 'returns the correct error' do
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:message]).to match(expected_message)
end
end
context 'when the user does not have access' do
let(:user) { create(:user) }
it_behaves_like 'an error response', 'You are not allowed to push into this branch'
end
context 'when the patches are not valid' do
let(:patches) { "a" * 2.1.megabytes }
it_behaves_like 'an error response', 'Patches are too big'
end
context 'when the new branch name is invalid' do
let(:branch_name) { 'HEAD' }
it_behaves_like 'an error response', 'Branch name is invalid'
end
context 'when the patches do not apply' do
let(:branch_name) { 'feature' }
it_behaves_like 'an error response', 'Patch failed at'
end
context 'when specifying a non existent start branch' do
let(:start_branch) { 'does-not-exist' }
it_behaves_like 'an error response', 'Failed to create branch'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Commits
class CherryPickService < ChangeService
def initialize(*args)
super
@start_project = params[:target_project] || @project
@source_project = params[:source_project] || @project
end
def create_commit!
Gitlab::Git::CrossRepo.new(@project.repository, @source_project.repository).execute(@commit.id) do
commit_change(:cherry_pick).tap do |sha|
track_mr_picking(sha)
end
end
end
private
def track_mr_picking(pick_sha)
merge_request = project.merge_requests.by_merge_commit_sha(@commit.sha).first
return unless merge_request
::SystemNotes::MergeRequestsService.new(
noteable: merge_request,
project: project,
author: current_user
).picked_into_branch(@branch_name, pick_sha)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Commits::CherryPickService, feature_category: :source_code_management do
let(:project) { create(:project, :repository) }
# * ddd0f15ae83993f5cb66a927a28673882e99100b (HEAD -> master, origin/master, origin/HEAD) Merge branch 'po-fix-test-en
# |\
# | * 2d1db523e11e777e49377cfb22d368deec3f0793 Correct test_env.rb path for adding branch
# |/
# * 1e292f8fedd741b75372e19097c76d327140c312 Merge branch 'cherry-pick-ce369011' into 'master'
let_it_be(:merge_commit_sha) { 'ddd0f15ae83993f5cb66a927a28673882e99100b' }
let_it_be(:merge_base_sha) { '1e292f8fedd741b75372e19097c76d327140c312' }
let_it_be(:branch_name) { 'stable' }
let(:repository) { project.repository }
let(:commit) { project.commit }
let(:user) { create(:user) }
before do
project.add_maintainer(user)
repository.add_branch(user, branch_name, merge_base_sha)
end
def cherry_pick(sha, branch_name, message: nil)
commit = project.commit(sha)
described_class.new(
project,
user,
commit: commit,
start_branch: branch_name,
branch_name: branch_name,
message: message
).execute
end
describe '#execute' do
shared_examples 'successful cherry-pick' do
it 'picks the commit into the branch' do
result = cherry_pick(merge_commit_sha, branch_name)
expect(result[:status]).to eq(:success), result[:message]
head = repository.find_branch(branch_name).target
expect(head).not_to eq(merge_base_sha)
end
it 'supports a custom commit message' do
result = cherry_pick(merge_commit_sha, branch_name, message: 'foo')
branch = repository.find_branch(branch_name)
expect(result[:status]).to eq(:success)
expect(branch.dereferenced_target.message).to eq('foo')
end
end
it_behaves_like 'successful cherry-pick'
context 'when picking a merge-request' do
let!(:merge_request) { create(:merge_request, :simple, :merged, author: user, source_project: project, merge_commit_sha: merge_commit_sha) }
it_behaves_like 'successful cherry-pick'
it 'adds a system note' do
result = cherry_pick(merge_commit_sha, branch_name)
mr_notes = find_cherry_pick_notes(merge_request)
expect(mr_notes.length).to eq(1)
expect(mr_notes[0].commit_id).to eq(result[:result])
end
end
def find_cherry_pick_notes(noteable)
noteable
.notes
.joins(:system_note_metadata)
.where(system_note_metadata: { action: 'cherry_pick' })
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Commits
class TagService < BaseService
def execute(commit)
unless params[:tag_name]
return error('Missing parameter tag_name')
end
tag_name = params[:tag_name]
message = params[:tag_message]
result = Tags::CreateService
.new(commit.project, current_user)
.execute(tag_name, commit.sha, message)
if result[:status] == :success
tag = result[:tag]
SystemNoteService.tag_commit(commit, commit.project, current_user, tag.name)
end
result
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Commits::TagService, feature_category: :source_code_management do
let(:project) { create(:project, :repository) }
let(:user) { create(:user) }
let(:commit) { project.commit }
before do
project.add_maintainer(user)
end
describe '#execute' do
let(:service) { described_class.new(project, user, opts) }
shared_examples 'tag failure' do
it 'returns a hash with the :error status' do
result = service.execute(commit)
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq(error_message)
end
it 'does not add a system note' do
service.execute(commit)
description_notes = find_notes('tag')
expect(description_notes).to be_empty
end
end
def find_notes(action)
commit
.notes
.joins(:system_note_metadata)
.where(system_note_metadata: { action: action })
end
context 'valid params' do
let(:opts) do
{
tag_name: 'v1.2.3',
tag_message: 'Release'
}
end
def find_notes(action)
commit
.notes
.joins(:system_note_metadata)
.where(system_note_metadata: { action: action })
end
context 'when tagging succeeds' do
it 'returns a hash with the :success status and created tag' do
result = service.execute(commit)
expect(result[:status]).to eq(:success)
tag = result[:tag]
expect(tag.name).to eq(opts[:tag_name])
expect(tag.message).to eq(opts[:tag_message])
end
it 'adds a system note' do
service.execute(commit)
description_notes = find_notes('tag')
expect(description_notes.length).to eq(1)
end
end
context 'when tagging fails' do
let(:tag_error) { 'GitLab: You are not allowed to push code to this project.' }
before do
tag_stub = instance_double(Tags::CreateService)
allow(Tags::CreateService).to receive(:new).and_return(tag_stub)
allow(tag_stub).to receive(:execute).and_return({
status: :error, message: tag_error
})
end
it_behaves_like 'tag failure' do
let(:error_message) { tag_error }
end
end
end
context 'invalid params' do
let(:opts) do
{}
end
it_behaves_like 'tag failure' do
let(:error_message) { 'Missing parameter tag_name' }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ImportCsv
class BaseService
include Gitlab::Utils::StrongMemoize
def initialize(user, project, csv_io)
@user = user
@project = project
@csv_io = csv_io
@results = { success: 0, error_lines: [], parse_error: false, preprocess_errors: {} }
end
PreprocessError = Class.new(StandardError)
def execute
process_csv
email_results_to_user
results
end
def email_results_to_user
raise NotImplementedError
end
private
attr_reader :user, :project, :csv_io, :results
def attributes_for(row)
raise NotImplementedError
end
def validate_headers_presence!(headers)
raise NotImplementedError
end
def create_object_class
raise NotImplementedError
end
def validate_structure!
header_line = csv_data.lines.first
raise CSV::MalformedCSVError.new('File is empty, no headers found', 1) if header_line.blank?
validate_headers_presence!(header_line)
detect_col_sep
end
def preprocess!
# any logic can be added in subclasses if needed
# hence just a no-op rather than NotImplementedError
end
def process_csv
validate_structure!
preprocess!
with_csv_lines.each do |row, line_no|
attributes = attributes_for(row)
if create_object(attributes)&.persisted?
results[:success] += 1
else
results[:error_lines].push(line_no)
end
end
rescue ArgumentError, CSV::MalformedCSVError => e
results[:parse_error] = true
results[:error_lines].push(e.line_number) if e.respond_to?(:line_number)
rescue PreprocessError
results[:parse_error] = false
end
def with_csv_lines
CSV.new(
csv_data,
col_sep: detect_col_sep,
headers: true,
header_converters: :symbol
).each.with_index(2)
end
def csv_data
@csv_io.open(&:read).force_encoding(Encoding::UTF_8)
end
strong_memoize_attr :csv_data
def detect_col_sep
header = csv_data.lines.first
if header.include?(",")
","
elsif header.include?(";")
";"
elsif header.include?("\t")
"\t"
else
raise CSV::MalformedCSVError.new('Invalid CSV format', 1)
end
end
strong_memoize_attr :detect_col_sep
def create_object(attributes)
# default_params can be extracted into a method if we need
# to support creation of objects that belongs to groups.
default_params = { container: project,
current_user: user,
params: attributes,
perform_spam_check: false }
create_service = create_object_class.new(**default_params.merge(extra_create_service_params))
create_service.execute_without_rate_limiting
end
# Overidden in subclasses to support specific parameters
def extra_create_service_params
{}
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ImportCsv::BaseService, feature_category: :importers do
let_it_be(:user) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:csv_io) { double }
subject { described_class.new(user, project, csv_io) }
shared_examples 'abstract method' do |method, args|
it "raises NotImplemented error when #{method} is called" do
if args
expect { subject.send(method, args) }.to raise_error(NotImplementedError)
else
expect { subject.send(method) }.to raise_error(NotImplementedError)
end
end
end
it_behaves_like 'abstract method', :email_results_to_user
it_behaves_like 'abstract method', :attributes_for, "any"
it_behaves_like 'abstract method', :validate_headers_presence!, "any"
it_behaves_like 'abstract method', :create_object_class
context 'when given a class' do
let(:importer_klass) do
Class.new(described_class) do
def attributes_for(row)
{ title: row[:title] }
end
def validate_headers_presence!(headers)
raise CSV::MalformedCSVError.new("Missing required headers", 1) unless headers.present?
end
def create_object_class
Class.new
end
def email_results_to_user
# no-op
end
end
end
let(:service) do
uploader = FileUploader.new(project)
uploader.store!(file)
importer_klass.new(user, project, uploader)
end
subject { service.execute }
it_behaves_like 'correctly handles invalid files'
describe '#detect_col_sep' do
using RSpec::Parameterized::TableSyntax
let(:file) { double }
before do
allow(service).to receive_message_chain('csv_data.lines.first').and_return(header)
end
where(:sep_character, :valid) do
'&' | false
'?' | false
';' | true
',' | true
"\t" | true
end
with_them do
let(:header) { "Name#{sep_character}email" }
it 'responds appropriately' do
if valid
expect(service.send(:detect_col_sep)).to eq sep_character
else
expect { service.send(:detect_col_sep) }.to raise_error(CSV::MalformedCSVError)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ImportCsv
class PreprocessMilestonesService < BaseService
def initialize(user, project, provided_titles)
@user = user
@project = project
@provided_titles = provided_titles
@results = { success: 0, errors: nil }
@milestone_errors = { missing: { header: {}, titles: [] } }
end
attr_reader :user, :project, :provided_titles, :results, :milestone_errors
def execute
result = find_milestones_by_titles
available_milestones = result.map(&:title).uniq.sort
return ServiceResponse.success(payload: result) if provided_titles.sort == available_milestones
milestone_errors[:missing][:header] = 'Milestone'
milestone_errors[:missing][:titles] = provided_titles.difference(available_milestones) || []
ServiceResponse.error(message: "", payload: milestone_errors)
end
def find_milestones_by_titles
# Find if these milestones exist in the project or its group and group ancestors
finder_params = {
project_ids: [project.id],
title: provided_titles
}
finder_params[:group_ids] = project.group.self_and_ancestors.select(:id) if project.group
MilestonesFinder.new(finder_params).execute
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ImportCsv::PreprocessMilestonesService, feature_category: :importers do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, group: group) }
let_it_be(:user) { create(:user) }
let_it_be(:provided_titles) { %w[15.10 10.1] }
let(:service) { described_class.new(user, project, provided_titles) }
subject { service.execute }
describe '#execute' do
let(:project_milestones) { ::MilestonesFinder.new({ project_ids: [project.id] }).execute }
shared_examples 'csv import' do |is_success:, milestone_errors:|
it 'does not create milestones' do
expect { subject }.not_to change { project_milestones.count }
end
it 'reports any missing milestones' do
result = subject
if is_success
expect(result).to be_success
else
expect(result[:status]).to eq(:error)
expect(result.payload).to match(milestone_errors)
end
end
end
context 'with csv that has missing or unavailable milestones' do
it_behaves_like 'csv import',
{ is_success: false, milestone_errors: { missing: { header: 'Milestone', titles: %w[15.10 10.1] } } }
end
context 'with csv that includes project milestones' do
let!(:project_milestone) { create(:milestone, project: project, title: '15.10') }
it_behaves_like 'csv import',
{ is_success: false, milestone_errors: { missing: { header: 'Milestone', titles: ["10.1"] } } }
end
context 'with csv that includes milestones column' do
let!(:project_milestone) { create(:milestone, project: project, title: '15.10') }
context 'when milestones exist in the importing projects group' do
let!(:group_milestone) { create(:milestone, group: group, title: '10.1') }
it_behaves_like 'csv import', { is_success: true, milestone_errors: nil }
end
context 'when milestones exist in a subgroup of the importing projects group' do
let_it_be(:subgroup) { create(:group, parent: group) }
let!(:group_milestone) { create(:milestone, group: subgroup, title: '10.1') }
it_behaves_like 'csv import',
{ is_success: false, milestone_errors: { missing: { header: 'Milestone', titles: ["10.1"] } } }
end
context 'when milestones exist in a different project from the importing project' do
let_it_be(:second_project) { create(:project, group: group) }
let!(:second_project_milestone) { create(:milestone, project: second_project, title: '10.1') }
it_behaves_like 'csv import',
{ is_success: false, milestone_errors: { missing: { header: 'Milestone', titles: ["10.1"] } } }
end
context 'when duplicate milestones exist in the projects group and parent group' do
let_it_be(:sub_group) { create(:group, parent: group) }
let_it_be(:project) { create(:project, group: sub_group) }
let!(:ancestor_group_milestone) { create(:milestone, group: group, title: '15.10') }
let!(:ancestor_group_milestone_two) { create(:milestone, group: group, title: '10.1') }
let!(:group_milestone) { create(:milestone, group: sub_group, title: '10.1') }
it_behaves_like 'csv import', { is_success: true, milestone_errors: nil }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AutoMerge
class MergeWhenPipelineSucceedsService < AutoMerge::BaseService
def execute(merge_request)
super do
add_system_note(merge_request)
end
end
def process(merge_request)
logger.info("Processing Automerge")
return unless merge_request.actual_head_pipeline_success?
logger.info("Pipeline Success")
return unless merge_request.mergeable?
logger.info("Merge request mergeable")
merge_request.merge_async(merge_request.merge_user_id, merge_request.merge_params)
end
def cancel(merge_request)
super do
SystemNoteService.cancel_merge_when_pipeline_succeeds(merge_request, project, current_user)
end
end
def abort(merge_request, reason)
super do
SystemNoteService.abort_merge_when_pipeline_succeeds(merge_request, project, current_user, reason)
end
end
def available_for?(merge_request)
super do
check_availability(merge_request)
end
end
private
def add_system_note(merge_request)
SystemNoteService.merge_when_pipeline_succeeds(merge_request, project, current_user, merge_request.actual_head_pipeline.sha) if merge_request.saved_change_to_auto_merge_enabled?
end
def check_availability(merge_request)
merge_request.actual_head_pipeline&.active?
end
def notify(merge_request)
notification_service.async.merge_when_pipeline_succeeds(merge_request, current_user) if merge_request.saved_change_to_auto_merge_enabled?
end
def logger
@logger ||= Gitlab::AppLogger
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AutoMerge::MergeWhenPipelineSucceedsService, feature_category: :code_review_workflow do
include_context 'for auto_merge strategy context'
describe "#available_for?" do
subject { service.available_for?(mr_merge_if_green_enabled) }
let(:pipeline_status) { :running }
before do
create(
:ci_pipeline,
pipeline_status,
ref: mr_merge_if_green_enabled.source_branch,
sha: mr_merge_if_green_enabled.diff_head_sha,
project: mr_merge_if_green_enabled.source_project
)
mr_merge_if_green_enabled.update_head_pipeline
end
it { is_expected.to be_truthy }
it 'memoizes the result' do
expect(mr_merge_if_green_enabled).to receive(:can_be_merged_by?).once.and_call_original
2.times { is_expected.to be_truthy }
end
context 'when the head pipeline succeeded' do
let(:pipeline_status) { :success }
it { is_expected.to be_falsy }
end
context 'when the user does not have permission to merge' do
before do
allow(mr_merge_if_green_enabled).to receive(:can_be_merged_by?) { false }
end
it { is_expected.to be_falsy }
end
end
describe "#execute" do
it_behaves_like 'auto_merge service #execute', 'merge_when_pipeline_succeeds' do
let(:auto_merge_strategy) { AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS }
let(:expected_note) do
"enabled an automatic merge when the pipeline for #{pipeline.sha}"
end
end
end
describe "#process" do
it_behaves_like 'auto_merge service #process'
end
describe '#cancel' do
it_behaves_like 'auto_merge service #cancel'
end
describe '#abort' do
it_behaves_like 'auto_merge service #abort'
end
describe 'pipeline integration' do
context 'when there are multiple stages in the pipeline' do
let(:ref) { mr_merge_if_green_enabled.source_branch }
let(:sha) { project.commit(ref).id }
let(:build_stage) { create(:ci_stage, name: 'build', pipeline: pipeline) }
let(:pipeline) do
create(:ci_empty_pipeline, ref: ref, sha: sha, project: project)
end
let!(:build) do
create(
:ci_build,
:created,
pipeline: pipeline,
ref: ref,
name: 'build',
ci_stage: build_stage
)
end
let!(:test) do
create(:ci_build, :created, pipeline: pipeline, ref: ref, name: 'test')
end
before do
# This behavior of MergeRequest: we instantiate a new object
#
allow_any_instance_of(MergeRequest)
.to receive(:head_pipeline)
.and_wrap_original do
Ci::Pipeline.find(pipeline.id)
end
end
it "doesn't merge if any of stages failed" do
expect(MergeWorker).not_to receive(:perform_async)
build.success
test.reload
test.drop
end
it 'merges when all stages succeeded', :sidekiq_might_not_need_inline do
expect(MergeWorker).to receive(:perform_async)
build.success
test.reload
test.success
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AutoMerge
class BaseService < ::BaseService
include Gitlab::Utils::StrongMemoize
include MergeRequests::AssignsMergeParams
def execute(merge_request)
ApplicationRecord.transaction do
register_auto_merge_parameters!(merge_request)
yield if block_given?
end
notify(merge_request)
AutoMergeProcessWorker.perform_async(merge_request.id)
strategy.to_sym
rescue StandardError => e
track_exception(e, merge_request)
:failed
end
def process(_)
raise NotImplementedError
end
def update(merge_request)
assign_allowed_merge_params(merge_request, params.merge(auto_merge_strategy: strategy))
return :failed unless merge_request.save
strategy.to_sym
end
def cancel(merge_request)
ApplicationRecord.transaction do
clear_auto_merge_parameters!(merge_request)
yield if block_given?
end
success
rescue StandardError => e
track_exception(e, merge_request)
error("Can't cancel the automatic merge", 406)
end
def abort(merge_request, reason)
ApplicationRecord.transaction do
clear_auto_merge_parameters!(merge_request)
yield if block_given?
end
success
rescue StandardError => e
track_exception(e, merge_request)
error("Can't abort the automatic merge", 406)
end
def available_for?(merge_request)
strong_memoize("available_for_#{merge_request.id}") do
merge_request.can_be_merged_by?(current_user) &&
merge_request.open? &&
!merge_request.broken? &&
overrideable_available_for_checks(merge_request) &&
yield
end
end
private
def overrideable_available_for_checks(merge_request)
!merge_request.draft? &&
merge_request.mergeable_discussions_state? &&
!merge_request.merge_blocked_by_other_mrs?
end
# Overridden in child classes
def notify(merge_request)
end
def strategy
strong_memoize(:strategy) do
self.class.name.demodulize.remove('Service').underscore
end
end
def register_auto_merge_parameters!(merge_request)
assign_allowed_merge_params(merge_request, params.merge(auto_merge_strategy: strategy))
merge_request.auto_merge_enabled = true
merge_request.merge_user = current_user
merge_request.save!
end
def clear_auto_merge_parameters!(merge_request)
merge_request.auto_merge_enabled = false
merge_request.merge_user = nil
merge_request.merge_params&.except!(*clearable_auto_merge_parameters)
merge_request.save!
end
# Overridden in EE child classes
def clearable_auto_merge_parameters
%w[
should_remove_source_branch
commit_message
squash_commit_message
auto_merge_strategy
]
end
def track_exception(error, merge_request)
Gitlab::ErrorTracking.track_exception(error, merge_request_id: merge_request&.id)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AutoMerge::BaseService, feature_category: :code_review_workflow do
let(:project) { create(:project) }
let(:user) { create(:user) }
let(:service) { described_class.new(project, user, params) }
let(:merge_request) { create(:merge_request) }
let(:params) { {} }
describe '#execute' do
subject { service.execute(merge_request) }
before do
allow(AutoMergeProcessWorker).to receive(:perform_async) {}
end
it 'sets properies to the merge request' do
subject
merge_request.reload
expect(merge_request).to be_auto_merge_enabled
expect(merge_request.merge_user).to eq(user)
expect(merge_request.auto_merge_strategy).to eq('base')
end
it 'yields block' do
expect { |b| service.execute(merge_request, &b) }.to yield_control.once
end
it 'returns activated strategy name' do
is_expected.to eq(:base)
end
context 'when merge parameters are given' do
let(:params) do
{
'commit_message' => "Merge branch 'patch-12' into 'master'",
'sha' => "200fcc9c260f7219eaf0daba87d818f0922c5b18",
'should_remove_source_branch' => false,
'squash' => false,
'squash_commit_message' => "Update README.md"
}
end
it 'sets merge parameters' do
subject
merge_request.reload
expect(merge_request.merge_params['commit_message']).to eq("Merge branch 'patch-12' into 'master'")
expect(merge_request.merge_params['sha']).to eq('200fcc9c260f7219eaf0daba87d818f0922c5b18')
expect(merge_request.merge_params['should_remove_source_branch']).to eq(false)
expect(merge_request.squash_on_merge?).to eq(false)
expect(merge_request.merge_params['squash_commit_message']).to eq('Update README.md')
end
end
context 'when strategy is merge when pipeline succeeds' do
let(:service) { AutoMerge::MergeWhenPipelineSucceedsService.new(project, user) }
before do
pipeline = build(:ci_pipeline)
allow(merge_request).to receive(:actual_head_pipeline) { pipeline }
end
it 'sets the auto merge strategy' do
subject
merge_request.reload
expect(merge_request.auto_merge_strategy).to eq(AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS)
end
it 'returns activated strategy name' do
is_expected.to eq(AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS.to_sym)
end
it 'calls AutoMergeProcessWorker' do
expect(AutoMergeProcessWorker).to receive(:perform_async).with(merge_request.id).once
subject
end
end
context 'when failed to save merge request' do
before do
allow(merge_request).to receive(:save!) { raise ActiveRecord::RecordInvalid }
end
it 'does not yield block' do
expect { |b| service.execute(merge_request, &b) }.not_to yield_control
end
it 'returns failed' do
is_expected.to eq(:failed)
end
it 'tracks the exception' do
expect(Gitlab::ErrorTracking)
.to receive(:track_exception)
.with(kind_of(ActiveRecord::RecordInvalid), merge_request_id: merge_request.id)
subject
end
end
context 'when exception happens in yield block' do
def execute_with_error_in_yield
service.execute(merge_request) { raise 'Something went wrong' }
end
it 'returns failed status' do
expect(execute_with_error_in_yield).to eq(:failed)
end
it 'rollback the transaction' do
execute_with_error_in_yield
merge_request.reload
expect(merge_request).not_to be_auto_merge_enabled
end
it 'tracks the exception' do
expect(Gitlab::ErrorTracking)
.to receive(:track_exception)
.with(kind_of(RuntimeError), merge_request_id: merge_request.id)
execute_with_error_in_yield
end
end
end
describe '#update' do
subject { service.update(merge_request) } # rubocop:disable Rails/SaveBang
let(:merge_request) { create(:merge_request, :merge_when_pipeline_succeeds) }
context 'when merge params are specified' do
let(:params) do
{
'commit_message' => "Merge branch 'patch-12' into 'master'",
'sha' => "200fcc9c260f7219eaf0daba87d818f0922c5b18",
'should_remove_source_branch' => false,
'squash_commit_message' => "Update README.md"
}
end
it 'updates merge params' do
expect { subject }.to change {
merge_request.reload.merge_params.slice(*params.keys)
}.from({}).to(params)
end
end
end
shared_examples_for 'Canceled or Dropped' do
it 'removes properies from the merge request' do
subject
merge_request.reload
expect(merge_request).not_to be_auto_merge_enabled
expect(merge_request.merge_user).to be_nil
expect(merge_request.auto_merge_strategy).to be_nil
end
it 'yields block' do
expect { |b| service.cancel(merge_request, &b) }.to yield_control.once
end
it 'returns success status' do
expect(subject[:status]).to eq(:success)
end
context 'when merge params are set' do
before do
merge_request.update!(merge_params:
{
'should_remove_source_branch' => false,
'commit_message' => "Merge branch 'patch-12' into 'master'",
'squash_commit_message' => "Update README.md",
'auto_merge_strategy' => 'merge_when_pipeline_succeeds'
})
end
it 'removes merge parameters' do
subject
merge_request.reload
expect(merge_request.merge_params['should_remove_source_branch']).to be_nil
expect(merge_request.merge_params['commit_message']).to be_nil
expect(merge_request.merge_params['squash_commit_message']).to be_nil
expect(merge_request.merge_params['auto_merge_strategy']).to be_nil
end
end
context 'when failed to save' do
before do
allow(merge_request).to receive(:save!) { raise ActiveRecord::RecordInvalid }
end
it 'does not yield block' do
expect { |b| service.execute(merge_request, &b) }.not_to yield_control
end
end
end
describe '#cancel' do
subject { service.cancel(merge_request) }
let(:merge_request) { create(:merge_request, :merge_when_pipeline_succeeds) }
it_behaves_like 'Canceled or Dropped'
context 'when failed to save merge request' do
before do
allow(merge_request).to receive(:save!) { raise ActiveRecord::RecordInvalid }
end
it 'returns error status' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to eq("Can't cancel the automatic merge")
end
end
context 'when exception happens in yield block' do
def cancel_with_error_in_yield
service.cancel(merge_request) { raise 'Something went wrong' }
end
it 'returns error' do
result = cancel_with_error_in_yield
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq("Can't cancel the automatic merge")
end
it 'rollback the transaction' do
cancel_with_error_in_yield
merge_request.reload
expect(merge_request).to be_auto_merge_enabled
end
it 'tracks the exception' do
expect(Gitlab::ErrorTracking)
.to receive(:track_exception)
.with(kind_of(RuntimeError), merge_request_id: merge_request.id)
cancel_with_error_in_yield
end
end
end
describe '#abort' do
subject { service.abort(merge_request, reason) }
let(:merge_request) { create(:merge_request, :merge_when_pipeline_succeeds) }
let(:reason) { 'an error' }
it_behaves_like 'Canceled or Dropped'
context 'when failed to save' do
before do
allow(merge_request).to receive(:save!) { raise ActiveRecord::RecordInvalid }
end
it 'returns error status' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to eq("Can't abort the automatic merge")
end
end
context 'when exception happens in yield block' do
def abort_with_error_in_yield
service.abort(merge_request, reason) { raise 'Something went wrong' }
end
it 'returns error' do
result = abort_with_error_in_yield
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq("Can't abort the automatic merge")
end
it 'rollback the transaction' do
abort_with_error_in_yield
merge_request.reload
expect(merge_request).to be_auto_merge_enabled
end
it 'tracks the exception' do
expect(Gitlab::ErrorTracking)
.to receive(:track_exception)
.with(kind_of(RuntimeError), merge_request_id: merge_request.id)
abort_with_error_in_yield
end
end
end
describe '#process' do
specify { expect(service).to respond_to :process }
specify { expect { service.process(nil) }.to raise_error NotImplementedError }
end
describe '#available_for?' do
using RSpec::Parameterized::TableSyntax
subject(:available_for) { service.available_for?(merge_request) { true } }
let(:merge_request) { create(:merge_request) }
where(:can_be_merged, :open, :broken, :discussions, :blocked, :draft, :result) do
true | true | false | true | false | false | true
false | true | false | true | false | false | false
true | false | false | true | false | false | false
true | true | true | true | false | false | false
true | true | false | false | false | false | false
true | true | false | true | true | false | false
true | true | false | true | false | true | false
end
with_them do
before do
allow(merge_request).to receive(:can_be_merged_by?).and_return(can_be_merged)
allow(merge_request).to receive(:open?).and_return(open)
allow(merge_request).to receive(:broken?).and_return(broken)
allow(merge_request).to receive(:draft?).and_return(draft)
allow(merge_request).to receive(:mergeable_discussions_state?).and_return(discussions)
allow(merge_request).to receive(:merge_blocked_by_other_mrs?).and_return(blocked)
end
it 'returns the expected results' do
expect(available_for).to eq(result)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AuthorizedProjectUpdate
class ProjectAccessChangedService
def initialize(project_ids)
@project_ids = Array.wrap(project_ids)
end
def execute
return if @project_ids.empty?
bulk_args = @project_ids.map { |id| [id] }
AuthorizedProjectUpdate::ProjectRecalculateWorker.bulk_perform_async(bulk_args) # rubocop:disable Scalability/BulkPerformWithContext
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AuthorizedProjectUpdate::ProjectAccessChangedService, feature_category: :groups_and_projects do
describe '#execute' do
it 'executes projects_authorizations refresh' do
expect(AuthorizedProjectUpdate::ProjectRecalculateWorker).to receive(:bulk_perform_async)
.with([[1], [2]])
described_class.new([1, 2]).execute
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AuthorizedProjectUpdate
class ProjectRecalculatePerUserService < ProjectRecalculateService
def initialize(project, user)
@project = project
@user = user
end
private
attr_reader :user
def apply_scopes(project_authorizations)
super.where(user_id: user.id) # rubocop: disable CodeReuse/ActiveRecord
end
def effective_access_levels
Projects::Members::EffectiveAccessLevelPerUserFinder.new(project, user).execute
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AuthorizedProjectUpdate::ProjectRecalculatePerUserService, '#execute', feature_category: :groups_and_projects do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let_it_be(:another_user) { create(:user) }
subject(:execute) { described_class.new(project, user).execute }
it 'returns success' do
expect(execute.success?).to eq(true)
end
context 'when there are no changes to be made' do
it 'does not change authorizations' do
expect { execute }.not_to(change { ProjectAuthorization.count })
end
end
context 'when there are changes to be made' do
context 'when addition is required' do
before do
project.add_developer(user)
project.add_developer(another_user)
project.project_authorizations.where(user: [user, another_user]).delete_all
end
it 'adds a new authorization record for the specific user' do
expect { execute }.to(
change { project.project_authorizations.where(user: user).count }
.from(0).to(1)
)
end
it 'does not add a new authorization record for the other user' do
expect { execute }.not_to(
change { project.project_authorizations.where(user: another_user).count }
)
end
it 'adds a new authorization record with the correct access level for the specific user' do
execute
project_authorization = project.project_authorizations.where(
user: user,
access_level: Gitlab::Access::DEVELOPER
)
expect(project_authorization).to exist
end
end
context 'when removal is required' do
before do
create(:project_authorization, user: user, project: project)
create(:project_authorization, user: another_user, project: project)
end
it 'removes the authorization record for the specific user' do
expect { execute }.to(
change { project.project_authorizations.where(user: user).count }
.from(1).to(0)
)
end
it 'does not remove the authorization record for the other user' do
expect { execute }.not_to(
change { project.project_authorizations.where(user: another_user).count }
)
end
end
context 'when an update in access level is required' do
before do
project.add_developer(user)
project.add_developer(another_user)
project.project_authorizations.where(user: [user, another_user]).delete_all
create(:project_authorization, project: project, user: user, access_level: Gitlab::Access::GUEST)
create(:project_authorization, project: project, user: another_user, access_level: Gitlab::Access::GUEST)
end
it 'updates the authorization of the specific user to the correct access level' do
expect { execute }.to(
change { project.project_authorizations.find_by(user: user).access_level }
.from(Gitlab::Access::GUEST).to(Gitlab::Access::DEVELOPER)
)
end
it 'does not update the authorization of the other user to the correct access level' do
expect { execute }.not_to(
change { project.project_authorizations.find_by(user: another_user).access_level }
.from(Gitlab::Access::GUEST)
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AuthorizedProjectUpdate
class PeriodicRecalculateService
BATCH_SIZE = 450
DELAY_INTERVAL = 50.seconds.to_i
def execute
# Using this approach (instead of eg. User.each_batch) keeps the arguments
# the same for AuthorizedProjectUpdate::UserRefreshOverUserRangeWorker
# even if the user list changes, so we can deduplicate these jobs.
# Since UserRefreshOverUserRangeWorker has set data_consistency to delayed,
# a job enqueued without a delay could fail because the replica could not catch up with the primary.
# To prevent this, we start the index from `1` instead of `0` so as to ensure that
# no UserRefreshOverUserRangeWorker job is enqueued without a delay.
(1..User.maximum(:id)).each_slice(BATCH_SIZE).with_index(1) do |batch, index|
delay = DELAY_INTERVAL * index
AuthorizedProjectUpdate::UserRefreshOverUserRangeWorker.perform_in(delay, *batch.minmax)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AuthorizedProjectUpdate::PeriodicRecalculateService, feature_category: :groups_and_projects do
subject(:service) { described_class.new }
describe '#execute' do
let(:batch_size) { 2 }
let_it_be(:users) { create_list(:user, 4) }
before do
stub_const('AuthorizedProjectUpdate::PeriodicRecalculateService::BATCH_SIZE', batch_size)
User.delete([users[1], users[2]])
end
it 'calls AuthorizedProjectUpdate::UserRefreshOverUserRangeWorker' do
(1..User.maximum(:id)).each_slice(batch_size).with_index(1) do |batch, index|
delay = AuthorizedProjectUpdate::PeriodicRecalculateService::DELAY_INTERVAL * index
expect(AuthorizedProjectUpdate::UserRefreshOverUserRangeWorker).to(
receive(:perform_in).with(delay, *batch.minmax))
end
service.execute
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AuthorizedProjectUpdate
# Service for finding the authorized_projects records of a user that needs addition or removal.
#
# Usage:
#
# user = User.find_by(username: 'alice')
# service = AuthorizedProjectUpdate::FindRecordsDueForRefreshService.new(some_user)
# service.execute
class FindRecordsDueForRefreshService
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
current = current_authorizations_per_project
fresh = fresh_access_levels_per_project
# Projects that have more than one authorizations associated with
# the user needs to be deleted.
# The correct authorization is added to the ``add`` array in the
# next stage.
remove = projects_with_duplicates
current.except!(*projects_with_duplicates)
remove |= current.each_with_object([]) do |(project_id, row), array|
next if fresh[project_id] && fresh[project_id] == row.access_level
# rows not in the new list or with a different access level should be
# removed.
if incorrect_auth_found_callback
incorrect_auth_found_callback.call(project_id, row.access_level)
end
array << row.project_id
end
add = fresh.each_with_object([]) do |(project_id, level), array|
next if current[project_id] && current[project_id].access_level == level
# rows not in the old list or with a different access level should be
# added.
if missing_auth_found_callback
missing_auth_found_callback.call(project_id, level)
end
array << {
user_id: user.id,
project_id: project_id,
access_level: level
}
end
[remove, add]
end
def needs_refresh?
remove, add = execute
remove.present? || add.present?
end
def fresh_access_levels_per_project
fresh_authorizations.each_with_object({}) do |row, hash|
hash[row.project_id] = row.access_level
end
end
def current_authorizations_per_project
current_authorizations.index_by(&:project_id)
end
def current_authorizations
@current_authorizations ||= user.project_authorizations.select(:project_id, :access_level)
end
def fresh_authorizations
Gitlab::ProjectAuthorizations.new(user).calculate
end
private
attr_reader :user, :source, :incorrect_auth_found_callback, :missing_auth_found_callback
def projects_with_duplicates
@projects_with_duplicates ||= current_authorizations
.group_by(&:project_id)
.select { |project_id, authorizations| authorizations.count > 1 }
.keys
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AuthorizedProjectUpdate::FindRecordsDueForRefreshService, feature_category: :groups_and_projects do
# 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.owner }
let(:service) { described_class.new(user) }
describe '#execute' do
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
context 'finding project authorizations due for refresh' do
context 'when there are changes to be made' do
before do
user.project_authorizations.delete_all
end
it 'finds projects authorizations that needs to be refreshed' do
project2 = create(:project)
user.project_authorizations
.create!(project: project2, access_level: Gitlab::Access::MAINTAINER)
to_be_removed = [project2.id]
to_be_added = [
{ user_id: user.id, project_id: project.id, access_level: Gitlab::Access::OWNER }
]
expect(service.execute).to eq([to_be_removed, to_be_added])
end
it 'finds entries with wrong access levels' do
user.project_authorizations
.create!(project: project, access_level: Gitlab::Access::DEVELOPER)
to_be_removed = [project.id]
to_be_added = [
{ user_id: user.id, project_id: project.id, access_level: Gitlab::Access::OWNER }
]
expect(service.execute).to eq([to_be_removed, to_be_added])
end
end
context 'when there are no changes to be made' do
it 'returns empty arrays' do
expect(service.execute).to eq([[], []])
end
end
end
end
describe '#needs_refresh?' do
subject { service.needs_refresh? }
context 'when there are records due for either removal or addition' do
context 'when there are both removals and additions to be made' do
before do
user.project_authorizations.delete_all
create(:project_authorization, user: user)
end
it { is_expected.to eq(true) }
end
context 'when there are no removals, but there are additions to be made' do
before do
user.project_authorizations.delete_all
end
it { is_expected.to eq(true) }
end
context 'when there are no additions, but there are removals to be made' do
before do
create(:project_authorization, user: user)
end
it { is_expected.to eq(true) }
end
end
context 'when there are no additions or removals to be made' do
it { is_expected.to eq(false) }
end
end
describe '#fresh_access_levels_per_project' do
let(:hash) { service.fresh_access_levels_per_project }
it 'returns a Hash' do
expect(hash).to be_an_instance_of(Hash)
end
it 'sets the keys to the project IDs' do
expect(hash.keys).to match_array([project.id])
end
it 'sets the values to the access levels' do
expect(hash.values).to match_array([Gitlab::Access::OWNER])
end
context 'personal projects' do
it 'includes the project with the right access level' do
expect(hash[project.id]).to eq(Gitlab::Access::OWNER)
end
end
context 'projects the user is a member of' do
let!(:other_project) { create(:project) }
before do
other_project.team.add_reporter(user)
end
it 'includes the project with the right access level' do
expect(hash[other_project.id]).to eq(Gitlab::Access::REPORTER)
end
end
context 'projects of groups the user is a member of' do
let(:group) { create(:group) }
let!(:other_project) { create(:project, group: group) }
before do
group.add_owner(user)
end
it 'includes the project with the right access level' do
expect(hash[other_project.id]).to eq(Gitlab::Access::OWNER)
end
end
context 'projects of subgroups of groups the user is a member of' do
let(:group) { create(:group) }
let(:nested_group) { create(:group, parent: group) }
let!(:other_project) { create(:project, group: nested_group) }
before do
group.add_maintainer(user)
end
it 'includes the project with the right access level' do
expect(hash[other_project.id]).to eq(Gitlab::Access::MAINTAINER)
end
end
context 'projects shared with groups the user is a member of' do
let(:group) { create(:group) }
let(:other_project) { create(:project) }
let!(:project_group_link) { create(:project_group_link, project: other_project, group: group, group_access: Gitlab::Access::GUEST) }
before do
group.add_maintainer(user)
end
it 'includes the project with the right access level' do
expect(hash[other_project.id]).to eq(Gitlab::Access::GUEST)
end
end
context 'projects shared with subgroups of groups the user is a member of' do
let(:group) { create(:group) }
let(:nested_group) { create(:group, parent: group) }
let(:other_project) { create(:project) }
let!(:project_group_link) { create(:project_group_link, project: other_project, group: nested_group, group_access: Gitlab::Access::DEVELOPER) }
before do
group.add_maintainer(user)
end
it 'includes the project with the right access level' do
expect(hash[other_project.id]).to eq(Gitlab::Access::DEVELOPER)
end
end
end
describe '#current_authorizations_per_project' do
let(:hash) { service.current_authorizations_per_project }
it 'returns a Hash' do
expect(hash).to be_an_instance_of(Hash)
end
it 'sets the keys to the project IDs' do
expect(hash.keys).to eq([project.id])
end
it 'sets the values to the project authorization rows' do
expect(hash.values.length).to eq(1)
value = hash.values[0]
expect(value.project_id).to eq(project.id)
expect(value.access_level).to eq(Gitlab::Access::OWNER)
end
end
describe '#current_authorizations' do
context 'without authorizations' do
it 'returns an empty list' do
user.project_authorizations.delete_all
expect(service.current_authorizations.empty?).to eq(true)
end
end
context 'with an authorization' do
let(:row) { service.current_authorizations.take }
it 'returns the currently authorized projects' do
expect(service.current_authorizations.length).to eq(1)
end
it 'includes the project ID for every row' do
expect(row.project_id).to eq(project.id)
end
it 'includes the access level for every row' do
expect(row.access_level).to eq(Gitlab::Access::OWNER)
end
end
end
describe '#fresh_authorizations' do
it 'returns the new authorized projects' do
expect(service.fresh_authorizations.length).to eq(1)
end
it 'returns the highest access level' do
project.team.add_guest(user)
rows = service.fresh_authorizations.to_a
expect(rows.length).to eq(1)
expect(rows.first.access_level).to eq(Gitlab::Access::OWNER)
end
context 'every returned row' do
let(:row) { service.fresh_authorizations.take }
it 'includes the project ID' do
expect(row.project_id).to eq(project.id)
end
it 'includes the access level' do
expect(row.access_level).to eq(Gitlab::Access::OWNER)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module AuthorizedProjectUpdate
class ProjectRecalculateService
# Service for refreshing all the authorizations to a particular project.
include Gitlab::Utils::StrongMemoize
BATCH_SIZE = 1000
def initialize(project)
@project = project
end
def execute
refresh_authorizations if needs_refresh?
ServiceResponse.success
end
private
attr_reader :project
def needs_refresh?
user_ids_to_remove.any? ||
authorizations_to_create.any?
end
def current_authorizations
strong_memoize(:current_authorizations) do
apply_scopes(project.project_authorizations)
.pluck(:user_id, :access_level) # rubocop: disable CodeReuse/ActiveRecord
end
end
def fresh_authorizations
strong_memoize(:fresh_authorizations) do
result = []
effective_access_levels
.each_batch(of: BATCH_SIZE, column: :user_id) do |member_batch|
result += member_batch.pluck(:user_id, 'MAX(access_level)') # rubocop: disable CodeReuse/ActiveRecord
end
result
end
end
def user_ids_to_remove
strong_memoize(:user_ids_to_remove) do
(current_authorizations - fresh_authorizations)
.map { |user_id, _| user_id }
end
end
def authorizations_to_create
strong_memoize(:authorizations_to_create) do
(fresh_authorizations - current_authorizations).map do |user_id, access_level|
{
user_id: user_id,
access_level: access_level,
project_id: project.id
}
end
end
end
def refresh_authorizations
ProjectAuthorizations::Changes.new do |changes|
changes.add(authorizations_to_create)
changes.remove_users_in_project(project, user_ids_to_remove)
end.apply!
end
def apply_scopes(project_authorizations)
project_authorizations
end
def effective_access_levels
Projects::Members::EffectiveAccessLevelFinder.new(project).execute
end
end
end
AuthorizedProjectUpdate::ProjectRecalculateService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe AuthorizedProjectUpdate::ProjectRecalculateService, '#execute', feature_category: :groups_and_projects do
let_it_be(:project) { create(:project) }
subject(:execute) { described_class.new(project).execute }
it 'returns success' do
expect(execute.success?).to eq(true)
end
context 'when there are no changes to be made' do
it 'does not change authorizations' do
expect { execute }.not_to(change { ProjectAuthorization.count })
end
end
context 'when there are changes to be made' do
let(:user) { create(:user) }
context 'when addition is required' do
before do
project.add_developer(user)
project.project_authorizations.where(user: user).delete_all
end
it 'adds a new authorization record' do
expect { execute }.to(
change { project.project_authorizations.where(user: user).count }
.from(0).to(1)
)
end
it 'adds a new authorization record with the correct access level' do
execute
project_authorization = project.project_authorizations.where(
user: user,
access_level: Gitlab::Access::DEVELOPER
)
expect(project_authorization).to exist
end
end
context 'when removal is required' do
before do
create(:project_authorization, user: user, project: project)
end
it 'removes the authorization record' do
expect { execute }.to(
change { project.project_authorizations.where(user: user).count }
.from(1).to(0)
)
end
end
context 'when an update in access level is required' do
before do
project.add_developer(user)
project.project_authorizations.where(user: user).delete_all
create(:project_authorization, project: project, user: user, access_level: Gitlab::Access::GUEST)
end
it 'updates the authorization of the user to the correct access level' do
expect { execute }.to(
change { project.project_authorizations.find_by(user: user).access_level }
.from(Gitlab::Access::GUEST).to(Gitlab::Access::DEVELOPER)
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class IssuablesService < ::SystemNotes::BaseService
# We create cross-referenced system notes when a commit relates to an issue.
# There are two options what time to use for the system note:
# 1. The push date (default)
# 2. The commit date
#
# The commit date is useful when an existing Git repository is imported to GitLab.
# It helps to preserve an original order of all notes (comments, commits, status changes, e.t.c)
# in the imported issues. Otherwise, all commits will be linked before or after all other imported notes.
#
# See also the discussion in https://gitlab.com/gitlab-org/gitlab/-/merge_requests/60700#note_612724683
USE_COMMIT_DATE_FOR_CROSS_REFERENCE_NOTE = false
def self.issuable_events
{
assigned: s_('IssuableEvents|assigned to'),
unassigned: s_('IssuableEvents|unassigned'),
review_requested: s_('IssuableEvents|requested review from'),
review_request_removed: s_('IssuableEvents|removed review request for')
}.freeze
end
#
# noteable_ref - Referenced noteable object, or array of objects
#
# Example Note text:
#
# "marked this issue as related to gitlab-foss#9001"
# "marked this issue as related to gitlab-foss#9001, gitlab-foss#9002, and gitlab-foss#9003"
#
# Returns the created Note object
def relate_issuable(noteable_ref)
body = "marked this #{noteable_name} as related to #{extract_issuable_reference(noteable_ref)}"
track_issue_event(:track_issue_related_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'relate'))
end
#
# noteable_ref - Referenced noteable object
#
# Example Note text:
#
# "removed the relation with gitlab-foss#9001"
#
# Returns the created Note object
def unrelate_issuable(noteable_ref)
body = "removed the relation with #{noteable_ref.to_reference(noteable.resource_parent)}"
track_issue_event(:track_issue_unrelated_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'unrelate'))
end
# Called when the assignee of a Noteable is changed or removed
#
# assignee - User being assigned, or nil
#
# Example Note text:
#
# "removed assignee"
#
# "assigned to @rspeicher"
#
# Returns the created Note object
def change_assignee(assignee)
body = assignee.nil? ? 'removed assignee' : "assigned to #{assignee.to_reference}"
track_issue_event(:track_issue_assignee_changed_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'assignee'))
end
# Called when the assignees of an issuable is changed or removed
#
# assignees - Users being assigned, or nil
#
# Example Note text:
#
# "removed all assignees"
#
# "assigned to @user1 additionally to @user2"
#
# "assigned to @user1, @user2 and @user3 and unassigned @user4 and @user5"
#
# "assigned to @user1 and @user2"
#
# Returns the created Note object
def change_issuable_assignees(old_assignees)
unassigned_users = old_assignees - noteable.assignees
added_users = noteable.assignees.to_a - old_assignees
text_parts = []
Gitlab::I18n.with_default_locale do
text_parts << "#{self.class.issuable_events[:assigned]} #{added_users.map(&:to_reference).to_sentence}" if added_users.any?
text_parts << "#{self.class.issuable_events[:unassigned]} #{unassigned_users.map(&:to_reference).to_sentence}" if unassigned_users.any?
end
body = text_parts.join(' and ')
track_issue_event(:track_issue_assignee_changed_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'assignee'))
end
# Called when the reviewers of an issuable is changed or removed
#
# reviewers - Users being requested to review, or nil
#
# Example Note text:
#
# "requested review from @user1 and @user2"
#
# "requested review from @user1, @user2 and @user3 and removed review request for @user4 and @user5"
#
# Returns the created Note object
def change_issuable_reviewers(old_reviewers)
unassigned_users = old_reviewers - noteable.reviewers
added_users = noteable.reviewers - old_reviewers
text_parts = []
Gitlab::I18n.with_default_locale do
text_parts << "#{self.class.issuable_events[:review_requested]} #{added_users.map(&:to_reference).to_sentence}" if added_users.any?
text_parts << "#{self.class.issuable_events[:review_request_removed]} #{unassigned_users.map(&:to_reference).to_sentence}" if unassigned_users.any?
end
body = text_parts.join(' and ')
create_note(NoteSummary.new(noteable, project, author, body, action: 'reviewer'))
end
# Called when the contacts of an issuable are changed or removed
# We intend to reference the contacts but for security we are just
# going to state how many were added/removed for now. See discussion:
# https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77816#note_806114273
#
# added_count - number of contacts added, or 0
# removed_count - number of contacts removed, or 0
#
# Example Note text:
#
# "added 2 contacts"
#
# "added 3 contacts and removed one contact"
#
# Returns the created Note object
def change_issuable_contacts(added_count, removed_count)
text_parts = []
Gitlab::I18n.with_default_locale do
text_parts << "added #{added_count} #{'contact'.pluralize(added_count)}" if added_count > 0
text_parts << "removed #{removed_count} #{'contact'.pluralize(removed_count)}" if removed_count > 0
end
return if text_parts.empty?
body = text_parts.join(' and ')
create_note(NoteSummary.new(noteable, project, author, body, action: 'contact'))
end
# Called when the title of a Noteable is changed
#
# old_title - Previous String title
#
# Example Note text:
#
# "changed title from **Old** to **New**"
#
# Returns the created Note object
def change_title(old_title)
new_title = noteable.title.dup
old_diffs, new_diffs = Gitlab::Diff::InlineDiff.new(old_title, new_title).inline_diffs
marked_old_title = Gitlab::Diff::InlineDiffMarkdownMarker.new(old_title).mark(old_diffs)
marked_new_title = Gitlab::Diff::InlineDiffMarkdownMarker.new(new_title).mark(new_diffs)
body = "changed title from **#{marked_old_title}** to **#{marked_new_title}**"
track_issue_event(:track_issue_title_changed_action)
work_item_activity_counter.track_work_item_title_changed_action(author: author) if noteable.is_a?(WorkItem)
create_note(NoteSummary.new(noteable, project, author, body, action: 'title'))
end
# Called when the hierarchy of a work item is changed
#
# noteable - Noteable object that responds to `work_item_parent` and `work_item_children`
# project - Project owning noteable
# author - User performing the change
#
# Example Note text:
#
# "added #1 as child Task"
#
# Returns the created Note object
def hierarchy_changed(work_item, action)
params = hierarchy_note_params(action, noteable, work_item)
create_note(NoteSummary.new(noteable, project, author, params[:parent_note_body], action: params[:parent_action]))
create_note(NoteSummary.new(work_item, project, author, params[:child_note_body], action: params[:child_action]))
end
# Called when the description of a Noteable is changed
#
# noteable - Noteable object that responds to `description`
# project - Project owning noteable
# author - User performing the change
#
# Example Note text:
#
# "changed the description"
#
# Returns the created Note object
def change_description
body = 'changed the description'
track_issue_event(:track_issue_description_changed_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'description'))
end
# Called when a Mentionable (the `mentioned_in`) references another Mentionable (the `mentioned`,
# passed to this service as `noteable`).
#
# Example Note text:
#
# "mentioned in #1"
#
# "mentioned in !2"
#
# "mentioned in 54f7727c"
#
# See cross_reference_note_content.
#
# @param mentioned_in [Mentionable]
# @return [Note]
def cross_reference(mentioned_in)
return if cross_reference_disallowed?(mentioned_in)
gfm_reference = mentioned_in.gfm_reference(noteable.project || noteable.group)
body = cross_reference_note_content(gfm_reference)
if noteable.is_a?(ExternalIssue)
Integrations::CreateExternalCrossReferenceWorker.perform_async(
noteable.project_id,
noteable.id,
mentioned_in.class.name,
mentioned_in.id,
author.id
)
else
track_cross_reference_action
created_at = mentioner.created_at if USE_COMMIT_DATE_FOR_CROSS_REFERENCE_NOTE && mentioner.is_a?(Commit)
create_note(NoteSummary.new(noteable, noteable.project, author, body, action: 'cross_reference', created_at: created_at))
end
end
# Check if a cross-reference is disallowed
#
# This method prevents adding a "mentioned in !1" note on every single commit
# in a merge request. Additionally, it prevents the creation of references to
# external issues (which would fail).
#
# @param mentioned_in [Mentionable]
# @return [Boolean]
def cross_reference_disallowed?(mentioned_in)
return true if noteable.is_a?(ExternalIssue) && !noteable.project&.external_references_supported?
return false unless mentioned_in.is_a?(MergeRequest)
return false unless noteable.is_a?(Commit)
mentioned_in.commits.include?(noteable)
end
# Called when the status of a Task has changed
#
# new_task - TaskList::Item object.
#
# Example Note text:
#
# "marked the checklist item Whatever as completed."
#
# Returns the created Note object
def change_task_status(new_task)
status_label = new_task.complete? ? Taskable::COMPLETED : Taskable::INCOMPLETE
body = "marked the checklist item **#{new_task.source}** as #{status_label}"
track_issue_event(:track_issue_description_changed_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'task'))
end
# Called when noteable has been moved to another project
#
# noteable_ref - Referenced noteable
# direction - symbol, :to or :from
#
# Example Note text:
#
# "moved to some_namespace/project_new#11"
#
# Returns the created Note object
def noteable_moved(noteable_ref, direction)
unless [:to, :from].include?(direction)
raise ArgumentError, "Invalid direction `#{direction}`"
end
cross_reference = noteable_ref.to_reference(project)
body = "moved #{direction} #{cross_reference}"
track_issue_event(:track_issue_moved_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'moved'))
end
# Called when noteable has been cloned
#
# noteable_ref - Referenced noteable
# direction - symbol, :to or :from
# created_at - timestamp for the system note, defaults to current time
#
# Example Note text:
#
# "cloned to some_namespace/project_new#11"
#
# Returns the created Note object
def noteable_cloned(noteable_ref, direction, created_at: nil)
unless [:to, :from].include?(direction)
raise ArgumentError, "Invalid direction `#{direction}`"
end
cross_reference = noteable_ref.to_reference(project)
body = "cloned #{direction} #{cross_reference}"
track_issue_event(:track_issue_cloned_action) if direction == :to
create_note(NoteSummary.new(noteable, project, author, body, action: 'cloned', created_at: created_at))
end
# Called when the confidentiality changes
#
# Example Note text:
#
# "made the issue confidential"
#
# Returns the created Note object
def change_issue_confidentiality
if noteable.confidential
body = "made the #{noteable_name} confidential"
action = 'confidential'
track_issue_event(:track_issue_made_confidential_action)
else
body = "made the #{noteable_name} visible to everyone"
action = 'visible'
track_issue_event(:track_issue_made_visible_action)
end
create_note(NoteSummary.new(noteable, project, author, body, action: action))
end
# Called when the status of a Noteable is changed
#
# status - String status
# source - Mentionable performing the change, or nil
#
# Example Note text:
#
# "merged"
#
# "closed via bc17db76"
#
# Returns the created Note object
def change_status(status, source = nil)
create_resource_state_event(status: status, mentionable_source: source)
end
# Check if a cross reference to a Mentionable from the `mentioned_in` Mentionable
# already exists.
#
# This method is used to prevent multiple notes being created for a mention
# when a issue is updated, for example. The method also calls `existing_mentions_for`
# to check if the mention is in a commit, and return matches only on commit hash
# instead of project + commit, to avoid repeated mentions from forks.
#
# @param mentioned_in [Mentionable]
# @return [Boolean]
def cross_reference_exists?(mentioned_in)
notes = noteable.notes.system
existing_mentions_for(mentioned_in, noteable, notes).exists?
end
# Called when a Noteable has been marked as the canonical Issue of a duplicate
#
# duplicate_issue - Issue that was a duplicate of this
#
# Example Note text:
#
# "marked #1234 as a duplicate of this issue"
#
# "marked other_project#5678 as a duplicate of this issue"
#
# Returns the created Note object
def mark_canonical_issue_of_duplicate(duplicate_issue)
body = "marked #{duplicate_issue.to_reference(project)} as a duplicate of this issue"
create_note(NoteSummary.new(noteable, project, author, body, action: 'duplicate'))
end
# Called when a Noteable has been marked as a duplicate of another Issue
#
# canonical_issue - Issue that this is a duplicate of
#
# Example Note text:
#
# "marked this issue as a duplicate of #1234"
#
# "marked this issue as a duplicate of other_project#5678"
#
# Returns the created Note object
def mark_duplicate_issue(canonical_issue)
body = "marked this issue as a duplicate of #{canonical_issue.to_reference(project)}"
track_issue_event(:track_issue_marked_as_duplicate_action)
create_note(NoteSummary.new(noteable, project, author, body, action: 'duplicate'))
end
def add_email_participants(body)
create_note(NoteSummary.new(noteable, project, author, body))
end
def discussion_lock
action = noteable.discussion_locked? ? 'locked' : 'unlocked'
body = "#{action} the discussion in this #{noteable.class.to_s.titleize.downcase}"
if action == 'locked'
track_issue_event(:track_issue_locked_action)
else
track_issue_event(:track_issue_unlocked_action)
end
create_note(NoteSummary.new(noteable, project, author, body, action: action))
end
def close_after_error_tracking_resolve
create_resource_state_event(status: 'closed', close_after_error_tracking_resolve: true)
end
def auto_resolve_prometheus_alert
create_resource_state_event(status: 'closed', close_auto_resolve_prometheus_alert: true)
end
def change_issue_type(previous_type)
previous = previous_type.humanize(capitalize: false)
new = noteable.issue_type.humanize(capitalize: false)
body = "changed type from #{previous} to #{new}"
create_note(NoteSummary.new(noteable, project, author, body, action: 'issue_type'))
end
private
def cross_reference_note_content(gfm_reference)
"#{self.class.cross_reference_note_prefix}#{gfm_reference}"
end
def existing_mentions_for(mentioned_in, noteable, notes)
if mentioned_in.is_a?(Commit)
text = "#{self.class.cross_reference_note_prefix}%#{mentioned_in.to_reference(nil)}"
notes.like_note_or_capitalized_note(text)
else
gfm_reference = mentioned_in.gfm_reference(noteable.project || noteable.group)
text = cross_reference_note_content(gfm_reference)
notes.for_note_or_capitalized_note(text)
end
end
def self.cross_reference_note_prefix
'mentioned in '
end
def self.cross_reference?(note_text)
note_text =~ /\A#{cross_reference_note_prefix}/i
end
def create_resource_state_event(params)
ResourceEvents::ChangeStateService.new(resource: noteable, user: author)
.execute(params)
end
def issue_activity_counter
Gitlab::UsageDataCounters::IssueActivityUniqueCounter
end
def work_item_activity_counter
Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter
end
def track_cross_reference_action
track_issue_event(:track_issue_cross_referenced_action)
end
def hierarchy_note_params(action, parent, child)
return {} unless child && parent
child_type = child.issue_type.humanize(capitalize: false)
parent_type = parent.issue_type.humanize(capitalize: false)
if action == 'relate'
{
parent_note_body: "added #{child.to_reference} as child #{child_type}",
child_note_body: "added #{parent.to_reference} as parent #{parent_type}",
parent_action: 'relate_to_child',
child_action: 'relate_to_parent'
}
else
{
parent_note_body: "removed child #{child_type} #{child.to_reference}",
child_note_body: "removed parent #{parent_type} #{parent.to_reference}",
parent_action: 'unrelate_from_child',
child_action: 'unrelate_from_parent'
}
end
end
def track_issue_event(event_name)
return unless noteable.is_a?(Issue)
issue_activity_counter.public_send(event_name, author: author, project: project || noteable.project) # rubocop: disable GitlabSecurity/PublicSend
end
def noteable_name
name = noteable.try(:issue_type) || noteable.to_ability_name
name.humanize(capitalize: false)
end
def extract_issuable_reference(reference)
if reference.is_a?(Array)
reference.map { |item| item.to_reference(noteable.resource_parent) }.to_sentence
else
reference.to_reference(noteable.resource_parent)
end
end
end
end
SystemNotes::IssuablesService.prepend_mod_with('SystemNotes::IssuablesService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::SystemNotes::IssuablesService, feature_category: :team_planning do
include ProjectForksHelper
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, :repository, group: group) }
let_it_be(:author) { create(:user) }
let(:noteable) { create(:issue, project: project) }
let(:issue) { noteable }
let(:service) { described_class.new(noteable: noteable, project: project, author: author) }
describe '#relate_issuable' do
let_it_be(:issue1) { create(:issue, project: project) }
let_it_be(:issue2) { create(:issue, project: project) }
let(:noteable_ref) { issue1 }
subject(:system_note) { service.relate_issuable(noteable_ref) }
context 'when issue marks another as related' do
it_behaves_like 'a system note' do
let(:action) { 'relate' }
end
it 'sets the note text' do
expect(system_note.note).to eq "marked this issue as related to #{issue1.to_reference(project)}"
end
end
context 'when issue marks several other issues as related' do
let(:noteable_ref) { [issue1, issue2] }
it_behaves_like 'a system note' do
let(:action) { 'relate' }
end
it 'sets the note text' do
expect(system_note.note).to eq(
"marked this issue as related to #{issue1.to_reference(project)} and #{issue2.to_reference(project)}"
)
end
end
context 'with work items' do
let_it_be(:noteable) { create(:work_item, :task, project: project) }
it 'sets the note text with the correct work item type' do
expect(subject.note).to eq "marked this task as related to #{noteable_ref.to_reference(project)}"
end
end
end
describe '#unrelate_issuable' do
let(:noteable_ref) { create(:issue) }
subject { service.unrelate_issuable(noteable_ref) }
it_behaves_like 'a system note' do
let(:action) { 'unrelate' }
end
context 'when issue relation is removed' do
it 'sets the note text' do
expect(subject.note).to eq "removed the relation with #{noteable_ref.to_reference(project)}"
end
end
end
describe '#change_assignee' do
subject { service.change_assignee(assignee) }
let(:assignee) { create(:user) }
it_behaves_like 'a system note' do
let(:action) { 'assignee' }
end
context 'when assignee added' do
it_behaves_like 'a note with overridable created_at'
it 'sets the note text' do
expect(subject.note).to eq "assigned to @#{assignee.username}"
end
end
context 'when assignee removed' do
let(:assignee) { nil }
it_behaves_like 'a note with overridable created_at'
it 'sets the note text' do
expect(subject.note).to eq 'removed assignee'
end
end
end
describe '#change_issuable_assignees' do
subject { service.change_issuable_assignees([assignee]) }
let(:assignee) { create(:user) }
let(:assignee1) { create(:user) }
let(:assignee2) { create(:user) }
let(:assignee3) { create(:user) }
it_behaves_like 'a system note' do
let(:action) { 'assignee' }
end
def build_note(old_assignees, new_assignees)
issue.assignees = new_assignees
service.change_issuable_assignees(old_assignees).note
end
it_behaves_like 'a note with overridable created_at'
it 'builds a correct phrase when an assignee is added to a non-assigned issue' do
expect(build_note([], [assignee1])).to eq "assigned to @#{assignee1.username}"
end
it 'builds a correct phrase when assignee removed' do
expect(build_note([assignee1], [])).to eq "unassigned @#{assignee1.username}"
end
it 'builds a correct phrase when assignees changed' do
expect(build_note([assignee1], [assignee2])).to eq \
"assigned to @#{assignee2.username} and unassigned @#{assignee1.username}"
end
it 'builds a correct phrase when three assignees removed and one added' do
expect(build_note([assignee, assignee1, assignee2], [assignee3])).to eq \
"assigned to @#{assignee3.username} and unassigned @#{assignee.username}, @#{assignee1.username}, and @#{assignee2.username}"
end
it 'builds a correct phrase when one assignee changed from a set' do
expect(build_note([assignee, assignee1], [assignee, assignee2])).to eq \
"assigned to @#{assignee2.username} and unassigned @#{assignee1.username}"
end
it 'builds a correct phrase when one assignee removed from a set' do
expect(build_note([assignee, assignee1, assignee2], [assignee, assignee1])).to eq \
"unassigned @#{assignee2.username}"
end
it 'builds a correct phrase when the locale is different' do
Gitlab::I18n.with_locale('pt-BR') do
expect(build_note([assignee, assignee1, assignee2], [assignee3])).to eq \
"assigned to @#{assignee3.username} and unassigned @#{assignee.username}, @#{assignee1.username}, and @#{assignee2.username}"
end
end
end
describe '#change_issuable_reviewers' do
subject { service.change_issuable_reviewers([reviewer]) }
let_it_be(:noteable) { create(:merge_request, :simple, source_project: project) }
let_it_be(:reviewer) { create(:user) }
let_it_be(:reviewer1) { create(:user) }
let_it_be(:reviewer2) { create(:user) }
let_it_be(:reviewer3) { create(:user) }
it_behaves_like 'a system note' do
let(:action) { 'reviewer' }
end
def build_note(old_reviewers, new_reviewers)
noteable.reviewers = new_reviewers
service.change_issuable_reviewers(old_reviewers).note
end
it 'builds a correct phrase when a reviewer is added to a non-assigned merge request' do
expect(build_note([], [reviewer1])).to eq "requested review from @#{reviewer1.username}"
end
it 'builds a correct phrase when reviewer is removed' do
expect(build_note([reviewer], [])).to eq "removed review request for @#{reviewer.username}"
end
it 'builds a correct phrase when reviewers changed' do
expect(build_note([reviewer1], [reviewer2])).to(
eq("requested review from @#{reviewer2.username} and removed review request for @#{reviewer1.username}")
)
end
it 'builds a correct phrase when three reviewers removed and one added' do
expect(build_note([reviewer, reviewer1, reviewer2], [reviewer3])).to(
eq("requested review from @#{reviewer3.username} and removed review request for @#{reviewer.username}, @#{reviewer1.username}, and @#{reviewer2.username}")
)
end
it 'builds a correct phrase when one reviewer is changed from a set' do
expect(build_note([reviewer, reviewer1], [reviewer, reviewer2])).to(
eq("requested review from @#{reviewer2.username} and removed review request for @#{reviewer1.username}")
)
end
it 'builds a correct phrase when one reviewer removed from a set' do
expect(build_note([reviewer, reviewer1, reviewer2], [reviewer, reviewer1])).to(
eq("removed review request for @#{reviewer2.username}")
)
end
it 'builds a correct phrase when the locale is different' do
Gitlab::I18n.with_locale('pt-BR') do
expect(build_note([reviewer, reviewer1, reviewer2], [reviewer3])).to(
eq("requested review from @#{reviewer3.username} and removed review request for @#{reviewer.username}, @#{reviewer1.username}, and @#{reviewer2.username}")
)
end
end
end
describe '#change_issuable_contacts' do
subject { service.change_issuable_contacts(1, 1) }
let_it_be(:noteable) { create(:issue, project: project) }
it_behaves_like 'a system note' do
let(:action) { 'contact' }
end
def build_note(added_count, removed_count)
service.change_issuable_contacts(added_count, removed_count).note
end
it 'builds a correct phrase when one contact is added' do
expect(build_note(1, 0)).to eq "added 1 contact"
end
it 'builds a correct phrase when one contact is removed' do
expect(build_note(0, 1)).to eq "removed 1 contact"
end
it 'builds a correct phrase when one contact is added and one contact is removed' do
expect(build_note(1, 1)).to(
eq("added 1 contact and removed 1 contact")
)
end
it 'builds a correct phrase when three contacts are added and one removed' do
expect(build_note(3, 1)).to(
eq("added 3 contacts and removed 1 contact")
)
end
it 'builds a correct phrase when three contacts are removed and one added' do
expect(build_note(1, 3)).to(
eq("added 1 contact and removed 3 contacts")
)
end
it 'builds a correct phrase when the locale is different' do
Gitlab::I18n.with_locale('pt-BR') do
expect(build_note(1, 3)).to(
eq("added 1 contact and removed 3 contacts")
)
end
end
end
describe '#change_status' do
subject { service.change_status(status, source) }
let(:status) { 'reopened' }
let(:source) { nil }
it 'creates a resource state event' do
expect { subject }.to change { ResourceStateEvent.count }.by(1)
end
end
describe '#change_title' do
let(:noteable) { create(:issue, project: project, title: 'Lorem ipsum') }
subject { service.change_title('Old title') }
context 'when noteable responds to `title`' do
it_behaves_like 'a system note' do
let(:action) { 'title' }
end
it_behaves_like 'a note with overridable created_at'
it 'sets the note text' do
expect(subject.note)
.to eq "changed title from **{-Old title-}** to **{+Lorem ipsum+}**"
end
end
end
describe '#change_description' do
subject { service.change_description }
context 'when noteable responds to `description`' do
it_behaves_like 'a system note' do
let(:action) { 'description' }
end
it_behaves_like 'a note with overridable created_at'
it 'sets the note text' do
expect(subject.note).to eq('changed the description')
end
it 'associates the related description version' do
noteable.update!(description: 'New description')
description_version_id = subject.system_note_metadata.description_version_id
expect(description_version_id).not_to be_nil
expect(description_version_id).to eq(noteable.saved_description_version.id)
end
end
end
describe '#change_issue_confidentiality' do
subject { service.change_issue_confidentiality }
context 'issue has been made confidential' do
before do
noteable.update_attribute(:confidential, true)
end
it_behaves_like 'a system note' do
let(:action) { 'confidential' }
end
it 'sets the note text' do
expect(subject.note).to eq 'made the issue confidential'
end
end
context 'issue has been made visible' do
it_behaves_like 'a system note' do
let(:action) { 'visible' }
end
it 'sets the note text' do
expect(subject.note).to eq 'made the issue visible to everyone'
end
end
end
describe '#cross_reference' do
let(:service) { described_class.new(noteable: noteable, author: author) }
let(:mentioned_in) { create(:issue, project: project) }
subject { service.cross_reference(mentioned_in) }
it_behaves_like 'a system note' do
let(:action) { 'cross_reference' }
end
context 'when cross-reference disallowed' do
before do
expect_next_instance_of(described_class) do |instance|
expect(instance).to receive(:cross_reference_disallowed?).and_return(true)
end
end
it 'returns nil' do
expect(subject).to be_nil
end
it 'does not create a system note metadata record' do
expect { subject }.not_to change { SystemNoteMetadata.count }
end
end
context 'when cross-reference allowed' do
before do
expect_next_instance_of(described_class) do |instance|
expect(instance).to receive(:cross_reference_disallowed?).and_return(false)
end
end
it_behaves_like 'a system note' do
let(:action) { 'cross_reference' }
end
it_behaves_like 'a note with overridable created_at'
describe 'note_body' do
context 'cross-project' do
let(:project2) { create(:project, :repository) }
let(:mentioned_in) { create(:issue, project: project2) }
context 'from Commit' do
let(:mentioned_in) { project2.repository.commit }
it 'references the mentioning commit' do
expect(subject.note).to eq "mentioned in commit #{mentioned_in.to_reference(project)}"
end
end
context 'from non-Commit' do
it 'references the mentioning object' do
expect(subject.note).to eq "mentioned in issue #{mentioned_in.to_reference(project)}"
end
end
end
context 'within the same project' do
context 'from Commit' do
let(:mentioned_in) { project.repository.commit }
it 'references the mentioning commit' do
expect(subject.note).to eq "mentioned in commit #{mentioned_in.to_reference}"
end
end
context 'from non-Commit' do
it 'references the mentioning object' do
expect(subject.note).to eq "mentioned in issue #{mentioned_in.to_reference}"
end
end
end
end
context 'with external issue' do
let(:noteable) { ExternalIssue.new('JIRA-123', project) }
let(:mentioned_in) { project.commit }
it 'queues a background worker' do
expect(Integrations::CreateExternalCrossReferenceWorker).to receive(:perform_async).with(
project.id,
'JIRA-123',
'Commit',
mentioned_in.id,
author.id
)
subject
end
end
end
end
describe '#cross_reference_exists?' do
let(:commit0) { project.commit }
let(:commit1) { project.commit('HEAD~2') }
context 'issue from commit' do
before do
# Mention issue (noteable) from commit0
service.cross_reference(commit0)
end
it 'is truthy when already mentioned' do
expect(service.cross_reference_exists?(commit0))
.to be_truthy
end
it 'is falsey when not already mentioned' do
expect(service.cross_reference_exists?(commit1))
.to be_falsey
end
context 'legacy capitalized cross reference' do
before do
# Mention issue (noteable) from commit0
system_note = service.cross_reference(commit0)
system_note.update!(note: system_note.note.capitalize)
end
it 'is truthy when already mentioned' do
expect(service.cross_reference_exists?(commit0))
.to be_truthy
end
end
end
context 'commit from commit' do
let(:service) { described_class.new(noteable: commit0, author: author) }
before do
# Mention commit1 from commit0
service.cross_reference(commit1)
end
it 'is truthy when already mentioned' do
expect(service.cross_reference_exists?(commit1))
.to be_truthy
end
it 'is falsey when not already mentioned' do
service = described_class.new(noteable: commit1, author: author)
expect(service.cross_reference_exists?(commit0))
.to be_falsey
end
context 'legacy capitalized cross reference' do
before do
# Mention commit1 from commit0
system_note = service.cross_reference(commit1)
system_note.update!(note: system_note.note.capitalize)
end
it 'is truthy when already mentioned' do
expect(service.cross_reference_exists?(commit1))
.to be_truthy
end
end
end
context 'commit with cross-reference from fork', :sidekiq_might_not_need_inline do
let(:author2) { create(:project_member, :reporter, user: create(:user), project: project).user }
let(:forked_project) { fork_project(project, author2, repository: true) }
let(:commit2) { forked_project.commit }
let(:service) { described_class.new(noteable: noteable, author: author2) }
before do
service.cross_reference(commit0)
end
it 'is true when a fork mentions an external issue' do
expect(service.cross_reference_exists?(commit2))
.to be true
end
context 'legacy capitalized cross reference' do
before do
system_note = service.cross_reference(commit0)
system_note.update!(note: system_note.note.capitalize)
end
it 'is true when a fork mentions an external issue' do
expect(service.cross_reference_exists?(commit2))
.to be true
end
end
end
end
describe '#change_task_status' do
let(:noteable) { create(:issue, project: project) }
let(:task) { double(:task, complete?: true, source: 'task') }
subject { service.change_task_status(task) }
it_behaves_like 'a system note' do
let(:action) { 'task' }
end
it "posts the 'marked the checklist item as complete' system note" do
expect(subject.note).to eq("marked the checklist item **task** as completed")
end
end
describe '#noteable_moved' do
let(:new_project) { create(:project) }
let(:new_noteable) { create(:issue, project: new_project) }
subject do
# service = described_class.new(noteable: noteable, project: project, author: author)
service.noteable_moved(new_noteable, direction)
end
shared_examples 'cross project mentionable' do
include MarkupHelper
it 'contains cross reference to new noteable' do
expect(subject.note).to include cross_project_reference(new_project, new_noteable)
end
it 'mentions referenced noteable' do
expect(subject.note).to include new_noteable.to_reference
end
it 'mentions referenced project' do
expect(subject.note).to include new_project.full_path
end
end
context 'moved to' do
let(:direction) { :to }
it_behaves_like 'cross project mentionable'
it_behaves_like 'a system note' do
let(:action) { 'moved' }
end
it 'notifies about noteable being moved to' do
expect(subject.note).to match('moved to')
end
end
context 'moved from' do
let(:direction) { :from }
it_behaves_like 'cross project mentionable'
it_behaves_like 'a system note' do
let(:action) { 'moved' }
end
it 'notifies about noteable being moved from' do
expect(subject.note).to match('moved from')
end
end
context 'invalid direction' do
let(:direction) { :invalid }
it 'raises error' do
expect { subject }.to raise_error StandardError, /Invalid direction/
end
end
end
describe '#noteable_cloned' do
let_it_be(:new_project) { create(:project) }
let_it_be(:new_noteable) { create(:issue, project: new_project) }
subject do
service.noteable_cloned(new_noteable, direction)
end
shared_examples 'cross project mentionable' do
include MarkupHelper
it 'contains cross reference to new noteable' do
expect(subject.note).to include cross_project_reference(new_project, new_noteable)
end
it 'mentions referenced noteable' do
expect(subject.note).to include new_noteable.to_reference
end
it 'mentions referenced project' do
expect(subject.note).to include new_project.full_path
end
end
context 'cloned to' do
let(:direction) { :to }
it_behaves_like 'cross project mentionable'
it_behaves_like 'a system note' do
let(:action) { 'cloned' }
end
it 'notifies about noteable being cloned to' do
expect(subject.note).to match('cloned to')
end
end
context 'cloned from' do
let(:direction) { :from }
it_behaves_like 'cross project mentionable'
it_behaves_like 'a system note' do
let(:action) { 'cloned' }
end
it 'notifies about noteable being cloned from' do
expect(subject.note).to match('cloned from')
end
end
context 'invalid direction' do
let(:direction) { :invalid }
it 'raises error' do
expect { subject }.to raise_error StandardError, /Invalid direction/
end
end
context 'custom created timestamp' do
let(:direction) { :from }
it 'allows setting of custom created_at value' do
timestamp = 1.day.ago
note = service.noteable_cloned(new_noteable, direction, created_at: timestamp)
expect(note.created_at).to be_like_time(timestamp)
end
it 'defaults to current time when created_at is not given', :freeze_time do
expect(subject.created_at).to be_like_time(Time.current)
end
end
context 'metrics' do
context 'cloned from' do
let(:direction) { :from }
it 'does not tracks usage' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter)
.not_to receive(:track_issue_cloned_action).with(author: author)
subject
end
end
context 'cloned to', :snowplow do
let(:direction) { :to }
it 'tracks usage' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter)
.to receive(:track_issue_cloned_action).with(author: author, project: project)
subject
end
it_behaves_like 'internal event tracking' do
let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_CLONED }
let(:user) { author }
let(:namespace) { project.namespace }
end
end
end
end
describe '#mark_duplicate_issue' do
subject { service.mark_duplicate_issue(canonical_issue) }
context 'within the same project' do
let(:canonical_issue) { create(:issue, project: project) }
it_behaves_like 'a system note' do
let(:action) { 'duplicate' }
end
it { expect(subject.note).to eq "marked this issue as a duplicate of #{canonical_issue.to_reference}" }
end
context 'across different projects' do
let(:other_project) { create(:project) }
let(:canonical_issue) { create(:issue, project: other_project) }
it_behaves_like 'a system note' do
let(:action) { 'duplicate' }
end
it { expect(subject.note).to eq "marked this issue as a duplicate of #{canonical_issue.to_reference(project)}" }
end
end
describe '#mark_canonical_issue_of_duplicate' do
subject { service.mark_canonical_issue_of_duplicate(duplicate_issue) }
context 'within the same project' do
let(:duplicate_issue) { create(:issue, project: project) }
it_behaves_like 'a system note' do
let(:action) { 'duplicate' }
end
it { expect(subject.note).to eq "marked #{duplicate_issue.to_reference} as a duplicate of this issue" }
end
context 'across different projects' do
let(:other_project) { create(:project) }
let(:duplicate_issue) { create(:issue, project: other_project) }
it_behaves_like 'a system note' do
let(:action) { 'duplicate' }
end
it { expect(subject.note).to eq "marked #{duplicate_issue.to_reference(project)} as a duplicate of this issue" }
end
end
describe '#discussion_lock' do
subject { service.discussion_lock }
context 'discussion unlocked' do
it_behaves_like 'a system note' do
let(:action) { 'unlocked' }
end
it 'creates the note text correctly' do
[:issue, :merge_request].each do |type|
issuable = create(type) # rubocop:disable Rails/SaveBang
service = described_class.new(noteable: issuable, author: author)
expect(service.discussion_lock.note)
.to eq("unlocked the discussion in this #{type.to_s.titleize.downcase}")
end
end
end
context 'discussion locked' do
before do
noteable.update_attribute(:discussion_locked, true)
end
it_behaves_like 'a system note' do
let(:action) { 'locked' }
end
it 'creates the note text correctly' do
[:issue, :merge_request].each do |type|
issuable = create(type, discussion_locked: true)
service = described_class.new(noteable: issuable, author: author)
expect(service.discussion_lock.note)
.to eq("locked the discussion in this #{type.to_s.titleize.downcase}")
end
end
end
end
describe '#cross_reference_disallowed?' do
context 'when mentioned_in is not a MergeRequest' do
it 'is falsey' do
mentioned_in = noteable.dup
expect(service.cross_reference_disallowed?(mentioned_in)).to be_falsey
end
end
context 'when mentioned_in is a MergeRequest' do
let(:mentioned_in) { create(:merge_request, :simple, source_project: project) }
let(:noteable) { project.commit }
it 'is truthy when noteable is in commits' do
expect(mentioned_in).to receive(:commits).and_return([noteable])
expect(service.cross_reference_disallowed?(mentioned_in)).to be_truthy
end
it 'is falsey when noteable is not in commits' do
expect(mentioned_in).to receive(:commits).and_return([])
expect(service.cross_reference_disallowed?(mentioned_in)).to be_falsey
end
end
context 'when notable is an ExternalIssue' do
let(:project) { create(:project) }
let(:noteable) { ExternalIssue.new('EXT-1234', project) }
it 'is false with issue tracker supporting referencing' do
create(:jira_integration, project: project)
project.reload
expect(service.cross_reference_disallowed?(noteable)).to be_falsey
end
it 'is true with issue tracker not supporting referencing' do
create(:bugzilla_integration, project: project)
project.reload
expect(service.cross_reference_disallowed?(noteable)).to be_truthy
end
it 'is true without issue tracker' do
expect(service.cross_reference_disallowed?(noteable)).to be_truthy
end
end
end
describe '#close_after_error_tracking_resolve' do
subject { service.close_after_error_tracking_resolve }
it 'creates the expected state event' do
subject
event = ResourceStateEvent.last
expect(event.close_after_error_tracking_resolve).to eq(true)
expect(event.state).to eq('closed')
end
end
describe '#auto_resolve_prometheus_alert' do
subject { service.auto_resolve_prometheus_alert }
it 'creates the expected state event' do
subject
event = ResourceStateEvent.last
expect(event.close_auto_resolve_prometheus_alert).to eq(true)
expect(event.state).to eq('closed')
end
end
describe '#change_issue_type' do
context 'with issue' do
let_it_be_with_reload(:noteable) { create(:issue, project: project) }
subject { service.change_issue_type('incident') }
it_behaves_like 'a system note' do
let(:action) { 'issue_type' }
end
it { expect(subject.note).to eq "changed type from incident to issue" }
end
context 'with work item' do
let_it_be_with_reload(:noteable) { create(:work_item, project: project) }
subject { service.change_issue_type('task') }
it_behaves_like 'a system note' do
let(:action) { 'issue_type' }
end
it { expect(subject.note).to eq "changed type from task to issue" }
end
end
describe '#hierarchy_changed' do
let_it_be_with_reload(:work_item) { create(:work_item, project: project) }
let_it_be_with_reload(:task) { create(:work_item, :task, project: project) }
let(:service) { described_class.new(noteable: work_item, project: project, author: author) }
subject { service.hierarchy_changed(task, hierarchy_change_action) }
context 'when task is added as a child' do
let(:hierarchy_change_action) { 'relate' }
it_behaves_like 'a system note' do
let(:expected_noteable) { task }
let(:action) { 'relate_to_parent' }
end
it 'sets the correct note text' do
expect { subject }.to change { Note.system.count }.by(2)
expect(work_item.notes.last.note).to eq("added ##{task.iid} as child task")
expect(task.notes.last.note).to eq("added ##{work_item.iid} as parent issue")
end
end
context 'when child task is removed' do
let(:hierarchy_change_action) { 'unrelate' }
it_behaves_like 'a system note' do
let(:expected_noteable) { task }
let(:action) { 'unrelate_from_parent' }
end
it 'sets the correct note text' do
expect { subject }.to change { Note.system.count }.by(2)
expect(work_item.notes.last.note).to eq("removed child task ##{task.iid}")
expect(task.notes.last.note).to eq("removed parent issue ##{work_item.iid}")
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class DesignManagementService < ::SystemNotes::BaseService
include ActionView::RecordIdentifier
# Parameters:
# - version [DesignManagement::Version]
#
# Example Note text:
#
# "added [1 designs](link-to-version)"
# "changed [2 designs](link-to-version)"
#
# Returns [Array<Note>]: the created Note objects
def design_version_added(version)
events = DesignManagement::Action.events
link_href = designs_path(version: version.id)
version.designs_by_event.map do |(event_name, designs)|
note_data = self.class.design_event_note_data(events[event_name])
icon_name = note_data[:icon]
n = designs.size
body = "%s [%d %s](%s)" % [note_data[:past_tense], n, 'design'.pluralize(n), link_href]
create_note(NoteSummary.new(noteable, project, author, body, action: icon_name))
end
end
# Called when a new discussion is created on a design
#
# discussion_note - DiscussionNote
#
# Example Note text:
#
# "started a discussion on screen.png"
#
# Returns the created Note object
def design_discussion_added(discussion_note)
design = discussion_note.noteable
body = _('started a discussion on %{design_link}') % {
design_link: '[%s](%s)' % [
design.filename,
designs_path(vueroute: design.filename, anchor: dom_id(discussion_note))
]
}
action = :designs_discussion_added
create_note(NoteSummary.new(noteable, project, author, body, action: action))
end
# Take one of the `DesignManagement::Action.events` and
# return:
# * an English past-tense verb.
# * the name of an icon used in renderin a system note
#
# We do not currently internationalize our system notes,
# instead we just produce English-language descriptions.
# See: https://gitlab.com/gitlab-org/gitlab/issues/30408
# See: https://gitlab.com/gitlab-org/gitlab/issues/14056
def self.design_event_note_data(event)
case event
when DesignManagement::Action.events[:creation]
{ icon: 'designs_added', past_tense: 'added' }
when DesignManagement::Action.events[:modification]
{ icon: 'designs_modified', past_tense: 'updated' }
when DesignManagement::Action.events[:deletion]
{ icon: 'designs_removed', past_tense: 'removed' }
else
raise "Unknown event: #{event}"
end
end
private
def designs_path(params = {})
url_helpers.designs_project_issue_path(project, noteable, params)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe SystemNotes::DesignManagementService, feature_category: :design_management do
let(:project) { create(:project) }
let(:issue) { create(:issue, project: project) }
let(:instance) { described_class.new(noteable: instance_noteable, project: instance_project, author: instance_author) }
describe '#design_version_added' do
let(:instance_noteable) { version.issue }
let(:instance_project) { version.issue.project }
let(:instance_author) { version.author }
subject { instance.design_version_added(version) }
# default (valid) parameters:
let(:n_designs) { 3 }
let(:designs) { create_list(:design, n_designs, issue: issue) }
let(:user) { build(:user) }
let(:version) do
create(:design_version, issue: issue, designs: designs)
end
before do
# Avoid needing to call into gitaly
allow(version).to receive(:author).and_return(user)
end
context 'with one kind of event' do
before do
DesignManagement::Action
.where(design: designs).update_all(event: :modification)
end
it 'makes just one note' do
expect(subject).to contain_exactly(Note)
end
it 'adds a new system note' do
expect { subject }.to change { Note.system.count }.by(1)
end
end
context 'with a mixture of events' do
let(:n_designs) { DesignManagement::Action.events.size }
before do
designs.each_with_index do |design, i|
design.actions.update_all(event: i)
end
end
it 'makes one note for each kind of event' do
expect(subject).to have_attributes(size: n_designs)
end
it 'adds a system note for each kind of event' do
expect { subject }.to change { Note.system.count }.by(n_designs)
end
end
describe 'icons' do
where(:action) do
[
[:creation],
[:modification],
[:deletion]
]
end
with_them do
before do
version.actions.update_all(event: action)
end
subject(:metadata) do
instance.design_version_added(version)
.first.system_note_metadata
end
it 'has a valid action' do
expect(::SystemNoteHelper::ICON_NAMES_BY_ACTION)
.to include(metadata.action)
end
end
end
context 'it succeeds' do
where(:action, :icon, :human_description) do
[
[:creation, 'designs_added', 'added'],
[:modification, 'designs_modified', 'updated'],
[:deletion, 'designs_removed', 'removed']
]
end
with_them do
before do
version.actions.update_all(event: action)
end
let(:anchor_tag) { %r{ <a[^>]*>#{link}</a>} }
let(:href) { instance.send(:designs_path, { version: version.id }) }
let(:link) { "#{n_designs} designs" }
subject(:note) { instance.design_version_added(version).first }
it 'has the correct data' do
expect(note)
.to be_system
.and have_attributes(
system_note_metadata: have_attributes(action: icon),
note: include(human_description)
.and(include link)
.and(include href),
note_html: a_string_matching(anchor_tag)
)
end
end
end
end
describe '#design_discussion_added' do
let(:instance_noteable) { design.issue }
let(:instance_project) { design.issue.project }
let(:instance_author) { discussion_note.author }
subject { instance.design_discussion_added(discussion_note) }
let(:design) { create(:design, :with_file, issue: issue) }
let(:author) { create(:user) }
let(:discussion_note) do
create(:diff_note_on_design, noteable: design, author: author)
end
let(:action) { 'designs_discussion_added' }
it_behaves_like 'a system note' do
let(:noteable) { discussion_note.noteable.issue }
end
it 'adds a new system note' do
expect { subject }.to change { Note.system.count }.by(1)
end
it 'has the correct note text' do
href = instance.send(:designs_path,
{ vueroute: design.filename, anchor: ActionView::RecordIdentifier.dom_id(discussion_note) }
)
expect(subject.note).to eq("started a discussion on [#{design.filename}](#{href})")
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class IncidentsService < ::SystemNotes::BaseService
CHANGED_TEXT = {
occurred_at: 'the event time/date on ',
note: 'the text on ',
occurred_at_and_note: 'the event time/date and text on '
}.freeze
def initialize(noteable:)
@noteable = noteable
@project = noteable.project
end
def add_timeline_event(timeline_event)
author = timeline_event.author
body = 'added an incident timeline event'
create_note(NoteSummary.new(noteable, project, author, body, action: 'timeline_event'))
end
def edit_timeline_event(timeline_event, author, was_changed:)
changed_text = CHANGED_TEXT.fetch(was_changed, '')
body = "edited #{changed_text}incident timeline event"
create_note(NoteSummary.new(noteable, project, author, body, action: 'timeline_event'))
end
def delete_timeline_event(author)
body = 'deleted an incident timeline event'
create_note(NoteSummary.new(noteable, project, author, body, action: 'timeline_event'))
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe SystemNotes::IncidentsService, feature_category: :incident_management do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let_it_be(:author) { create(:user) }
let_it_be(:incident) { create(:incident, project: project, author: user) }
let_it_be(:timeline_event) do
create(:incident_management_timeline_event, project: project, incident: incident, author: author)
end
describe '#add_timeline_event' do
subject { described_class.new(noteable: incident).add_timeline_event(timeline_event) }
it_behaves_like 'a system note' do
let(:noteable) { incident }
let(:action) { 'timeline_event' }
end
it 'posts the correct text to the system note' do
expect(subject.note).to match("added an incident timeline event")
end
end
describe '#edit_timeline_event' do
let(:was_changed) { :unknown }
subject do
described_class.new(noteable: incident).edit_timeline_event(timeline_event, author, was_changed: was_changed)
end
it_behaves_like 'a system note' do
let(:noteable) { incident }
let(:action) { 'timeline_event' }
end
context "when only timeline event's occurred_at was changed" do
let(:was_changed) { :occurred_at }
it 'posts the correct text to the system note' do
expect(subject.note).to match("edited the event time/date on incident timeline event")
end
end
context "when only timeline event's note was changed" do
let(:was_changed) { :note }
it 'posts the correct text to the system note' do
expect(subject.note).to match("edited the text on incident timeline event")
end
end
context "when both timeline events occurred_at and note was changed" do
let(:was_changed) { :occurred_at_and_note }
it 'posts the correct text to the system note' do
expect(subject.note).to match("edited the event time/date and text on incident timeline event")
end
end
context "when was changed reason is unknown" do
let(:was_changed) { :unknown }
it 'posts the correct text to the system note' do
expect(subject.note).to match("edited incident timeline event")
end
end
end
describe '#delete_timeline_event' do
subject { described_class.new(noteable: incident).delete_timeline_event(author) }
it_behaves_like 'a system note' do
let(:noteable) { incident }
let(:action) { 'timeline_event' }
end
it 'posts the correct text to the system note' do
expect(subject.note).to match('deleted an incident timeline event')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class CommitService < ::SystemNotes::BaseService
NEW_COMMIT_DISPLAY_LIMIT = 10
# Called when commits are added to a merge request
#
# new_commits - Array of Commits added since last push
# existing_commits - Array of Commits added in a previous push
# oldrev - Optional String SHA of a previous Commit
#
# See new_commit_summary and existing_commit_summary.
#
# Returns the created Note object
def add_commits(new_commits, existing_commits = [], oldrev = nil)
total_count = new_commits.length + existing_commits.length
commits_text = "#{total_count} commit".pluralize(total_count)
text_parts = ["added #{commits_text}"]
text_parts << commits_list(noteable, new_commits, existing_commits, oldrev)
text_parts << "[Compare with previous version](#{diff_comparison_path(noteable, project, oldrev)})"
body = text_parts.join("\n\n")
create_note(NoteSummary.new(noteable, project, author, body, action: 'commit', commit_count: total_count))
end
# Called when a commit was tagged
#
# tag_name - The created tag name
#
# Returns the created Note object
def tag_commit(tag_name)
link = url_helpers.project_tag_path(project, id: tag_name)
body = "tagged commit #{noteable.sha} to [`#{tag_name}`](#{link})"
create_note(NoteSummary.new(noteable, project, author, body, action: 'tag'))
end
private
# Build an Array of lines detailing each commit added in a merge request
#
# new_commits - Array of new Commit objects
#
# Returns an Array of Strings
def new_commits_list(new_commits)
new_commits.collect do |commit|
content_tag('li', "#{commit.short_id} - #{commit.title}")
end
end
# Builds an Array of lines describing each commit and truncate them based on the limit
# to avoid creating a note with a large number of commits.
#
# commits - Array of Commit objects
#
# Returns an Array of Strings
#
# rubocop: disable CodeReuse/ActiveRecord
def new_commit_summary(commits, start_rev)
if commits.size > NEW_COMMIT_DISPLAY_LIMIT
no_of_commits_to_truncate = commits.size - NEW_COMMIT_DISPLAY_LIMIT
commits_to_truncate = commits.take(no_of_commits_to_truncate)
remaining_commits = commits.drop(no_of_commits_to_truncate)
[truncated_new_commits(commits_to_truncate, start_rev)] + new_commits_list(remaining_commits)
else
new_commits_list(commits)
end
end
# rubocop: enable CodeReuse/ActiveRecord
# Builds a summary line that describes given truncated commits.
#
# commits - Array of Commit objects
# start_rev - String SHA of a Commit that will be used as the starting SHA of the range
#
# Returns a String wrapped in 'li' tag.
def truncated_new_commits(commits, start_rev)
count = commits.size
commit_ids = if count == 1
commits.first.short_id
elsif start_rev && !Gitlab::Git.blank_ref?(start_rev)
"#{Commit.truncate_sha(start_rev)}...#{commits.last.short_id}"
else
# This two-dots notation seems to be not functioning as expected, but we should
# fallback to it as start_rev can be empty.
#
# For more information, please see https://gitlab.com/gitlab-org/gitlab/-/issues/391809
"#{commits.first.short_id}..#{commits.last.short_id}"
end
commits_text = "#{count} earlier commit".pluralize(count)
content_tag('li', "#{commit_ids} - #{commits_text}")
end
# Builds a list of existing and new commits according to existing_commits and
# new_commits methods.
# Returns a String wrapped in `ul` and `li` tags.
def commits_list(noteable, new_commits, existing_commits, oldrev)
existing_commit_summary = existing_commit_summary(noteable, existing_commits, oldrev)
start_rev = existing_commits.empty? ? oldrev : existing_commits.last.id
new_commit_summary = new_commit_summary(new_commits, start_rev).join
content_tag('ul', "#{existing_commit_summary}#{new_commit_summary}".html_safe)
end
# Build a single line summarizing existing commits being added in a merge
# request
#
# existing_commits - Array of existing Commit objects
# oldrev - Optional String SHA of a previous Commit
#
# Examples:
#
# "* ea0f8418...2f4426b7 - 24 commits from branch `master`"
#
# "* ea0f8418..4188f0ea - 15 commits from branch `fork:master`"
#
# "* ea0f8418 - 1 commit from branch `feature`"
#
# Returns a newline-terminated String
def existing_commit_summary(noteable, existing_commits, oldrev = nil)
return '' if existing_commits.empty?
count = existing_commits.size
commit_ids = if count == 1
existing_commits.first.short_id
elsif oldrev && !Gitlab::Git.blank_ref?(oldrev)
"#{Commit.truncate_sha(oldrev)}...#{existing_commits.last.short_id}"
else
"#{existing_commits.first.short_id}..#{existing_commits.last.short_id}"
end
commits_text = "#{count} commit".pluralize(count)
branch = noteable.target_branch
branch = "#{noteable.target_project_namespace}:#{branch}" if noteable.for_fork?
branch_name = content_tag('code', branch)
content_tag('li', "#{commit_ids} - #{commits_text} from branch #{branch_name}".html_safe)
end
def diff_comparison_path(merge_request, project, oldrev)
diff_id = merge_request.merge_request_diff.id
url_helpers.diffs_project_merge_request_path(
project,
merge_request,
diff_id: diff_id,
start_sha: oldrev
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe SystemNotes::CommitService, feature_category: :code_review_workflow do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, :repository, group: group) }
let_it_be(:author) { create(:user) }
let(:commit_service) { described_class.new(noteable: noteable, project: project, author: author) }
describe '#add_commits' do
subject { commit_service.add_commits(new_commits, old_commits, oldrev) }
let(:noteable) { create(:merge_request, source_project: project, target_project: project) }
let(:new_commits) { create_commits(10) }
let(:old_commits) { [] }
let(:oldrev) { nil }
it_behaves_like 'a system note' do
let(:commit_count) { new_commits.size }
let(:action) { 'commit' }
end
describe 'note body' do
let(:note_lines) { subject.note.split("\n").reject(&:blank?) }
describe 'comparison diff link line' do
it 'adds the comparison text' do
expect(note_lines[2]).to match "[Compare with previous version]"
end
end
context 'without existing commits' do
it 'adds a message header' do
expect(note_lines[0]).to eq "added #{new_commits.size} commits"
end
it 'adds a message for each commit' do
decoded_note_content = HTMLEntities.new.decode(subject.note)
new_commits.each do |commit|
expect(decoded_note_content).to include("<li>#{commit.short_id} - #{commit.title}</li>")
end
end
context 'with HTML content' do
let(:new_commits) { [double(title: '<pre>This is a test</pre>', short_id: '12345678')] }
it 'escapes HTML titles' do
expect(note_lines[1]).to eq("<ul><li>12345678 - <pre>This is a test</pre></li></ul>")
end
end
context 'with one commit exceeding the NEW_COMMIT_DISPLAY_LIMIT' do
let(:new_commits) { create_commits(11) }
let(:earlier_commit_summary_line) { note_lines[1] }
it 'includes the truncated new commits summary' do
expect(earlier_commit_summary_line).to start_with("<ul><li>#{new_commits[0].short_id} - 1 earlier commit")
end
context 'with oldrev' do
let(:oldrev) { '12345678abcd' }
it 'includes the truncated new commits summary with the oldrev' do
expect(earlier_commit_summary_line).to start_with("<ul><li>#{new_commits[0].short_id} - 1 earlier commit")
end
end
end
context 'with multiple commits exceeding the NEW_COMMIT_DISPLAY_LIMIT' do
let(:new_commits) { create_commits(13) }
let(:earlier_commit_summary_line) { note_lines[1] }
it 'includes the truncated new commits summary' do
expect(earlier_commit_summary_line).to start_with("<ul><li>#{new_commits[0].short_id}..#{new_commits[2].short_id} - 3 earlier commits")
end
context 'with oldrev' do
let(:oldrev) { '12345678abcd' }
it 'includes the truncated new commits summary with the oldrev' do
expect(earlier_commit_summary_line).to start_with("<ul><li>12345678...#{new_commits[2].short_id} - 3 earlier commits")
end
end
end
end
describe 'summary line for existing commits' do
let(:summary_line) { note_lines[1] }
context 'with one existing commit' do
let(:old_commits) { [noteable.commits.last] }
it 'includes the existing commit' do
expect(summary_line).to start_with("<ul><li>#{old_commits.first.short_id} - 1 commit from branch <code>feature</code>")
end
context 'with new commits exceeding the display limit' do
let(:summary_line) { note_lines[1] }
let(:new_commits) { create_commits(13) }
it 'includes the existing commit as well as the truncated new commit summary' do
expect(summary_line).to start_with("<ul><li>#{old_commits.first.short_id} - 1 commit from branch <code>feature</code></li><li>#{old_commits.last.short_id}...#{new_commits[2].short_id} - 3 earlier commits")
end
end
end
context 'with multiple existing commits' do
let(:old_commits) { noteable.commits[3..] }
context 'with oldrev' do
let(:oldrev) { noteable.commits[2].id }
it 'includes a commit range and count' do
expect(summary_line)
.to start_with("<ul><li>#{Commit.truncate_sha(oldrev)}...#{old_commits.last.short_id} - 26 commits from branch <code>feature</code>")
end
context 'with new commits exceeding the display limit' do
let(:new_commits) { create_commits(13) }
it 'includes the existing commit as well as the truncated new commit summary' do
expect(summary_line)
.to start_with("<ul><li>#{Commit.truncate_sha(oldrev)}...#{old_commits.last.short_id} - 26 commits from branch <code>feature</code></li><li>#{old_commits.last.short_id}...#{new_commits[2].short_id} - 3 earlier commits")
end
end
end
context 'without oldrev' do
it 'includes a commit range and count' do
expect(summary_line)
.to start_with("<ul><li>#{old_commits[0].short_id}..#{old_commits[-1].short_id} - 26 commits from branch <code>feature</code>")
end
context 'with new commits exceeding the display limit' do
let(:new_commits) { create_commits(13) }
it 'includes the existing commit as well as the truncated new commit summary' do
expect(summary_line)
.to start_with("<ul><li>#{old_commits.first.short_id}..#{old_commits.last.short_id} - 26 commits from branch <code>feature</code></li><li>#{old_commits.last.short_id}...#{new_commits[2].short_id} - 3 earlier commits")
end
end
end
context 'on a fork' do
before do
expect(noteable).to receive(:for_fork?).and_return(true)
end
it 'includes the project namespace' do
expect(summary_line).to include("<code>#{noteable.target_project_namespace}:feature</code>")
end
end
end
end
end
end
describe '#tag_commit' do
let(:noteable) { project.commit }
let(:tag_name) { 'v1.2.3' }
subject { commit_service.tag_commit(tag_name) }
it_behaves_like 'a system note' do
let(:action) { 'tag' }
end
it 'sets the note text' do
link = "/#{project.full_path}/-/tags/#{tag_name}"
expect(subject.note).to eq "tagged commit #{noteable.sha} to [`#{tag_name}`](#{link})"
end
end
def create_commits(count)
Array.new(count) do |i|
double(title: "Test commit #{i}", short_id: "abcd00#{i}")
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class AlertManagementService < ::SystemNotes::BaseService
# Called when the a new AlertManagement::Alert has been created
#
# alert - AlertManagement::Alert object.
#
# Example Note text:
#
# "GitLab Alert Bot logged an alert from Prometheus"
#
# Returns the created Note object
def create_new_alert(monitoring_tool)
body = "logged an alert from **#{monitoring_tool}**"
create_note(NoteSummary.new(noteable, project, Users::Internal.alert_bot, body, action: 'new_alert_added'))
end
# Called when the status of an AlertManagement::Alert has changed
#
# alert - AlertManagement::Alert object.
#
# Example Note text:
#
# "changed the status to Acknowledged"
# "changed the status to Acknowledged by changing the incident status of #540"
#
# Returns the created Note object
def change_alert_status(reason)
status = noteable.state.to_s.titleize
body = "changed the status to **#{status}**#{reason}"
create_note(NoteSummary.new(noteable, project, author, body, action: 'status'))
end
# Called when an issue is created based on an AlertManagement::Alert
#
# issue - Issue object.
#
# Example Note text:
#
# "created incident #17 for this alert"
#
# Returns the created Note object
def new_alert_issue(issue)
body = "created incident #{issue.to_reference(project)} for this alert"
create_note(NoteSummary.new(noteable, project, author, body, action: 'alert_issue_added'))
end
# Called when an alert is resolved due to received resolving alert payload
#
# alert - AlertManagement::Alert object.
#
# Example Note text:
#
# "changed the status to Resolved by closing issue #17"
#
# Returns the created Note object
def log_resolving_alert(monitoring_tool)
body = "logged a recovery alert from **#{monitoring_tool}**"
create_note(NoteSummary.new(noteable, project, Users::Internal.alert_bot, body, action: 'new_alert_added'))
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::SystemNotes::AlertManagementService, feature_category: :groups_and_projects do
let_it_be(:author) { create(:user) }
let_it_be(:project) { create(:project, :repository) }
let_it_be(:noteable) { create(:alert_management_alert, :with_incident, :acknowledged, project: project) }
describe '#create_new_alert' do
subject { described_class.new(noteable: noteable, project: project).create_new_alert('Some Service') }
it_behaves_like 'a system note' do
let(:author) { Users::Internal.alert_bot }
let(:action) { 'new_alert_added' }
end
it 'has the appropriate message' do
expect(subject.note).to eq('logged an alert from **Some Service**')
end
end
describe '#change_alert_status' do
subject { described_class.new(noteable: noteable, project: project, author: author).change_alert_status(reason) }
context 'with no specified reason' do
let(:reason) { nil }
it_behaves_like 'a system note' do
let(:action) { 'status' }
end
it 'has the appropriate message' do
expect(subject.note).to eq("changed the status to **Acknowledged**")
end
end
context 'with reason provided' do
let(:reason) { ' by changing incident status' }
it 'has the appropriate message' do
expect(subject.note).to eq("changed the status to **Acknowledged** by changing incident status")
end
end
end
describe '#new_alert_issue' do
let_it_be(:issue) { noteable.issue }
subject { described_class.new(noteable: noteable, project: project, author: author).new_alert_issue(issue) }
it_behaves_like 'a system note' do
let(:action) { 'alert_issue_added' }
end
it 'has the appropriate message' do
expect(subject.note).to eq("created incident #{issue.to_reference(project)} for this alert")
end
end
describe '#log_resolving_alert' do
subject { described_class.new(noteable: noteable, project: project).log_resolving_alert('Some Service') }
it_behaves_like 'a system note' do
let(:author) { Users::Internal.alert_bot }
let(:action) { 'new_alert_added' }
end
it 'has the appropriate message' do
expect(subject.note).to eq('logged a recovery alert from **Some Service**')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class MergeRequestsService < ::SystemNotes::BaseService
# Called when 'merge when pipeline succeeds' is executed
def merge_when_pipeline_succeeds(sha)
body = "enabled an automatic merge when the pipeline for #{sha} succeeds"
create_note(NoteSummary.new(noteable, project, author, body, action: 'merge'))
end
# Called when 'merge when pipeline succeeds' is canceled
def cancel_merge_when_pipeline_succeeds
body = 'canceled the automatic merge'
create_note(NoteSummary.new(noteable, project, author, body, action: 'merge'))
end
# Called when 'merge when pipeline succeeds' is aborted
def abort_merge_when_pipeline_succeeds(reason)
body = "aborted the automatic merge because #{reason}"
##
# TODO: Abort message should be sent by the system, not a particular user.
# See https://gitlab.com/gitlab-org/gitlab-foss/issues/63187.
create_note(NoteSummary.new(noteable, project, author, body, action: 'merge'))
end
def handle_merge_request_draft
action = noteable.draft? ? "draft" : "ready"
body = "marked this merge request as **#{action}**"
create_note(NoteSummary.new(noteable, project, author, body, action: 'title'))
end
def add_merge_request_draft_from_commit(commit)
body = "marked this merge request as **draft** from #{commit.to_reference(project)}"
create_note(NoteSummary.new(noteable, project, author, body, action: 'title'))
end
def resolve_all_discussions
body = "resolved all threads"
create_note(NoteSummary.new(noteable, project, author, body, action: 'discussion'))
end
def discussion_continued_in_issue(discussion, issue)
body = "created #{issue.to_reference} to continue this discussion"
note_attributes = discussion.reply_attributes.merge(project: project, author: author, note: body)
Note.create(note_attributes.merge(system: true, created_at: issue.system_note_timestamp)).tap do |note|
note.system_note_metadata = SystemNoteMetadata.new(action: 'discussion')
end
end
def diff_discussion_outdated(discussion, change_position)
merge_request = discussion.noteable
diff_refs = change_position.diff_refs
version_index = merge_request.merge_request_diffs.viewable.count
position_on_text = change_position.on_text?
text_parts = ["changed this #{position_on_text ? 'line' : 'file'} in"]
if version_params = merge_request.version_params_for(diff_refs)
repository = project.repository
anchor = position_on_text ? change_position.line_code(repository) : change_position.file_hash
url = url_helpers.diffs_project_merge_request_path(project, merge_request, version_params.merge(anchor: anchor))
text_parts << "[version #{version_index} of the diff](#{url})"
else
text_parts << "version #{version_index} of the diff"
end
body = text_parts.join(' ')
note_attributes = discussion.reply_attributes.merge(project: project, author: author, note: body)
Note.create(note_attributes.merge(system: true)).tap do |note|
note.system_note_metadata = SystemNoteMetadata.new(action: 'outdated')
end
end
# Called when a branch in Noteable is changed
#
# branch_type - 'source' or 'target'
# event_type - the source of event: 'update' or 'delete'
# old_branch - old branch name
# new_branch - new branch name
# Example Note text is based on event_type:
#
# update: "changed target branch from `Old` to `New`"
# delete: "deleted the `Old` branch. This merge request now targets the `New` branch"
#
# Returns the created Note object
def change_branch(branch_type, event_type, old_branch, new_branch)
body =
case event_type.to_s
when 'delete'
"deleted the `#{old_branch}` branch. This merge request now targets the `#{new_branch}` branch"
when 'update'
"changed #{branch_type} branch from `#{old_branch}` to `#{new_branch}`"
else
raise ArgumentError, "invalid value for event_type: #{event_type}"
end
create_note(NoteSummary.new(noteable, project, author, body, action: 'branch'))
end
# Called when a branch in Noteable is added or deleted
#
# branch_type - :source or :target
# branch - branch name
# presence - :add or :delete
#
# Example Note text:
#
# "restored target branch `feature`"
#
# Returns the created Note object
def change_branch_presence(branch_type, branch, presence)
verb =
if presence == :add
'restored'
else
'deleted'
end
body = "#{verb} #{branch_type} branch `#{branch}`"
create_note(NoteSummary.new(noteable, project, author, body, action: 'branch'))
end
# Called when a branch is created from the 'new branch' button on a issue
# Example note text:
#
# "created branch `201-issue-branch-button`"
def new_issue_branch(branch, branch_project: nil)
branch_project ||= project
link = url_helpers.project_compare_path(branch_project, from: branch_project.default_branch, to: branch)
body = "created branch [`#{branch}`](#{link}) to address this issue"
create_note(NoteSummary.new(noteable, project, author, body, action: 'branch'))
end
def new_merge_request(merge_request)
body = "created merge request #{merge_request.to_reference(project)} to address this issue"
create_note(NoteSummary.new(noteable, project, author, body, action: 'merge'))
end
def picked_into_branch(branch_name, pick_commit)
link = url_helpers.project_tree_path(project, branch_name)
body = "picked the changes into the branch [`#{branch_name}`](#{link}) with commit #{pick_commit}"
summary = NoteSummary.new(noteable, project, author, body, action: 'cherry_pick')
summary.note[:commit_id] = pick_commit
create_note(summary)
end
# Called when the merge request is approved by user
#
# Example Note text:
#
# "approved this merge request"
#
# Returns the created Note object
def approve_mr
body = "approved this merge request"
create_note(NoteSummary.new(noteable, project, author, body, action: 'approved'))
end
def unapprove_mr
body = "unapproved this merge request"
create_note(NoteSummary.new(noteable, project, author, body, action: 'unapproved'))
end
end
end
SystemNotes::MergeRequestsService.prepend_mod_with('SystemNotes::MergeRequestsService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::SystemNotes::MergeRequestsService, feature_category: :code_review_workflow do
include Gitlab::Routing
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, :repository, group: group) }
let_it_be(:author) { create(:user) }
let(:noteable) { create(:merge_request, source_project: project, target_project: project) }
let(:service) { described_class.new(noteable: noteable, project: project, author: author) }
describe '.merge_when_pipeline_succeeds' do
let(:pipeline) { build(:ci_pipeline) }
subject { service.merge_when_pipeline_succeeds(pipeline.sha) }
it_behaves_like 'a system note' do
let(:action) { 'merge' }
end
it "posts the 'merge when pipeline succeeds' system note" do
expect(subject.note).to match(%r{enabled an automatic merge when the pipeline for (\w+/\w+@)?\h{40} succeeds})
end
end
describe '.cancel_merge_when_pipeline_succeeds' do
subject { service.cancel_merge_when_pipeline_succeeds }
it_behaves_like 'a system note' do
let(:action) { 'merge' }
end
it "posts the 'merge when pipeline succeeds' system note" do
expect(subject.note).to eq "canceled the automatic merge"
end
end
describe '.abort_merge_when_pipeline_succeeds' do
subject { service.abort_merge_when_pipeline_succeeds('merge request was closed') }
it_behaves_like 'a system note' do
let(:action) { 'merge' }
end
it "posts the 'merge when pipeline succeeds' system note" do
expect(subject.note).to eq "aborted the automatic merge because merge request was closed"
end
end
describe '.handle_merge_request_draft' do
context 'adding draft note' do
let(:noteable) { create(:merge_request, source_project: project, title: 'Draft: Lorem ipsum') }
subject { service.handle_merge_request_draft }
it_behaves_like 'a system note' do
let(:action) { 'title' }
end
it 'sets the note text' do
expect(subject.note).to eq 'marked this merge request as **draft**'
end
end
context 'removing draft note' do
subject { service.handle_merge_request_draft }
it_behaves_like 'a system note' do
let(:action) { 'title' }
end
it 'sets the note text' do
expect(subject.note).to eq 'marked this merge request as **ready**'
end
end
end
describe '.add_merge_request_draft_from_commit' do
subject { service.add_merge_request_draft_from_commit(noteable.diff_head_commit) }
it_behaves_like 'a system note' do
let(:action) { 'title' }
end
it "posts the 'marked this merge request as draft from commit' system note" do
expect(subject.note).to match(
/marked this merge request as \*\*draft\*\* from #{Commit.reference_pattern}/
)
end
end
describe '.resolve_all_discussions' do
subject { service.resolve_all_discussions }
it_behaves_like 'a system note' do
let(:action) { 'discussion' }
end
it 'sets the note text' do
expect(subject.note).to eq 'resolved all threads'
end
end
describe '.diff_discussion_outdated' do
let(:discussion) { create(:diff_note_on_merge_request, project: project).to_discussion }
let(:merge_request) { discussion.noteable }
let(:change_position) { discussion.position }
def reloaded_merge_request
MergeRequest.find(merge_request.id)
end
let(:service) { described_class.new(project: project, author: author) }
subject { service.diff_discussion_outdated(discussion, change_position) }
it_behaves_like 'a system note' do
let(:expected_noteable) { discussion.first_note.noteable }
let(:action) { 'outdated' }
end
context 'when the change_position is valid for the discussion' do
it 'creates a new note in the discussion' do
# we need to completely rebuild the merge request object, or the `@discussions` on the merge request are not reloaded.
expect { subject }.to change { reloaded_merge_request.discussions.first.notes.size }.by(1)
end
it 'links to the diff in the system note' do
diff_id = merge_request.merge_request_diff.id
line_code = change_position.line_code(project.repository)
link = diffs_project_merge_request_path(project, merge_request, diff_id: diff_id, anchor: line_code)
expect(subject.note).to eq("changed this line in [version 1 of the diff](#{link})")
end
context 'discussion is on an image' do
let(:discussion) { create(:image_diff_note_on_merge_request, project: project).to_discussion }
it 'links to the diff in the system note' do
diff_id = merge_request.merge_request_diff.id
file_hash = change_position.file_hash
link = diffs_project_merge_request_path(project, merge_request, diff_id: diff_id, anchor: file_hash)
expect(subject.note).to eq("changed this file in [version 1 of the diff](#{link})")
end
end
end
context 'when the change_position does not point to a valid version' do
before do
allow(merge_request).to receive(:version_params_for).and_return(nil)
end
it 'creates a new note in the discussion' do
# we need to completely rebuild the merge request object, or the `@discussions` on the merge request are not reloaded.
expect { subject }.to change { reloaded_merge_request.discussions.first.notes.size }.by(1)
end
it 'does not create a link' do
expect(subject.note).to eq('changed this line in version 1 of the diff')
end
end
end
describe '.change_branch' do
let(:old_branch) { 'old_branch' }
let(:new_branch) { 'new_branch' }
it_behaves_like 'a system note' do
let(:action) { 'branch' }
subject { service.change_branch('target', 'update', old_branch, new_branch) }
end
context 'when target branch name changed' do
context 'on update' do
subject { service.change_branch('target', 'update', old_branch, new_branch) }
it 'sets the note text' do
expect(subject.note).to eq "changed target branch from `#{old_branch}` to `#{new_branch}`"
end
end
context 'on delete' do
subject { service.change_branch('target', 'delete', old_branch, new_branch) }
it 'sets the note text' do
expect(subject.note).to eq "deleted the `#{old_branch}` branch. This merge request now targets the `#{new_branch}` branch"
end
end
context 'for invalid event_type' do
subject { service.change_branch('target', 'invalid', old_branch, new_branch) }
it 'raises exception' do
expect { subject }.to raise_error /invalid value for event_type/
end
end
end
end
describe '.change_branch_presence' do
subject { service.change_branch_presence(:source, 'feature', :delete) }
it_behaves_like 'a system note' do
let(:action) { 'branch' }
end
context 'when source branch deleted' do
it 'sets the note text' do
expect(subject.note).to eq "deleted source branch `feature`"
end
end
end
describe '.new_issue_branch' do
let(:branch) { '1-mepmep' }
subject { service.new_issue_branch(branch, branch_project: branch_project) }
shared_examples_for 'a system note for new issue branch' do
it_behaves_like 'a system note' do
let(:action) { 'branch' }
end
context 'when a branch is created from the new branch button' do
it 'sets the note text' do
expect(subject.note).to start_with("created branch [`#{branch}`]")
end
end
end
context 'branch_project is set' do
let(:branch_project) { create(:project, :repository) }
it_behaves_like 'a system note for new issue branch'
end
context 'branch_project is not set' do
let(:branch_project) { nil }
it_behaves_like 'a system note for new issue branch'
end
end
describe '.new_merge_request' do
subject { service.new_merge_request(merge_request) }
let!(:merge_request) { create(:merge_request, source_project: project, source_branch: generate(:branch), target_project: project) }
it_behaves_like 'a system note' do
let(:action) { 'merge' }
end
it 'sets the new merge request note text' do
expect(subject.note).to eq("created merge request #{merge_request.to_reference(project)} to address this issue")
end
end
describe '.picked_into_branch' do
let(:branch_name) { 'a-branch' }
let(:commit_sha) { project.commit.sha }
let(:merge_request) { noteable }
subject { service.picked_into_branch(branch_name, commit_sha) }
it_behaves_like 'a system note' do
let(:action) { 'cherry_pick' }
end
it "posts the 'picked merge request' system note" do
expect(subject.note).to eq("picked the changes into the branch [`#{branch_name}`](/#{project.full_path}/-/tree/#{branch_name}) with commit #{commit_sha}")
end
it 'links the merge request and the cherry-pick commit' do
expect(subject.noteable).to eq(merge_request)
expect(subject.commit_id).to eq(commit_sha)
end
end
describe '#approve_mr' do
subject { described_class.new(noteable: noteable, project: project, author: author).approve_mr }
it_behaves_like 'a system note' do
let(:action) { 'approved' }
end
context 'when merge request approved' do
it 'sets the note text' do
expect(subject.note).to eq "approved this merge request"
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class BaseService
attr_reader :noteable, :project, :author
def initialize(noteable: nil, author: nil, project: nil)
@noteable = noteable
@project = project
@author = author
end
protected
def create_note(note_summary)
note_params = note_summary.note.merge(system: true)
note_params[:system_note_metadata] = SystemNoteMetadata.new(note_summary.metadata) if note_summary.metadata?
Note.create(note_params)
end
def content_tag(...)
ActionController::Base.helpers.content_tag(...)
end
def url_helpers
@url_helpers ||= Gitlab::Routing.url_helpers
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe SystemNotes::BaseService, feature_category: :groups_and_projects do
let(:noteable) { double }
let(:project) { double }
let(:author) { double }
let(:base_service) { described_class.new(noteable: noteable, project: project, author: author) }
describe '#noteable' do
subject { base_service.noteable }
it { is_expected.to eq(noteable) }
it 'returns nil if no arguments are given' do
instance = described_class.new
expect(instance.noteable).to be_nil
end
end
describe '#project' do
subject { base_service.project }
it { is_expected.to eq(project) }
it 'returns nil if no arguments are given' do
instance = described_class.new
expect(instance.project).to be_nil
end
end
describe '#author' do
subject { base_service.author }
it { is_expected.to eq(author) }
it 'returns nil if no arguments are given' do
instance = described_class.new
expect(instance.author).to be_nil
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class TimeTrackingService < ::SystemNotes::BaseService
# Called when the start_date or due_date of an Issue/WorkItem is changed
#
# start_date - Start date being assigned, or nil
# due_date - Due date being assigned, or nil
#
# Example Note text:
#
# "removed due date"
#
# "changed due date to September 20, 2018"
# "changed start date to September 20, 2018 and changed due date to September 25, 2018"
#
# Returns the created Note object
def change_start_date_or_due_date(changed_dates = {})
return if changed_dates.empty?
# Using instance_of because WorkItem < Issue. We don't want to track work item updates as issue updates
if noteable.instance_of?(Issue) && changed_dates.key?('due_date')
issue_activity_counter.track_issue_due_date_changed_action(author: author, project: project)
end
work_item_activity_counter.track_work_item_date_changed_action(author: author) if noteable.is_a?(WorkItem)
create_note(
NoteSummary.new(noteable, project, author, changed_date_body(changed_dates), action: 'start_date_or_due_date')
)
end
# Called when the estimated time of a Noteable is changed
#
# time_estimate - Estimated time
#
# Example Note text:
#
# "removed time estimate"
#
# "changed time estimate to 3d 5h"
#
# Returns the created Note object
def change_time_estimate
parsed_time = Gitlab::TimeTrackingFormatter.output(noteable.time_estimate)
body = if noteable.time_estimate == 0
"removed time estimate"
else
"changed time estimate to #{parsed_time}"
end
if noteable.is_a?(Issue)
issue_activity_counter.track_issue_time_estimate_changed_action(author: author, project: project)
end
create_note(NoteSummary.new(noteable, project, author, body, action: 'time_tracking'))
end
# Called when the spent time of a Noteable is changed
#
# time_spent - Spent time
#
# Example Note text:
#
# "removed time spent"
#
# "added 2h 30m of time spent"
#
# Returns the created Note object
def change_time_spent
time_spent = noteable.time_spent
if time_spent == :reset
body = "removed time spent"
else
spent_at = noteable.spent_at&.to_date
parsed_time = Gitlab::TimeTrackingFormatter.output(time_spent.abs)
action = time_spent > 0 ? 'added' : 'subtracted'
text_parts = ["#{action} #{parsed_time} of time spent"]
text_parts << "at #{spent_at}" if spent_at && spent_at != DateTime.current.to_date
body = text_parts.join(' ')
end
if noteable.is_a?(Issue)
issue_activity_counter.track_issue_time_spent_changed_action(author: author, project: project)
end
create_note(NoteSummary.new(noteable, project, author, body, action: 'time_tracking'))
end
# Called when a timelog is added to an issuable
#
# timelog - Added timelog
#
# Example Note text:
#
# "subtracted 1h 15m of time spent"
#
# "added 2h 30m of time spent"
#
# Returns the created Note object
def created_timelog(timelog)
time_spent = timelog.time_spent
spent_at = timelog.spent_at&.to_date
parsed_time = Gitlab::TimeTrackingFormatter.output(time_spent.abs)
action = time_spent > 0 ? 'added' : 'subtracted'
text_parts = ["#{action} #{parsed_time} of time spent"]
text_parts << "at #{spent_at}" if spent_at && spent_at != DateTime.current.to_date
body = text_parts.join(' ')
if noteable.is_a?(Issue)
issue_activity_counter.track_issue_time_spent_changed_action(author: author, project: project)
end
create_note(NoteSummary.new(noteable, project, author, body, action: 'time_tracking'))
end
def remove_timelog(timelog)
time_spent = timelog.time_spent
spent_at = timelog.spent_at&.to_date
parsed_time = Gitlab::TimeTrackingFormatter.output(time_spent)
body = "deleted #{parsed_time} of spent time"
body += " from #{spent_at}" if spent_at
create_note(NoteSummary.new(noteable, project, author, body, action: 'time_tracking'))
end
private
def changed_date_body(changed_dates)
%w[start_date due_date].each_with_object([]) do |date_field, word_array|
next unless changed_dates.key?(date_field)
word_array << 'and' if word_array.any?
word_array << message_for_changed_date(changed_dates, date_field)
end.join(' ')
end
def message_for_changed_date(changed_dates, date_key)
changed_date = changed_dates[date_key].last
readable_date = date_key.humanize.downcase
if changed_date.nil?
"removed #{readable_date} #{changed_dates[date_key].first.to_fs(:long)}"
else
"changed #{readable_date} to #{changed_date.to_fs(:long)}"
end
end
def issue_activity_counter
Gitlab::UsageDataCounters::IssueActivityUniqueCounter
end
def work_item_activity_counter
Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::SystemNotes::TimeTrackingService, feature_category: :team_planning do
let_it_be(:author) { create(:user) }
let_it_be(:project) { create(:project, :repository) }
describe '#change_start_date_or_due_date' do
let_it_be(:issue) { create(:issue, project: project) }
let_it_be(:work_item) { create(:work_item, project: project) }
subject(:note) { described_class.new(noteable: noteable, project: project, author: author).change_start_date_or_due_date(changed_dates) }
let(:start_date) { Date.today }
let(:due_date) { 1.week.from_now.to_date }
let(:changed_dates) { { 'due_date' => [nil, due_date], 'start_date' => [nil, start_date] } }
shared_examples 'issuable getting date change notes' do
it_behaves_like 'a note with overridable created_at'
it_behaves_like 'a system note' do
let(:action) { 'start_date_or_due_date' }
end
context 'when both dates are added' do
it 'sets the correct note message' do
expect(note.note).to eq("changed start date to #{start_date.to_fs(:long)} and changed due date to #{due_date.to_fs(:long)}")
end
end
context 'when both dates are removed' do
let(:changed_dates) { { 'due_date' => [due_date, nil], 'start_date' => [start_date, nil] } }
before do
noteable.update!(start_date: start_date, due_date: due_date)
end
it 'sets the correct note message' do
expect(note.note).to eq("removed start date #{start_date.to_fs(:long)} and removed due date #{due_date.to_fs(:long)}")
end
end
context 'when due date is added' do
let(:changed_dates) { { 'due_date' => [nil, due_date] } }
it 'sets the correct note message' do
expect(note.note).to eq("changed due date to #{due_date.to_fs(:long)}")
end
context 'and start date removed' do
let(:changed_dates) { { 'due_date' => [nil, due_date], 'start_date' => [start_date, nil] } }
it 'sets the correct note message' do
expect(note.note).to eq("removed start date #{start_date.to_fs(:long)} and changed due date to #{due_date.to_fs(:long)}")
end
end
end
context 'when start_date is added' do
let(:changed_dates) { { 'start_date' => [nil, start_date] } }
it 'does not track the issue event' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_due_date_changed_action)
subject
end
it 'does not emit snowplow event', :snowplow do
expect_no_snowplow_event
subject
end
it 'sets the correct note message' do
expect(note.note).to eq("changed start date to #{start_date.to_fs(:long)}")
end
context 'and due date removed' do
let(:changed_dates) { { 'due_date' => [due_date, nil], 'start_date' => [nil, start_date] } }
it 'sets the correct note message' do
expect(note.note).to eq("changed start date to #{start_date.to_fs(:long)} and removed due date #{due_date.to_fs(:long)}")
end
end
end
context 'when no dates are changed' do
let(:changed_dates) { {} }
it 'does not create a note and returns nil' do
expect do
note
end.to not_change(Note, :count)
expect(note).to be_nil
end
end
end
context 'when noteable is an issue' do
let(:noteable) { issue }
let(:activity_counter_class) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter }
let(:activity_counter_method) { :track_issue_due_date_changed_action }
it_behaves_like 'issuable getting date change notes'
it 'does not track the work item event in usage ping' do
expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter).not_to receive(:track_work_item_date_changed_action)
subject
end
it 'tracks the issue event' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_due_date_changed_action)
.with(author: author, project: project)
subject
end
it_behaves_like 'internal event tracking' do
let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_DUE_DATE_CHANGED }
let(:user) { author }
let(:namespace) { project.namespace }
end
context 'when only start_date is added' do
let(:changed_dates) { { 'start_date' => [nil, start_date] } }
it 'does not track the issue event in usage ping' do
expect(activity_counter_class).not_to receive(activity_counter_method)
subject
end
end
end
context 'when noteable is a work item' do
let(:noteable) { work_item }
let(:activity_counter_class) { Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter }
let(:activity_counter_method) { :track_work_item_date_changed_action }
it_behaves_like 'issuable getting date change notes'
it 'does not track the issue event' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_due_date_changed_action)
subject
end
it 'does not emit snowplow event', :snowplow do
expect_no_snowplow_event
subject
end
context 'when only start_date is added' do
let(:changed_dates) { { 'start_date' => [nil, start_date] } }
it 'tracks the issue event in usage ping' do
expect(activity_counter_class).to receive(activity_counter_method).with(author: author)
subject
end
end
end
context 'when noteable is a merge request' do
let(:noteable) { create(:merge_request, source_project: project) }
it 'does not track the issue event' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_due_date_changed_action)
subject
end
it 'does not track the work item event in usage ping' do
expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter).not_to receive(:track_work_item_date_changed_action)
subject
end
it 'does not emit snowplow event', :snowplow do
expect_no_snowplow_event
subject
end
end
end
describe '#change_time_estimate' do
subject { described_class.new(noteable: noteable, project: project, author: author).change_time_estimate }
context 'when noteable is an issue' do
let_it_be(:noteable, reload: true) { create(:issue, project: project) }
it_behaves_like 'a system note' do
let(:action) { 'time_tracking' }
end
context 'with a time estimate' do
it 'sets the note text' do
noteable.update_attribute(:time_estimate, 277200)
expect(subject.note).to eq "changed time estimate to 1w 4d 5h"
end
context 'when time_tracking_limit_to_hours setting is true' do
before do
stub_application_setting(time_tracking_limit_to_hours: true)
end
it 'sets the note text' do
noteable.update_attribute(:time_estimate, 277200)
expect(subject.note).to eq "changed time estimate to 77h"
end
end
end
context 'without a time estimate' do
it 'sets the note text' do
expect(subject.note).to eq "removed time estimate"
end
end
it 'tracks the issue event in usage ping' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_time_estimate_changed_action)
.with(author: author, project: project)
subject
end
it_behaves_like 'internal event tracking' do
let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_TIME_ESTIMATE_CHANGED }
let(:user) { author }
let(:namespace) { project.namespace }
end
end
context 'when noteable is a merge request' do
let_it_be(:noteable) { create(:merge_request, source_project: project) }
it 'does not track the issue event' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_time_estimate_changed_action)
.with(author: author, project: project)
subject
end
it 'does not emit snowplow event', :snowplow do
expect_no_snowplow_event
subject
end
end
end
describe '#create_timelog' do
subject { described_class.new(noteable: noteable, project: project, author: author).created_timelog(timelog) }
context 'when the timelog has a positive time spent value' do
let_it_be(:noteable, reload: true) { create(:issue, project: project) }
let(:timelog) { create(:timelog, user: author, issue: noteable, time_spent: 1800, spent_at: '2022-03-30T00:00:00.000Z') }
it 'sets the note text' do
expect(subject.note).to eq "added 30m of time spent at 2022-03-30"
end
end
context 'when the timelog has a negative time spent value' do
let_it_be(:noteable, reload: true) { create(:issue, project: project) }
let(:timelog) { create(:timelog, user: author, issue: noteable, time_spent: -1800, spent_at: '2022-03-30T00:00:00.000Z') }
it 'sets the note text' do
expect(subject.note).to eq "subtracted 30m of time spent at 2022-03-30"
end
end
end
describe '#remove_timelog' do
subject { described_class.new(noteable: noteable, project: project, author: author).remove_timelog(timelog) }
context 'when the timelog has a positive time spent value' do
let_it_be(:noteable, reload: true) { create(:issue, project: project) }
let(:timelog) { create(:timelog, user: author, issue: noteable, time_spent: 1800, spent_at: '2022-03-30T00:00:00.000Z') }
it 'sets the note text' do
expect(subject.note).to eq "deleted 30m of spent time from 2022-03-30"
end
end
context 'when the timelog has a negative time spent value' do
let_it_be(:noteable, reload: true) { create(:issue, project: project) }
let(:timelog) { create(:timelog, user: author, issue: noteable, time_spent: -1800, spent_at: '2022-03-30T00:00:00.000Z') }
it 'sets the note text' do
expect(subject.note).to eq "deleted -30m of spent time from 2022-03-30"
end
end
end
describe '#change_time_spent' do
subject { described_class.new(noteable: noteable, project: project, author: author).change_time_spent }
context 'when noteable is an issue' do
let_it_be(:noteable, reload: true) { create(:issue, project: project) }
it_behaves_like 'a system note' do
let(:action) { 'time_tracking' }
before do
spend_time!(277200)
end
end
context 'when time was added' do
it 'sets the note text' do
spend_time!(277200)
expect(subject.note).to eq "added 1w 4d 5h of time spent"
end
context 'when time was subtracted' do
it 'sets the note text' do
spend_time!(360000)
spend_time!(-277200)
expect(subject.note).to eq "subtracted 1w 4d 5h of time spent"
end
end
context 'when time was removed' do
it 'sets the note text' do
spend_time!(:reset)
expect(subject.note).to eq "removed time spent"
end
end
context 'when time_tracking_limit_to_hours setting is true' do
before do
stub_application_setting(time_tracking_limit_to_hours: true)
end
it 'sets the note text' do
spend_time!(277200)
expect(subject.note).to eq "added 77h of time spent"
end
end
it 'tracks the issue event' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_time_spent_changed_action)
.with(author: author, project: project)
spend_time!(277200)
subject
end
it_behaves_like 'internal event tracking' do
let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_TIME_SPENT_CHANGED }
let(:user) { author }
let(:namespace) { project.namespace }
end
end
context 'when noteable is a merge request' do
let_it_be(:noteable) { create(:merge_request, source_project: project) }
it 'does not track the issue event' do
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_time_estimate_changed_action)
.with(author: author, project: project)
spend_time!(277200)
subject
end
it 'does not emit snowplow event', :snowplow do
expect_no_snowplow_event
subject
end
end
def spend_time!(seconds)
noteable.spend_time(duration: seconds, user_id: author.id)
noteable.save!
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class ZoomService < ::SystemNotes::BaseService
def zoom_link_added
create_note(NoteSummary.new(noteable, project, author, _('added a Zoom call to this issue'), action: 'pinned_embed'))
end
def zoom_link_removed
create_note(NoteSummary.new(noteable, project, author, _('removed a Zoom call from this issue'), action: 'pinned_embed'))
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::SystemNotes::ZoomService, feature_category: :integrations do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:author) { create(:user) }
let(:noteable) { create(:issue, project: project) }
let(:service) { described_class.new(noteable: noteable, project: project, author: author) }
describe '#zoom_link_added' do
subject { service.zoom_link_added }
it_behaves_like 'a system note' do
let(:action) { 'pinned_embed' }
end
it 'sets the zoom link added note text' do
expect(subject.note).to eq('added a Zoom call to this issue')
end
end
describe '#zoom_link_removed' do
subject { service.zoom_link_removed }
it_behaves_like 'a system note' do
let(:action) { 'pinned_embed' }
end
it 'sets the zoom link removed note text' do
expect(subject.note).to eq('removed a Zoom call from this issue')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module SystemNotes
class IncidentService < ::SystemNotes::BaseService
# Called when the severity of an Incident has changed
#
# Example Note text:
#
# "changed the severity to Medium - S3"
#
# Returns the created Note object
def change_incident_severity
severity = noteable.severity
if severity_label = IssuableSeverity::SEVERITY_LABELS[severity.to_sym]
body = "changed the severity to **#{severity_label}**"
create_note(NoteSummary.new(noteable, project, author, body, action: 'severity'))
else
Gitlab::AppLogger.error(
message: 'Cannot create a system note for severity change',
noteable_class: noteable.class.to_s,
noteable_id: noteable.id,
severity: severity
)
end
end
# Called when the status of an IncidentManagement::IssuableEscalationStatus has changed
#
# reason - String.
#
# Example Note text:
#
# "changed the incident status to Acknowledged"
# "changed the incident status to Acknowledged by changing the status of ^alert#540"
#
# Returns the created Note object
def change_incident_status(reason)
status = noteable.escalation_status.status_name.to_s.titleize
body = "changed the incident status to **#{status}**#{reason}"
create_note(NoteSummary.new(noteable, project, author, body, action: 'status'))
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::SystemNotes::IncidentService, feature_category: :incident_management do
let_it_be(:author) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:noteable) { create(:incident, project: project) }
let_it_be(:issuable_severity) { create(:issuable_severity, issue: noteable, severity: :medium) }
describe '#change_incident_severity' do
subject(:change_severity) { described_class.new(noteable: noteable, project: project, author: author).change_incident_severity }
before do
allow(Gitlab::AppLogger).to receive(:error).and_call_original
end
it_behaves_like 'a system note' do
let(:action) { 'severity' }
end
IssuableSeverity.severities.keys.each do |severity|
context "with #{severity} severity" do
before do
issuable_severity.update!(severity: severity)
end
it 'has the appropriate message' do
severity_label = IssuableSeverity::SEVERITY_LABELS.fetch(severity.to_sym)
expect(change_severity.note).to eq("changed the severity to **#{severity_label}**")
end
end
end
context 'when severity is invalid' do
let(:invalid_severity) { 'invalid-severity' }
before do
allow(noteable).to receive(:severity).and_return(invalid_severity)
end
it 'does not create system note' do
expect { change_severity }.not_to change { noteable.notes.count }
end
it 'writes error to logs' do
change_severity
expect(Gitlab::AppLogger).to have_received(:error).with(
message: 'Cannot create a system note for severity change',
noteable_class: noteable.class.to_s,
noteable_id: noteable.id,
severity: invalid_severity
)
end
end
end
describe '#change_incident_status' do
let_it_be(:escalation_status) { create(:incident_management_issuable_escalation_status, issue: noteable) }
let(:service) { described_class.new(noteable: noteable, project: project, author: author) }
context 'with a provided reason' do
subject(:change_incident_status) { service.change_incident_status(' by changing the alert status') }
it 'creates a new note for an incident status change', :aggregate_failures do
expect { change_incident_status }.to change { noteable.notes.count }.by(1)
expect(noteable.notes.last.note).to eq("changed the incident status to **Triggered** by changing the alert status")
end
end
context 'without provided reason' do
subject(:change_incident_status) { service.change_incident_status(nil) }
it 'creates a new note for an incident status change', :aggregate_failures do
expect { change_incident_status }.to change { noteable.notes.count }.by(1)
expect(noteable.notes.last.note).to eq("changed the incident status to **Triggered**")
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Organizations
class UpdateService < ::Organizations::BaseService
attr_reader :organization
def initialize(organization, current_user:, params: {})
@organization = organization
@current_user = current_user
@params = params.dup
return unless @params.key?(:description)
organization_detail_attributes = { description: @params.delete(:description) }
# TODO: Remove explicit passing of id once https://github.com/rails/rails/issues/48714 is resolved.
organization_detail_attributes[:id] = organization.id
@params[:organization_detail_attributes] ||= {}
@params[:organization_detail_attributes].merge!(organization_detail_attributes)
end
def execute
return error_no_permissions unless allowed?
if organization.update(params)
ServiceResponse.success(payload: organization)
else
error_updating
end
end
private
def allowed?
current_user&.can?(:admin_organization, organization)
end
def error_no_permissions
ServiceResponse.error(message: [_('You have insufficient permissions to update the organization')])
end
def error_updating
message = organization.errors.full_messages || _('Failed to update organization')
ServiceResponse.error(payload: organization, message: Array(message))
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Organizations::UpdateService, feature_category: :cell do
describe '#execute' do
let_it_be(:user) { create(:user) }
let_it_be_with_reload(:organization) { create(:organization) }
let(:current_user) { user }
let(:name) { 'Name' }
let(:path) { 'path' }
let(:description) { nil }
let(:params) { { name: name, path: path } }
subject(:response) do
described_class.new(organization, current_user: current_user, params: params).execute
end
context 'when user does not have permission' do
let(:current_user) { nil }
it 'returns an error' do
expect(response).to be_error
expect(response.message).to match_array(['You have insufficient permissions to update the organization'])
end
end
context 'when user has permission' do
before do
create(:organization_user, organization: organization, user: current_user)
end
shared_examples 'updating an organization' do
it 'updates the organization' do
response
organization.reset
expect(response).to be_success
expect(organization.name).to eq(name)
expect(organization.path).to eq(path)
expect(organization.description).to eq(description)
end
end
context 'with description' do
let(:description) { 'Organization description' }
let(:params) do
{
name: name,
path: path,
description: description
}
end
it_behaves_like 'updating an organization'
end
include_examples 'updating an organization'
it 'returns an error when the organization is not updated' do
params[:name] = nil
expect(response).to be_error
expect(response.message).to match_array(["Name can't be blank"])
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Organizations
class CreateService < ::Organizations::BaseService
def execute
return error_no_permissions unless current_user&.can?(:create_organization)
organization = Organization.create(params)
return error_creating(organization) unless organization.persisted?
ServiceResponse.success(payload: organization)
end
private
def error_no_permissions
ServiceResponse.error(message: [_('You have insufficient permissions to create organizations')])
end
def error_creating(organization)
message = organization.errors.full_messages || _('Failed to create organization')
ServiceResponse.error(message: Array(message))
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Organizations::CreateService, feature_category: :cell do
describe '#execute' do
let_it_be(:user) { create(:user) }
let(:current_user) { user }
let(:params) { attributes_for(:organization) }
subject(:response) { described_class.new(current_user: current_user, params: params).execute }
context 'when user does not have permission' do
let(:current_user) { nil }
it 'returns an error' do
expect(response).to be_error
expect(response.message).to match_array(
['You have insufficient permissions to create organizations'])
end
end
context 'when user has permission' do
it 'creates an organization' do
expect { response }.to change { Organizations::Organization.count }
expect(response).to be_success
end
it 'returns an error when the organization is not persisted' do
params[:name] = nil
expect(response).to be_error
expect(response.message).to match_array(["Name can't be blank"])
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Terraform
class RemoteStateHandler < BaseService
include Gitlab::OptimisticLocking
StateLockedError = Class.new(StandardError)
StateDeletedError = Class.new(StandardError)
UnauthorizedError = Class.new(StandardError)
def find_with_lock
retrieve_with_lock(find_only: true) do |state|
yield state if block_given?
end
end
def handle_with_lock
raise UnauthorizedError unless can_modify_state?
retrieve_with_lock do |state|
raise StateLockedError unless lock_matches?(state)
yield state if block_given?
state.save! unless state.destroyed?
end
nil
end
def lock!
raise ArgumentError if params[:lock_id].blank?
raise UnauthorizedError unless can_modify_state?
retrieve_with_lock do |state|
raise StateLockedError if state.locked?
state.lock_xid = params[:lock_id]
state.locked_by_user = current_user
state.locked_at = Time.current
state.save!
end
end
def unlock!
raise UnauthorizedError unless can_modify_state?
retrieve_with_lock do |state|
# force-unlock does not pass ID, so we ignore it if it is missing
raise StateLockedError unless params[:lock_id].nil? || lock_matches?(state)
state.lock_xid = nil
state.locked_by_user = nil
state.locked_at = nil
state.save!
end
end
private
def retrieve_with_lock(find_only: false)
create_or_find!(find_only: find_only).tap do |state|
retry_lock(state, name: "Terraform state: #{state.id}") { yield state }
end
end
def create_or_find!(find_only:)
raise ArgumentError unless params[:name].present?
find_params = { project: project, name: params[:name] }
state = if find_only
find_state!(find_params)
else
Terraform::State.safe_find_or_create_by(find_params)
end
raise StateDeletedError if state.deleted_at?
state
end
def lock_matches?(state)
return true if state.lock_xid.nil? && params[:lock_id].nil?
ActiveSupport::SecurityUtils
.secure_compare(state.lock_xid.to_s, params[:lock_id].to_s)
end
def can_modify_state?
current_user.can?(:admin_terraform_state, project)
end
def find_state(find_params)
Terraform::State.find_by(find_params) # rubocop: disable CodeReuse/ActiveRecord
end
def find_state!(find_params)
find_state(find_params) || raise(ActiveRecord::RecordNotFound, "Couldn't find state")
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Terraform::RemoteStateHandler, feature_category: :infrastructure_as_code do
let_it_be(:project) { create(:project) }
let_it_be(:developer) { create(:user, developer_projects: [project]) }
let_it_be(:maintainer) { create(:user, maintainer_projects: [project]) }
let_it_be(:user) { maintainer }
describe '#find_with_lock' do
context 'without a state name' do
subject { described_class.new(project, user) }
it 'raises an exception' do
expect { subject.find_with_lock }.to raise_error(ArgumentError)
end
end
context 'with a state name' do
subject { described_class.new(project, user, name: 'state') }
context 'with no matching state' do
it 'raises an exception' do
expect { subject.find_with_lock }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context 'with a matching state' do
let!(:state) { create(:terraform_state, project: project, name: 'state') }
it 'returns the state' do
expect(subject.find_with_lock).to eq(state)
end
context 'with a state scheduled for deletion' do
let!(:state) { create(:terraform_state, :deletion_in_progress, project: project, name: 'state') }
it 'raises an exception' do
expect { subject.find_with_lock }.to raise_error(described_class::StateDeletedError)
end
end
end
end
end
context 'when state locking is not being used' do
subject { described_class.new(project, user, name: 'my-state') }
describe '#handle_with_lock' do
it 'allows to modify a state using database locking' do
record = nil
subject.handle_with_lock do |state|
record = state
state.name = 'updated-name'
end
expect(record.reload.name).to eq 'updated-name'
end
it 'returns nil' do
expect(subject.handle_with_lock).to be_nil
end
end
describe '#lock!' do
it 'raises an error' do
expect { subject.lock! }.to raise_error(ArgumentError)
end
end
end
context 'when using locking' do
describe '#handle_with_lock' do
subject(:handler) { described_class.new(project, user, name: 'new-state', lock_id: 'abc-abc') }
it 'handles a locked state using exclusive read lock' do
handler.lock!
record = nil
handler.handle_with_lock do |state|
record = state
state.name = 'new-name'
end
expect(record.reload.name).to eq 'new-name'
expect(record.reload.project).to eq project
end
it 'raises exception if lock has not been acquired before' do
expect { handler.handle_with_lock }
.to raise_error(described_class::StateLockedError)
end
it 'raises an exception if the state is scheduled for deletion' do
create(:terraform_state, :deletion_in_progress, project: project, name: 'new-state')
expect { handler.handle_with_lock }
.to raise_error(described_class::StateDeletedError)
end
context 'user does not have permission to modify state' do
let(:user) { developer }
it 'raises an exception' do
expect { handler.handle_with_lock }
.to raise_error(described_class::UnauthorizedError)
end
end
end
describe '#lock!' do
let(:lock_id) { 'abc-abc' }
subject(:handler) do
described_class.new(
project,
user,
name: 'new-state',
lock_id: lock_id
)
end
it 'allows to lock state if it does not exist yet' do
state = handler.lock!
expect(state).to be_persisted
expect(state.name).to eq 'new-state'
end
it 'allows to lock state if it exists and is not locked' do
state = create(:terraform_state, project: project, name: 'new-state')
handler.lock!
expect(state.reload.lock_xid).to eq lock_id
expect(state).to be_locked
end
it 'raises an exception when trying to unlocked state locked by someone else' do
described_class.new(project, user, name: 'new-state', lock_id: '12a-23f').lock!
expect { handler.lock! }.to raise_error(described_class::StateLockedError)
end
it 'raises an exception when the state exists and is scheduled for deletion' do
create(:terraform_state, :deletion_in_progress, project: project, name: 'new-state')
expect { handler.lock! }.to raise_error(described_class::StateDeletedError)
end
end
describe '#unlock!' do
let_it_be(:state) { create(:terraform_state, :locked, project: project, name: 'new-state', lock_xid: 'abc-abc') }
let(:lock_id) { state.lock_xid }
subject(:handler) do
described_class.new(
project,
user,
name: state.name,
lock_id: lock_id
)
end
it 'unlocks the state' do
state = handler.unlock!
expect(state.lock_xid).to be_nil
end
context 'with no lock ID (force-unlock)' do
let(:lock_id) {}
it 'unlocks the state' do
state = handler.unlock!
expect(state.lock_xid).to be_nil
end
end
context 'with different lock ID' do
let(:lock_id) { 'other' }
it 'raises an exception' do
expect { handler.unlock! }
.to raise_error(described_class::StateLockedError)
end
end
context 'with a state scheduled for deletion' do
it 'raises an exception' do
state.update!(deleted_at: Time.current)
expect { handler.unlock! }
.to raise_error(described_class::StateDeletedError)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Terraform
module States
class TriggerDestroyService
def initialize(state, current_user:)
@state = state
@current_user = current_user
end
def execute
return unauthorized_response unless can_destroy_state?
return state_locked_response if state.locked?
state.run_after_commit do
Terraform::States::DestroyWorker.perform_async(id)
end
state.update!(deleted_at: Time.current)
ServiceResponse.success
end
private
attr_reader :state, :current_user
def can_destroy_state?
current_user.can?(:admin_terraform_state, state.project)
end
def unauthorized_response
error_response(s_('Terraform|You have insufficient permissions to delete this state'))
end
def state_locked_response
error_response(s_('Terraform|Cannot remove a locked state'))
end
def error_response(message)
ServiceResponse.error(message: message)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Terraform::States::TriggerDestroyService, feature_category: :infrastructure_as_code do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user, maintainer_projects: [project]) }
describe '#execute', :aggregate_failures do
let_it_be(:state) { create(:terraform_state, project: project) }
let(:service) { described_class.new(state, current_user: user) }
subject { service.execute }
it 'marks the state as deleted and schedules a cleanup worker' do
expect(Terraform::States::DestroyWorker).to receive(:perform_async).with(state.id).once
expect(subject).to be_success
expect(state.deleted_at).to be_like_time(Time.current)
end
context 'within a database transaction' do
subject { state.with_lock { service.execute } }
it 'does not raise an EnqueueFromTransactionError' do
expect { subject }.not_to raise_error
expect(state.deleted_at).to be_like_time(Time.current)
end
end
shared_examples 'unable to delete state' do
it 'does not modify the state' do
expect(Terraform::States::DestroyWorker).not_to receive(:perform_async)
expect { subject }.not_to change(state, :deleted_at)
expect(subject).to be_error
expect(subject.message).to eq(message)
end
end
context 'user does not have permission' do
let(:user) { create(:user, developer_projects: [project]) }
let(:message) { 'You have insufficient permissions to delete this state' }
include_examples 'unable to delete state'
end
context 'state is locked' do
let(:state) { create(:terraform_state, :locked, project: project) }
let(:message) { 'Cannot remove a locked state' }
include_examples 'unable to delete state'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Terraform
module States
class DestroyService
def initialize(state)
@state = state
end
def execute
return unless state.deleted_at?
state.versions.each_batch(column: :version) do |batch|
process_batch(batch)
end
state.destroy!
end
private
attr_reader :state
# Overridden in EE
def process_batch(batch)
batch.each do |version|
version.file.remove!
end
end
end
end
end
Terraform::States::DestroyService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Terraform::States::DestroyService, feature_category: :infrastructure_as_code do
let_it_be(:state) { create(:terraform_state, :with_version, :deletion_in_progress) }
let(:file) { instance_double(Terraform::StateUploader, relative_path: 'path') }
before do
allow_next_found_instance_of(Terraform::StateVersion) do |version|
allow(version).to receive(:file).and_return(file)
end
end
describe '#execute' do
subject { described_class.new(state).execute }
it 'removes version files from object storage, followed by the state record' do
expect(file).to receive(:remove!).once
expect(state).to receive(:destroy!)
subject
end
context 'state is not marked for deletion' do
let(:state) { create(:terraform_state) }
it 'does not delete the state' do
expect(state).not_to receive(:destroy!)
subject
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
class UpdateRepositoryStorageService
include UpdateRepositoryStorageMethods
delegate :snippet, to: :repository_storage_move
private
def track_repository(destination_storage_name)
snippet.track_snippet_repository(destination_storage_name)
end
def mirror_repositories
return unless snippet.repository_exists?
mirror_repository(type: Gitlab::GlRepository::SNIPPET)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::UpdateRepositoryStorageService, feature_category: :source_code_management do
subject { described_class.new(repository_storage_move) }
describe "#execute" do
let_it_be_with_reload(:snippet) { create(:snippet, :repository) }
let_it_be(:destination) { 'test_second_storage' }
let_it_be(:checksum) { snippet.repository.checksum }
let(:repository_storage_move_state) { :scheduled }
let(:repository_storage_move) { create(:snippet_repository_storage_move, repository_storage_move_state, container: snippet, destination_storage_name: destination) }
let(:snippet_repository_double) { double(:repository) }
let(:original_snippet_repository_double) { double(:repository) }
before do
allow(Gitlab.config.repositories.storages).to receive(:keys).and_return(%w[default test_second_storage])
allow(Gitlab::GitalyClient).to receive(:filesystem_id).with('default').and_call_original
allow(Gitlab::GitalyClient).to receive(:filesystem_id).with(destination).and_return(SecureRandom.uuid)
allow(Gitlab::Git::Repository).to receive(:new).and_call_original
allow(Gitlab::Git::Repository).to receive(:new)
.with(destination, snippet.repository.raw.relative_path, snippet.repository.gl_repository, snippet.repository.full_path)
.and_return(snippet_repository_double)
allow(Gitlab::Git::Repository).to receive(:new)
.with('default', snippet.repository.raw.relative_path, nil, nil)
.and_return(original_snippet_repository_double)
end
context 'when the move succeeds' do
it 'moves the repository to the new storage and unmarks the repository as read-only' do
expect(snippet_repository_double).to receive(:replicate)
.with(snippet.repository.raw)
expect(snippet_repository_double).to receive(:checksum)
.and_return(checksum)
expect(original_snippet_repository_double).to receive(:remove)
result = subject.execute
snippet.reload
expect(result).to be_success
expect(snippet).not_to be_repository_read_only
expect(snippet.repository_storage).to eq(destination)
expect(snippet.snippet_repository.shard_name).to eq(destination)
expect(repository_storage_move.reload).to be_finished
expect(repository_storage_move.error_message).to be_nil
end
end
context 'when the filesystems are the same' do
before do
expect(Gitlab::GitalyClient).to receive(:filesystem_id).twice.and_return(SecureRandom.uuid)
end
it 'updates the database without trying to move the repostory', :aggregate_failures do
result = subject.execute
snippet.reload
expect(result).to be_success
expect(snippet).not_to be_repository_read_only
expect(snippet.repository_storage).to eq(destination)
expect(snippet.snippet_repository.shard_name).to eq(destination)
end
end
context 'when the move fails' do
it 'unmarks the repository as read-only without updating the repository storage' do
expect(snippet_repository_double).to receive(:replicate)
.with(snippet.repository.raw)
.and_raise(Gitlab::Git::CommandError, 'Boom')
expect(snippet_repository_double).to receive(:remove)
expect do
subject.execute
end.to raise_error(Gitlab::Git::CommandError)
expect(snippet).not_to be_repository_read_only
expect(snippet.repository_storage).to eq('default')
expect(repository_storage_move).to be_failed
expect(repository_storage_move.error_message).to eq('Boom')
end
end
context 'when the cleanup fails' do
it 'sets the correct state' do
expect(snippet_repository_double).to receive(:replicate)
.with(snippet.repository.raw)
expect(snippet_repository_double).to receive(:checksum)
.and_return(checksum)
expect(original_snippet_repository_double).to receive(:remove)
.and_raise(Gitlab::Git::CommandError)
expect do
subject.execute
end.to raise_error(Gitlab::Git::CommandError)
expect(repository_storage_move).to be_cleanup_failed
end
end
context 'when the checksum does not match' do
it 'unmarks the repository as read-only without updating the repository storage' do
expect(snippet_repository_double).to receive(:replicate)
.with(snippet.repository.raw)
expect(snippet_repository_double).to receive(:checksum)
.and_return('not matching checksum')
expect(snippet_repository_double).to receive(:remove)
expect do
subject.execute
end.to raise_error(Repositories::ReplicateService::Error, /Failed to verify snippet repository checksum from \w+ to not matching checksum/)
expect(snippet).not_to be_repository_read_only
expect(snippet.repository_storage).to eq('default')
end
end
context 'when the repository move is finished' do
let(:repository_storage_move_state) { :finished }
it 'is idempotent' do
expect do
result = subject.execute
expect(result).to be_success
end.not_to change(repository_storage_move, :state)
end
end
context 'when the repository move is failed' do
let(:repository_storage_move_state) { :failed }
it 'is idempotent' do
expect do
result = subject.execute
expect(result).to be_success
end.not_to change(repository_storage_move, :state)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
class RepositoryValidationService
attr_reader :current_user, :snippet, :repository
RepositoryValidationError = Class.new(StandardError)
def initialize(user, snippet)
@current_user = user
@snippet = snippet
@repository = snippet.repository
end
def execute
if snippet.nil?
return service_response_error('No snippet found.', 404)
end
check_branch_count!
check_branch_name_default!
check_tag_count!
check_file_count!
check_size!
ServiceResponse.success(message: 'Valid snippet repository.')
rescue RepositoryValidationError => e
ServiceResponse.error(message: "Error: #{e.message}", http_status: 400)
end
private
def check_branch_count!
return if repository.branch_count == 1
raise RepositoryValidationError, _('Repository has more than one branch.')
end
def check_branch_name_default!
branches = repository.branch_names
return if branches.first == snippet.default_branch
raise RepositoryValidationError, _('Repository has an invalid default branch name.')
end
def check_tag_count!
return if repository.tag_count == 0
raise RepositoryValidationError, _('Repository has tags.')
end
def check_file_count!
file_count = repository.ls_files(snippet.default_branch).size
limit = Snippet.max_file_limit
if file_count > limit
raise RepositoryValidationError, _('Repository files count over the limit')
end
if file_count == 0
raise RepositoryValidationError, _('Repository must contain at least 1 file.')
end
end
def check_size!
return unless snippet.repository_size_checker.above_size_limit?
raise RepositoryValidationError, _('Repository size is above the limit.')
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::RepositoryValidationService, feature_category: :source_code_management do
describe '#execute' do
let_it_be(:user) { create(:user) }
let_it_be(:snippet) { create(:personal_snippet, :empty_repo, author: user) }
let(:repository) { snippet.repository }
let(:service) { described_class.new(user, snippet) }
subject { service.execute }
before do
allow(repository).to receive(:branch_count).and_return(1)
allow(repository).to receive(:ls_files).and_return(['foo'])
allow(repository).to receive(:branch_names).and_return(['master'])
end
it 'returns error when the repository has more than one branch' do
allow(repository).to receive(:branch_count).and_return(2)
expect(subject).to be_error
expect(subject.message).to match /Repository has more than one branch/
end
it 'returns error when existing branch name is not the default one' do
allow(repository).to receive(:branch_names).and_return(['foo'])
expect(subject).to be_error
expect(subject.message).to match /Repository has an invalid default branch name/
end
it 'returns error when the repository has tags' do
allow(repository).to receive(:tag_count).and_return(1)
expect(subject).to be_error
expect(subject.message).to match /Repository has tags/
end
it 'returns error when the repository has more file than the limit' do
limit = Snippet.max_file_limit + 1
files = Array.new(limit) { FFaker::Filesystem.file_name }
allow(repository).to receive(:ls_files).and_return(files)
expect(subject).to be_error
expect(subject.message).to match /Repository files count over the limit/
end
it 'returns error when the repository has no files' do
allow(repository).to receive(:ls_files).and_return([])
expect(subject).to be_error
expect(subject.message).to match /Repository must contain at least 1 file/
end
it 'returns error when the repository size is over the limit' do
expect_next_instance_of(Gitlab::RepositorySizeChecker) do |checker|
expect(checker).to receive(:above_size_limit?).and_return(true)
end
expect(subject).to be_error
expect(subject.message).to match /Repository size is above the limit/
end
it 'returns success when no validation errors are raised' do
expect(subject).to be_success
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
# Tries to schedule a move for every snippet with repositories on the source shard
class ScheduleBulkRepositoryShardMovesService
include ScheduleBulkRepositoryShardMovesMethods
extend ::Gitlab::Utils::Override
private
override :repository_klass
def repository_klass
SnippetRepository
end
override :container_klass
def container_klass
Snippet
end
override :container_column
def container_column
:snippet_id
end
override :schedule_bulk_worker_klass
def self.schedule_bulk_worker_klass
::Snippets::ScheduleBulkRepositoryShardMovesWorker
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::ScheduleBulkRepositoryShardMovesService, feature_category: :source_code_management do
it_behaves_like 'moves repository shard in bulk' do
let_it_be_with_reload(:container) { create(:snippet, :repository) }
let(:move_service_klass) { Snippets::RepositoryStorageMove }
let(:bulk_worker_klass) { ::Snippets::ScheduleBulkRepositoryShardMovesWorker }
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
class DestroyService
include Gitlab::Allowable
attr_reader :current_user, :snippet
DestroyError = Class.new(StandardError)
def initialize(user, snippet)
@current_user = user
@snippet = snippet
end
def execute
if snippet.nil?
return service_response_error('No snippet found.', 404)
end
unless user_can_delete_snippet?
return service_response_error(
"You don't have access to delete this snippet.",
403
)
end
attempt_destroy!
ServiceResponse.success(message: 'Snippet was deleted.')
rescue DestroyError
service_response_error('Failed to remove snippet repository.', 400)
rescue StandardError
service_response_error('Failed to remove snippet.', 400)
end
private
def attempt_destroy!
result = Repositories::DestroyService.new(snippet.repository).execute
raise DestroyError if result[:status] == :error
snippet.destroy!
end
def user_can_delete_snippet?
can?(current_user, :admin_snippet, snippet)
end
def service_response_error(message, http_status)
ServiceResponse.error(message: message, http_status: http_status)
end
end
end
Snippets::DestroyService.prepend_mod_with('Snippets::DestroyService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::DestroyService, feature_category: :source_code_management do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let_it_be(:other_user) { create(:user) }
describe '#execute' do
subject { described_class.new(user, snippet).execute }
context 'when snippet is nil' do
let(:snippet) { nil }
it 'returns a ServiceResponse error' do
expect(subject).to be_error
end
end
shared_examples 'a successful destroy' do
it 'deletes the snippet' do
expect { subject }.to change { Snippet.count }.by(-1)
end
it 'returns ServiceResponse success' do
expect(subject).to be_success
end
end
shared_examples 'an unsuccessful destroy' do
it 'does not delete the snippet' do
expect { subject }.not_to change { Snippet.count }
end
it 'returns ServiceResponse error' do
expect(subject).to be_error
end
end
shared_examples 'deletes the snippet repository' do
it 'removes the snippet repository' do
expect(snippet.repository.exists?).to be_truthy
expect_next_instance_of(Repositories::DestroyService) do |instance|
expect(instance).to receive(:execute).and_call_original
end
expect(subject).to be_success
end
context 'when the repository deletion service raises an error' do
before do
allow_next_instance_of(Repositories::DestroyService) do |instance|
allow(instance).to receive(:execute).and_return({ status: :error })
end
end
it_behaves_like 'an unsuccessful destroy'
end
context 'when a destroy error is raised' do
before do
allow(snippet).to receive(:destroy!).and_raise(ActiveRecord::ActiveRecordError)
end
it_behaves_like 'an unsuccessful destroy'
end
context 'when repository is nil' do
it 'does not schedule anything and return success' do
allow(snippet).to receive(:repository).and_return(nil)
expect_next_instance_of(Repositories::DestroyService) do |instance|
expect(instance).to receive(:execute).and_call_original
end
expect(subject).to be_success
end
end
end
context 'when ProjectSnippet' do
let!(:snippet) { create(:project_snippet, :repository, project: project, author: author) }
context 'when user is able to admin_project_snippet' do
let(:author) { user }
before do
project.add_developer(user)
end
it_behaves_like 'a successful destroy'
it_behaves_like 'deletes the snippet repository'
context 'project statistics' do
before do
snippet.statistics.refresh!
end
it 'updates stats after deletion' do
expect(project.reload.statistics.snippets_size).not_to be_zero
subject
expect(project.reload.statistics.snippets_size).to be_zero
end
it 'schedules a namespace statistics update' do
expect(Namespaces::ScheduleAggregationWorker).to receive(:perform_async).with(project.namespace_id).once
subject
end
end
end
context 'when user is not able to admin_project_snippet' do
let(:author) { other_user }
it_behaves_like 'an unsuccessful destroy'
end
end
context 'when PersonalSnippet' do
let!(:snippet) { create(:personal_snippet, :repository, author: author) }
context 'when user is able to admin_personal_snippet' do
let(:author) { user }
it_behaves_like 'a successful destroy'
it_behaves_like 'deletes the snippet repository'
it 'schedules a namespace statistics update' do
expect(Namespaces::ScheduleAggregationWorker).to receive(:perform_async).with(author.namespace_id)
subject
end
end
context 'when user is not able to admin_personal_snippet' do
let(:author) { other_user }
it_behaves_like 'an unsuccessful destroy'
end
end
context 'when the repository does not exist' do
let(:snippet) { create(:personal_snippet, author: user) }
it 'does not schedule anything and return success' do
expect(snippet.repository).not_to be_nil
expect(snippet.repository.exists?).to be_falsey
expect_next_instance_of(Repositories::DestroyService) do |instance|
expect(instance).to receive(:execute).and_call_original
end
expect(subject).to be_success
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
class UpdateService < Snippets::BaseService
COMMITTABLE_ATTRIBUTES = %w[file_name content].freeze
UpdateError = Class.new(StandardError)
def initialize(project:, current_user: nil, params: {}, perform_spam_check: false)
super(project: project, current_user: current_user, params: params)
@perform_spam_check = perform_spam_check
end
def execute(snippet)
return invalid_params_error(snippet) unless valid_params?
if visibility_changed?(snippet) && !visibility_allowed?(visibility_level)
return forbidden_visibility_error(snippet)
end
update_snippet_attributes(snippet)
files = snippet.all_files.map { |f| { path: f } } + file_paths_to_commit
if perform_spam_check
snippet.check_for_spam(user: current_user, action: :update, extra_features: { files: files })
end
if save_and_commit(snippet)
Gitlab::UsageDataCounters::SnippetCounter.count(:update)
ServiceResponse.success(payload: { snippet: snippet })
else
snippet_error_response(snippet, 400)
end
end
private
attr_reader :perform_spam_check
def visibility_changed?(snippet)
visibility_level && visibility_level.to_i != snippet.visibility_level
end
def update_snippet_attributes(snippet)
# We can remove the following condition once
# https://gitlab.com/gitlab-org/gitlab/-/issues/217801
# is implemented.
# Once we can perform different operations through this service
# we won't need to keep track of the `content` and `file_name` fields
#
# If the repository does not exist we don't need to update `params`
# because we need to commit the information from the database
if snippet_actions.any? && snippet.repository_exists?
params[:content] = snippet_actions[0].content if snippet_actions[0].content
params[:file_name] = snippet_actions[0].file_path
end
snippet.assign_attributes(params)
end
def save_and_commit(snippet)
return false unless snippet.save
# If the updated attributes does not need to update
# the repository we can just return
return true unless committable_attributes?
unless snippet.repository_exists?
create_repository_for(snippet)
create_first_commit_using_db_data(snippet)
end
create_commit(snippet)
true
rescue StandardError => e
# Restore old attributes but re-assign changes so they're not lost
unless snippet.previous_changes.empty?
snippet.previous_changes.each { |attr, value| snippet[attr] = value[0] }
snippet.save
snippet.assign_attributes(params)
end
add_snippet_repository_error(snippet: snippet, error: e)
Gitlab::ErrorTracking.log_exception(e, service: 'Snippets::UpdateService')
# If the commit action failed we remove it because
# we don't want to leave empty repositories
# around, to allow cloning them.
delete_repository(snippet) if repository_empty?(snippet)
false
end
def create_repository_for(snippet)
snippet.create_repository
raise CreateRepositoryError, 'Repository could not be created' unless snippet.repository_exists?
end
# If the user provides `snippet_actions` and the repository
# does not exist, we need to commit first the snippet info stored
# in the database. Mostly because the content inside `snippet_actions`
# would assume that the file is already in the repository.
def create_first_commit_using_db_data(snippet)
return if snippet_actions.empty?
attrs = commit_attrs(snippet, INITIAL_COMMIT_MSG)
actions = [{ file_path: snippet.file_name, content: snippet.content }]
snippet.snippet_repository.multi_files_action(current_user, actions, **attrs)
end
def create_commit(snippet)
raise UpdateError unless snippet.snippet_repository
attrs = commit_attrs(snippet, UPDATE_COMMIT_MSG)
snippet.snippet_repository.multi_files_action(current_user, files_to_commit(snippet), **attrs)
end
# Because we are removing repositories we don't want to remove
# any existing repository with data. Therefore, we cannot
# rely on cached methods for that check in order to avoid losing
# data.
def repository_empty?(snippet)
snippet.repository._uncached_exists? && !snippet.repository._uncached_has_visible_content?
end
def committable_attributes?
(params.stringify_keys.keys & COMMITTABLE_ATTRIBUTES).present? || snippet_actions.any?
end
def build_actions_from_params(snippet)
file_name_on_repo = snippet.file_name_on_repo
[{ previous_path: file_name_on_repo,
file_path: params[:file_name] || file_name_on_repo,
content: params[:content] }]
end
end
end
Snippets::UpdateService.prepend_mod_with('Snippets::UpdateService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::UpdateService, feature_category: :source_code_management do
describe '#execute', :aggregate_failures do
let_it_be(:user) { create(:user) }
let_it_be(:admin) { create :user, admin: true }
let(:action) { :update }
let(:visibility_level) { Gitlab::VisibilityLevel::PRIVATE }
let(:base_opts) do
{
title: 'Test snippet',
file_name: 'snippet.rb',
content: 'puts "hello world"',
visibility_level: visibility_level
}
end
let(:extra_opts) { {} }
let(:options) { base_opts.merge(extra_opts) }
let(:updater) { user }
let(:service) { described_class.new(project: project, current_user: updater, params: options, perform_spam_check: true) }
subject { service.execute(snippet) }
shared_examples 'a service that updates a snippet' do
it 'updates a snippet with the provided attributes' do
expect { subject }.to change { snippet.title }.from(snippet.title).to(options[:title])
.and change { snippet.file_name }.from(snippet.file_name).to(options[:file_name])
.and change { snippet.content }.from(snippet.content).to(options[:content])
end
end
shared_examples 'public visibility level restrictions apply' do
let(:visibility_level) { Gitlab::VisibilityLevel::PUBLIC }
before do
stub_application_setting(restricted_visibility_levels: [Gitlab::VisibilityLevel::PUBLIC])
end
context 'when user is not an admin' do
it 'responds with an error' do
expect(subject).to be_error
end
it 'does not update snippet to public visibility' do
original_visibility = snippet.visibility_level
expect(subject.message).to match('has been restricted')
expect(snippet.visibility_level).to eq(original_visibility)
end
end
context 'when user is an admin' do
let(:updater) { admin }
it 'responds with success' do
expect(subject).to be_success
end
it 'updates the snippet to public visibility' do
old_visibility = snippet.visibility_level
expect(subject.payload[:snippet]).not_to be_nil
expect(snippet.visibility_level).not_to eq(old_visibility)
expect(snippet.visibility_level).to eq(Gitlab::VisibilityLevel::PUBLIC)
end
end
context 'when visibility level is passed as a string' do
before do
options[:visibility] = 'internal'
options.delete(:visibility_level)
end
it 'assigns the correct visibility level' do
expect(subject).to be_success
expect(snippet.visibility_level).to eq(Gitlab::VisibilityLevel::INTERNAL)
end
end
end
shared_examples 'snippet update data is tracked' do
let(:counter) { Gitlab::UsageDataCounters::SnippetCounter }
it 'increments count when create succeeds' do
expect { subject }.to change { counter.read(:update) }.by 1
end
context 'when update fails' do
let(:extra_opts) { { title: '' } }
it 'does not increment count' do
expect { subject }.not_to change { counter.read(:update) }
end
end
end
shared_examples 'creates repository and creates file' do
context 'when file_name and content params are used' do
it 'creates repository' do
expect(snippet.repository).not_to exist
subject
expect(snippet.repository).to exist
end
it 'commits the files to the repository' do
subject
expect(snippet.blobs.count).to eq 1
blob = snippet.repository.blob_at('master', options[:file_name])
expect(blob.data).to eq options[:content]
end
context 'when the repository creation fails' do
before do
allow(snippet).to receive(:repository_exists?).and_return(false)
end
it 'raise an error' do
expect(subject).to be_error
expect(subject.payload[:snippet].errors[:repository].to_sentence).to eq 'Error updating the snippet - Repository could not be created'
end
it 'does not try to commit file' do
expect(service).not_to receive(:create_commit)
subject
end
end
end
context 'when snippet_actions param is used' do
let(:file_path) { 'CHANGELOG' }
let(:created_file_path) { 'New file' }
let(:content) { 'foobar' }
let(:snippet_actions) { [{ action: :move, previous_path: snippet.file_name, file_path: file_path }, { action: :create, file_path: created_file_path, content: content }] }
let(:base_opts) do
{
snippet_actions: snippet_actions
}
end
it 'performs operation without raising errors' do
db_content = snippet.content
expect(subject).to be_success
new_blob = snippet.repository.blob_at('master', file_path)
created_file = snippet.repository.blob_at('master', created_file_path)
expect(new_blob.data).to eq db_content
expect(created_file.data).to eq content
end
context 'when the repository is not created' do
it 'keeps snippet database data' do
old_file_name = snippet.file_name
old_file_content = snippet.content
expect_next_instance_of(described_class) do |instance|
expect(instance).to receive(:create_repository_for).and_raise(StandardError)
end
snippet = subject.payload[:snippet]
expect(subject).to be_error
expect(snippet.file_name).to eq(old_file_name)
expect(snippet.content).to eq(old_file_content)
end
end
end
end
shared_examples 'commit operation fails' do
let_it_be(:gitlab_shell) { Gitlab::Shell.new }
before do
allow(service).to receive(:create_commit).and_raise(SnippetRepository::CommitError)
end
it 'returns error' do
response = subject
expect(response).to be_error
expect(response.payload[:snippet].errors[:repository].to_sentence).to eq 'Error updating the snippet'
end
context 'when repository is empty' do
before do
allow(service).to receive(:repository_empty?).and_return(true)
end
it 'destroys the created repository in disk' do
subject
expect(gitlab_shell.repository_exists?(snippet.repository.storage, "#{snippet.disk_path}.git")).to be_falsey
end
it 'destroys the SnippetRepository object' do
subject
expect(snippet.reload.snippet_repository).to be_nil
end
it 'expires the repository exists method cache' do
response = subject
expect(response).to be_error
expect(response.payload[:snippet].repository_exists?).to be_falsey
end
end
context 'when repository is not empty' do
before do
allow(service).to receive(:repository_empty?).and_return(false)
end
it 'does not destroy the repository' do
subject
expect(gitlab_shell.repository_exists?(snippet.repository.storage, "#{snippet.disk_path}.git")).to be_truthy
end
it 'does not destroy the snippet repository' do
subject
expect(snippet.reload.snippet_repository).not_to be_nil
end
it 'expires the repository exists method cache' do
response = subject
expect(response).to be_error
expect(response.payload[:snippet].repository_exists?).to be_truthy
end
end
context 'with snippet modifications' do
let(:option_keys) { options.stringify_keys.keys }
it 'rolls back any snippet modifications' do
orig_attrs = snippet.attributes.select { |k, v| k.in?(option_keys) }
subject
persisted_attrs = snippet.reload.attributes.select { |k, v| k.in?(option_keys) }
expect(orig_attrs).to eq persisted_attrs
end
it 'keeps any snippet modifications' do
subject
instance_attrs = snippet.attributes.select { |k, v| k.in?(option_keys) }
expect(options.stringify_keys).to eq instance_attrs
end
end
end
shared_examples 'updates repository content' do
it 'commit the files to the repository' do
blob = snippet.blobs.first
options[:file_name] = blob.path + '_new'
expect(blob.data).not_to eq(options[:content])
subject
blob = snippet.blobs.first
expect(blob.path).to eq(options[:file_name])
expect(blob.data).to eq(options[:content])
end
context 'when an error is raised' do
let(:error) { SnippetRepository::CommitError.new('foobar') }
before do
allow(snippet.snippet_repository).to receive(:multi_files_action).and_raise(error)
end
it 'logs the error' do
expect(Gitlab::ErrorTracking).to receive(:log_exception).with(error, service: 'Snippets::UpdateService')
subject
end
it 'returns error with generic error message' do
response = subject
expect(response).to be_error
expect(response.payload[:snippet].errors[:repository].to_sentence).to eq 'Error updating the snippet'
end
end
it 'returns error if snippet does not have a snippet_repository' do
allow(snippet).to receive(:snippet_repository).and_return(nil)
allow(snippet).to receive(:track_snippet_repository).and_return(nil)
expect(subject).to be_error
end
context 'when the repository does not exist' do
it 'does not try to commit file' do
allow(snippet).to receive(:repository_exists?).and_return(false)
expect(service).not_to receive(:create_commit)
subject
end
end
end
shared_examples 'committable attributes' do
context 'when file_name is updated' do
let(:extra_opts) { { file_name: 'snippet.rb' } }
it 'commits to repository' do
expect(service).to receive(:create_commit)
expect(subject).to be_success
end
end
context 'when content is updated' do
let(:extra_opts) { { content: 'puts "hello world"' } }
it 'commits to repository' do
expect(service).to receive(:create_commit)
expect(subject).to be_success
end
end
context 'when content or file_name is not updated' do
let(:options) { { title: 'Test snippet' } }
it 'does not perform any commit' do
expect(service).not_to receive(:create_commit)
expect(subject).to be_success
end
end
end
shared_examples 'when snippet_actions param is present' do
let(:file_path) { 'CHANGELOG' }
let(:content) { 'snippet_content' }
let(:new_title) { 'New title' }
let(:snippet_actions) { [{ action: 'update', previous_path: file_path, file_path: file_path, content: content }] }
let(:base_opts) do
{
title: new_title,
snippet_actions: snippet_actions
}
end
it 'updates a snippet with the provided attributes' do
file_path = 'foo'
snippet_actions[0][:action] = 'move'
snippet_actions[0][:file_path] = file_path
response = subject
snippet = response.payload[:snippet]
expect(response).to be_success
expect(snippet.title).to eq(new_title)
expect(snippet.file_name).to eq(file_path)
expect(snippet.content).to eq(content)
end
it 'commits the files to the repository' do
subject
blob = snippet.repository.blob_at('master', file_path)
expect(blob.data).to eq content
end
context 'when content or file_name params are present' do
let(:extra_opts) { { content: 'foo', file_name: 'path' } }
it 'raises a validation error' do
response = subject
snippet = response.payload[:snippet]
expect(response).to be_error
expect(snippet.errors.full_messages_for(:content)).to eq ['Content and snippet files cannot be used together']
expect(snippet.errors.full_messages_for(:file_name)).to eq ['File name and snippet files cannot be used together']
end
end
context 'when snippet_file content is not present' do
let(:snippet_actions) { [{ action: :move, previous_path: file_path, file_path: 'new_file_path' }] }
it 'does not update snippet content' do
content = snippet.content
expect(subject).to be_success
expect(snippet.reload.content).to eq content
end
end
context 'when snippet_actions param is invalid' do
let(:snippet_actions) { [{ action: 'invalid_action' }] }
it 'raises a validation error' do
snippet = subject.payload[:snippet]
expect(subject).to be_error
expect(snippet.errors.full_messages_for(:snippet_actions)).to eq ['Snippet actions have invalid data']
end
end
context 'when an error is raised committing the file' do
it 'keeps any snippet modifications' do
expect_next_instance_of(described_class) do |instance|
expect(instance).to receive(:create_commit).and_raise(StandardError)
end
snippet = subject.payload[:snippet]
expect(subject).to be_error
expect(snippet.title).to eq(new_title)
expect(snippet.file_name).to eq(file_path)
expect(snippet.content).to eq(content)
end
end
context 'commit actions' do
let(:new_path) { 'created_new_file' }
let(:base_opts) { { snippet_actions: snippet_actions } }
shared_examples 'returns an error' do |error_msg|
specify do
response = subject
expect(response).to be_error
expect(response.message).to eq error_msg
end
end
context 'update action' do
let(:snippet_actions) { [{ action: :update, file_path: file_path, content: content }] }
it 'updates the file content' do
expect(subject).to be_success
blob = blob(file_path)
expect(blob.data).to eq content
end
context 'when previous_path is present' do
let(:snippet_actions) { [{ action: :update, previous_path: file_path, file_path: file_path, content: content }] }
it 'updates the file content' do
expect(subject).to be_success
blob = blob(file_path)
expect(blob.data).to eq content
end
end
context 'when content is not present' do
let(:snippet_actions) { [{ action: :update, file_path: file_path }] }
it_behaves_like 'returns an error', 'Snippet actions have invalid data'
end
context 'when file_path does not exist' do
let(:snippet_actions) { [{ action: :update, file_path: 'makeup_name', content: content }] }
it_behaves_like 'returns an error', 'Repository Error updating the snippet'
end
end
context 'move action' do
context 'when file_path and previous_path are the same' do
let(:snippet_actions) { [{ action: :move, previous_path: file_path, file_path: file_path }] }
it_behaves_like 'returns an error', 'Snippet actions have invalid data'
end
context 'when file_path and previous_path are different' do
let(:snippet_actions) { [{ action: :move, previous_path: file_path, file_path: new_path }] }
it 'renames the file' do
old_blob = blob(file_path)
expect(subject).to be_success
blob = blob(new_path)
expect(blob).to be_present
expect(blob.data).to eq old_blob.data
end
end
context 'when previous_path does not exist' do
let(:snippet_actions) { [{ action: :move, previous_path: 'makeup_name', file_path: new_path }] }
it_behaves_like 'returns an error', 'Repository Error updating the snippet'
end
context 'when user wants to rename the file and update content' do
let(:snippet_actions) { [{ action: :move, previous_path: file_path, file_path: new_path, content: content }] }
it 'performs both operations' do
expect(subject).to be_success
blob = blob(new_path)
expect(blob).to be_present
expect(blob.data).to eq content
end
end
context 'when the file_path is not present' do
let(:snippet_actions) { [{ action: :move, previous_path: file_path }] }
it 'generates the name for the renamed file' do
old_blob = blob(file_path)
expect(blob('snippetfile1.txt')).to be_nil
expect(subject).to be_success
new_blob = blob('snippetfile1.txt')
expect(new_blob).to be_present
expect(new_blob.data).to eq old_blob.data
end
end
end
context 'delete action' do
let(:snippet_actions) { [{ action: :delete, file_path: file_path }] }
shared_examples 'deletes the file' do
specify do
old_blob = blob(file_path)
expect(old_blob).to be_present
expect(subject).to be_success
expect(blob(file_path)).to be_nil
end
end
it_behaves_like 'deletes the file'
context 'when previous_path is present and same as file_path' do
let(:snippet_actions) { [{ action: :delete, previous_path: file_path, file_path: file_path }] }
it_behaves_like 'deletes the file'
end
context 'when previous_path is present and is different from file_path' do
let(:snippet_actions) { [{ action: :delete, previous_path: 'foo', file_path: file_path }] }
it_behaves_like 'deletes the file'
end
context 'when content is present' do
let(:snippet_actions) { [{ action: :delete, file_path: file_path, content: 'foo' }] }
it_behaves_like 'deletes the file'
end
context 'when file_path does not exist' do
let(:snippet_actions) { [{ action: :delete, file_path: 'makeup_name' }] }
it_behaves_like 'returns an error', 'Repository Error updating the snippet'
end
end
context 'create action' do
let(:snippet_actions) { [{ action: :create, file_path: new_path, content: content }] }
it 'creates the file' do
expect(subject).to be_success
blob = blob(new_path)
expect(blob).to be_present
expect(blob.data).to eq content
end
context 'when content is not present' do
let(:snippet_actions) { [{ action: :create, file_path: new_path }] }
it_behaves_like 'returns an error', 'Snippet actions have invalid data'
end
context 'when file_path is not present or empty' do
let(:snippet_actions) { [{ action: :create, content: content }, { action: :create, file_path: '', content: content }] }
it 'generates the file path for the files' do
expect(blob('snippetfile1.txt')).to be_nil
expect(blob('snippetfile2.txt')).to be_nil
expect(subject).to be_success
expect(blob('snippetfile1.txt').data).to eq content
expect(blob('snippetfile2.txt').data).to eq content
end
end
context 'when file_path already exists in the repository' do
let(:snippet_actions) { [{ action: :create, file_path: file_path, content: content }] }
it_behaves_like 'returns an error', 'Repository Error updating the snippet'
end
context 'when previous_path is present' do
let(:snippet_actions) { [{ action: :create, previous_path: 'foo', file_path: new_path, content: content }] }
it 'creates the file' do
expect(subject).to be_success
blob = blob(new_path)
expect(blob).to be_present
expect(blob.data).to eq content
end
end
end
context 'combination of actions' do
let(:delete_file_path) { 'CHANGELOG' }
let(:create_file_path) { 'created_new_file' }
let(:update_file_path) { 'LICENSE' }
let(:move_previous_path) { 'VERSION' }
let(:move_file_path) { 'VERSION_new' }
let(:snippet_actions) do
[
{ action: :create, file_path: create_file_path, content: content },
{ action: :update, file_path: update_file_path, content: content },
{ action: :delete, file_path: delete_file_path },
{ action: :move, previous_path: move_previous_path, file_path: move_file_path, content: content }
]
end
it 'performs all operations' do
expect(subject).to be_success
expect(blob(delete_file_path)).to be_nil
created_blob = blob(create_file_path)
expect(created_blob.data).to eq content
updated_blob = blob(update_file_path)
expect(updated_blob.data).to eq content
expect(blob(move_previous_path)).to be_nil
moved_blob = blob(move_file_path)
expect(moved_blob.data).to eq content
end
end
def blob(path)
snippet.repository.blob_at('master', path)
end
end
end
shared_examples 'only file_name is present' do
let(:base_opts) do
{
file_name: file_name
}
end
shared_examples 'content is not updated' do
specify do
existing_content = snippet.blobs.first.data
response = subject
snippet = response.payload[:snippet]
blob = snippet.repository.blob_at('master', file_name)
expect(blob).not_to be_nil
expect(response).to be_success
expect(blob.data).to eq existing_content
end
end
context 'when renaming the file_name' do
let(:file_name) { 'new_file_name' }
it_behaves_like 'content is not updated'
end
context 'when file_name does not change' do
let(:file_name) { snippet.blobs.first.path }
it_behaves_like 'content is not updated'
end
end
shared_examples 'only content is present' do
let(:content) { 'new_content' }
let(:base_opts) do
{
content: content
}
end
it 'updates the content' do
response = subject
snippet = response.payload[:snippet]
blob = snippet.repository.blob_at('master', snippet.blobs.first.path)
expect(blob).not_to be_nil
expect(response).to be_success
expect(blob.data).to eq content
end
end
context 'when Project Snippet' do
let_it_be(:project) { create(:project) }
let!(:snippet) { create(:project_snippet, :repository, author: user, project: project) }
before do
project.add_developer(user)
end
it_behaves_like 'a service that updates a snippet'
it_behaves_like 'public visibility level restrictions apply'
it_behaves_like 'snippet update data is tracked'
it_behaves_like 'updates repository content'
it_behaves_like 'commit operation fails'
it_behaves_like 'committable attributes'
it_behaves_like 'when snippet_actions param is present'
it_behaves_like 'only file_name is present'
it_behaves_like 'only content is present'
it_behaves_like 'invalid params error response'
it_behaves_like 'checking spam'
context 'when snippet does not have a repository' do
let!(:snippet) { create(:project_snippet, author: user, project: project) }
it_behaves_like 'creates repository and creates file'
it_behaves_like 'commit operation fails'
end
end
context 'when PersonalSnippet' do
let(:project) { nil }
let!(:snippet) { create(:personal_snippet, :repository, author: user) }
it_behaves_like 'a service that updates a snippet'
it_behaves_like 'public visibility level restrictions apply'
it_behaves_like 'snippet update data is tracked'
it_behaves_like 'updates repository content'
it_behaves_like 'commit operation fails'
it_behaves_like 'committable attributes'
it_behaves_like 'when snippet_actions param is present'
it_behaves_like 'only file_name is present'
it_behaves_like 'only content is present'
it_behaves_like 'invalid params error response'
it_behaves_like 'checking spam'
context 'when snippet does not have a repository' do
let!(:snippet) { create(:personal_snippet, author: user, project: project) }
it_behaves_like 'creates repository and creates file'
it_behaves_like 'commit operation fails'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
class BulkDestroyService
include Gitlab::Allowable
attr_reader :current_user, :snippets
DeleteRepositoryError = Class.new(StandardError)
SnippetAccessError = Class.new(StandardError)
def initialize(user, snippets)
@current_user = user
@snippets = snippets
end
def execute(skip_authorization: false)
return ServiceResponse.success(message: 'No snippets found.') if snippets.empty?
user_can_delete_snippets! unless skip_authorization
attempt_delete_repositories!
snippets.destroy_all # rubocop: disable Cop/DestroyAll
ServiceResponse.success(message: 'Snippets were deleted.')
rescue SnippetAccessError
service_response_error("You don't have access to delete these snippets.", 403)
rescue DeleteRepositoryError
service_response_error('Failed to delete snippet repositories.', 400)
rescue StandardError
# In case the delete operation fails
service_response_error('Failed to remove snippets.', 400)
end
private
def user_can_delete_snippets!
allowed = DeclarativePolicy.user_scope do
snippets.find_each.all? { |snippet| user_can_delete_snippet?(snippet) }
end
raise SnippetAccessError unless allowed
end
def user_can_delete_snippet?(snippet)
can?(current_user, :admin_snippet, snippet)
end
def attempt_delete_repositories!
snippets.each do |snippet|
result = Repositories::DestroyService.new(snippet.repository).execute
raise DeleteRepositoryError if result[:status] == :error
end
end
def service_response_error(message, http_status)
ServiceResponse.error(message: message, http_status: http_status)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::BulkDestroyService, feature_category: :source_code_management do
let_it_be(:project) { create(:project) }
let(:user) { create(:user) }
let!(:personal_snippet) { create(:personal_snippet, :repository, author: user) }
let!(:project_snippet) { create(:project_snippet, :repository, project: project, author: user) }
let(:snippets) { user.snippets }
let(:gitlab_shell) { Gitlab::Shell.new }
let(:service_user) { user }
before do
project.add_developer(user)
end
subject { described_class.new(service_user, snippets) }
describe '#execute' do
it 'deletes the snippets in bulk' do
response = nil
expect(Repositories::DestroyService).to receive(:new).with(personal_snippet.repository).and_call_original
expect(Repositories::DestroyService).to receive(:new).with(project_snippet.repository).and_call_original
aggregate_failures do
expect do
response = subject.execute
end.to change(Snippet, :count).by(-2)
expect(response).to be_success
expect(repository_exists?(personal_snippet)).to be_falsey
expect(repository_exists?(project_snippet)).to be_falsey
end
end
context 'when snippets is empty' do
let(:snippets) { Snippet.none }
it 'returns a ServiceResponse success response' do
response = subject.execute
expect(response).to be_success
expect(response.message).to eq 'No snippets found.'
end
end
shared_examples 'error is raised' do
it 'returns error' do
response = subject.execute
aggregate_failures do
expect(response).to be_error
expect(response.message).to eq error_message
end
end
it 'no record is deleted' do
expect do
subject.execute
end.not_to change(Snippet, :count)
end
end
context 'when user does not have access to remove the snippet' do
let(:service_user) { create(:user) }
it_behaves_like 'error is raised' do
let(:error_message) { "You don't have access to delete these snippets." }
end
context 'when skip_authorization option is passed' do
subject { described_class.new(service_user, snippets).execute(skip_authorization: true) }
it 'returns a ServiceResponse success response' do
expect(subject).to be_success
end
it 'deletes all the snippets that belong to the user' do
expect { subject }.to change(Snippet, :count).by(-2)
end
end
end
context 'when an error is raised deleting the repository' do
before do
allow_next_instance_of(Repositories::DestroyService) do |instance|
allow(instance).to receive(:execute).and_return({ status: :error })
end
end
it_behaves_like 'error is raised' do
let(:error_message) { 'Failed to delete snippet repositories.' }
end
end
context 'when an error is raised deleting the records' do
before do
allow(snippets).to receive(:destroy_all).and_raise(ActiveRecord::ActiveRecordError)
end
it_behaves_like 'error is raised' do
let(:error_message) { 'Failed to remove snippets.' }
end
end
context 'when snippet does not have a repository attached' do
let!(:snippet_without_repo) { create(:personal_snippet, author: user) }
it 'returns success' do
response = nil
expect(Repositories::DestroyService).to receive(:new).with(personal_snippet.repository).and_call_original
expect(Repositories::DestroyService).to receive(:new).with(project_snippet.repository).and_call_original
expect(Repositories::DestroyService).to receive(:new).with(snippet_without_repo.repository).and_call_original
expect do
response = subject.execute
end.to change(Snippet, :count).by(-3)
expect(response).to be_success
end
end
end
def repository_exists?(snippet, path = snippet.disk_path + ".git")
gitlab_shell.repository_exists?(snippet.snippet_repository.shard_name, path)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
class UpdateStatisticsService
attr_reader :snippet
def initialize(snippet)
@snippet = snippet
end
def execute
unless snippet.repository_exists?
return ServiceResponse.error(message: 'Invalid snippet repository', http_status: 400)
end
snippet.repository.expire_statistics_caches
statistics.refresh!
ServiceResponse.success(message: 'Snippet statistics successfully updated.')
end
private
def statistics
@statistics ||= snippet.statistics || snippet.build_statistics
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::UpdateStatisticsService, feature_category: :source_code_management do
describe '#execute' do
subject { described_class.new(snippet).execute }
shared_examples 'updates statistics' do
it 'returns a successful response' do
expect(subject).to be_success
end
it 'expires statistics cache' do
expect(snippet.repository).to receive(:expire_statistics_caches)
subject
end
context 'when snippet statistics does not exist' do
it 'creates snippet statistics' do
snippet.statistics.delete
snippet.reload
expect do
subject
end.to change(SnippetStatistics, :count).by(1)
expect(snippet.statistics.commit_count).not_to be_zero
expect(snippet.statistics.file_count).not_to be_zero
expect(snippet.statistics.repository_size).not_to be_zero
end
end
context 'when snippet statistics exists' do
it 'updates snippet statistics' do
expect(snippet.statistics.commit_count).to be_zero
expect(snippet.statistics.file_count).to be_zero
expect(snippet.statistics.repository_size).to be_zero
subject
expect(snippet.statistics.commit_count).not_to be_zero
expect(snippet.statistics.file_count).not_to be_zero
expect(snippet.statistics.repository_size).not_to be_zero
end
end
context 'when snippet does not have a repository' do
it 'returns an error response' do
expect(snippet).to receive(:repository_exists?).and_return(false)
expect(subject).to be_error
end
end
it 'schedules a namespace storage statistics update' do
expect(Namespaces::ScheduleAggregationWorker)
.to receive(:perform_async).once
subject
end
end
context 'with PersonalSnippet' do
let!(:snippet) { create(:personal_snippet, :repository) }
it_behaves_like 'updates statistics'
end
context 'with ProjectSnippet' do
let!(:snippet) { create(:project_snippet, :repository) }
let(:project_statistics) { snippet.project.statistics }
it_behaves_like 'updates statistics'
it 'updates projects statistics "snippets_size"' do
expect(project_statistics.snippets_size).to be_zero
subject
expect(snippet.reload.statistics.repository_size).to eq project_statistics.reload.snippets_size
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
# Service for calculating visible Snippet counts via one query
# for the given user or project.
#
# Authorisation level checks will be included, ensuring the correct
# counts will be returned for the given user (if any).
#
# Basic usage:
#
# user = User.find(1)
#
# Snippets::CountService.new(user, author: user).execute
# #=> {
# are_public: 1,
# are_internal: 1,
# are_private: 1,
# all: 3
# }
#
# Counts can be scoped to a project:
#
# user = User.find(1)
# project = Project.find(1)
#
# Snippets::CountService.new(user, project: project).execute
# #=> {
# are_public: 1,
# are_internal: 1,
# are_private: 0,
# all: 2
# }
#
# Either a project or an author *must* be supplied.
module Snippets
class CountService
def initialize(current_user, author: nil, project: nil)
if !author && !project
raise(
ArgumentError, 'Must provide either an author or a project'
)
end
@snippets_finder = SnippetsFinder.new(current_user, author: author, project: project)
end
def execute
counts = snippet_counts
return {} unless counts
counts.slice(
:are_public,
:are_private,
:are_internal,
:are_public_or_internal,
:total
)
end
private
# rubocop: disable CodeReuse/ActiveRecord
def snippet_counts
@snippets_finder.execute
.reorder(nil)
.select("
count(case when snippets.visibility_level=#{Snippet::PUBLIC} and snippets.secret is FALSE then 1 else null end) as are_public,
count(case when snippets.visibility_level=#{Snippet::INTERNAL} then 1 else null end) as are_internal,
count(case when snippets.visibility_level=#{Snippet::PRIVATE} then 1 else null end) as are_private,
count(case when visibility_level=#{Snippet::PUBLIC} OR visibility_level=#{Snippet::INTERNAL} then 1 else null end) as are_public_or_internal,
count(*) as total
")
.take
end
# rubocop: enable CodeReuse/ActiveRecord
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::CountService, feature_category: :source_code_management do
let_it_be(:user) { create(:user) }
let_it_be(:project) { create(:project, :public) }
describe '#new' do
it 'raises an error if no author or project' do
expect { described_class.new(user) }.to raise_error(ArgumentError)
end
it 'uses the SnippetsFinder to scope snippets by user' do
expect(SnippetsFinder)
.to receive(:new)
.with(user, author: user, project: nil)
described_class.new(user, author: user)
end
it 'allows scoping to project' do
expect(SnippetsFinder)
.to receive(:new)
.with(user, author: nil, project: project)
described_class.new(user, project: project)
end
end
describe '#execute' do
subject { described_class.new(user, author: user).execute }
it 'returns a hash of counts' do
expect(subject).to match({
are_public: 0,
are_internal: 0,
are_private: 0,
are_public_or_internal: 0,
total: 0
})
end
it 'only counts snippets the user has access to' do
create(:personal_snippet, :private, author: user)
create(:project_snippet, :private, author: user)
create(:project_snippet, :private, author: create(:user))
expect(subject).to match({
are_public: 0,
are_internal: 0,
are_private: 1,
are_public_or_internal: 0,
total: 1
})
end
it 'returns an empty hash if select returns nil' do
allow_next_instance_of(described_class) do |instance|
allow(instance).to receive(:snippet_counts).and_return(nil)
end
expect(subject).to match({})
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Snippets
class CreateService < Snippets::BaseService
def initialize(project:, current_user: nil, params: {}, perform_spam_check: true)
super(project: project, current_user: current_user, params: params)
@perform_spam_check = perform_spam_check
end
def execute
@snippet = build_from_params
return invalid_params_error(@snippet) unless valid_params?
unless visibility_allowed?(snippet.visibility_level)
return forbidden_visibility_error(snippet)
end
@snippet.author = current_user
if perform_spam_check
@snippet.check_for_spam(user: current_user, action: :create, extra_features: { files: file_paths_to_commit })
end
if save_and_commit
UserAgentDetailService.new(spammable: @snippet, perform_spam_check: perform_spam_check).create
Gitlab::UsageDataCounters::SnippetCounter.count(:create)
move_temporary_files
ServiceResponse.success(payload: { snippet: @snippet })
else
snippet_error_response(@snippet, 400)
end
end
private
attr_reader :snippet, :perform_spam_check
def build_from_params
if project
project.snippets.build(create_params)
else
PersonalSnippet.new(create_params)
end
end
# If the snippet_actions param is present
# we need to fill content and file_name from
# the model
def create_params
return params if snippet_actions.empty?
params.merge(content: snippet_actions[0].content, file_name: snippet_actions[0].file_path)
end
def save_and_commit
snippet_saved = @snippet.save
if snippet_saved
create_repository
create_commit
end
snippet_saved
rescue StandardError => e # Rescuing all because we can receive Creation exceptions, GRPC exceptions, Git exceptions, ...
Gitlab::ErrorTracking.log_exception(e, service: 'Snippets::CreateService')
# If the commit action failed we need to remove the repository if exists
delete_repository(@snippet) if @snippet.repository_exists?
# If the snippet was created, we need to remove it as we
# would do like if it had had any validation error
# and reassign a dupe so we don't return the deleted snippet
if @snippet.persisted?
@snippet.delete
@snippet = @snippet.dup
end
add_snippet_repository_error(snippet: @snippet, error: e)
false
end
def create_repository
@snippet.create_repository
raise CreateRepositoryError, 'Repository could not be created' unless @snippet.repository_exists?
end
def create_commit
attrs = commit_attrs(@snippet, INITIAL_COMMIT_MSG)
@snippet.snippet_repository.multi_files_action(current_user, files_to_commit(@snippet), **attrs)
end
def move_temporary_files
return unless @snippet.is_a?(PersonalSnippet)
uploaded_assets.each do |file|
FileMover.new(file, from_model: current_user, to_model: @snippet).execute
end
end
def build_actions_from_params(_snippet)
[{ file_path: params[:file_name], content: params[:content] }]
end
def restricted_files_actions
:create
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Snippets::CreateService, feature_category: :source_code_management do
describe '#execute' do
let_it_be(:user) { create(:user) }
let_it_be(:admin) { create(:user, :admin) }
let(:action) { :create }
let(:opts) { base_opts.merge(extra_opts) }
let(:base_opts) do
{
title: 'Test snippet',
file_name: 'snippet.rb',
content: 'puts "hello world"',
visibility_level: Gitlab::VisibilityLevel::PRIVATE
}
end
let(:extra_opts) { {} }
let(:creator) { admin }
subject { described_class.new(project: project, current_user: creator, params: opts).execute }
let(:snippet) { subject.payload[:snippet] }
shared_examples 'a service that creates a snippet' do
it 'creates a snippet with the provided attributes' do
expect(snippet.title).to eq(opts[:title])
expect(snippet.file_name).to eq(opts[:file_name])
expect(snippet.content).to eq(opts[:content])
expect(snippet.visibility_level).to eq(opts[:visibility_level])
end
end
shared_examples 'public visibility level restrictions apply' do
let(:extra_opts) { { visibility_level: Gitlab::VisibilityLevel::PUBLIC } }
before do
stub_application_setting(restricted_visibility_levels: [Gitlab::VisibilityLevel::PUBLIC])
end
context 'when user is not an admin' do
let(:creator) { user }
it 'responds with an error' do
expect(subject).to be_error
end
it 'does not create a public snippet' do
expect(subject.message).to match('has been restricted')
end
end
context 'when user is an admin' do
it 'responds with success' do
expect(subject).to be_success
end
it 'creates a public snippet' do
expect(snippet.visibility_level).to eq(Gitlab::VisibilityLevel::PUBLIC)
end
end
describe 'when visibility level is passed as a string' do
let(:extra_opts) { { visibility: 'internal' } }
before do
base_opts.delete(:visibility_level)
end
it 'assigns the correct visibility level' do
expect(subject).to be_success
expect(snippet.visibility_level).to eq(Gitlab::VisibilityLevel::INTERNAL)
end
end
end
shared_examples 'snippet create data is tracked' do
let(:counter) { Gitlab::UsageDataCounters::SnippetCounter }
it 'increments count when create succeeds' do
expect { subject }.to change { counter.read(:create) }.by 1
end
context 'when create fails' do
let(:opts) { {} }
it 'does not increment count' do
expect { subject }.not_to change { counter.read(:create) }
end
end
end
shared_examples 'an error service response when save fails' do
let(:extra_opts) { { content: nil } }
it 'responds with an error' do
expect(subject).to be_error
end
it 'does not create the snippet' do
expect { subject }.not_to change { Snippet.count }
end
end
shared_examples 'creates repository and files' do
it 'creates repository' do
subject
expect(snippet.repository.exists?).to be_truthy
end
it 'commits the files to the repository' do
subject
blob = snippet.repository.blob_at('master', base_opts[:file_name])
expect(blob.data).to eq base_opts[:content]
end
context 'when repository creation action fails' do
before do
allow_next_instance_of(Snippet) do |instance|
allow(instance).to receive(:create_repository).and_return(nil)
end
end
it 'does not create the snippet' do
expect { subject }.not_to change { Snippet.count }
end
it 'returns a generic creation error' do
expect(snippet.errors[:repository]).to eq ['Error creating the snippet - Repository could not be created']
end
it 'does not return a snippet with an id' do
expect(snippet.id).to be_nil
end
end
context 'when repository creation fails with invalid file name' do
let(:extra_opts) { { file_name: 'invalid://file/name/here' } }
it 'returns an appropriate error' do
expect(snippet.errors[:repository]).to eq ['Error creating the snippet - Invalid file name']
end
end
context 'when the commit action fails' do
let(:error) { SnippetRepository::CommitError.new('foobar') }
before do
allow_next_instance_of(SnippetRepository) do |instance|
allow(instance).to receive(:multi_files_action).and_raise(error)
end
end
it 'does not create the snippet' do
expect { subject }.not_to change { Snippet.count }
end
it 'destroys the created repository' do
expect_next_instance_of(Repository) do |instance|
expect(instance).to receive(:remove).and_call_original
end
subject
end
it 'destroys the snippet_repository' do
subject
expect(SnippetRepository.count).to be_zero
end
it 'logs the error' do
expect(Gitlab::ErrorTracking).to receive(:log_exception).with(error, service: 'Snippets::CreateService')
subject
end
it 'returns a generic error' do
expect(subject).to be_error
expect(snippet.errors[:repository]).to eq ['Error creating the snippet']
end
end
context 'when snippet creation fails' do
let(:extra_opts) { { content: nil } }
it 'does not create repository' do
expect do
subject
end.not_to change(Snippet, :count)
expect(snippet.repository_exists?).to be_falsey
end
end
end
shared_examples 'after_save callback to store_mentions' do |mentionable_class|
context 'when mentionable attributes change' do
let(:extra_opts) { { description: "Description with #{user.to_reference}" } }
it 'saves mentions' do
expect_next_instance_of(mentionable_class) do |instance|
expect(instance).to receive(:store_mentions!).and_call_original
end
expect(snippet.user_mentions.count).to eq 1
end
end
context 'when mentionable attributes do not change' do
it 'does not call store_mentions' do
expect_next_instance_of(mentionable_class) do |instance|
expect(instance).not_to receive(:store_mentions!)
end
expect(snippet.user_mentions.count).to eq 0
end
end
context 'when save fails' do
it 'does not call store_mentions' do
base_opts.delete(:title)
expect_next_instance_of(mentionable_class) do |instance|
expect(instance).not_to receive(:store_mentions!)
end
expect(snippet.valid?).to be false
end
end
end
shared_examples 'when snippet_actions param is present' do
let(:file_path) { 'snippet_file_path.rb' }
let(:content) { 'snippet_content' }
let(:snippet_actions) { [{ action: 'create', file_path: file_path, content: content }] }
let(:base_opts) do
{
title: 'Test snippet',
visibility_level: Gitlab::VisibilityLevel::PRIVATE,
snippet_actions: snippet_actions
}
end
it 'creates a snippet with the provided attributes' do
expect(snippet.title).to eq(opts[:title])
expect(snippet.visibility_level).to eq(opts[:visibility_level])
expect(snippet.file_name).to eq(file_path)
expect(snippet.content).to eq(content)
end
it 'commit the files to the repository' do
expect(subject).to be_success
blob = snippet.repository.blob_at('master', file_path)
expect(blob.data).to eq content
end
context 'when content or file_name params are present' do
let(:extra_opts) { { content: 'foo', file_name: 'path' } }
it 'a validation error is raised' do
expect(subject).to be_error
expect(snippet.errors.full_messages_for(:content)).to eq ['Content and snippet files cannot be used together']
expect(snippet.errors.full_messages_for(:file_name)).to eq ['File name and snippet files cannot be used together']
expect(snippet.repository.exists?).to be_falsey
end
end
context 'when snippet_actions param is invalid' do
let(:snippet_actions) { [{ action: 'invalid_action', file_path: 'snippet_file_path.rb', content: 'snippet_content' }] }
it 'a validation error is raised' do
expect(subject).to be_error
expect(snippet.errors.full_messages_for(:snippet_actions)).to eq ['Snippet actions have invalid data']
expect(snippet.repository.exists?).to be_falsey
end
end
context 'when snippet_actions contain an action different from "create"' do
let(:snippet_actions) { [{ action: 'delete', file_path: 'snippet_file_path.rb' }] }
it 'a validation error is raised' do
expect(subject).to be_error
expect(snippet.errors.full_messages_for(:snippet_actions)).to eq ['Snippet actions have invalid data']
expect(snippet.repository.exists?).to be_falsey
end
end
context 'when "create" operation does not have file_path or is empty' do
let(:snippet_actions) { [{ action: 'create', content: content }, { action: 'create', content: content, file_path: '' }] }
it 'generates the file path for the files' do
expect(subject).to be_success
expect(snippet.repository.blob_at('master', 'snippetfile1.txt').data).to eq content
expect(snippet.repository.blob_at('master', 'snippetfile2.txt').data).to eq content
end
end
end
context 'when ProjectSnippet' do
let_it_be(:project) { create(:project) }
before do
project.add_developer(user)
end
it_behaves_like 'a service that creates a snippet'
it_behaves_like 'public visibility level restrictions apply'
it_behaves_like 'checking spam'
it_behaves_like 'snippet create data is tracked'
it_behaves_like 'an error service response when save fails'
it_behaves_like 'creates repository and files'
it_behaves_like 'after_save callback to store_mentions', ProjectSnippet
it_behaves_like 'when snippet_actions param is present'
it_behaves_like 'invalid params error response'
context 'when uploaded files are passed to the service' do
let(:extra_opts) { { files: ['foo'] } }
it 'does not move uploaded files to the snippet' do
expect_next_instance_of(described_class) do |instance|
expect(instance).to receive(:move_temporary_files).and_call_original
end
expect_any_instance_of(FileMover).not_to receive(:execute)
subject
end
end
end
context 'when PersonalSnippet' do
let(:project) { nil }
it_behaves_like 'a service that creates a snippet'
it_behaves_like 'public visibility level restrictions apply'
it_behaves_like 'checking spam'
it_behaves_like 'snippet create data is tracked'
it_behaves_like 'an error service response when save fails'
it_behaves_like 'creates repository and files'
it_behaves_like 'after_save callback to store_mentions', PersonalSnippet
it_behaves_like 'when snippet_actions param is present'
it_behaves_like 'invalid params error response'
context 'when the snippet description contains files' do
include FileMoverHelpers
let(:title) { 'Title' }
let(:picture_secret) { SecureRandom.hex }
let(:text_secret) { SecureRandom.hex }
let(:picture_file) { "/-/system/user/#{creator.id}/#{picture_secret}/picture.jpg" }
let(:text_file) { "/-/system/user/#{creator.id}/#{text_secret}/text.txt" }
let(:files) { [picture_file, text_file] }
let(:description) do
"Description with picture:  and "\
"text: [text.txt](/uploads#{text_file})"
end
before do
allow(FileUtils).to receive(:mkdir_p)
allow(FileUtils).to receive(:move)
end
let(:extra_opts) { { description: description, title: title, files: files } }
it 'stores the snippet description correctly' do
stub_file_mover(text_file)
stub_file_mover(picture_file)
snippet = subject.payload[:snippet]
expected_description = "Description with picture: "\
" and "\
"text: [text.txt](/uploads/-/system/personal_snippet/#{snippet.id}/#{text_secret}/text.txt)"
expect(snippet.description).to eq(expected_description)
end
context 'when there is a validation error' do
let(:title) { nil }
it 'does not move uploaded files to the snippet' do
expect_any_instance_of(described_class).not_to receive(:move_temporary_files)
subject
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Database
class ConsistencyFixService
def initialize(source_model:, target_model:, sync_event_class:, source_sort_key:, target_sort_key:)
@source_model = source_model
@target_model = target_model
@sync_event_class = sync_event_class
@source_sort_key = source_sort_key
@target_sort_key = target_sort_key
end
attr_accessor :source_model, :target_model, :sync_event_class, :source_sort_key, :target_sort_key
def execute(ids:)
ids.each do |id|
if source_object(id) && target_object(id)
create_sync_event_for(id)
elsif target_object(id)
target_object(id).destroy!
end
end
sync_event_class.enqueue_worker
end
private
# rubocop: disable CodeReuse/ActiveRecord
def source_object(id)
source_model.find_by(source_sort_key => id)
end
def target_object(id)
target_model.find_by(target_sort_key => id)
end
# rubocop: enable CodeReuse/ActiveRecord
def create_sync_event_for(id)
if source_model == Namespace
sync_event_class.create!(namespace_id: id)
elsif source_model == Project
sync_event_class.create!(project_id: id)
else
raise("Unknown Source Model #{source_model.name}")
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Database::ConsistencyFixService, feature_category: :cell do
describe '#execute' do
context 'fixing namespaces inconsistencies' do
subject(:consistency_fix_service) do
described_class.new(
source_model: Namespace,
target_model: Ci::NamespaceMirror,
sync_event_class: Namespaces::SyncEvent,
source_sort_key: :id,
target_sort_key: :namespace_id
)
end
let(:table) { 'public.namespaces' }
let!(:namespace) { create(:namespace) }
let!(:namespace_mirror) { Ci::NamespaceMirror.find_by(namespace_id: namespace.id) }
context 'when both objects exist' do
it 'creates a Namespaces::SyncEvent to modify the target object' do
expect do
consistency_fix_service.execute(ids: [namespace.id])
end.to change {
Namespaces::SyncEvent.where(namespace_id: namespace.id).count
}.by(1)
end
it 'enqueues the worker to process the Namespaces::SyncEvents' do
expect(::Namespaces::ProcessSyncEventsWorker).to receive(:perform_async)
consistency_fix_service.execute(ids: [namespace.id])
end
end
context 'when the source object has been deleted, but not the target' do
before do
namespace.delete
end
it 'deletes the target object' do
expect do
consistency_fix_service.execute(ids: [namespace.id])
end.to change { Ci::NamespaceMirror.where(namespace_id: namespace.id).count }.by(-1)
end
end
end
context 'fixing projects inconsistencies' do
subject(:consistency_fix_service) do
described_class.new(
source_model: Project,
target_model: Ci::ProjectMirror,
sync_event_class: Projects::SyncEvent,
source_sort_key: :id,
target_sort_key: :project_id
)
end
let(:table) { 'public.projects' }
let!(:project) { create(:project) }
let!(:project_mirror) { Ci::ProjectMirror.find_by(project_id: project.id) }
context 'when both objects exist' do
it 'creates a Projects::SyncEvent to modify the target object' do
expect do
consistency_fix_service.execute(ids: [project.id])
end.to change {
Projects::SyncEvent.where(project_id: project.id).count
}.by(1)
end
it 'enqueues the worker to process the Projects::SyncEvents' do
expect(::Projects::ProcessSyncEventsWorker).to receive(:perform_async)
consistency_fix_service.execute(ids: [project.id])
end
end
context 'when the source object has been deleted, but not the target' do
before do
project.delete
end
it 'deletes the target object' do
expect do
consistency_fix_service.execute(ids: [project.id])
end.to change { Ci::ProjectMirror.where(project_id: project.id).count }.by(-1)
end
end
end
end
describe '#create_sync_event_for' do
context 'when the source model is Namespace' do
let(:namespace) { create(:namespace) }
let(:service) do
described_class.new(
source_model: Namespace,
target_model: Ci::NamespaceMirror,
sync_event_class: Namespaces::SyncEvent,
source_sort_key: :id,
target_sort_key: :namespace_id
)
end
it 'creates a Namespaces::SyncEvent object' do
expect do
service.send(:create_sync_event_for, namespace.id)
end.to change { Namespaces::SyncEvent.where(namespace_id: namespace.id).count }.by(1)
end
end
context 'when the source model is Project' do
let(:project) { create(:project) }
let(:service) do
described_class.new(
source_model: Project,
target_model: Ci::ProjectMirror,
sync_event_class: Projects::SyncEvent,
source_sort_key: :id,
target_sort_key: :project_id
)
end
it 'creates a Projects::SyncEvent object' do
expect do
service.send(:create_sync_event_for, project.id)
end.to change { Projects::SyncEvent.where(project_id: project.id).count }.by(1)
end
end
end
context 'when the source model is User' do
let(:service) do
described_class.new(
source_model: User,
target_model: Ci::ProjectMirror,
sync_event_class: Projects::SyncEvent,
source_sort_key: :id,
target_sort_key: :project_id
)
end
it 'raises an error' do
expect do
service.send(:create_sync_event_for, 1)
end.to raise_error("Unknown Source Model User")
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Database
class ConsistencyCheckService
CURSOR_REDIS_KEY_TTL = 7.days
EMPTY_RESULT = { matches: 0, mismatches: 0, batches: 0, mismatches_details: [] }.freeze
def initialize(source_model:, target_model:, source_columns:, target_columns:)
@source_model = source_model
@target_model = target_model
@source_columns = source_columns
@target_columns = target_columns
@source_sort_column = source_columns.first
@target_sort_column = target_columns.first
end
# This class takes two ActiveRecord models, and compares the selected columns
# of the two models tables, for the purposes of checking the consistency of
# mirroring of tables. For example Namespace and Ci::NamepaceMirror
#
# It compares up to 25 batches (1000 records / batch), or up to 30 seconds
# for all the batches in total.
#
# It saves the cursor of the next start_id (cusror) in Redis. If the start_id
# wasn't saved in Redis, for example, in the first run, it will choose some random start_id
#
# Example:
# service = Database::ConsistencyCheckService.new(
# source_model: Namespace,
# target_model: Ci::NamespaceMirror,
# source_columns: %w[id traversal_ids],
# target_columns: %w[namespace_id traversal_ids],
# )
# result = service.execute
#
# result is a hash that has the following fields:
# - batches: Number of batches checked
# - matches: The number of matched records
# - mismatches: The number of mismatched records
# - mismatches_details: It's an array that contains details about the mismatched records.
# each record in this array is a hash of format {id: ID, source_table: [...], target_table: [...]}
# Each record represents the attributes of the records in the two tables.
# - start_id: The start id cursor of the current batch. <nil> means no records.
# - next_start_id: The ID that can be used for the next batch iteration check. <nil> means no records
def execute
start_id = next_start_id
return EMPTY_RESULT if start_id.nil?
result = consistency_checker.execute(start_id: start_id)
result[:start_id] = start_id
save_next_start_id(result[:next_start_id])
result
end
private
attr_reader :source_model, :target_model, :source_columns, :target_columns, :source_sort_column, :target_sort_column
def consistency_checker
@consistency_checker ||= Gitlab::Database::ConsistencyChecker.new(
source_model: source_model,
target_model: target_model,
source_columns: source_columns,
target_columns: target_columns
)
end
def next_start_id
return if min_id.nil?
fetch_next_start_id || random_start_id
end
# rubocop: disable CodeReuse/ActiveRecord
def min_id
@min_id ||= source_model.minimum(source_sort_column)
end
def max_id
@max_id ||= source_model.maximum(source_sort_column)
end
# rubocop: enable CodeReuse/ActiveRecord
def fetch_next_start_id
Gitlab::Redis::SharedState.with { |redis| redis.get(cursor_redis_shared_state_key)&.to_i }
end
# This returns some random start_id, so that we don't always start checking
# from the start of the table, in case we lose the cursor in Redis.
def random_start_id
range_start = min_id
range_end = [min_id, max_id - Gitlab::Database::ConsistencyChecker::BATCH_SIZE].max
rand(range_start..range_end)
end
def save_next_start_id(start_id)
Gitlab::Redis::SharedState.with do |redis|
redis.set(cursor_redis_shared_state_key, start_id, ex: CURSOR_REDIS_KEY_TTL)
end
end
def cursor_redis_shared_state_key
"consistency_check_cursor:#{source_model.table_name}:#{target_model.table_name}"
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Database::ConsistencyCheckService, feature_category: :cell do
let(:batch_size) { 5 }
let(:max_batches) { 2 }
before do
stub_const("Gitlab::Database::ConsistencyChecker::BATCH_SIZE", batch_size)
stub_const("Gitlab::Database::ConsistencyChecker::MAX_BATCHES", max_batches)
end
after do
redis_shared_state_cleanup!
end
subject(:consistency_check_service) do
described_class.new(
source_model: Namespace,
target_model: Ci::NamespaceMirror,
source_columns: %w[id traversal_ids],
target_columns: %w[namespace_id traversal_ids]
)
end
describe '#min_id' do
before do
create_list(:namespace, 3)
end
it 'returns the id of the first record in the database' do
expect(subject.send(:min_id)).to eq(Namespace.first.id)
end
end
describe '#max_id' do
before do
create_list(:namespace, 3)
end
it 'returns the id of the first record in the database' do
expect(subject.send(:max_id)).to eq(Namespace.last.id)
end
end
describe '#random_start_id' do
before do
create_list(:namespace, 50) # This will also create Ci::NameSpaceMirror objects
end
it 'generates a random start_id within the records ids' do
10.times do
start_id = subject.send(:random_start_id)
expect(start_id).to be_between(Namespace.first.id, Namespace.last.id).inclusive
end
end
end
describe '#execute' do
let(:empty_results) do
{ batches: 0, matches: 0, mismatches: 0, mismatches_details: [] }
end
context 'when empty tables' do
it 'returns results with zero counters' do
result = consistency_check_service.execute
expect(result).to eq(empty_results)
end
it 'does not call the ConsistencyCheckService' do
expect(Gitlab::Database::ConsistencyChecker).not_to receive(:new)
consistency_check_service.execute
end
end
context 'no cursor has been saved before' do
let(:min_id) { Namespace.first.id }
let(:max_id) { Namespace.last.id }
before do
create_list(:namespace, 50) # This will also create Ci::NameSpaceMirror objects
end
it 'picks a random start_id' do
expected_result = {
batches: 2,
matches: 10,
mismatches: 0,
mismatches_details: [],
start_id: be_between(min_id, max_id),
next_start_id: be_between(min_id, max_id)
}
expect(consistency_check_service).to receive(:rand).with(min_id..max_id).and_call_original
result = consistency_check_service.execute
expect(result).to match(expected_result)
end
it 'calls the ConsistencyCheckService with the expected parameters' do
expect(consistency_check_service).to receive(:random_start_id).and_return(min_id)
allow_next_instance_of(Gitlab::Database::ConsistencyChecker) do |instance|
expect(instance).to receive(:execute).with(start_id: min_id).and_return({
batches: 2,
next_start_id: min_id + batch_size,
matches: 10,
mismatches: 0,
mismatches_details: []
})
end
expect(Gitlab::Database::ConsistencyChecker).to receive(:new).with(
source_model: Namespace,
target_model: Ci::NamespaceMirror,
source_columns: %w[id traversal_ids],
target_columns: %w[namespace_id traversal_ids]
).and_call_original
expected_result = {
batches: 2,
matches: 10,
mismatches: 0,
mismatches_details: [],
start_id: be_between(min_id, max_id),
next_start_id: be_between(min_id, max_id)
}
result = consistency_check_service.execute
expect(result).to match(expected_result)
end
it 'saves the next_start_id in Redis for he next iteration' do
expect(consistency_check_service).to receive(:save_next_start_id)
.with(be_between(min_id, max_id)).and_call_original
consistency_check_service.execute
end
end
context 'cursor saved in Redis and moving' do
let(:first_namespace_id) { Namespace.order(:id).first.id }
let(:second_namespace_id) { Namespace.order(:id).second.id }
before do
create_list(:namespace, 30) # This will also create Ci::NameSpaceMirror objects
end
it "keeps moving the cursor with each call to the service" do
expect(consistency_check_service).to receive(:random_start_id).at_most(:once).and_return(first_namespace_id)
allow_next_instance_of(Gitlab::Database::ConsistencyChecker) do |instance|
expect(instance).to receive(:execute).ordered.with(start_id: first_namespace_id).and_call_original
expect(instance).to receive(:execute).ordered.with(start_id: first_namespace_id + 10).and_call_original
expect(instance).to receive(:execute).ordered.with(start_id: first_namespace_id + 20).and_call_original
# Gets back to the start of the table
expect(instance).to receive(:execute).ordered.with(start_id: first_namespace_id).and_call_original
end
4.times do
consistency_check_service.execute
end
end
it "keeps moving the cursor from any start point" do
expect(consistency_check_service).to receive(:random_start_id).at_most(:once).and_return(second_namespace_id)
allow_next_instance_of(Gitlab::Database::ConsistencyChecker) do |instance|
expect(instance).to receive(:execute).ordered.with(start_id: second_namespace_id).and_call_original
expect(instance).to receive(:execute).ordered.with(start_id: second_namespace_id + 10).and_call_original
end
2.times do
consistency_check_service.execute
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Database
class MarkMigrationService
def initialize(connection:, version:)
@connection = connection
@version = version
end
def execute
return error(reason: :not_found) unless migration.present?
return error(reason: :invalid) if all_versions.include?(migration.version)
if create_version(version)
ServiceResponse.success
else
error(reason: :invalid)
end
end
private
attr_reader :connection, :version
def migration
@migration ||= connection
.migration_context
.migrations
.find { |migration| migration.version == version }
end
def all_versions
all_executed_migrations.map(&:to_i)
end
def all_executed_migrations
sm = Arel::SelectManager.new(arel_table)
sm.project(arel_table[:version])
sm.order(arel_table[:version].asc) # rubocop: disable CodeReuse/ActiveRecord
connection.select_values(sm, "#{self.class} Load")
end
def create_version(version)
im = Arel::InsertManager.new
im.into(arel_table)
im.insert(arel_table[:version] => version)
connection.insert(im, "#{self.class} Create", :version, version)
end
def arel_table
@arel_table ||= Arel::Table.new(:schema_migrations)
end
def error(reason:)
ServiceResponse.error(message: 'error', reason: reason)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Database::MarkMigrationService, feature_category: :database do
let(:service) { described_class.new(connection: connection, version: version) }
let(:version) { 1 }
let(:connection) { ApplicationRecord.connection }
let(:migrations) do
[
instance_double(
ActiveRecord::MigrationProxy,
version: 1,
name: 'migration_pending',
filename: 'db/migrate/1_migration_pending.rb'
)
]
end
before do
ctx = instance_double(ActiveRecord::MigrationContext, migrations: migrations)
allow(connection).to receive(:migration_context).and_return(ctx)
end
describe '#execute' do
subject(:execute) { service.execute }
it 'marks the migration as successful' do
expect { execute }
.to change { ActiveRecord::SchemaMigration.where(version: version).count }
.by(1)
is_expected.to be_success
end
context 'when the migration does not exist' do
let(:version) { 123 }
it { is_expected.to be_error }
it { expect(execute.reason).to eq(:not_found) }
it 'does not insert records' do
expect { execute }
.not_to change { ActiveRecord::SchemaMigration.where(version: version).count }
end
end
context 'when the migration was already executed' do
before do
allow(service).to receive(:all_versions).and_return([version])
end
it { is_expected.to be_error }
it { expect(execute.reason).to eq(:invalid) }
it 'does not insert records' do
expect { execute }
.not_to change { ActiveRecord::SchemaMigration.where(version: version).count }
end
end
context 'when the insert fails' do
it 'returns an error response' do
expect(service).to receive(:create_version).with(version).and_return(false)
is_expected.to be_error
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module FeatureFlags
class HookService
HOOK_NAME = :feature_flag_hooks
def initialize(feature_flag, current_user)
@feature_flag = feature_flag
@current_user = current_user
end
def execute
project.execute_hooks(hook_data, HOOK_NAME)
end
private
attr_reader :feature_flag, :current_user
def project
@project ||= feature_flag.project
end
def hook_data
Gitlab::DataBuilder::FeatureFlag.build(feature_flag, current_user)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe FeatureFlags::HookService, feature_category: :feature_flags do
describe '#execute_hooks' do
let_it_be(:namespace) { create(:namespace) }
let_it_be(:project) { create(:project, :repository, namespace: namespace) }
let_it_be(:feature_flag) { create(:operations_feature_flag, project: project) }
let_it_be(:user) { namespace.first_owner }
let!(:hook) { create(:project_hook, project: project) }
let(:hook_data) { double }
subject(:service) { described_class.new(feature_flag, user) }
before do
allow(Gitlab::DataBuilder::FeatureFlag).to receive(:build).with(feature_flag, user).once.and_return(hook_data)
end
describe 'HOOK_NAME' do
specify { expect(described_class::HOOK_NAME).to eq(:feature_flag_hooks) }
end
it 'calls feature_flag.project.execute_hooks' do
expect(feature_flag.project).to receive(:execute_hooks).with(hook_data, described_class::HOOK_NAME)
service.execute
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module FeatureFlags
class DestroyService < FeatureFlags::BaseService
def execute(feature_flag)
destroy_feature_flag(feature_flag)
end
private
def destroy_feature_flag(feature_flag)
return error('Access Denied', 403) unless can_destroy?(feature_flag)
ApplicationRecord.transaction do
if feature_flag.destroy
update_last_feature_flag_updated_at!
success(feature_flag: feature_flag)
else
error(feature_flag.errors.full_messages)
end
end
end
def audit_context(feature_flag)
{
name: 'feature_flag_deleted',
message: audit_message(feature_flag),
author: current_user,
scope: feature_flag.project,
target: feature_flag
}
end
def audit_message(feature_flag)
"Deleted feature flag #{feature_flag.name}."
end
def can_destroy?(feature_flag)
Ability.allowed?(current_user, :destroy_feature_flag, feature_flag)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe FeatureFlags::DestroyService, feature_category: :feature_flags do
include FeatureFlagHelpers
let_it_be(:project) { create(:project) }
let_it_be(:developer) { create(:user) }
let_it_be(:reporter) { create(:user) }
let(:user) { developer }
let!(:feature_flag) { create(:operations_feature_flag, project: project) }
before_all do
project.add_developer(developer)
project.add_reporter(reporter)
end
describe '#execute' do
subject { described_class.new(project, user, params).execute(feature_flag) }
let(:audit_event_details) { AuditEvent.last.details }
let(:audit_event_message) { audit_event_details[:custom_message] }
let(:params) { {} }
it 'returns status success' do
expect(subject[:status]).to eq(:success)
end
it 'destroys feature flag' do
expect { subject }.to change { Operations::FeatureFlag.count }.by(-1)
end
it 'creates audit log', :with_license do
expect { subject }.to change { AuditEvent.count }.by(1)
expect(audit_event_message).to eq("Deleted feature flag #{feature_flag.name}.")
end
it_behaves_like 'update feature flag client'
context 'when user is reporter' do
let(:user) { reporter }
it 'returns error status' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to eq('Access Denied')
end
end
context 'when feature flag can not be destroyed' do
before do
allow(feature_flag).to receive(:destroy).and_return(false)
end
it 'returns status error' do
expect(subject[:status]).to eq(:error)
end
it 'does not create audit log' do
expect { subject }.not_to change { AuditEvent.count }
end
it_behaves_like 'does not update feature flag client'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module FeatureFlags
class UpdateService < FeatureFlags::BaseService
AUDITABLE_STRATEGY_ATTRIBUTES_HUMAN_NAMES = {
'scopes' => 'environment scopes',
'parameters' => 'parameters'
}.freeze
def success(**args)
execute_hooks_after_commit(args[:feature_flag])
super
end
def execute(feature_flag)
return error('Access Denied', 403) unless can_update?(feature_flag)
return error('Not Found', 404) unless valid_user_list_ids?(feature_flag, user_list_ids(params))
ApplicationRecord.transaction do
feature_flag.assign_attributes(params)
feature_flag.strategies.each do |strategy|
if strategy.name_changed? && strategy.name_was == ::Operations::FeatureFlags::Strategy::STRATEGY_GITLABUSERLIST
strategy.user_list = nil
end
end
# We generate the audit context before the feature flag is saved as #changed_strategies_messages depends on the strategies' states before save
saved_audit_context = audit_context feature_flag
if feature_flag.save
update_last_feature_flag_updated_at!
success(feature_flag: feature_flag, audit_context: saved_audit_context)
else
error(feature_flag.errors.full_messages, :bad_request)
end
end
end
private
def execute_hooks_after_commit(feature_flag)
return unless feature_flag.active_previously_changed?
# The `current_user` method (defined in `BaseService`) is not available within the `run_after_commit` block
user = current_user
feature_flag.run_after_commit do
HookService.new(feature_flag, user).execute
end
end
def audit_context(feature_flag)
{
name: 'feature_flag_updated',
message: audit_message(feature_flag),
author: current_user,
scope: feature_flag.project,
target: feature_flag
}
end
def audit_message(feature_flag)
changes = changed_attributes_messages(feature_flag)
changes += changed_strategies_messages(feature_flag)
return if changes.empty?
"Updated feature flag #{feature_flag.name}. " + changes.join(" ")
end
def changed_attributes_messages(feature_flag)
feature_flag.changes.slice(*AUDITABLE_ATTRIBUTES).map do |attribute_name, changes|
"Updated #{attribute_name} "\
"from \"#{changes.first}\" to "\
"\"#{changes.second}\"."
end
end
def changed_strategies_messages(feature_flag)
feature_flag.strategies.map do |strategy|
if strategy.new_record?
created_strategy_message(strategy)
elsif strategy.marked_for_destruction?
deleted_strategy_message(strategy)
else
updated_strategy_message(strategy)
end
end.compact # updated_strategy_message can return nil if nothing has been changed
end
def deleted_strategy_message(strategy)
scopes = strategy.scopes.map { |scope| scope.environment_scope }.join(', ')
"Deleted strategy #{strategy.name} with environment scopes #{scopes}."
end
def updated_strategy_message(strategy)
changes = strategy.changes.slice(*AUDITABLE_STRATEGY_ATTRIBUTES_HUMAN_NAMES.keys)
return if changes.empty?
message = "Updated strategy #{strategy.name} "
message += changes.map do |attribute_name, change|
name = AUDITABLE_STRATEGY_ATTRIBUTES_HUMAN_NAMES[attribute_name]
"#{name} from #{change.first} to #{change.second}"
end.join(' ')
message + '.'
end
def can_update?(feature_flag)
Ability.allowed?(current_user, :update_feature_flag, feature_flag)
end
def user_list_ids(params)
params.fetch(:strategies_attributes, [])
.select { |s| s[:user_list_id].present? }
.map { |s| s[:user_list_id] }
end
def valid_user_list_ids?(feature_flag, user_list_ids)
user_list_ids.empty? || ::Operations::FeatureFlags::UserList.belongs_to?(feature_flag.project_id, user_list_ids)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe FeatureFlags::UpdateService, :with_license, feature_category: :feature_flags do
let_it_be(:project) { create(:project) }
let_it_be(:developer) { create(:user) }
let_it_be(:reporter) { create(:user) }
let(:user) { developer }
let(:feature_flag) { create(:operations_feature_flag, project: project, active: true) }
before_all do
project.add_developer(developer)
project.add_reporter(reporter)
end
describe '#execute' do
subject { described_class.new(project, user, params).execute(feature_flag) }
let(:params) { { name: 'new_name' } }
let(:audit_event_details) { AuditEvent.last.details }
let(:audit_event_message) { audit_event_details[:custom_message] }
it 'returns success status' do
expect(subject[:status]).to eq(:success)
end
context 'when Jira Connect subscription does not exist' do
it 'does not sync the feature flag to Jira' do
expect(::JiraConnect::SyncFeatureFlagsWorker).not_to receive(:perform_async)
subject
end
end
context 'when Jira Connect subscription exists' do
before do
create(:jira_connect_subscription, namespace: project.namespace)
end
it 'syncs the feature flag to Jira' do
expect(::JiraConnect::SyncFeatureFlagsWorker).to receive(:perform_async).with(Integer, Integer)
subject
end
end
it 'creates audit event with correct message' do
name_was = feature_flag.name
expect { subject }.to change { AuditEvent.count }.by(1)
expect(audit_event_message).to(
eq("Updated feature flag new_name. "\
"Updated name from \"#{name_was}\" "\
"to \"new_name\".")
)
end
it_behaves_like 'update feature flag client'
context 'with invalid params' do
let(:params) { { name: nil } }
it 'returns error status' do
expect(subject[:status]).to eq(:error)
expect(subject[:http_status]).to eq(:bad_request)
end
it 'returns error messages' do
expect(subject[:message]).to include("Name can't be blank")
end
it 'does not create audit event' do
expect { subject }.not_to change { AuditEvent.count }
end
it 'does not sync the feature flag to Jira' do
expect(::JiraConnect::SyncFeatureFlagsWorker).not_to receive(:perform_async)
subject
end
it_behaves_like 'does not update feature flag client'
end
context 'when user is reporter' do
let(:user) { reporter }
it 'returns error status' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to eq('Access Denied')
end
end
context 'when nothing is changed' do
let(:params) { {} }
it 'returns success status' do
expect(subject[:status]).to eq(:success)
end
it 'does not create audit event' do
expect { subject }.not_to change { AuditEvent.count }
end
end
context 'description is being changed' do
let(:params) { { description: 'new description' } }
it 'creates audit event with changed description' do
expect { subject }.to change { AuditEvent.count }.by(1)
expect(audit_event_message).to(
include("Updated description from \"\""\
" to \"new description\".")
)
end
end
context 'when flag active state is changed' do
let(:params) do
{
active: false
}
end
it 'creates audit event about changing active state' do
expect { subject }.to change { AuditEvent.count }.by(1)
expect(audit_event_message).to(
include('Updated active from "true" to "false".')
)
end
it 'executes hooks' do
hook = create(:project_hook, :all_events_enabled, project: project)
expect(WebHookWorker).to receive(:perform_async).with(hook.id, an_instance_of(Hash), 'feature_flag_hooks', an_instance_of(Hash))
subject
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module FeatureFlags
class CreateService < FeatureFlags::BaseService
def execute
return error('Access Denied', 403) unless can_create?
return error('Version is invalid', :bad_request) unless valid_version?
ApplicationRecord.transaction do
feature_flag = project.operations_feature_flags.new(params)
if feature_flag.save
update_last_feature_flag_updated_at!
success(feature_flag: feature_flag)
else
error(feature_flag.errors.full_messages, 400)
end
end
end
private
def audit_context(feature_flag)
{
name: 'feature_flag_created',
message: audit_message(feature_flag),
author: current_user,
scope: feature_flag.project,
target: feature_flag
}
end
def audit_message(feature_flag)
message_parts = ["Created feature flag #{feature_flag.name} with description \"#{feature_flag.description}\"."]
message_parts += feature_flag.strategies.map do |strategy|
created_strategy_message(strategy)
end
message_parts.join(" ")
end
def can_create?
Ability.allowed?(current_user, :create_feature_flag, project)
end
def valid_version?
!params.key?(:version) || Operations::FeatureFlag.versions.key?(params[:version])
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe FeatureFlags::CreateService, feature_category: :feature_flags do
let_it_be(:project) { create(:project) }
let_it_be(:developer) { create(:user) }
let_it_be(:reporter) { create(:user) }
let(:user) { developer }
before_all do
project.add_developer(developer)
project.add_reporter(reporter)
end
describe '#execute' do
subject do
described_class.new(project, user, params).execute
end
let(:feature_flag) { subject[:feature_flag] }
context 'when feature flag can not be created' do
let(:params) { {} }
it 'returns status error' do
expect(subject[:status]).to eq(:error)
end
it 'returns validation errors' do
expect(subject[:message]).to include("Name can't be blank")
end
it 'does not create audit log' do
expect { subject }.not_to change { AuditEvent.count }
end
it 'does not sync the feature flag to Jira' do
expect(::JiraConnect::SyncFeatureFlagsWorker).not_to receive(:perform_async)
subject
end
it_behaves_like 'does not update feature flag client'
end
context 'when feature flag is saved correctly' do
let(:audit_event_details) { AuditEvent.last.details }
let(:audit_event_message) { audit_event_details[:custom_message] }
let(:params) do
{
name: 'feature_flag',
description: 'description',
version: 'new_version_flag',
strategies_attributes: [{ name: 'default', scopes_attributes: [{ environment_scope: '*' }], parameters: {} },
{ name: 'default', parameters: {}, scopes_attributes: [{ environment_scope: 'production' }] }]
}
end
it 'returns status success' do
expect(subject[:status]).to eq(:success)
end
it 'creates feature flag' do
expect { subject }.to change { Operations::FeatureFlag.count }.by(1)
end
it_behaves_like 'update feature flag client'
context 'when Jira Connect subscription does not exist' do
it 'does not sync the feature flag to Jira' do
expect(::JiraConnect::SyncFeatureFlagsWorker).not_to receive(:perform_async)
subject
end
end
context 'when Jira Connect subscription exists' do
before do
create(:jira_connect_subscription, namespace: project.namespace)
end
it 'syncs the feature flag to Jira' do
expect(::JiraConnect::SyncFeatureFlagsWorker).to receive(:perform_async).with(Integer, Integer)
subject
end
end
it 'creates audit event', :with_license do
expect { subject }.to change { AuditEvent.count }.by(1)
expect(audit_event_message).to start_with('Created feature flag feature_flag with description "description".')
expect(audit_event_message).to include('Created strategy "default" with scopes "*".')
expect(audit_event_message).to include('Created strategy "default" with scopes "production".')
end
context 'when user is reporter' do
let(:user) { reporter }
it 'returns error status' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to eq('Access Denied')
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module IssueLinks
class DestroyService < IssuableLinks::DestroyService
include IncidentManagement::UsageData
private
def permission_to_remove_relation?
can?(current_user, :admin_issue_link, source) && can?(current_user, :admin_issue_link, target)
end
def track_event
track_incident_action(current_user, target, :incident_unrelate)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe IssueLinks::DestroyService, feature_category: :team_planning do
describe '#execute' do
let_it_be(:project) { create(:project_empty_repo, :private) }
let_it_be(:reporter) { create(:user).tap { |user| project.add_reporter(user) } }
let_it_be(:issue_a) { create(:issue, project: project) }
let_it_be(:issue_b) { create(:issue, project: project) }
let!(:issuable_link) { create(:issue_link, source: issue_a, target: issue_b) }
let(:user) { reporter }
subject { described_class.new(issuable_link, user).execute }
it_behaves_like 'a destroyable issuable link'
context 'when target is an incident' do
let(:issue_b) { create(:incident, project: project) }
it_behaves_like 'an incident management tracked event', :incident_management_incident_unrelate do
let(:current_user) { reporter }
end
it_behaves_like 'Snowplow event tracking with RedisHLL context' do
let(:namespace) { issue_b.namespace }
let(:category) { described_class.to_s }
let(:action) { 'incident_management_incident_unrelate' }
let(:label) { 'redis_hll_counters.incident_management.incident_management_total_unique_counts_monthly' }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module IssueLinks
class ListService < IssuableLinks::ListService
extend ::Gitlab::Utils::Override
private
def child_issuables
issuable.related_issues(current_user, preload: preload_for_collection)
end
override :serializer
def serializer
LinkedProjectIssueSerializer
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe IssueLinks::ListService, feature_category: :team_planning do
let(:user) { create :user }
let(:project) { create(:project_empty_repo, :private) }
let(:issue) { create :issue, project: project }
let(:user_role) { :developer }
before do
project.add_role(user, user_role)
end
describe '#execute' do
subject { described_class.new(issue, user).execute }
context 'user can see all issues' do
let(:issue_b) { create :issue, project: project }
let(:issue_c) { create :issue, project: project }
let(:issue_d) { create :issue, project: project }
let!(:issue_link_c) do
create(:issue_link, source: issue_d, target: issue)
end
let!(:issue_link_b) do
create(:issue_link, source: issue, target: issue_c)
end
let!(:issue_link_a) do
create(:issue_link, source: issue, target: issue_b)
end
it 'ensures no N+1 queries are made' do
control_count = ActiveRecord::QueryRecorder.new { subject }.count
project = create :project, :public
milestone = create :milestone, project: project
issue_x = create :issue, project: project, milestone: milestone
issue_y = create :issue, project: project, assignees: [user]
issue_z = create :issue, project: project
create :issue_link, source: issue_x, target: issue_y
create :issue_link, source: issue_x, target: issue_z
create :issue_link, source: issue_y, target: issue_z
expect { subject }.not_to exceed_query_limit(control_count)
end
it 'returns related issues JSON' do
expect(subject.size).to eq(3)
expect(subject).to include(include(
id: issue_b.id,
title: issue_b.title,
state: issue_b.state,
reference: issue_b.to_reference(project),
path: "/#{project.full_path}/-/issues/#{issue_b.iid}",
relation_path: "/#{project.full_path}/-/issues/#{issue.iid}/links/#{issue_link_a.id}"
))
expect(subject).to include(include(
id: issue_c.id,
title: issue_c.title,
state: issue_c.state,
reference: issue_c.to_reference(project),
path: "/#{project.full_path}/-/issues/#{issue_c.iid}",
relation_path: "/#{project.full_path}/-/issues/#{issue.iid}/links/#{issue_link_b.id}"
))
expect(subject).to include(include(
id: issue_d.id,
title: issue_d.title,
state: issue_d.state,
reference: issue_d.to_reference(project),
path: "/#{project.full_path}/-/issues/#{issue_d.iid}",
relation_path: "/#{project.full_path}/-/issues/#{issue.iid}/links/#{issue_link_c.id}"
))
end
end
context 'referencing a public project issue' do
let(:public_project) { create :project, :public }
let(:issue_b) { create :issue, project: public_project }
let!(:issue_link) do
create(:issue_link, source: issue, target: issue_b)
end
it 'presents issue' do
expect(subject.size).to eq(1)
end
end
context 'referencing issue with removed relationships' do
context 'when referenced a deleted issue' do
let(:issue_b) { create :issue, project: project }
let!(:issue_link) do
create(:issue_link, source: issue, target: issue_b)
end
it 'ignores issue' do
issue_b.destroy!
is_expected.to eq([])
end
end
context 'when referenced an issue with deleted project' do
let(:issue_b) { create :issue, project: project }
let!(:issue_link) do
create(:issue_link, source: issue, target: issue_b)
end
it 'ignores issue' do
project.destroy!
is_expected.to eq([])
end
end
context 'when referenced an issue with deleted namespace' do
let(:issue_b) { create :issue, project: project }
let!(:issue_link) do
create(:issue_link, source: issue, target: issue_b)
end
it 'ignores issue' do
project.namespace.destroy!
is_expected.to eq([])
end
end
end
context 'user cannot see relations' do
context 'when user cannot see the referenced issue' do
let!(:issue_link) do
create(:issue_link, source: issue)
end
it 'returns an empty list' do
is_expected.to eq([])
end
end
context 'when user cannot see the issue that referenced' do
let!(:issue_link) do
create(:issue_link, target: issue)
end
it 'returns an empty list' do
is_expected.to eq([])
end
end
end
context 'remove relations' do
let!(:issue_link) do
create(:issue_link, source: issue, target: referenced_issue)
end
context 'user can admin related issues just on target project' do
let(:user_role) { :guest }
let(:target_project) { create :project }
let(:referenced_issue) { create :issue, project: target_project }
it 'returns no destroy relation path' do
target_project.add_developer(user)
expect(subject.first[:relation_path]).to be_nil
end
end
context 'user can admin related issues just on source project' do
let(:user_role) { :developer }
let(:target_project) { create :project }
let(:referenced_issue) { create :issue, project: target_project }
it 'returns no destroy relation path' do
target_project.add_guest(user)
expect(subject.first[:relation_path]).to be_nil
end
end
context 'when user can admin related issues on both projects' do
let(:referenced_issue) { create :issue, project: project }
it 'returns related issue destroy relation path' do
expect(subject.first[:relation_path])
.to eq("/#{project.full_path}/-/issues/#{issue.iid}/links/#{issue_link.id}")
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module IssueLinks
class CreateService < IssuableLinks::CreateService
include IncidentManagement::UsageData
def linkable_issuables(issues)
@linkable_issuables ||= issues.select { |issue| can?(current_user, :admin_issue_link, issue) }
end
def previous_related_issuables
@related_issues ||= issuable.related_issues(authorize: false).to_a
end
private
def readonly_issuables(issuables)
@readonly_issuables ||= issuables.select { |issuable| issuable.readable_by?(current_user) }
end
def track_event
track_incident_action(current_user, issuable, :incident_relate)
end
def link_class
IssueLink
end
end
end
IssueLinks::CreateService.prepend_mod_with('IssueLinks::CreateService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe IssueLinks::CreateService, feature_category: :team_planning do
describe '#execute' do
let_it_be(:user) { create :user }
let_it_be(:namespace) { create :namespace }
let_it_be(:project) { create :project, namespace: namespace }
let_it_be(:issuable) { create :issue, project: project }
let_it_be(:issuable2) { create :issue, project: project }
let_it_be(:restricted_issuable) { create :issue }
let_it_be(:another_project) { create :project, namespace: project.namespace }
let_it_be(:issuable3) { create :issue, project: another_project }
let_it_be(:issuable_a) { create :issue, project: project }
let_it_be(:issuable_b) { create :issue, project: project }
let_it_be(:issuable_link) { create :issue_link, source: issuable, target: issuable_b, link_type: IssueLink::TYPE_RELATES_TO }
let(:issuable_parent) { issuable.project }
let(:issuable_type) { :issue }
let(:issuable_link_class) { IssueLink }
let(:params) { {} }
before do
project.add_developer(user)
restricted_issuable.project.add_guest(user)
another_project.add_developer(user)
end
it_behaves_like 'issuable link creation'
context 'when target is an incident' do
let_it_be(:issue) { create(:incident, project: project) }
let(:params) do
{ issuable_references: [issuable2.to_reference, issuable3.to_reference(another_project)] }
end
subject { described_class.new(issue, user, params).execute }
it_behaves_like 'an incident management tracked event', :incident_management_incident_relate 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_relate' }
let(:label) { 'redis_hll_counters.incident_management.incident_management_total_unique_counts_monthly' }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Spam
class SpamActionService
include SpamConstants
def initialize(spammable:, user:, action:, extra_features: {})
@target = spammable
@user = user
@action = action
@extra_features = extra_features
end
def execute
return ServiceResponse.success(message: 'Skipped spam check because user was not present') unless user
if target.supports_recaptcha? && spam_params
execute_with_captcha_support
else
execute_spam_check
end
end
delegate :check_for_spam?, to: :target
private
attr_reader :user, :action, :target, :spam_log, :extra_features
def spam_params
Gitlab::RequestContext.instance.spam_params
end
def execute_with_captcha_support
recaptcha_verified = Captcha::CaptchaVerificationService.new(spam_params: spam_params).execute
if recaptcha_verified
# If it's a request which is already verified through CAPTCHA,
# update the spam log accordingly.
SpamLog.verify_recaptcha!(user_id: user.id, id: spam_params.spam_log_id)
ServiceResponse.success(message: "CAPTCHA successfully verified")
else
execute_spam_check
end
end
def execute_spam_check
return ServiceResponse.success(message: 'Skipped spam check because user was allowlisted') if allowlisted?(user)
return ServiceResponse.success(message: 'Skipped spam check because it was not required') unless check_for_spam?(user: user)
perform_spam_service_check
ServiceResponse.success(message: "Spam check performed. Check #{target.class.name} spammable model for any errors or CAPTCHA requirement")
end
##
# In order to be proceed to the spam check process, the target must be
# a dirty instance, which means it should be already assigned with the new
# attribute values.
def ensure_target_is_dirty
msg = "Target instance of #{target.class.name} must be dirty (must have changes to save)"
raise(msg) unless target.has_changes_to_save?
end
def allowlisted?(user)
user.try(:gitlab_bot?) || user.try(:gitlab_service_user?)
end
##
# Performs the spam check using the spam verdict service, and modifies the target model
# accordingly based on the result.
def perform_spam_service_check
ensure_target_is_dirty
# since we can check for spam, and recaptcha is not verified,
# ask the SpamVerdictService what to do with the target.
spam_verdict_service.execute.tap do |result|
case result
when BLOCK_USER
target.spam!
create_spam_log
create_spam_abuse_event(result)
ban_user!
when DISALLOW
target.spam!
create_spam_log
create_spam_abuse_event(result)
when CONDITIONAL_ALLOW
# This means "require a CAPTCHA to be solved"
target.needs_recaptcha!
create_spam_log
create_spam_abuse_event(result)
when OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM
create_spam_log
when ALLOW
target.clear_spam_flags!
when NOOP
# spamcheck is not explicitly rendering a verdict & therefore can't make a decision
target.clear_spam_flags!
end
end
end
def create_spam_log
@spam_log = SpamLog.create!(
{
user_id: user.id,
title: target.spam_title,
description: target.spam_description,
source_ip: spam_params&.ip_address,
user_agent: spam_params&.user_agent,
noteable_type: noteable_type,
# Now, all requests are via the API, so hardcode it to true to simplify the logic and API
# of this service. See https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/2266
# for original introduction of `via_api` field.
# See discussion here about possibly deprecating this field:
# https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/2266#note_542527450
via_api: true
}
)
target.spam_log = spam_log
end
def create_spam_abuse_event(result)
params = {
user_id: user.id,
title: target.spam_title,
description: target.spam_description,
source_ip: spam_params&.ip_address,
user_agent: spam_params&.user_agent,
noteable_type: noteable_type,
verdict: result
}
target.run_after_commit_or_now do
Abuse::SpamAbuseEventsWorker.perform_async(params)
end
end
def ban_user!
UserCustomAttribute.set_banned_by_spam_log(target.spam_log)
user.ban!
end
def spam_verdict_service
context = {
action: action,
target_type: noteable_type
}
options = {
ip_address: spam_params&.ip_address,
user_agent: spam_params&.user_agent,
referer: spam_params&.referer
}
SpamVerdictService.new(
target: target,
user: user,
options: options,
context: context,
extra_features: extra_features
)
end
def noteable_type
@notable_type ||= target.class.to_s
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Spam::SpamActionService, feature_category: :instance_resiliency do
include_context 'includes Spam constants'
let(:issue) { create(:issue, project: project, author: author) }
let(:personal_snippet) { create(:personal_snippet, :public, author: author) }
let(:project_snippet) { create(:project_snippet, :public, author: author) }
let(:fake_ip) { '1.2.3.4' }
let(:fake_user_agent) { 'fake-user-agent' }
let(:fake_referer) { 'fake-http-referer' }
let(:captcha_response) { 'abc123' }
let(:spam_log_id) { existing_spam_log.id }
let(:spam_params) do
::Spam::SpamParams.new(
captcha_response: captcha_response,
spam_log_id: spam_log_id,
ip_address: fake_ip,
user_agent: fake_user_agent,
referer: fake_referer
)
end
let_it_be(:project) { create(:project, :public) }
let_it_be(:user) { create(:user) }
let_it_be(:author) { create(:user) }
before do
issue.spam = false
personal_snippet.spam = false
allow_next_instance_of(described_class) do |service|
allow(service).to receive(:spam_params).and_return(spam_params)
end
end
describe 'constructor argument validation' do
subject do
described_service = described_class.new(spammable: issue, user: user, action: :create)
described_service.execute
end
context 'when user is nil' do
let(:spam_params) { true }
let(:user) { nil }
let(:expected_service_user_not_present_message) do
/Skipped spam check because user was not present/
end
it "returns success with a messaage" do
response = subject
expect(response.message).to match(expected_service_user_not_present_message)
expect(issue).not_to be_spam
end
end
end
shared_examples 'allows user' do
it 'does not perform spam check' do
expect(Spam::SpamVerdictService).not_to receive(:new)
response = subject
expect(response.message).to match(/user was allowlisted/)
end
end
shared_examples 'creates a spam log' do |target_type|
it do
expect { subject }
.to log_spam(title: target.title, description: target.description, noteable_type: target_type)
# TODO: These checks should be incorporated into the `log_spam` RSpec matcher above
new_spam_log = SpamLog.last
expect(new_spam_log.user_id).to eq(user.id)
expect(new_spam_log.title).to eq(target.title)
expect(new_spam_log.description).to eq(target.spam_description)
expect(new_spam_log.source_ip).to eq(fake_ip)
expect(new_spam_log.user_agent).to eq(fake_user_agent)
expect(new_spam_log.noteable_type).to eq(target_type)
expect(new_spam_log.via_api).to eq(true)
end
end
shared_examples 'calls SpamAbuseEventsWorker with correct arguments' do
let(:params) do
{
user_id: user.id,
title: target.title,
description: target.spam_description,
source_ip: fake_ip,
user_agent: fake_user_agent,
noteable_type: target_type,
verdict: verdict
}
end
it do
expect(::Abuse::SpamAbuseEventsWorker).to receive(:perform_async).with(params)
subject
end
end
shared_examples 'execute spam action service' do |target_type|
let(:fake_captcha_verification_service) { double(:captcha_verification_service) }
let(:fake_verdict_service) { double(:spam_verdict_service) }
let(:verdict_service_opts) do
{
ip_address: fake_ip,
user_agent: fake_user_agent,
referer: fake_referer
}
end
let(:verdict_service_args) do
{
target: target,
user: user,
options: verdict_service_opts,
context: {
action: :create,
target_type: target_type
},
extra_features: extra_features
}
end
let_it_be(:existing_spam_log) { create(:spam_log, user: user, recaptcha_verified: false) }
subject do
described_service = described_class.new(spammable: target, extra_features:
extra_features, user: user, action: :create)
described_service.execute
end
before do
allow(Captcha::CaptchaVerificationService).to receive(:new).with(spam_params: spam_params) { fake_captcha_verification_service }
allow(Spam::SpamVerdictService).to receive(:new).with(verdict_service_args).and_return(fake_verdict_service)
allow(fake_verdict_service).to receive(:execute).and_return({})
end
context 'when captcha response verification returns true' do
before do
allow(fake_captcha_verification_service)
.to receive(:execute).and_return(true)
end
it "doesn't check with the SpamVerdictService" do
aggregate_failures do
expect(SpamLog).to receive(:verify_recaptcha!).with(
user_id: user.id,
id: spam_log_id
)
expect(fake_verdict_service).not_to receive(:execute)
end
subject
end
it 'updates spam log' do
expect { subject }.to change { existing_spam_log.reload.recaptcha_verified }.from(false).to(true)
end
end
context 'when captcha response verification returns false' do
before do
allow(fake_captcha_verification_service)
.to receive(:execute).and_return(false)
end
context 'when spammable attributes have not changed' do
before do
allow(target).to receive(:has_changes_to_save?).and_return(true)
end
it 'does not create a spam log' do
expect { subject }.not_to change(SpamLog, :count)
end
it 'does not call SpamAbuseEventsWorker' do
expect(::Abuse::SpamAbuseEventsWorker).not_to receive(:perform_async)
subject
end
end
context 'when spammable attributes have changed' do
let(:expected_service_check_response_message) do
/Check #{target_type} spammable model for any errors or CAPTCHA requirement/
end
before do
target.description = 'Lovely Spam! Wonderful Spam!'
end
context 'when captcha is not supported' do
before do
allow(target).to receive(:supports_recaptcha?).and_return(false)
end
it "does not execute with captcha support" do
expect(Captcha::CaptchaVerificationService).not_to receive(:new)
subject
end
it "executes a spam check" do
expect(fake_verdict_service).to receive(:execute)
subject
end
end
context 'when user is a gitlab bot' do
before do
allow(user).to receive(:gitlab_bot?).and_return(true)
end
it_behaves_like 'allows user'
end
context 'when user is a gitlab service user' do
before do
allow(user).to receive(:gitlab_service_user?).and_return(true)
end
it_behaves_like 'allows user'
end
context 'when disallowed by the spam verdict service' do
before do
allow(fake_verdict_service).to receive(:execute).and_return(DISALLOW)
end
it_behaves_like 'creates a spam log', target_type
it_behaves_like 'calls SpamAbuseEventsWorker with correct arguments' do
let(:verdict) { DISALLOW }
let(:target_type) { target_type }
end
it 'marks as spam' do
response = subject
expect(response.message).to match(expected_service_check_response_message)
expect(target).to be_spam
end
end
context 'spam verdict service advises to block the user' do
# create a fresh user to ensure it is in the unbanned state
let(:user) { create(:user) }
before do
allow(fake_verdict_service).to receive(:execute).and_return(BLOCK_USER)
end
it_behaves_like 'creates a spam log', target_type
it_behaves_like 'calls SpamAbuseEventsWorker with correct arguments' do
let(:verdict) { BLOCK_USER }
let(:target_type) { target_type }
end
it 'marks as spam' do
response = subject
expect(response.message).to match(expected_service_check_response_message)
expect(target).to be_spam
end
it 'bans the user' do
subject
custom_attribute = user.custom_attributes.by_key(UserCustomAttribute::AUTO_BANNED_BY_SPAM_LOG_ID).first
expect(custom_attribute.value).to eq(target.spam_log.id.to_s)
expect(user).to be_banned
end
end
context 'when spam verdict service conditionally allows' do
before do
allow(fake_verdict_service).to receive(:execute).and_return(CONDITIONAL_ALLOW)
end
it_behaves_like 'creates a spam log', target_type
it_behaves_like 'calls SpamAbuseEventsWorker with correct arguments' do
let(:verdict) { CONDITIONAL_ALLOW }
let(:target_type) { target_type }
end
it 'does not mark as spam' do
response = subject
expect(response.message).to match(expected_service_check_response_message)
expect(target).not_to be_spam
end
it 'marks as needing reCAPTCHA' do
response = subject
expect(response.message).to match(expected_service_check_response_message)
expect(target).to be_needs_recaptcha
end
end
context 'when spam verdict service returns OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM' do
before do
allow(fake_verdict_service).to receive(:execute).and_return(OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM)
end
it_behaves_like 'creates a spam log', target_type
it 'does not call SpamAbuseEventsWorker' do
expect(::Abuse::SpamAbuseEventsWorker).not_to receive(:perform_async)
subject
end
it 'does not mark as spam' do
response = subject
expect(response.message).to match(expected_service_check_response_message)
expect(target).not_to be_spam
end
it 'does not mark as needing CAPTCHA' do
response = subject
expect(response.message).to match(expected_service_check_response_message)
expect(target).not_to be_needs_recaptcha
end
end
context 'when spam verdict service allows creation' do
before do
allow(fake_verdict_service).to receive(:execute).and_return(ALLOW)
end
it 'does not create a spam log' do
expect { subject }.not_to change(SpamLog, :count)
end
it 'does not call SpamAbuseEventsWorker' do
expect(::Abuse::SpamAbuseEventsWorker).not_to receive(:perform_async)
subject
end
it 'clears spam flags' do
expect(target).to receive(:clear_spam_flags!)
subject
end
end
context 'when spam verdict service returns noop' do
before do
allow(fake_verdict_service).to receive(:execute).and_return(NOOP)
end
it 'does not create a spam log' do
expect { subject }.not_to change(SpamLog, :count)
end
it 'does not call SpamAbuseEventsWorker' do
expect(::Abuse::SpamAbuseEventsWorker).not_to receive(:perform_async)
subject
end
it 'clears spam flags' do
expect(target).to receive(:clear_spam_flags!)
subject
end
end
context 'with spam verdict service options' do
before do
allow(fake_verdict_service).to receive(:execute).and_return(ALLOW)
end
it 'assembles the options with information from the request' do
expect(Spam::SpamVerdictService).to receive(:new).with(verdict_service_args)
subject
end
end
end
end
end
describe '#execute' do
describe 'issue' do
let(:target) { issue }
let(:extra_features) { {} }
it_behaves_like 'execute spam action service', 'Issue'
end
describe 'project snippet' do
let(:target) { project_snippet }
let(:extra_features) { { files: [{ path: 'project.rb' }] } }
it_behaves_like 'execute spam action service', 'ProjectSnippet'
end
describe 'personal snippet' do
let(:target) { personal_snippet }
let(:extra_features) { { files: [{ path: 'personal.rb' }] } }
it_behaves_like 'execute spam action service', 'PersonalSnippet'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Spam
class HamService
include AkismetMethods
attr_accessor :spam_log, :options
def initialize(spam_log)
@spam_log = spam_log
@user = spam_log.user
@options = {
ip_address: spam_log.source_ip,
user_agent: spam_log.user_agent
}
end
def execute
if akismet.submit_ham
spam_log.update_attribute(:submitted_as_ham, true)
else
false
end
end
alias_method :target, :spam_log
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Spam::HamService, feature_category: :instance_resiliency do
let_it_be(:user) { create(:user) }
let!(:spam_log) { create(:spam_log, user: user, submitted_as_ham: false) }
let(:fake_akismet_service) { double(:akismet_service) }
subject { described_class.new(spam_log) }
before do
allow(Spam::AkismetService).to receive(:new).and_return fake_akismet_service
end
describe '#execute' do
context 'AkismetService returns false (Akismet cannot be reached, etc)' do
before do
allow(fake_akismet_service).to receive(:submit_ham).and_return false
end
it 'returns false' do
expect(subject.execute).to be_falsey
end
it 'does not update the record' do
expect { subject.execute }.not_to change { spam_log.submitted_as_ham }
end
context 'if spam log record has already been marked as spam' do
before do
spam_log.update_attribute(:submitted_as_ham, true)
end
it 'does not update the record' do
expect { subject.execute }.not_to change { spam_log.submitted_as_ham }
end
end
end
context 'Akismet ham submission is successful' do
before do
spam_log.update_attribute(:submitted_as_ham, false)
allow(fake_akismet_service).to receive(:submit_ham).and_return true
end
it 'returns true' do
expect(subject.execute).to be_truthy
end
it 'updates the record' do
expect { subject.execute }.to change { spam_log.submitted_as_ham }.from(false).to(true)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Spam
class AkismetService
attr_accessor :text, :options
def initialize(owner_name, owner_email, text, options = {})
@owner_name = owner_name
@owner_email = owner_email
@text = text
@options = options
end
def spam?
return false unless akismet_enabled?
params = {
type: 'comment',
text: text,
created_at: DateTime.current,
author: owner_name,
author_email: owner_email,
# NOTE: The akismet_client needs the option to be named `:referrer`, not `:referer`
referrer: options[:referer]
}
begin
is_spam, is_blatant = akismet_client.check(options[:ip_address], options[:user_agent], params)
is_spam || is_blatant
rescue ArgumentError => e
Gitlab::ErrorTracking.track_and_raise_for_dev_exception(e)
false
rescue StandardError => e
Gitlab::ErrorTracking.track_exception(e)
Gitlab::AppLogger.error("Error during Akismet spam check, flagging as not spam: #{e}")
false
end
end
def submit_ham
submit(:ham)
end
def submit_spam
submit(:spam)
end
private
attr_accessor :owner_name, :owner_email
def akismet_client
@akismet_client ||= ::Akismet::Client.new(
Gitlab::CurrentSettings.akismet_api_key,
Gitlab.config.gitlab.url
)
end
def akismet_enabled?
Gitlab::CurrentSettings.akismet_enabled
end
def submit(type)
return false unless akismet_enabled?
params = {
type: 'comment',
text: text,
author: owner_name,
author_email: owner_email
}
begin
akismet_client.public_send(type, options[:ip_address], options[:user_agent], params) # rubocop:disable GitlabSecurity/PublicSend
true
rescue StandardError => e
Gitlab::AppLogger.error("Unable to connect to Akismet: #{e}, skipping!")
false
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Spam::AkismetService, feature_category: :instance_resiliency do
let(:fake_akismet_client) { double(:akismet_client) }
let(:ip) { '1.2.3.4' }
let(:user_agent) { 'some user_agent' }
let(:referer) { 'some referer' }
let_it_be(:text) { "Would you like to buy some tinned meat product?" }
let_it_be(:spam_owner) { create(:user) }
subject do
options = { ip_address: ip, user_agent: user_agent, referer: referer }
described_class.new(spam_owner.name, spam_owner.email, text, options)
end
before do
stub_application_setting(akismet_enabled: true)
allow(subject).to receive(:akismet_client).and_return(fake_akismet_client)
end
shared_examples 'no activity if Akismet is not enabled' do |method_call|
before do
stub_application_setting(akismet_enabled: false)
end
it 'is automatically false' do
expect(subject.send(method_call)).to be_falsey
end
it 'performs no check' do
expect(fake_akismet_client).not_to receive(:public_send)
subject.send(method_call)
end
end
shared_examples 'false if Akismet is not available' do |method_call|
context 'if Akismet is not available' do
before do
allow(fake_akismet_client).to receive(:public_send).and_raise(StandardError.new("oh noes!"))
end
specify do
expect(subject.send(method_call)).to be_falsey
end
it 'logs an error' do
expect(Gitlab::AppLogger).to receive(:error).with(/skipping/)
subject.send(method_call)
end
end
end
describe '#spam?' do
it_behaves_like 'no activity if Akismet is not enabled', :spam?, :check
context 'if Akismet is enabled' do
it 'correctly transforms options for the akismet client, including spelling of referrer key' do
expected_check_params = {
type: 'comment',
text: text,
created_at: anything,
author: spam_owner.name,
author_email: spam_owner.email,
# NOTE: The akismet_client needs the option to be named `:referrer`, not `:referer`
referrer: referer
}
expect(fake_akismet_client).to receive(:check).with(ip, user_agent, expected_check_params)
subject.spam?
end
context 'the text is spam' do
before do
allow(fake_akismet_client).to receive(:check).and_return([true, false])
end
specify do
expect(subject.spam?).to be_truthy
end
end
context 'the text is blatant spam' do
before do
allow(fake_akismet_client).to receive(:check).and_return([false, true])
end
specify do
expect(subject.spam?).to be_truthy
end
end
context 'the text is not spam' do
before do
allow(fake_akismet_client).to receive(:check).and_return([false, false])
end
specify do
expect(subject.spam?).to be_falsey
end
end
describe 'error handling' do
before do
allow(fake_akismet_client).to receive(:check).and_raise(error)
end
context 'StandardError other than ArgumentError is raised' do
let(:error) { Akismet::Error.new("Lovely spam! Wonderful spam!") }
specify do
expect(subject.spam?).to be_falsey
end
it 'logs an error' do
expect(Gitlab::AppLogger).to receive(:error).with(/Error during Akismet.*flagging as not spam.*Lovely spam/)
subject.spam?
end
end
context 'ArgumentError is raised in dev' do
let(:error) { ArgumentError }
it 'raises original error' do
expect { subject.spam? }.to raise_error(error)
end
end
end
end
end
describe '#submit_ham' do
it_behaves_like 'no activity if Akismet is not enabled', :submit_ham
it_behaves_like 'false if Akismet is not available', :submit_ham
context 'if Akismet is available' do
specify do
expect(fake_akismet_client).to receive(:public_send).with(:ham, any_args)
expect(subject.submit_ham).to be_truthy
end
end
end
describe '#submit_spam' do
it_behaves_like 'no activity if Akismet is not enabled', :submit_spam
it_behaves_like 'false if Akismet is not available', :submit_spam
context 'if Akismet is available' do
specify do
expect(fake_akismet_client).to receive(:public_send).with(:spam, any_args)
expect(subject.submit_spam).to be_truthy
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Spam
class SpamVerdictService
include AkismetMethods
include SpamConstants
def initialize(user:, target:, options:, context: {}, extra_features: {})
@target = target
@user = user
@options = options
@context = context
@extra_features = extra_features
end
def execute
spamcheck_verdict = nil
external_spam_check_round_trip_time = Benchmark.realtime do
spamcheck_verdict = get_spamcheck_verdict
end
histogram.observe({ result: spamcheck_verdict.upcase }, external_spam_check_round_trip_time) if spamcheck_verdict
akismet_verdict = get_akismet_verdict
# filter out anything we don't recognise, including nils.
valid_verdicts = [spamcheck_verdict, akismet_verdict].compact.select { |r| SUPPORTED_VERDICTS.key?(r) }
# Treat nils - such as service unavailable - as ALLOW
return ALLOW unless valid_verdicts.any?
# Favour the most restrictive verdict
final_verdict = valid_verdicts.min_by { |v| SUPPORTED_VERDICTS[v][:priority] }
# The target can override the verdict via the `allow_possible_spam` application setting
final_verdict = OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM if override_via_allow_possible_spam?(verdict: final_verdict)
logger.info(
class: self.class.name,
akismet_verdict: akismet_verdict,
spam_check_verdict: spamcheck_verdict,
spam_check_rtt: external_spam_check_round_trip_time.real,
final_verdict: final_verdict,
username: user.username,
user_id: user.id,
target_type: target.class.to_s,
project_id: target.project_id
)
final_verdict
end
private
attr_reader :user, :target, :options, :context, :extra_features
def get_akismet_verdict
if akismet.spam?
Gitlab::Recaptcha.enabled? ? CONDITIONAL_ALLOW : DISALLOW
else
ALLOW
end
end
def get_spamcheck_verdict
return unless Gitlab::CurrentSettings.spam_check_endpoint_enabled
begin
result = spamcheck_client.spam?(spammable: target, user: user, context: context, extra_features: extra_features)
if result.evaluated?
Abuse::TrustScore.create!(user: user, score: result.score, source: :spamcheck)
end
result.verdict
rescue StandardError => e
Gitlab::ErrorTracking.log_exception(e, error: ERROR_TYPE)
nil
end
end
def override_via_allow_possible_spam?(verdict:)
# If the verdict is already going to allow (because current verdict's priority value is greater
# than the override verdict's priority value), then we don't need to override it.
return false if SUPPORTED_VERDICTS[verdict][:priority] > SUPPORTED_VERDICTS[OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM][:priority]
allow_possible_spam?
end
def allow_possible_spam?
target.allow_possible_spam?(user) || user.trusted?
end
def spamcheck_client
@spamcheck_client ||= Gitlab::Spamcheck::Client.new
end
def logger
@logger ||= Gitlab::AppJsonLogger.build
end
def histogram
@histogram ||= Gitlab::Metrics.histogram(:gitlab_spamcheck_request_duration_seconds, 'Request duration to the anti-spam service')
end
end
end
Spam::SpamVerdictService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Spam::SpamVerdictService, feature_category: :instance_resiliency do
include_context 'includes Spam constants'
let(:fake_ip) { '1.2.3.4' }
let(:fake_user_agent) { 'fake-user-agent' }
let(:fake_referer) { 'fake-http-referer' }
let(:env) do
{ 'action_dispatch.remote_ip' => fake_ip,
'HTTP_USER_AGENT' => fake_user_agent,
'HTTP_REFERER' => fake_referer }
end
let(:verdict_value) { ::Spamcheck::SpamVerdict::Verdict::ALLOW }
let(:verdict_score) { 0.01 }
let(:verdict_evaluated) { true }
let(:response) do
response = ::Spamcheck::SpamVerdict.new
response.verdict = verdict_value
response.score = verdict_score
response.evaluated = verdict_evaluated
response
end
let(:spam_client_result) do
Gitlab::Spamcheck::Result.new(response)
end
let(:check_for_spam) { true }
let_it_be_with_reload(:user) { create(:user) }
let_it_be(:issue) { create(:issue, author: user) }
let_it_be(:snippet) { create(:personal_snippet, :public, author: user) }
let(:service) do
described_class.new(user: user, target: target, options: {})
end
shared_examples 'execute spam verdict service' do
subject(:execute) { service.execute }
before do
allow(service).to receive(:get_akismet_verdict).and_return(nil)
allow(service).to receive(:get_spamcheck_verdict).and_return(nil)
end
context 'if all services return nil' do
it 'renders ALLOW verdict' do
is_expected.to eq ALLOW
end
end
context 'if only one service returns a verdict' do
context 'and it is supported' do
before do
allow(service).to receive(:get_akismet_verdict).and_return(DISALLOW)
end
it 'renders that verdict' do
is_expected.to eq DISALLOW
end
end
context 'and it is unexpected' do
before do
allow(service).to receive(:get_akismet_verdict).and_return("unexpected")
end
it 'allows' do
is_expected.to eq ALLOW
end
end
end
context 'if more than one service returns a verdict' do
context 'and they are supported' do
before do
allow(service).to receive(:get_akismet_verdict).and_return(DISALLOW)
allow(service).to receive(:get_spamcheck_verdict).and_return(BLOCK_USER)
end
it 'renders the more restrictive verdict' do
is_expected.to eq BLOCK_USER
end
end
context 'and one is supported' do
before do
allow(service).to receive(:get_akismet_verdict).and_return('nonsense')
allow(service).to receive(:get_spamcheck_verdict).and_return(BLOCK_USER)
end
it 'renders the more restrictive verdict' do
is_expected.to eq BLOCK_USER
end
end
context 'and none are supported' do
before do
allow(service).to receive(:get_akismet_verdict).and_return('nonsense')
allow(service).to receive(:get_spamcheck_verdict).and_return('rubbish')
end
it 'renders the more restrictive verdict' do
is_expected.to eq ALLOW
end
end
end
context 'if allow_possible_spam application setting is true' do
before do
stub_application_setting(allow_possible_spam: true)
end
context 'and a service returns a verdict that should be overridden' do
before do
allow(service).to receive(:get_spamcheck_verdict).and_return(BLOCK_USER)
end
it 'overrides and renders the override verdict' do
is_expected.to eq OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM
end
end
context 'and a service returns a verdict that does not need to be overridden' do
before do
allow(service).to receive(:get_spamcheck_verdict).and_return(ALLOW)
end
it 'does not override and renders the original verdict' do
is_expected.to eq ALLOW
end
end
end
context 'if user is trusted to create possible spam' do
before do
user.custom_attributes.create!(key: 'trusted_by', value: 'does not matter')
end
context 'and a service returns a verdict that should be overridden' do
before do
allow(service).to receive(:get_spamcheck_verdict).and_return(BLOCK_USER)
end
it 'overrides and renders the override verdict' do
is_expected.to eq OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM
end
end
context 'and a service returns a verdict that does not need to be overridden' do
before do
allow(service).to receive(:get_spamcheck_verdict).and_return(ALLOW)
end
it 'does not override and renders the original verdict' do
is_expected.to eq ALLOW
end
end
end
context 'records metrics' do
let(:histogram) { instance_double(Prometheus::Client::Histogram) }
using RSpec::Parameterized::TableSyntax
where(:verdict, :label) do
Spam::SpamConstants::ALLOW | 'ALLOW'
Spam::SpamConstants::CONDITIONAL_ALLOW | 'CONDITIONAL_ALLOW'
Spam::SpamConstants::BLOCK_USER | 'BLOCK'
Spam::SpamConstants::DISALLOW | 'DISALLOW'
Spam::SpamConstants::NOOP | 'NOOP'
end
with_them do
before do
allow(Gitlab::Metrics).to receive(:histogram).with(:gitlab_spamcheck_request_duration_seconds, anything).and_return(histogram)
allow(service).to receive(:get_spamcheck_verdict).and_return(verdict)
end
it 'records duration with labels' do
expect(histogram).to receive(:observe).with(a_hash_including(result: label), anything)
execute
end
end
end
end
shared_examples 'akismet verdict' do
let(:target) { issue }
subject(:get_akismet_verdict) { service.send(:get_akismet_verdict) }
context 'if Akismet is enabled' do
before do
stub_application_setting(akismet_enabled: true)
allow_next_instance_of(Spam::AkismetService) do |service|
allow(service).to receive(:spam?).and_return(akismet_result)
end
end
context 'if Akismet considers it spam' do
let(:akismet_result) { true }
context 'if reCAPTCHA is enabled' do
before do
stub_application_setting(recaptcha_enabled: true)
end
it 'returns conditionally allow verdict' do
is_expected.to eq CONDITIONAL_ALLOW
end
end
context 'if reCAPTCHA is not enabled' do
before do
stub_application_setting(recaptcha_enabled: false)
end
it 'renders disallow verdict' do
is_expected.to eq DISALLOW
end
end
end
context 'if Akismet does not consider it spam' do
let(:akismet_result) { false }
it 'renders allow verdict' do
is_expected.to eq ALLOW
end
end
end
context 'if Akismet is not enabled' do
before do
stub_application_setting(akismet_enabled: false)
end
it 'renders allow verdict' do
is_expected.to eq ALLOW
end
end
end
shared_examples 'spamcheck verdict' do
subject(:get_spamcheck_verdict) { service.send(:get_spamcheck_verdict) }
context 'if a Spam Check endpoint enabled and set to a URL' do
let(:spam_check_body) { {} }
let(:endpoint_url) { "grpc://www.spamcheckurl.com/spam_check" }
let(:spam_client) do
Gitlab::Spamcheck::Client.new
end
before do
stub_application_setting(spam_check_endpoint_enabled: true)
stub_application_setting(spam_check_endpoint_url: endpoint_url)
end
context 'if the endpoint is accessible' do
let(:user_scores) { Abuse::UserTrustScore.new(user) }
before do
allow(service).to receive(:spamcheck_client).and_return(spam_client)
allow(spam_client).to receive(:spam?).and_return(spam_client_result)
end
context 'if the result is a NOOP verdict' do
let(:verdict_evaluated) { false }
let(:verdict_value) { ::Spamcheck::SpamVerdict::Verdict::NOOP }
it 'returns the verdict' do
is_expected.to eq(NOOP)
expect(user_scores.spam_score).to eq(0.0)
end
end
context 'the result is a valid verdict' do
let(:verdict_score) { 0.05 }
let(:verdict_value) { ::Spamcheck::SpamVerdict::Verdict::ALLOW }
context 'the result was evaluated' do
it 'returns the verdict and updates the spam score' do
is_expected.to eq(ALLOW)
expect(user_scores.spam_score).to be_within(0.000001).of(verdict_score)
end
end
context 'the result was not evaluated' do
let(:verdict_evaluated) { false }
it 'returns the verdict and does not update the spam score' do
expect(subject).to eq(ALLOW)
expect(user_scores.spam_score).to eq(0.0)
end
end
end
context 'when recaptcha is enabled' do
before do
allow(Gitlab::Recaptcha).to receive(:enabled?).and_return(true)
end
using RSpec::Parameterized::TableSyntax
where(:verdict_value, :expected, :verdict_score) do
::Spamcheck::SpamVerdict::Verdict::ALLOW | ::Spam::SpamConstants::ALLOW | 0.1
::Spamcheck::SpamVerdict::Verdict::CONDITIONAL_ALLOW | ::Spam::SpamConstants::CONDITIONAL_ALLOW | 0.5
::Spamcheck::SpamVerdict::Verdict::DISALLOW | ::Spam::SpamConstants::DISALLOW | 0.8
::Spamcheck::SpamVerdict::Verdict::BLOCK | ::Spam::SpamConstants::BLOCK_USER | 0.9
end
with_them do
it "returns expected spam constant and updates the spam score" do
is_expected.to eq(expected)
expect(user_scores.spam_score).to be_within(0.000001).of(verdict_score)
end
end
end
context 'when recaptcha is disabled' do
before do
allow(Gitlab::Recaptcha).to receive(:enabled?).and_return(false)
end
using RSpec::Parameterized::TableSyntax
where(:verdict_value, :expected) do
::Spamcheck::SpamVerdict::Verdict::ALLOW | ::Spam::SpamConstants::ALLOW
::Spamcheck::SpamVerdict::Verdict::CONDITIONAL_ALLOW | ::Spam::SpamConstants::CONDITIONAL_ALLOW
::Spamcheck::SpamVerdict::Verdict::DISALLOW | ::Spam::SpamConstants::DISALLOW
::Spamcheck::SpamVerdict::Verdict::BLOCK | ::Spam::SpamConstants::BLOCK_USER
end
with_them do
it "returns expected spam constant" do
is_expected.to eq(expected)
end
end
end
context 'the requested is aborted' do
before do
allow(spam_client).to receive(:spam?).and_raise(GRPC::Aborted)
end
it 'returns nil' do
expect(Gitlab::ErrorTracking).to receive(:log_exception).with(
an_instance_of(GRPC::Aborted), error: ::Spam::SpamConstants::ERROR_TYPE
)
is_expected.to be_nil
end
end
context 'if the endpoint times out' do
before do
allow(spam_client).to receive(:spam?).and_raise(GRPC::DeadlineExceeded)
end
it 'returns nil' do
expect(Gitlab::ErrorTracking).to receive(:log_exception).with(
an_instance_of(GRPC::DeadlineExceeded), error: ::Spam::SpamConstants::ERROR_TYPE
)
is_expected.to be_nil
end
end
end
end
context 'if a Spam Check endpoint is not set' do
before do
stub_application_setting(spam_check_endpoint_url: nil)
end
it 'returns nil' do
is_expected.to be_nil
end
end
context 'if Spam Check endpoint is not enabled' do
before do
stub_application_setting(spam_check_endpoint_enabled: false)
end
it 'returns nil' do
is_expected.to be_nil
end
end
end
describe '#execute' do
describe 'issue' do
let(:target) { issue }
context 'when issue is publicly visible' do
before do
allow(issue).to receive(:publicly_visible?).and_return(true)
end
it_behaves_like 'execute spam verdict service'
end
context 'when issue is not publicly visible' do
before do
allow(issue).to receive(:publicly_visible?).and_return(false)
allow(service).to receive(:get_spamcheck_verdict).and_return(BLOCK_USER)
end
it 'overrides and renders the override verdict' do
expect(service.execute).to eq OVERRIDE_VIA_ALLOW_POSSIBLE_SPAM
end
end
end
describe 'snippet' do
let(:target) { snippet }
it_behaves_like 'execute spam verdict service'
end
end
describe '#get_akismet_verdict' do
describe 'issue' do
let(:target) { issue }
it_behaves_like 'akismet verdict'
end
describe 'snippet' do
let(:target) { snippet }
it_behaves_like 'akismet verdict'
end
end
describe '#get_spamcheck_verdict' do
describe 'issue' do
let(:target) { issue }
it_behaves_like 'spamcheck verdict'
end
describe 'snippet' do
let(:target) { snippet }
it_behaves_like 'spamcheck verdict'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Spam
class AkismetMarkAsSpamService
include ::AkismetMethods
attr_accessor :target, :options
def initialize(target:)
@target = target
@options = {}
end
def execute
@options[:ip_address] = @target.ip_address
@options[:user_agent] = @target.user_agent
return unless target.submittable_as_spam?
return unless akismet.submit_spam
target.user_agent_detail.update_attribute(:submitted, true)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Spam::AkismetMarkAsSpamService, feature_category: :instance_resiliency do
let(:user_agent_detail) { build(:user_agent_detail) }
let(:spammable) { build(:issue, user_agent_detail: user_agent_detail) }
let(:fake_akismet_service) { double(:akismet_service, submit_spam: true) }
subject { described_class.new(target: spammable) }
describe '#execute' do
before do
allow(subject).to receive(:akismet).and_return(fake_akismet_service)
end
context 'when the spammable object is not submittable' do
before do
allow(spammable).to receive(:submittable_as_spam?).and_return false
end
it 'does not submit as spam' do
expect(subject.execute).to be_falsey
end
end
context 'spam is submitted successfully' do
before do
allow(spammable).to receive(:submittable_as_spam?).and_return true
allow(fake_akismet_service).to receive(:submit_spam).and_return true
end
it 'submits as spam' do
expect(subject.execute).to be_truthy
end
it "updates the spammable object's user agent detail as being submitted as spam" do
expect(user_agent_detail).to receive(:update_attribute)
subject.execute
end
context 'when Akismet does not consider it spam' do
it 'does not update the spammable object as spam' do
allow(fake_akismet_service).to receive(:submit_spam).and_return false
expect(subject.execute).to be_falsey
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Spam
##
# This class is a Parameter Object (https://refactoring.com/catalog/introduceParameterObject.html)
# which acts as an container abstraction for multiple values related to spam and
# captcha processing for a provided HTTP request object.
#
# It is used to encapsulate these values and allow them to be passed from the Controller/GraphQL
# layers down into to the Service layer, without needing to pass the entire request and therefore
# unnecessarily couple the Service layer to the HTTP request.
#
# Values contained are:
#
# captcha_response: The response resulting from the user solving a captcha. Currently it is
# a scalar reCAPTCHA response string, but it can be expanded to an object in the future to
# support other captcha implementations such as FriendlyCaptcha. Obtained from
# request.headers['X-GitLab-Captcha-Response']
# spam_log_id: The id of a SpamLog record. Obtained from request.headers['X-GitLab-Spam-Log-Id']
# ip_address = The remote IP. Obtained from request.env['action_dispatch.remote_ip']
# user_agent = The user agent. Obtained from request.env['HTTP_USER_AGENT']
# referer = The HTTP referer. Obtained from request.env['HTTP_REFERER']
#
# NOTE: The presence of these values in the request is not currently enforced. If they are missing,
# then the spam check may fail, or the SpamLog or UserAgentDetail may have missing fields.
class SpamParams
def self.new_from_request(request:)
self.normalize_grape_request_headers(request: request)
self.new(
captcha_response: request.headers['X-GitLab-Captcha-Response'],
spam_log_id: request.headers['X-GitLab-Spam-Log-Id'],
ip_address: request.env['action_dispatch.remote_ip'].to_s,
user_agent: request.env['HTTP_USER_AGENT'],
referer: request.env['HTTP_REFERER']
)
end
attr_reader :captcha_response, :spam_log_id, :ip_address, :user_agent, :referer
def initialize(captcha_response:, spam_log_id:, ip_address:, user_agent:, referer:)
@captcha_response = captcha_response
@spam_log_id = spam_log_id
@ip_address = ip_address
@user_agent = user_agent
@referer = referer
end
def ==(other)
other.class <= self.class &&
other.captcha_response == captcha_response &&
other.spam_log_id == spam_log_id &&
other.ip_address == ip_address &&
other.user_agent == user_agent &&
other.referer == referer
end
def self.normalize_grape_request_headers(request:)
# If needed, make a normalized copy of Grape headers with the case of 'GitLab' (with an
# uppercase 'L') instead of 'Gitlab' (with a lowercase 'l'), because Grape header helper keys
# are "coerced into a capitalized kebab case". See https://github.com/ruby-grape/grape#request
%w[X-Gitlab-Captcha-Response X-Gitlab-Spam-Log-Id].each do |header|
request.headers[header.gsub('Gitlab', 'GitLab')] = request.headers[header] if request.headers.key?(header)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Spam::SpamParams, feature_category: :instance_resiliency do
shared_examples 'constructs from a request' do
it 'constructs from a request' do
expected = ::Spam::SpamParams.new(
captcha_response: captcha_response,
spam_log_id: spam_log_id,
ip_address: ip_address,
user_agent: user_agent,
referer: referer
)
expect(described_class.new_from_request(request: request)).to eq(expected)
end
end
describe '.new_from_request' do
let(:captcha_response) { 'abc123' }
let(:spam_log_id) { 42 }
let(:ip_address) { '0.0.0.0' }
let(:user_agent) { 'Lynx' }
let(:referer) { 'http://localhost' }
let(:env) do
{
'action_dispatch.remote_ip' => ip_address,
'HTTP_USER_AGENT' => user_agent,
'HTTP_REFERER' => referer
}
end
let(:request) { double(:request, headers: headers, env: env) }
context 'with a normal Rails request' do
let(:headers) do
{
'X-GitLab-Captcha-Response' => captcha_response,
'X-GitLab-Spam-Log-Id' => spam_log_id
}
end
it_behaves_like 'constructs from a request'
end
context 'with a grape request' do
let(:headers) do
{
'X-Gitlab-Captcha-Response' => captcha_response,
'X-Gitlab-Spam-Log-Id' => spam_log_id
}
end
it_behaves_like 'constructs from a request'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
class CreateEvidenceService
def initialize(release, pipeline: nil)
@release = release
@pipeline = pipeline
end
def execute
evidence = release.evidences.build
summary = ::Evidences::EvidenceSerializer.new.represent(evidence, evidence_options) # rubocop: disable CodeReuse/Serializer
evidence.summary = summary
# TODO: fix the sha generation https://gitlab.com/groups/gitlab-org/-/epics/3683
evidence.summary_sha = Gitlab::CryptoHelper.sha256(summary)
evidence.save!
end
private
attr_reader :release, :pipeline
def evidence_options
{}
end
end
end
Releases::CreateEvidenceService.prepend_mod_with('Releases::CreateEvidenceService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::CreateEvidenceService, feature_category: :release_orchestration do
let_it_be(:project) { create(:project) }
let(:release) { create(:release, project: project) }
let(:service) { described_class.new(release) }
it 'creates evidence' do
expect { service.execute }.to change { release.reload.evidences.count }.by(1)
end
it 'saves evidence summary' do
service.execute
evidence = Releases::Evidence.last
expect(release.tag).not_to be_nil
expect(evidence.summary["release"]["tag_name"]).to eq(release.tag)
end
it 'saves sha' do
service.execute
evidence = Releases::Evidence.last
expect(evidence.summary_sha).not_to be_nil
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
class DestroyService < Releases::BaseService
def execute
return error(_('Release does not exist'), 404) unless release
return error(_('Access Denied'), 403) unless allowed?
if release.destroy
update_catalog_resource!
execute_hooks(release, 'delete')
audit(release, action: :deleted)
success(tag: existing_tag, release: release)
else
error(release.errors.messages || '400 Bad request', 400)
end
end
private
def update_catalog_resource!
return unless project.catalog_resource
return unless project.catalog_resource.versions.none?
project.catalog_resource.update!(state: 'draft')
end
def allowed?
Ability.allowed?(current_user, :destroy_release, release)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::DestroyService, feature_category: :release_orchestration do
let(:project) { create(:project, :repository) }
let(:mainatiner) { create(:user) }
let(:repoter) { create(:user) }
let(:tag) { 'v1.1.0' }
let!(:release) { create(:release, project: project, tag: tag) }
let(:service) { described_class.new(project, user, params) }
let(:params) { { tag: tag } }
let(:user) { mainatiner }
before do
project.add_maintainer(mainatiner)
project.add_reporter(repoter)
end
describe '#execute' do
subject { service.execute }
context 'when there is a release' do
it 'removes the release' do
expect { subject }.to change { project.releases.count }.by(-1)
end
it 'returns the destroyed object' do
is_expected.to include(status: :success, release: release)
end
context 'when the release is for a catalog resource' do
let!(:catalog_resource) { create(:ci_catalog_resource, :published, project: project) }
let!(:version) { create(:ci_catalog_resource_version, catalog_resource: catalog_resource, release: release) }
it 'does not update the catalog resources if there are still releases' do
second_release = create(:release, project: project, tag: 'v1.2.0')
create(:ci_catalog_resource_version, catalog_resource: catalog_resource, release: second_release)
subject
expect(catalog_resource.reload.state).to eq('published')
end
it 'updates the catalog resource if there are no more releases' do
subject
expect(catalog_resource.reload.state).to eq('draft')
end
end
end
context 'when tag does not exist in the repository' do
let(:tag) { 'v1.1.1' }
it 'removes the orphaned release' do
expect { subject }.to change { project.releases.count }.by(-1)
end
end
context 'when release is not found' do
let!(:release) {}
it 'returns an error' do
is_expected.to include(status: :error, message: 'Release does not exist', http_status: 404)
end
end
context 'when user does not have permission' do
let(:user) { repoter }
it 'returns an error' do
is_expected.to include(status: :error, message: 'Access Denied', http_status: 403)
end
end
context 'when a milestone is tied to the release' do
let!(:milestone) { create(:milestone, :active, project: project, title: 'v1.0') }
let!(:release) { create(:release, milestones: [milestone], project: project, tag: tag) }
it 'destroys the release but leave the milestone intact' do
expect { subject }.not_to change { Milestone.count }
expect(milestone.reload).to be_persisted
end
end
it 'executes hooks' do
expect(service.release).to receive(:execute_hooks).with('delete')
service.execute
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
class UpdateService < Releases::BaseService
def execute
if error = validate
return error
end
if param_for_milestones_provided?
previous_milestones = release.milestones.map(&:id)
params[:milestones] = milestones
end
# transaction needed as Rails applies `save!` to milestone_releases
# when it does assign_attributes instead of actual saving
# this leads to the validation error being raised
# see https://gitlab.com/gitlab-org/gitlab/-/merge_requests/43385
ApplicationRecord.transaction do
if release.update(params)
execute_hooks(release, 'update')
audit(release, action: :updated)
audit(release, action: :milestones_updated) if milestones_updated?(previous_milestones)
success(tag: existing_tag, release: release, milestones_updated: milestones_updated?(previous_milestones))
else
error(release.errors.messages || '400 Bad request', 400)
end
rescue ActiveRecord::RecordInvalid => e
error(e.message || '400 Bad request', 400)
end
end
private
def validate
return error(_('Tag does not exist'), 404) unless existing_tag
return error(_('Release does not exist'), 404) unless release
return error(_('Access Denied'), 403) unless allowed?
return error(_('params is empty'), 400) if empty_params?
return error(format(_("Milestone(s) not found: %{milestones}"), milestones: inexistent_milestone_titles.join(', ')), 400) if inexistent_milestone_titles.any? # rubocop:disable Layout/LineLength
return error(format(_("Milestone id(s) not found: %{milestones}"), milestones: inexistent_milestone_ids.join(', ')), 400) if inexistent_milestone_ids.any? # rubocop:disable Layout/LineLength
end
def allowed?
Ability.allowed?(current_user, :update_release, release)
end
def empty_params?
params.except(:tag).empty?
end
def milestones_updated?(previous_milestones)
return false unless param_for_milestones_provided?
previous_milestones.to_set != release.milestones.map(&:id)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::UpdateService, feature_category: :continuous_integration do
let(:project) { create(:project, :repository) }
let(:user) { create(:user) }
let(:new_name) { 'A new name' }
let(:new_description) { 'The best release!' }
let(:params) { { name: new_name, description: new_description, tag: tag_name } }
let(:service) { described_class.new(project, user, params) }
let!(:release) { create(:release, project: project, author: user, tag: tag_name) }
let(:tag_name) { 'v1.1.0' }
before do
project.add_developer(user)
end
describe '#execute' do
shared_examples 'a failed update' do
it 'raises an error' do
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:milestones_updated]).to be_falsy
end
end
it 'successfully updates an existing release' do
result = service.execute
expect(result[:status]).to eq(:success)
expect(result[:release].name).to eq(new_name)
expect(result[:release].description).to eq(new_description)
end
it 'executes hooks' do
expect(service.release).to receive(:execute_hooks).with('update')
service.execute
end
context 'when the tag does not exists' do
let(:tag_name) { 'foobar' }
it_behaves_like 'a failed update'
end
context 'when the release does not exist' do
let!(:release) {}
it_behaves_like 'a failed update'
end
context 'when a milestone is passed in' do
let(:milestone) { create(:milestone, project: project, title: 'v1.0') }
let(:params_with_milestone) { params.merge!({ milestones: [new_title] }) }
let(:new_milestone) { create(:milestone, project: project, title: new_title) }
let(:service) { described_class.new(new_milestone.project, user, params_with_milestone) }
before do
release.milestones << milestone
end
shared_examples 'updates milestones' do
it 'updates the related milestone accordingly' do
release.reload
result = service.execute
expect(release.milestones.first.title).to eq(new_title)
expect(result[:milestones_updated]).to be_truthy
end
end
context 'a different milestone' do
let(:new_title) { 'v2.0' }
it_behaves_like 'updates milestones'
end
context 'an identical milestone' do
let(:new_title) { 'v1.0' }
it "raises an error" do
expect { service.execute }.to raise_error(ActiveRecord::RecordInvalid)
end
end
context 'by ids' do
let(:new_title) { 'v2.0' }
let(:params_with_milestone) { params.merge!({ milestone_ids: [new_milestone.id] }) }
it_behaves_like 'updates milestones'
end
end
context "when an 'empty' milestone is passed in" do
let(:milestone) { create(:milestone, project: project, title: 'v1.0') }
before do
release.milestones << milestone
service.params = params_with_empty_milestone
end
shared_examples 'removes milestones' do
it 'removes the old milestone and does not associate any new milestone' do
result = service.execute
release.reload
expect(release.milestones).not_to be_present
expect(result[:milestones_updated]).to be_truthy
end
end
context 'by title' do
let(:params_with_empty_milestone) { params.merge!({ milestones: [] }) }
it_behaves_like 'removes milestones'
end
context 'by id' do
let(:params_with_empty_milestone) { params.merge!({ milestone_ids: [] }) }
it_behaves_like 'removes milestones'
end
end
context "when multiple new milestones are passed in" do
let(:new_title_1) { 'v2.0' }
let(:new_title_2) { 'v2.0-rc' }
let(:milestone) { create(:milestone, project: project, title: 'v1.0') }
let(:service) { described_class.new(project, user, params_with_milestones) }
let!(:new_milestone_1) { create(:milestone, project: project, title: new_title_1) }
let!(:new_milestone_2) { create(:milestone, project: project, title: new_title_2) }
before do
release.milestones << milestone
end
shared_examples 'updates multiple milestones' do
it 'removes the old milestone and update the release with the new ones' do
result = service.execute
release.reload
milestone_titles = release.milestones.map(&:title)
expect(milestone_titles).to match_array([new_title_1, new_title_2])
expect(result[:milestones_updated]).to be_truthy
end
end
context 'by title' do
let(:params_with_milestones) { params.merge!({ milestones: [new_title_1, new_title_2] }) }
it_behaves_like 'updates multiple milestones'
end
context 'by id' do
let(:params_with_milestones) { params.merge!({ milestone_ids: [new_milestone_1.id, new_milestone_2.id] }) }
it_behaves_like 'updates multiple milestones'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
class CreateService < Releases::BaseService
def execute
return error(_('Access Denied'), 403) unless allowed?
return error(_('You are not allowed to create this tag as it is protected.'), 403) unless can_create_tag?
return error(_('Release already exists'), 409) if release
return error(format(_("Milestone(s) not found: %{milestones}"), milestones: inexistent_milestone_titles.join(', ')), 400) if inexistent_milestone_titles.any? # rubocop:disable Layout/LineLength
return error(format(_("Milestone id(s) not found: %{milestones}"), milestones: inexistent_milestone_ids.join(', ')), 400) if inexistent_milestone_ids.any? # rubocop:disable Layout/LineLength
# should be found before the creation of new tag
# because tag creation can spawn new pipeline
# which won't have any data for evidence yet
evidence_pipeline = Releases::EvidencePipelineFinder.new(project, params).execute
tag = ensure_tag
return tag unless tag.is_a?(Gitlab::Git::Tag)
create_release(tag, evidence_pipeline)
end
private
def ensure_tag
existing_tag || create_tag
end
def create_tag
return error('Ref is not specified', 422) unless ref
result = Tags::CreateService
.new(project, current_user)
.execute(tag_name, ref, tag_message)
return result unless result[:status] == :success
result[:tag]
end
def allowed?
Ability.allowed?(current_user, :create_release, project)
end
def can_create_tag?
::Gitlab::UserAccess.new(current_user, container: project).can_create_tag?(tag_name)
end
def create_release(tag, evidence_pipeline)
release = build_release(tag)
if project.catalog_resource && release.valid?
response = Ci::Catalog::Resources::ReleaseService.new(release).execute
return error(response.message, 422) if response.error?
end
release.save!
notify_create_release(release)
execute_hooks(release, 'create')
create_evidence!(release, evidence_pipeline)
audit(release, action: :created)
success(tag: tag, release: release)
rescue StandardError => e
error(e.message, 400)
end
def notify_create_release(release)
NotificationService.new.async.send_new_release_notifications(release)
end
def build_release(tag)
project.releases.build(
name: name,
description: description,
author: current_user,
tag: tag.name,
sha: tag.dereferenced_target.sha,
released_at: released_at,
links_attributes: links_attributes,
milestones: milestones
)
end
def links_attributes
(params.dig(:assets, 'links') || []).map do |link_params|
Releases::Links::Params.new(link_params).allowed_params
end
end
def create_evidence!(release, pipeline)
return if release.historical_release? || release.upcoming_release?
::Releases::CreateEvidenceWorker.perform_async(release.id, pipeline&.id)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::CreateService, feature_category: :continuous_integration do
let(:project) { create(:project, :repository) }
let(:user) { create(:user) }
let(:tag_name) { project.repository.tag_names.first }
let(:tag_message) { nil }
let(:tag_sha) { project.repository.find_tag(tag_name).dereferenced_target.sha }
let(:name) { 'Bionic Beaver' }
let(:description) { 'Awesome release!' }
let(:params) { { tag: tag_name, name: name, description: description, ref: ref, tag_message: tag_message } }
let(:ref) { nil }
let(:service) { described_class.new(project, user, params) }
before do
project.add_maintainer(user)
end
describe '#execute' do
shared_examples 'a successful release creation' do
it 'creates a new release' do
expected_job_count = MailScheduler::NotificationServiceWorker.jobs.size + 1
expect_next_instance_of(Release) do |release|
expect(release)
.to receive(:execute_hooks)
.with('create')
end
result = service.execute
expect(project.releases.count).to eq(1)
expect(result[:status]).to eq(:success)
expect(result[:tag]).not_to be_nil
expect(result[:release]).not_to be_nil
expect(result[:release].description).to eq(description)
expect(result[:release].name).to eq(name)
expect(result[:release].author).to eq(user)
expect(result[:release].sha).to eq(tag_sha)
expect(MailScheduler::NotificationServiceWorker.jobs.size).to eq(expected_job_count)
end
end
it_behaves_like 'a successful release creation'
context 'when the tag does not exist' do
let(:tag_name) { 'non-exist-tag' }
it 'raises an error' do
result = service.execute
expect(result[:status]).to eq(:error)
end
end
context 'when project is a catalog resource' do
let(:project) { create(:project, :catalog_resource_with_components, create_tag: 'final') }
let!(:ci_catalog_resource) { create(:ci_catalog_resource, project: project) }
let(:ref) { 'master' }
context 'and it is valid' do
it_behaves_like 'a successful release creation'
end
context 'and it is an invalid resource' do
let_it_be(:project) { create(:project, :repository) }
it 'raises an error and does not update the release' do
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:http_status]).to eq(422)
expect(result[:message]).to eq(
'Project must have a description, ' \
'Project must contain components. Ensure you are using the correct directory structure')
end
end
end
context 'when ref is provided' do
let(:ref) { 'master' }
let(:tag_name) { 'foobar' }
it_behaves_like 'a successful release creation'
it 'creates a tag if the tag does not exist' do
expect(project.repository.ref_exists?("refs/tags/#{tag_name}")).to be_falsey
result = service.execute
expect(result[:status]).to eq(:success)
expect(result[:tag]).not_to be_nil
expect(result[:release]).not_to be_nil
end
context 'and the tag would be protected' do
let!(:protected_tag) { create(:protected_tag, project: project, name: tag_name) }
context 'and the user does not have permissions' do
let(:user) { create(:user) }
before do
project.add_developer(user)
end
it 'raises an error' do
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:http_status]).to eq(403)
end
end
context 'and the user has permissions' do
it_behaves_like 'a successful release creation'
end
end
context 'and tag_message is provided' do
let(:ref) { 'master' }
let(:tag_name) { 'foobar' }
let(:tag_message) { 'Annotated tag message' }
it_behaves_like 'a successful release creation'
it 'creates a tag if the tag does not exist' do
expect(project.repository.ref_exists?("refs/tags/#{tag_name}")).to be_falsey
result = service.execute
expect(result[:status]).to eq(:success)
expect(result[:tag]).not_to be_nil
expect(result[:release]).not_to be_nil
expect(project.repository.find_tag(tag_name).message).to eq(tag_message)
end
end
end
context 'there already exists a release on a tag' do
let!(:release) do
create(:release, project: project, tag: tag_name, description: description)
end
it 'raises an error and does not update the release' do
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:http_status]).to eq(409)
expect(project.releases.find_by(tag: tag_name).description).to eq(description)
end
end
context 'when a passed-in milestone does not exist for this project' do
it 'raises an error saying the milestone is inexistent' do
inexistent_milestone_tag = 'v111.0'
service = described_class.new(project, user, params.merge!({ milestones: [inexistent_milestone_tag] }))
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:http_status]).to eq(400)
expect(result[:message]).to eq("Milestone(s) not found: #{inexistent_milestone_tag}")
end
it 'raises an error saying the milestone id is inexistent' do
inexistent_milestone_id = non_existing_record_id
service = described_class.new(project, user, params.merge!({ milestone_ids: [inexistent_milestone_id] }))
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:http_status]).to eq(400)
expect(result[:message]).to eq("Milestone id(s) not found: #{inexistent_milestone_id}")
end
end
context 'when existing milestone is passed in' do
let(:title) { 'v1.0' }
let(:milestone) { create(:milestone, :active, project: project, title: title) }
let(:params_with_milestone) { params.merge!({ milestones: [title] }) }
let(:service) { described_class.new(milestone.project, user, params_with_milestone) }
shared_examples 'creates release' do
it 'creates a release and ties this milestone to it' do
result = service.execute
expect(project.releases.count).to eq(1)
expect(result[:status]).to eq(:success)
release = project.releases.last
expect(release.milestones).to match_array([milestone])
end
end
context 'by title' do
it_behaves_like 'creates release'
end
context 'by ids' do
let(:params_with_milestone) { params.merge!({ milestone_ids: [milestone.id] }) }
it_behaves_like 'creates release'
end
context 'when another release was previously created with that same milestone linked' do
it 'also creates another release tied to that same milestone' do
other_release = create(:release, milestones: [milestone], project: project, tag: 'v1.0')
service.execute
release = project.releases.last
expect(release.milestones).to match_array([milestone])
expect(other_release.milestones).to match_array([milestone])
expect(release.id).not_to eq(other_release.id)
end
end
end
context 'when multiple existing milestones are passed in' do
let(:title_1) { 'v1.0' }
let(:title_2) { 'v1.0-rc' }
let!(:milestone_1) { create(:milestone, :active, project: project, title: title_1) }
let!(:milestone_2) { create(:milestone, :active, project: project, title: title_2) }
shared_examples 'creates multiple releases' do
it 'creates a release and ties it to these milestones' do
described_class.new(project, user, params_with_milestones).execute
release = project.releases.last
expect(release.milestones.map(&:title)).to include(title_1, title_2)
end
end
context 'by title' do
let!(:params_with_milestones) { params.merge!({ milestones: [title_1, title_2] }) }
it_behaves_like 'creates multiple releases'
end
context 'by ids' do
let!(:params_with_milestones) { params.merge!({ milestone_ids: [milestone_1.id, milestone_2.id] }) }
it_behaves_like 'creates multiple releases'
end
end
context 'when multiple milestone titles are passed in but one of them does not exist' do
let(:title) { 'v1.0' }
let(:inexistent_title) { 'v111.0' }
let!(:milestone) { create(:milestone, :active, project: project, title: title) }
let!(:params_with_milestones) { params.merge!({ milestones: [title, inexistent_title] }) }
let(:service) { described_class.new(milestone.project, user, params_with_milestones) }
it 'raises an error' do
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:http_status]).to eq(400)
expect(result[:message]).to eq("Milestone(s) not found: #{inexistent_title}")
end
it 'does not create any release' do
expect do
service.execute
end.not_to change(Release, :count)
end
context 'with milestones as ids' do
let!(:params_with_milestones) { params.merge!({ milestone_ids: [milestone.id, non_existing_record_id] }) }
it 'raises an error' do
result = service.execute
expect(result[:status]).to eq(:error)
expect(result[:http_status]).to eq(400)
expect(result[:message]).to eq("Milestone id(s) not found: #{non_existing_record_id}")
end
end
end
context 'no milestone association behavior' do
let(:title_1) { 'v1.0' }
let(:title_2) { 'v1.0-rc' }
let!(:milestone_1) { create(:milestone, :active, project: project, title: title_1) }
let!(:milestone_2) { create(:milestone, :active, project: project, title: title_2) }
context 'when no milestones parameter is passed' do
it 'creates a release without a milestone tied to it' do
expect(service.param_for_milestone_titles_provided?).to be_falsey
service.execute
release = project.releases.last
expect(release.milestones).to be_empty
end
it 'does not create any new MilestoneRelease object' do
expect { service.execute }.not_to change { MilestoneRelease.count }
end
end
context 'when an empty array is passed as the milestones parameter' do
it 'creates a release without a milestone tied to it' do
service = described_class.new(project, user, params.merge!({ milestones: [] }))
service.execute
release = project.releases.last
expect(release.milestones).to be_empty
end
end
context 'when nil is passed as the milestones parameter' do
it 'creates a release without a milestone tied to it' do
expect(service.param_for_milestone_titles_provided?).to be_falsey
service = described_class.new(project, user, params.merge!({ milestones: nil }))
service.execute
release = project.releases.last
expect(release.milestones).to be_empty
end
end
end
end
context 'Evidence collection' do
let(:sha) { project.repository.commit('master').sha }
let(:params) do
{
name: 'New release',
ref: 'master',
tag: 'v0.1',
description: 'Super nice release',
released_at: released_at
}.compact
end
let(:last_release) { project.releases.last }
around do |example|
freeze_time { example.run }
end
subject { service.execute }
context 'historical release' do
let(:released_at) { 3.weeks.ago }
it 'does not execute CreateEvidenceWorker' do
expect { subject }.not_to change(Releases::CreateEvidenceWorker.jobs, :size)
end
it 'does not create an Evidence object', :sidekiq_inline do
expect { subject }.not_to change(Releases::Evidence, :count)
end
it 'is a historical release' do
subject
expect(last_release.historical_release?).to be_truthy
end
it 'is not an upcoming release' do
subject
expect(last_release.upcoming_release?).to be_falsy
end
end
shared_examples 'uses the right pipeline for evidence' do
it 'creates evidence without pipeline if it does not exist', :sidekiq_inline do
expect_next_instance_of(Releases::CreateEvidenceService, anything, pipeline: nil) do |service|
expect(service).to receive(:execute).and_call_original
end
expect { subject }.to change(Releases::Evidence, :count).by(1)
end
it 'uses the last pipeline for evidence', :sidekiq_inline do
create(:ci_empty_pipeline, sha: sha, project: project) # old pipeline
pipeline = create(:ci_empty_pipeline, sha: sha, project: project)
expect_next_instance_of(Releases::CreateEvidenceService, anything, pipeline: pipeline) do |service|
expect(service).to receive(:execute).and_call_original
end
expect { subject }.to change(Releases::Evidence, :count).by(1)
end
context 'when old evidence_pipeline is passed to service' do
let!(:old_pipeline) { create(:ci_empty_pipeline, sha: sha, project: project) }
let!(:new_pipeline) { create(:ci_empty_pipeline, sha: sha, project: project) }
let(:params) do
super().merge(
evidence_pipeline: old_pipeline
)
end
it 'uses the old pipeline for evidence', :sidekiq_inline do
expect_next_instance_of(Releases::CreateEvidenceService, anything, pipeline: old_pipeline) do |service|
expect(service).to receive(:execute).and_call_original
end
expect { subject }.to change(Releases::Evidence, :count).by(1)
end
end
it 'pipeline is still being used for evidence if new pipeline is being created for tag', :sidekiq_inline do
pipeline = create(:ci_empty_pipeline, sha: sha, project: project)
expect(project.repository).to receive(:add_tag).and_wrap_original do |m, *args|
create(:ci_empty_pipeline, sha: sha, project: project)
m.call(*args)
end
expect_next_instance_of(Releases::CreateEvidenceService, anything, pipeline: pipeline) do |service|
expect(service).to receive(:execute).and_call_original
end
expect { subject }.to change(Releases::Evidence, :count).by(1)
end
it 'uses the last pipeline for evidence when tag is already created', :sidekiq_inline do
Tags::CreateService.new(project, user).execute('v0.1', 'master', nil)
expect(project.repository.find_tag('v0.1')).to be_present
create(:ci_empty_pipeline, sha: sha, project: project) # old pipeline
pipeline = create(:ci_empty_pipeline, sha: sha, project: project)
expect_next_instance_of(Releases::CreateEvidenceService, anything, pipeline: pipeline) do |service|
expect(service).to receive(:execute).and_call_original
end
expect { subject }.to change(Releases::Evidence, :count).by(1)
end
end
context 'immediate release' do
let(:released_at) { nil }
it 'sets `released_at` to the current dttm' do
subject
expect(last_release.updated_at).to be_like_time(Time.current)
end
it 'queues CreateEvidenceWorker' do
expect { subject }.to change(Releases::CreateEvidenceWorker.jobs, :size).by(1)
end
it 'creates Evidence', :sidekiq_inline do
expect { subject }.to change(Releases::Evidence, :count).by(1)
end
it 'is not a historical release' do
subject
expect(last_release.historical_release?).to be_falsy
end
it 'is not an upcoming release' do
subject
expect(last_release.upcoming_release?).to be_falsy
end
include_examples 'uses the right pipeline for evidence'
end
context 'upcoming release' do
let(:released_at) { 1.day.from_now }
it 'does not execute CreateEvidenceWorker' do
expect { subject }.not_to change(Releases::CreateEvidenceWorker.jobs, :size)
end
it 'does not create an Evidence object', :sidekiq_inline do
expect { subject }.not_to change(Releases::Evidence, :count)
end
it 'is not a historical release' do
subject
expect(last_release.historical_release?).to be_falsy
end
it 'is an upcoming release' do
subject
expect(last_release.upcoming_release?).to be_truthy
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
module Links
class DestroyService < BaseService
def execute(link)
return ServiceResponse.error(reason: REASON_FORBIDDEN, message: _('Access Denied')) unless allowed?
return ServiceResponse.error(reason: REASON_NOT_FOUND, message: _('Link does not exist')) unless link
if link.destroy
ServiceResponse.success(payload: { link: link })
else
ServiceResponse.error(reason: REASON_BAD_REQUEST, message: link.errors.full_messages)
end
end
private
def allowed?
Ability.allowed?(current_user, :destroy_release, release)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::Links::DestroyService, feature_category: :release_orchestration do
let(:service) { described_class.new(release, user, {}) }
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user) }
let_it_be(:release) { create(:release, project: project, author: user, tag: 'v1.1.0') }
let!(:release_link) do
create(
:release_link,
release: release,
name: 'awesome-app.dmg',
url: 'https://example.com/download/awesome-app.dmg'
)
end
before do
project.add_developer(user)
end
describe '#execute' do
subject(:execute) { service.execute(release_link) }
it 'successfully deletes a release link' do
expect { execute }.to change { release.links.count }.by(-1)
is_expected.to be_success
end
context 'when user does not have access to delete release link' do
before do
project.add_guest(user)
end
it 'returns an error' do
expect { execute }.not_to change { release.links.count }
is_expected.to be_error
expect(execute.message).to include('Access Denied')
expect(execute.reason).to eq(:forbidden)
end
end
context 'when release link does not exist' do
let(:release_link) { nil }
it 'returns an error' do
expect { execute }.not_to change { release.links.count }
is_expected.to be_error
expect(execute.message).to eq('Link does not exist')
expect(execute.reason).to eq(:not_found)
end
end
context 'when release link deletion failed' do
before do
allow(release_link).to receive(:destroy).and_return(false)
end
it 'returns an error' do
expect { execute }.not_to change { release.links.count }
is_expected.to be_error
expect(execute.reason).to eq(:bad_request)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
module Links
class UpdateService < BaseService
def execute(link)
return ServiceResponse.error(reason: REASON_FORBIDDEN, message: _('Access Denied')) unless allowed?
return ServiceResponse.error(reason: REASON_NOT_FOUND, message: _('Link does not exist')) unless link
if link.update(allowed_params)
ServiceResponse.success(payload: { link: link })
else
ServiceResponse.error(reason: REASON_BAD_REQUEST, message: link.errors.full_messages)
end
end
private
def allowed?
Ability.allowed?(current_user, :update_release, release)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::Links::UpdateService, feature_category: :release_orchestration do
let(:service) { described_class.new(release, user, params) }
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user) }
let_it_be(:release) { create(:release, project: project, author: user, tag: 'v1.1.0') }
let(:release_link) do
create(
:release_link,
release: release,
name: 'awesome-app.dmg',
url: 'https://example.com/download/awesome-app.dmg'
)
end
let(:params) { { name: name, url: url, direct_asset_path: direct_asset_path, link_type: link_type } }
let(:name) { 'link' }
let(:url) { 'https://example.com' }
let(:direct_asset_path) { '/path' }
let(:link_type) { 'other' }
before do
project.add_developer(user)
end
describe '#execute' do
subject(:execute) { service.execute(release_link) }
let(:updated_link) { execute.payload[:link] }
it 'successfully updates a release link' do
is_expected.to be_success
expect(updated_link).to have_attributes(
name: name,
url: url,
filepath: direct_asset_path,
link_type: link_type
)
end
context 'when user does not have access to update release link' do
before do
project.add_guest(user)
end
it 'returns an error' do
is_expected.to be_error
expect(execute.message).to include('Access Denied')
expect(execute.reason).to eq(:forbidden)
end
end
context 'when url is invalid' do
let(:url) { 'not_a_url' }
it 'returns an error' do
is_expected.to be_error
expect(execute.message[0]).to include('Url is blocked')
expect(execute.reason).to eq(:bad_request)
end
end
context 'when both direct_asset_path and filepath are provided' do
let(:params) { super().merge(filepath: '/filepath') }
it 'prefers direct_asset_path' do
is_expected.to be_success
expect(updated_link.filepath).to eq(direct_asset_path)
end
end
context 'when only filepath is set' do
let(:params) { super().merge(filepath: '/filepath') }
let(:direct_asset_path) { nil }
it 'uses filepath' do
is_expected.to be_success
expect(updated_link.filepath).to eq('/filepath')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
module Links
class CreateService < BaseService
def execute
return ServiceResponse.error(reason: REASON_FORBIDDEN, message: _('Access Denied')) unless allowed?
link = release.links.create(allowed_params)
if link.persisted?
ServiceResponse.success(payload: { link: link })
else
ServiceResponse.error(reason: REASON_BAD_REQUEST, message: link.errors.full_messages)
end
end
private
def allowed?
Ability.allowed?(current_user, :create_release, release)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::Links::CreateService, feature_category: :release_orchestration do
let(:service) { described_class.new(release, user, params) }
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user) }
let_it_be(:release) { create(:release, project: project, author: user, tag: 'v1.1.0') }
let(:params) { { name: name, url: url, direct_asset_path: direct_asset_path, link_type: link_type } }
let(:name) { 'link' }
let(:url) { 'https://example.com' }
let(:direct_asset_path) { '/path' }
let(:link_type) { 'other' }
before do
project.add_developer(user)
end
describe '#execute' do
subject(:execute) { service.execute }
let(:link) { subject.payload[:link] }
it 'successfully creates a release link' do
expect { execute }.to change { Releases::Link.count }.by(1)
expect(link).to have_attributes(
name: name,
url: url,
filepath: direct_asset_path,
link_type: link_type
)
end
context 'when user does not have access to create release link' do
before do
project.add_guest(user)
end
it 'returns an error' do
expect { execute }.not_to change { Releases::Link.count }
is_expected.to be_error
expect(execute.message).to include('Access Denied')
expect(execute.reason).to eq(:forbidden)
end
end
context 'when url is invalid' do
let(:url) { 'not_a_url' }
it 'returns an error' do
expect { execute }.not_to change { Releases::Link.count }
is_expected.to be_error
expect(execute.message[0]).to include('Url is blocked')
expect(execute.reason).to eq(:bad_request)
end
end
context 'when both direct_asset_path and filepath are provided' do
let(:params) { super().merge(filepath: '/filepath') }
it 'prefers direct_asset_path' do
is_expected.to be_success
expect(link.filepath).to eq(direct_asset_path)
end
end
context 'when only filepath is set' do
let(:params) { super().merge(filepath: '/filepath') }
let(:direct_asset_path) { nil }
it 'uses filepath' do
is_expected.to be_success
expect(link.filepath).to eq('/filepath')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Releases
module Links
class Params
def initialize(params)
@params = params.with_indifferent_access
end
def allowed_params
@allowed_params ||= params.slice(:name, :url, :link_type).tap do |hash|
hash[:filepath] = filepath if provided_filepath?
end
end
private
attr_reader :params
def provided_filepath?
params.key?(:direct_asset_path) || params.key?(:filepath)
end
def filepath
params[:direct_asset_path] || params[:filepath]
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Releases::Links::Params, feature_category: :release_orchestration do
subject(:filter) { described_class.new(params) }
let(:params) { { name: name, url: url, direct_asset_path: direct_asset_path, link_type: link_type, unknown: '?' } }
let(:name) { 'link' }
let(:url) { 'https://example.com' }
let(:direct_asset_path) { '/path' }
let(:link_type) { 'other' }
describe '#allowed_params' do
subject { filter.allowed_params }
it 'returns only allowed params' do
is_expected.to eq('name' => name, 'url' => url, 'filepath' => direct_asset_path, 'link_type' => link_type)
end
context 'when deprecated filepath is used' do
let(:params) { super().merge(direct_asset_path: nil, filepath: 'filepath') }
it 'uses filepath value' do
is_expected.to eq('name' => name, 'url' => url, 'filepath' => 'filepath', 'link_type' => link_type)
end
end
context 'when both direct_asset_path and filepath are provided' do
let(:params) { super().merge(filepath: 'filepath') }
it 'uses direct_asset_path value' do
is_expected.to eq('name' => name, 'url' => url, 'filepath' => direct_asset_path, 'link_type' => link_type)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ChatNames
class FindUserService
def initialize(team_id, user_id)
@team_id = team_id
@user_id = user_id
end
def execute
chat_name = find_chat_name
return unless chat_name
record_chat_activity(chat_name)
chat_name
end
private
attr_reader :team_id, :user_id
# rubocop: disable CodeReuse/ActiveRecord
def find_chat_name
ChatName.find_by(
team_id: team_id,
chat_id: user_id
)
end
# rubocop: enable CodeReuse/ActiveRecord
def record_chat_activity(chat_name)
chat_name.update_last_used_at
Users::ActivityService.new(author: chat_name.user).execute
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ChatNames::FindUserService, :clean_gitlab_redis_shared_state, feature_category: :user_profile do
describe '#execute' do
subject { described_class.new(team_id, user_id).execute }
context 'find user mapping' do
let_it_be(:user) { create(:user) }
let(:chat_name) { create(:chat_name, user: user) }
let(:team_id) { chat_name.team_id }
let(:user_id) { chat_name.chat_id }
context 'when existing user is requested' do
it 'returns the existing chat_name' do
is_expected.to eq(chat_name)
end
it 'updates the last used timestamp if one is not already set' do
expect { subject }.to change { chat_name.reload.last_used_at }.from(nil)
end
it 'only updates an existing timestamp once within a certain time frame' do
expect { described_class.new(team_id, user_id).execute }.to change { chat_name.reload.last_used_at }.from(nil)
expect { described_class.new(team_id, user_id).execute }.not_to change { chat_name.reload.last_used_at }
end
it 'records activity for the related user' do
expect_next_instance_of(Users::ActivityService, author: user) do |activity_service|
expect(activity_service).to receive(:execute)
end
subject
end
end
context 'when different user is requested' do
let(:user_id) { 'non-existing-user' }
it 'returns nil' do
is_expected.to be_nil
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ChatNames
class AuthorizeUserService
include Gitlab::Routing
def initialize(params)
@params = params
end
def execute
return unless chat_name_params.values.all?(&:present?)
token = request_token
new_profile_chat_name_url(token: token) if token
end
private
def request_token
chat_name_token.store!(chat_name_params)
end
def chat_name_token
@chat_name_token ||= Gitlab::ChatNameToken.new
end
def chat_name_params
{
team_id: @params[:team_id],
team_domain: @params[:team_domain],
chat_id: @params[:user_id],
chat_name: @params[:user_name]
}
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ChatNames::AuthorizeUserService, feature_category: :user_profile do
describe '#execute' do
let(:result) { subject.execute }
subject { described_class.new(params) }
context 'when all parameters are valid' do
let(:params) { { team_id: 'T0001', team_domain: 'myteam', user_id: 'U0001', user_name: 'user' } }
it 'produces a valid HTTP URL' do
expect(result).to be_http_url
end
it 'requests a new token' do
expect(subject).to receive(:request_token).once.and_call_original
subject.execute
end
end
context 'when there are missing parameters' do
let(:params) { {} }
it 'does not produce a URL' do
expect(result).to be_nil
end
it 'does not request a new token' do
expect(subject).not_to receive(:request_token)
subject.execute
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ErrorTracking
class IssueDetailsService < ErrorTracking::BaseService
include Gitlab::Routing
include Gitlab::Utils::StrongMemoize
private
def perform
response = find_issue_details(params[:issue_id])
compose_response(response) do
# The gitlab_issue attribute can contain an absolute GitLab url from the Sentry Client
# here we overwrite that in favor of our own data if we have it
response[:issue].gitlab_issue = gitlab_issue_url if gitlab_issue_url
end
end
def gitlab_issue_url
strong_memoize(:gitlab_issue_url) do
# Use the absolute url to match the GitLab issue url that the Sentry api provides
project_issue_url(project, gitlab_issue.iid) if gitlab_issue
end
end
def gitlab_issue
strong_memoize(:gitlab_issue) do
SentryIssueFinder
.new(project, current_user: current_user)
.execute(params[:issue_id])
&.issue
end
end
def parse_response(response)
{ issue: response[:issue] }
end
def find_issue_details(issue_id)
# There are 2 types of the data source for the error tracking feature:
#
# * When integrated error tracking is enabled, we use the application database
# to read and save error tracking data.
#
# * When integrated error tracking is disabled we call
# project_error_tracking_setting method which works with Sentry API.
#
# Issue https://gitlab.com/gitlab-org/gitlab/-/issues/329596
#
if project_error_tracking_setting.integrated_client?
handle_error_repository_exceptions do
error = error_repository.find_error(issue_id)
{ issue: error }
end
else
project_error_tracking_setting.issue_details(issue_id: issue_id)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ErrorTracking::IssueDetailsService, feature_category: :error_tracking do
include_context 'sentry error tracking context'
subject(:service) { described_class.new(project, user, params) }
describe '#execute' do
context 'with authorized user' do
context 'when issue_details returns a detailed error' do
let(:detailed_error) { build(:error_tracking_sentry_detailed_error) }
let(:params) { { issue_id: detailed_error.id } }
before do
allow(error_tracking_setting)
.to receive(:issue_details).and_return(issue: detailed_error)
end
it 'returns the detailed error' do
expect(result).to eq(status: :success, issue: detailed_error)
end
it 'returns the gitlab_issue when the error has a sentry_issue' do
gitlab_issue = create(:issue, project: project)
create(:sentry_issue, issue: gitlab_issue, sentry_issue_identifier: detailed_error.id)
expect(result[:issue].gitlab_issue).to include(
"http", "/#{project.full_path}/-/issues/#{gitlab_issue.iid}"
)
end
it 'returns the gitlab_issue path from sentry when the error has no sentry_issue' do
expect(result[:issue].gitlab_issue).to eq(detailed_error.gitlab_issue)
end
end
include_examples 'error tracking service data not ready', :issue_details
include_examples 'error tracking service sentry error handling', :issue_details
include_examples 'error tracking service http status handling', :issue_details
context 'with integrated error tracking' do
let(:error_repository) { instance_double(Gitlab::ErrorTracking::ErrorRepository) }
let(:params) { { issue_id: issue_id } }
before do
error_tracking_setting.update!(integrated: true)
allow(service).to receive(:error_repository).and_return(error_repository)
end
context 'when error is found' do
let(:error) { build_stubbed(:error_tracking_open_api_error, project_id: project.id) }
let(:issue_id) { error.fingerprint }
before do
allow(error_repository).to receive(:find_error).with(issue_id).and_return(error)
end
it 'returns the error in detailed format' do
expect(result[:status]).to eq(:success)
expect(result[:issue]).to eq(error)
end
end
context 'when error does not exist' do
let(:issue_id) { non_existing_record_id }
before do
allow(error_repository).to receive(:find_error).with(issue_id)
.and_raise(Gitlab::ErrorTracking::ErrorRepository::DatabaseError.new('Error not found'))
end
it 'returns the error in detailed format' do
expect(result).to match(
status: :error,
message: /Error not found/,
http_status: :bad_request
)
end
end
end
end
include_examples 'error tracking service unauthorized user'
include_examples 'error tracking service disabled'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ErrorTracking
class ListProjectsService < ErrorTracking::BaseService
private
def perform
return error('Access denied', :unauthorized) unless can?(current_user, :admin_sentry, project)
unless project_error_tracking_setting.valid?
return error(project_error_tracking_setting.errors.full_messages.join(', '), :bad_request)
end
response = project_error_tracking_setting.list_sentry_projects
compose_response(response)
end
def parse_response(response)
{ projects: response[:projects] }
end
def project_error_tracking_setting
(super || project.build_error_tracking_setting).tap do |setting|
setting.api_url = ErrorTracking::ProjectErrorTrackingSetting.build_api_url_from(
api_host: params[:api_host],
organization_slug: 'org',
project_slug: 'proj'
)
setting.token = token(setting)
setting.enabled = true
end
end
strong_memoize_attr :project_error_tracking_setting
def token(setting)
return if setting.api_url_changed? && masked_token?
# Use param token if not masked, otherwise use database token
return params[:token] unless masked_token?
setting.token
end
def masked_token?
ErrorTracking::SentryClient::Token.masked_token?(params[:token])
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ErrorTracking::ListProjectsService, feature_category: :integrations do
let_it_be(:user) { create(:user) }
let_it_be(:project, reload: true) { create(:project) }
let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/org/proj/' }
let(:token) { 'test-token' }
let(:new_api_host) { 'https://gitlab.com/' }
let(:new_token) { 'new-token' }
let(:params) { ActionController::Parameters.new(api_host: new_api_host, token: new_token) }
let(:error_tracking_setting) do
create(:project_error_tracking_setting, api_url: sentry_url, token: token, project: project)
end
subject { described_class.new(project, user, params) }
before do
project.add_maintainer(user)
end
describe '#execute' do
let(:result) { subject.execute }
context 'with authorized user' do
before do
expect(project).to receive(:error_tracking_setting).at_least(:once)
.and_return(error_tracking_setting)
end
context 'set model attributes to new values' do
let(:new_api_url) { new_api_host + 'api/0/projects/org/proj/' }
before do
expect(error_tracking_setting).to receive(:list_sentry_projects)
.and_return({ projects: [] })
end
it 'uses new api_url and token' do
subject.execute
expect(error_tracking_setting.api_url).to eq(new_api_url)
expect(error_tracking_setting.token).to eq(new_token)
error_tracking_setting.reload
expect(error_tracking_setting.api_url).to eq(sentry_url)
expect(error_tracking_setting.token).to eq(token)
end
end
context 'masked param token' do
let(:params) { ActionController::Parameters.new(token: "*********", api_host: api_host) }
context 'with the current api host' do
let(:api_host) { 'https://sentrytest.gitlab.com' }
before do
expect(error_tracking_setting).to receive(:list_sentry_projects)
.and_return({ projects: [] })
end
it 'uses database token' do
expect { subject.execute }.not_to change { error_tracking_setting.token }
end
end
context 'with the similar api host' do
let(:api_host) { 'https://sentrytest.gitlab.co' }
it 'returns an error' do
expect(result[:message]).to start_with('Token is a required field')
expect(error_tracking_setting).not_to be_valid
expect(error_tracking_setting).not_to receive(:list_sentry_projects)
end
it 'resets the token' do
expect { subject.execute }.to change { error_tracking_setting.token }.from(token).to(nil)
end
end
context 'with a new api host' do
let(:api_host) { new_api_host }
it 'returns an error' do
expect(result[:message]).to start_with('Token is a required field')
expect(error_tracking_setting).not_to be_valid
expect(error_tracking_setting).not_to receive(:list_sentry_projects)
end
it 'resets the token' do
expect { subject.execute }.to change { error_tracking_setting.token }.from(token).to(nil)
end
end
end
context 'with invalid url' do
let(:params) do
ActionController::Parameters.new(
api_host: 'https://localhost',
token: new_token
)
end
before do
error_tracking_setting.enabled = false
end
it 'returns error' do
expect(result[:message]).to start_with('Api url is blocked')
expect(error_tracking_setting).not_to be_valid
end
end
context 'when list_sentry_projects returns projects' do
let(:projects) { [:list, :of, :projects] }
before do
expect(error_tracking_setting)
.to receive(:list_sentry_projects).and_return(projects: projects)
end
it 'returns the projects' do
expect(result).to eq(status: :success, projects: projects)
end
end
end
context 'with unauthorized user' do
before do
project.add_guest(user)
end
it 'returns error' do
expect(result).to include(status: :error, message: 'Access denied', http_status: :unauthorized)
end
end
context 'with user with insufficient permissions' do
before do
project.add_developer(user)
end
it 'returns error' do
expect(result).to include(status: :error, message: 'Access denied', http_status: :unauthorized)
end
end
context 'with error tracking disabled' do
before do
expect(project).to receive(:error_tracking_setting).at_least(:once)
.and_return(error_tracking_setting)
expect(error_tracking_setting)
.to receive(:list_sentry_projects).and_return(projects: [])
error_tracking_setting.enabled = false
end
it 'ignores enabled flag' do
expect(result).to include(status: :success, projects: [])
end
end
context 'error_tracking_setting is nil' do
let(:error_tracking_setting) { build(:project_error_tracking_setting, project: project) }
let(:new_api_url) { new_api_host + 'api/0/projects/org/proj/' }
before do
expect(project).to receive(:build_error_tracking_setting).once
.and_return(error_tracking_setting)
expect(error_tracking_setting).to receive(:list_sentry_projects)
.and_return(projects: [:project1, :project2])
end
it 'builds a new error_tracking_setting' do
expect(project.error_tracking_setting).to be_nil
expect(result[:projects]).to eq([:project1, :project2])
expect(error_tracking_setting.api_url).to eq(new_api_url)
expect(error_tracking_setting.token).to eq(new_token)
expect(error_tracking_setting.enabled).to be true
expect(error_tracking_setting.persisted?).to be false
expect(error_tracking_setting.project_id).not_to be_nil
expect(project.error_tracking_setting).to be_nil
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ErrorTracking
class BaseService < ::BaseProjectService
include Gitlab::Utils::UsageData
def initialize(project, user = nil, params = {})
super(project: project, current_user: user, params: params.dup)
end
def execute
return unauthorized if unauthorized
perform
end
private
def perform
raise NotImplementedError, "#{self.class} does not implement #{__method__}"
end
def compose_response(response, &block)
errors = parse_errors(response)
return errors if errors
yield if block
track_usage_event(params[:tracking_event], current_user.id) if params[:tracking_event]
success(parse_response(response))
end
def parse_response(response)
raise NotImplementedError, "#{self.class} does not implement #{__method__}"
end
def unauthorized
return error('Error Tracking is not enabled') unless enabled?
return error('Access denied', :unauthorized) unless can_read?
end
def parse_errors(response)
return error('Not ready. Try again later', :no_content) unless response
return error(response[:error], http_status_for(response[:error_type])) if response[:error].present?
end
def http_status_for(error_type)
case error_type
when ErrorTracking::ProjectErrorTrackingSetting::SENTRY_API_ERROR_TYPE_MISSING_KEYS
:internal_server_error
else
:bad_request
end
end
def project_error_tracking_setting
project.error_tracking_setting
end
def enabled?
project_error_tracking_setting&.enabled?
end
def can_read?
can?(current_user, :read_sentry_issue, project)
end
def can_update?
can?(current_user, :update_sentry_issue, project)
end
def error_repository
Gitlab::ErrorTracking::ErrorRepository.build(project)
end
def handle_error_repository_exceptions
yield
rescue Gitlab::ErrorTracking::ErrorRepository::DatabaseError => e
{ error: e.message }
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ErrorTracking::BaseService, feature_category: :error_tracking do
describe '#compose_response' do
let(:project) { build_stubbed(:project) }
let(:user) { build_stubbed(:user, id: non_existing_record_id) }
let(:service) { described_class.new(project, user) }
it 'returns bad_request error when response has an error key' do
data = { error: 'Unexpected Error' }
result = service.send(:compose_response, data)
expect(result[:status]).to be(:error)
expect(result[:message]).to be('Unexpected Error')
expect(result[:http_status]).to be(:bad_request)
end
it 'returns server error when response has missing key error_type' do
data = {
error: 'Unexpected Error',
error_type: ErrorTracking::ProjectErrorTrackingSetting::SENTRY_API_ERROR_TYPE_MISSING_KEYS
}
result = service.send(:compose_response, data)
expect(result[:status]).to be(:error)
expect(result[:message]).to be('Unexpected Error')
expect(result[:http_status]).to be(:internal_server_error)
end
it 'returns no content when response is nil' do
data = nil
result = service.send(:compose_response, data)
expect(result[:status]).to be(:error)
expect(result[:message]).to be('Not ready. Try again later')
expect(result[:http_status]).to be(:no_content)
end
context 'when result has no errors key' do
let(:data) { { thing: :cat } }
it 'raises NotImplementedError' do
expect { service.send(:compose_response, data) }
.to raise_error(NotImplementedError)
end
context 'when parse_response is implemented' do
before do
allow(service).to receive(:parse_response) do |response|
{ animal: response[:thing] }
end
end
it 'returns successful response' do
result = service.send(:compose_response, data)
expect(result[:animal]).to eq(:cat)
expect(result[:status]).to eq(:success)
end
it 'returns successful response with changes from passed block' do
result = service.send(:compose_response, data) do
data[:thing] = :fish
end
expect(result[:animal]).to eq(:fish)
expect(result[:status]).to eq(:success)
end
context 'when tracking_event is provided' do
let(:service) { described_class.new(project, user, tracking_event: :error_tracking_view_list) }
it_behaves_like 'tracking unique hll events' do
let(:target_event) { 'error_tracking_view_list' }
let(:expected_value) { non_existing_record_id }
let(:request) { service.send(:compose_response, data) }
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ErrorTracking
class IssueLatestEventService < ErrorTracking::BaseService
private
def perform
response = find_issue_latest_event(params[:issue_id])
compose_response(response)
end
def parse_response(response)
{ latest_event: response[:latest_event] }
end
def find_issue_latest_event(issue_id)
# There are 2 types of the data source for the error tracking feature:
#
# * When integrated error tracking is enabled, we use the application database
# to read and save error tracking data.
#
# * When integrated error tracking is disabled we call
# project_error_tracking_setting method which works with Sentry API.
#
# Issue https://gitlab.com/gitlab-org/gitlab/-/issues/329596
#
if project_error_tracking_setting.integrated_client?
handle_error_repository_exceptions do
event = error_repository.last_event_for(issue_id)
# We use the same response format as project_error_tracking_setting
# method below for compatibility with existing code.
{ latest_event: event }
end
else
project_error_tracking_setting.issue_latest_event(issue_id: issue_id)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ErrorTracking::IssueLatestEventService, feature_category: :error_tracking do
include_context 'sentry error tracking context'
let(:params) { {} }
subject(:service) { described_class.new(project, user, params) }
describe '#execute' do
context 'with authorized user' do
context 'when issue_latest_event returns an error event' do
let(:error_event) { build(:error_tracking_sentry_error_event) }
before do
allow(error_tracking_setting)
.to receive(:issue_latest_event).and_return(latest_event: error_event)
end
it 'returns the error event' do
expect(result).to eq(status: :success, latest_event: error_event)
end
end
include_examples 'error tracking service data not ready', :issue_latest_event
include_examples 'error tracking service sentry error handling', :issue_latest_event
include_examples 'error tracking service http status handling', :issue_latest_event
context 'with integrated error tracking' do
let(:error_repository) { instance_double(Gitlab::ErrorTracking::ErrorRepository) }
let(:params) { { issue_id: issue_id } }
before do
error_tracking_setting.update!(integrated: true)
allow(service).to receive(:error_repository).and_return(error_repository)
end
context 'when error is found' do
let(:error) { build_stubbed(:error_tracking_open_api_error, project_id: project.id) }
let(:event) { build_stubbed(:error_tracking_open_api_error_event, fingerprint: error.fingerprint) }
let(:issue_id) { error.fingerprint }
before do
allow(error_repository).to receive(:last_event_for).with(issue_id).and_return(event)
end
it 'returns the latest event in expected format' do
expect(result[:status]).to eq(:success)
expect(result[:latest_event]).to eq(event)
end
end
context 'when error does not exist' do
let(:issue_id) { non_existing_record_id }
before do
allow(error_repository).to receive(:last_event_for).with(issue_id)
.and_raise(Gitlab::ErrorTracking::ErrorRepository::DatabaseError.new('Error not found'))
end
it 'returns the error in detailed format' do
expect(result).to match(
status: :error,
message: /Error not found/,
http_status: :bad_request
)
end
end
end
end
include_examples 'error tracking service unauthorized user'
include_examples 'error tracking service disabled'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ErrorTracking
class IssueUpdateService < ErrorTracking::BaseService
private
def perform
update_opts = {
issue_id: params[:issue_id],
params: update_params
}
response = update_issue(update_opts)
compose_response(response) do
project_error_tracking_setting.expire_issues_cache
response[:closed_issue_iid] = update_related_issue&.iid
end
end
def update_related_issue
issue = related_issue
return unless issue
close_and_create_note(issue)
end
def close_and_create_note(issue)
return unless resolving? && issue.opened?
processed_issue = close_issue(issue)
return unless processed_issue.reset.closed?
create_system_note(processed_issue)
processed_issue
end
def close_issue(issue)
Issues::CloseService
.new(container: project, current_user: current_user)
.execute(issue, system_note: false)
end
def create_system_note(issue)
SystemNoteService.close_after_error_tracking_resolve(issue, project, current_user)
end
def related_issue
SentryIssueFinder
.new(project, current_user: current_user)
.execute(params[:issue_id])
&.issue
end
def resolving?
update_params[:status] == 'resolved'
end
def update_params
params.except(:issue_id)
end
def parse_response(response)
{
updated: response[:updated].present?,
closed_issue_iid: response[:closed_issue_iid]
}
end
def unauthorized
return error('Error Tracking is not enabled') unless enabled?
return error('Access denied', :unauthorized) unless can_update?
end
def update_issue(opts)
# There are 2 types of the data source for the error tracking feature:
#
# * When integrated error tracking is enabled, we use the application database
# to read and save error tracking data.
#
# * When integrated error tracking is disabled we call
# project_error_tracking_setting method which works with Sentry API.
#
# Issue https://gitlab.com/gitlab-org/gitlab/-/issues/329596
#
if project_error_tracking_setting.integrated_client?
updated = error_repository.update_error(opts[:issue_id], status: opts[:params][:status])
# We use the same response format as project_error_tracking_setting
# method below for compatibility with existing code.
{
updated: updated
}
else
project_error_tracking_setting.update_issue(**opts)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ErrorTracking::IssueUpdateService, feature_category: :error_tracking do
include_context 'sentry error tracking context'
let(:arguments) { { issue_id: non_existing_record_id, status: 'resolved' } }
subject(:update_service) { described_class.new(project, user, arguments) }
shared_examples 'does not perform close issue flow' do
it 'does not call the close issue service' do
update_service.execute
expect(issue_close_service).not_to have_received(:execute)
end
it 'does not create system note' do
expect(SystemNoteService).not_to receive(:close_after_error_tracking_resolve)
update_service.execute
end
end
describe '#execute' do
context 'with authorized user' do
context 'when update_issue returns success' do
let(:update_issue_response) { { updated: true } }
before do
allow(error_tracking_setting).to receive(:update_issue).and_return(update_issue_response)
end
it 'returns the response' do
expect(update_service.execute).to eq(update_issue_response.merge(status: :success, closed_issue_iid: nil))
end
it 'updates any related issue' do
expect(update_service).to receive(:update_related_issue)
update_service.execute
end
it 'clears the reactive cache' do
expect(error_tracking_setting).to receive(:expire_issues_cache)
result
end
context 'with related issue and resolving' do
let(:issue) { create(:issue, project: project) }
let(:sentry_issue) { create(:sentry_issue, issue: issue) }
let(:arguments) { { issue_id: sentry_issue.sentry_issue_identifier, status: 'resolved' } }
let(:issue_close_service) { instance_double('Issues::CloseService') }
before do
allow_next_instance_of(SentryIssueFinder) do |finder|
allow(finder).to receive(:execute).and_return(sentry_issue)
end
allow(Issues::CloseService)
.to receive(:new)
.and_return(issue_close_service)
allow(issue_close_service)
.to receive(:execute)
.and_return(issue)
end
it 'closes the issue' do
update_service.execute
expect(issue_close_service)
.to have_received(:execute)
.with(issue, system_note: false)
end
context 'when issue gets closed' do
let(:closed_issue) { create(:issue, :closed, project: project) }
before do
allow(issue_close_service)
.to receive(:execute)
.with(issue, system_note: false)
.and_return(closed_issue)
end
it 'creates a system note' do
expect(SystemNoteService).to receive(:close_after_error_tracking_resolve)
update_service.execute
end
it 'returns a response with closed issue' do
expect(update_service.execute).to eq(status: :success, updated: true, closed_issue_iid: closed_issue.iid)
end
end
context 'when issue is already closed' do
let(:issue) { create(:issue, :closed, project: project) }
include_examples 'does not perform close issue flow'
end
context 'when status is not resolving' do
let(:arguments) { { issue_id: sentry_issue.sentry_issue_identifier, status: 'ignored' } }
include_examples 'does not perform close issue flow'
end
end
end
include_examples 'error tracking service sentry error handling', :update_issue
context 'with integrated error tracking' do
let(:error_repository) { instance_double(Gitlab::ErrorTracking::ErrorRepository) }
let(:error) { build_stubbed(:error_tracking_open_api_error, project_id: project.id) }
let(:issue_id) { error.fingerprint }
let(:arguments) { { issue_id: issue_id, status: 'resolved' } }
before do
error_tracking_setting.update!(integrated: true)
allow(update_service).to receive(:error_repository).and_return(error_repository)
allow(error_repository).to receive(:update_error)
.with(issue_id, status: 'resolved').and_return(updated)
end
context 'when update succeeded' do
let(:updated) { true }
it 'returns success with updated true' do
expect(project.error_tracking_setting).to receive(:expire_issues_cache)
expect(update_service.execute).to eq(
status: :success,
updated: true,
closed_issue_iid: nil
)
end
end
context 'when update failed' do
let(:updated) { false }
it 'returns success with updated false' do
expect(project.error_tracking_setting).to receive(:expire_issues_cache)
expect(update_service.execute).to eq(
status: :success,
updated: false,
closed_issue_iid: nil
)
end
end
end
end
include_examples 'error tracking service unauthorized user'
include_examples 'error tracking service disabled'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ErrorTracking
class ListIssuesService < ErrorTracking::BaseService
DEFAULT_ISSUE_STATUS = 'unresolved'
DEFAULT_LIMIT = 20
DEFAULT_SORT = 'last_seen'
# Sentry client supports 'muted' and 'assigned' but GitLab does not
ISSUE_STATUS_VALUES = %w[
resolved
unresolved
ignored
].freeze
def external_url
project_error_tracking_setting&.sentry_external_url
end
private
def perform
return invalid_status_error unless valid_status?
sentry_opts = {
issue_status: issue_status,
limit: limit,
search_term: params[:search_term].presence,
sort: sort,
cursor: params[:cursor].presence
}
response = list_issues(sentry_opts)
compose_response(response)
end
def parse_response(response)
response.slice(:issues, :pagination)
end
def invalid_status_error
error('Bad Request: Invalid issue_status', http_status_for(:bad_Request))
end
def valid_status?
ISSUE_STATUS_VALUES.include?(issue_status)
end
def issue_status
params[:issue_status] || DEFAULT_ISSUE_STATUS
end
def limit
params[:limit] || DEFAULT_LIMIT
end
def sort
params[:sort] || DEFAULT_SORT
end
def list_issues(opts)
# There are 2 types of the data source for the error tracking feature:
#
# * When integrated error tracking is enabled, we use the application database
# to read and save error tracking data.
#
# * When integrated error tracking is disabled we call
# project_error_tracking_setting method which works with Sentry API.
#
# Issue https://gitlab.com/gitlab-org/gitlab/-/issues/329596
#
if project_error_tracking_setting.integrated_client?
# We are going to support more options in the future.
# For now we implement the bare minimum for rendering the list in UI.
list_opts = {
filters: { status: opts[:issue_status] },
query: opts[:search_term],
sort: opts[:sort],
limit: opts[:limit],
cursor: opts[:cursor]
}
errors, pagination = error_repository.list_errors(**list_opts)
pagination_hash = {}
pagination_hash[:next] = { cursor: pagination.next } if pagination.next
pagination_hash[:previous] = { cursor: pagination.prev } if pagination.prev
# We use the same response format as project_error_tracking_setting
# method below for compatibility with existing code.
{
issues: errors,
pagination: pagination_hash
}
else
project_error_tracking_setting.list_sentry_issues(**opts)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ErrorTracking::ListIssuesService, feature_category: :error_tracking do
include_context 'sentry error tracking context'
let(:params) { {} }
subject(:service) { described_class.new(project, user, params) }
describe '#execute' do
context 'with Sentry backend' do
let(:params) { { search_term: 'something', sort: 'last_seen', cursor: 'some-cursor' } }
let(:list_sentry_issues_args) do
{
issue_status: 'unresolved',
limit: 20,
search_term: 'something',
sort: 'last_seen',
cursor: 'some-cursor'
}
end
context 'with authorized user' do
let(:issues) { [] }
described_class::ISSUE_STATUS_VALUES.each do |status|
it "returns the issues with #{status} issue_status" do
params[:issue_status] = status
list_sentry_issues_args[:issue_status] = status
expect_list_sentry_issues_with(list_sentry_issues_args)
expect(result).to eq(status: :success, pagination: {}, issues: issues)
end
end
it 'returns the issues with no issue_status' do
expect_list_sentry_issues_with(list_sentry_issues_args)
expect(result).to eq(status: :success, pagination: {}, issues: issues)
end
it 'returns bad request with invalid issue_status' do
params[:issue_status] = 'assigned'
expect(error_tracking_setting).not_to receive(:list_sentry_issues)
expect(result).to eq(message: "Bad Request: Invalid issue_status", status: :error, http_status: :bad_request)
end
include_examples 'error tracking service data not ready', :list_sentry_issues
include_examples 'error tracking service sentry error handling', :list_sentry_issues
include_examples 'error tracking service http status handling', :list_sentry_issues
end
include_examples 'error tracking service unauthorized user'
include_examples 'error tracking service disabled'
def expect_list_sentry_issues_with(list_sentry_issues_args)
expect(error_tracking_setting)
.to receive(:list_sentry_issues)
.with(list_sentry_issues_args)
.and_return(issues: [], pagination: {})
end
end
context 'with integrated error tracking' do
let(:error_repository) { instance_double(Gitlab::ErrorTracking::ErrorRepository) }
let(:errors) { [] }
let(:pagination) { Gitlab::ErrorTracking::ErrorRepository::Pagination.new(nil, nil) }
let(:opts) { default_opts }
let(:default_opts) do
{
filters: { status: described_class::DEFAULT_ISSUE_STATUS },
query: nil,
sort: described_class::DEFAULT_SORT,
limit: described_class::DEFAULT_LIMIT,
cursor: nil
}
end
let(:params) { {} }
before do
error_tracking_setting.update!(integrated: true)
allow(service).to receive(:error_repository).and_return(error_repository)
end
context 'when errors are found' do
let(:error) { build_stubbed(:error_tracking_open_api_error, project_id: project.id) }
let(:errors) { [error] }
before do
allow(error_repository).to receive(:list_errors)
.with(**opts)
.and_return([errors, pagination])
end
context 'without params' do
it 'returns the errors without pagination' do
expect(result[:status]).to eq(:success)
expect(result[:issues]).to eq(errors)
expect(result[:pagination]).to eq({})
expect(error_repository).to have_received(:list_errors).with(**opts)
end
end
context 'with pagination' do
context 'with next page' do
before do
pagination.next = 'next cursor'
end
it 'has next cursor' do
expect(result[:pagination]).to eq(next: { cursor: 'next cursor' })
end
end
context 'with prev page' do
before do
pagination.prev = 'prev cursor'
end
it 'has prev cursor' do
expect(result[:pagination]).to eq(previous: { cursor: 'prev cursor' })
end
end
context 'with next and prev page' do
before do
pagination.next = 'next cursor'
pagination.prev = 'prev cursor'
end
it 'has both cursors' do
expect(result[:pagination]).to eq(
next: { cursor: 'next cursor' },
previous: { cursor: 'prev cursor' }
)
end
end
end
end
end
end
describe '#external_url' do
it 'calls the project setting sentry_external_url' do
expect(error_tracking_setting).to receive(:sentry_external_url).and_return(sentry_url)
expect(subject.external_url).to eql sentry_url
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WebHooks
class LogExecutionService
include ::Gitlab::ExclusiveLeaseHelpers
LOCK_TTL = 15.seconds.freeze
LOCK_SLEEP = 0.25.seconds.freeze
LOCK_RETRY = 65
attr_reader :hook, :log_data, :response_category
def initialize(hook:, log_data:, response_category:)
@hook = hook
@log_data = log_data.transform_keys(&:to_sym)
@response_category = response_category
end
def execute
update_hook_failure_state
log_execution
end
private
def log_execution
mask_response_headers
log_data[:request_headers]['X-Gitlab-Token'] = _('[REDACTED]') if hook.token?
WebHookLog.create!(web_hook: hook, **log_data)
end
def mask_response_headers
return unless hook.url_variables?
return unless log_data.key?(:response_headers)
variables_map = hook.url_variables.invert.transform_values { "{#{_1}}" }
regex = Regexp.union(variables_map.keys)
log_data[:response_headers].transform_values! do |value|
regex === value ? value.gsub(regex, variables_map) : value
end
end
# Perform this operation within an `Gitlab::ExclusiveLease` lock to make it
# safe to be called concurrently from different workers.
def update_hook_failure_state
in_lock(lock_name, ttl: LOCK_TTL, sleep_sec: LOCK_SLEEP, retries: LOCK_RETRY) do |retried|
hook.reset # Reload within the lock so properties are guaranteed to be current.
case response_category
when :ok
hook.enable!
when :error
hook.backoff!
when :failed
hook.failed!
end
hook.update_last_failure
end
rescue Gitlab::ExclusiveLeaseHelpers::FailedToObtainLockError
raise if raise_lock_error?
end
def lock_name
"web_hooks:update_hook_failure_state:#{hook.id}"
end
# Allow an error to be raised after failing to obtain a lease only if the hook
# is not already in the correct failure state.
def raise_lock_error?
hook.reset # Reload so properties are guaranteed to be current.
hook.executable? != (response_category == :ok)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WebHooks::LogExecutionService, feature_category: :webhooks do
include ExclusiveLeaseHelpers
using RSpec::Parameterized::TableSyntax
describe '#execute' do
around do |example|
travel_to(Time.current) { example.run }
end
let_it_be_with_reload(:project_hook) { create(:project_hook, :token) }
let(:response_category) { :ok }
let(:request_headers) { { 'Header' => 'header value' } }
let(:data) do
{
trigger: 'trigger_name',
url: 'https://example.com',
request_headers: request_headers,
request_data: { 'Request Data' => 'request data value' },
response_body: 'Response body',
response_status: '200',
execution_duration: 1.2,
internal_error_message: 'error message'
}
end
subject(:service) { described_class.new(hook: project_hook, log_data: data, response_category: response_category) }
it 'logs the data' do
expect { service.execute }.to change(::WebHookLog, :count).by(1)
expect(WebHookLog.recent.first).to have_attributes(data)
end
it 'updates the last failure' do
expect(project_hook).to receive(:update_last_failure)
service.execute
end
context 'obtaining an exclusive lease' do
let(:lease_key) { "web_hooks:update_hook_failure_state:#{project_hook.id}" }
it 'updates failure state using a lease that ensures fresh state is written' do
service = described_class.new(hook: project_hook, log_data: data, response_category: :error)
# Write state somewhere else, so that the hook is out-of-date
WebHook.find(project_hook.id).update!(recent_failures: 5, disabled_until: 10.minutes.from_now, backoff_count: 1)
lease = stub_exclusive_lease(lease_key, timeout: described_class::LOCK_TTL)
expect(lease).to receive(:try_obtain)
expect(lease).to receive(:cancel)
expect { service.execute }.to change { WebHook.find(project_hook.id).backoff_count }.to(2)
end
context 'when a lease cannot be obtained' do
where(:response_category, :executable, :needs_updating) do
:ok | true | false
:ok | false | true
:failed | true | true
:failed | false | false
:error | true | true
:error | false | false
end
with_them do
subject(:service) { described_class.new(hook: project_hook, log_data: data, response_category: response_category) }
before do
# stub LOCK_RETRY to be 0 in order for tests to run quicker
stub_const("#{described_class.name}::LOCK_RETRY", 0)
stub_exclusive_lease_taken(lease_key, timeout: described_class::LOCK_TTL)
allow(project_hook).to receive(:executable?).and_return(executable)
end
it 'raises an error if the hook needs to be updated' do
if needs_updating
expect { service.execute }.to raise_error(Gitlab::ExclusiveLeaseHelpers::FailedToObtainLockError)
else
expect { service.execute }.not_to raise_error
end
end
end
end
end
context 'when response_category is :ok' do
it 'does not increment the failure count' do
expect { service.execute }.not_to change(project_hook, :recent_failures)
end
it 'does not change the disabled_until attribute' do
expect { service.execute }.not_to change(project_hook, :disabled_until)
end
context 'when the hook had previously failed' do
before do
project_hook.update!(recent_failures: 2)
end
it 'resets the failure count' do
expect { service.execute }.to change(project_hook, :recent_failures).to(0)
end
end
end
context 'when response_category is :failed' do
let(:response_category) { :failed }
before do
data[:response_status] = '400'
end
it 'increments the failure count' do
expect { service.execute }.to change(project_hook, :recent_failures).by(1)
end
it 'does not change the disabled_until attribute' do
expect { service.execute }.not_to change(project_hook, :disabled_until)
end
it 'does not allow the failure count to overflow' do
project_hook.update!(recent_failures: 32767)
expect { service.execute }.not_to change(project_hook, :recent_failures)
end
end
context 'when response_category is :error' do
let(:response_category) { :error }
before do
data[:response_status] = '500'
end
it 'backs off' do
expect(project_hook).to receive(:backoff!)
service.execute
end
end
context 'with url_variables' do
before do
project_hook.update!(
url: 'http://example1.test/{foo}-{bar}',
url_variables: { 'foo' => 'supers3cret', 'bar' => 'token' }
)
end
let(:data) { super().merge(response_headers: { 'X-Token-Id' => 'supers3cret-token', 'X-Request' => 'PUBLIC-token' }) }
let(:expected_headers) { { 'X-Token-Id' => '{foo}-{bar}', 'X-Request' => 'PUBLIC-{bar}' } }
it 'logs the data and masks response headers' do
expect { service.execute }.to change(::WebHookLog, :count).by(1)
expect(WebHookLog.recent.first.response_headers).to eq(expected_headers)
end
end
context 'with X-Gitlab-Token' do
let(:request_headers) { { 'X-Gitlab-Token' => project_hook.token } }
it 'redacts the token' do
service.execute
expect(WebHookLog.recent.first.request_headers).to include('X-Gitlab-Token' => '[REDACTED]')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WebHooks
class LogDestroyService
BATCH_SIZE = 1000
def initialize(web_hook_id)
@web_hook_id = web_hook_id
end
def execute
next while WebHookLog.delete_batch_for(@web_hook_id, batch_size: BATCH_SIZE)
ServiceResponse.success
rescue StandardError => ex
ServiceResponse.error(message: ex.message)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WebHooks::LogDestroyService, feature_category: :webhooks do
subject(:service) { described_class.new(hook.id) }
describe '#execute' do
shared_examples 'deletes web hook logs for hook' do
before do
create_list(:web_hook_log, 3, web_hook: hook)
hook.destroy! # The LogDestroyService is expected to be called _after_ hook destruction
end
it 'deletes the logs' do
expect { service.execute }
.to change(WebHookLog, :count).from(3).to(0)
end
context 'when the data-set exceeds the batch size' do
before do
stub_const("#{described_class}::BATCH_SIZE", 2)
end
it 'deletes the logs' do
expect { service.execute }
.to change(WebHookLog, :count).from(3).to(0)
end
end
context 'when it encounters an error' do
before do
allow(WebHookLog).to receive(:delete_batch_for).and_raise(StandardError.new('bang'))
end
it 'reports the error' do
expect(service.execute)
.to be_error
.and have_attributes(message: 'bang')
end
end
end
context 'with system hook' do
let!(:hook) { create(:system_hook, url: "http://example.com") }
it_behaves_like 'deletes web hook logs for hook'
end
context 'with project hook' do
let!(:hook) { create(:project_hook) }
it_behaves_like 'deletes web hook logs for hook'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WebHooks
# Destroy a hook, and schedule the logs for deletion.
class DestroyService
include Services::ReturnServiceResponses
attr_accessor :current_user
DENIED = 'Insufficient permissions'
def initialize(current_user)
@current_user = current_user
end
def execute(web_hook)
return error(DENIED, 401) unless authorized?(web_hook)
hook_id = web_hook.id
if web_hook.destroy
WebHooks::LogDestroyWorker.perform_async({ 'hook_id' => hook_id })
Gitlab::AppLogger.info(log_message(web_hook))
success({ async: false })
else
error("Unable to destroy #{web_hook.model_name.human}", 500)
end
end
private
def log_message(hook)
"User #{current_user&.id} scheduled a deletion of logs for hook ID #{hook.id}"
end
def authorized?(web_hook)
Ability.allowed?(current_user, :destroy_web_hook, web_hook)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WebHooks::DestroyService, feature_category: :webhooks do
let_it_be(:user) { create(:user) }
subject { described_class.new(user) }
describe '#execute' do
# Testing with a project hook only - for permission tests, see policy specs.
let!(:hook) { create(:project_hook) }
let!(:log) { create_list(:web_hook_log, 3, web_hook: hook) }
context 'when the user does not have permission' do
it 'is an error' do
expect(subject.execute(hook))
.to be_error
.and have_attributes(message: described_class::DENIED)
end
end
context 'when the user does have permission' do
before do
hook.project.add_maintainer(user)
end
it 'is successful' do
expect(subject.execute(hook)).to be_success
end
it 'destroys the hook' do
expect { subject.execute(hook) }.to change(WebHook, :count).from(1).to(0)
end
it 'does not destroy logs' do
expect { subject.execute(hook) }.not_to change(WebHookLog, :count)
end
it 'schedules the destruction of logs' do
expect(WebHooks::LogDestroyWorker).to receive(:perform_async).with({ 'hook_id' => hook.id })
expect(Gitlab::AppLogger).to receive(:info).with(match(/scheduled a deletion of logs/))
subject.execute(hook)
end
context 'when the hook fails to destroy' do
before do
allow(hook).to receive(:destroy).and_return(false)
end
it 'is not a success' do
expect(WebHooks::LogDestroyWorker).not_to receive(:perform_async)
r = subject.execute(hook)
expect(r).to be_error
expect(r[:message]).to match %r{Unable to destroy}
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ContainerRegistry
module Protection
class CreateRuleService < BaseService
ALLOWED_ATTRIBUTES = %i[
container_path_pattern
push_protected_up_to_access_level
delete_protected_up_to_access_level
].freeze
def execute
unless can?(current_user, :admin_container_image, project)
error_message = _('Unauthorized to create a container registry protection rule')
return service_response_error(message: error_message)
end
container_registry_protection_rule =
project.container_registry_protection_rules.create(params.slice(*ALLOWED_ATTRIBUTES))
unless container_registry_protection_rule.persisted?
return service_response_error(message: container_registry_protection_rule.errors.full_messages.to_sentence)
end
ServiceResponse.success(payload: { container_registry_protection_rule: container_registry_protection_rule })
rescue StandardError => e
service_response_error(message: e.message)
end
private
def service_response_error(message:)
ServiceResponse.error(
message: message,
payload: { container_registry_protection_rule: nil }
)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ContainerRegistry::Protection::CreateRuleService, '#execute', feature_category: :container_registry do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:current_user) { create(:user, maintainer_projects: [project]) }
let(:service) { described_class.new(project, current_user, params) }
let(:params) { attributes_for(:container_registry_protection_rule) }
subject { service.execute }
shared_examples 'a successful service response' do
it { is_expected.to be_success }
it { is_expected.to have_attributes(errors: be_blank) }
it do
is_expected.to have_attributes(
payload: {
container_registry_protection_rule:
be_a(ContainerRegistry::Protection::Rule)
.and(have_attributes(
container_path_pattern: params[:container_path_pattern],
push_protected_up_to_access_level: params[:push_protected_up_to_access_level].to_s,
delete_protected_up_to_access_level: params[:delete_protected_up_to_access_level].to_s
))
}
)
end
it 'creates a new container registry protection rule in the database' do
expect { subject }.to change { ContainerRegistry::Protection::Rule.count }.by(1)
expect(
ContainerRegistry::Protection::Rule.where(
project: project,
container_path_pattern: params[:container_path_pattern],
push_protected_up_to_access_level: params[:push_protected_up_to_access_level]
)
).to exist
end
end
shared_examples 'an erroneous service response' do
it { is_expected.to be_error }
it { is_expected.to have_attributes(errors: be_present, payload: include(container_registry_protection_rule: nil)) }
it 'does not create a new container registry protection rule in the database' do
expect { subject }.not_to change { ContainerRegistry::Protection::Rule.count }
end
it 'does not create a container registry protection rule with the given params' do
subject
expect(
ContainerRegistry::Protection::Rule.where(
project: project,
container_path_pattern: params[:container_path_pattern],
push_protected_up_to_access_level: params[:push_protected_up_to_access_level]
)
).not_to exist
end
end
it_behaves_like 'a successful service response'
context 'when fields are invalid' do
context 'when container_path_pattern is invalid' do
let(:params) { super().merge(container_path_pattern: '') }
it_behaves_like 'an erroneous service response'
it { is_expected.to have_attributes(message: match(/Container path pattern can't be blank/)) }
end
context 'when delete_protected_up_to_access_level is invalid' do
let(:params) { super().merge(delete_protected_up_to_access_level: 1000) }
it_behaves_like 'an erroneous service response'
it { is_expected.to have_attributes(message: match(/is not a valid delete_protected_up_to_access_level/)) }
end
context 'when push_protected_up_to_access_level is invalid' do
let(:params) { super().merge(push_protected_up_to_access_level: 1000) }
it_behaves_like 'an erroneous service response'
it { is_expected.to have_attributes(message: match(/is not a valid push_protected_up_to_access_level/)) }
end
end
context 'with existing container registry protection rule in the database' do
let_it_be_with_reload(:existing_container_registry_protection_rule) do
create(:container_registry_protection_rule, project: project)
end
context 'when container registry name pattern is slightly different' do
let(:params) do
super().merge(
# The field `container_path_pattern` is unique; this is why we change the value in a minimum way
container_path_pattern: "#{existing_container_registry_protection_rule.container_path_pattern}-unique",
push_protected_up_to_access_level:
existing_container_registry_protection_rule.push_protected_up_to_access_level
)
end
it_behaves_like 'a successful service response'
end
context 'when field `container_path_pattern` is taken' do
let(:params) do
super().merge(
container_path_pattern: existing_container_registry_protection_rule.container_path_pattern,
push_protected_up_to_access_level: :maintainer
)
end
it_behaves_like 'an erroneous service response'
it { is_expected.to have_attributes(errors: ['Container path pattern has already been taken']) }
it { expect { subject }.not_to change { existing_container_registry_protection_rule.updated_at } }
end
end
context 'with disallowed params' do
let(:params) { super().merge(project_id: 1, unsupported_param: 'unsupported_param_value') }
it_behaves_like 'a successful service response'
end
context 'with forbidden user access level (project developer role)' do
# Because of the access level hierarchy, we can assume that
# other access levels below developer role will also not be able to
# create container registry protection rules.
let_it_be(:current_user) { create(:user).tap { |u| project.add_developer(u) } }
it_behaves_like 'an erroneous service response'
it { is_expected.to have_attributes(message: match(/Unauthorized/)) }
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module LooseForeignKeys
class ProcessDeletedRecordsService
BATCH_SIZE = 1000
def initialize(connection:, modification_tracker: LooseForeignKeys::ModificationTracker.new)
@connection = connection
@modification_tracker = modification_tracker
end
def execute
raised_error = false
tracked_tables.cycle do |table|
records = load_batch_for_table(table)
if records.empty?
tracked_tables.delete(table)
next
end
break if modification_tracker.over_limit?
loose_foreign_key_definitions = Gitlab::Database::LooseForeignKeys.definitions_by_table[table]
next if loose_foreign_key_definitions.empty?
LooseForeignKeys::BatchCleanerService
.new(
parent_table: table,
loose_foreign_key_definitions: loose_foreign_key_definitions,
deleted_parent_records: records,
modification_tracker: modification_tracker)
.execute
break if modification_tracker.over_limit?
end
::Gitlab::Metrics::LooseForeignKeysSlis.record_apdex(
success: !modification_tracker.over_limit?,
db_config_name: db_config_name
)
modification_tracker.stats
rescue StandardError
raised_error = true
raise
ensure
::Gitlab::Metrics::LooseForeignKeysSlis.record_error_rate(
error: raised_error,
db_config_name: db_config_name
)
end
private
attr_reader :connection, :modification_tracker
def db_config_name
::Gitlab::Database.db_config_name(connection)
end
def load_batch_for_table(table)
fully_qualified_table_name = "#{current_schema}.#{table}"
LooseForeignKeys::DeletedRecord.load_batch_for_table(fully_qualified_table_name, BATCH_SIZE)
end
def current_schema
@current_schema = connection.current_schema
end
def tracked_tables
@tracked_tables ||= Gitlab::Database::LooseForeignKeys.definitions_by_table.keys.shuffle
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe LooseForeignKeys::ProcessDeletedRecordsService, feature_category: :database do
include MigrationsHelpers
def create_table_structure
migration = ActiveRecord::Migration.new.extend(Gitlab::Database::MigrationHelpers::LooseForeignKeyHelpers)
migration.create_table :_test_loose_fk_parent_table_1
migration.create_table :_test_loose_fk_parent_table_2
migration.create_table :_test_loose_fk_child_table_1_1 do |t|
t.bigint :parent_id
end
migration.create_table :_test_loose_fk_child_table_1_2 do |t|
t.bigint :parent_id_with_different_column
end
migration.create_table :_test_loose_fk_child_table_2_1 do |t|
t.bigint :parent_id
end
migration.track_record_deletions(:_test_loose_fk_parent_table_1)
migration.track_record_deletions(:_test_loose_fk_parent_table_2)
end
let(:all_loose_foreign_key_definitions) do
{
'_test_loose_fk_parent_table_1' => [
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
'_test_loose_fk_child_table_1_1',
'_test_loose_fk_parent_table_1',
{
column: 'parent_id',
on_delete: :async_delete,
gitlab_schema: :gitlab_main
}
),
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
'_test_loose_fk_child_table_1_2',
'_test_loose_fk_parent_table_1',
{
column: 'parent_id_with_different_column',
on_delete: :async_nullify,
gitlab_schema: :gitlab_main
}
)
],
'_test_loose_fk_parent_table_2' => [
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
'_test_loose_fk_child_table_2_1',
'_test_loose_fk_parent_table_2',
{
column: 'parent_id',
on_delete: :async_delete,
gitlab_schema: :gitlab_main
}
)
]
}
end
let(:connection) { ::ApplicationRecord.connection }
let(:loose_fk_parent_table_1) { table(:_test_loose_fk_parent_table_1) }
let(:loose_fk_parent_table_2) { table(:_test_loose_fk_parent_table_2) }
let(:loose_fk_child_table_1_1) { table(:_test_loose_fk_child_table_1_1) }
let(:loose_fk_child_table_1_2) { table(:_test_loose_fk_child_table_1_2) }
let(:loose_fk_child_table_2_1) { table(:_test_loose_fk_child_table_2_1) }
before_all do
create_table_structure
end
after(:all) do
migration = ActiveRecord::Migration.new
migration.drop_table :_test_loose_fk_parent_table_1
migration.drop_table :_test_loose_fk_parent_table_2
migration.drop_table :_test_loose_fk_child_table_1_1
migration.drop_table :_test_loose_fk_child_table_1_2
migration.drop_table :_test_loose_fk_child_table_2_1
end
before do
allow(Gitlab::Database::LooseForeignKeys).to receive(:definitions_by_table)
.and_return(all_loose_foreign_key_definitions)
parent_record_1 = loose_fk_parent_table_1.create!
loose_fk_child_table_1_1.create!(parent_id: parent_record_1.id)
loose_fk_child_table_1_2.create!(parent_id_with_different_column: parent_record_1.id)
parent_record_2 = loose_fk_parent_table_1.create!
2.times { loose_fk_child_table_1_1.create!(parent_id: parent_record_2.id) }
3.times { loose_fk_child_table_1_2.create!(parent_id_with_different_column: parent_record_2.id) }
parent_record_3 = loose_fk_parent_table_2.create!
5.times { loose_fk_child_table_2_1.create!(parent_id: parent_record_3.id) }
loose_fk_parent_table_1.delete_all
loose_fk_parent_table_2.delete_all
end
describe '#execute' do
def execute
::Gitlab::Database::SharedModel.using_connection(connection) do
described_class.new(connection: connection).execute
end
end
it 'cleans up all rows' do
execute
expect(loose_fk_child_table_1_1.count).to eq(0)
expect(loose_fk_child_table_1_2.where(parent_id_with_different_column: nil).count).to eq(4)
expect(loose_fk_child_table_2_1.count).to eq(0)
end
it 'returns stats for records cleaned up' do
stats = execute
expect(stats[:delete_count]).to eq(8)
expect(stats[:update_count]).to eq(4)
end
it 'records the Apdex as success: true' do
expect(::Gitlab::Metrics::LooseForeignKeysSlis).to receive(:record_apdex)
.with(success: true, db_config_name: 'main')
execute
end
it 'records the error rate as error: false' do
expect(::Gitlab::Metrics::LooseForeignKeysSlis).to receive(:record_error_rate)
.with(error: false, db_config_name: 'main')
execute
end
context 'when the amount of records to clean up exceeds BATCH_SIZE' do
before do
stub_const('LooseForeignKeys::CleanupWorker::BATCH_SIZE', 2)
end
it 'cleans up everything over multiple batches' do
expect(LooseForeignKeys::BatchCleanerService).to receive(:new).exactly(:twice).and_call_original
execute
expect(loose_fk_child_table_1_1.count).to eq(0)
expect(loose_fk_child_table_1_2.where(parent_id_with_different_column: nil).count).to eq(4)
expect(loose_fk_child_table_2_1.count).to eq(0)
end
end
context 'when the amount of records to clean up exceeds the total MAX_DELETES' do
def count_deletable_rows
loose_fk_child_table_1_1.count + loose_fk_child_table_2_1.count
end
before do
allow_next_instance_of(LooseForeignKeys::ModificationTracker) do |instance|
allow(instance).to receive(:max_deletes).and_return(2)
end
stub_const('LooseForeignKeys::CleanerService::DELETE_LIMIT', 1)
end
it 'cleans up MAX_DELETES and leaves the rest for the next run' do
expect { execute }.to change { count_deletable_rows }.by(-2)
expect(count_deletable_rows).to be > 0
end
it 'records the Apdex as success: false' do
expect(::Gitlab::Metrics::LooseForeignKeysSlis).to receive(:record_apdex)
.with(success: false, db_config_name: 'main')
execute
end
end
context 'when cleanup raises an error' do
before do
expect_next_instance_of(::LooseForeignKeys::BatchCleanerService) do |service|
allow(service).to receive(:execute).and_raise("Something broke")
end
end
it 'records the error rate as error: true and does not increment apdex' do
expect(::Gitlab::Metrics::LooseForeignKeysSlis).to receive(:record_error_rate)
.with(error: true, db_config_name: 'main')
expect(::Gitlab::Metrics::LooseForeignKeysSlis).not_to receive(:record_apdex)
expect { execute }.to raise_error("Something broke")
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module LooseForeignKeys
# rubocop: disable CodeReuse/ActiveRecord
class CleanerService
DELETE_LIMIT = 1000
UPDATE_LIMIT = 500
def initialize(loose_foreign_key_definition:, connection:, deleted_parent_records:, with_skip_locked: false)
@loose_foreign_key_definition = loose_foreign_key_definition
@connection = connection
@deleted_parent_records = deleted_parent_records
@with_skip_locked = with_skip_locked
end
def execute
result = connection.execute(build_query)
{ affected_rows: result.cmd_tuples, table: loose_foreign_key_definition.from_table }
end
def async_delete?
loose_foreign_key_definition.on_delete == :async_delete
end
def async_nullify?
loose_foreign_key_definition.on_delete == :async_nullify
end
private
attr_reader :loose_foreign_key_definition, :connection, :deleted_parent_records, :with_skip_locked
def build_query
query = if async_delete?
delete_query
elsif async_nullify?
update_query
else
raise "Invalid on_delete argument: #{loose_foreign_key_definition.on_delete}"
end
unless query.include?(%{"#{loose_foreign_key_definition.column}" IN (})
raise("FATAL: foreign key condition is missing from the generated query: #{query}")
end
query
end
def arel_table
@arel_table ||= Arel::Table.new(loose_foreign_key_definition.from_table)
end
def primary_keys
@primary_keys ||= connection.primary_keys(loose_foreign_key_definition.from_table).map { |key| arel_table[key] }
end
def quoted_table_name
@quoted_table_name ||= Arel.sql(connection.quote_table_name(loose_foreign_key_definition.from_table))
end
def delete_query
query = Arel::DeleteManager.new
query.from(quoted_table_name)
add_in_query_with_limit(query, DELETE_LIMIT)
end
def update_query
query = Arel::UpdateManager.new
query.table(quoted_table_name)
query.set([[arel_table[loose_foreign_key_definition.column], nil]])
add_in_query_with_limit(query, UPDATE_LIMIT)
end
# IN query with one or composite primary key
# WHERE (primary_key1, primary_key2) IN (subselect)
def add_in_query_with_limit(query, limit)
columns = Arel::Nodes::Grouping.new(primary_keys)
query.where(columns.in(in_query_with_limit(limit))).to_sql
end
# Builds the following sub-query
# SELECT primary_keys FROM table WHERE foreign_key IN (1, 2, 3) LIMIT N
def in_query_with_limit(limit)
in_query = Arel::SelectManager.new
in_query.from(quoted_table_name)
in_query.where(arel_table[loose_foreign_key_definition.column].in(deleted_parent_records.map(&:primary_key_value)))
in_query.projections = primary_keys
in_query.take(limit)
in_query.lock(Arel.sql('FOR UPDATE SKIP LOCKED')) if with_skip_locked
in_query
end
end
# rubocop: enable CodeReuse/ActiveRecord
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe LooseForeignKeys::CleanerService, feature_category: :database do
let(:schema) { ApplicationRecord.connection.current_schema }
let(:deleted_records) do
[
LooseForeignKeys::DeletedRecord.new(fully_qualified_table_name: "#{schema}.projects", primary_key_value: non_existing_record_id),
LooseForeignKeys::DeletedRecord.new(fully_qualified_table_name: "#{schema}.projects", primary_key_value: non_existing_record_id)
]
end
let(:loose_fk_definition) do
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
'issues',
'projects',
{
column: 'project_id',
on_delete: :async_nullify,
gitlab_schema: :gitlab_main
}
)
end
subject(:cleaner_service) do
described_class.new(
loose_foreign_key_definition: loose_fk_definition,
connection: ApplicationRecord.connection,
deleted_parent_records: deleted_records)
end
context 'when invalid foreign key definition is passed' do
context 'when invalid on_delete argument was given' do
before do
loose_fk_definition.options[:on_delete] = :invalid
end
it 'raises KeyError' do
expect { cleaner_service.execute }.to raise_error(StandardError, /Invalid on_delete argument/)
end
end
end
describe 'query generation' do
context 'when single primary key is used' do
let(:issue) { create(:issue) }
let(:deleted_records) do
[
LooseForeignKeys::DeletedRecord.new(fully_qualified_table_name: "#{schema}.projects", primary_key_value: issue.project_id)
]
end
it 'generates an IN query for nullifying the rows' do
expected_query = %{UPDATE "issues" SET "project_id" = NULL WHERE ("issues"."id") IN (SELECT "issues"."id" FROM "issues" WHERE "issues"."project_id" IN (#{issue.project_id}) LIMIT 500)}
expect(ApplicationRecord.connection).to receive(:execute).with(expected_query).and_call_original
cleaner_service.execute
issue.reload
expect(issue.project_id).to be_nil
end
it 'generates an IN query for deleting the rows' do
loose_fk_definition.options[:on_delete] = :async_delete
expected_query = %{DELETE FROM "issues" WHERE ("issues"."id") IN (SELECT "issues"."id" FROM "issues" WHERE "issues"."project_id" IN (#{issue.project_id}) LIMIT 1000)}
expect(ApplicationRecord.connection).to receive(:execute).with(expected_query).and_call_original
cleaner_service.execute
expect(Issue.exists?(id: issue.id)).to eq(false)
end
end
context 'when composite primary key is used' do
let!(:user) { create(:user) }
let!(:project) { create(:project) }
let(:loose_fk_definition) do
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
'project_authorizations',
'users',
{
column: 'user_id',
on_delete: :async_delete,
gitlab_schema: :gitlab_main
}
)
end
let(:deleted_records) do
[
LooseForeignKeys::DeletedRecord.new(fully_qualified_table_name: "#{schema}.users", primary_key_value: user.id)
]
end
subject(:cleaner_service) do
described_class.new(
loose_foreign_key_definition: loose_fk_definition,
connection: ApplicationRecord.connection,
deleted_parent_records: deleted_records
)
end
before do
project.add_developer(user)
end
it 'generates an IN query for deleting the rows' do
expected_query = %{DELETE FROM "project_authorizations" WHERE ("project_authorizations"."user_id", "project_authorizations"."project_id", "project_authorizations"."access_level") IN (SELECT "project_authorizations"."user_id", "project_authorizations"."project_id", "project_authorizations"."access_level" FROM "project_authorizations" WHERE "project_authorizations"."user_id" IN (#{user.id}) LIMIT 1000)}
expect(ApplicationRecord.connection).to receive(:execute).with(expected_query).and_call_original
cleaner_service.execute
expect(ProjectAuthorization.exists?(user_id: user.id)).to eq(false)
end
context 'when the query generation is incorrect (paranoid check)' do
it 'raises error if the foreign key condition is missing' do
expect_next_instance_of(LooseForeignKeys::CleanerService) do |instance|
expect(instance).to receive(:delete_query).and_return('wrong query')
end
expect { cleaner_service.execute }.to raise_error /FATAL: foreign key condition is missing from the generated query/
end
end
end
context 'when with_skip_locked parameter is true' do
subject(:cleaner_service) do
described_class.new(
loose_foreign_key_definition: loose_fk_definition,
connection: ApplicationRecord.connection,
deleted_parent_records: deleted_records,
with_skip_locked: true
)
end
it 'generates a query with the SKIP LOCKED clause' do
expect(ApplicationRecord.connection).to receive(:execute).with(/FOR UPDATE SKIP LOCKED/).and_call_original
cleaner_service.execute
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module LooseForeignKeys
class BatchCleanerService
CLEANUP_ATTEMPTS_BEFORE_RESCHEDULE = 3
CONSUME_AFTER_RESCHEDULE = 5.minutes
def initialize(parent_table:, loose_foreign_key_definitions:, deleted_parent_records:, modification_tracker: LooseForeignKeys::ModificationTracker.new)
@parent_table = parent_table
@loose_foreign_key_definitions = loose_foreign_key_definitions
@deleted_parent_records = deleted_parent_records
@modification_tracker = modification_tracker
@deleted_records_counter = Gitlab::Metrics.counter(
:loose_foreign_key_processed_deleted_records,
'The number of processed loose foreign key deleted records'
)
@deleted_records_rescheduled_count = Gitlab::Metrics.counter(
:loose_foreign_key_rescheduled_deleted_records,
'The number of rescheduled loose foreign key deleted records'
)
@deleted_records_incremented_count = Gitlab::Metrics.counter(
:loose_foreign_key_incremented_deleted_records,
'The number of loose foreign key deleted records with incremented cleanup_attempts'
)
end
def execute
loose_foreign_key_definitions.each do |loose_foreign_key_definition|
run_cleaner_service(loose_foreign_key_definition, with_skip_locked: true)
if modification_tracker.over_limit?
handle_over_limit
break
end
run_cleaner_service(loose_foreign_key_definition, with_skip_locked: false)
if modification_tracker.over_limit?
handle_over_limit
break
end
end
return if modification_tracker.over_limit?
# At this point, all associations are cleaned up, we can update the status of the parent records
update_count = LooseForeignKeys::DeletedRecord.mark_records_processed(deleted_parent_records)
deleted_records_counter.increment({ table: parent_table, db_config_name: db_config_name }, update_count)
end
private
attr_reader :parent_table, :loose_foreign_key_definitions, :deleted_parent_records, :modification_tracker, :deleted_records_counter, :deleted_records_rescheduled_count, :deleted_records_incremented_count
def handle_over_limit
records_to_reschedule = []
records_to_increment = []
deleted_parent_records.each do |deleted_record|
if deleted_record.cleanup_attempts >= CLEANUP_ATTEMPTS_BEFORE_RESCHEDULE
records_to_reschedule << deleted_record
else
records_to_increment << deleted_record
end
end
reschedule_count = LooseForeignKeys::DeletedRecord.reschedule(records_to_reschedule, CONSUME_AFTER_RESCHEDULE.from_now)
deleted_records_rescheduled_count.increment({ table: parent_table, db_config_name: db_config_name }, reschedule_count)
increment_count = LooseForeignKeys::DeletedRecord.increment_attempts(records_to_increment)
deleted_records_incremented_count.increment({ table: parent_table, db_config_name: db_config_name }, increment_count)
end
def record_result(cleaner, result)
if cleaner.async_delete?
modification_tracker.add_deletions(result[:table], result[:affected_rows])
elsif cleaner.async_nullify?
modification_tracker.add_updates(result[:table], result[:affected_rows])
end
end
def run_cleaner_service(loose_foreign_key_definition, with_skip_locked:)
base_models_for_gitlab_schema = Gitlab::Database.schemas_to_base_models.fetch(loose_foreign_key_definition.options[:gitlab_schema])
base_models_for_gitlab_schema.each do |base_model|
cleaner = CleanerService.new(
loose_foreign_key_definition: loose_foreign_key_definition,
connection: base_model.connection,
deleted_parent_records: deleted_parent_records,
with_skip_locked: with_skip_locked
)
loop do
result = cleaner.execute
record_result(cleaner, result)
break if modification_tracker.over_limit? || result[:affected_rows] == 0
end
end
end
def db_config_name
LooseForeignKeys::DeletedRecord.connection.pool.db_config.name
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe LooseForeignKeys::BatchCleanerService, feature_category: :database do
include MigrationsHelpers
def create_table_structure
migration = ActiveRecord::Migration.new.extend(Gitlab::Database::MigrationHelpers::LooseForeignKeyHelpers)
migration.create_table :_test_loose_fk_parent_table
migration.create_table :_test_loose_fk_child_table_1 do |t|
t.bigint :parent_id
end
migration.create_table :_test_loose_fk_child_table_2 do |t|
t.bigint :parent_id_with_different_column
end
migration.track_record_deletions(:_test_loose_fk_parent_table)
end
let(:loose_foreign_key_definitions) do
[
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
'_test_loose_fk_child_table_1',
'_test_loose_fk_parent_table',
{
column: 'parent_id',
on_delete: :async_delete,
gitlab_schema: :gitlab_main
}
),
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(
'_test_loose_fk_child_table_2',
'_test_loose_fk_parent_table',
{
column: 'parent_id_with_different_column',
on_delete: :async_nullify,
gitlab_schema: :gitlab_main
}
)
]
end
let(:loose_fk_parent_table) { table(:_test_loose_fk_parent_table) }
let(:loose_fk_child_table_1) { table(:_test_loose_fk_child_table_1) }
let(:loose_fk_child_table_2) { table(:_test_loose_fk_child_table_2) }
let(:parent_record_1) { loose_fk_parent_table.create! }
let(:other_parent_record) { loose_fk_parent_table.create! }
before_all do
create_table_structure
end
before do
parent_record_1
loose_fk_child_table_1.create!(parent_id: parent_record_1.id)
loose_fk_child_table_1.create!(parent_id: parent_record_1.id)
# these will not be deleted
loose_fk_child_table_1.create!(parent_id: other_parent_record.id)
loose_fk_child_table_1.create!(parent_id: other_parent_record.id)
loose_fk_child_table_2.create!(parent_id_with_different_column: parent_record_1.id)
loose_fk_child_table_2.create!(parent_id_with_different_column: parent_record_1.id)
# these will not be deleted
loose_fk_child_table_2.create!(parent_id_with_different_column: other_parent_record.id)
loose_fk_child_table_2.create!(parent_id_with_different_column: other_parent_record.id)
end
after(:all) do
migration = ActiveRecord::Migration.new
migration.drop_table :_test_loose_fk_parent_table
migration.drop_table :_test_loose_fk_child_table_1
migration.drop_table :_test_loose_fk_child_table_2
end
context 'when parent records are deleted' do
let(:deleted_records_counter) { Gitlab::Metrics.registry.get(:loose_foreign_key_processed_deleted_records) }
before do
parent_record_1.delete
expect(loose_fk_child_table_1.count).to eq(4)
expect(loose_fk_child_table_2.count).to eq(4)
described_class.new(
parent_table: '_test_loose_fk_parent_table',
loose_foreign_key_definitions: loose_foreign_key_definitions,
deleted_parent_records: LooseForeignKeys::DeletedRecord.load_batch_for_table('public._test_loose_fk_parent_table', 100)
).execute
end
it 'cleans up the child records' do
expect(loose_fk_child_table_1.where(parent_id: parent_record_1.id)).to be_empty
expect(loose_fk_child_table_2.where(parent_id_with_different_column: nil).count).to eq(2)
end
it 'cleans up the pending parent DeletedRecord' do
expect(LooseForeignKeys::DeletedRecord.status_pending.count).to eq(0)
expect(LooseForeignKeys::DeletedRecord.status_processed.count).to eq(1)
end
it 'records the DeletedRecord status updates', :prometheus do
counter = Gitlab::Metrics.registry.get(:loose_foreign_key_processed_deleted_records)
expect(counter.get(table: loose_fk_parent_table.table_name, db_config_name: 'main')).to eq(1)
end
it 'does not delete unrelated records' do
expect(loose_fk_child_table_1.where(parent_id: other_parent_record.id).count).to eq(2)
expect(loose_fk_child_table_2.where(parent_id_with_different_column: other_parent_record.id).count).to eq(2)
end
end
describe 'fair queueing' do
context 'when the execution is over the limit' do
let(:modification_tracker) { instance_double(LooseForeignKeys::ModificationTracker) }
let(:over_limit_return_values) { [true] }
let(:deleted_record) { LooseForeignKeys::DeletedRecord.load_batch_for_table('public._test_loose_fk_parent_table', 1).first }
let(:deleted_records_rescheduled_counter) { Gitlab::Metrics.registry.get(:loose_foreign_key_rescheduled_deleted_records) }
let(:deleted_records_incremented_counter) { Gitlab::Metrics.registry.get(:loose_foreign_key_incremented_deleted_records) }
let(:cleaner) do
described_class.new(
parent_table: '_test_loose_fk_parent_table',
loose_foreign_key_definitions: loose_foreign_key_definitions,
deleted_parent_records: LooseForeignKeys::DeletedRecord.load_batch_for_table('public._test_loose_fk_parent_table', 100),
modification_tracker: modification_tracker
)
end
before do
parent_record_1.delete
allow(modification_tracker).to receive(:over_limit?).and_return(*over_limit_return_values)
allow(modification_tracker).to receive(:add_deletions)
end
context 'when the deleted record is under the maximum allowed cleanup attempts' do
it 'updates the cleanup_attempts column', :aggregate_failures do
deleted_record.update!(cleanup_attempts: 1)
cleaner.execute
expect(deleted_record.reload.cleanup_attempts).to eq(2)
expect(deleted_records_incremented_counter.get(table: loose_fk_parent_table.table_name, db_config_name: 'main')).to eq(1)
end
context 'when the deleted record is above the maximum allowed cleanup attempts' do
it 'reschedules the record', :aggregate_failures do
deleted_record.update!(cleanup_attempts: LooseForeignKeys::BatchCleanerService::CLEANUP_ATTEMPTS_BEFORE_RESCHEDULE + 1)
freeze_time do
cleaner.execute
expect(deleted_record.reload).to have_attributes(
cleanup_attempts: 0,
consume_after: 5.minutes.from_now
)
expect(deleted_records_rescheduled_counter.get(table: loose_fk_parent_table.table_name, db_config_name: 'main')).to eq(1)
end
end
end
describe 'when over limit happens on the second cleanup call without skip locked' do
# over_limit? is called twice, we test here the 2nd call
# - When invoking cleanup with SKIP LOCKED
# - When invoking cleanup (no SKIP LOCKED)
let(:over_limit_return_values) { [false, true] }
it 'updates the cleanup_attempts column' do
expect(cleaner).to receive(:run_cleaner_service).twice
deleted_record.update!(cleanup_attempts: 1)
cleaner.execute
expect(deleted_record.reload.cleanup_attempts).to eq(2)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
#
# Used by NotificationService to determine who should receive notification
#
module NotificationRecipients
module BuildService
def self.notifiable_users(users, *args)
users.compact.map { |u| NotificationRecipient.new(u, *args) }.select(&:notifiable?).map(&:user)
end
def self.notifiable?(user, *args)
NotificationRecipient.new(user, *args).notifiable?
end
def self.build_recipients(target, current_user, **args)
::NotificationRecipients::Builder::Default.new(target, current_user, **args).notification_recipients
end
def self.build_new_note_recipients(...)
::NotificationRecipients::Builder::NewNote.new(...).notification_recipients
end
def self.build_merge_request_unmergeable_recipients(...)
::NotificationRecipients::Builder::MergeRequestUnmergeable.new(...).notification_recipients
end
def self.build_project_maintainers_recipients(target, **args)
::NotificationRecipients::Builder::ProjectMaintainers.new(target, **args).notification_recipients
end
def self.build_new_review_recipients(...)
::NotificationRecipients::Builder::NewReview.new(...).notification_recipients
end
def self.build_requested_review_recipients(...)
::NotificationRecipients::Builder::RequestReview.new(...).notification_recipients
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe NotificationRecipients::BuildService, feature_category: :team_planning do
let(:service) { described_class }
let(:assignee) { create(:user) }
let(:project) { create(:project, :public) }
let(:other_projects) { create_list(:project, 5, :public) }
describe '#build_new_note_recipients' do
let(:issue) { create(:issue, project: project, assignees: [assignee]) }
let(:note) { create(:note_on_issue, noteable: issue, project_id: issue.project_id) }
shared_examples 'no N+1 queries' do
it 'avoids N+1 queries', :request_store do
# existing N+1 due to multiple users having to be looked up in the project_authorizations table
threshold = project.private? ? 1 : 0
create_user
service.build_new_note_recipients(note)
control_count = ActiveRecord::QueryRecorder.new do
service.build_new_note_recipients(note)
end
create_user
expect { service.build_new_note_recipients(note) }.not_to exceed_query_limit(control_count).with_threshold(threshold)
end
end
context 'when there are multiple watchers' do
def create_user
watcher = create(:user)
create(:notification_setting, source: project, user: watcher, level: :watch)
other_projects.each do |other_project|
create(:notification_setting, source: other_project, user: watcher, level: :watch)
end
end
include_examples 'no N+1 queries'
end
context 'when there are multiple subscribers' do
def create_user
subscriber = create(:user)
issue.subscriptions.create!(user: subscriber, project: project, subscribed: true)
end
include_examples 'no N+1 queries'
context 'when the project is private' do
before do
project.update!(visibility_level: Gitlab::VisibilityLevel::PRIVATE)
end
include_examples 'no N+1 queries'
end
end
end
describe '#build_new_review_recipients' do
let(:merge_request) { create(:merge_request, source_project: project, target_project: project) }
let(:review) { create(:review, merge_request: merge_request, project: project, author: merge_request.author) }
let(:notes) { create_list(:note_on_merge_request, 3, review: review, noteable: review.merge_request, project: review.project) }
shared_examples 'no N+1 queries' do
it 'avoids N+1 queries', :request_store do
# existing N+1 due to multiple users having to be looked up in the project_authorizations table
threshold = project.private? ? 1 : 0
create_user
service.build_new_review_recipients(review)
control_count = ActiveRecord::QueryRecorder.new do
service.build_new_review_recipients(review)
end
create_user
expect { service.build_new_review_recipients(review) }.not_to exceed_query_limit(control_count).with_threshold(threshold)
end
end
context 'when there are multiple watchers' do
def create_user
watcher = create(:user)
create(:notification_setting, source: project, user: watcher, level: :watch)
other_projects.each do |other_project|
create(:notification_setting, source: other_project, user: watcher, level: :watch)
end
end
include_examples 'no N+1 queries'
end
context 'when there are multiple subscribers' do
def create_user
subscriber = create(:user)
merge_request.subscriptions.create!(user: subscriber, project: project, subscribed: true)
end
include_examples 'no N+1 queries'
context 'when the project is private' do
before do
project.update!(visibility_level: Gitlab::VisibilityLevel::PRIVATE)
end
include_examples 'no N+1 queries'
end
end
end
describe '#build_requested_review_recipients' do
let(:merge_request) { create(:merge_request, source_project: project, target_project: project) }
before do
merge_request.reviewers.push(assignee)
end
shared_examples 'no N+1 queries' do
it 'avoids N+1 queries', :request_store do
create_user
service.build_requested_review_recipients(note)
control_count = ActiveRecord::QueryRecorder.new do
service.build_requested_review_recipients(note)
end
create_user
expect { service.build_requested_review_recipients(note) }.not_to exceed_query_limit(control_count)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module NotificationRecipients
module Builder
class NewNote < Base
attr_reader :note
def initialize(note)
@note = note
end
def target
note.noteable
end
def recipients_target
note
end
# NOTE: may be nil, in the case of a PersonalSnippet
#
# (this is okay because NotificationRecipient is written
# to handle nil projects)
def project
note.project
end
def group
if note.for_project_noteable?
project.group
else
target.try(:group)
end
end
def build!
# Add all users participating in the thread (author, assignee, comment authors)
add_participants(note.author)
add_mentions(note.author, target: note)
if note.for_project_noteable?
# Merge project watchers
add_project_watchers
else
add_group_watchers
end
add_custom_notifications
add_subscribed_users
end
def custom_action
:new_note
end
def acting_user
note.author
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe NotificationRecipients::Builder::NewNote, feature_category: :team_planning do
describe '#notification_recipients' do
let_it_be(:group) { create(:group, :public) }
let_it_be(:project) { create(:project, :public, group: group) }
let_it_be(:issue) { create(:issue, project: project) }
let_it_be(:other_user) { create(:user) }
let_it_be(:participant) { create(:user) }
let_it_be(:non_member_participant) { create(:user) }
let_it_be(:group_watcher) { create(:user) }
let_it_be(:project_watcher) { create(:user) }
let_it_be(:guest_project_watcher) { create(:user) }
let_it_be(:subscriber) { create(:user) }
let_it_be(:unsubscribed_user) { create(:user) }
let_it_be(:non_member_subscriber) { create(:user) }
let_it_be(:notification_setting_project_w) { create(:notification_setting, source: project, user: project_watcher, level: 2) }
let_it_be(:notification_setting_guest_w) { create(:notification_setting, source: project, user: guest_project_watcher, level: 2) }
let_it_be(:notification_setting_group_w) { create(:notification_setting, source: group, user: group_watcher, level: 2) }
let_it_be(:subscriptions) do
[
create(:subscription, project: project, user: subscriber, subscribable: issue, subscribed: true),
create(:subscription, project: project, user: unsubscribed_user, subscribable: issue, subscribed: false),
create(:subscription, project: project, user: non_member_subscriber, subscribable: issue, subscribed: true)
]
end
subject { described_class.new(note) }
before do
project.add_developer(participant)
project.add_developer(project_watcher)
project.add_guest(guest_project_watcher)
project.add_developer(subscriber)
group.add_developer(group_watcher)
expect(issue).to receive(:participants).and_return([participant, non_member_participant])
end
context 'for public notes' do
let_it_be(:note) { create(:note, noteable: issue, project: project) }
it 'adds all participants, watchers and subscribers' do
expect(subject.notification_recipients.map(&:user)).to contain_exactly(
participant, non_member_participant, project_watcher, group_watcher, guest_project_watcher, subscriber, non_member_subscriber
)
end
end
context 'for confidential notes' do
let_it_be(:note) { create(:note, :confidential, noteable: issue, project: project) }
it 'adds all participants, watchers and subscribers that are project memebrs' do
expect(subject.notification_recipients.map(&:user)).to contain_exactly(
participant, project_watcher, group_watcher, subscriber
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module NotificationRecipients
module Builder
class Default < Base
MENTION_TYPE_ACTIONS = [:new_issue, :new_merge_request].freeze
attr_reader :target
attr_reader :current_user
attr_reader :action
attr_reader :previous_assignees
attr_reader :skip_current_user
def initialize(target, current_user, action:, custom_action: nil, previous_assignees: nil, skip_current_user: true)
@target = target
@current_user = current_user
@action = action
@custom_action = custom_action
@previous_assignees = previous_assignees
@skip_current_user = skip_current_user
end
def add_watchers
add_project_watchers
end
def build!
add_participants(current_user)
add_watchers
add_custom_notifications
# Re-assign is considered as a mention of the new assignee
case custom_action
when :reassign_merge_request, :reassign_issue
add_recipients(previous_assignees, :mention, nil)
add_recipients(target.assignees, :mention, NotificationReason::ASSIGNED)
when :change_reviewer_merge_request
add_recipients(previous_assignees, :mention, nil)
add_recipients(target.reviewers, :mention, NotificationReason::REVIEW_REQUESTED)
end
add_subscribed_users
if self.class.mention_type_actions.include?(custom_action)
# These will all be participants as well, but adding with the :mention
# type ensures that users with the mention notification level will
# receive them, too.
add_mentions(current_user, target: target)
# We use the `:participating` notification level in order to match existing legacy behavior as captured
# in existing specs (notification_service_spec.rb ~ line 507)
if target.is_a?(Issuable)
add_recipients(target.assignees, :participating, NotificationReason::ASSIGNED)
end
add_labels_subscribers
end
end
def acting_user
current_user if skip_current_user
end
# Build event key to search on custom notification level
# Check NotificationSetting.email_events
def custom_action
@custom_action ||= "#{action}_#{target.class.model_name.name.underscore}".to_sym
end
def self.mention_type_actions
MENTION_TYPE_ACTIONS.dup
end
end
end
end
NotificationRecipients::Builder::Default.prepend_mod_with('NotificationRecipients::Builder::Default')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe NotificationRecipients::Builder::Default, feature_category: :team_planning do
describe '#build!' do
let_it_be(:group) { create(:group, :public) }
let_it_be(:project) { create(:project, :public, group: group).tap { |p| p.add_developer(project_watcher) if project_watcher } }
let_it_be(:target) { create(:issue, project: project) }
let_it_be(:current_user) { create(:user) }
let_it_be(:other_user) { create(:user) }
let_it_be(:participant) { create(:user) }
let_it_be(:group_watcher) { create(:user) }
let_it_be(:project_watcher) { create(:user) }
let_it_be(:notification_setting_project_w) { create(:notification_setting, source: project, user: project_watcher, level: 2) }
let_it_be(:notification_setting_group_w) { create(:notification_setting, source: group, user: group_watcher, level: 2) }
subject { described_class.new(target, current_user, action: :new).tap { |s| s.build! } }
context 'participants and project watchers' do
before do
expect(target).to receive(:participants).and_return([participant, current_user])
end
it 'adds all participants and watchers' do
expect(subject.recipients.map(&:user)).to include(participant, project_watcher, group_watcher)
expect(subject.recipients.map(&:user)).not_to include(other_user)
end
end
context 'subscribers' do
it 'adds all subscribers' do
subscriber = create(:user)
non_subscriber = create(:user)
create(:subscription, project: project, user: subscriber, subscribable: target, subscribed: true)
create(:subscription, project: project, user: non_subscriber, subscribable: target, subscribed: false)
expect(subject.recipients.map(&:user)).to include(subscriber)
end
end
context 'custom notifications' do
shared_examples 'custom notification recipients' do
let_it_be(:custom_notification_user) { create(:user) }
let_it_be(:another_group) { create(:group) }
let_it_be(:another_project) { create(:project, namespace: another_group) }
context 'with project custom notification setting' do
before do
create(:notification_setting, source: project, user: custom_notification_user, level: :custom)
end
it 'adds the user to the recipients' do
expect(subject.recipients.map(&:user)).to include(custom_notification_user)
end
end
context 'with the project custom notification setting in another project' do
before do
create(:notification_setting, source: another_project, user: custom_notification_user, level: :custom)
end
it 'does not add the user to the recipients' do
expect(subject.recipients.map(&:user)).not_to include(custom_notification_user)
end
end
context 'with group custom notification setting' do
before do
create(:notification_setting, source: group, user: custom_notification_user, level: :custom)
end
it 'adds the user to the recipients' do
expect(subject.recipients.map(&:user)).to include(custom_notification_user)
end
end
context 'with the group custom notification setting in another group' do
before do
create(:notification_setting, source: another_group, user: custom_notification_user, level: :custom)
end
it 'does not add the user to the recipients' do
expect(subject.recipients.map(&:user)).not_to include(custom_notification_user)
end
end
context 'with project global custom notification setting' do
before do
create(:notification_setting, source: project, user: custom_notification_user, level: :global)
end
context 'with global custom notification setting' do
before do
create(:notification_setting, source: nil, user: custom_notification_user, level: :custom)
end
it 'adds the user to the recipients' do
expect(subject.recipients.map(&:user)).to include(custom_notification_user)
end
end
context 'without global custom notification setting' do
it 'does not add the user to the recipients' do
expect(subject.recipients.map(&:user)).not_to include(custom_notification_user)
end
end
end
context 'with group global custom notification setting' do
before do
create(:notification_setting, source: group, user: custom_notification_user, level: :global)
end
context 'with global custom notification setting' do
before do
create(:notification_setting, source: nil, user: custom_notification_user, level: :custom)
end
it 'adds the user to the recipients' do
expect(subject.recipients.map(&:user)).to include(custom_notification_user)
end
end
context 'without global custom notification setting' do
it 'does not add the user to the recipients' do
expect(subject.recipients.map(&:user)).not_to include(custom_notification_user)
end
end
end
context 'with group custom notification setting in deeply nested parent group' do
let(:grand_parent_group) { create(:group, :public) }
let(:parent_group) { create(:group, :public, parent: grand_parent_group) }
let(:group) { create(:group, :public, parent: parent_group) }
let(:project) { create(:project, :public, group: group).tap { |p| p.add_developer(project_watcher) } }
let(:target) { create(:issue, project: project) }
before do
create(:notification_setting, source: grand_parent_group, user: custom_notification_user, level: :custom)
end
it 'adds the user to the recipients' do
expect(subject.recipients.map(&:user)).to include(custom_notification_user)
end
end
context 'without a project or group' do
let(:target) { create(:snippet) }
before do
create(:notification_setting, source: nil, user: custom_notification_user, level: :custom)
end
it 'does not add the user to the recipients' do
expect(subject.recipients.map(&:user)).not_to include(custom_notification_user)
end
end
end
it_behaves_like 'custom notification recipients'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module JiraConnectInstallations
class ProxyLifecycleEventService
SUPPOERTED_EVENTS = %i[installed uninstalled].freeze
def self.execute(installation, event, instance_url)
new(installation, event, instance_url).execute
end
def initialize(installation, event, instance_url)
# To ensure the event is sent to the right instance, this makes
# a copy of the installation and assigns the instance_url
#
# The installation might be modified already with a new instance_url.
# This can be the case for an uninstalled event.
# The installation is updated first, and the uninstalled event has to be sent to
# the old instance_url.
@installation = installation.dup
@installation.instance_url = instance_url
@event = event.to_sym
raise(ArgumentError, "Unknown event '#{@event}'") unless SUPPOERTED_EVENTS.include?(@event)
end
def execute
result = send_hook
return ServiceResponse.new(status: :success) if result.code == 200
log_unsuccessful_response(result.code, result.body)
ServiceResponse.error(message: { type: :response_error, code: result.code })
rescue *Gitlab::HTTP::HTTP_ERRORS => error
ServiceResponse.error(message: { type: :network_error, message: error.message })
end
private
attr_reader :installation, :event
def send_hook
Gitlab::HTTP.post(hook_uri, body: body)
end
def hook_uri
case event
when :installed
installation.audience_installed_event_url
when :uninstalled
installation.audience_uninstalled_event_url
end
end
def body
return base_body unless event == :installed
base_body.merge(installed_body)
end
def base_body
{
clientKey: installation.client_key,
jwt: jwt_token,
eventType: event
}
end
def installed_body
{
sharedSecret: installation.shared_secret,
baseUrl: installation.base_url
}
end
def jwt_token
@jwt_token ||= JiraConnect::CreateAsymmetricJwtService.new(@installation, event: event).execute
end
def log_unsuccessful_response(status_code, body)
Gitlab::IntegrationsLogger.info(
integration: 'JiraConnect',
message: 'Proxy lifecycle event received error response',
jira_event_type: event,
jira_status_code: status_code,
jira_body: body
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe JiraConnectInstallations::ProxyLifecycleEventService, feature_category: :integrations do
describe '.execute' do
let(:installation) { create(:jira_connect_installation) }
it 'creates an instance and calls execute' do
expect_next_instance_of(described_class, installation, 'installed', 'https://test.gitlab.com') do |update_service|
expect(update_service).to receive(:execute)
end
described_class.execute(installation, 'installed', 'https://test.gitlab.com')
end
end
describe '.new' do
let_it_be(:installation) { create(:jira_connect_installation, instance_url: nil) }
let(:event) { :installed }
subject(:service) { described_class.new(installation, event, 'https://test.gitlab.com') }
it 'creates an internal duplicate of the installation and sets the instance_url' do
expect(service.instance_variable_get(:@installation).instance_url).to eq('https://test.gitlab.com')
end
context 'with unknown event' do
let(:event) { 'test' }
it 'raises an error' do
expect { service }.to raise_error(ArgumentError, 'Unknown event \'test\'')
end
end
end
describe '#execute' do
let_it_be(:installation) { create(:jira_connect_installation, instance_url: 'https://old_instance_url.example.com') }
let(:service) { described_class.new(installation, evnet_type, 'https://gitlab.example.com') }
let(:service_instance_installation) { service.instance_variable_get(:@installation) }
before do
allow_next_instance_of(JiraConnect::CreateAsymmetricJwtService) do |create_asymmetric_jwt_service|
allow(create_asymmetric_jwt_service).to receive(:execute).and_return('123456')
end
stub_request(:post, hook_url)
end
subject(:execute_service) { service.execute }
shared_examples 'sends the event hook' do
it 'returns a ServiceResponse' do
expect(execute_service).to be_kind_of(ServiceResponse)
expect(execute_service[:status]).to eq(:success)
end
it 'sends an installed event to the instance' do
execute_service
expect(WebMock).to have_requested(:post, hook_url).with(body: expected_request_body)
end
it 'creates the JWT token with the event and installation' do
expect_next_instance_of(
JiraConnect::CreateAsymmetricJwtService,
service_instance_installation,
event: evnet_type
) do |create_asymmetric_jwt_service|
expect(create_asymmetric_jwt_service).to receive(:execute).and_return('123456')
end
expect(execute_service[:status]).to eq(:success)
end
context 'and the instance responds with an error' do
before do
stub_request(:post, hook_url).to_return(
status: 422,
body: 'Error message',
headers: {}
)
end
it 'returns an error ServiceResponse', :aggregate_failures do
expect(execute_service).to be_kind_of(ServiceResponse)
expect(execute_service[:status]).to eq(:error)
expect(execute_service[:message]).to eq( { type: :response_error, code: 422 } )
end
it 'logs the error response' do
expect(Gitlab::IntegrationsLogger).to receive(:info).with(
integration: 'JiraConnect',
message: 'Proxy lifecycle event received error response',
jira_event_type: evnet_type,
jira_status_code: 422,
jira_body: 'Error message'
)
execute_service
end
end
context 'and the request raises an error' do
before do
allow(Gitlab::HTTP).to receive(:post).and_raise(Errno::ECONNREFUSED, 'error message')
end
it 'returns an error ServiceResponse', :aggregate_failures do
expect(execute_service).to be_kind_of(ServiceResponse)
expect(execute_service[:status]).to eq(:error)
expect(execute_service[:message]).to eq(
{
type: :network_error,
message: 'Connection refused - error message'
}
)
end
end
end
context 'when installed event' do
let(:evnet_type) { :installed }
let(:hook_url) { 'https://gitlab.example.com/-/jira_connect/events/installed' }
let(:expected_request_body) do
{
clientKey: installation.client_key,
sharedSecret: installation.shared_secret,
baseUrl: installation.base_url,
jwt: '123456',
eventType: 'installed'
}
end
it_behaves_like 'sends the event hook'
end
context 'when uninstalled event' do
let(:evnet_type) { :uninstalled }
let(:hook_url) { 'https://gitlab.example.com/-/jira_connect/events/uninstalled' }
let(:expected_request_body) do
{
clientKey: installation.client_key,
jwt: '123456',
eventType: 'uninstalled'
}
end
it_behaves_like 'sends the event hook'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module JiraConnectInstallations
class DestroyService
def self.execute(installation, jira_connect_base_path, jira_connect_uninstalled_event_path)
new(installation, jira_connect_base_path, jira_connect_uninstalled_event_path).execute
end
def initialize(installation, jira_connect_base_path, jira_connect_uninstalled_event_path)
@installation = installation
@jira_connect_base_path = jira_connect_base_path
@jira_connect_uninstalled_event_path = jira_connect_uninstalled_event_path
end
def execute
if @installation.instance_url.present?
JiraConnect::ForwardEventWorker.perform_async(@installation.id, @jira_connect_base_path, @jira_connect_uninstalled_event_path)
return true
end
@installation.destroy
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe JiraConnectInstallations::DestroyService, feature_category: :integrations do
describe '.execute' do
it 'creates an instance and calls execute' do
expect_next_instance_of(described_class, 'param1', 'param2', 'param3') do |destroy_service|
expect(destroy_service).to receive(:execute)
end
described_class.execute('param1', 'param2', 'param3')
end
end
describe '#execute' do
let!(:installation) { create(:jira_connect_installation) }
let(:jira_base_path) { '/-/jira_connect' }
let(:jira_event_path) { '/-/jira_connect/events/uninstalled' }
subject { described_class.new(installation, jira_base_path, jira_event_path).execute }
it { is_expected.to be_truthy }
it 'deletes the installation' do
expect { subject }.to change(JiraConnectInstallation, :count).by(-1)
end
context 'and the installation has an instance_url set' do
let!(:installation) { create(:jira_connect_installation, instance_url: 'http://example.com') }
it { is_expected.to be_truthy }
it 'schedules a ForwardEventWorker background job and keeps the installation' do
expect(JiraConnect::ForwardEventWorker).to receive(:perform_async).with(installation.id, jira_base_path, jira_event_path)
expect { subject }.not_to change(JiraConnectInstallation, :count)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module JiraConnectInstallations
class UpdateService
def self.execute(installation, update_params)
new(installation, update_params).execute
end
def initialize(installation, update_params)
@installation = installation
@update_params = update_params
end
def execute
return update_error unless @installation.update(@update_params)
if @installation.instance_url?
hook_result = ProxyLifecycleEventService.execute(@installation, :installed, @installation.instance_url)
if instance_url_changed? && hook_result.error?
@installation.update!(instance_url: @installation.instance_url_before_last_save)
return instance_installation_creation_error(hook_result.message)
end
end
send_uninstalled_hook if instance_url_changed? && @installation.instance_url.blank?
ServiceResponse.new(status: :success)
end
private
def instance_url_changed?
@installation.instance_url_before_last_save != @installation.instance_url
end
def send_uninstalled_hook
return if @installation.instance_url_before_last_save.blank?
JiraConnect::SendUninstalledHookWorker.perform_async(
@installation.id,
@installation.instance_url_before_last_save
)
end
def instance_installation_creation_error(error_message)
message = if error_message[:type] == :response_error
"Could not be installed on the instance. Error response code #{error_message[:code]}"
else
'Could not be installed on the instance. Network error'
end
ServiceResponse.error(message: message)
end
def update_error
ServiceResponse.error(message: @installation.errors)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe JiraConnectInstallations::UpdateService, feature_category: :integrations do
describe '.execute' do
it 'creates an instance and calls execute' do
expect_next_instance_of(described_class, 'param1', 'param2') do |update_service|
expect(update_service).to receive(:execute)
end
described_class.execute('param1', 'param2')
end
end
describe '#execute' do
let_it_be_with_reload(:installation) { create(:jira_connect_installation) }
let(:update_params) { { client_key: 'new_client_key' } }
subject(:execute_service) { described_class.new(installation, update_params).execute }
it 'returns a ServiceResponse' do
expect(execute_service).to be_kind_of(ServiceResponse)
expect(execute_service[:status]).to eq(:success)
end
it 'updates the installation' do
expect { execute_service }.to change { installation.client_key }.to('new_client_key')
end
it 'returns a successful result' do
expect(execute_service.success?).to eq(true)
end
context 'and model validation fails' do
let(:update_params) { { instance_url: 'invalid' } }
it 'returns an error result' do
expect(execute_service.error?).to eq(true)
expect(execute_service.message).to eq(installation.errors)
end
end
context 'and the installation has an instance_url' do
let_it_be_with_reload(:installation) { create(:jira_connect_installation, instance_url: 'https://other_gitlab.example.com') }
it 'sends an installed event to the instance', :aggregate_failures do
expect_next_instance_of(
JiraConnectInstallations::ProxyLifecycleEventService, installation, :installed, 'https://other_gitlab.example.com'
) do |proxy_lifecycle_events_service|
expect(proxy_lifecycle_events_service).to receive(:execute).and_return(ServiceResponse.new(status: :success))
end
expect(JiraConnect::SendUninstalledHookWorker).not_to receive(:perform_async)
expect { execute_service }.not_to change { installation.instance_url }
end
context 'and instance_url gets updated' do
let(:update_params) { { instance_url: 'https://gitlab.example.com' } }
before do
stub_request(:post, 'https://other_gitlab.example.com/-/jira_connect/events/uninstalled')
end
it 'sends an installed event to the instance and updates instance_url' do
expect(JiraConnectInstallations::ProxyLifecycleEventService)
.to receive(:execute).with(installation, :installed, 'https://gitlab.example.com')
.and_return(ServiceResponse.new(status: :success))
expect(JiraConnect::SendUninstalledHookWorker).not_to receive(:perform_async)
execute_service
expect(installation.instance_url).to eq(update_params[:instance_url])
end
context 'and the new instance_url is nil' do
let(:update_params) { { instance_url: nil } }
it 'starts an async worker to send an uninstalled event to the previous instance' do
expect(JiraConnect::SendUninstalledHookWorker).to receive(:perform_async).with(installation.id, 'https://other_gitlab.example.com')
execute_service
expect(installation.instance_url).to eq(nil)
end
it 'does not send an installed event' do
expect(JiraConnectInstallations::ProxyLifecycleEventService).not_to receive(:new)
execute_service
end
end
end
end
context 'and instance_url is updated' do
let(:update_params) { { instance_url: 'https://gitlab.example.com' } }
it 'sends an installed event to the instance and updates instance_url' do
expect_next_instance_of(
JiraConnectInstallations::ProxyLifecycleEventService, installation, :installed, 'https://gitlab.example.com'
) do |proxy_lifecycle_events_service|
expect(proxy_lifecycle_events_service).to receive(:execute).and_return(ServiceResponse.new(status: :success))
end
expect(JiraConnect::SendUninstalledHookWorker).not_to receive(:perform_async)
execute_service
expect(installation.instance_url).to eq(update_params[:instance_url])
end
context 'and the instance installation cannot be created' do
before do
allow_next_instance_of(
JiraConnectInstallations::ProxyLifecycleEventService,
installation,
:installed,
'https://gitlab.example.com'
) do |proxy_lifecycle_events_service|
allow(proxy_lifecycle_events_service).to receive(:execute).and_return(
ServiceResponse.error(
message: {
type: :response_error,
code: '422'
}
)
)
end
end
it 'does not change instance_url' do
expect { execute_service }.not_to change { installation.instance_url }
end
it 'returns an error message' do
expect(execute_service[:status]).to eq(:error)
expect(execute_service[:message]).to eq("Could not be installed on the instance. Error response code 422")
end
context 'and the installation had a previous instance_url' do
let(:installation) { build(:jira_connect_installation, instance_url: 'https://other_gitlab.example.com') }
it 'does not send the uninstalled hook to the previous instance_url' do
expect(JiraConnect::SendUninstalledHookWorker).not_to receive(:perform_async)
execute_service
end
end
context 'when failure because of a network error' do
before do
allow_next_instance_of(
JiraConnectInstallations::ProxyLifecycleEventService,
installation,
:installed,
'https://gitlab.example.com'
) do |proxy_lifecycle_events_service|
allow(proxy_lifecycle_events_service).to receive(:execute).and_return(
ServiceResponse.error(
message: {
type: :network_error,
message: 'Connection refused - error message'
}
)
)
end
end
it 'returns an error message' do
expect(execute_service[:status]).to eq(:error)
expect(execute_service[:message]).to eq("Could not be installed on the instance. Network error")
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module JiraConnectSubscriptions
class CreateService < ::JiraConnectSubscriptions::BaseService
include Gitlab::Utils::StrongMemoize
MERGE_REQUEST_SYNC_BATCH_SIZE = 20
MERGE_REQUEST_SYNC_BATCH_DELAY = 1.minute.freeze
def execute
if !params[:jira_user]
return error(s_('JiraConnect|Could not fetch user information from Jira. ' \
'Check the permissions in Jira and try again.'), 403)
elsif !can_administer_jira?
return error(s_('JiraConnect|The Jira user is not a site or organization administrator. ' \
'Check the permissions in Jira and try again.'), 403)
end
unless namespace && can?(current_user, :create_jira_connect_subscription, namespace)
return error(s_('JiraConnect|Cannot find namespace. Make sure you have sufficient permissions.'), 401)
end
create_subscription
end
private
def can_administer_jira?
params[:jira_user]&.jira_admin?
end
def create_subscription
subscription = JiraConnectSubscription.new(installation: jira_connect_installation, namespace: namespace)
if subscription.save
schedule_sync_project_jobs
success
else
error(subscription.errors.full_messages.join(', '), 422)
end
end
def namespace
strong_memoize(:namespace) do
Namespace.find_by_full_path(params[:namespace_path])
end
end
def schedule_sync_project_jobs
namespace.all_projects.each_batch(of: MERGE_REQUEST_SYNC_BATCH_SIZE) do |projects, index|
JiraConnect::SyncProjectWorker.bulk_perform_in_with_contexts(
index * MERGE_REQUEST_SYNC_BATCH_DELAY,
projects,
arguments_proc: -> (project) { [project.id, Atlassian::JiraConnect::Client.generate_update_sequence_id] },
context_proc: -> (project) { { project: project } }
)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe JiraConnectSubscriptions::CreateService, feature_category: :integrations do
let_it_be(:installation) { create(:jira_connect_installation) }
let_it_be(:current_user) { create(:user) }
let_it_be(:group) { create(:group) }
let(:path) { group.full_path }
let(:params) { { namespace_path: path, jira_user: jira_user } }
let(:jira_user) { double(:JiraUser, jira_admin?: true) }
subject { described_class.new(installation, current_user, params).execute }
before do
group.add_maintainer(current_user)
end
shared_examples 'a failed execution' do |**status_attributes|
it 'does not create a subscription' do
expect { subject }.not_to change { installation.subscriptions.count }
end
it 'returns an error status' do
expect(subject[:status]).to eq(:error)
expect(subject).to include(status_attributes)
end
end
context 'remote user does not have access' do
let(:jira_user) { double(jira_admin?: false) }
it_behaves_like 'a failed execution',
http_status: 403,
message: 'The Jira user is not a site or organization administrator. Check the permissions in Jira and try again.'
end
context 'remote user cannot be retrieved' do
let(:jira_user) { nil }
it_behaves_like 'a failed execution',
http_status: 403,
message: 'Could not fetch user information from Jira. Check the permissions in Jira and try again.'
end
context 'when user does have access' do
it 'creates a subscription' do
expect { subject }.to change { installation.subscriptions.count }.from(0).to(1)
end
it 'returns success' do
expect(subject[:status]).to eq(:success)
end
context 'namespace has projects' do
let_it_be(:project_1) { create(:project, group: group) }
let_it_be(:project_2) { create(:project, group: group) }
before do
stub_const("#{described_class}::MERGE_REQUEST_SYNC_BATCH_SIZE", 1)
end
it 'starts workers to sync projects in batches with delay' do
allow(Atlassian::JiraConnect::Client).to receive(:generate_update_sequence_id).and_return(123)
expect(JiraConnect::SyncProjectWorker).to receive(:bulk_perform_in).with(1.minute, [[project_1.id, 123]])
expect(JiraConnect::SyncProjectWorker).to receive(:bulk_perform_in).with(2.minutes, [[project_2.id, 123]])
subject
end
end
end
context 'when path is invalid' do
let(:path) { 'some_invalid_namespace_path' }
it_behaves_like 'a failed execution',
http_status: 401,
message: 'Cannot find namespace. Make sure you have sufficient permissions.'
end
context 'when user does not have access' do
let_it_be(:other_group) { create(:group) }
let(:path) { other_group.full_path }
it_behaves_like 'a failed execution',
http_status: 401,
message: 'Cannot find namespace. Make sure you have sufficient permissions.'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Discussions
class ResolveService < Discussions::BaseService
include Gitlab::Utils::StrongMemoize
def initialize(project, user = nil, params = {})
@discussions = Array.wrap(params.fetch(:one_or_more_discussions))
@follow_up_issue = params[:follow_up_issue]
@resolved_count = 0
raise ArgumentError, 'Discussions must be all for the same noteable' \
unless noteable_is_same?
super
end
def execute
discussions.each { |discussion| resolve_discussion(discussion) }
after_resolve_cleanup
end
private
attr_accessor :discussions, :follow_up_issue
def noteable_is_same?
return true unless discussions.size > 1
# Perform this check without fetching extra records
discussions.all? do |discussion|
discussion.noteable_type == first_discussion.noteable_type &&
discussion.noteable_id == first_discussion.noteable_id
end
end
def resolve_discussion(discussion)
return unless discussion.can_resolve?(current_user)
discussion.resolve!(current_user)
@resolved_count += 1
if merge_request
Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter
.track_resolve_thread_action(user: current_user)
MergeRequests::ResolvedDiscussionNotificationService.new(project: project, current_user: current_user).execute(merge_request)
end
resolve_user_todos_for(discussion)
SystemNoteService.discussion_continued_in_issue(discussion, project, current_user, follow_up_issue) if follow_up_issue
end
def resolve_user_todos_for(discussion)
return unless discussion.for_design?
TodoService.new.resolve_todos_for_target(discussion, current_user)
end
def first_discussion
@first_discussion ||= discussions.first
end
def merge_request
strong_memoize(:merge_request) do
first_discussion.noteable if first_discussion.for_merge_request?
end
end
def after_resolve_cleanup
return unless merge_request
return unless @resolved_count > 0
send_graphql_triggers
process_auto_merge
end
def send_graphql_triggers
GraphqlTriggers.merge_request_merge_status_updated(merge_request)
end
def process_auto_merge
return unless discussions_ready_to_merge?
AutoMergeProcessWorker.perform_async(merge_request.id)
end
def discussions_ready_to_merge?
merge_request.auto_merge_enabled? && merge_request.mergeable_discussions_state?
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Discussions::ResolveService, feature_category: :code_review_workflow do
describe '#execute' do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user, developer_projects: [project]) }
let_it_be(:merge_request) { create(:merge_request, :merge_when_pipeline_succeeds, source_project: project) }
let(:discussion) { create(:diff_note_on_merge_request, noteable: merge_request, project: project).to_discussion }
let(:service) { described_class.new(project, user, one_or_more_discussions: discussion) }
it "doesn't resolve discussions the user can't resolve" do
expect(discussion).to receive(:can_resolve?).with(user).and_return(false)
service.execute
expect(discussion).not_to be_resolved
end
it 'resolves the discussion' do
service.execute
expect(discussion).to be_resolved
end
it 'tracks thread resolve usage data' do
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.to receive(:track_resolve_thread_action).with(user: user)
service.execute
end
it 'executes the notification service' do
expect_next_instance_of(MergeRequests::ResolvedDiscussionNotificationService) do |instance|
expect(instance).to receive(:execute).with(discussion.noteable)
end
service.execute
end
it 'schedules an auto-merge' do
expect(AutoMergeProcessWorker).to receive(:perform_async).with(discussion.noteable.id)
service.execute
end
it 'sends GraphQL triggers' do
expect(GraphqlTriggers).to receive(:merge_request_merge_status_updated).with(discussion.noteable)
service.execute
end
context 'with a project that requires all discussion to be resolved' do
before do
project.update!(only_allow_merge_if_all_discussions_are_resolved: true)
end
after do
project.update!(only_allow_merge_if_all_discussions_are_resolved: false)
end
let_it_be(:other_discussion) { create(:diff_note_on_merge_request, noteable: merge_request, project: project).to_discussion }
it 'does not schedule an auto-merge' do
expect(AutoMergeProcessWorker).not_to receive(:perform_async)
service.execute
end
it 'schedules an auto-merge' do
expect(AutoMergeProcessWorker).to receive(:perform_async)
described_class.new(project, user, one_or_more_discussions: [discussion, other_discussion]).execute
end
end
it 'adds a system note to the discussion' do
issue = create(:issue, project: project)
expect(SystemNoteService).to receive(:discussion_continued_in_issue).with(discussion, project, user, issue)
service = described_class.new(project, user, one_or_more_discussions: discussion, follow_up_issue: issue)
service.execute
end
it 'can resolve multiple discussions at once' do
other_discussion = create(:diff_note_on_merge_request, noteable: merge_request, project: project).to_discussion
service = described_class.new(project, user, one_or_more_discussions: [discussion, other_discussion])
service.execute
expect([discussion, other_discussion]).to all(be_resolved)
end
it 'raises an argument error if discussions do not belong to the same noteable' do
other_merge_request = create(:merge_request)
other_discussion = create(
:diff_note_on_merge_request,
noteable: other_merge_request,
project: other_merge_request.source_project
).to_discussion
expect do
described_class.new(project, user, one_or_more_discussions: [discussion, other_discussion])
end.to raise_error(
ArgumentError,
'Discussions must be all for the same noteable'
)
end
context 'when discussion is not for a merge request' do
let_it_be(:design) { create(:design, :with_file, issue: create(:issue, project: project)) }
let(:discussion) { create(:diff_note_on_design, noteable: design, project: project).to_discussion }
it 'does not execute the notification service' do
expect(MergeRequests::ResolvedDiscussionNotificationService).not_to receive(:new)
service.execute
end
it 'does not track thread resolve usage data' do
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.not_to receive(:track_resolve_thread_action).with(user: user)
service.execute
end
it 'does not schedule an auto-merge' do
expect(AutoMergeProcessWorker).not_to receive(:perform_async)
service.execute
end
it 'does not send GraphQL triggers' do
expect(GraphqlTriggers).not_to receive(:merge_request_merge_status_updated).with(discussion.noteable)
service.execute
end
end
context 'when resolving a discussion' do
def resolve_discussion(discussion, user)
described_class.new(project, user, one_or_more_discussions: discussion).execute
end
context 'in a design' do
let_it_be(:design) { create(:design, :with_file, issue: create(:issue, project: project)) }
let_it_be(:user_1) { create(:user) }
let_it_be(:user_2) { create(:user) }
let_it_be(:discussion_1) { create(:diff_note_on_design, noteable: design, project: project, author: user_1).to_discussion }
let_it_be(:discussion_2) { create(:diff_note_on_design, noteable: design, project: project, author: user_2).to_discussion }
before do
project.add_developer(user_1)
project.add_developer(user_2)
end
context 'when user resolving discussion has open todos' do
let!(:user_1_todo_for_discussion_1) { create(:todo, :pending, user: user_1, target: design, note: discussion_1.notes.first, project: project) }
let!(:user_1_todo_2_for_discussion_1) { create(:todo, :pending, user: user_1, target: design, note: discussion_1.notes.first, project: project) }
let!(:user_1_todo_for_discussion_2) { create(:todo, :pending, user: user_1, target: design, note: discussion_2.notes.first, project: project) }
let!(:user_2_todo_for_discussion_1) { create(:todo, :pending, user: user_2, target: design, note: discussion_1.notes.first, project: project) }
it 'marks user todos for given discussion as done' do
resolve_discussion(discussion_1, user_1)
expect(user_1_todo_for_discussion_1.reload).to be_done
expect(user_1_todo_2_for_discussion_1.reload).to be_done
expect(user_1_todo_for_discussion_2.reload).to be_pending
expect(user_2_todo_for_discussion_1.reload).to be_pending
end
end
end
context 'in a merge request' do
let!(:user_todo_for_discussion) { create(:todo, :pending, user: user, target: merge_request, note: discussion.notes.first, project: project) }
it 'does not mark user todo as done' do
resolve_discussion(discussion, user)
expect(user_todo_for_discussion).to be_pending
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Discussions
class UnresolveService < Discussions::BaseService
include Gitlab::Utils::StrongMemoize
def initialize(discussion, user)
@discussion = discussion
@user = user
super
end
def execute
@all_discussions_resolved_before = merge_request ? @discussion.noteable.discussions_resolved? : false
@discussion.unresolve!
send_graphql_triggers
Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter
.track_unresolve_thread_action(user: @user)
end
private
def merge_request
@discussion.noteable if @discussion.for_merge_request?
end
strong_memoize_attr :merge_request
def send_graphql_triggers
return unless merge_request && @all_discussions_resolved_before
GraphqlTriggers.merge_request_merge_status_updated(merge_request)
end
end
end
``` | # frozen_string_literal: true
require "spec_helper"
RSpec.describe Discussions::UnresolveService, feature_category: :code_review_workflow do
describe "#execute" do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user, developer_projects: [project]) }
let_it_be(:merge_request) { create(:merge_request, :merge_when_pipeline_succeeds, source_project: project) }
let(:discussion) { create(:diff_note_on_merge_request, noteable: merge_request, project: project).to_discussion }
let(:service) { described_class.new(discussion, user) }
before do
project.add_developer(user)
discussion.resolve!(user)
end
it "unresolves the discussion" do
service.execute
expect(discussion).not_to be_resolved
end
it "counts the unresolve event" do
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.to receive(:track_unresolve_thread_action).with(user: user)
service.execute
end
it "sends GraphQL triggers" do
expect(GraphqlTriggers).to receive(:merge_request_merge_status_updated).with(discussion.noteable)
service.execute
end
context "when there are existing unresolved discussions" do
before do
create(:diff_note_on_merge_request, noteable: merge_request, project: project).to_discussion
end
it "does not send a GraphQL triggers" do
expect(GraphqlTriggers).not_to receive(:merge_request_merge_status_updated)
service.execute
end
end
context "when the noteable is not a merge request" do
it "does not send a GraphQL triggers" do
expect(discussion).to receive(:for_merge_request?).and_return(false)
expect(GraphqlTriggers).not_to receive(:merge_request_merge_status_updated)
service.execute
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Discussions
class UpdateDiffPositionService < BaseService
def execute(discussion)
old_position = discussion.position
result = tracer.trace(old_position)
return unless result
position = result[:position]
outdated = result[:outdated]
discussion.notes.each do |note|
if outdated
note.change_position = position
if project.resolve_outdated_diff_discussions?
note.resolve_without_save(current_user, resolved_by_push: true)
end
else
note.position = position
note.change_position = nil
end
end
Note.transaction do
discussion.notes.each do |note|
note.save(touch: false)
end
if outdated && current_user
SystemNoteService.diff_discussion_outdated(discussion, project, current_user, position)
end
end
end
private
def tracer
@tracer ||= Gitlab::Diff::PositionTracer.new(
project: project,
old_diff_refs: params[:old_diff_refs],
new_diff_refs: params[:new_diff_refs],
paths: params[:paths]
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Discussions::UpdateDiffPositionService, feature_category: :code_review_workflow do
let(:project) { create(:project, :repository) }
let(:current_user) { project.first_owner }
let(:create_commit) { project.commit("913c66a37b4a45b9769037c55c2d238bd0942d2e") }
let(:modify_commit) { project.commit("874797c3a73b60d2187ed6e2fcabd289ff75171e") }
let(:edit_commit) { project.commit("570e7b2abdd848b95f2f578043fc23bd6f6fd24d") }
let(:path) { "files/ruby/popen.rb" }
let(:old_diff_refs) do
Gitlab::Diff::DiffRefs.new(
base_sha: create_commit.parent_id,
head_sha: modify_commit.sha
)
end
let(:new_diff_refs) do
Gitlab::Diff::DiffRefs.new(
base_sha: create_commit.parent_id,
head_sha: edit_commit.sha
)
end
subject do
described_class.new(
project,
current_user,
old_diff_refs: old_diff_refs,
new_diff_refs: new_diff_refs,
paths: [path]
)
end
# old diff:
# 1 + require 'fileutils'
# 2 + require 'open3'
# 3 +
# 4 + module Popen
# 5 + extend self
# 6 +
# 7 + def popen(cmd, path=nil)
# 8 + unless cmd.is_a?(Array)
# 9 + raise "System commands must be given as an array of strings"
# 10 + end
# 11 +
# 12 + path ||= Dir.pwd
# 13 + vars = { "PWD" => path }
# 14 + options = { chdir: path }
# 15 +
# 16 + unless File.directory?(path)
# 17 + FileUtils.mkdir_p(path)
# 18 + end
# 19 +
# 20 + @cmd_output = ""
# 21 + @cmd_status = 0
# 22 + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
# 23 + @cmd_output << stdout.read
# 24 + @cmd_output << stderr.read
# 25 + @cmd_status = wait_thr.value.exitstatus
# 26 + end
# 27 +
# 28 + return @cmd_output, @cmd_status
# 29 + end
# 30 + end
#
# new diff:
# 1 + require 'fileutils'
# 2 + require 'open3'
# 3 +
# 4 + module Popen
# 5 + extend self
# 6 +
# 7 + def popen(cmd, path=nil)
# 8 + unless cmd.is_a?(Array)
# 9 + raise RuntimeError, "System commands must be given as an array of strings"
# 10 + end
# 11 +
# 12 + path ||= Dir.pwd
# 13 +
# 14 + vars = {
# 15 + "PWD" => path
# 16 + }
# 17 +
# 18 + options = {
# 19 + chdir: path
# 20 + }
# 21 +
# 22 + unless File.directory?(path)
# 23 + FileUtils.mkdir_p(path)
# 24 + end
# 25 +
# 26 + @cmd_output = ""
# 27 + @cmd_status = 0
# 28 +
# 29 + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
# 30 + @cmd_output << stdout.read
# 31 + @cmd_output << stderr.read
# 32 + @cmd_status = wait_thr.value.exitstatus
# 33 + end
# 34 +
# 35 + return @cmd_output, @cmd_status
# 36 + end
# 37 + end
#
# old->new diff:
# .. .. @@ -6,12 +6,18 @@ module Popen
# 6 6
# 7 7 def popen(cmd, path=nil)
# 8 8 unless cmd.is_a?(Array)
# 9 - raise "System commands must be given as an array of strings"
# 9 + raise RuntimeError, "System commands must be given as an array of strings"
# 10 10 end
# 11 11
# 12 12 path ||= Dir.pwd
# 13 - vars = { "PWD" => path }
# 14 - options = { chdir: path }
# 13 +
# 14 + vars = {
# 15 + "PWD" => path
# 16 + }
# 17 +
# 18 + options = {
# 19 + chdir: path
# 20 + }
# 15 21
# 16 22 unless File.directory?(path)
# 17 23 FileUtils.mkdir_p(path)
# 18 24 end
# 19 25
# 20 26 @cmd_output = ""
# 21 27 @cmd_status = 0
# 28 +
# 22 29 Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
# 23 30 @cmd_output << stdout.read
# 24 31 @cmd_output << stderr.read
# .. ..
describe "#execute" do
let(:discussion) { create(:diff_note_on_merge_request, project: project, position: old_position).to_discussion }
let(:old_position) do
Gitlab::Diff::Position.new(
old_path: path,
new_path: path,
old_line: nil,
new_line: line,
diff_refs: old_diff_refs
)
end
shared_examples 'outdated diff note' do
it "doesn't update the position" do
subject.execute(discussion)
expect(discussion.original_position).to eq(old_position)
expect(discussion.position).to eq(old_position)
end
it 'sets the change position' do
subject.execute(discussion)
change_position = discussion.change_position
expect(change_position.start_sha).to eq(old_diff_refs.head_sha)
expect(change_position.head_sha).to eq(new_diff_refs.head_sha)
expect(change_position.formatter.old_line).to eq(9)
expect(change_position.formatter.new_line).to be_nil
end
it 'creates a system discussion' do
expect(SystemNoteService).to receive(:diff_discussion_outdated).with(
discussion, project, current_user, instance_of(Gitlab::Diff::Position))
subject.execute(discussion)
end
end
context "when the diff line is the same" do
let(:line) { 16 }
it "updates the position" do
subject.execute(discussion)
expect(discussion.original_position).to eq(old_position)
expect(discussion.position).not_to eq(old_position)
expect(discussion.position.formatter.new_line).to eq(22)
end
context 'when the resolve_outdated_diff_discussions setting is set' do
before do
project.update!(resolve_outdated_diff_discussions: true)
end
it 'does not resolve the discussion' do
subject.execute(discussion)
expect(discussion).not_to be_resolved
expect(discussion).not_to be_resolved_by_push
end
end
end
context "when the diff line has changed" do
let(:line) { 9 }
include_examples 'outdated diff note'
context 'when the resolve_outdated_diff_discussions setting is set' do
before do
project.update!(resolve_outdated_diff_discussions: true)
end
it 'sets resolves the discussion and sets resolved_by_push' do
subject.execute(discussion)
expect(discussion).to be_resolved
expect(discussion).to be_resolved_by_push
end
include_examples 'outdated diff note'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Discussions
class CaptureDiffNotePositionsService
def initialize(merge_request)
@merge_request = merge_request
end
def execute
return unless merge_request.has_complete_diff_refs?
discussions, paths = build_discussions
service = Discussions::CaptureDiffNotePositionService.new(merge_request, paths)
discussions.each do |discussion|
service.execute(discussion)
end
end
private
attr_reader :merge_request
def build_discussions
active_diff_discussions = merge_request.notes.new_diff_notes.discussions.select do |discussion|
discussion.active?(merge_request.diff_refs)
end
paths = active_diff_discussions.flat_map { |n| n.diff_file&.paths }
[active_diff_discussions, paths]
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Discussions::CaptureDiffNotePositionsService, feature_category: :code_review_workflow do
context 'when merge request has a discussion' do
let(:source_branch) { 'compare-with-merge-head-source' }
let(:target_branch) { 'compare-with-merge-head-target' }
let(:merge_request) { create(:merge_request, source_branch: source_branch, target_branch: target_branch) }
let(:project) { merge_request.project }
let(:offset) { 30 }
let(:first_new_line) { 508 }
let(:second_new_line) { 521 }
let(:third_removed_line) { 1240 }
let(:service) { described_class.new(merge_request) }
def build_position(diff_refs, new_line: nil, old_line: nil)
path = 'files/markdown/ruby-style-guide.md'
Gitlab::Diff::Position.new(
old_path: path, new_path: path, new_line: new_line, old_line: old_line, diff_refs: diff_refs)
end
def note_for(new_line: nil, old_line: nil)
position = build_position(merge_request.diff_refs, new_line: new_line, old_line: old_line)
create(:diff_note_on_merge_request, project: project, position: position, noteable: merge_request)
end
def verify_diff_note_position!(note, new_line: nil, old_line: nil)
id, removed_line, added_line = note.line_code.split('_')
expect(note.diff_note_positions.size).to eq(1)
diff_position = note.diff_note_positions.last
diff_refs = Gitlab::Diff::DiffRefs.new(
base_sha: merge_request.target_branch_sha,
start_sha: merge_request.target_branch_sha,
head_sha: merge_request.merge_ref_head.sha)
expect(diff_position.line_code).to eq("#{id}_#{removed_line.to_i - offset}_#{added_line}")
expect(diff_position.position).to eq(build_position(diff_refs, new_line: new_line, old_line: old_line))
end
let!(:first_discussion_note) { note_for(new_line: first_new_line) }
let!(:second_discussion_note) { note_for(new_line: second_new_line) }
let!(:third_discussion_note) { note_for(old_line: third_removed_line) }
let!(:second_discussion_another_note) do
create(:diff_note_on_merge_request,
project: project,
position: second_discussion_note.position,
discussion_id: second_discussion_note.discussion_id,
noteable: merge_request)
end
context 'and position of the discussion changed on target branch head' do
it 'diff positions are created for the first notes of the discussions' do
MergeRequests::MergeToRefService.new(project: project, current_user: merge_request.author).execute(merge_request)
service.execute
verify_diff_note_position!(first_discussion_note, new_line: first_new_line)
verify_diff_note_position!(second_discussion_note, new_line: second_new_line)
verify_diff_note_position!(third_discussion_note, old_line: third_removed_line - offset)
expect(second_discussion_another_note.diff_note_positions).to be_empty
end
end
end
end
|
Subsets and Splits