INSTRUCTION
stringlengths 202
35.5k
| RESPONSE
stringlengths 75
161k
|
---|---|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class DismissProjectCalloutService < DismissCalloutService
private
def callout
current_user.find_or_initialize_project_callout(params[:feature_name], params[:project_id])
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::DismissProjectCalloutService, feature_category: :user_management do
describe '#execute' do
let_it_be(:user) { create(:user) }
let_it_be(:project) { create(:project) }
let(:params) { { feature_name: feature_name, project_id: project.id } }
let(:feature_name) { Users::ProjectCallout.feature_names.each_key.first }
subject(:execute) do
described_class.new(
container: nil, current_user: user, params: params
).execute
end
it_behaves_like 'dismissing user callout', Users::ProjectCallout
it 'sets the project_id' do
expect(execute.project_id).to eq(project.id)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class UnblockService < BaseService
def initialize(current_user)
@current_user = current_user
end
def execute(user)
if user.activate
after_unblock_hook(user)
ServiceResponse.success(payload: { user: user })
else
ServiceResponse.error(message: user.errors.full_messages)
end
end
private
def after_unblock_hook(user)
custom_attribute = {
user_id: user.id,
key: UserCustomAttribute::UNBLOCKED_BY,
value: "#{current_user.username}/#{current_user.id}+#{Time.current}"
}
UserCustomAttribute.upsert_custom_attributes([custom_attribute])
end
end
end
Users::UnblockService.prepend_mod_with('Users::UnblockService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::UnblockService, feature_category: :user_management do
let_it_be(:current_user) { create(:admin) }
subject(:service) { described_class.new(current_user) }
describe '#execute' do
subject(:operation) { service.execute(user) }
context 'when successful' do
let(:user) { create(:user, :blocked) }
it { expect(operation.success?).to eq(true) }
it "change the user's state" do
expect { operation }.to change { user.active? }.to(true)
end
it 'saves a custom attribute', :aggregate_failures, :freeze_time, feature_category: :insider_threat do
operation
custom_attribute = user.custom_attributes.last
expect(custom_attribute.key).to eq(UserCustomAttribute::UNBLOCKED_BY)
expect(custom_attribute.value).to eq("#{current_user.username}/#{current_user.id}+#{Time.current}")
end
end
context 'when failed' do
let(:user) { create(:user) }
it 'returns error result', :aggregate_failures do
expect(operation.error?).to eq(true)
expect(operation[:message]).to include(/State cannot transition/)
end
it "does not change the user's state" do
expect { operation }.not_to change { user.state }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class UntrustService < BaseService
def initialize(current_user)
@current_user = current_user
end
def execute(user)
user.trusted_with_spam_attribute.delete
success
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::UntrustService, feature_category: :user_management do
let_it_be(:current_user) { create(:admin) }
subject(:service) { described_class.new(current_user) }
describe '#execute' do
let(:user) { create(:user) }
subject(:operation) { service.execute(user) }
before do
UserCustomAttribute.upsert_custom_attributes(
[{
user_id: user.id,
key: UserCustomAttribute::TRUSTED_BY,
value: 'not important'
}]
)
end
it 'updates the custom attributes', :aggregate_failures do
expect(user.trusted_with_spam_attribute).to be_present
operation
user.reload
expect(user.trusted_with_spam_attribute).to be nil
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class AssignedIssuesCountService < ::BaseCountService
def initialize(current_user:, max_limit: User::MAX_LIMIT_FOR_ASSIGNEED_ISSUES_COUNT)
@current_user = current_user
@max_limit = max_limit
end
def cache_key
['users', @current_user.id, 'max_assigned_open_issues_count']
end
def cache_options
{ force: false, expires_in: User::COUNT_CACHE_VALIDITY_PERIOD }
end
# rubocop: disable CodeReuse/ActiveRecord
def uncached_count
# When a user has many assigned issues, counting them all can be very slow.
# As a workaround, we will short-circuit the counting query once the count reaches some threshold.
#
# Concretely, given a threshold, say 100 (= max_limit),
# iterate through the first 100 issues, sorted by ID desc, assigned to the user using `issue_assignees` table.
# For each issue iterated, use IssuesFinder to check if the issue should be counted.
initializer = IssueAssignee
.select(:issue_id).joins(", LATERAL (#{finder_constraint.to_sql}) as issues")
.where(user_id: @current_user.id)
.order(issue_id: :desc)
.limit(1)
recursive_finder = initializer.where("issue_assignees.issue_id < assigned_issues.issue_id")
cte = <<~SQL
WITH RECURSIVE assigned_issues AS (
(
#{initializer.to_sql}
)
UNION ALL
(
SELECT next_assigned_issue.issue_id
FROM assigned_issues,
LATERAL (
#{recursive_finder.to_sql}
) next_assigned_issue
)
) SELECT COUNT(*) FROM (SELECT * FROM assigned_issues LIMIT #{@max_limit}) issues
SQL
ApplicationRecord.connection.execute(cte).first["count"]
end
# rubocop: enable CodeReuse/ActiveRecord
private
# rubocop: disable CodeReuse/ActiveRecord
def finder_constraint
IssuesFinder.new(@current_user, assignee_id: @current_user.id, state: 'opened', non_archived: true)
.execute
.where("issues.id=issue_assignees.issue_id").limit(1)
end
# rubocop: enable CodeReuse/ActiveRecord
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::AssignedIssuesCountService, :use_clean_rails_memory_store_caching,
feature_category: :team_planning do
let_it_be(:user) { create(:user) }
let_it_be(:max_limit) { 10 }
let(:current_user) { user }
subject { described_class.new(current_user: current_user, max_limit: max_limit) }
it_behaves_like 'a counter caching service'
context 'when user has assigned open issues from archived and closed projects' do
before do
project = create(:project, :public)
archived_project = create(:project, :public, :archived)
create(:issue, project: project, author: user, assignees: [user])
create(:issue, :closed, project: project, author: user, assignees: [user])
create(:issue, project: archived_project, author: user, assignees: [user])
end
it 'count all assigned open issues excluding those from closed or archived projects' do
expect(subject.count).to eq(1)
end
end
context 'when the number of assigned open issues exceeds max_limit' do
let_it_be(:banned_user) { create(:user, :banned) }
let_it_be(:project) { create(:project).tap { |p| p.add_developer(user) } }
context 'when user is admin', :enable_admin_mode do
let_it_be(:admin) { create(:admin) }
let_it_be(:issues) { create_list(:issue, max_limit + 1, project: project, assignees: [admin]) }
let_it_be(:banned_issue) { create(:issue, project: project, assignees: [admin], author: banned_user) }
let(:current_user) { admin }
it 'returns the max_limit count' do
expect(subject.count).to eq max_limit
end
end
context 'when user is non-admin' do
let_it_be(:issues) { create_list(:issue, max_limit + 1, project: project, assignees: [user]) }
let_it_be(:closed_issue) { create(:issue, :closed, project: project, assignees: [user]) }
let_it_be(:banned_issue) { create(:issue, project: project, assignees: [user], author: banned_user) }
it 'returns the max_limit count' do
expect(subject.count).to eq max_limit
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class RegistrationsBuildService < BuildService
extend ::Gitlab::Utils::Override
private
def signup_params
super + [:skip_confirmation]
end
override :assign_skip_confirmation_from_settings?
def assign_skip_confirmation_from_settings?
user_params[:skip_confirmation].blank?
end
end
end
Users::RegistrationsBuildService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::RegistrationsBuildService, feature_category: :system_access do
describe '#execute' do
let(:base_params) { build_stubbed(:user).slice(:first_name, :last_name, :username, :email, :password) }
let(:skip_param) { {} }
let(:params) { base_params.merge(skip_param) }
subject(:service) { described_class.new(nil, params) }
before do
stub_application_setting(signup_enabled?: true)
end
context 'when automatic user confirmation is not enabled' do
before do
stub_application_setting_enum('email_confirmation_setting', 'hard')
end
context 'when skip_confirmation is true' do
let(:skip_param) { { skip_confirmation: true } }
it 'confirms the user' do
expect(service.execute).to be_confirmed
end
end
context 'when skip_confirmation is not set' do
it 'does not confirm the user' do
expect(service.execute).not_to be_confirmed
end
end
context 'when skip_confirmation is false' do
let(:skip_param) { { skip_confirmation: false } }
it 'does not confirm the user' do
expect(service.execute).not_to be_confirmed
end
end
end
context 'when automatic user confirmation is enabled' do
before do
stub_application_setting_enum('email_confirmation_setting', 'off')
end
context 'when skip_confirmation is true' do
let(:skip_param) { { skip_confirmation: true } }
it 'confirms the user' do
expect(service.execute).to be_confirmed
end
end
context 'when skip_confirmation is not set the application setting takes precedence' do
it 'confirms the user' do
expect(service.execute).to be_confirmed
end
end
context 'when skip_confirmation is false the application setting takes precedence' do
let(:skip_param) { { skip_confirmation: false } }
it 'confirms the user' do
expect(service.execute).to be_confirmed
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class DismissGroupCalloutService < DismissCalloutService
private
def callout
current_user.find_or_initialize_group_callout(params[:feature_name], params[:group_id])
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::DismissGroupCalloutService, feature_category: :user_management do
describe '#execute' do
let_it_be(:user) { create(:user) }
let_it_be(:group) { create(:group) }
let(:params) { { feature_name: feature_name, group_id: group.id } }
let(:feature_name) { Users::GroupCallout.feature_names.each_key.first }
subject(:execute) do
described_class.new(
container: nil, current_user: user, params: params
).execute
end
it_behaves_like 'dismissing user callout', Users::GroupCallout
it 'sets the group_id' do
expect(execute.group_id).to eq(group.id)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class RepairLdapBlockedService
attr_accessor :user
def initialize(user)
@user = user
end
def execute
user.block if ldap_hard_blocked?
end
private
def ldap_hard_blocked?
user.ldap_blocked? && !user.ldap_user?
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::RepairLdapBlockedService, feature_category: :system_access do
let(:user) { create(:omniauth_user, provider: 'ldapmain', state: 'ldap_blocked') }
let(:identity) { user.ldap_identity }
subject(:service) { described_class.new(user) }
describe '#execute' do
it 'changes to normal block after destroying last ldap identity' do
identity.destroy!
service.execute
expect(user.reload).not_to be_ldap_blocked
end
it 'changes to normal block after changing last ldap identity to another provider' do
identity.update_attribute(:provider, 'twitter')
service.execute
expect(user.reload).not_to be_ldap_blocked
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class UpdateCanonicalEmailService
extend ActiveSupport::Concern
INCLUDED_DOMAINS_PATTERN = [/gmail.com/].freeze
def initialize(user:)
raise ArgumentError, "Please provide a user" unless user.is_a?(User)
@user = user
end
def execute
return unless user.email
return unless user.email.match? Devise.email_regexp
canonical_email = canonicalize_email
unless canonical_email
# the canonical email doesn't exist, probably because the domain doesn't match
# destroy any UserCanonicalEmail record associated with this user
user.user_canonical_email&.delete
# nothing else to do here
return
end
if user.user_canonical_email
# update to the new value
user.user_canonical_email.canonical_email = canonical_email
else
user.build_user_canonical_email(canonical_email: canonical_email)
end
end
private
attr_reader :user
def canonicalize_email
email = user.email
portions = email.split('@')
username = portions.shift
rest = portions.join
regex = Regexp.union(INCLUDED_DOMAINS_PATTERN)
return unless regex.match?(rest)
no_dots = username.tr('.', '')
before_plus = no_dots.split('+')[0]
"#{before_plus}@#{rest}"
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::UpdateCanonicalEmailService, feature_category: :user_profile do
let(:other_email) { "[email protected]" }
before do
stub_const("Users::UpdateCanonicalEmailService::INCLUDED_DOMAINS_PATTERN", [/includeddomain/])
end
describe '#initialize' do
context 'unsuccessful' do
it 'raises an error if there is no user' do
expect { described_class.new(user: nil) }.to raise_error(ArgumentError, /Please provide a user/)
end
it 'raises an error if the object is not a User' do
expect { described_class.new(user: 123) }.to raise_error(ArgumentError, /Please provide a user/)
end
end
context 'when a user is provided' do
it 'does not error' do
user = build(:user)
expect { described_class.new(user: user) }.not_to raise_error
end
end
end
describe "#canonicalize_email" do
let(:user) { build(:user) }
let(:subject) { described_class.new(user: user) }
context 'when the email domain is included' do
context 'strips out any . or anything after + in the agent for included domains' do
using RSpec::Parameterized::TableSyntax
let(:expected_result) { '[email protected]' }
where(:raw_email, :expected_result) do
'[email protected]' | '[email protected]'
'[email protected]' | '[email protected]'
'[email protected]' | '[email protected]'
'[email protected]' | '[email protected]'
end
with_them do
before do
user.email = raw_email
end
specify do
subject.execute
expect(user.user_canonical_email).not_to be_nil
expect(user.user_canonical_email.canonical_email).to eq expected_result
end
end
end
context 'when the user has an existing canonical email' do
it 'updates the user canonical email record' do
user.user_canonical_email = build(:user_canonical_email, canonical_email: other_email)
user.email = "[email protected]"
subject.execute
expect(user.user_canonical_email.canonical_email).to eq "[email protected]"
end
end
end
context 'when the email domain is not included' do
it 'returns nil' do
user.email = "[email protected]"
subject.execute
expect(user.user_canonical_email).to be_nil
end
it 'destroys any existing UserCanonicalEmail record' do
user.email = "[email protected]"
user.user_canonical_email = build(:user_canonical_email, canonical_email: other_email)
expect(user.user_canonical_email).to receive(:delete)
subject.execute
end
end
context 'when the user email is not processable' do
[nil, 'nonsense'].each do |invalid_address|
context "with #{invalid_address}" do
before do
user.email = invalid_address
end
specify do
subject.execute
expect(user.user_canonical_email).to be_nil
end
it 'preserves any existing record' do
user.email = nil
user.user_canonical_email = build(:user_canonical_email, canonical_email: other_email)
subject.execute
expect(user.user_canonical_email.canonical_email).to eq other_email
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class BanService < BannedUserBaseService
extend ::Gitlab::Utils::Override
private
def update_user(user)
user.ban
end
def valid_state?(user)
user.active?
end
def action
:ban
end
override :track_event
def track_event(user)
experiment(:phone_verification_for_low_risk_users, user: user).track(:banned)
end
end
end
Users::BanService.prepend_mod_with('Users::BanService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::BanService, feature_category: :user_management do
let(:user) { create(:user) }
let_it_be(:current_user) { create(:admin) }
shared_examples 'does not modify the BannedUser record or user state' do
it 'does not modify the BannedUser record or user state' do
expect { ban_user }.not_to change { Users::BannedUser.count }
expect { ban_user }.not_to change { user.state }
end
end
context 'ban', :aggregate_failures do
subject(:ban_user) { described_class.new(current_user).execute(user) }
context 'when successful', :enable_admin_mode do
it 'returns success status' do
response = ban_user
expect(response[:status]).to eq(:success)
end
it 'bans the user' do
expect { ban_user }.to change { user.state }.from('active').to('banned')
end
it 'creates a BannedUser' do
expect { ban_user }.to change { Users::BannedUser.count }.by(1)
expect(Users::BannedUser.last.user_id).to eq(user.id)
end
it 'logs ban in application logs' do
expect(Gitlab::AppLogger).to receive(:info).with(message: "User ban", user: user.username.to_s, email: user.email.to_s, ban_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s)
ban_user
end
it 'tracks the event', :experiment do
expect(experiment(:phone_verification_for_low_risk_users))
.to track(:banned).on_next_instance.with_context(user: user)
ban_user
end
end
context 'when failed' do
context 'when user is blocked', :enable_admin_mode do
before do
user.block!
end
it 'returns state error message' do
response = ban_user
expect(response[:status]).to eq(:error)
expect(response[:message]).to match('You cannot ban blocked users.')
end
it_behaves_like 'does not modify the BannedUser record or user state'
end
context 'when user is not an admin' do
it 'returns permissions error message' do
response = ban_user
expect(response[:status]).to eq(:error)
expect(response[:message]).to match(/You are not allowed to ban a user/)
end
it_behaves_like 'does not modify the BannedUser record or user state'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class BuildService < BaseService
ALLOWED_USER_TYPES = %i[project_bot security_policy_bot].freeze
delegate :user_default_internal_regex_enabled?,
:user_default_internal_regex_instance,
to: :'Gitlab::CurrentSettings.current_application_settings'
def initialize(current_user, params = {})
@current_user = current_user
@params = params.dup
@identity_params = params.slice(*identity_attributes)
end
def execute
build_user
build_identity
update_canonical_email
user
end
private
attr_reader :identity_params, :user_params, :user
def identity_attributes
[:extern_uid, :provider]
end
def build_user
if admin?
admin_build_user
else
standard_build_user
end
user.assign_personal_namespace
end
def admin?
return false unless current_user
current_user.admin?
end
def admin_build_user
build_user_params_for_admin
init_user
password_reset
end
def standard_build_user
# current_user non admin or nil
validate_access!
build_user_params_for_non_admin
init_user
end
def build_user_params_for_admin
@user_params = params.slice(*admin_create_params)
@user_params.merge!(force_random_password: true, password_expires_at: nil) if params[:reset_password]
end
def init_user
assign_common_user_params
@user = User.new(user_params)
end
def assign_common_user_params
@user_params[:created_by_id] = current_user&.id
@user_params[:external] = user_external? if set_external_param?
@user_params.delete(:user_type) unless allowed_user_type?
end
def set_external_param?
user_default_internal_regex_enabled? && !user_params.key?(:external)
end
def user_external?
user_default_internal_regex_instance.match(params[:email]).nil?
end
def allowed_user_type?
ALLOWED_USER_TYPES.include?(user_params[:user_type]&.to_sym)
end
def password_reset
@reset_token = user.generate_reset_token if params[:reset_password]
if user_params[:force_random_password]
random_password = User.random_password
@user.password = user.password_confirmation = random_password
end
end
def validate_access!
return if can_create_user?
raise Gitlab::Access::AccessDeniedError
end
def can_create_user?
current_user.nil? && Gitlab::CurrentSettings.allow_signup?
end
def build_user_params_for_non_admin
@user_params = params.slice(*signup_params)
# if skip_confirmation is set to `true`, devise will set confirmed_at
# see: https://github.com/heartcombo/devise/blob/8593801130f2df94a50863b5db535c272b00efe1/lib/devise/models/confirmable.rb#L156
@user_params[:skip_confirmation] = skip_user_confirmation_email_from_setting if assign_skip_confirmation_from_settings?
@user_params[:name] = fallback_name if use_fallback_name?
end
def assign_skip_confirmation_from_settings?
user_params[:skip_confirmation].nil?
end
def skip_user_confirmation_email_from_setting
Gitlab::CurrentSettings.email_confirmation_setting_off?
end
def use_fallback_name?
user_params[:name].blank? && fallback_name.present?
end
def fallback_name
"#{user_params[:first_name]} #{user_params[:last_name]}"
end
def build_identity
return if identity_params.empty?
user.identities.build(identity_params)
end
def update_canonical_email
Users::UpdateCanonicalEmailService.new(user: user).execute
end
# Allowed params for creating a user (admins only)
def admin_create_params
[
:access_level,
:admin,
:avatar,
:bio,
:can_create_group,
:color_scheme_id,
:email,
:external,
:force_random_password,
:hide_no_password,
:hide_no_ssh_key,
:linkedin,
:name,
:password,
:password_automatically_set,
:password_expires_at,
:projects_limit,
:remember_me,
:skip_confirmation,
:skype,
:theme_id,
:twitter,
:discord,
:username,
:website_url,
:private_profile,
:organization,
:location,
:public_email,
:user_type,
:note,
:view_diffs_file_by_file
]
end
# Allowed params for user signup
def signup_params
[
:email,
:name,
:password,
:password_automatically_set,
:preferred_language,
:username,
:user_type,
:first_name,
:last_name
]
end
end
end
Users::BuildService.prepend_mod_with('Users::BuildService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::BuildService, feature_category: :user_management do
using RSpec::Parameterized::TableSyntax
describe '#execute' do
let_it_be(:current_user) { nil }
let(:params) { build_stubbed(:user).slice(:first_name, :last_name, :username, :email, :password) }
let(:service) { described_class.new(current_user, params) }
context 'with nil current_user' do
subject(:user) { service.execute }
it_behaves_like 'common user build items'
it_behaves_like 'current user not admin build items'
context 'with "user_default_external" application setting' do
using RSpec::Parameterized::TableSyntax
where(:user_default_external, :external, :email, :user_default_internal_regex, :result) do
true | nil | '[email protected]' | nil | true
true | true | '[email protected]' | nil | true
true | false | '[email protected]' | nil | true # admin difference
true | nil | '[email protected]' | '' | true
true | true | '[email protected]' | '' | true
true | false | '[email protected]' | '' | true # admin difference
true | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
true | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false # admin difference
true | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
true | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true
true | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true
true | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true # admin difference
false | nil | '[email protected]' | nil | false
false | true | '[email protected]' | nil | false # admin difference
false | false | '[email protected]' | nil | false
false | nil | '[email protected]' | '' | false
false | true | '[email protected]' | '' | false # admin difference
false | false | '[email protected]' | '' | false
false | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
false | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false # admin difference
false | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
false | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
false | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false # admin difference
false | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
end
with_them do
before do
stub_application_setting(user_default_external: user_default_external)
stub_application_setting(user_default_internal_regex: user_default_internal_regex)
params.merge!({ external: external, email: email }.compact)
end
it 'sets the value of Gitlab::CurrentSettings.user_default_external' do
expect(user.external).to eq(result)
end
end
end
end
context 'with non admin current_user' do
let_it_be(:current_user) { create(:user) }
it 'raises AccessDeniedError exception' do
expect { described_class.new(current_user, params).execute }.to raise_error Gitlab::Access::AccessDeniedError
end
end
context 'with an admin current_user' do
let_it_be(:current_user) { create(:admin) }
let(:params) { build_stubbed(:user).slice(:name, :username, :email, :password) }
let(:service) { described_class.new(current_user, ActionController::Parameters.new(params).permit!) }
subject(:user) { service.execute }
it_behaves_like 'common user build items'
context 'with allowed params' do
let(:params) do
{
access_level: 1,
admin: 1,
avatar: anything,
bio: 1,
can_create_group: 1,
color_scheme_id: 1,
email: 1,
external: 1,
force_random_password: 1,
hide_no_password: 1,
hide_no_ssh_key: 1,
linkedin: 1,
name: 1,
password: 1,
password_automatically_set: 1,
password_expires_at: 1,
projects_limit: 1,
remember_me: 1,
skip_confirmation: 1,
skype: 1,
theme_id: 1,
twitter: 1,
username: 1,
website_url: 1,
private_profile: 1,
organization: 1,
location: 1,
public_email: 1,
user_type: 'project_bot',
note: 1,
view_diffs_file_by_file: 1
}
end
it 'sets all allowed attributes' do
expect(User).to receive(:new).with(hash_including(params)).and_call_original
service.execute
end
end
context 'with "user_default_external" application setting' do
where(:user_default_external, :external, :email, :user_default_internal_regex, :result) do
true | nil | '[email protected]' | nil | true
true | true | '[email protected]' | nil | true
true | false | '[email protected]' | nil | false # admin difference
true | nil | '[email protected]' | '' | true
true | true | '[email protected]' | '' | true
true | false | '[email protected]' | '' | false # admin difference
true | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
true | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true # admin difference
true | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
true | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true
true | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true
true | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false # admin difference
false | nil | '[email protected]' | nil | false
false | true | '[email protected]' | nil | true # admin difference
false | false | '[email protected]' | nil | false
false | nil | '[email protected]' | '' | false
false | true | '[email protected]' | '' | true # admin difference
false | false | '[email protected]' | '' | false
false | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
false | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true # admin difference
false | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
false | nil | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
false | true | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | true # admin difference
false | false | '[email protected]' | '^(?:(?!\.ext@).)*$\r?' | false
end
with_them do
before do
stub_application_setting(user_default_external: user_default_external)
stub_application_setting(user_default_internal_regex: user_default_internal_regex)
params.merge!({ external: external, email: email }.compact)
end
it 'sets the value of Gitlab::CurrentSettings.user_default_external' do
expect(user.external).to eq(result)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class DismissCalloutService < BaseContainerService
def execute
callout.tap do |record|
record.update(dismissed_at: Time.current) if record.valid?
end
end
private
def callout
current_user.find_or_initialize_callout(params[:feature_name])
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::DismissCalloutService, feature_category: :user_management do
describe '#execute' do
let_it_be(:user) { create(:user) }
let(:params) { { feature_name: feature_name } }
let(:feature_name) { Users::Callout.feature_names.each_key.first }
subject(:execute) do
described_class.new(
container: nil, current_user: user, params: params
).execute
end
it_behaves_like 'dismissing user callout', Users::Callout
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class AutoBanService < BaseService
def initialize(user:, reason:)
@user = user
@reason = reason
end
def execute
if user.ban
record_custom_attribute
success
else
messages = user.errors.full_messages
error(messages.uniq.join('. '))
end
end
private
attr_reader :user, :reason
def record_custom_attribute
custom_attribute = {
user_id: user.id,
key: UserCustomAttribute::AUTO_BANNED_BY,
value: reason
}
UserCustomAttribute.upsert_custom_attributes([custom_attribute])
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::AutoBanService, feature_category: :instance_resiliency do
let_it_be_with_reload(:user) { create(:user) }
let(:reason) { :auto_ban_reason }
context 'when auto banning a user', :aggregate_failures do
subject(:auto_ban_user) { described_class.new(user: user, reason: reason).execute }
context 'when successful' do
it 'returns success status' do
response = auto_ban_user
expect(response[:status]).to eq(:success)
end
it 'bans the user' do
expect { auto_ban_user }.to change { user.state }.from('active').to('banned')
end
it 'creates a BannedUser' do
expect { auto_ban_user }.to change { Users::BannedUser.count }.by(1)
expect(Users::BannedUser.last.user_id).to eq(user.id)
end
describe 'recording a custom attribute' do
it 'records a custom attribute' do
expect { auto_ban_user }.to change { UserCustomAttribute.count }.by(1)
expect(user.custom_attributes.by_key(UserCustomAttribute::AUTO_BANNED_BY).first.value).to eq(reason.to_s)
end
end
end
context 'when failed' do
context 'when user is blocked' do
before do
user.block!
end
it 'returns state error message' do
response = auto_ban_user
expect(response[:status]).to eq(:error)
expect(response[:message]).to match('State cannot transition via \"ban\"')
end
it 'does not modify the BannedUser record or user state' do
expect { auto_ban_user }.not_to change { Users::BannedUser.count }
expect { auto_ban_user }.not_to change { user.state }
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class UnbanService < BannedUserBaseService
private
def update_user(user)
user.unban
end
def valid_state?(user)
user.banned?
end
def action
:unban
end
end
end
Users::UnbanService.prepend_mod_with('Users::UnbanService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::UnbanService, feature_category: :user_management do
let(:user) { create(:user) }
let_it_be(:current_user) { create(:admin) }
shared_examples 'does not modify the BannedUser record or user state' do
it 'does not modify the BannedUser record or user state' do
expect { unban_user }.not_to change { Users::BannedUser.count }
expect { unban_user }.not_to change { user.state }
end
end
context 'unban', :aggregate_failures do
subject(:unban_user) { described_class.new(current_user).execute(user) }
context 'when successful', :enable_admin_mode do
before do
user.ban!
end
it 'returns success status' do
response = unban_user
expect(response[:status]).to eq(:success)
end
it 'unbans the user' do
expect { unban_user }.to change { user.state }.from('banned').to('active')
end
it 'removes the BannedUser' do
expect { unban_user }.to change { Users::BannedUser.count }.by(-1)
expect(user.reload.banned_user).to be_nil
end
it 'logs unban in application logs' do
expect(Gitlab::AppLogger).to receive(:info).with(message: "User unban", user: user.username.to_s, email: user.email.to_s, unban_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s)
unban_user
end
end
context 'when failed' do
context 'when user is already active', :enable_admin_mode do
it 'returns state error message' do
response = unban_user
expect(response[:status]).to eq(:error)
expect(response[:message]).to match('You cannot unban active users.')
end
it_behaves_like 'does not modify the BannedUser record or user state'
end
context 'when user is not an admin' do
before do
user.ban!
end
it 'returns permissions error message' do
response = unban_user
expect(response[:status]).to eq(:error)
expect(response[:message]).to match(/You are not allowed to unban a user/)
end
it_behaves_like 'does not modify the BannedUser record or user state'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class DeactivateService < BaseService
def initialize(current_user, skip_authorization: false)
@current_user = current_user
@skip_authorization = skip_authorization
end
def execute(user)
unless allowed?
return ::ServiceResponse.error(message: _('You are not authorized to perform this action'),
reason: :forbidden)
end
if user.blocked?
return ::ServiceResponse.error(message: _('Error occurred. A blocked user cannot be deactivated'),
reason: :forbidden)
end
if user.internal?
return ::ServiceResponse.error(message: _('Internal users cannot be deactivated'),
reason: :forbidden)
end
return ::ServiceResponse.success(message: _('User has already been deactivated')) if user.deactivated?
unless user.can_be_deactivated?
message = _(
'The user you are trying to deactivate has been active in the past %{minimum_inactive_days} days ' \
'and cannot be deactivated')
deactivation_error_message = format(message,
minimum_inactive_days: Gitlab::CurrentSettings.deactivate_dormant_users_period)
return ::ServiceResponse.error(message: deactivation_error_message, reason: :forbidden)
end
unless user.deactivate
return ::ServiceResponse.error(message: user.errors.full_messages.to_sentence,
reason: :bad_request)
end
log_event(user)
::ServiceResponse.success
end
private
attr_reader :current_user
def allowed?
return true if @skip_authorization
can?(current_user, :admin_all_resources)
end
def log_event(user)
Gitlab::AppLogger.info(message: 'User deactivated', user: user.username.to_s, email: user.email.to_s,
deactivated_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s)
end
end
end
Users::DeactivateService.prepend_mod_with('Users::DeactivateService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::DeactivateService, feature_category: :user_management do
let_it_be(:current_user) { build(:admin) }
let_it_be(:user) { build(:user) }
subject(:service) { described_class.new(current_user) }
describe '#execute' do
subject(:operation) { service.execute(user) }
context 'when successful', :enable_admin_mode do
let(:user) { create(:user) }
it 'returns success status' do
expect(operation[:status]).to eq(:success)
end
it "changes the user's state" do
expect { operation }.to change { user.state }.to('deactivated')
end
it 'creates a log entry' do
expect(Gitlab::AppLogger).to receive(:info).with(message: "User deactivated", user: user.username,
email: user.email, deactivated_by: current_user.username, ip_address: current_user.current_sign_in_ip.to_s)
operation
end
end
context 'when the user is already deactivated', :enable_admin_mode do
let(:user) { create(:user, :deactivated) }
it 'returns error result' do
aggregate_failures 'error result' do
expect(operation[:status]).to eq(:success)
expect(operation[:message]).to eq('User has already been deactivated')
end
end
it "does not change the user's state" do
expect { operation }.not_to change { user.state }
end
end
context 'when internal user', :enable_admin_mode do
let(:user) { create(:user, :bot) }
it 'returns an error message' do
expect(operation[:status]).to eq(:error)
expect(operation[:message]).to eq('Internal users cannot be deactivated')
expect(operation.reason).to eq :forbidden
end
end
context 'when user is blocked', :enable_admin_mode do
let(:user) { create(:user, :blocked) }
it 'returns an error message' do
expect(operation[:status]).to eq(:error)
expect(operation[:message]).to eq('Error occurred. A blocked user cannot be deactivated')
expect(operation.reason).to eq :forbidden
end
end
context 'when user is not an admin' do
it 'returns permissions error message' do
expect(operation[:status]).to eq(:error)
expect(operation[:message]).to eq("You are not authorized to perform this action")
expect(operation.reason).to eq :forbidden
end
end
context 'when skip_authorization is true' do
let(:non_admin_user) { create(:user) }
let(:user_to_deactivate) { create(:user) }
let(:skip_authorization_service) { described_class.new(non_admin_user, skip_authorization: true) }
it 'deactivates the user even if the current user is not an admin' do
expect(skip_authorization_service.execute(user_to_deactivate)[:status]).to eq(:success)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class ValidatePushOtpService < BaseService
include ::Gitlab::Auth::Otp::Fortinet
def initialize(current_user)
@current_user = current_user
@strategy = if forti_authenticator_enabled?(current_user)
::Gitlab::Auth::Otp::Strategies::FortiAuthenticator::PushOtp.new(current_user)
end
end
def execute
strategy.validate
rescue StandardError => ex
Gitlab::ErrorTracking.log_exception(ex)
error(ex.message)
end
private
attr_reader :strategy
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::ValidatePushOtpService, feature_category: :user_profile do
let_it_be(:user) { create(:user) }
subject(:validate) { described_class.new(user).execute }
context 'FortiAuthenticator' do
before do
stub_feature_flags(forti_authenticator: user)
allow(::Gitlab.config.forti_authenticator).to receive(:enabled).and_return(true)
end
it 'calls PushOtp strategy' do
expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::FortiAuthenticator::PushOtp) do |strategy|
expect(strategy).to receive(:validate).once
end
validate
end
end
context 'unexpected error' do
before do
stub_feature_flags(forti_authenticator: user)
allow(::Gitlab.config.forti_authenticator).to receive(:enabled).and_return(true)
end
it 'returns error' do
error_message = "boom!"
expect_next_instance_of(::Gitlab::Auth::Otp::Strategies::FortiAuthenticator::PushOtp) do |strategy|
expect(strategy).to receive(:validate).once.and_raise(StandardError, error_message)
end
expect(Gitlab::ErrorTracking).to receive(:log_exception)
result = validate
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq(error_message)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
# Service class for getting the number of SSH keys that belong to a user.
class KeysCountService < BaseCountService
attr_reader :user
# user - The User for which to get the number of SSH keys.
def initialize(user)
@user = user
end
def relation_for_count
user.keys.auth
end
def raw?
# Since we're storing simple integers we don't need all of the additional
# Marshal data Rails includes by default.
true
end
def cache_key
"users/key-count-service/#{user.id}"
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::KeysCountService, :use_clean_rails_memory_store_caching, feature_category: :system_access do
let(:user) { create(:user) }
subject { described_class.new(user) }
it_behaves_like 'a counter caching service'
describe '#count' do
before do
create(:personal_key, user: user)
end
it 'returns the number of SSH keys as an Integer' do
expect(subject.count).to eq(1)
end
it 'does not count signing keys' do
create(:key, usage_type: :signing, user: user)
expect(subject.count).to eq(1)
end
end
describe '#uncached_count' do
it 'returns the number of SSH keys' do
expect(subject.uncached_count).to be_zero
end
end
describe '#cache_key' do
it 'returns the cache key' do
expect(subject.cache_key).to eq("users/key-count-service/#{user.id}")
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class DestroyService
DestroyError = Class.new(StandardError)
attr_accessor :current_user
def initialize(current_user)
@current_user = current_user
@scheduled_records_gauge = Gitlab::Metrics.gauge(
:gitlab_ghost_user_migration_scheduled_records_total,
'The total number of scheduled ghost user migrations'
)
@lag_gauge = Gitlab::Metrics.gauge(
:gitlab_ghost_user_migration_lag_seconds,
'The waiting time in seconds of the oldest scheduled record for ghost user migration'
)
end
# Asynchronously destroys +user+
# Migrating the associated user records, and post-migration cleanup is
# handled by the Users::MigrateRecordsToGhostUserWorker cron worker.
#
# The operation will fail if the user is the sole owner of any groups. To
# force the groups to be destroyed, pass `delete_solo_owned_groups: true` in
# +options+.
#
# The user's contributions will be migrated to a global ghost user. To
# force the contributions to be destroyed, pass `hard_delete: true` in
# +options+.
#
# `hard_delete: true` implies `delete_solo_owned_groups: true`. To perform
# a hard deletion without destroying solo-owned groups, pass
# `delete_solo_owned_groups: false, hard_delete: true` in +options+.
#
def execute(user, options = {})
delete_solo_owned_groups = options.fetch(:delete_solo_owned_groups, options[:hard_delete])
unless Ability.allowed?(current_user, :destroy_user, user) || options[:skip_authorization]
raise Gitlab::Access::AccessDeniedError, "#{current_user} tried to destroy user #{user}!"
end
if !delete_solo_owned_groups && user.solo_owned_groups.present?
user.errors.add(:base, 'You must transfer ownership or delete groups before you can remove user')
return user
end
user.block
# Load the records. Groups are unavailable after membership is destroyed.
solo_owned_groups = user.solo_owned_groups.load
user.members.each_batch { |batch| batch.destroy_all } # rubocop:disable Style/SymbolProc, Cop/DestroyAll
solo_owned_groups.each do |group|
Groups::DestroyService.new(group, current_user).execute
end
user.personal_projects.each do |project|
success = ::Projects::DestroyService.new(project, current_user).execute
raise DestroyError, "Project #{project.id} can't be deleted" unless success
end
yield(user) if block_given?
hard_delete = options.fetch(:hard_delete, false)
Users::GhostUserMigration.create!(
user: user,
initiator_user: current_user,
hard_delete: hard_delete
)
update_metrics
end
private
attr_reader :scheduled_records_gauge, :lag_gauge
def update_metrics
update_scheduled_records_gauge
update_lag_gauge
end
def update_scheduled_records_gauge
# We do not want to issue unbounded COUNT() queries, hence we limit the
# query to count 1001 records and then approximate the result.
count = Users::GhostUserMigration.limit(1001).count
if count == 1001
# more than 1000 records, approximate count
min = Users::GhostUserMigration.minimum(:id) || 0
max = Users::GhostUserMigration.maximum(:id) || 0
scheduled_records_gauge.set({}, max - min)
else
# less than 1000 records, count is accurate
scheduled_records_gauge.set({}, count)
end
end
def update_lag_gauge
oldest_job = Users::GhostUserMigration.first
lag_gauge.set({}, Time.current - oldest_job.created_at)
end
end
end
Users::DestroyService.prepend_mod_with('Users::DestroyService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::DestroyService, feature_category: :user_management do
let!(:user) { create(:user) }
let!(:admin) { create(:admin) }
let!(:namespace) { user.namespace }
let!(:project) { create(:project, namespace: namespace) }
let(:service) { described_class.new(admin) }
let(:gitlab_shell) { Gitlab::Shell.new }
describe "Initiates user deletion and deletes all their personal projects", :enable_admin_mode do
context 'no options are given' do
it 'creates GhostUserMigration record to handle migration in a worker' do
expect { service.execute(user) }
.to(
change do
Users::GhostUserMigration.where(user: user, initiator_user: admin).exists?
end.from(false).to(true))
end
it 'will delete the personal project' do
expect_next_instance_of(Projects::DestroyService) do |destroy_service|
expect(destroy_service).to receive(:execute).once.and_return(true)
end
service.execute(user)
end
end
context 'personal projects in pending_delete' do
before do
project.pending_delete = true
project.save!
end
it 'destroys a personal project in pending_delete' do
expect_next_instance_of(Projects::DestroyService) do |destroy_service|
expect(destroy_service).to receive(:execute).once.and_return(true)
end
service.execute(user)
end
end
context "solo owned groups present" do
let(:solo_owned) { create(:group) }
let(:member) { create(:group_member) }
let(:user) { member.user }
before do
solo_owned.group_members = [member]
end
it 'returns the user with attached errors' do
expect(service.execute(user)).to be(user)
expect(user.errors.full_messages).to(
contain_exactly('You must transfer ownership or delete groups before you can remove user'))
end
it 'does not delete the user, nor the group' do
service.execute(user)
expect(User.find(user.id)).to eq user
expect(Group.find(solo_owned.id)).to eq solo_owned
end
end
context "deletions with solo owned groups" do
let(:solo_owned) { create(:group) }
let(:member) { create(:group_member) }
let(:user) { member.user }
before do
solo_owned.group_members = [member]
service.execute(user, delete_solo_owned_groups: true)
end
it 'deletes solo owned groups' do
expect { Group.find(solo_owned.id) }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context 'deletions with inherited group owners' do
let(:group) { create(:group, :nested) }
let(:user) { create(:user) }
let(:inherited_owner) { create(:user) }
before do
group.parent.add_owner(inherited_owner)
group.add_owner(user)
service.execute(user, delete_solo_owned_groups: true)
end
it 'does not delete the group' do
expect(Group.exists?(id: group)).to be_truthy
end
end
describe "user personal's repository removal" do
context 'storages' do
before do
perform_enqueued_jobs { service.execute(user) }
end
context 'legacy storage' do
let!(:project) { create(:project, :empty_repo, :legacy_storage, namespace: user.namespace) }
it 'removes repository' do
expect(
gitlab_shell.repository_exists?(project.repository_storage, "#{project.disk_path}.git")
).to be_falsey
end
end
context 'hashed storage' do
let!(:project) { create(:project, :empty_repo, namespace: user.namespace) }
it 'removes repository' do
expect(
gitlab_shell.repository_exists?(project.repository_storage, "#{project.disk_path}.git")
).to be_falsey
end
end
end
context 'repository removal status is taken into account' do
it 'raises exception' do
expect_next_instance_of(::Projects::DestroyService) do |destroy_service|
expect(destroy_service).to receive(:execute).and_return(false)
end
expect { service.execute(user) }
.to raise_error(Users::DestroyService::DestroyError, "Project #{project.id} can't be deleted")
end
end
end
describe "calls the before/after callbacks" do
it 'of project_members' do
expect_any_instance_of(ProjectMember).to receive(:run_callbacks).with(:find).once
expect_any_instance_of(ProjectMember).to receive(:run_callbacks).with(:initialize).once
expect_any_instance_of(ProjectMember).to receive(:run_callbacks).with(:destroy).once
service.execute(user)
end
it 'of group_members' do
group_member = create(:group_member)
group_member.group.group_members.create!(user: user, access_level: 40)
expect_any_instance_of(GroupMember).to receive(:run_callbacks).with(:find).once
expect_any_instance_of(GroupMember).to receive(:run_callbacks).with(:initialize).once
expect_any_instance_of(GroupMember).to receive(:run_callbacks).with(:destroy).once
service.execute(user)
end
end
describe 'prometheus metrics', :prometheus do
context 'scheduled records' do
context 'with a single record' do
it 'updates the scheduled records gauge' do
service.execute(user)
gauge = Gitlab::Metrics.registry.get(:gitlab_ghost_user_migration_scheduled_records_total)
expect(gauge.get).to eq(1)
end
end
context 'with approximate count due to large number of records' do
it 'updates the scheduled records gauge' do
allow(Users::GhostUserMigration)
.to(receive_message_chain(:limit, :count).and_return(1001))
allow(Users::GhostUserMigration).to(receive(:minimum)).and_return(42)
allow(Users::GhostUserMigration).to(receive(:maximum)).and_return(9042)
service.execute(user)
gauge = Gitlab::Metrics.registry.get(:gitlab_ghost_user_migration_scheduled_records_total)
expect(gauge.get).to eq(9000)
end
end
end
context 'lag' do
it 'update the lag gauge', :freeze_time do
create(:ghost_user_migration, created_at: 10.minutes.ago)
service.execute(user)
gauge = Gitlab::Metrics.registry.get(:gitlab_ghost_user_migration_lag_seconds)
expect(gauge.get).to eq(600)
end
end
end
end
describe "Deletion permission checks" do
it 'does not delete the user when user is not an admin' do
other_user = create(:user)
expect { described_class.new(other_user).execute(user) }.to raise_error(Gitlab::Access::AccessDeniedError)
expect(Users::GhostUserMigration).not_to be_exists
end
context 'when admin mode is enabled', :enable_admin_mode do
it 'allows admins to delete anyone' do
expect { described_class.new(admin).execute(user) }
.to(
change do
Users::GhostUserMigration.where(user: user, initiator_user: admin).exists?
end.from(false).to(true))
end
end
context 'when admin mode is disabled' do
it 'disallows admins to delete anyone' do
expect { described_class.new(admin).execute(user) }.to raise_error(Gitlab::Access::AccessDeniedError)
expect(Users::GhostUserMigration).not_to be_exists
end
end
it 'allows users to delete their own account' do
expect { described_class.new(user).execute(user) }
.to(
change do
Users::GhostUserMigration.where(user: user, initiator_user: user).exists?
end.from(false).to(true))
end
it 'allows user to be deleted if skip_authorization: true' do
other_user = create(:user)
expect do
described_class.new(user)
.execute(other_user, skip_authorization: true)
end.to(
change do
Users::GhostUserMigration.where(user: other_user, initiator_user: user).exists?
end.from(false).to(true))
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class UpdateService < BaseService
include NewUserNotifier
attr_reader :user, :identity_params
ATTRS_REQUIRING_PASSWORD_CHECK = %w[email].freeze
BATCH_SIZE = 100
def initialize(current_user, params = {})
@current_user = current_user
@validation_password = params.delete(:validation_password)
@user = params.delete(:user)
@status_params = params.delete(:status)
@identity_params = params.slice(*identity_attributes)
@params = params.dup
end
def execute(validate: true, check_password: false, &block)
yield(@user) if block
user_exists = @user.persisted?
@user.user_detail # prevent assignment
discard_read_only_attributes
assign_attributes
if check_password && require_password_check? && [email protected]_password?(@validation_password)
return error(s_("Profiles|Invalid password"))
end
assign_identity
build_canonical_email
reset_unconfirmed_email
if @user.save(validate: validate) && update_status
after_update(user_exists)
else
messages = @user.errors.full_messages + Array(@user.status&.errors&.full_messages)
error(messages.uniq.join('. '))
end
end
def execute!(*args, **kargs, &block)
result = execute(*args, **kargs, &block)
raise ActiveRecord::RecordInvalid, @user unless result[:status] == :success
true
end
private
def require_password_check?
return false unless @user.persisted?
return false if @user.password_automatically_set?
changes = @user.changed
ATTRS_REQUIRING_PASSWORD_CHECK.any? { |param| changes.include?(param) }
end
def build_canonical_email
return unless @user.email_changed?
Users::UpdateCanonicalEmailService.new(user: @user).execute
end
def reset_unconfirmed_email
return unless @user.persisted?
return unless @user.email_changed?
@user.update_column(:unconfirmed_email, nil)
end
def update_status
return true unless @status_params
Users::SetStatusService.new(current_user, @status_params.merge(user: @user)).execute
end
def notify_success(user_exists)
notify_new_user(@user, nil) unless user_exists
end
def discard_read_only_attributes
discard_synced_attributes
end
def discard_synced_attributes
if (metadata = @user.user_synced_attributes_metadata)
read_only = metadata.read_only_attributes
params.reject! { |key, _| read_only.include?(key.to_sym) }
end
end
def assign_attributes
@user.assign_attributes(params.except(*identity_attributes)) unless params.empty?
end
def assign_identity
return unless identity_params.present?
identity = user.identities.find_or_create_by(provider_params) # rubocop: disable CodeReuse/ActiveRecord
identity.update(identity_params)
end
def identity_attributes
[:provider, :extern_uid]
end
def provider_attributes
[:provider]
end
def provider_params
identity_params.slice(*provider_attributes)
end
def after_update(user_exists)
notify_success(user_exists)
remove_followers_and_followee!
success
end
def remove_followers_and_followee!
return false unless user.user_preference.enabled_following_previously_changed?(from: true, to: false)
# rubocop: disable CodeReuse/ActiveRecord
loop do
inner_query = Users::UserFollowUser
.where(follower_id: user.id).or(Users::UserFollowUser.where(followee_id: user.id))
.select(:follower_id, :followee_id)
.limit(BATCH_SIZE)
deleted_records = Users::UserFollowUser.where('(follower_id, followee_id) IN (?)', inner_query).delete_all
break if deleted_records == 0
end
# rubocop: enable CodeReuse/ActiveRecord
end
end
end
Users::UpdateService.prepend_mod_with('Users::UpdateService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::UpdateService, feature_category: :user_profile do
let(:password) { User.random_password }
let(:user) { create(:user, password: password, password_confirmation: password) }
describe '#execute' do
it 'updates time preferences' do
result = update_user(user, timezone: 'Europe/Warsaw', time_display_relative: true)
expect(result).to eq(status: :success)
expect(user.reload.timezone).to eq('Europe/Warsaw')
expect(user.time_display_relative).to eq(true)
end
it 'returns an error result when record cannot be updated' do
result = {}
expect do
result = update_user(user, { email: 'invalid', validation_password: password })
end.not_to change { user.reload.email }
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq('Email is invalid')
end
it 'includes namespace error messages' do
create(:group, path: 'taken')
result = {}
expect do
result = update_user(user, { username: 'taken' })
end.not_to change { user.reload.username }
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq('A user, alias, or group already exists with that username.')
end
it 'updates the status if status params were given' do
update_user(user, status: { message: "On a call" })
expect(user.status.message).to eq("On a call")
end
it 'does not delete the status if no status param was passed' do
create(:user_status, user: user, message: 'Busy!')
update_user(user, name: 'New name')
expect(user.status.message).to eq('Busy!')
end
it 'includes status error messages' do
result = update_user(user, status: { emoji: "Moo!" })
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq("Emoji is not a valid emoji name")
end
it 'updates user detail with provided attributes' do
result = update_user(user, job_title: 'Backend Engineer')
expect(result).to eq(status: :success)
expect(user.job_title).to eq('Backend Engineer')
end
context 'updating canonical email' do
context 'if email was changed' do
subject do
update_user(user, email: '[email protected]', validation_password: password)
end
it 'calls canonicalize_email' do
expect_next_instance_of(Users::UpdateCanonicalEmailService) do |service|
expect(service).to receive(:execute)
end
subject
end
context 'when race condition' do
# See https://gitlab.com/gitlab-org/gitlab/-/issues/382957
it 'updates email for stale user', :aggregate_failures do
unconfirmed_email = '[email protected]'
forgery_email = '[email protected]'
user.update!(email: unconfirmed_email)
stale_user = User.find(user.id)
service1 = described_class.new(stale_user, { email: unconfirmed_email }.merge(user: stale_user))
service2 = described_class.new(user, { email: forgery_email }.merge(user: user))
service2.execute
reloaded_user = User.find(user.id)
expect(reloaded_user.unconfirmed_email).to eq(forgery_email)
expect(stale_user.confirmation_token).not_to eq(user.confirmation_token)
expect(reloaded_user.confirmation_token).to eq(user.confirmation_token)
service1.execute
reloaded_user = User.find(user.id)
expect(reloaded_user.unconfirmed_email).to eq(unconfirmed_email)
expect(stale_user.confirmation_token).not_to eq(user.confirmation_token)
expect(reloaded_user.confirmation_token).to eq(stale_user.confirmation_token)
end
end
context 'when check_password is true' do
def update_user(user, opts)
described_class.new(user, opts.merge(user: user)).execute(check_password: true)
end
it 'returns error if no password confirmation was passed', :aggregate_failures do
result = {}
expect do
result = update_user(user, { email: '[email protected]' })
end.not_to change { user.reload.unconfirmed_email }
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq('Invalid password')
end
it 'returns error if wrong password confirmation was passed', :aggregate_failures do
result = {}
expect do
result = update_user(user, { email: '[email protected]', validation_password: 'wrongpassword' })
end.not_to change { user.reload.unconfirmed_email }
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq('Invalid password')
end
it 'does not require password if it was automatically set', :aggregate_failures do
user.update!(password_automatically_set: true)
result = {}
expect do
result = update_user(user, { email: '[email protected]' })
end.to change { user.reload.unconfirmed_email }
expect(result[:status]).to eq(:success)
end
it 'does not require a password if the attribute changed does not require it' do
result = {}
expect do
result = update_user(user, { job_title: 'supreme leader of the universe' })
end.to change { user.reload.job_title }
expect(result[:status]).to eq(:success)
end
end
end
context 'when check_password is left to false' do
it 'does not require a password check', :aggregate_failures do
result = {}
expect do
result = update_user(user, { email: '[email protected]' })
end.to change { user.reload.unconfirmed_email }
expect(result[:status]).to eq(:success)
end
end
context 'if email was NOT changed' do
it 'skips update canonicalize email service call' do
expect do
update_user(user, job_title: 'supreme leader of the universe')
end.not_to change { user.user_canonical_email }
end
it 'does not reset unconfirmed email' do
unconfirmed_email = '[email protected]'
user.update!(email: unconfirmed_email)
expect do
update_user(user, job_title: 'supreme leader of the universe')
end.not_to change { user.unconfirmed_email }
end
end
end
it 'does not try to reset unconfirmed email for a new user' do
expect do
update_user(build(:user), job_title: 'supreme leader of the universe')
end.not_to raise_error
end
describe 'updates the enabled_following' do
let(:user) { create(:user) }
before do
3.times do
user.follow(create(:user))
create(:user).follow(user)
end
user.reload
end
it 'removes followers and followees' do
expect do
update_user(user, enabled_following: false)
end.to change { user.followed_users.count }.from(3).to(0)
.and change { user.following_users.count }.from(3).to(0)
expect(user.enabled_following).to eq(false)
end
context 'when there is more followers/followees then batch limit' do
before do
stub_env('BATCH_SIZE', 1)
end
it 'removes followers and followees' do
expect do
update_user(user, enabled_following: false)
end.to change { user.followed_users.count }.from(3).to(0)
.and change { user.following_users.count }.from(3).to(0)
expect(user.enabled_following).to eq(false)
end
end
end
def update_user(user, opts)
described_class.new(user, opts.merge(user: user)).execute
end
end
describe '#execute!' do
it 'updates the name' do
service = described_class.new(user, user: user, name: 'New Name')
expect(service).not_to receive(:notify_new_user)
result = service.execute!
expect(result).to be true
expect(user.name).to eq('New Name')
end
it 'raises an error when record cannot be updated' do
expect do
update_user(user, email: 'invalid', validation_password: password)
end.to raise_error(ActiveRecord::RecordInvalid)
end
it 'fires system hooks when a new user is saved' do
system_hook_service = spy(:system_hook_service)
user = build(:user)
service = described_class.new(user, user: user, name: 'John Doe')
expect(service).to receive(:notify_new_user).and_call_original
expect(service).to receive(:system_hook_service).and_return(system_hook_service)
service.execute
expect(system_hook_service).to have_received(:execute_hooks_for).with(user, :create)
end
def update_user(user, opts)
described_class.new(user, opts.merge(user: user)).execute!
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class UpdateHighestMemberRoleService < BaseService
attr_reader :user
def initialize(user)
@user = user
end
def execute
return true if user_highest_role.persisted? && highest_access_level == user_highest_role.highest_access_level
user_highest_role.update!(highest_access_level: highest_access_level)
end
private
def user_highest_role
@user_highest_role ||= @user.user_highest_role || @user.build_user_highest_role
end
def highest_access_level
@highest_access_level ||= @user.current_highest_access_level
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::UpdateHighestMemberRoleService, feature_category: :user_management do
let(:user) { create(:user) }
let(:execute_service) { described_class.new(user).execute }
describe '#execute' do
context 'when user_highest_role already exists' do
let!(:user_highest_role) { create(:user_highest_role, :guest, user: user) }
context 'when the current highest access level equals the already stored highest access level' do
it 'does not update the highest access level' do
create(:group_member, :guest, user: user)
expect { execute_service }.not_to change { user_highest_role.reload.highest_access_level }
end
end
context 'when the current highest access level does not equal the already stored highest access level' do
it 'updates the highest access level' do
create(:group_member, :developer, user: user)
expect { execute_service }
.to change { user_highest_role.reload.highest_access_level }
.from(Gitlab::Access::GUEST)
.to(Gitlab::Access::DEVELOPER)
end
end
end
context 'when user_highest_role does not exist' do
it 'creates an user_highest_role object to store the highest access level' do
create(:group_member, :guest, user: user)
expect { execute_service }.to change { UserHighestRole.count }.from(0).to(1)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class ApproveService < BaseService
def initialize(current_user)
@current_user = current_user
end
def execute(user)
return error(_('You are not allowed to approve a user'), :forbidden) unless allowed?
return error(_('The user you are trying to approve is not pending approval'), :conflict) if user.active? || !approval_required?(user)
if user.activate
# Resends confirmation email if the user isn't confirmed yet.
# Please see Devise's implementation of `resend_confirmation_instructions` for detail.
user.resend_confirmation_instructions
user.accept_pending_invitations! if user.active_for_authentication?
DeviseMailer.user_admin_approval(user).deliver_later
if user.created_by_id
reset_token = user.generate_reset_token
NotificationService.new.new_user(user, reset_token)
end
log_event(user)
after_approve_hook(user)
success(message: 'Success', http_status: :created)
else
error(user.errors.full_messages.uniq.join('. '), :unprocessable_entity)
end
end
private
attr_reader :current_user
def after_approve_hook(user)
# overridden by EE module
end
def allowed?
can?(current_user, :approve_user)
end
def approval_required?(user)
user.blocked_pending_approval?
end
def log_event(user)
Gitlab::AppLogger.info(message: "User instance access request approved", user: user.username.to_s, email: user.email.to_s, approved_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s)
end
end
end
Users::ApproveService.prepend_mod_with('Users::ApproveService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::ApproveService, feature_category: :user_management do
let_it_be(:current_user) { create(:admin) }
let(:user) { create(:user, :blocked_pending_approval) }
subject(:execute) { described_class.new(current_user).execute(user) }
describe '#execute' do
context 'failures' do
context 'when the executor user is not allowed to approve users' do
let(:current_user) { create(:user) }
it 'returns error result' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to match(/You are not allowed to approve a user/)
end
end
context 'when the executor user is an admin not in admin mode' do
it 'returns error result' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to match(/You are not allowed to approve a user/)
end
end
context 'when the executor user is an admin in admin mode', :enable_admin_mode do
context 'when user is not in pending approval state' do
let(:user) { create(:user, state: 'active') }
it 'returns error result' do
expect(subject[:status]).to eq(:error)
expect(subject[:message])
.to match(/The user you are trying to approve is not pending approval/)
end
end
context 'when user cannot be activated' do
let(:user) do
build(:user, state: 'blocked_pending_approval', email: 'invalid email')
end
it 'returns error result' do
expect(subject[:status]).to eq(:error)
expect(subject[:message]).to match(/Email is invalid/)
end
it 'does not change the state of the user' do
expect { subject }.not_to change { user.state }
end
end
end
end
context 'success' do
context 'when the executor user is an admin in admin mode', :enable_admin_mode do
it 'activates the user' do
expect(subject[:status]).to eq(:success)
expect(user.reload).to be_active
end
it 'logs approval in application logs' do
allow(Gitlab::AppLogger).to receive(:info)
subject
expect(Gitlab::AppLogger).to have_received(:info).with(message: "User instance access request approved", user: user.username.to_s, email: user.email.to_s, approved_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s)
end
it 'emails the user on approval' do
expect(DeviseMailer).to receive(:user_admin_approval).with(user).and_call_original
expect { subject }.to have_enqueued_mail(DeviseMailer, :user_admin_approval)
end
context 'when the user was created via sign up' do
it 'does not send a password reset email' do
expect { subject }.not_to have_enqueued_mail(Notify, :new_user_email)
end
end
context 'when the user was created by an admin' do
let(:user) { create(:user, :blocked_pending_approval, created_by_id: current_user.id) }
it 'sends a password reset email' do
allow(user).to receive(:generate_reset_token).and_return(:reset_token)
expect(Notify).to receive(:new_user_email).with(user.id, :reset_token).and_call_original
expect { subject }.to have_enqueued_mail(Notify, :new_user_email)
end
end
context 'email confirmation status' do
context 'user is unconfirmed' do
let(:user) { create(:user, :blocked_pending_approval, :unconfirmed) }
it 'sends confirmation instructions' do
expect { subject }
.to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
end
end
context 'user is confirmed' do
it 'does not send a confirmation email' do
expect { subject }
.not_to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
end
end
context 'audit events' do
context 'when not licensed' do
before do
stub_licensed_features(
admin_audit_log: false
)
end
it 'does not log any audit event' do
expect { subject }.not_to change(AuditEvent, :count)
end
end
end
end
context 'pending invitations' do
let!(:project_member_invite) { create(:project_member, :invited, invite_email: user.email) }
let!(:group_member_invite) { create(:group_member, :invited, invite_email: user.email) }
context 'user is unconfirmed' do
let(:user) { create(:user, :blocked_pending_approval, :unconfirmed) }
it 'does not accept pending invites of the user' do
expect(subject[:status]).to eq(:success)
group_member_invite.reload
project_member_invite.reload
expect(group_member_invite).to be_invite
expect(project_member_invite).to be_invite
end
end
context 'user is confirmed' do
it 'accepts pending invites of the user' do
expect(subject[:status]).to eq(:success)
group_member_invite.reload
project_member_invite.reload
expect(group_member_invite).not_to be_invite
expect(project_member_invite).not_to be_invite
expect(group_member_invite.user).to eq(user)
expect(project_member_invite.user).to eq(user)
end
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class RespondToTermsService
def initialize(user, term)
@user = user
@term = term
end
# rubocop: disable CodeReuse/ActiveRecord
def execute(accepted:)
agreement = @user.term_agreements.find_or_initialize_by(term: @term)
agreement.accepted = accepted
if agreement.save
store_accepted_term(accepted)
end
agreement
end
# rubocop: enable CodeReuse/ActiveRecord
private
def store_accepted_term(accepted)
@user.update_column(:accepted_term_id, accepted ? @term.id : nil)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::RespondToTermsService, feature_category: :user_profile do
let(:user) { create(:user) }
let(:term) { create(:term) }
subject(:service) { described_class.new(user, term) }
describe '#execute' do
it 'creates a new agreement if it did not exist' do
expect { service.execute(accepted: true) }
.to change { user.term_agreements.size }.by(1)
end
it 'updates an agreement if it existed' do
agreement = create(:term_agreement, user: user, term: term, accepted: true)
service.execute(accepted: true)
expect(agreement.reload.accepted).to be_truthy
end
it 'adds the accepted terms to the user' do
service.execute(accepted: true)
expect(user.reload.accepted_term).to eq(term)
end
it 'removes accepted terms when declining' do
user.update!(accepted_term: term)
service.execute(accepted: false)
expect(user.reload.accepted_term).to be_nil
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class UpdateTodoCountCacheService < BaseService
QUERY_BATCH_SIZE = 10
attr_reader :user_ids
# user_ids - An array of User IDs
def initialize(user_ids)
@user_ids = user_ids
end
def execute
user_ids.each_slice(QUERY_BATCH_SIZE) do |user_ids_batch|
todo_counts = Todo.for_user(user_ids_batch).count_grouped_by_user_id_and_state
user_ids_batch.each do |user_id|
update_count_cache(user_id, todo_counts, :done)
update_count_cache(user_id, todo_counts, :pending)
end
end
end
private
def update_count_cache(user_id, todo_counts, state)
count = todo_counts.fetch([user_id, state.to_s], 0)
Rails.cache.write(
['users', user_id, "todos_#{state}_count"],
count,
expires_in: User::COUNT_CACHE_VALIDITY_PERIOD
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::UpdateTodoCountCacheService, feature_category: :team_planning do
describe '#execute' do
let_it_be(:user1) { create(:user) }
let_it_be(:user2) { create(:user) }
let_it_be(:todo1) { create(:todo, user: user1, state: :done) }
let_it_be(:todo2) { create(:todo, user: user1, state: :done) }
let_it_be(:todo3) { create(:todo, user: user1, state: :pending) }
let_it_be(:todo4) { create(:todo, user: user2, state: :done) }
let_it_be(:todo5) { create(:todo, user: user2, state: :pending) }
let_it_be(:todo6) { create(:todo, user: user2, state: :pending) }
def execute_all
described_class.new([user1.id, user2.id]).execute
end
def execute_single
described_class.new([user1.id]).execute
end
it 'updates the todos_counts for users', :use_clean_rails_memory_store_caching do
Rails.cache.write(['users', user1.id, 'todos_done_count'], 0)
Rails.cache.write(['users', user1.id, 'todos_pending_count'], 0)
Rails.cache.write(['users', user2.id, 'todos_done_count'], 0)
Rails.cache.write(['users', user2.id, 'todos_pending_count'], 0)
expect { execute_all }
.to change(user1, :todos_done_count).from(0).to(2)
.and change(user1, :todos_pending_count).from(0).to(1)
.and change(user2, :todos_done_count).from(0).to(1)
.and change(user2, :todos_pending_count).from(0).to(2)
Todo.delete_all
expect { execute_all }
.to change(user1, :todos_done_count).from(2).to(0)
.and change(user1, :todos_pending_count).from(1).to(0)
.and change(user2, :todos_done_count).from(1).to(0)
.and change(user2, :todos_pending_count).from(2).to(0)
end
it 'avoids N+1 queries' do
control_count = ActiveRecord::QueryRecorder.new { execute_single }.count
expect { execute_all }.not_to exceed_query_limit(control_count)
end
it 'executes one query per batch of users' do
stub_const("#{described_class}::QUERY_BATCH_SIZE", 1)
expect(ActiveRecord::QueryRecorder.new { execute_single }.count).to eq(1)
expect(ActiveRecord::QueryRecorder.new { execute_all }.count).to eq(2)
end
it 'sets the correct cache expire time' do
expect(Rails.cache).to receive(:write)
.with(['users', user1.id, anything], anything, expires_in: User::COUNT_CACHE_VALIDITY_PERIOD)
.twice
execute_single
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class ActivateService < BaseService
def initialize(current_user)
@current_user = current_user
end
def execute(user)
return error(_('You are not authorized to perform this action'), :forbidden) unless allowed?
return error(_('Error occurred. A blocked user must be unblocked to be activated'), :forbidden) if user.blocked?
return success(_('Successfully activated')) if user.active?
if user.activate
after_activate_hook(user)
log_event(user)
success(_('Successfully activated'))
else
error(user.errors.full_messages.to_sentence, :unprocessable_entity)
end
end
private
attr_reader :current_user
def allowed?
can?(current_user, :admin_all_resources)
end
def after_activate_hook(user)
# overridden by EE module
end
def log_event(user)
Gitlab::AppLogger.info(message: 'User activated', user: user.username.to_s, email: user.email.to_s,
activated_by: current_user.username.to_s, ip_address: current_user.current_sign_in_ip.to_s)
end
def success(message)
::ServiceResponse.success(message: message)
end
def error(message, reason)
::ServiceResponse.error(message: message, reason: reason)
end
end
end
Users::ActivateService.prepend_mod_with('Users::ActivateService') # rubocop: disable Cop/InjectEnterpriseEditionModule
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::ActivateService, feature_category: :user_management do
let_it_be(:current_user) { build(:admin) }
subject(:service) { described_class.new(current_user) }
describe '#execute' do
let!(:user) { create(:user, :deactivated) }
subject(:operation) { service.execute(user) }
context 'when successful', :enable_admin_mode do
it 'returns success status' do
expect(operation[:status]).to eq(:success)
end
it "changes the user's state" do
expect { operation }.to change { user.state }.to('active')
end
it 'creates a log entry' do
expect(Gitlab::AppLogger).to receive(:info).with(message: "User activated", user: user.username,
email: user.email, activated_by: current_user.username, ip_address: current_user.current_sign_in_ip.to_s)
operation
end
end
context 'when the user is already active', :enable_admin_mode do
let(:user) { create(:user) }
it 'returns success result' do
aggregate_failures 'success result' do
expect(operation[:status]).to eq(:success)
expect(operation[:message]).to eq('Successfully activated')
end
end
it "does not change the user's state" do
expect { operation }.not_to change { user.state }
end
end
context 'when user activation fails', :enable_admin_mode do
before do
allow(user).to receive(:activate).and_return(false)
end
it 'returns an unprocessable entity error' do
result = service.execute(user)
expect(result[:status]).to eq(:error)
expect(result[:reason]).to eq(:unprocessable_entity)
end
end
context 'when user is not an admin' do
let(:non_admin_user) { build(:user) }
let(:service) { described_class.new(non_admin_user) }
it 'returns permissions error message' do
expect(operation[:status]).to eq(:error)
expect(operation[:message]).to eq("You are not authorized to perform this action")
expect(operation.reason).to eq :forbidden
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class MigrateRecordsToGhostUserInBatchesService
LIMIT_SIZE = 1000
def initialize
@execution_tracker = Gitlab::Utils::ExecutionTracker.new
end
def execute
ghost_user_migrations.each do |job|
break if execution_tracker.over_limit?
service = Users::MigrateRecordsToGhostUserService.new(
job.user,
job.initiator_user,
execution_tracker
)
service.execute(hard_delete: job.hard_delete)
rescue Gitlab::Utils::ExecutionTracker::ExecutionTimeOutError
# no-op
rescue StandardError => e
::Gitlab::ErrorTracking.track_exception(e)
reschedule(job)
end
end
private
attr_reader :execution_tracker
def ghost_user_migrations
Users::GhostUserMigration.consume_order.limit(LIMIT_SIZE)
end
def reschedule(job)
job.update(consume_after: 30.minutes.from_now)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::MigrateRecordsToGhostUserInBatchesService, feature_category: :user_management do
let(:service) { described_class.new }
let_it_be(:ghost_user_migration) { create(:ghost_user_migration) }
describe '#execute' do
it 'stops when execution time limit reached' do
expect_next_instance_of(::Gitlab::Utils::ExecutionTracker) do |tracker|
expect(tracker).to receive(:over_limit?).and_return(true)
end
expect(Users::MigrateRecordsToGhostUserService).not_to receive(:new)
service.execute
end
it 'calls Users::MigrateRecordsToGhostUserService' do
expect_next_instance_of(Users::MigrateRecordsToGhostUserService) do |service|
expect(service).to(
receive(:execute)
.with(hard_delete: ghost_user_migration.hard_delete))
end
service.execute
end
it 'process jobs ordered by the consume_after timestamp' do
older_ghost_user_migration = create(
:ghost_user_migration,
user: create(:user),
consume_after: 5.minutes.ago
)
# setup execution tracker to only allow a single job to be processed
allow_next_instance_of(::Gitlab::Utils::ExecutionTracker) do |tracker|
allow(tracker).to receive(:over_limit?).and_return(false, true)
end
expect(Users::MigrateRecordsToGhostUserService).to(
receive(:new).with(
older_ghost_user_migration.user,
older_ghost_user_migration.initiator_user,
any_args
)
).and_call_original
service.execute
end
it 'reschedules job in case of an error', :freeze_time do
expect_next_instance_of(Users::MigrateRecordsToGhostUserService) do |service|
expect(service).to(receive(:execute)).and_raise(ActiveRecord::QueryCanceled)
end
expect(Gitlab::ErrorTracking).to receive(:track_exception)
expect { service.execute }.to(
change { ghost_user_migration.reload.consume_after }
.to(30.minutes.from_now))
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class CreateService < BaseService
include NewUserNotifier
def initialize(current_user, params = {})
@current_user = current_user
@params = params.dup
end
def execute
user = build_class.new(current_user, params).execute
reset_token = user.generate_reset_token if user.recently_sent_password_reset?
after_create_hook(user, reset_token) if user.save
user
end
private
def after_create_hook(user, reset_token)
notify_new_user(user, reset_token)
end
def build_class
# overridden by inheriting classes
Users::BuildService
end
end
end
Users::CreateService.prepend_mod_with('Users::CreateService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::CreateService, feature_category: :user_management do
describe '#execute' do
let(:password) { User.random_password }
let(:admin_user) { create(:admin) }
context 'with an admin user' do
let(:service) { described_class.new(admin_user, params) }
let(:email) { '[email protected]' }
context 'when required parameters are provided' do
let(:params) do
{ name: 'John Doe', username: 'jduser', email: email, password: password }
end
it 'returns a persisted user' do
expect(service.execute).to be_persisted
end
it 'persists the given attributes' do
user = service.execute
user.reload
expect(user).to have_attributes(
name: params[:name],
username: params[:username],
email: params[:email],
password: params[:password],
created_by_id: admin_user.id
)
end
context 'when the current_user is not persisted' do
let(:admin_user) { build(:admin) }
it 'persists the given attributes and sets created_by_id to nil' do
user = service.execute
user.reload
expect(user).to have_attributes(
name: params[:name],
username: params[:username],
email: params[:email],
password: params[:password],
created_by_id: nil
)
end
end
it 'user is not confirmed if skip_confirmation param is not present' do
expect(service.execute).not_to be_confirmed
end
it 'logs the user creation' do
expect(service).to receive(:log_info).with("User \"John Doe\" ([email protected]) was created")
service.execute
end
it 'executes system hooks' do
system_hook_service = spy(:system_hook_service)
expect(service).to receive(:system_hook_service).and_return(system_hook_service)
user = service.execute
expect(system_hook_service).to have_received(:execute_hooks_for).with(user, :create)
end
it 'does not send a notification email' do
notification_service = spy(:notification_service)
expect(service).not_to receive(:notification_service)
service.execute
expect(notification_service).not_to have_received(:new_user)
end
end
context 'when force_random_password parameter is true' do
let(:params) do
{ name: 'John Doe', username: 'jduser', email: '[email protected]', password: password, force_random_password: true }
end
it 'generates random password' do
user = service.execute
expect(user.password).not_to eq password
expect(user.password).to be_present
end
end
context 'when password_automatically_set parameter is true' do
let(:params) do
{
name: 'John Doe',
username: 'jduser',
email: '[email protected]',
password: password,
password_automatically_set: true
}
end
it 'persists the given attributes' do
user = service.execute
user.reload
expect(user).to have_attributes(
name: params[:name],
username: params[:username],
email: params[:email],
password: params[:password],
created_by_id: admin_user.id,
password_automatically_set: params[:password_automatically_set]
)
end
end
context 'when skip_confirmation parameter is true' do
let(:params) do
{ name: 'John Doe', username: 'jduser', email: '[email protected]', password: password, skip_confirmation: true }
end
it 'confirms the user' do
expect(service.execute).to be_confirmed
end
end
context 'when reset_password parameter is true' do
let(:params) do
{ name: 'John Doe', username: 'jduser', email: '[email protected]', password: password, reset_password: true }
end
it 'resets password even if a password parameter is given' do
expect(service.execute).to be_recently_sent_password_reset
end
it 'sends a notification email' do
notification_service = spy(:notification_service)
expect(service).to receive(:notification_service).and_return(notification_service)
user = service.execute
expect(notification_service).to have_received(:new_user).with(user, an_instance_of(String))
end
end
end
context 'with nil user' do
let(:params) do
{ name: 'John Doe', username: 'jduser', email: '[email protected]', password: password, skip_confirmation: true }
end
let(:service) { described_class.new(nil, params) }
it 'persists the given attributes' do
user = service.execute
user.reload
expect(user).to have_attributes(
name: params[:name],
username: params[:username],
email: params[:email],
password: params[:password],
created_by_id: nil,
admin: false
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
class BatchStatusCleanerService
BATCH_SIZE = 100
# Cleanup BATCH_SIZE user_statuses records
# rubocop: disable CodeReuse/ActiveRecord
def self.execute(batch_size: BATCH_SIZE)
scope = UserStatus
.select(:user_id)
.scheduled_for_cleanup
.lock('FOR UPDATE SKIP LOCKED')
.limit(batch_size)
deleted_rows = UserStatus.where(user_id: scope).delete_all
{ deleted_rows: deleted_rows }
end
# rubocop: enable CodeReuse/ActiveRecord
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::BatchStatusCleanerService, feature_category: :user_management do
let_it_be(:user_status_1) { create(:user_status, emoji: 'coffee', message: 'msg1', clear_status_at: 1.year.ago) }
let_it_be(:user_status_2) { create(:user_status, emoji: 'coffee', message: 'msg1', clear_status_at: 1.year.from_now) }
let_it_be(:user_status_3) { create(:user_status, emoji: 'coffee', message: 'msg1', clear_status_at: 2.years.ago) }
let_it_be(:user_status_4) { create(:user_status, emoji: 'coffee', message: 'msg1') }
subject(:result) { described_class.execute }
it 'cleans up scheduled user statuses' do
expect(result[:deleted_rows]).to eq(2)
deleted_statuses = UserStatus.where(user_id: [user_status_1.user_id, user_status_3.user_id])
expect(deleted_statuses).to be_empty
end
it 'does not affect rows with future clear_status_at' do
expect { result }.not_to change { user_status_2.reload }
end
it 'does not affect rows without clear_status_at' do
expect { result }.not_to change { user_status_4.reload }
end
describe 'batch_size' do
it 'clears status in batches' do
result = described_class.execute(batch_size: 1)
expect(result[:deleted_rows]).to eq(1)
result = described_class.execute(batch_size: 1)
expect(result[:deleted_rows]).to eq(1)
result = described_class.execute(batch_size: 1)
expect(result[:deleted_rows]).to eq(0)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
module SavedReplies
class DestroyService
def initialize(saved_reply:)
@saved_reply = saved_reply
end
def execute
if saved_reply.destroy
ServiceResponse.success(payload: { saved_reply: saved_reply })
else
ServiceResponse.error(message: saved_reply.errors.full_messages)
end
end
private
attr_reader :saved_reply
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::SavedReplies::DestroyService, feature_category: :team_planning do
describe '#execute' do
let!(:saved_reply) { create(:saved_reply) }
subject { described_class.new(saved_reply: saved_reply).execute }
context 'when destroy fails' do
before do
allow(saved_reply).to receive(:destroy).and_return(false)
end
it 'does not remove Saved Reply from database' do
expect { subject }.not_to change(::Users::SavedReply, :count)
end
it { is_expected.not_to be_success }
end
context 'when destroy succeeds' do
it { is_expected.to be_success }
it 'removes Saved Reply from database' do
expect { subject }.to change(::Users::SavedReply, :count).by(-1)
end
it 'returns saved reply' do
expect(subject[:saved_reply]).to eq(saved_reply)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
module SavedReplies
class UpdateService
def initialize(saved_reply:, name:, content:)
@saved_reply = saved_reply
@name = name
@content = content
end
def execute
if saved_reply.update(name: name, content: content)
ServiceResponse.success(payload: { saved_reply: saved_reply.reset })
else
ServiceResponse.error(message: saved_reply.errors.full_messages)
end
end
private
attr_reader :saved_reply, :name, :content
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::SavedReplies::UpdateService, feature_category: :team_planning do
describe '#execute' do
let_it_be(:current_user) { create(:user) }
let_it_be(:saved_reply) { create(:saved_reply, user: current_user) }
let_it_be(:other_saved_reply) { create(:saved_reply, user: current_user) }
let_it_be(:saved_reply_from_other_user) { create(:saved_reply) }
subject { described_class.new(saved_reply: saved_reply, name: name, content: content).execute }
context 'when update fails' do
let(:name) { other_saved_reply.name }
let(:content) { '' }
it { is_expected.not_to be_success }
it 'returns error messages' do
expect(subject.errors).to match_array(["Content can't be blank", "Name has already been taken"])
end
end
context 'when update succeeds' do
let(:name) { saved_reply_from_other_user.name }
let(:content) { 'New content for Saved Reply' }
it { is_expected.to be_success }
it 'updates new Saved Reply in database' do
expect { subject }.not_to change(::Users::SavedReply, :count)
end
it 'returns saved reply' do
expect(subject[:saved_reply]).to eq(saved_reply)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
module SavedReplies
class CreateService
def initialize(current_user:, name:, content:)
@current_user = current_user
@name = name
@content = content
end
def execute
saved_reply = saved_replies.build(name: name, content: content)
if saved_reply.save
ServiceResponse.success(payload: { saved_reply: saved_reply })
else
ServiceResponse.error(message: saved_reply.errors.full_messages)
end
end
private
attr_reader :current_user, :name, :content
delegate :saved_replies, to: :current_user
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::SavedReplies::CreateService, feature_category: :team_planning do
describe '#execute' do
let_it_be(:current_user) { create(:user) }
let_it_be(:saved_reply) { create(:saved_reply, user: current_user) }
subject { described_class.new(current_user: current_user, name: name, content: content).execute }
context 'when create fails' do
let(:name) { saved_reply.name }
let(:content) { '' }
it { is_expected.not_to be_success }
it 'does not create new Saved Reply in database' do
expect { subject }.not_to change(::Users::SavedReply, :count)
end
it 'returns error messages' do
expect(subject.errors).to match_array(["Content can't be blank", "Name has already been taken"])
end
end
context 'when create succeeds' do
let(:name) { 'new_saved_reply_name' }
let(:content) { 'New content for Saved Reply' }
it { is_expected.to be_success }
it 'creates new Saved Reply in database' do
expect { subject }.to change(::Users::SavedReply, :count).by(1)
end
it 'returns new saved reply', :aggregate_failures do
expect(subject[:saved_reply]).to eq(::Users::SavedReply.last)
expect(subject[:saved_reply].name).to eq(name)
expect(subject[:saved_reply].content).to eq(content)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
module EmailVerification
class ValidateTokenService < EmailVerification::BaseService
include ActionView::Helpers::DateHelper
TOKEN_VALID_FOR_MINUTES = 60
def initialize(attr:, user:, token:)
super(attr: attr, user: user)
@token = token
end
def execute
return failure(:rate_limited) if verification_rate_limited?
return failure(:invalid) unless valid?
return failure(:expired) if expired_token?
success
end
private
attr_reader :user
def verification_rate_limited?
Gitlab::ApplicationRateLimiter.throttled?(:email_verification, scope: user[attr])
end
def valid?
return false unless token.present?
Devise.secure_compare(user[attr], digest)
end
def expired_token?
generated_at = case attr
when :unlock_token then user.locked_at
when :confirmation_token then user.confirmation_sent_at
end
generated_at < TOKEN_VALID_FOR_MINUTES.minutes.ago
end
def success
{ status: :success }
end
def failure(reason)
{
status: :failure,
reason: reason,
message: failure_message(reason)
}
end
def failure_message(reason)
case reason
when :rate_limited
format(s_("IdentityVerification|You've reached the maximum amount of tries. "\
'Wait %{interval} or send a new code and try again.'), interval: email_verification_interval)
when :expired
s_('IdentityVerification|The code has expired. Send a new code and try again.')
when :invalid
s_('IdentityVerification|The code is incorrect. Enter it again, or send a new code.')
end
end
def email_verification_interval
interval_in_seconds = Gitlab::ApplicationRateLimiter.rate_limits[:email_verification][:interval]
distance_of_time_in_words(interval_in_seconds)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::EmailVerification::ValidateTokenService, :clean_gitlab_redis_rate_limiting, feature_category: :system_access do
using RSpec::Parameterized::TableSyntax
let(:service) { described_class.new(attr: attr, user: user, token: token) }
let(:email) { build_stubbed(:user).email }
let(:token) { 'token' }
let(:encrypted_token) { Devise.token_generator.digest(User, email, token) }
let(:generated_at_attr) { attr == :unlock_token ? :locked_at : :confirmation_sent_at }
let(:token_generated_at) { 1.minute.ago }
let(:user) { build(:user, email: email, attr => encrypted_token, generated_at_attr => token_generated_at) }
describe '#execute' do
context 'with a valid attribute' do
where(:attr) { [:unlock_token, :confirmation_token] }
with_them do
context 'when successful' do
it 'returns a success status' do
expect(service.execute).to eq(status: :success)
end
end
context 'when rate limited' do
before do
allow(Gitlab::ApplicationRateLimiter).to receive(:throttled?)
.with(:email_verification, scope: encrypted_token).and_return(true)
end
it 'returns a failure status' do
expect(service.execute).to eq(
{
status: :failure,
reason: :rate_limited,
message: format(s_("IdentityVerification|You've reached the maximum amount of tries. "\
'Wait %{interval} or send a new code and try again.'), interval: '10 minutes')
}
)
end
end
context 'when expired' do
let(:token_generated_at) { 2.hours.ago }
it 'returns a failure status' do
expect(service.execute).to eq(
{
status: :failure,
reason: :expired,
message: s_('IdentityVerification|The code has expired. Send a new code and try again.')
}
)
end
end
context 'when invalid' do
let(:encrypted_token) { 'xxx' }
it 'returns a failure status' do
expect(service.execute).to eq(
{
status: :failure,
reason: :invalid,
message: s_('IdentityVerification|The code is incorrect. Enter it again, or send a new code.')
}
)
end
end
context 'when encrypted token was not set and a blank token is provided' do
let(:encrypted_token) { nil }
let(:token) { '' }
it 'returns a failure status' do
expect(service.execute).to eq(
{
status: :failure,
reason: :invalid,
message: s_('IdentityVerification|The code is incorrect. Enter it again, or send a new code.')
}
)
end
end
end
end
context 'with an invalid attribute' do
let(:attr) { :username }
it 'raises an error' do
expect { service.execute }.to raise_error(ArgumentError, 'Invalid attribute')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
module EmailVerification
class GenerateTokenService < EmailVerification::BaseService
TOKEN_LENGTH = 6
def execute
@token = generate_token
[token, digest]
end
private
def generate_token
SecureRandom.random_number(10**TOKEN_LENGTH).to_s.rjust(TOKEN_LENGTH, '0')
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::EmailVerification::GenerateTokenService, feature_category: :system_access do
using RSpec::Parameterized::TableSyntax
let(:user) { build_stubbed(:user) }
let(:service) { described_class.new(attr: attr, user: user) }
let(:token) { 'token' }
let(:digest) { service.send(:digest) }
describe '#execute' do
context 'with a valid attribute' do
where(:attr) { [:unlock_token, :confirmation_token] }
with_them do
before do
allow_next_instance_of(described_class) do |service|
allow(service).to receive(:generate_token).and_return(token)
end
end
it "returns a token and it's digest" do
expect(service.execute).to eq([token, digest])
end
end
end
context 'with an invalid attribute' do
let(:attr) { :xxx }
it 'raises an error' do
expect { service.execute }.to raise_error(ArgumentError, 'Invalid attribute')
end
end
context 'when similar tokens are generated' do
let(:attr) { :confirmation_token }
before do
allow_next_instance_of(described_class) do |service|
allow(service).to receive(:generate_token).and_return(token)
end
end
it 'generates a unique digest' do
second_service = described_class.new(attr: attr, user: build_stubbed(:user))
expect(service.execute[1]).not_to eq(second_service.execute[1])
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Users
module EmailVerification
class UpdateEmailService
include ActionView::Helpers::DateHelper
RATE_LIMIT = :email_verification_code_send
def initialize(user:)
@user = user
end
def execute(email:)
return failure(:rate_limited) if rate_limited?
return failure(:already_offered) if already_offered?
return failure(:no_change) if no_change?(email)
return failure(:validation_error) unless update_email
success
end
private
attr_reader :user
def rate_limited?
Gitlab::ApplicationRateLimiter.throttled?(RATE_LIMIT, scope: user)
end
def already_offered?
user.email_reset_offered_at.present?
end
def no_change?(email)
user.email = email
!user.will_save_change_to_email?
end
def update_email
user.skip_confirmation_notification!
user.save
end
def success
{ status: :success }
end
def failure(reason)
{
status: :failure,
reason: reason,
message: failure_message(reason)
}
end
def failure_message(reason)
case reason
when :rate_limited
interval = distance_of_time_in_words(Gitlab::ApplicationRateLimiter.rate_limits[RATE_LIMIT][:interval])
format(
s_("IdentityVerification|You've reached the maximum amount of tries. Wait %{interval} and try again."),
interval: interval
)
when :already_offered
s_('IdentityVerification|Email update is only offered once.')
when :no_change
s_('IdentityVerification|A code has already been sent to this email address. ' \
'Check your spam folder or enter another email address.')
when :validation_error
user.errors.full_messages.join(' ')
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Users::EmailVerification::UpdateEmailService, feature_category: :instance_resiliency do
let_it_be_with_reload(:user) { create(:user) }
let(:email) { build_stubbed(:user).email }
describe '#execute' do
subject(:execute_service) { described_class.new(user: user).execute(email: email) }
context 'when successful' do
it { is_expected.to eq(status: :success) }
it 'does not send a confirmation instructions email' do
expect { execute_service }.not_to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
end
it 'sets the unconfirmed_email and confirmation_sent_at fields', :freeze_time do
expect { execute_service }
.to change { user.unconfirmed_email }.from(nil).to(email)
.and change { user.confirmation_sent_at }.from(nil).to(Time.current)
end
end
context 'when rate limited' do
before do
allow(Gitlab::ApplicationRateLimiter).to receive(:throttled?)
.with(:email_verification_code_send, scope: user).and_return(true)
end
it 'returns a failure status' do
expect(execute_service).to eq(
{
status: :failure,
reason: :rate_limited,
message: format(s_("IdentityVerification|You've reached the maximum amount of tries. " \
'Wait %{interval} and try again.'), interval: 'about 1 hour')
}
)
end
end
context 'when email reset has already been offered' do
before do
user.email_reset_offered_at = 1.minute.ago
end
it 'returns a failure status' do
expect(execute_service).to eq(
{
status: :failure,
reason: :already_offered,
message: s_('IdentityVerification|Email update is only offered once.')
}
)
end
end
context 'when email is unchanged' do
let(:email) { user.email }
it 'returns a failure status' do
expect(execute_service).to eq(
{
status: :failure,
reason: :no_change,
message: s_('IdentityVerification|A code has already been sent to this email address. ' \
'Check your spam folder or enter another email address.')
}
)
end
end
context 'when email is missing' do
let(:email) { '' }
it 'returns a failure status' do
expect(execute_service).to eq(
{
status: :failure,
reason: :validation_error,
message: "Email can't be blank"
}
)
end
end
context 'when email is not valid' do
let(:email) { 'xxx' }
it 'returns a failure status' do
expect(execute_service).to eq(
{
status: :failure,
reason: :validation_error,
message: 'Email is invalid'
}
)
end
end
context 'when email is already taken' do
before do
create(:user, email: email)
end
it 'returns a failure status' do
expect(execute_service).to eq(
{
status: :failure,
reason: :validation_error,
message: 'Email has already been taken'
}
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module ServiceDeskSettings
class UpdateService < BaseService
include ::ServiceDesk::CustomEmails::Logger
def execute
settings = ServiceDeskSetting.safe_find_or_create_by!(project_id: project.id)
params[:project_key] = nil if params[:project_key].blank?
apply_feature_flag_restrictions!
# We want to know when custom email got enabled
write_log_message = params[:custom_email_enabled].present? && !settings.custom_email_enabled?
if settings.update(params)
log_info if write_log_message
ServiceResponse.success
else
ServiceResponse.error(message: settings.errors.full_messages.to_sentence)
end
end
private
def apply_feature_flag_restrictions!
return if Feature.enabled?(:issue_email_participants, project)
return unless params.include?(:add_external_participants_from_cc)
params.delete(:add_external_participants_from_cc)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ServiceDeskSettings::UpdateService, :aggregate_failures, feature_category: :service_desk do
describe '#execute' do
let_it_be(:settings) do
create(:service_desk_setting, outgoing_name: 'original name', custom_email: '[email protected]')
end
let_it_be(:credential) { create(:service_desk_custom_email_credential, project: settings.project) }
let_it_be(:verification) { create(:service_desk_custom_email_verification, :finished, project: settings.project) }
let_it_be(:user) { create(:user) }
context 'with valid params' do
let(:params) { { outgoing_name: 'some name', project_key: 'foo', add_external_participants_from_cc: true } }
it 'updates service desk settings' do
response = described_class.new(settings.project, user, params).execute
expect(response).to be_success
expect(settings.reset).to have_attributes(
outgoing_name: 'some name',
project_key: 'foo',
add_external_participants_from_cc: true
)
end
context 'with custom email verification in finished state' do
let(:params) { { custom_email_enabled: true } }
before do
allow(Gitlab::AppLogger).to receive(:info)
end
it 'allows to enable custom email' do
settings.project.reset
response = described_class.new(settings.project, user, params).execute
expect(response).to be_success
expect(settings.reset.custom_email_enabled).to be true
expect(Gitlab::AppLogger).to have_received(:info).with({ category: 'custom_email' })
end
end
context 'when issue_email_participants feature flag is disabled' do
before do
stub_feature_flags(issue_email_participants: false)
end
it 'updates service desk setting but not add_external_participants_from_cc value' do
response = described_class.new(settings.project, user, params).execute
expect(response).to be_success
expect(settings.reset).to have_attributes(
outgoing_name: 'some name',
project_key: 'foo',
add_external_participants_from_cc: false
)
end
end
end
context 'when project_key is an empty string' do
let(:params) { { project_key: '' } }
it 'sets nil project_key' do
response = described_class.new(settings.project, user, params).execute
expect(response).to be_success
expect(settings.reload.project_key).to be_nil
end
end
context 'with invalid params' do
let(:params) { { outgoing_name: 'x' * 256 } }
it 'does not update service desk settings' do
response = described_class.new(settings.project, user, params).execute
expect(response).to be_error
expect(response.message).to eq 'Outgoing name is too long (maximum is 255 characters)'
expect(settings.reload.outgoing_name).to eq 'original name'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class ExportCsvService < ExportCsv::BaseService
NotAvailableError = StandardError.new('This feature is currently behind a feature flag and it is not available.')
def csv_data
raise NotAvailableError unless Feature.enabled?(:import_export_work_items_csv, resource_parent)
super
end
def email(mail_to_user)
Notify.export_work_items_csv_email(mail_to_user, resource_parent, csv_data, csv_builder.status).deliver_now
end
private
def associations_to_preload
[:project, [work_item_type: :enabled_widget_definitions], :author]
end
def header_to_value_hash
{
'Id' => 'iid',
'Title' => 'title',
'Description' => ->(work_item) { get_widget_value_for(work_item, :description) },
'Type' => ->(work_item) { work_item.work_item_type.name },
'Author' => 'author_name',
'Author Username' => ->(work_item) { work_item.author.username },
'Created At (UTC)' => ->(work_item) { work_item.created_at.to_fs(:csv) }
}
end
def get_widget_value_for(work_item, field)
widget_name = field_to_widget_map[field]
widget = work_item.get_widget(widget_name)
widget.try(field)
end
def field_to_widget_map
{
description: :description
}
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::ExportCsvService, :with_license, feature_category: :team_planning do
let_it_be(:user) { create(:user) }
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, :public, group: group) }
let_it_be(:work_item_1) { create(:work_item, description: 'test', project: project) }
let_it_be(:work_item_2) { create(:work_item, :incident, project: project) }
subject { described_class.new(WorkItem.all, project) }
def csv
CSV.parse(subject.csv_data, headers: true)
end
context 'when import_export_work_items_csv flag is not enabled' do
before do
stub_feature_flags(import_export_work_items_csv: false)
end
it 'renders an error' do
expect { subject.csv_data }.to raise_error(described_class::NotAvailableError)
end
end
it 'renders csv to string' do
expect(subject.csv_data).to be_a String
end
describe '#email' do
it 'emails csv' do
expect { subject.email(user) }.to change { ActionMailer::Base.deliveries.count }.from(0).to(1)
end
end
it 'returns two work items' do
expect(csv.count).to eq(2)
end
specify 'iid' do
expect(csv[0]['Id']).to eq work_item_1.iid.to_s
end
specify 'title' do
expect(csv[0]['Title']).to eq work_item_1.title
end
specify 'type' do
expect(csv[0]['Type']).to eq('Issue')
expect(csv[1]['Type']).to eq('Incident')
end
specify 'author name' do
expect(csv[0]['Author']).to eq(work_item_1.author_name)
end
specify 'author username' do
expect(csv[0]['Author Username']).to eq(work_item_1.author.username)
end
specify 'created_at' do
expect(csv[0]['Created At (UTC)']).to eq(work_item_1.created_at.to_fs(:csv))
end
specify 'description' do
expect(csv[0]['Description']).to be_present
expect(csv[0]['Description']).to eq(work_item_1.description)
end
it 'preloads fields to avoid N+1 queries' do
control = ActiveRecord::QueryRecorder.new { subject.csv_data }
create(:work_item, :task, project: project)
expect { subject.csv_data }.not_to exceed_query_limit(control)
end
it_behaves_like 'a service that returns invalid fields from selection'
# TODO - once we have a UI for this feature
# we can turn these into feature specs.
# more info at: https://gitlab.com/gitlab-org/gitlab/-/issues/396943
context 'when importing an exported file' do
context 'for work item of type issue' do
it_behaves_like 'a exported file that can be imported' do
let_it_be(:user) { create(:user) }
let_it_be(:origin_project) { create(:project) }
let_it_be(:target_project) { create(:project) }
let_it_be(:work_item) { create(:work_item, project: origin_project) }
let(:expected_matching_fields) { %w[title work_item_type] }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class DeleteTaskService
def initialize(work_item:, lock_version:, current_user: nil, task_params: {})
@work_item = work_item
@current_user = current_user
@task_params = task_params
@lock_version = lock_version
@task = task_params[:task]
@errors = []
end
def execute
transaction_result = ::WorkItem.transaction do
replacement_result = TaskListReferenceRemovalService.new(
work_item: @work_item,
task: @task,
line_number_start: @task_params[:line_number_start],
line_number_end: @task_params[:line_number_end],
lock_version: @lock_version,
current_user: @current_user
).execute
next ::ServiceResponse.error(message: replacement_result.errors, http_status: 422) if replacement_result.error?
delete_result = ::WorkItems::DeleteService.new(
container: @task.project,
current_user: @current_user
).execute(@task)
if delete_result.error?
@errors += delete_result.errors
raise ActiveRecord::Rollback
end
delete_result
end
return transaction_result if transaction_result
::ServiceResponse.error(message: @errors, http_status: 422)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::DeleteTaskService, feature_category: :team_planning do
let_it_be(:project) { create(:project) }
let_it_be(:developer) { create(:user).tap { |u| project.add_developer(u) } }
let_it_be_with_refind(:task) { create(:work_item, project: project, author: developer) }
let_it_be_with_refind(:list_work_item) do
create(:work_item, project: project, description: "- [ ] #{task.to_reference}+")
end
let(:current_user) { developer }
let(:line_number_start) { 1 }
let(:params) do
{
line_number_start: line_number_start,
line_number_end: 1,
task: task
}
end
before_all do
create(:issue_link, source_id: list_work_item.id, target_id: task.id)
end
shared_examples 'failing WorkItems::DeleteTaskService' do |error_message|
it { is_expected.to be_error }
it 'does not remove work item or issue links' do
expect do
service_result
list_work_item.reload
end.to not_change(WorkItem, :count).and(
not_change(IssueLink, :count)
).and(
not_change(list_work_item, :description)
)
end
it 'returns an error message' do
expect(service_result.errors).to contain_exactly(error_message)
end
end
describe '#execute' do
subject(:service_result) do
described_class.new(
work_item: list_work_item,
current_user: current_user,
lock_version: list_work_item.lock_version,
task_params: params
).execute
end
context 'when work item params are valid' do
it { is_expected.to be_success }
it 'deletes the work item and the related issue link' do
expect do
service_result
end.to change(WorkItem, :count).by(-1).and(
change(IssueLink, :count).by(-1)
)
end
it 'removes the task list item with the work item reference' do
expect do
service_result
end.to change(list_work_item, :description).from(list_work_item.description).to("- [ ] #{task.title}")
end
end
context 'when first operation fails' do
let(:line_number_start) { -1 }
it_behaves_like 'failing WorkItems::DeleteTaskService', 'line_number_start must be greater than 0'
end
context 'when last operation fails' do
let_it_be(:non_member_user) { create(:user) }
let(:current_user) { non_member_user }
it_behaves_like 'failing WorkItems::DeleteTaskService', 'User not authorized to delete work item'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class PrepareImportCsvService < Import::PrepareService
extend ::Gitlab::Utils::Override
private
override :worker
def worker
ImportWorkItemsCsvWorker
end
override :success_message
def success_message
_("Your work items are being imported. Once finished, you'll receive a confirmation email.")
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::PrepareImportCsvService, feature_category: :team_planning do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let(:file) { double }
let(:upload_service) { double }
let(:uploader) { double }
let(:upload) { double }
let(:subject) do
described_class.new(project, user, file: file).execute
end
context 'when file is uploaded correctly' do
let(:upload_id) { 99 }
before do
mock_upload
end
it 'returns a success message' do
result = subject
expect(result[:status]).to eq(:success)
expect(result[:message]).to eq(
"Your work items are being imported. Once finished, you'll receive a confirmation email.")
end
it 'enqueues the ImportWorkItemsCsvWorker' do
expect(WorkItems::ImportWorkItemsCsvWorker).to receive(:perform_async).with(user.id, project.id, upload_id)
subject
end
end
context 'when file upload fails' do
before do
mock_upload(false)
end
it 'returns an error message' do
result = subject
expect(result[:status]).to eq(:error)
expect(result[:message]).to eq('File upload error.')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class TaskListReferenceReplacementService
STALE_OBJECT_MESSAGE = 'Stale work item. Check lock version'
def initialize(work_item:, current_user:, work_item_reference:, line_number_start:, line_number_end:, title:, lock_version:)
@work_item = work_item
@current_user = current_user
@work_item_reference = work_item_reference
@line_number_start = line_number_start
@line_number_end = line_number_end
@title = title
@lock_version = lock_version
end
def execute
return ::ServiceResponse.error(message: STALE_OBJECT_MESSAGE) if @work_item.lock_version > @lock_version
return ::ServiceResponse.error(message: 'line_number_start must be greater than 0') if @line_number_start < 1
return ::ServiceResponse.error(message: 'line_number_end must be greater or equal to line_number_start') if @line_number_end < @line_number_start
return ::ServiceResponse.error(message: "Work item description can't be blank") if @work_item.description.blank?
source_lines = @work_item.description.split("\n")
markdown_task_first_line = source_lines[@line_number_start - 1]
task_line = Taskable::ITEM_PATTERN.match(markdown_task_first_line)
return ::ServiceResponse.error(message: "Unable to detect a task on line #{@line_number_start}") unless task_line
captures = task_line.captures
markdown_task_first_line.sub!(Taskable::ITEM_PATTERN, "#{captures[0]} #{captures[1]} #{@work_item_reference}+")
source_lines[@line_number_start - 1] = markdown_task_first_line
remove_additional_lines!(source_lines)
::WorkItems::UpdateService.new(
container: @work_item.project,
current_user: @current_user,
params: { description: source_lines.join("\n"), lock_version: @lock_version }
).execute(@work_item)
::ServiceResponse.success
rescue ActiveRecord::StaleObjectError
::ServiceResponse.error(message: STALE_OBJECT_MESSAGE)
end
private
def remove_additional_lines!(source_lines)
return if @line_number_end <= @line_number_start
source_lines.delete_if.each_with_index do |_line, index|
index >= @line_number_start && index < @line_number_end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::TaskListReferenceReplacementService, feature_category: :team_planning do
let_it_be(:developer) { create(:user) }
let_it_be(:project) { create(:project, :repository).tap { |project| project.add_developer(developer) } }
let_it_be(:single_line_work_item, refind: true) { create(:work_item, project: project, description: '- [ ] single line', lock_version: 3) }
let_it_be(:multiple_line_work_item, refind: true) { create(:work_item, project: project, description: "Any text\n\n* [ ] Item to be converted\n second line\n third line", lock_version: 3) }
let(:line_number_start) { 3 }
let(:line_number_end) { 5 }
let(:title) { 'work item title' }
let(:reference) { 'any reference' }
let(:work_item) { multiple_line_work_item }
let(:lock_version) { 3 }
let(:expected_additional_text) { '' }
shared_examples 'successful work item task reference replacement service' do
it { is_expected.to be_success }
it 'replaces the original issue markdown description with new work item reference' do
result
expect(work_item.description).to eq("#{expected_additional_text}#{task_prefix} #{reference}+")
end
end
shared_examples 'failing work item task reference replacement service' do |error_message|
it { is_expected.to be_error }
it 'returns an error message' do
expect(result.errors).to contain_exactly(error_message)
end
end
describe '#execute' do
subject(:result) do
described_class.new(
work_item: work_item,
current_user: developer,
work_item_reference: reference,
line_number_start: line_number_start,
line_number_end: line_number_end,
title: title,
lock_version: lock_version
).execute
end
context 'when task mardown spans a single line' do
let(:line_number_start) { 1 }
let(:line_number_end) { 1 }
let(:work_item) { single_line_work_item }
let(:task_prefix) { '- [ ]' }
it_behaves_like 'successful work item task reference replacement service'
it 'creates description version note' do
expect { result }.to change(Note, :count).by(1)
expect(work_item.notes.last.note).to eq('changed the description')
expect(work_item.saved_description_version.id).to eq(work_item.notes.last.system_note_metadata.description_version_id)
end
end
context 'when task mardown spans multiple lines' do
let(:task_prefix) { '* [ ]' }
let(:expected_additional_text) { "Any text\n\n" }
it_behaves_like 'successful work item task reference replacement service'
end
context 'when description does not contain a task' do
let_it_be(:no_matching_work_item) { create(:work_item, project: project, description: 'no matching task') }
let(:work_item) { no_matching_work_item }
it_behaves_like 'failing work item task reference replacement service', 'Unable to detect a task on line 3'
end
context 'when description is empty' do
let_it_be(:empty_work_item) { create(:work_item, project: project, description: '') }
let(:work_item) { empty_work_item }
it_behaves_like 'failing work item task reference replacement service', "Work item description can't be blank"
end
context 'when line_number_start is lower than 1' do
let(:line_number_start) { 0 }
it_behaves_like 'failing work item task reference replacement service', 'line_number_start must be greater than 0'
end
context 'when line_number_end is lower than line_number_start' do
let(:line_number_end) { line_number_start - 1 }
it_behaves_like 'failing work item task reference replacement service', 'line_number_end must be greater or equal to line_number_start'
end
context 'when lock_version is older than current' do
let(:lock_version) { 2 }
it_behaves_like 'failing work item task reference replacement service', 'Stale work item. Check lock version'
end
context 'when work item is stale before updating' do
it_behaves_like 'failing work item task reference replacement service', 'Stale work item. Check lock version' do
before do
::WorkItem.where(id: work_item.id).update_all(lock_version: lock_version + 1)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class ImportCsvService < ImportCsv::BaseService
extend ::Gitlab::Utils::Override
FeatureNotAvailableError = StandardError.new(
'This feature is currently behind a feature flag and it is not available.'
)
NotAuthorizedError = StandardError.new('You do not have permission to import work items in this project.')
override :initialize
def initialize(*args)
super
@type_errors = {
blank: [],
missing: {},
disallowed: {}
}
end
def self.required_headers
%w[title type].freeze
end
def execute
raise FeatureNotAvailableError if ::Feature.disabled?(:import_export_work_items_csv, project)
raise NotAuthorizedError unless Ability.allowed?(user, :import_work_items, project)
super
end
def email_results_to_user
Notify.import_work_items_csv_email(user.id, project.id, results).deliver_later
end
private
attr_accessor :type_errors
def create_object(attributes)
super[:work_item]
end
def create_object_class
::WorkItems::CreateService
end
override :attributes_for
def attributes_for(row)
{
title: row[:title],
work_item_type: match_work_item_type(row[:type])
}
end
override :validate_headers_presence!
def validate_headers_presence!(headers)
required_headers = self.class.required_headers
headers.downcase!
return if headers && required_headers.all? { |rh| headers.include?(rh) }
required_headers_message = "Required headers are missing. Required headers are #{required_headers.join(', ')}"
raise CSV::MalformedCSVError.new(required_headers_message, 1)
end
def match_work_item_type(work_item_type)
match = available_work_item_types[work_item_type&.downcase]
match[:type] if match
end
def available_work_item_types
{
issue: {
allowed: Ability.allowed?(user, :create_issue, project),
type: WorkItems::Type.default_by_type(:issue)
}
}.with_indifferent_access
end
strong_memoize_attr :available_work_item_types
def preprocess!
with_csv_lines.each do |row, line_no|
work_item_type = row[:type]&.strip&.downcase
if work_item_type.blank?
type_errors[:blank] << line_no
elsif missing?(work_item_type)
# does this work item exist in the range of work items we support?
(type_errors[:missing][work_item_type] ||= []) << line_no
elsif !allowed?(work_item_type)
(type_errors[:disallowed][work_item_type] ||= []) << line_no
end
end
return if type_errors[:blank].empty? &&
type_errors[:missing].blank? &&
type_errors[:disallowed].blank?
results[:type_errors] = type_errors
raise PreprocessError
end
def missing?(work_item_type_name)
!available_work_item_types.key?(work_item_type_name)
end
def allowed?(work_item_type_name)
!!available_work_item_types[work_item_type_name][:allowed]
end
end
end
WorkItems::ImportCsvService.prepend_mod
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::ImportCsvService, feature_category: :team_planning do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let_it_be(:author) { create(:user, username: 'csv_author') }
let(:file) { fixture_file_upload('spec/fixtures/work_items_valid_types.csv') }
let(:service) do
uploader = FileUploader.new(project)
uploader.store!(file)
described_class.new(user, project, uploader)
end
let_it_be(:issue_type) { ::WorkItems::Type.default_issue_type }
let(:work_items) { ::WorkItems::WorkItemsFinder.new(user, project: project).execute }
let(:email_method) { :import_work_items_csv_email }
subject { service.execute }
describe '#execute', :aggregate_failures do
context 'when user has permission' do
before do
project.add_reporter(user)
end
it_behaves_like 'importer with email notification'
context 'when file format is valid' do
context 'when work item types are available' do
it 'creates the expected number of work items' do
expect { subject }.to change { work_items.count }.by 2
end
it 'sets work item attributes' do
result = subject
expect(work_items.reload).to contain_exactly(
have_attributes(
title: 'Valid issue',
work_item_type_id: issue_type.id
),
have_attributes(
title: 'Valid issue with alternate case',
work_item_type_id: issue_type.id
)
)
expect(result[:success]).to eq(2)
expect(result[:error_lines]).to eq([])
expect(result[:type_errors]).to be_nil
expect(result[:parse_error]).to eq(false)
end
end
context 'when csv contains work item types that are missing or not available' do
let(:file) { fixture_file_upload('spec/fixtures/work_items_invalid_types.csv') }
it 'creates no work items' do
expect { subject }.not_to change { work_items.count }
end
it 'returns the correct result' do
result = subject
expect(result[:success]).to eq(0)
expect(result[:error_lines]).to be_empty # there are problematic lines detailed below
expect(result[:parse_error]).to eq(false)
expect(result[:type_errors]).to match({
blank: [4],
disallowed: {}, # tested in the EE version
missing: {
"isssue" => [2],
"issue!!" => [3]
}
})
end
end
end
context 'when file is missing necessary headers' do
let(:file) { fixture_file_upload('spec/fixtures/work_items_missing_header.csv') }
it 'creates no records' do
result = subject
expect(result[:success]).to eq(0)
expect(result[:error_lines]).to eq([1])
expect(result[:type_errors]).to be_nil
expect(result[:parse_error]).to eq(true)
end
it 'creates no work items' do
expect { subject }.not_to change { work_items.count }
end
end
context 'when import_export_work_items_csv feature flag is off' do
before do
stub_feature_flags(import_export_work_items_csv: false)
end
it 'raises an error' do
expect { subject }.to raise_error(/This feature is currently behind a feature flag and it is not available./)
end
end
end
context 'when user does not have permission' do
before do
project.add_guest(user)
end
it 'raises an error' do
expect { subject }.to raise_error(/You do not have permission to import work items in this project/)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class CreateFromTaskService
def initialize(work_item:, perform_spam_check: true, current_user: nil, work_item_params: {})
@work_item = work_item
@current_user = current_user
@work_item_params = work_item_params
@perform_spam_check = perform_spam_check
@errors = []
end
def execute
transaction_result = ApplicationRecord.transaction do
create_and_link_result = CreateAndLinkService.new(
project: @work_item.project,
current_user: @current_user,
params: @work_item_params.slice(:title, :work_item_type_id),
perform_spam_check: @perform_spam_check,
link_params: { parent_work_item: @work_item }
).execute
if create_and_link_result.error?
@errors += create_and_link_result.errors
raise ActiveRecord::Rollback
end
replacement_result = TaskListReferenceReplacementService.new(
work_item: @work_item,
current_user: @current_user,
work_item_reference: create_and_link_result[:work_item].to_reference,
line_number_start: @work_item_params[:line_number_start],
line_number_end: @work_item_params[:line_number_end],
title: @work_item_params[:title],
lock_version: @work_item_params[:lock_version]
).execute
if replacement_result.error?
@errors += replacement_result.errors
raise ActiveRecord::Rollback
end
create_and_link_result
end
return transaction_result if transaction_result
::ServiceResponse.error(message: @errors, http_status: 422)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::CreateFromTaskService, feature_category: :team_planning do
let_it_be(:project) { create(:project) }
let_it_be(:developer) { create(:user) }
let_it_be(:list_work_item, refind: true) { create(:work_item, project: project, description: "- [ ] Item to be converted\n second line\n third line") }
let(:work_item_to_update) { list_work_item }
let(:link_params) { {} }
let(:current_user) { developer }
let(:params) do
{
title: 'Awesome work item',
work_item_type_id: WorkItems::Type.default_by_type(:task).id,
line_number_start: 1,
line_number_end: 3,
lock_version: work_item_to_update.lock_version
}
end
before_all do
project.add_developer(developer)
end
shared_examples 'CreateFromTask service with invalid params' do
it { is_expected.to be_error }
it 'does not create a work item or links' do
expect do
service_result
end.to not_change(WorkItem, :count).and(
not_change(WorkItems::ParentLink, :count)
)
end
end
describe '#execute' do
subject(:service_result) { described_class.new(work_item: work_item_to_update, current_user: current_user, work_item_params: params).execute }
context 'when work item params are valid' do
it { is_expected.to be_success }
it 'creates a work item and creates parent link to the original work item' do
expect do
service_result
end.to change(WorkItem, :count).by(1).and(
change(WorkItems::ParentLink, :count).by(1)
)
expect(work_item_to_update.reload.work_item_children).not_to be_empty
end
it 'replaces the original issue markdown description with new work item reference' do
service_result
created_work_item = WorkItem.last
expect(list_work_item.description).to eq("- [ ] #{created_work_item.to_reference}+")
end
it_behaves_like 'title with extra spaces'
end
context 'when last operation fails' do
before do
params.merge!(line_number_start: 0)
end
it 'rollbacks all operations' do
expect do
service_result
end.to not_change(WorkItem, :count).and(
not_change(WorkItems::ParentLink, :count)
)
end
it { is_expected.to be_error }
it 'returns an error message' do
expect(service_result.errors).to contain_exactly('line_number_start must be greater than 0')
end
end
context 'when work item params are invalid' do
let(:params) { { title: '' } }
it_behaves_like 'CreateFromTask service with invalid params'
it 'returns work item errors' do
expect(service_result.errors).to contain_exactly("Title can't be blank")
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class TaskListReferenceRemovalService
STALE_OBJECT_MESSAGE = 'Stale work item. Check lock version'
def initialize(work_item:, task:, line_number_start:, line_number_end:, lock_version:, current_user:)
@work_item = work_item
@task = task
@line_number_start = line_number_start
@line_number_end = line_number_end
@lock_version = lock_version
@current_user = current_user
@task_reference = /#{Regexp.escape(@task.to_reference)}(?!\d)\+/
end
def execute
return ::ServiceResponse.error(message: 'line_number_start must be greater than 0') if @line_number_start < 1
return ::ServiceResponse.error(message: "Work item description can't be blank") if @work_item.description.blank?
if @line_number_end < @line_number_start
return ::ServiceResponse.error(message: 'line_number_end must be greater or equal to line_number_start')
end
source_lines = @work_item.description.split("\n")
line_matches_reference = (@line_number_start..@line_number_end).any? do |line_number|
markdown_line = source_lines[line_number - 1]
if @task_reference.match?(markdown_line)
markdown_line.sub!(@task_reference, @task.title)
end
end
unless line_matches_reference
return ::ServiceResponse.error(
message: "Unable to detect a task on lines #{@line_number_start}-#{@line_number_end}"
)
end
::WorkItems::UpdateService.new(
container: @work_item.project,
current_user: @current_user,
params: { description: source_lines.join("\n"), lock_version: @lock_version }
).execute(@work_item)
if @work_item.valid?
::ServiceResponse.success
else
::ServiceResponse.error(message: @work_item.errors.full_messages)
end
rescue ActiveRecord::StaleObjectError
::ServiceResponse.error(message: STALE_OBJECT_MESSAGE)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::TaskListReferenceRemovalService, feature_category: :team_planning do
let_it_be(:developer) { create(:user) }
let_it_be(:project) { create(:project, :repository).tap { |project| project.add_developer(developer) } }
let_it_be(:task) { create(:work_item, project: project, title: 'Task title') }
let_it_be(:single_line_work_item, refind: true) do
create(:work_item, project: project, description: "- [ ] #{task.to_reference}+ single line")
end
let_it_be(:multiple_line_work_item, refind: true) do
create(
:work_item,
project: project,
description: <<~MARKDOWN
Any text
* [ ] Item to be converted
#{task.to_reference}+ second line
third line
* [x] task
More text
MARKDOWN
)
end
let(:line_number_start) { 3 }
let(:line_number_end) { 5 }
let(:work_item) { multiple_line_work_item }
let(:lock_version) { work_item.lock_version }
shared_examples 'successful work item task reference removal service' do |expected_description|
it { is_expected.to be_success }
it 'removes the task list item containing the task reference' do
expect do
result
end.to change(work_item, :description).from(work_item.description).to(expected_description)
end
it 'creates system notes' do
expect do
result
end.to change(Note, :count).by(1)
expect(Note.last.note).to include('changed the description')
end
end
shared_examples 'failing work item task reference removal service' do |error_message|
it { is_expected.to be_error }
it 'does not change the work item description' do
expect do
result
work_item.reload
end.to not_change(work_item, :description)
end
it 'returns an error message' do
expect(result.errors).to contain_exactly(error_message)
end
end
describe '#execute' do
subject(:result) do
described_class.new(
work_item: work_item,
task: task,
line_number_start: line_number_start,
line_number_end: line_number_end,
lock_version: lock_version,
current_user: developer
).execute
end
context 'when task mardown spans a single line' do
let(:line_number_start) { 1 }
let(:line_number_end) { 1 }
let(:work_item) { single_line_work_item }
it_behaves_like 'successful work item task reference removal service', '- [ ] Task title single line'
context 'when description does not contain a task' do
let_it_be(:no_matching_work_item) { create(:work_item, project: project, description: 'no matching task') }
let(:work_item) { no_matching_work_item }
it_behaves_like 'failing work item task reference removal service', 'Unable to detect a task on lines 1-1'
end
context 'when description reference does not exactly match the task reference' do
before do
work_item.update!(description: work_item.description.gsub(task.to_reference, "#{task.to_reference}200"))
end
it_behaves_like 'failing work item task reference removal service', 'Unable to detect a task on lines 1-1'
end
end
context 'when task mardown spans multiple lines' do
it_behaves_like 'successful work item task reference removal service',
"Any text\n\n* [ ] Item to be converted\n Task title second line\n third line\n* [x] task\n\nMore text"
end
context 'when updating the work item fails' do
before do
work_item.title = nil
end
it_behaves_like 'failing work item task reference removal service', "Title can't be blank"
end
context 'when description is empty' do
let_it_be(:empty_work_item) { create(:work_item, project: project, description: '') }
let(:work_item) { empty_work_item }
it_behaves_like 'failing work item task reference removal service', "Work item description can't be blank"
end
context 'when line_number_start is lower than 1' do
let(:line_number_start) { 0 }
it_behaves_like 'failing work item task reference removal service', 'line_number_start must be greater than 0'
end
context 'when line_number_end is lower than line_number_start' do
let(:line_number_end) { line_number_start - 1 }
it_behaves_like 'failing work item task reference removal service',
'line_number_end must be greater or equal to line_number_start'
end
context 'when lock_version is older than current' do
let(:lock_version) { work_item.lock_version - 1 }
it_behaves_like 'failing work item task reference removal service', 'Stale work item. Check lock version'
end
context 'when work item is stale before updating' do
it_behaves_like 'failing work item task reference removal service', 'Stale work item. Check lock version' do
before do
::WorkItem.where(id: work_item.id).update_all(lock_version: lock_version + 1)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class BuildService < ::Issues::BuildService
private
def model_klass
::WorkItem
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::BuildService, feature_category: :team_planning do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:guest) { create(:user) }
let(:user) { guest }
before_all do
project.add_guest(guest)
end
describe '#execute' do
subject { described_class.new(container: project, current_user: user, params: {}).execute }
it { is_expected.to be_a(::WorkItem) }
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
# Create and link operations are not run inside a transaction in this class
# because CreateFromTaskService also creates a transaction.
# This class should always be run inside a transaction as we could end up with
# new work items that were never associated with other work items as expected.
class CreateAndLinkService
def initialize(project:, perform_spam_check: true, current_user: nil, params: {}, link_params: {})
@project = project
@current_user = current_user
@params = params
@link_params = link_params
@perform_spam_check = perform_spam_check
end
def execute
create_result = CreateService.new(
container: @project,
current_user: @current_user,
params: @params.merge(title: @params[:title].strip).reverse_merge(confidential: confidential_parent),
perform_spam_check: @perform_spam_check
).execute
return create_result if create_result.error?
work_item = create_result[:work_item]
return ::ServiceResponse.success(payload: payload(work_item)) if @link_params.blank?
result = WorkItems::ParentLinks::CreateService.new(
@link_params[:parent_work_item],
@current_user,
{ target_issuable: work_item }
).execute
if result[:status] == :success
::ServiceResponse.success(payload: payload(work_item))
else
::ServiceResponse.error(message: result[:message], http_status: 404)
end
end
private
def confidential_parent
!!@link_params[:parent_work_item]&.confidential
end
def payload(work_item)
{ work_item: work_item }
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::CreateAndLinkService, feature_category: :portfolio_management do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, group: group) }
let_it_be(:user) { create(:user) }
let_it_be(:related_work_item, refind: true) { create(:work_item, project: project) }
let_it_be(:invalid_parent) { create(:work_item, :task, project: project) }
let(:link_params) { {} }
let(:params) do
{
title: 'Awesome work item',
description: 'please fix',
work_item_type_id: WorkItems::Type.default_by_type(:task).id
}
end
before_all do
project.add_developer(user)
end
shared_examples 'successful work item and link creator' do
it 'creates a work item successfully with links' do
expect do
service_result
end.to change(WorkItem, :count).by(1).and(
change(WorkItems::ParentLink, :count).by(1)
)
end
it 'copies confidential status from the parent' do
expect do
service_result
end.to change(WorkItem, :count).by(1)
created_task = WorkItem.last
expect(created_task.confidential).to eq(related_work_item.confidential)
end
end
describe '#execute' do
subject(:service_result) { described_class.new(project: project, current_user: user, params: params, link_params: link_params).execute }
context 'when work item params are valid' do
it { is_expected.to be_success }
it 'creates a work item successfully with no links' do
expect do
service_result
end.to change(WorkItem, :count).by(1).and(
not_change(IssueLink, :count)
)
end
it_behaves_like 'title with extra spaces'
context 'when link params are valid' do
let(:link_params) { { parent_work_item: related_work_item } }
context 'when parent is not confidential' do
it_behaves_like 'successful work item and link creator'
end
context 'when parent is confidential' do
before do
related_work_item.update!(confidential: true)
end
it_behaves_like 'successful work item and link creator'
end
end
context 'when link creation fails' do
let(:link_params) { { parent_work_item: invalid_parent } }
it { is_expected.to be_error }
it 'does not create a link and does not rollback transaction' do
expect do
service_result
end.to not_change(WorkItems::ParentLink, :count).and(
change(WorkItem, :count).by(1)
)
end
it 'returns a link creation error message' do
expect(service_result.errors).to contain_exactly(/is not allowed to add this type of parent/)
end
end
end
context 'when work item params are invalid' do
let(:params) do
{
title: '',
description: 'invalid work item'
}
end
it { is_expected.to be_error }
it 'does not create a work item or links' do
expect do
service_result
end.to not_change(WorkItem, :count).and(
not_change(WorkItems::ParentLink, :count)
)
end
it 'returns work item errors' do
expect(service_result.errors).to contain_exactly("Title can't be blank")
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class UpdateService < ::Issues::UpdateService
extend Gitlab::Utils::Override
include WidgetableService
def initialize(container:, current_user: nil, params: {}, perform_spam_check: false, widget_params: {})
params[:widget_params] = true if widget_params.present?
super(container: container, current_user: current_user, params: params, perform_spam_check: perform_spam_check)
@widget_params = widget_params
end
def execute(work_item)
updated_work_item = super
if updated_work_item.valid?
success(payload(work_item))
else
error(updated_work_item.errors.full_messages, :unprocessable_entity, pass_back: payload(updated_work_item))
end
rescue ::WorkItems::Widgets::BaseService::WidgetError => e
error(e.message, :unprocessable_entity)
end
private
override :handle_quick_actions
def handle_quick_actions(work_item)
# Do not handle quick actions unless the work item is the default Issue.
# The available quick actions for a work item depend on its type and widgets.
return unless work_item.work_item_type.default_issue?
super
end
def prepare_update_params(work_item)
execute_widgets(
work_item: work_item,
callback: :prepare_update_params,
widget_params: @widget_params,
service_params: params
)
super
end
def before_update(work_item, skip_spam_check: false)
execute_widgets(work_item: work_item, callback: :before_update_callback, widget_params: @widget_params)
super
end
def transaction_update(work_item, opts = {})
execute_widgets(work_item: work_item, callback: :before_update_in_transaction, widget_params: @widget_params)
super
end
override :after_update
def after_update(work_item, old_associations)
super
GraphqlTriggers.issuable_title_updated(work_item) if work_item.previous_changes.key?(:title)
end
def payload(work_item)
{ work_item: work_item }
end
def handle_label_changes(issuable, old_labels)
return false unless super
Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter.track_work_item_labels_changed_action(
author: current_user
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::UpdateService, feature_category: :team_planning do
let_it_be(:developer) { create(:user) }
let_it_be(:guest) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:parent) { create(:work_item, project: project) }
let_it_be_with_reload(:work_item) { create(:work_item, project: project, assignees: [developer]) }
let(:widget_params) { {} }
let(:opts) { {} }
let(:current_user) { developer }
before do
project.add_developer(developer)
project.add_guest(guest)
end
describe '#execute' do
let(:service) do
described_class.new(
container: project,
current_user: current_user,
params: opts,
widget_params: widget_params
)
end
subject(:update_work_item) { service.execute(work_item) }
shared_examples 'update service that triggers graphql dates updated subscription' do
it 'triggers graphql subscription issueableDatesUpdated' do
expect(GraphqlTriggers).to receive(:issuable_dates_updated).with(work_item).and_call_original
update_work_item
end
end
context 'when applying quick actions' do
let(:opts) { { description: "/shrug" } }
context 'when work item type is not the default Issue' do
before do
task_type = WorkItems::Type.default_by_type(:task)
work_item.update_columns(work_item_type_id: task_type.id)
end
it 'does not apply the quick action' do
expect do
update_work_item
end.to change(work_item, :description).to('/shrug')
end
end
context 'when work item type is the default Issue' do
let(:issue) { create(:work_item, description: '') }
it 'applies the quick action' do
expect do
update_work_item
end.to change(work_item, :description).to(' ¯\_(ツ)_/¯')
end
end
end
context 'when title is changed' do
let(:opts) { { title: 'changed' } }
it 'triggers issuable_title_updated graphql subscription' do
expect(GraphqlTriggers).to receive(:issuable_title_updated).with(work_item).and_call_original
expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter).to receive(:track_work_item_title_changed_action).with(author: current_user)
# During the work item transition we also want to track work items as issues
expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_title_changed_action)
expect(update_work_item[:status]).to eq(:success)
end
it_behaves_like 'internal event tracking' do
let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_TITLE_CHANGED }
let(:user) { current_user }
let(:namespace) { project.namespace }
subject(:service_action) { update_work_item[:status] }
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
end
context 'when title is not changed' do
let(:opts) { { description: 'changed' } }
it 'does not trigger issuable_title_updated graphql subscription' do
expect(GraphqlTriggers).not_to receive(:issuable_title_updated)
expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter).not_to receive(:track_work_item_title_changed_action)
expect(update_work_item[:status]).to eq(:success)
end
it 'does not emit Snowplow event', :snowplow do
expect_no_snowplow_event
update_work_item
end
end
context 'when dates are changed' do
let(:opts) { { start_date: Date.today } }
it 'tracks users updating work item dates' do
expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter).to receive(:track_work_item_date_changed_action).with(author: current_user)
update_work_item
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
end
context 'when decription is changed' do
let(:opts) { { description: 'description changed' } }
it 'triggers GraphQL description updated subscription' do
expect(GraphqlTriggers).to receive(:issuable_description_updated).with(work_item).and_call_original
update_work_item
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
end
context 'when decription is not changed' do
let(:opts) { { title: 'title changed' } }
it 'does not trigger GraphQL description updated subscription' do
expect(GraphqlTriggers).not_to receive(:issuable_description_updated)
update_work_item
end
end
context 'when updating state_event' do
context 'when state_event is close' do
let(:opts) { { state_event: 'close' } }
it 'closes the work item' do
expect do
update_work_item
work_item.reload
end.to change(work_item, :state).from('opened').to('closed')
end
end
context 'when state_event is reopen' do
let(:opts) { { state_event: 'reopen' } }
before do
work_item.close!
end
it 'reopens the work item' do
expect do
update_work_item
work_item.reload
end.to change(work_item, :state).from('closed').to('opened')
end
end
end
it_behaves_like 'work item widgetable service' do
let(:widget_params) do
{
hierarchy_widget: { parent: parent },
description_widget: { description: 'foo' }
}
end
let(:service) do
described_class.new(
container: project,
current_user: current_user,
params: opts,
widget_params: widget_params
)
end
let(:service_execute) { service.execute(work_item) }
let(:supported_widgets) do
[
{ klass: WorkItems::Widgets::DescriptionService::UpdateService, callback: :before_update_callback, params: { description: 'foo' } },
{ klass: WorkItems::Widgets::HierarchyService::UpdateService, callback: :before_update_in_transaction, params: { parent: parent } }
]
end
end
context 'when updating widgets' do
let(:widget_service_class) { WorkItems::Widgets::DescriptionService::UpdateService }
let(:widget_params) { { description_widget: { description: 'changed' } } }
context 'when widget service is not present' do
before do
allow(widget_service_class).to receive(:new).and_return(nil)
end
it 'ignores widget param' do
expect { update_work_item }.not_to change(work_item, :description)
end
end
context 'when the widget does not support update callback' do
before do
allow_next_instance_of(widget_service_class) do |instance|
allow(instance)
.to receive(:before_update_callback)
.with(params: { description: 'changed' }).and_return(nil)
end
end
it 'ignores widget param' do
expect { update_work_item }.not_to change(work_item, :description)
end
end
context 'for the description widget' do
it 'updates the description of the work item' do
update_work_item
expect(work_item.description).to eq('changed')
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
context 'with mentions', :mailer, :sidekiq_might_not_need_inline do
shared_examples 'creates the todo and sends email' do |attribute|
it 'creates a todo and sends email' do
expect { perform_enqueued_jobs { update_work_item } }.to change(Todo, :count).by(1)
expect(work_item.reload.attributes[attribute.to_s]).to eq("mention #{guest.to_reference}")
should_email(guest)
end
end
context 'when description contains a user mention' do
let(:widget_params) { { description_widget: { description: "mention #{guest.to_reference}" } } }
it_behaves_like 'creates the todo and sends email', :description
end
context 'when title contains a user mention' do
let(:opts) { { title: "mention #{guest.to_reference}" } }
it_behaves_like 'creates the todo and sends email', :title
end
end
context 'when work item validation fails' do
let(:opts) { { title: '' } }
it 'returns validation errors' do
expect(update_work_item[:message]).to contain_exactly("Title can't be blank")
end
it 'does not execute after-update widgets', :aggregate_failures do
expect(service).to receive(:update).and_call_original
expect(service).not_to receive(:execute_widgets).with(callback: :update, widget_params: widget_params)
expect { update_work_item }.not_to change(work_item, :description)
end
end
end
context 'for start and due date widget' do
let(:updated_date) { 1.week.from_now.to_date }
context 'when due_date is updated' do
let(:widget_params) { { start_and_due_date_widget: { due_date: updated_date } } }
it_behaves_like 'update service that triggers graphql dates updated subscription'
end
context 'when start_date is updated' do
let(:widget_params) { { start_and_due_date_widget: { start_date: updated_date } } }
it_behaves_like 'update service that triggers graphql dates updated subscription'
end
context 'when no date param is updated' do
let(:opts) { { title: 'should not trigger' } }
it 'does not trigger date updated subscription' do
expect(GraphqlTriggers).not_to receive(:issuable_dates_updated)
update_work_item
end
end
end
context 'for the hierarchy widget' do
let(:opts) { { title: 'changed' } }
let_it_be(:child_work_item) { create(:work_item, :task, project: project) }
let(:widget_params) { { hierarchy_widget: { children: [child_work_item] } } }
it 'updates the children of the work item' do
expect do
update_work_item
work_item.reload
end.to change(WorkItems::ParentLink, :count).by(1)
expect(work_item.work_item_children).to include(child_work_item)
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
context 'when child type is invalid' do
let_it_be(:child_work_item) { create(:work_item, project: project) }
it 'returns error status' do
expect(subject[:status]).to be(:error)
expect(subject[:message])
.to match("#{child_work_item.to_reference} cannot be added: is not allowed to add this type of parent")
end
it 'does not update work item attributes' do
expect do
update_work_item
work_item.reload
end.to not_change(WorkItems::ParentLink, :count).and(not_change(work_item, :title))
end
end
context 'when work item validation fails' do
let(:opts) { { title: '' } }
it 'returns validation errors' do
expect(update_work_item[:message]).to contain_exactly("Title can't be blank")
end
it 'does not execute after-update widgets', :aggregate_failures do
expect(service).to receive(:update).and_call_original
expect(service).not_to receive(:execute_widgets).with(callback: :before_update_in_transaction, widget_params: widget_params)
expect(work_item.work_item_children).not_to include(child_work_item)
update_work_item
end
end
end
context 'for milestone widget' do
let_it_be(:milestone) { create(:milestone, project: project) }
let(:widget_params) { { milestone_widget: { milestone_id: milestone.id } } }
context 'when milestone is updated' do
it "triggers 'issuableMilestoneUpdated'" do
expect(work_item.milestone).to eq(nil)
expect(GraphqlTriggers).to receive(:issuable_milestone_updated).with(work_item).and_call_original
update_work_item
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
end
context 'when milestone remains unchanged' do
before do
update_work_item
end
it "does not trigger 'issuableMilestoneUpdated'" do
expect(work_item.milestone).to eq(milestone)
expect(GraphqlTriggers).not_to receive(:issuable_milestone_updated)
update_work_item
end
end
end
context 'for current user todos widget' do
let_it_be(:user_todo) { create(:todo, target: work_item, user: developer, project: project, state: :pending) }
let_it_be(:other_todo) { create(:todo, target: work_item, user: create(:user), project: project, state: :pending) }
context 'when action is mark_as_done' do
let(:widget_params) { { current_user_todos_widget: { action: 'mark_as_done' } } }
it 'marks current user todo as done' do
expect do
update_work_item
user_todo.reload
other_todo.reload
end.to change(user_todo, :state).from('pending').to('done').and not_change { other_todo.state }
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
end
context 'when action is add' do
let(:widget_params) { { current_user_todos_widget: { action: 'add' } } }
it 'adds a ToDo for the work item' do
expect do
update_work_item
work_item.reload
end.to change(Todo, :count).by(1)
end
end
end
end
describe 'label updates' do
let_it_be(:label1) { create(:label, project: project) }
let_it_be(:label2) { create(:label, project: project) }
context 'when labels are changed' do
let(:label) { create(:label, project: project) }
let(:opts) { { label_ids: [label1.id] } }
it 'tracks users updating work item labels' do
expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter).to receive(:track_work_item_labels_changed_action).with(author: current_user)
update_work_item
end
it_behaves_like 'update service that triggers GraphQL work_item_updated subscription' do
subject(:execute_service) { update_work_item }
end
it_behaves_like 'broadcasting issuable labels updates' do
let(:issuable) { work_item }
let(:label_a) { label1 }
let(:label_b) { label2 }
def update_issuable(update_params)
described_class.new(
container: project,
current_user: current_user,
params: update_params,
widget_params: widget_params
).execute(work_item)
end
end
end
context 'when labels are not changed' do
shared_examples 'work item update that does not track label updates' do
it 'does not track users updating work item labels' do
expect(Gitlab::UsageDataCounters::WorkItemActivityUniqueCounter).not_to receive(:track_work_item_labels_changed_action)
update_work_item
end
end
context 'when labels param is not provided' do
let(:opts) { { title: 'not updating labels' } }
it_behaves_like 'work item update that does not track label updates'
end
context 'when labels param is provided but labels remain unchanged' do
let(:opts) { { label_ids: [] } }
it_behaves_like 'work item update that does not track label updates'
end
context 'when labels param is provided invalid values' do
let(:opts) { { label_ids: [non_existing_record_id] } }
it_behaves_like 'work item update that does not track label updates'
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class CreateService < Issues::CreateService
extend ::Gitlab::Utils::Override
include WidgetableService
def initialize(container:, perform_spam_check: true, current_user: nil, params: {}, widget_params: {})
super(
container: container,
current_user: current_user,
params: params,
perform_spam_check: perform_spam_check,
build_service: ::WorkItems::BuildService.new(container: container, current_user: current_user, params: params)
)
@widget_params = widget_params
end
def execute
result = super
return result if result.error?
work_item = result[:issue]
if work_item.valid?
success(payload(work_item))
else
error(work_item.errors.full_messages, :unprocessable_entity, pass_back: payload(work_item))
end
rescue ::WorkItems::Widgets::BaseService::WidgetError => e
error(e.message, :unprocessable_entity)
end
def before_create(work_item)
execute_widgets(
work_item: work_item,
callback: :before_create_callback,
widget_params: @widget_params
)
super
end
def transaction_create(work_item)
super.tap do |save_result|
if save_result
execute_widgets(
work_item: work_item,
callback: :after_create_in_transaction,
widget_params: @widget_params
)
end
end
end
private
override :handle_quick_actions
def handle_quick_actions(work_item)
# Do not handle quick actions unless the work item is the default Issue.
# The available quick actions for a work item depend on its type and widgets.
return if work_item.work_item_type != WorkItems::Type.default_by_type(:issue)
super
end
def authorization_action
:create_work_item
end
def payload(work_item)
{ work_item: work_item }
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::CreateService, feature_category: :team_planning do
include AfterNextHelpers
RSpec.shared_examples 'creates work item in container' do |container_type|
let_it_be_with_reload(:project) { create(:project) }
let_it_be_with_reload(:group) { create(:group) }
let_it_be(:container) do
case container_type
when :project then project
when :project_namespace then project.project_namespace
when :group then group
end
end
let_it_be(:container_args) do
case container_type
when :project, :project_namespace then { project: project }
when :group then { namespace: group }
end
end
let_it_be(:parent) { create(:work_item, **container_args) }
let_it_be(:guest) { create(:user) }
let_it_be(:reporter) { create(:user) }
let_it_be(:user_with_no_access) { create(:user) }
let(:widget_params) { {} }
let(:perform_spam_check) { false }
let(:current_user) { guest }
let(:opts) do
{
title: 'Awesome work_item',
description: 'please fix'
}
end
before_all do
memberships_container = container.is_a?(Namespaces::ProjectNamespace) ? container.reload.project : container
memberships_container.add_guest(guest)
memberships_container.add_reporter(reporter)
end
describe '#execute' do
shared_examples 'fails creating work item and returns errors' do
it 'does not create new work item if parent can not be set' do
expect { service_result }.not_to change(WorkItem, :count)
expect(service_result[:status]).to be(:error)
expect(service_result[:message]).to match(error_message)
end
end
let(:service) do
described_class.new(
container: container,
current_user: current_user,
params: opts,
perform_spam_check: perform_spam_check,
widget_params: widget_params
)
end
subject(:service_result) { service.execute }
context 'when user is not allowed to create a work item in the container' do
let(:current_user) { user_with_no_access }
it { is_expected.to be_error }
it 'returns an access error' do
expect(service_result.errors).to contain_exactly('Operation not allowed')
end
end
context 'when applying quick actions' do
let(:work_item) { service_result[:work_item] }
let(:opts) do
{
title: 'My work item',
work_item_type: work_item_type,
description: '/shrug'
}
end
context 'when work item type is not the default Issue' do
let(:work_item_type) { create(:work_item_type, :task, namespace: group) }
it 'saves the work item without applying the quick action' do
expect(service_result).to be_success
expect(work_item).to be_persisted
expect(work_item.description).to eq('/shrug')
end
end
context 'when work item type is the default Issue' do
let(:work_item_type) { WorkItems::Type.default_by_type(:issue) }
it 'saves the work item and applies the quick action' do
expect(service_result).to be_success
expect(work_item).to be_persisted
expect(work_item.description).to eq(' ¯\_(ツ)_/¯')
end
end
end
context 'when params are valid' do
it 'created instance is a WorkItem' do
expect(Issuable::CommonSystemNotesService).to receive_message_chain(:new, :execute)
work_item = service_result[:work_item]
expect(work_item).to be_persisted
expect(work_item).to be_a(::WorkItem)
expect(work_item.title).to eq('Awesome work_item')
expect(work_item.description).to eq('please fix')
expect(work_item.work_item_type.base_type).to eq('issue')
end
it 'calls NewIssueWorker with correct arguments' do
expect(NewIssueWorker).to receive(:perform_async).with(Integer, current_user.id, 'WorkItem')
service_result
end
end
context 'when params are invalid' do
let(:opts) { { title: '' } }
it { is_expected.to be_error }
it 'returns validation errors' do
expect(service_result.errors).to contain_exactly("Title can't be blank")
end
it 'does not execute after-create transaction widgets' do
expect(service).to receive(:create).and_call_original
expect(service).not_to receive(:execute_widgets)
.with(callback: :after_create_in_transaction, widget_params: widget_params)
service_result
end
end
context 'checking spam' do
let(:perform_spam_check) { true }
it 'checks for spam' do
expect_next_instance_of(WorkItem) do |instance|
expect(instance).to receive(:check_for_spam).with(user: current_user, action: :create)
end
service_result
end
context 'when `perform_spam_check` is set to `false`' do
let(:perform_spam_check) { false }
it 'does not check for spam' do
expect_next_instance_of(WorkItem) do |instance|
expect(instance).not_to receive(:check_for_spam)
end
service_result
end
end
end
it_behaves_like 'work item widgetable service' do
let(:widget_params) do
{
hierarchy_widget: { parent: parent }
}
end
let(:service) do
described_class.new(
container: container,
current_user: current_user,
params: opts,
widget_params: widget_params
)
end
let(:service_execute) { service.execute }
let(:supported_widgets) do
[
{
klass: WorkItems::Widgets::HierarchyService::CreateService,
callback: :after_create_in_transaction,
params: { parent: parent }
}
]
end
end
describe 'hierarchy widget' do
let(:widget_params) { { hierarchy_widget: { parent: parent } } }
context 'when user can admin parent link' do
let(:current_user) { reporter }
context 'when parent is valid work item' do
let(:opts) do
{
title: 'Awesome work_item',
description: 'please fix',
work_item_type: WorkItems::Type.default_by_type(:task)
}
end
it 'creates new work item and sets parent reference' do
expect { service_result }.to change(WorkItem, :count).by(1).and(
change(WorkItems::ParentLink, :count).by(1)
)
expect(service_result[:status]).to be(:success)
end
end
context 'when parent type is invalid' do
let_it_be(:parent) { create(:work_item, :task, **container_args) }
it_behaves_like 'fails creating work item and returns errors' do
let(:error_message) { 'is not allowed to add this type of parent' }
end
end
end
context 'when user cannot admin parent link' do
let(:current_user) { guest }
let(:opts) do
{
title: 'Awesome work_item',
description: 'please fix',
work_item_type: WorkItems::Type.default_by_type(:task)
}
end
it_behaves_like 'fails creating work item and returns errors' do
let(:error_message) { 'No matching work item found. Make sure that you are adding a valid work item ID.' }
end
end
end
end
end
it_behaves_like 'creates work item in container', :project
it_behaves_like 'creates work item in container', :project_namespace
it_behaves_like 'creates work item in container', :group
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
class DeleteService < Issuable::DestroyService
def execute(work_item)
unless current_user.can?(:delete_work_item, work_item)
return ::ServiceResponse.error(message: 'User not authorized to delete work item')
end
if super
::ServiceResponse.success
else
::ServiceResponse.error(message: work_item.errors.full_messages)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::DeleteService, feature_category: :team_planning do
let_it_be(:project) { create(:project, :repository) }
let_it_be(:guest) { create(:user) }
let_it_be(:work_item, refind: true) { create(:work_item, project: project, author: guest) }
let(:user) { guest }
before_all do
project.add_guest(guest)
# note necessary to test note removal as part of work item deletion
create(:note, project: project, noteable: work_item)
end
describe '#execute' do
subject(:result) { described_class.new(container: project, current_user: user).execute(work_item) }
context 'when user can delete the work item' do
it { is_expected.to be_success }
# currently we don't expect destroy to fail. Mocking here for coverage and keeping
# the service's return type consistent
context 'when there are errors preventing to delete the work item' do
before do
allow(work_item).to receive(:destroy).and_return(false)
work_item.errors.add(:title)
end
it { is_expected.to be_error }
it 'returns error messages' do
expect(result.errors).to contain_exactly('Title is invalid')
end
end
end
context 'when user cannot delete the work item' do
let(:user) { create(:user) }
it { is_expected.to be_error }
it 'returns error messages' do
expect(result.errors).to contain_exactly('User not authorized to delete work item')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Callbacks
class AwardEmoji < Base
def before_update
return unless params.present? && params.key?(:name) && params.key?(:action)
return unless has_permission?(:award_emoji)
execute_emoji_service(params[:action], params[:name])
end
private
def execute_emoji_service(action, name)
class_name = {
add: ::AwardEmojis::AddService,
remove: ::AwardEmojis::DestroyService,
toggle: ::AwardEmojis::ToggleService
}
raise_error(invalid_action_error(action)) unless class_name.key?(action)
result = class_name[action].new(work_item, name, current_user).execute
raise_error(result[:message]) if result[:status] == :error
end
def invalid_action_error(key)
format(_("%{key} is not a valid action."), key: key)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Callbacks::AwardEmoji, feature_category: :team_planning do
let_it_be(:reporter) { create(:user) }
let_it_be(:unauthorized_user) { create(:user) }
let_it_be(:project) { create(:project, :private) }
let_it_be(:work_item) { create(:work_item, project: project) }
let(:current_user) { reporter }
before_all do
project.add_reporter(reporter)
end
describe '#before_update' do
subject do
described_class.new(issuable: work_item, current_user: current_user, params: params)
.before_update
end
shared_examples 'raises a WidgetError' do
it { expect { subject }.to raise_error(::WorkItems::Widgets::BaseService::WidgetError, message) }
end
context 'when awarding an emoji' do
let(:params) { { action: :add, name: 'star' } }
context 'when user has no access' do
let(:current_user) { unauthorized_user }
it 'does not award the emoji' do
expect { subject }.not_to change { AwardEmoji.count }
end
end
context 'when user has access' do
it 'awards the emoji to the work item' do
expect { subject }.to change { AwardEmoji.count }.by(1)
emoji = AwardEmoji.last
expect(emoji.name).to eq('star')
expect(emoji.awardable_id).to eq(work_item.id)
expect(emoji.user).to eq(current_user)
end
context 'when the name is incorrect' do
let(:params) { { action: :add, name: 'foo' } }
it_behaves_like 'raises a WidgetError' do
let(:message) { 'Name is not a valid emoji name' }
end
end
context 'when the action is incorrect' do
let(:params) { { action: :foo, name: 'star' } }
it_behaves_like 'raises a WidgetError' do
let(:message) { 'foo is not a valid action.' }
end
end
end
end
context 'when removing emoji' do
let(:params) { { action: :remove, name: 'thumbsup' } }
context 'when user has no access' do
let(:current_user) { unauthorized_user }
it 'does not remove the emoji' do
expect { subject }.not_to change { AwardEmoji.count }
end
end
context 'when user has access' do
it 'removes existing emoji' do
create(:award_emoji, :upvote, awardable: work_item, user: current_user)
expect { subject }.to change { AwardEmoji.count }.by(-1)
end
context 'when work item does not have the emoji' do
let(:params) { { action: :remove, name: 'star' } }
it_behaves_like 'raises a WidgetError' do
let(:message) { 'User has not awarded emoji of type star on the awardable' }
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module RelatedWorkItemLinks
class DestroyService < BaseService
def initialize(work_item, user, params)
@work_item = work_item
@current_user = user
@params = params.dup
@failed_ids = []
@removed_ids = []
end
def execute
return error(_('No work item found.'), 403) unless can?(current_user, :admin_work_item_link, work_item)
return error(_('No work item IDs provided.'), 409) if params[:item_ids].empty?
destroy_links_for(params[:item_ids])
if removed_ids.any?
success(message: response_message, items_removed: removed_ids, items_with_errors: failed_ids.flatten)
else
error(error_message)
end
end
private
attr_reader :work_item, :current_user, :failed_ids, :removed_ids
def destroy_links_for(item_ids)
destroy_links(source: work_item, target: item_ids, direction: :target)
destroy_links(source: item_ids, target: work_item, direction: :source)
end
def destroy_links(source:, target:, direction:)
WorkItems::RelatedWorkItemLink.for_source_and_target(source, target).each do |link|
linked_item = link.try(direction)
if can?(current_user, :admin_work_item_link, linked_item)
link.destroy!
removed_ids << linked_item.id
create_notes(link)
else
failed_ids << linked_item.id
end
end
end
def create_notes(link)
SystemNoteService.unrelate_issuable(link.source, link.target, current_user)
SystemNoteService.unrelate_issuable(link.target, link.source, current_user)
end
def error_message
not_linked = params[:item_ids] - (removed_ids + failed_ids)
error_messages = []
if failed_ids.any?
error_messages << format(
_('%{item_ids} could not be removed due to insufficient permissions'), item_ids: failed_ids.to_sentence
)
end
if not_linked.any?
error_messages << format(
_('%{item_ids} could not be removed due to not being linked'), item_ids: not_linked.to_sentence
)
end
return '' unless error_messages.any?
format(_('IDs with errors: %{error_messages}.'), error_messages: error_messages.join(', '))
end
def response_message
success_message = format(_('Successfully unlinked IDs: %{item_ids}.'), item_ids: removed_ids.to_sentence)
return success_message unless error_message.present?
"#{success_message} #{error_message}"
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::RelatedWorkItemLinks::DestroyService, feature_category: :portfolio_management do
describe '#execute' do
let_it_be(:project) { create(:project_empty_repo, :private) }
let_it_be(:other_project) { create(:project_empty_repo, :private) }
let_it_be(:user) { create(:user) }
let_it_be(:source) { create(:work_item, project: project) }
let_it_be(:linked_item1) { create(:work_item, project: project) }
let_it_be(:linked_item2) { create(:work_item, project: project) }
let_it_be(:no_access_item) { create(:work_item, project: other_project) }
let_it_be(:not_linked_item) { create(:work_item, project: project) }
let_it_be(:link1) { create(:work_item_link, source: source, target: linked_item1) }
let_it_be(:link2) { create(:work_item_link, source: source, target: linked_item2) }
let_it_be(:link3) { create(:work_item_link, source: source, target: no_access_item) }
let(:ids_to_remove) { [linked_item1.id, linked_item2.id, no_access_item.id, not_linked_item.id] }
subject(:destroy_links) { described_class.new(source, user, { item_ids: ids_to_remove }).execute }
context 'when user can `admin_work_item_link` for the work item' do
before_all do
project.add_guest(user)
end
it 'removes existing linked items with access' do
expect { destroy_links }.to change { WorkItems::RelatedWorkItemLink.count }.by(-2)
end
it 'creates notes for the source and target of each removed link' do
[linked_item1, linked_item2].each do |item|
expect(SystemNoteService).to receive(:unrelate_issuable).with(source, item, user)
expect(SystemNoteService).to receive(:unrelate_issuable).with(item, source, user)
end
destroy_links
end
it 'returns correct response message' do
message = "Successfully unlinked IDs: #{linked_item1.id} and #{linked_item2.id}. IDs with errors: " \
"#{no_access_item.id} could not be removed due to insufficient permissions, " \
"#{not_linked_item.id} could not be removed due to not being linked."
is_expected.to eq(
status: :success,
message: message,
items_removed: [linked_item1.id, linked_item2.id],
items_with_errors: [no_access_item.id]
)
end
context 'when all items fail' do
let(:ids_to_remove) { [no_access_item.id] }
let(:params) { { item_ids: [no_access_item.id] } }
let(:error_msg) { "IDs with errors: #{ids_to_remove[0]} could not be removed due to insufficient permissions." }
it 'returns an error response' do
expect { destroy_links }.not_to change { WorkItems::RelatedWorkItemLink.count }
is_expected.to eq(status: :error, message: error_msg)
end
end
context 'when item_ids is empty' do
let(:ids_to_remove) { [] }
it 'returns error response' do
is_expected.to eq(message: 'No work item IDs provided.', status: :error, http_status: 409)
end
end
end
context 'when user cannot `admin_work_item_link` for the work item' do
it 'returns error response' do
is_expected.to eq(message: 'No work item found.', status: :error, http_status: 403)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module RelatedWorkItemLinks
class CreateService < IssuableLinks::CreateService
extend ::Gitlab::Utils::Override
def execute
return error(_('No matching work item found.'), 404) unless can?(current_user, :admin_work_item_link, issuable)
response = super
create_notes_async if new_links.any?
if response[:status] == :success
response[:message] = format(
_('Successfully linked ID(s): %{item_ids}.'),
item_ids: linked_ids(response[:created_references]).to_sentence
)
end
response
end
def linkable_issuables(work_items)
@linkable_issuables ||= work_items.select { |work_item| can_link_item?(work_item) }
end
def previous_related_issuables
@related_issues ||= issuable.linked_work_items(authorize: false).to_a
end
private
def create_notes(_issuable_link)
# no-op notes are created asynchronously
end
def link_class
WorkItems::RelatedWorkItemLink
end
def can_link_item?(work_item)
return true if can?(current_user, :admin_work_item_link, work_item)
@errors << format(
_("Item with ID: %{id} cannot be added. You don't have permission to perform this action."),
id: work_item.id
)
false
end
def linked_ids(created_links)
created_links.collect(&:target_id)
end
def create_notes_async
link_ids = new_links.collect(&:id)
worker_params = {
issuable_class: issuable.class.name,
issuable_id: issuable.id,
link_ids: link_ids,
link_type: params[:link_type] || 'relates_to',
user_id: current_user.id
}
Issuable::RelatedLinksCreateWorker.perform_async(worker_params)
end
override :issuables_already_assigned_message
def issuables_already_assigned_message
_('Items are already linked')
end
override :issuables_not_found_message
def issuables_not_found_message
_('No matching work item found. Make sure you are adding a valid ID and you have access to the item.')
end
end
end
end
WorkItems::RelatedWorkItemLinks::CreateService.prepend_mod_with('WorkItems::RelatedWorkItemLinks::CreateService')
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::RelatedWorkItemLinks::CreateService, feature_category: :portfolio_management do
describe '#execute' do
let_it_be(:user) { create(:user) }
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, group: group) }
let_it_be(:issuable) { create(:work_item, project: project) }
let_it_be(:issuable2) { create(:work_item, project: project) }
let_it_be(:restricted_issuable) { create(:work_item) }
let_it_be(:another_project) { create(:project, group: group) }
let_it_be(:issuable3) { create(:work_item, project: another_project) }
let_it_be(:issuable_a) { create(:work_item, project: project) }
let_it_be(:issuable_b) { create(:work_item, project: project) }
let_it_be(:issuable_link) { create(:work_item_link, source: issuable, target: issuable_b) }
let(:issuable_parent) { issuable.project }
let(:issuable_type) { 'work item' }
let(:issuable_link_class) { WorkItems::RelatedWorkItemLink }
let(:params) { {} }
before_all do
project.add_guest(user)
another_project.add_guest(user)
end
it_behaves_like 'issuable link creation', use_references: false do
let(:response_keys) { [:status, :created_references, :message] }
let(:async_notes) { true }
let(:already_assigned_error_msg) { "Items are already linked" }
let(:no_found_error_msg) do
'No matching work item found. Make sure you are adding a valid ID and you have access to the item.'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module ParentLinks
class BaseService < IssuableLinks::CreateService
extend ::Gitlab::Utils::Override
private
def set_parent(issuable, work_item)
link = WorkItems::ParentLink.for_work_item(work_item)
link.work_item_parent = issuable
link
end
def create_notes(work_item)
SystemNoteService.relate_work_item(issuable, work_item, current_user)
end
def linkable_issuables(work_items)
@linkable_issuables ||= if can_admin_link?(issuable)
work_items.select { |work_item| linkable?(work_item) }
else
[]
end
end
def linkable?(work_item)
can_admin_link?(work_item) && previous_related_issuables.exclude?(work_item)
end
def can_admin_link?(work_item)
can?(current_user, :admin_parent_link, work_item)
end
override :previous_related_issuables
def previous_related_issuables
@previous_related_issuables ||= issuable.work_item_children.to_a
end
override :target_issuable_type
def target_issuable_type
'work item'
end
override :issuables_not_found_message
def issuables_not_found_message
format(_('No matching %{issuable} found. Make sure that you are adding a valid %{issuable} ID.'),
issuable: target_issuable_type)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
module WorkItems
class ParentLinksService < WorkItems::ParentLinks::BaseService; end
end
RSpec.describe WorkItems::ParentLinks::BaseService, feature_category: :portfolio_management do
let_it_be(:user) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:work_item) { create(:work_item, :objective, project: project) }
let_it_be(:target_work_item) { create(:work_item, :objective, project: project) }
let(:params) { { target_issuable: target_work_item } }
let(:described_class_descendant) { WorkItems::ParentLinksService }
before do
project.add_reporter(user)
end
describe '#execute' do
subject { described_class_descendant.new(work_item, user, params).execute }
context 'when user has sufficient permissions' do
it 'raises NotImplementedError' do
expect { subject }.to raise_error(NotImplementedError)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module ParentLinks
class ReorderService < WorkItems::ParentLinks::BaseService
private
override :relate_issuables
def relate_issuables(work_item)
notes_are_expected = work_item.work_item_parent != issuable
link = set_parent(issuable, work_item)
reorder(link, params[:adjacent_work_item], params[:relative_position])
create_notes(work_item) if link.save && notes_are_expected
link
end
def reorder(link, adjacent_work_item, relative_position)
WorkItems::ParentLink.move_nulls_to_end(RelativePositioning.mover.context(link).relative_siblings)
link.move_before(adjacent_work_item.parent_link) if relative_position == 'BEFORE'
link.move_after(adjacent_work_item.parent_link) if relative_position == 'AFTER'
end
override :render_conflict_error?
def render_conflict_error?
return false if params[:adjacent_work_item] && params[:relative_position]
super
end
override :linkable?
def linkable?(work_item)
can_admin_link?(work_item)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::ParentLinks::ReorderService, feature_category: :portfolio_management do
describe '#execute' do
let_it_be(:reporter) { create(:user) }
let_it_be(:guest) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be_with_reload(:parent) { create(:work_item, :objective, project: project) }
let_it_be_with_reload(:work_item) { create(:work_item, :objective, project: project) }
let_it_be_with_reload(:top_adjacent) { create(:work_item, :objective, project: project) }
let_it_be_with_reload(:last_adjacent) { create(:work_item, :objective, project: project) }
let(:parent_link_class) { WorkItems::ParentLink }
let(:user) { reporter }
let(:params) { { target_issuable: work_item } }
let(:relative_range) { [top_adjacent, last_adjacent].map(&:parent_link).map(&:relative_position) }
subject { described_class.new(parent, user, params).execute }
before do
project.add_reporter(reporter)
project.add_guest(guest)
create(:parent_link, work_item: top_adjacent, work_item_parent: parent)
create(:parent_link, work_item: last_adjacent, work_item_parent: parent)
end
shared_examples 'raises a service error' do |message, status = 409|
it { is_expected.to eq(service_error(message, http_status: status)) }
end
shared_examples 'returns not found error' do
it 'returns error' do
error = "No matching work item found. Make sure that you are adding a valid work item ID."
is_expected.to eq(service_error(error))
end
it 'creates no relationship' do
expect { subject }.not_to change { parent_link_class.count }
end
end
shared_examples 'returns conflict error' do
it_behaves_like 'raises a service error', 'Work item(s) already assigned'
it 'creates no relationship' do
expect { subject }.to not_change { parent_link_class.count }
end
end
shared_examples 'processes ordered hierarchy' do
it 'returns success status and processed links', :aggregate_failures do
expect(subject.keys).to match_array([:status, :created_references])
expect(subject[:status]).to eq(:success)
expect(subject[:created_references].map(&:work_item_id)).to match_array([work_item.id])
end
it 'orders hierarchy' do
subject
expect(last_adjacent.parent_link.relative_position).to be_between(*relative_range)
end
end
context 'when user has insufficient permissions' do
let(:user) { guest }
it_behaves_like 'returns not found error'
context 'when user is a guest assigned to the work item' do
before do
work_item.assignees = [guest]
end
it_behaves_like 'returns not found error'
end
end
context 'when child and parent are already linked' do
before do
create(:parent_link, work_item: work_item, work_item_parent: parent)
end
it_behaves_like 'returns conflict error'
context 'when adjacents are already in place and the user has sufficient permissions' do
let(:base_param) { { target_issuable: work_item } }
shared_examples 'updates hierarchy order without notes' do
it_behaves_like 'processes ordered hierarchy'
it 'keeps relationships', :aggregate_failures do
expect { subject }.to not_change { parent_link_class.count }
expect(parent_link_class.where(work_item: work_item).last.work_item_parent).to eq(parent)
end
it 'does not create notes', :aggregate_failures do
expect { subject }.to not_change { work_item.notes.count }.and(not_change { work_item.notes.count })
end
end
context 'when moving before adjacent work item' do
let(:params) { base_param.merge({ adjacent_work_item: last_adjacent, relative_position: 'BEFORE' }) }
it_behaves_like 'updates hierarchy order without notes'
end
context 'when moving after adjacent work item' do
let(:params) { base_param.merge({ adjacent_work_item: top_adjacent, relative_position: 'AFTER' }) }
it_behaves_like 'updates hierarchy order without notes'
end
end
end
context 'when new parent is assigned' do
shared_examples 'updates hierarchy order and creates notes' do
it_behaves_like 'processes ordered hierarchy'
it 'creates notes', :aggregate_failures do
subject
expect(parent.notes.last.note).to eq("added #{work_item.to_reference} as child objective")
expect(work_item.notes.last.note).to eq("added #{parent.to_reference} as parent objective")
end
end
context 'when adjacents are already in place and the user has sufficient permissions' do
let(:base_param) { { target_issuable: work_item } }
context 'when moving before adjacent work item' do
let(:params) { base_param.merge({ adjacent_work_item: last_adjacent, relative_position: 'BEFORE' }) }
it_behaves_like 'updates hierarchy order and creates notes'
end
context 'when moving after adjacent work item' do
let(:params) { base_param.merge({ adjacent_work_item: top_adjacent, relative_position: 'AFTER' }) }
it_behaves_like 'updates hierarchy order and creates notes'
end
context 'when previous parent was in place' do
before do
create(:parent_link, work_item: work_item,
work_item_parent: create(:work_item, :objective, project: project))
end
context 'when moving before adjacent work item' do
let(:params) { base_param.merge({ adjacent_work_item: last_adjacent, relative_position: 'BEFORE' }) }
it_behaves_like 'updates hierarchy order and creates notes'
end
context 'when moving after adjacent work item' do
let(:params) { base_param.merge({ adjacent_work_item: top_adjacent, relative_position: 'AFTER' }) }
it_behaves_like 'updates hierarchy order and creates notes'
end
end
end
end
end
def service_error(message, http_status: 404)
{
message: message,
status: :error,
http_status: http_status
}
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module ParentLinks
class DestroyService < IssuableLinks::DestroyService
attr_reader :link, :current_user, :parent, :child
def initialize(link, user)
@link = link
@current_user = user
@parent = link.work_item_parent
@child = link.work_item
end
private
def create_notes
unrelate_note = SystemNoteService.unrelate_work_item(parent, child, current_user)
ResourceLinkEvent.create(
user: @current_user,
work_item: @link.work_item_parent,
child_work_item: @link.work_item,
action: ResourceLinkEvent.actions[:remove],
system_note_metadata_id: unrelate_note&.system_note_metadata&.id
)
end
def not_found_message
_('No Work Item Link found')
end
def permission_to_remove_relation?
can?(current_user, :admin_parent_link, child) && can?(current_user, :admin_parent_link, parent)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::ParentLinks::DestroyService, feature_category: :team_planning do
describe '#execute' do
let_it_be(:reporter) { create(:user) }
let_it_be(:guest) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:work_item) { create(:work_item, project: project) }
let_it_be(:task) { create(:work_item, :task, project: project) }
let_it_be(:parent_link) { create(:parent_link, work_item: task, work_item_parent: work_item) }
let(:parent_link_class) { WorkItems::ParentLink }
subject { described_class.new(parent_link, user).execute }
before do
project.add_reporter(reporter)
project.add_guest(guest)
end
context 'when user has permissions to update work items' do
let(:user) { reporter }
it 'removes relation and creates notes', :aggregate_failures do
expect { subject }
.to change(parent_link_class, :count).by(-1)
.and change(WorkItems::ResourceLinkEvent, :count).by(1)
expect(work_item.notes.last.note).to eq("removed child task #{task.to_reference}")
expect(task.notes.last.note).to eq("removed parent issue #{work_item.to_reference}")
expect(WorkItems::ResourceLinkEvent.last).to have_attributes(
user_id: user.id,
issue_id: work_item.id,
child_work_item_id: task.id,
action: "remove",
system_note_metadata_id: task.notes.last.system_note_metadata.id
)
end
it 'returns success message' do
is_expected.to eq(message: 'Relation was removed', status: :success)
end
context 'when note creation fails for some reason' do
[Note.new, nil].each do |unrelate_child_note|
it 'still records the link event', :aggregate_failures do
allow(SystemNoteService).to receive(:unrelate_work_item).and_return(unrelate_child_note)
expect { subject }
.to change(WorkItems::ResourceLinkEvent, :count).by(1)
.and not_change(Note, :count)
expect(WorkItems::ResourceLinkEvent.last).to have_attributes(
user_id: user.id,
issue_id: work_item.id,
child_work_item_id: task.id,
action: "remove",
system_note_metadata_id: nil
)
end
end
end
end
context 'when user has insufficient permissions' do
let(:user) { guest }
it 'does not remove relation', :aggregate_failures do
expect { subject }
.to not_change(parent_link_class, :count).from(1)
.and not_change(WorkItems::ResourceLinkEvent, :count)
expect(SystemNoteService).not_to receive(:unrelate_work_item)
end
it 'returns error message' do
is_expected.to eq(message: 'No Work Item Link found', status: :error, http_status: 404)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module ParentLinks
class CreateService < WorkItems::ParentLinks::BaseService
private
override :relate_issuables
def relate_issuables(work_item)
link = set_parent(issuable, work_item)
link.move_to_end
if link.changed? && link.save
relate_child_note = create_notes(work_item)
ResourceLinkEvent.create(
user: current_user,
work_item: link.work_item_parent,
child_work_item: link.work_item,
action: ResourceLinkEvent.actions[:add],
system_note_metadata_id: relate_child_note&.system_note_metadata&.id
)
end
link
end
override :extract_references
def extract_references
params[:issuable_references]
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::ParentLinks::CreateService, feature_category: :portfolio_management do
describe '#execute' do
let_it_be(:user) { create(:user) }
let_it_be(:guest) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:work_item) { create(:work_item, project: project) }
let_it_be(:task) { create(:work_item, :task, project: project) }
let_it_be_with_reload(:task1) { create(:work_item, :task, project: project) }
let_it_be_with_reload(:task2) { create(:work_item, :task, project: project) }
let_it_be(:guest_task) { create(:work_item, :task) }
let_it_be(:invalid_task) { build_stubbed(:work_item, :task, id: non_existing_record_id) }
let_it_be(:another_project) { (create :project) }
let_it_be(:other_project_task) { create(:work_item, :task, iid: 100, project: another_project) }
let_it_be(:existing_parent_link) { create(:parent_link, work_item: task, work_item_parent: work_item) }
let(:parent_link_class) { WorkItems::ParentLink }
let(:issuable_type) { :task }
let(:params) { {} }
before do
project.add_reporter(user)
project.add_guest(guest)
guest_task.project.add_guest(user)
another_project.add_reporter(user)
end
shared_examples 'returns not found error' do
it 'returns error' do
error = "No matching work item found. Make sure that you are adding a valid work item ID."
is_expected.to eq(service_error(error))
end
it 'no relationship is created' do
expect { subject }.not_to change(parent_link_class, :count)
end
end
subject { described_class.new(work_item, user, params).execute }
context 'when the reference list is empty' do
let(:params) { { issuable_references: [] } }
it_behaves_like 'returns not found error'
end
context 'when work item not found' do
let(:params) { { issuable_references: [invalid_task] } }
it_behaves_like 'returns not found error'
end
context 'when user has no permission to link work items' do
let(:params) { { issuable_references: [guest_task] } }
it_behaves_like 'returns not found error'
end
context 'child and parent are the same work item' do
let(:params) { { issuable_references: [work_item] } }
it 'no relationship is created' do
expect { subject }.not_to change(parent_link_class, :count)
end
end
context 'when adjacent is already in place' do
using RSpec::Parameterized::TableSyntax
let_it_be_with_reload(:parent_item) { create(:work_item, :objective, project: project) }
let_it_be_with_reload(:current_item) { create(:work_item, :objective, project: project) }
let_it_be_with_reload(:adjacent) do
create(:work_item, :objective, project: project)
end
let_it_be_with_reload(:link_to_adjacent) do
create(:parent_link, work_item_parent: parent_item, work_item: adjacent)
end
subject { described_class.new(parent_item, user, { target_issuable: current_item }).execute }
where(:adjacent_position, :expected_order) do
-100 | lazy { [adjacent, current_item] }
0 | lazy { [adjacent, current_item] }
100 | lazy { [adjacent, current_item] }
end
with_them do
before do
link_to_adjacent.update!(relative_position: adjacent_position)
end
it 'sets relative positions' do
expect { subject }.to change(parent_link_class, :count).by(1)
expect(parent_item.work_item_children_by_relative_position).to eq(expected_order)
end
end
end
context 'when there are tasks to relate' do
let(:params) { { issuable_references: [task1, task2] } }
it 'creates relationships', :aggregate_failures do
expect { subject }.to change(parent_link_class, :count).by(2)
tasks_parent = parent_link_class.where(work_item: [task1, task2]).map(&:work_item_parent).uniq
expect(tasks_parent).to match_array([work_item])
end
it 'returns success status and created links', :aggregate_failures do
expect(subject.keys).to match_array([:status, :created_references])
expect(subject[:status]).to eq(:success)
expect(subject[:created_references].map(&:work_item_id)).to match_array([task1.id, task2.id])
end
it 'creates notes and records the events', :aggregate_failures do
expect { subject }.to change(WorkItems::ResourceLinkEvent, :count).by(2)
work_item_notes = work_item.notes.last(2)
resource_link_events = WorkItems::ResourceLinkEvent.last(2)
expect(work_item_notes.first.note).to eq("added #{task1.to_reference} as child task")
expect(work_item_notes.last.note).to eq("added #{task2.to_reference} as child task")
expect(task1.notes.last.note).to eq("added #{work_item.to_reference} as parent issue")
expect(task2.notes.last.note).to eq("added #{work_item.to_reference} as parent issue")
expect(resource_link_events.first).to have_attributes(
user_id: user.id,
issue_id: work_item.id,
child_work_item_id: task1.id,
action: "add",
system_note_metadata_id: task1.notes.last.system_note_metadata.id
)
expect(resource_link_events.last).to have_attributes(
user_id: user.id,
issue_id: work_item.id,
child_work_item_id: task2.id,
action: "add",
system_note_metadata_id: task2.notes.last.system_note_metadata.id
)
end
context 'when note creation fails for some reason' do
let(:params) { { issuable_references: [task1] } }
[Note.new, nil].each do |relate_child_note|
it 'still records the link event', :aggregate_failures do
allow_next_instance_of(WorkItems::ParentLinks::CreateService) do |instance|
allow(instance).to receive(:create_notes).and_return(relate_child_note)
end
expect { subject }
.to change(WorkItems::ResourceLinkEvent, :count).by(1)
.and not_change(Note, :count)
expect(WorkItems::ResourceLinkEvent.last).to have_attributes(
user_id: user.id,
issue_id: work_item.id,
child_work_item_id: task1.id,
action: "add",
system_note_metadata_id: nil
)
end
end
end
context 'when task is already assigned' do
let(:params) { { issuable_references: [task, task2] } }
it 'creates links only for non related tasks', :aggregate_failures do
expect { subject }
.to change(parent_link_class, :count).by(1)
.and change(WorkItems::ResourceLinkEvent, :count).by(1)
expect(subject[:created_references].map(&:work_item_id)).to match_array([task2.id])
expect(work_item.notes.last.note).to eq("added #{task2.to_reference} as child task")
expect(task2.notes.last.note).to eq("added #{work_item.to_reference} as parent issue")
expect(task.notes).to be_empty
expect(WorkItems::ResourceLinkEvent.last).to have_attributes(
user_id: user.id,
issue_id: work_item.id,
child_work_item_id: task2.id,
action: "add",
system_note_metadata_id: task2.notes.last.system_note_metadata.id
)
end
end
context 'when there are invalid children' do
let_it_be(:issue) { create(:work_item, project: project) }
let(:params) { { issuable_references: [task1, issue, other_project_task] } }
it 'creates links only for valid children' do
expect { subject }.to change { parent_link_class.count }.by(1)
end
it 'returns error status' do
error = "#{issue.to_reference} cannot be added: is not allowed to add this type of parent. " \
"#{other_project_task.to_reference} cannot be added: parent must be in the same project or group as child."
is_expected.to eq(service_error(error, http_status: 422))
end
it 'creates notes for valid links' do
subject
expect(work_item.notes.last.note).to eq("added #{task1.to_reference} as child task")
expect(task1.notes.last.note).to eq("added #{work_item.to_reference} as parent issue")
expect(issue.notes).to be_empty
expect(other_project_task.notes).to be_empty
end
end
context 'when parent type is invalid' do
let(:work_item) { create :work_item, :task, project: project }
let(:params) { { target_issuable: task1 } }
it 'returns error status' do
error = "#{task1.to_reference} cannot be added: is not allowed to add this type of parent"
is_expected.to eq(service_error(error, http_status: 422))
end
end
context 'when max depth is reached' do
let(:params) { { issuable_references: [task2] } }
before do
stub_const("#{parent_link_class}::MAX_CHILDREN", 1)
end
it 'returns error status' do
error = "#{task2.to_reference} cannot be added: parent already has maximum number of children."
is_expected.to eq(service_error(error, http_status: 422))
end
end
context 'when params include invalid ids' do
let(:params) { { issuable_references: [task1, guest_task] } }
it 'creates links only for valid IDs' do
expect { subject }.to change(parent_link_class, :count).by(1)
end
end
context 'when user is a guest' do
let(:user) { guest }
it_behaves_like 'returns not found error'
end
context 'when user is a guest assigned to the work item' do
let(:user) { guest }
before do
work_item.assignees = [guest]
end
it_behaves_like 'returns not found error'
end
end
end
def service_error(message, http_status: 404)
{
message: message,
status: :error,
http_status: http_status
}
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module CurrentUserTodosService
class UpdateService < WorkItems::Widgets::BaseService
def before_update_in_transaction(params:)
return unless params.present? && params.key?(:action)
case params[:action]
when "add"
add_todo
when "mark_as_done"
mark_as_done(params[:todo_id])
end
end
private
def add_todo
return unless has_permission?(:create_todo)
TodoService.new.mark_todo(work_item, current_user)&.first
end
def mark_as_done(todo_id)
todos = TodosFinder.new(current_user, state: :pending, target_id: work_item.id).execute
todos = todo_id ? todos.id_in(todo_id) : todos
return if todos.empty?
TodoService.new.resolve_todos(todos, current_user, resolved_by_action: :api_done)
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::CurrentUserTodosService::UpdateService, feature_category: :team_planning do
let_it_be(:reporter) { create(:user) }
let_it_be(:project) { create(:project, :private) }
let_it_be(:current_user) { reporter }
let_it_be(:work_item) { create(:work_item, project: project) }
let_it_be(:pending_todo1) do
create(:todo, state: :pending, target: work_item, target_type: work_item.class.name, user: current_user)
end
let_it_be(:pending_todo2) do
create(:todo, state: :pending, target: work_item, target_type: work_item.class.name, user: current_user)
end
let_it_be(:done_todo) do
create(:todo, state: :done, target: work_item, target_type: work_item.class.name, user: current_user)
end
let_it_be(:other_work_item_todo) { create(:todo, state: :pending, target: create(:work_item), user: current_user) }
let_it_be(:other_user_todo) do
create(:todo, state: :pending, target: work_item, target_type: work_item.class.name, user: create(:user))
end
let(:widget) { work_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::CurrentUserTodos) } }
before_all do
project.add_reporter(reporter)
end
describe '#before_update_in_transaction' do
subject do
described_class.new(widget: widget, current_user: current_user)
.before_update_in_transaction(params: params)
end
context 'when adding a todo' do
let(:params) { { action: "add" } }
context 'when user has no access' do
let(:current_user) { create(:user) }
it 'does add a todo' do
expect { subject }.not_to change { Todo.count }
end
end
context 'when user has access' do
let(:params) { { action: "add" } }
it 'creates a new todo for the user and the work item' do
expect { subject }.to change { current_user.todos.count }.by(1)
todo = current_user.todos.last
expect(todo.target.id).to eq(work_item.id)
expect(todo).to be_pending
end
end
end
context 'when marking as done' do
let(:params) { { action: "mark_as_done" } }
context 'when user has no access' do
let(:current_user) { create(:user) }
it 'does not change todo status' do
subject
expect(pending_todo1.reload).to be_pending
expect(pending_todo2.reload).to be_pending
expect(other_work_item_todo.reload).to be_pending
expect(other_user_todo.reload).to be_pending
end
end
context 'when resolving all todos of the work item', :aggregate_failures do
it 'resolves todos of the user for the work item' do
subject
expect(pending_todo1.reload).to be_done
expect(pending_todo2.reload).to be_done
expect(other_work_item_todo.reload).to be_pending
expect(other_user_todo.reload).to be_pending
end
end
context 'when resolving a specific todo', :aggregate_failures do
let(:params) { { action: "mark_as_done", todo_id: pending_todo1.id } }
it 'resolves todos of the user for the work item' do
subject
expect(pending_todo1.reload).to be_done
expect(pending_todo2.reload).to be_pending
expect(other_work_item_todo.reload).to be_pending
expect(other_user_todo.reload).to be_pending
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module HierarchyService
class UpdateService < WorkItems::Widgets::HierarchyService::BaseService
INVALID_RELATIVE_POSITION_ERROR = 'Relative position is not valid.'
CHILDREN_REORDERING_ERROR = 'Relative position cannot be combined with childrenIds.'
UNRELATED_ADJACENT_HIERARCHY_ERROR = 'The adjacent work item\'s parent must match the new parent work item.'
INVALID_ADJACENT_PARENT_ERROR = 'The adjacent work item\'s parent must match the current parent work item.'
def before_update_in_transaction(params:)
return unless params.present?
if positioning?(params)
service_response!(handle_positioning(params))
else
service_response!(handle_hierarchy_changes(params))
end
end
private
def handle_positioning(params)
validate_positioning!(params)
arguments = {
target_issuable: work_item,
adjacent_work_item: params.delete(:adjacent_work_item),
relative_position: params.delete(:relative_position)
}
work_item_parent = params.delete(:parent) || work_item.work_item_parent
::WorkItems::ParentLinks::ReorderService.new(work_item_parent, current_user, arguments).execute
end
def positioning?(params)
params[:relative_position].present? || params[:adjacent_work_item].present?
end
def error!(message)
service_response!(error(_(message)))
end
def validate_positioning!(params)
error!(INVALID_RELATIVE_POSITION_ERROR) if incomplete_relative_position?(params)
error!(CHILDREN_REORDERING_ERROR) if positioning_children?(params)
error!(UNRELATED_ADJACENT_HIERARCHY_ERROR) if unrelated_adjacent_hierarchy?(params)
error!(INVALID_ADJACENT_PARENT_ERROR) if invalid_adjacent_parent?(params)
end
def positioning_children?(params)
params.key?(:children)
end
def incomplete_relative_position?(params)
params[:adjacent_work_item].blank? || params[:relative_position].blank?
end
def unrelated_adjacent_hierarchy?(params)
return false if params[:parent].blank?
params[:parent] != params[:adjacent_work_item].work_item_parent
end
def invalid_adjacent_parent?(params)
return false if params[:parent].present?
work_item.work_item_parent != params[:adjacent_work_item].work_item_parent
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::HierarchyService::UpdateService, feature_category: :portfolio_management do
let_it_be(:user) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:work_item) { create(:work_item, project: project) }
let_it_be(:parent_work_item) { create(:work_item, project: project) }
let_it_be(:child_work_item) { create(:work_item, :task, project: project) }
let_it_be(:existing_link) { create(:parent_link, work_item: child_work_item, work_item_parent: work_item) }
let(:widget) { work_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::Hierarchy) } }
let(:not_found_error) { 'No matching work item found. Make sure that you are adding a valid work item ID.' }
shared_examples 'raises a WidgetError' do |message|
it { expect { subject }.to raise_error(described_class::WidgetError, message) }
end
shared_examples 'raises a WidgetError with message' do
let(:message) { not_found_error }
it { expect { subject }.to raise_error(described_class::WidgetError, message) }
end
describe '#update' do
subject { described_class.new(widget: widget, current_user: user).before_update_in_transaction(params: params) }
context 'when parent and children params are present' do
let(:params) { { parent: parent_work_item, children: [child_work_item] } }
it_behaves_like 'raises a WidgetError', 'A Work Item can be a parent or a child, but not both.'
end
context 'when invalid params are present' do
let(:params) { { other_parent: parent_work_item } }
it_behaves_like 'raises a WidgetError', 'One or more arguments are invalid: other_parent.'
end
context 'when relative position params are incomplete' do
context 'when only adjacent_work_item is present' do
let(:params) do
{ parent: parent_work_item, adjacent_work_item: child_work_item }
end
it_behaves_like 'raises a WidgetError', described_class::INVALID_RELATIVE_POSITION_ERROR
end
context 'when only relative_position is present' do
let(:params) do
{ parent: parent_work_item, relative_position: 'AFTER' }
end
it_behaves_like 'raises a WidgetError', described_class::INVALID_RELATIVE_POSITION_ERROR
end
end
context 'when updating children' do
let_it_be(:child_work_item2) { create(:work_item, :task, project: project) }
let_it_be(:child_work_item3) { create(:work_item, :task, project: project) }
let_it_be(:child_work_item4) { create(:work_item, :task, project: project) }
context 'when user has insufficient permissions to link work items' do
let(:params) { { children: [child_work_item4] } }
it_behaves_like 'raises a WidgetError with message' do
let(:message) { not_found_error }
end
end
context 'when user has sufficient permissions to link work item' do
before do
project.add_developer(user)
end
context 'with valid children params' do
let(:params) { { children: [child_work_item2, child_work_item3] } }
it 'correctly sets work item parent' do
subject
expect(work_item.reload.work_item_children)
.to contain_exactly(child_work_item, child_work_item2, child_work_item3)
end
context 'when relative_position and adjacent_work_item are given' do
context 'with BEFORE value' do
let(:params) do
{ children: [child_work_item3], relative_position: 'BEFORE', adjacent_work_item: child_work_item }
end
it_behaves_like 'raises a WidgetError', described_class::CHILDREN_REORDERING_ERROR
end
context 'with AFTER value' do
let(:params) do
{ children: [child_work_item2], relative_position: 'AFTER', adjacent_work_item: child_work_item }
end
it_behaves_like 'raises a WidgetError', described_class::CHILDREN_REORDERING_ERROR
end
end
end
context 'when child is already assigned' do
let(:params) { { children: [child_work_item] } }
it_behaves_like 'raises a WidgetError', 'Work item(s) already assigned'
end
context 'when child type is invalid' do
let_it_be(:child_issue) { create(:work_item, project: project) }
let(:params) { { children: [child_issue] } }
it_behaves_like 'raises a WidgetError with message' do
let(:message) { "#{child_issue.to_reference} cannot be added: is not allowed to add this type of parent" }
end
end
end
end
context 'when updating parent' do
let_it_be(:work_item) { create(:work_item, :task, project: project) }
let(:params) { { parent: parent_work_item } }
context 'when user has insufficient permissions to link work items' do
it_behaves_like 'raises a WidgetError with message' do
let(:message) { not_found_error }
end
end
context 'when user has sufficient permissions to link work item' do
before do
project.add_developer(user)
end
it 'correctly sets new parent' do
expect(subject[:status]).to eq(:success)
expect(work_item.work_item_parent).to eq(parent_work_item)
end
context 'when parent is nil' do
let(:params) { { parent: nil } }
it 'removes the work item parent if present' do
work_item.update!(work_item_parent: parent_work_item)
expect do
subject
work_item.reload
end.to change(work_item, :work_item_parent).from(parent_work_item).to(nil)
end
it 'returns success status if parent not present', :aggregate_failures do
work_item.update!(work_item_parent: nil)
expect(subject[:status]).to eq(:success)
expect(work_item.reload.work_item_parent).to be_nil
end
end
context 'when type is invalid' do
let_it_be(:parent_task) { create(:work_item, :task, project: project) }
let(:params) { { parent: parent_task } }
it_behaves_like 'raises a WidgetError with message' do
let(:message) { "#{work_item.to_reference} cannot be added: is not allowed to add this type of parent" }
end
end
context 'with positioning arguments' do
let_it_be_with_reload(:adjacent) { create(:work_item, :task, project: project) }
let_it_be_with_reload(:adjacent_link) do
create(:parent_link, work_item: adjacent, work_item_parent: parent_work_item)
end
let(:params) { { parent: parent_work_item, adjacent_work_item: adjacent, relative_position: 'AFTER' } }
it 'correctly sets new parent and position' do
expect(subject[:status]).to eq(:success)
expect(work_item.work_item_parent).to eq(parent_work_item)
expect(work_item.parent_link.relative_position).to be > adjacent_link.relative_position
end
context 'when other hierarchy adjacent is provided' do
let_it_be(:other_hierarchy_adjacent) { create(:parent_link).work_item }
let(:params) do
{ parent: parent_work_item, adjacent_work_item: other_hierarchy_adjacent, relative_position: 'AFTER' }
end
it_behaves_like 'raises a WidgetError', described_class::UNRELATED_ADJACENT_HIERARCHY_ERROR
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module HierarchyService
class CreateService < WorkItems::Widgets::HierarchyService::BaseService
def after_create_in_transaction(params:)
return unless params.present?
service_response!(handle_hierarchy_changes(params))
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::HierarchyService::CreateService, feature_category: :portfolio_management do
let_it_be(:user) { create(:user) }
let_it_be(:project) { create(:project) }
let_it_be(:parent_item) { create(:work_item, project: project) }
let(:widget) { parent_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::Hierarchy) } }
shared_examples 'raises a WidgetError' do
it { expect { subject }.to raise_error(described_class::WidgetError, message) }
end
before_all do
project.add_developer(user)
end
describe '#create' do
subject { described_class.new(widget: widget, current_user: user).after_create_in_transaction(params: params) }
context 'when invalid params are present' do
let(:params) { { other_parent: 'parent_work_item' } }
it_behaves_like 'raises a WidgetError' do
let(:message) { 'One or more arguments are invalid: other_parent.' }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module NotificationsService
class UpdateService < WorkItems::Widgets::BaseService
def before_update_in_transaction(params:)
return unless params.present? && params.key?(:subscribed)
return unless has_permission?(:update_subscription)
update_subscription(work_item, params)
end
private
def update_subscription(work_item, subscription_params)
work_item.set_subscription(
current_user,
subscription_params[:subscribed],
work_item.project
)
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::NotificationsService::UpdateService, feature_category: :team_planning do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, :private, group: group) }
let_it_be(:guest) { create(:user).tap { |u| project.add_guest(u) } }
let_it_be(:author) { create(:user).tap { |u| project.add_guest(u) } }
let_it_be_with_reload(:work_item) { create(:work_item, project: project, author: author) }
let_it_be(:current_user) { guest }
let(:widget) { work_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::Notifications) } }
let(:service) { described_class.new(widget: widget, current_user: current_user) }
describe '#before_update_in_transaction' do
let(:expected) { params[:subscribed] }
subject(:update_notifications) { service.before_update_in_transaction(params: params) }
shared_examples 'failing to update subscription' do
context 'when user is subscribed with a subscription record' do
let_it_be(:subscription) { create_subscription(:subscribed) }
it "does not update the work item's subscription" do
expect do
update_notifications
subscription.reload
end.to not_change { subscription.subscribed }
.and(not_change { work_item.subscribed?(current_user, project) })
end
end
context 'when user is subscribed by being a participant' do
let_it_be(:current_user) { author }
it 'does not create subscription record or change subscription state' do
expect { update_notifications }
.to not_change { Subscription.count }
.and(not_change { work_item.subscribed?(current_user, project) })
end
end
end
shared_examples 'updating notifications subscription successfully' do
it 'updates existing subscription record' do
expect do
update_notifications
subscription.reload
end.to change { subscription.subscribed }.to(expected)
.and(change { work_item.subscribed?(current_user, project) }.to(expected))
end
end
context 'when update fails' do
context 'when user lack update_subscription permissions' do
let_it_be(:params) { { subscribed: false } }
before do
allow(Ability).to receive(:allowed?).and_call_original
allow(Ability).to receive(:allowed?)
.with(current_user, :update_subscription, work_item)
.and_return(false)
end
it_behaves_like 'failing to update subscription'
end
context 'when notifications params are not present' do
let_it_be(:params) { {} }
it_behaves_like 'failing to update subscription'
end
end
context 'when update is successful' do
context 'when subscribing' do
let_it_be(:subscription) { create_subscription(:unsubscribed) }
let(:params) { { subscribed: true } }
it_behaves_like 'updating notifications subscription successfully'
end
context 'when unsubscribing' do
let(:params) { { subscribed: false } }
context 'when user is subscribed with a subscription record' do
let_it_be(:subscription) { create_subscription(:subscribed) }
it_behaves_like 'updating notifications subscription successfully'
end
context 'when user is subscribed by being a participant' do
let_it_be(:current_user) { author }
it 'creates a subscription with expected value' do
expect { update_notifications }
.to change { Subscription.count }.by(1)
.and(change { work_item.subscribed?(current_user, project) }.to(expected))
expect(Subscription.last.subscribed).to eq(expected)
end
end
end
end
end
def create_subscription(state)
create(
:subscription,
project: project,
user: current_user,
subscribable: work_item,
subscribed: (state == :subscribed)
)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module DescriptionService
class UpdateService < WorkItems::Widgets::BaseService
def before_update_callback(params: {})
params[:description] = nil if new_type_excludes_widget?
return unless params.present? && params.key?(:description)
return unless has_permission?(:update_work_item)
work_item.description = params[:description]
work_item.assign_attributes(last_edited_at: Time.current, last_edited_by: current_user)
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::DescriptionService::UpdateService, feature_category: :portfolio_management do
let_it_be(:random_user) { create(:user) }
let_it_be(:author) { create(:user) }
let_it_be(:guest) { create(:user) }
let_it_be(:reporter) { create(:user) }
let_it_be(:project) { create(:project, :public) }
let(:params) { { description: 'updated description' } }
let(:current_user) { author }
let(:work_item) do
create(
:work_item,
author: author,
project: project,
description: 'old description',
last_edited_at: Date.yesterday,
last_edited_by: random_user
)
end
let(:widget) { work_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::Description) } }
describe '#update' do
let(:service) { described_class.new(widget: widget, current_user: current_user) }
subject(:before_update_callback) { service.before_update_callback(params: params) }
shared_examples 'sets work item description' do
it 'correctly sets work item description value' do
subject
expect(work_item.description).to eq(params[:description])
expect(work_item.last_edited_by).to eq(current_user)
expect(work_item.last_edited_at).to be_within(2.seconds).of(Time.current)
end
end
shared_examples 'does not set work item description' do
it 'does not change work item description value' do
subject
expect(work_item.description).to eq('old description')
expect(work_item.last_edited_by).to eq(random_user)
expect(work_item.last_edited_at).to eq(Date.yesterday)
end
end
context 'when user has permission to update description' do
context 'when user is work item author' do
let(:current_user) { author }
it_behaves_like 'sets work item description'
end
context 'when user is a project reporter' do
let(:current_user) { reporter }
before do
project.add_reporter(reporter)
end
it_behaves_like 'sets work item description'
end
context 'when description is nil' do
let(:current_user) { author }
let(:params) { { description: nil } }
it_behaves_like 'sets work item description'
end
context 'when description is empty' do
let(:current_user) { author }
let(:params) { { description: '' } }
it_behaves_like 'sets work item description'
end
context 'when description param is not present' do
let(:params) { {} }
it_behaves_like 'does not set work item description'
end
context 'when widget does not exist in new type' do
let(:current_user) { author }
let(:params) { {} }
before do
allow(service).to receive(:new_type_excludes_widget?).and_return(true)
work_item.update!(description: 'test')
end
it "resets the work item's description" do
expect { before_update_callback }
.to change { work_item.description }
.from('test')
.to(nil)
end
end
end
context 'when user does not have permission to update description' do
context 'when user is a project guest' do
let(:current_user) { guest }
before do
project.add_guest(guest)
end
it_behaves_like 'does not set work item description'
end
context 'with private project' do
let_it_be(:project) { create(:project) }
context 'when user is work item author' do
let(:current_user) { author }
it_behaves_like 'does not set work item description'
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module LabelsService
class UpdateService < WorkItems::Widgets::BaseService
def prepare_update_params(params: {})
if new_type_excludes_widget?
params[:remove_label_ids] = @work_item.labels.map(&:id)
params[:add_label_ids] = []
end
return if params.blank?
return unless has_permission?(:set_work_item_metadata)
service_params.merge!(params.slice(:add_label_ids, :remove_label_ids))
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::LabelsService::UpdateService, feature_category: :team_planning do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, group: group) }
let_it_be(:label1) { create(:label, project: project) }
let_it_be(:label2) { create(:label, project: project) }
let_it_be(:label3) { create(:label, project: project) }
let_it_be(:current_user) { create(:user).tap { |user| project.add_reporter(user) } }
let(:work_item) { create(:work_item, project: project, labels: [label1, label2]) }
let(:widget) { work_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::Labels) } }
let(:service) { described_class.new(widget: widget, current_user: current_user) }
describe '#prepare_update_params' do
context 'when params are set' do
let(:params) { { add_label_ids: [label1.id], remove_label_ids: [label2.id] } }
it "sets params correctly" do
expect(service.prepare_update_params(params: params)).to include(
{
add_label_ids: match_array([label1.id]),
remove_label_ids: match_array([label2.id])
}
)
end
context "and user doesn't have permissions to update labels" do
let_it_be(:current_user) { create(:user) }
it 'removes label params' do
expect(service.prepare_update_params(params: params)).to be_nil
end
end
end
context 'when widget does not exist in new type' do
let(:params) { {} }
before do
allow(service).to receive(:new_type_excludes_widget?).and_return(true)
end
it "sets correct params to remove work item labels" do
expect(service.prepare_update_params(params: params)).to include(
{
remove_label_ids: match_array([label1.id, label2.id]),
add_label_ids: []
}
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module StartAndDueDateService
class UpdateService < WorkItems::Widgets::BaseService
def before_update_callback(params: {})
return widget.work_item.assign_attributes({ start_date: nil, due_date: nil }) if new_type_excludes_widget?
return if params.blank?
return unless has_permission?(:set_work_item_metadata)
widget.work_item.assign_attributes(params.slice(:start_date, :due_date))
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::StartAndDueDateService::UpdateService, feature_category: :portfolio_management do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user).tap { |user| project.add_reporter(user) } }
let_it_be_with_reload(:work_item) { create(:work_item, project: project) }
let(:widget) { work_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::StartAndDueDate) } }
describe '#before_update_callback' do
let(:start_date) { Date.today }
let(:due_date) { 1.week.from_now.to_date }
let(:service) { described_class.new(widget: widget, current_user: user) }
subject(:update_params) { service.before_update_callback(params: params) }
context 'when start and due date params are present' do
let(:params) { { start_date: Date.today, due_date: 1.week.from_now.to_date } }
it 'correctly sets date values' do
expect do
update_params
end.to change(work_item, :start_date).from(nil).to(start_date).and(
change(work_item, :due_date).from(nil).to(due_date)
)
end
context "and user doesn't have permissions to update start and due date" do
let_it_be(:user) { create(:user) }
it 'removes start and due date params params' do
expect(update_params).to be_nil
end
end
end
context 'when date params are not present' do
let(:params) { {} }
it 'does not change work item date values' do
expect do
update_params
end.to not_change(work_item, :start_date).from(nil).and(
not_change(work_item, :due_date).from(nil)
)
end
end
context 'when work item had both date values already set' do
before do
work_item.update!(start_date: start_date, due_date: due_date)
end
context 'when one of the two params is null' do
let(:params) { { start_date: nil } }
it 'sets only one date to null' do
expect do
update_params
end.to change(work_item, :start_date).from(start_date).to(nil).and(
not_change(work_item, :due_date).from(due_date)
)
end
end
end
context 'when widget does not exist in new type' do
let(:params) { {} }
before do
allow(service).to receive(:new_type_excludes_widget?).and_return(true)
work_item.update!(start_date: start_date, due_date: due_date)
end
it 'sets both dates to null' do
expect do
update_params
end.to change(work_item, :start_date).from(start_date).to(nil).and(
change(work_item, :due_date).from(due_date).to(nil)
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module WorkItems
module Widgets
module AssigneesService
class UpdateService < WorkItems::Widgets::BaseService
def before_update_in_transaction(params:)
params[:assignee_ids] = [] if new_type_excludes_widget?
return unless params.present? && params.has_key?(:assignee_ids)
return unless has_permission?(:set_work_item_metadata)
assignee_ids = filter_assignees_count(params[:assignee_ids])
assignee_ids = filter_assignee_permissions(assignee_ids)
return if assignee_ids.sort == work_item.assignee_ids.sort
work_item.assignee_ids = assignee_ids
work_item.touch
end
private
def filter_assignees_count(assignee_ids)
return assignee_ids if work_item.allows_multiple_assignees?
assignee_ids.first(1)
end
def filter_assignee_permissions(assignee_ids)
assignees = User.id_in(assignee_ids)
assignees.select { |assignee| assignee.can?(:read_work_item, work_item) }.map(&:id)
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WorkItems::Widgets::AssigneesService::UpdateService, :freeze_time, feature_category: :portfolio_management do
let_it_be(:reporter) { create(:user) }
let_it_be(:project) { create(:project, :private) }
let_it_be(:new_assignee) { create(:user) }
let(:work_item) do
create(:work_item, project: project, updated_at: 1.day.ago)
end
let(:widget) { work_item.widgets.find { |widget| widget.is_a?(WorkItems::Widgets::Assignees) } }
let(:current_user) { reporter }
let(:params) { { assignee_ids: [new_assignee.id] } }
before_all do
project.add_reporter(reporter)
project.add_guest(new_assignee)
end
describe '#before_update_in_transaction' do
let(:service) { described_class.new(widget: widget, current_user: current_user) }
subject { service.before_update_in_transaction(params: params) }
it 'updates the assignees and sets updated_at to the current time' do
subject
expect(work_item.assignee_ids).to contain_exactly(new_assignee.id)
expect(work_item.updated_at).to be_like_time(Time.current)
end
context 'when passing an empty array' do
let(:params) { { assignee_ids: [] } }
before do
work_item.assignee_ids = [reporter.id]
end
it 'removes existing assignees' do
subject
expect(work_item.assignee_ids).to be_empty
expect(work_item.updated_at).to be_like_time(Time.current)
end
end
context 'when user does not have access' do
let(:current_user) { create(:user) }
it 'does not update the assignees' do
subject
expect(work_item.assignee_ids).to be_empty
expect(work_item.updated_at).to be_like_time(1.day.ago)
end
end
context 'when multiple assignees are given' do
let(:params) { { assignee_ids: [new_assignee.id, reporter.id] } }
context 'when work item allows multiple assignees' do
before do
allow(work_item).to receive(:allows_multiple_assignees?).and_return(true)
end
it 'sets all the given assignees' do
subject
expect(work_item.assignee_ids).to contain_exactly(new_assignee.id, reporter.id)
expect(work_item.updated_at).to be_like_time(Time.current)
end
end
context 'when work item does not allow multiple assignees' do
before do
allow(work_item).to receive(:allows_multiple_assignees?).and_return(false)
end
it 'only sets the first assignee' do
subject
expect(work_item.assignee_ids).to contain_exactly(new_assignee.id)
expect(work_item.updated_at).to be_like_time(Time.current)
end
end
end
context 'when assignee does not have access to the work item' do
let(:params) { { assignee_ids: [create(:user).id] } }
it 'does not set the assignee' do
subject
expect(work_item.assignee_ids).to be_empty
expect(work_item.updated_at).to be_like_time(1.day.ago)
end
end
context 'when assignee ids are the same as the existing ones' do
before do
work_item.assignee_ids = [new_assignee.id]
end
it 'does not touch updated_at' do
subject
expect(work_item.assignee_ids).to contain_exactly(new_assignee.id)
expect(work_item.updated_at).to be_like_time(1.day.ago)
end
end
context 'when widget does not exist in new type' do
let(:params) { {} }
before do
allow(service).to receive(:new_type_excludes_widget?).and_return(true)
work_item.assignee_ids = [new_assignee.id]
end
it "resets the work item's assignees" do
subject
expect(work_item.assignee_ids).to be_empty
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Webauthn
class RegisterService < BaseService
def initialize(user, params, challenge)
@user = user
@params = params
@challenge = challenge
end
def execute
registration = WebauthnRegistration.new
begin
webauthn_credential = WebAuthn::Credential.from_create(Gitlab::Json.parse(@params[:device_response]))
webauthn_credential.verify(@challenge)
registration.update(
credential_xid: Base64.strict_encode64(webauthn_credential.raw_id),
public_key: webauthn_credential.public_key,
counter: webauthn_credential.sign_count,
name: @params[:name],
user: @user
)
rescue JSON::ParserError
registration.errors.add(:base, _('Your WebAuthn device did not send a valid JSON response.'))
rescue WebAuthn::Error => e
registration.errors.add(:base, e.message)
end
registration
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
require 'webauthn/fake_client'
RSpec.describe Webauthn::RegisterService, feature_category: :system_access do
let(:client) { WebAuthn::FakeClient.new(origin) }
let(:user) { create(:user) }
let(:challenge) { Base64.strict_encode64(SecureRandom.random_bytes(32)) }
let(:origin) { 'http://localhost' }
describe '#execute' do
it 'returns a registration if challenge matches' do
create_result = client.create(challenge: challenge) # rubocop:disable Rails/SaveBang
webauthn_credential = WebAuthn::Credential.from_create(create_result)
params = { device_response: create_result.to_json, name: 'abc' }
service = described_class.new(user, params, challenge)
registration = service.execute
expect(registration.credential_xid).to eq(Base64.strict_encode64(webauthn_credential.raw_id))
expect(registration.errors.size).to eq(0)
end
it 'returns an error if challenge does not match' do
create_result = client.create(challenge: Base64.strict_encode64(SecureRandom.random_bytes(16))) # rubocop:disable Rails/SaveBang
params = { device_response: create_result.to_json, name: 'abc' }
service = described_class.new(user, params, challenge)
registration = service.execute
expect(registration.errors.size).to eq(1)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Webauthn
class AuthenticateService < BaseService
def initialize(user, device_response, challenge)
@user = user
@device_response = device_response
@challenge = challenge
end
def execute
parsed_device_response = Gitlab::Json.parse(@device_response)
webauthn_credential = WebAuthn::Credential.from_get(parsed_device_response)
encoded_raw_id = Base64.strict_encode64(webauthn_credential.raw_id)
stored_webauthn_credential = @user.webauthn_registrations.find_by_credential_xid(encoded_raw_id)
encoder = WebAuthn.configuration.encoder
if stored_webauthn_credential &&
validate_webauthn_credential(webauthn_credential) &&
verify_webauthn_credential(webauthn_credential, stored_webauthn_credential, @challenge, encoder)
stored_webauthn_credential.update!(counter: webauthn_credential.sign_count)
return true
end
false
rescue JSON::ParserError, WebAuthn::SignCountVerificationError, WebAuthn::Error
false
end
private
##
# Validates that webauthn_credential is syntactically valid
#
# duplicated from WebAuthn::PublicKeyCredential#verify
# which can't be used here as we need to call WebAuthn::AuthenticatorAssertionResponse#verify instead
# (which is done in #verify_webauthn_credential)
def validate_webauthn_credential(webauthn_credential)
webauthn_credential.type == WebAuthn::TYPE_PUBLIC_KEY &&
webauthn_credential.raw_id && webauthn_credential.id &&
webauthn_credential.raw_id == WebAuthn.standard_encoder.decode(webauthn_credential.id)
end
##
# Verifies that webauthn_credential matches stored_credential with the given challenge
#
def verify_webauthn_credential(webauthn_credential, stored_credential, challenge, encoder)
# We need to adjust the relaying party id (RP id) we verify against if the registration in question
# is a migrated U2F registration. This is beacuse the appid of U2F and the rp id of WebAuthn differ.
rp_id = webauthn_credential.client_extension_outputs['appid'] ? WebAuthn.configuration.origin : URI(WebAuthn.configuration.origin).host
webauthn_credential.response.verify(
encoder.decode(challenge),
public_key: encoder.decode(stored_credential.public_key),
sign_count: stored_credential.counter,
rp_id: rp_id
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
require 'webauthn/fake_client'
RSpec.describe Webauthn::AuthenticateService, feature_category: :system_access do
let(:client) { WebAuthn::FakeClient.new(origin) }
let(:user) { create(:user) }
let(:challenge) { Base64.strict_encode64(SecureRandom.random_bytes(32)) }
let(:origin) { 'http://localhost' }
before do
create_result = client.create(challenge: challenge) # rubocop:disable Rails/SaveBang
webauthn_credential = WebAuthn::Credential.from_create(create_result)
registration = WebauthnRegistration.new(
credential_xid: Base64.strict_encode64(webauthn_credential.raw_id),
public_key: webauthn_credential.public_key,
counter: 0,
name: 'name',
user_id: user.id
)
registration.save!
end
describe '#execute' do
it 'returns true if the response is valid and a matching stored credential is present' do
get_result = client.get(challenge: challenge)
get_result['clientExtensionResults'] = {}
service = described_class.new(user, get_result.to_json, challenge)
expect(service.execute).to eq true
end
context 'when response is valid but no matching stored credential is present' do
it 'returns false' do
other_client = WebAuthn::FakeClient.new(origin)
other_client.create(challenge: challenge) # rubocop:disable Rails/SaveBang
get_result = other_client.get(challenge: challenge)
get_result['clientExtensionResults'] = {}
service = described_class.new(user, get_result.to_json, challenge)
expect(service.execute).to eq false
end
end
context 'when device response includes invalid json' do
it 'returns false' do
service = described_class.new(user, 'invalid JSON', '')
expect(service.execute).to eq false
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Webauthn
class DestroyService < BaseService
attr_reader :webauthn_registration, :user, :current_user
def initialize(current_user, user, webauthn_registrations_id)
@current_user = current_user
@user = user
@webauthn_registration = user.webauthn_registrations.find(webauthn_registrations_id)
end
def execute
return error(_('You are not authorized to perform this action')) unless authorized?
webauthn_registration.destroy
user.reset_backup_codes! if last_two_factor_registration?
end
private
def last_two_factor_registration?
user.webauthn_registrations.empty? && !user.otp_required_for_login?
end
def authorized?
current_user.can?(:disable_two_factor, user)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Webauthn::DestroyService, feature_category: :system_access do
let(:user) { create(:user, :two_factor_via_webauthn, registrations_count: 1) }
let(:current_user) { user }
describe '#execute' do
let(:webauthn_id) { user.webauthn_registrations.first.id }
subject { described_class.new(current_user, user, webauthn_id).execute }
context 'with only one webauthn method enabled' do
context 'when another user is calling the service' do
context 'for a user without permissions' do
let(:current_user) { create(:user) }
it 'does not destry the webauthn registration' do
expect { subject }.not_to change { user.webauthn_registrations.count }
end
it 'does not remove the user backup codes' do
expect { subject }.not_to change { user.otp_backup_codes }
end
it 'returns error' do
expect(subject[:status]).to eq(:error)
end
end
context 'for an admin' do
it 'destroys the webauthn registration' do
expect { subject }.to change { user.webauthn_registrations.count }.by(-1)
end
it 'removes the user backup codes' do
subject
expect(user.otp_backup_codes).to be_nil
end
end
end
context 'when current user is calling the service' do
context 'when there is also OTP enabled' do
before do
user.otp_required_for_login = true
user.otp_secret = User.generate_otp_secret(32)
user.otp_grace_period_started_at = Time.current
user.generate_otp_backup_codes!
user.save!
end
it 'removes the webauth registrations' do
expect { subject }.to change { user.webauthn_registrations.count }.by(-1)
end
it 'does not remove the user backup codes' do
expect { subject }.not_to change { user.otp_backup_codes }
end
end
end
end
context 'with multiple webauthn methods enabled' do
before do
create(:webauthn_registration, user: user)
end
it 'destroys the webauthn registration' do
expect { subject }.to change { user.webauthn_registrations.count }.by(-1)
end
it 'does not remove the user backup codes' do
expect { subject }.not_to change { user.otp_backup_codes }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class CreateEventService < BaseService
def execute
::Packages::Event.unique_counters_for(event_scope, event_name, originator_type).each do |event_name|
::Gitlab::UsageDataCounters::HLLRedisCounter.track_event(event_name, values: current_user.id)
end
::Packages::Event.counters_for(event_scope, event_name, originator_type).each do |event_name|
::Gitlab::UsageDataCounters::PackageEventCounter.count(event_name)
end
end
def originator_type
case current_user
when User
:user
when DeployToken
:deploy_token
else
:guest
end
end
private
def event_scope
@event_scope ||= scope.is_a?(::Packages::Package) ? scope.package_type : scope
end
def scope
params[:scope]
end
def event_name
params[:event_name]
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::CreateEventService, feature_category: :package_registry do
let(:scope) { 'generic' }
let(:event_name) { 'push_package' }
let(:params) do
{
scope: scope,
event_name: event_name
}
end
subject { described_class.new(nil, user, params).execute }
describe '#execute' do
shared_examples 'redis package unique event creation' do |originator_type, expected_scope|
it 'tracks the event' do
expect(::Gitlab::UsageDataCounters::HLLRedisCounter).to receive(:track_event).with(/package/, values: user.id)
subject
end
end
shared_examples 'redis package count event creation' do |originator_type, expected_scope|
it 'tracks the event' do
expect(::Gitlab::UsageDataCounters::PackageEventCounter).to receive(:count).at_least(:once)
subject
end
end
context 'with a user' do
let(:user) { create(:user) }
it_behaves_like 'redis package unique event creation', 'user', 'generic'
it_behaves_like 'redis package count event creation', 'user', 'generic'
end
context 'with a deploy token' do
let(:user) { create(:deploy_token) }
it_behaves_like 'redis package unique event creation', 'deploy_token', 'generic'
it_behaves_like 'redis package count event creation', 'deploy_token', 'generic'
end
context 'with no user' do
let(:user) { nil }
it_behaves_like 'redis package count event creation', 'guest', 'generic'
end
context 'with a package as scope' do
let(:scope) { create(:npm_package) }
context 'as guest' do
let(:user) { nil }
it_behaves_like 'redis package count event creation', 'guest', 'npm'
end
context 'with user' do
let(:user) { create(:user) }
it_behaves_like 'redis package unique event creation', 'user', 'npm'
it_behaves_like 'redis package count event creation', 'user', 'npm'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
# WARNING: ensure that permissions are verified before using this service.
class MarkPackageFilesForDestructionService
BATCH_SIZE = 500
def initialize(package_files)
@package_files = package_files
end
def execute(batch_deadline: nil, batch_size: BATCH_SIZE)
timeout = false
updates_count = 0
min_batch_size = [batch_size, BATCH_SIZE].min
@package_files.each_batch(of: min_batch_size) do |batched_package_files|
if batch_deadline && Time.zone.now > batch_deadline
timeout = true
break
end
updates_count += batched_package_files.update_all(status: :pending_destruction)
end
payload = { marked_package_files_count: updates_count }
return response_error(payload) if timeout
response_success(payload)
end
private
def response_success(payload)
ServiceResponse.success(
message: 'Package files are now pending destruction',
payload: payload
)
end
def response_error(payload)
ServiceResponse.error(
message: 'Timeout while marking package files as pending destruction',
payload: payload
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::MarkPackageFilesForDestructionService, :aggregate_failures,
feature_category: :package_registry do
let(:service) { described_class.new(package_files) }
describe '#execute', :aggregate_failures do
let(:batch_deadline) { nil }
subject { service.execute(batch_deadline: batch_deadline) }
shared_examples 'executing successfully' do |marked_package_files_count: 0|
it 'marks package files for destruction' do
expect { subject }
.to change { ::Packages::PackageFile.pending_destruction.count }.by(package_files.size)
end
it 'executes successfully' do
expect(subject).to be_success
expect(subject.message).to eq('Package files are now pending destruction')
expect(subject.payload).to eq(marked_package_files_count: marked_package_files_count)
end
end
context 'with no package files' do
let_it_be(:package_files) { ::Packages::PackageFile.none }
it_behaves_like 'executing successfully'
end
context 'with a single package file' do
let_it_be(:package_file) { create(:package_file) }
let_it_be(:package_files) { ::Packages::PackageFile.id_in(package_file.id) }
it_behaves_like 'executing successfully', marked_package_files_count: 1
end
context 'with many package files' do
let_it_be(:package_files) { ::Packages::PackageFile.id_in(create_list(:package_file, 3).map(&:id)) }
it_behaves_like 'executing successfully', marked_package_files_count: 3
context 'with a batch deadline' do
let_it_be(:batch_deadline) { 250.seconds.from_now }
context 'when the deadline is not hit' do
before do
expect(Time.zone).to receive(:now).and_return(batch_deadline - 10.seconds)
end
it_behaves_like 'executing successfully', marked_package_files_count: 3
end
context 'when the deadline is hit' do
it 'does not execute the batch loop' do
expect(Time.zone).to receive(:now).and_return(batch_deadline + 10.seconds)
expect { subject }.to not_change { ::Packages::PackageFile.pending_destruction.count }
expect(subject).to be_error
expect(subject.message).to eq('Timeout while marking package files as pending destruction')
expect(subject.payload).to eq(marked_package_files_count: 0)
end
end
end
context 'when a batch size is defined' do
let_it_be(:batch_deadline) { 250.seconds.from_now }
let(:batch_size) { 2 }
subject { service.execute(batch_deadline: batch_deadline, batch_size: batch_size) }
before do
expect(Time.zone).to receive(:now).twice.and_call_original
end
it_behaves_like 'executing successfully', marked_package_files_count: 3
end
end
context 'with an error during the update' do
let_it_be(:package_files) { ::Packages::PackageFile.none }
before do
expect(package_files).to receive(:each_batch).and_raise('error!')
end
it 'raises the error' do
expect { subject }
.to raise_error('error!')
.and not_change { ::Packages::PackageFile.pending_destruction.count }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class UpdatePackageFileService
delegate :file, to: :@package_file
def initialize(package_file, params)
@package_file = package_file
@params = params
end
def execute
check_params
return if same_as_params?
# we need to access the file *before* updating the attributes linked to its path/key.
file_storage_mode = file.file_storage?
@package_file.package_id = package_id if package_id
@package_file.file_name = file_name if file_name
if file_storage_mode
# package file is in mode LOCAL: we can pass the `file` to the update
@package_file.file = file
else
# package file is in mode REMOTE: don't pass the `file` to the update
# instead, pass the new file path. This will move the file
# in object storage.
@package_file.new_file_path = File.join(file.store_dir, @package_file.file_name)
end
@package_file.save!
end
private
def check_params
raise ArgumentError, 'package_file not persisted' unless @package_file.persisted?
raise ArgumentError, 'package_id and file_name are blank' if package_id.blank? && file_name.blank?
end
def same_as_params?
return false if package_id && package_id != @package_file.package_id
return false if file_name && file_name != @package_file.file_name
true
end
def package_id
@params[:package_id]
end
def file_name
@params[:file_name]
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::UpdatePackageFileService, feature_category: :package_registry do
let_it_be(:another_package) { create(:package) }
let_it_be(:old_file_name) { 'old_file_name.txt' }
let_it_be(:new_file_name) { 'new_file_name.txt' }
let(:package) { package_file.package }
let(:params) { { package_id: another_package.id, file_name: new_file_name } }
let(:service) { described_class.new(package_file, params) }
describe '#execute' do
subject { service.execute }
shared_examples 'updating package file with valid parameters' do
context 'with both parameters set' do
it 'updates the package file accordingly' do
expect { subject }
.to change { package.package_files.count }.from(1).to(0)
.and change { another_package.package_files.count }.from(0).to(1)
.and change { package_file.package_id }.from(package.id).to(another_package.id)
.and change { package_file.file_name }.from(old_file_name).to(new_file_name)
end
end
context 'with only file_name set' do
let(:params) { { file_name: new_file_name } }
it 'updates the package file accordingly' do
expect { subject }
.to not_change { package.package_files.count }
.and not_change { another_package.package_files.count }
.and not_change { package_file.package_id }
.and change { package_file.file_name }.from(old_file_name).to(new_file_name)
end
end
context 'with only package_id set' do
let(:params) { { package_id: another_package.id } }
it 'updates the package file accordingly' do
expect { subject }
.to change { package.package_files.count }.from(1).to(0)
.and change { another_package.package_files.count }.from(0).to(1)
.and change { package_file.package_id }.from(package.id).to(another_package.id)
.and not_change { package_file.file_name }
end
end
end
shared_examples 'not updating package with invalid parameters' do
context 'with blank parameters' do
let(:params) { {} }
it 'raise an argument error' do
expect { subject }.to raise_error(ArgumentError, 'package_id and file_name are blank')
end
end
context 'with non persisted package file' do
let(:package_file) { build(:package_file) }
it 'raise an argument error' do
expect { subject }.to raise_error(ArgumentError, 'package_file not persisted')
end
end
end
context 'with object storage disabled' do
let(:package_file) { create(:package_file, file_name: old_file_name) }
before do
stub_package_file_object_storage(enabled: false)
end
it_behaves_like 'updating package file with valid parameters' do
before do
expect(package_file).to receive(:remove_previously_stored_file).and_call_original
expect(package_file).not_to receive(:move_in_object_storage)
end
end
it_behaves_like 'not updating package with invalid parameters'
end
context 'with object storage enabled' do
let(:package_file) do
create(
:package_file,
file_name: old_file_name,
file: CarrierWaveStringFile.new_file(
file_content: 'content',
filename: old_file_name,
content_type: 'text/plain'
),
file_store: ::Packages::PackageFileUploader::Store::REMOTE
)
end
before do
stub_package_file_object_storage(enabled: true)
end
it_behaves_like 'updating package file with valid parameters' do
before do
expect(package_file).not_to receive(:remove_previously_stored_file)
expect(package_file).to receive(:move_in_object_storage).and_call_original
end
end
it_behaves_like 'not updating package with invalid parameters' do
before do
expect(package_file.file.file).not_to receive(:copy_to)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class CreatePackageFileService
attr_reader :package, :params
def initialize(package, params)
@package = package
@params = params
end
def execute
package_file = package.package_files.build(
file: params[:file],
size: params[:size],
file_name: params[:file_name],
file_sha1: params[:file_sha1],
file_sha256: params[:file_sha256],
file_md5: params[:file_md5]
)
if params[:build].present?
package_file.package_file_build_infos << package_file.package_file_build_infos.build(pipeline: params[:build].pipeline)
end
package_file.save!
package_file
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::CreatePackageFileService, feature_category: :package_registry do
let_it_be(:package) { create(:maven_package) }
let_it_be(:user) { create(:user) }
let(:service) { described_class.new(package, params) }
describe '#execute' do
subject { service.execute }
context 'with valid params' do
let(:params) do
{
file: Tempfile.new,
file_name: 'foo.jar'
}
end
it 'creates a new package file' do
package_file = subject
expect(package_file).to be_valid
expect(package_file.file_name).to eq('foo.jar')
end
it_behaves_like 'assigns build to package file'
end
context 'file is missing' do
let(:params) do
{
file_name: 'foo.jar'
}
end
it 'raises an error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class UpdateTagsService
include Gitlab::Utils::StrongMemoize
def initialize(package, tags = [])
@package = package
@tags = tags
end
def execute
return if @tags.empty?
tags_to_destroy = existing_tags - @tags
tags_to_create = @tags - existing_tags
@package.tags.with_name(tags_to_destroy).delete_all if tags_to_destroy.any?
::ApplicationRecord.legacy_bulk_insert(Packages::Tag.table_name, rows(tags_to_create)) if tags_to_create.any? # rubocop:disable Gitlab/BulkInsert
end
private
def existing_tags
@package.tag_names
end
strong_memoize_attr :existing_tags
def rows(tags)
now = Time.zone.now
tags.map do |tag|
{
package_id: @package.id,
name: tag,
created_at: now,
updated_at: now,
project_id: @package.project_id
}
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::UpdateTagsService, feature_category: :package_registry do
let_it_be(:package, reload: true) { create(:nuget_package) }
let(:tags) { %w[test-tag tag1 tag2 tag3] }
let(:service) { described_class.new(package, tags) }
describe '#execute' do
subject { service.execute }
RSpec.shared_examples 'updating tags' do |tags_count|
it 'updates a tag' do
expect { subject }.to change { Packages::Tag.count }.by(tags_count)
expect(package.reload.tags.map(&:name)).to contain_exactly(*tags)
end
end
it_behaves_like 'updating tags', 4
context 'with an existing tag' do
before do
create(:packages_tag, package: package2, name: 'test-tag')
end
context 'on the same package' do
let_it_be(:package2) { package }
it_behaves_like 'updating tags', 3
context 'with different name' do
before do
create(:packages_tag, package: package2, name: 'to_be_destroyed')
end
it_behaves_like 'updating tags', 2
end
end
context 'on a different package' do
let_it_be(:package2) { create(:nuget_package) }
it_behaves_like 'updating tags', 4
end
end
context 'with empty tags' do
let(:tags) { [] }
it 'is a no op' do
expect(package).not_to receive(:tags)
expect(::ApplicationRecord).not_to receive(:legacy_bulk_insert)
subject
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class RemoveTagService < BaseService
attr_reader :package_tag
def initialize(package_tag)
raise ArgumentError, "Package tag must be set" if package_tag.blank?
@package_tag = package_tag
end
def execute
package_tag.delete
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::RemoveTagService, feature_category: :package_registry do
let!(:package_tag) { create(:packages_tag) }
describe '#execute' do
subject { described_class.new(package_tag).execute }
context 'with existing tag' do
it { expect { subject }.to change { Packages::Tag.count }.by(-1) }
end
context 'with nil' do
subject { described_class.new(nil) }
it { expect { subject }.to raise_error(ArgumentError) }
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class MarkPackageForDestructionService < BaseContainerService
alias_method :package, :container
def execute
return service_response_error("You don't have access to this package", 403) unless user_can_delete_package?
package.pending_destruction!
package.mark_package_files_for_destruction
package.sync_maven_metadata(current_user)
service_response_success('Package was successfully marked as pending destruction')
rescue StandardError => e
track_exception(e)
service_response_error('Failed to mark the package as pending destruction', 400)
end
private
def service_response_error(message, http_status)
ServiceResponse.error(message: message, http_status: http_status)
end
def service_response_success(message)
ServiceResponse.success(message: message)
end
def user_can_delete_package?
can?(current_user, :destroy_package, package.project)
end
def track_exception(error)
Gitlab::ErrorTracking.track_exception(
error,
project_id: package.project_id,
package_id: package.id
)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::MarkPackageForDestructionService, feature_category: :package_registry do
let_it_be(:user) { create(:user) }
let_it_be_with_reload(:package) { create(:npm_package) }
describe '#execute' do
subject(:service) { described_class.new(container: package, current_user: user) }
context 'when the user is authorized' do
before do
package.project.add_maintainer(user)
end
context 'when it is successful' do
it 'marks the package and package files as pending destruction' do
expect(package).to receive(:sync_maven_metadata).and_call_original
expect(package).to receive(:mark_package_files_for_destruction).and_call_original
expect { service.execute }.to change { package.status }.from('default').to('pending_destruction')
end
it 'returns a success ServiceResponse' do
response = service.execute
expect(response).to be_a(ServiceResponse)
expect(response).to be_success
expect(response.message).to eq("Package was successfully marked as pending destruction")
end
end
context 'when it is not successful' do
before do
allow(package).to receive(:pending_destruction!).and_raise(StandardError, "test")
end
it 'returns an error ServiceResponse' do
expect(Gitlab::ErrorTracking).to receive(:track_exception).with(
instance_of(StandardError),
project_id: package.project_id,
package_id: package.id
)
response = service.execute
expect(package).not_to receive(:sync_maven_metadata)
expect(response).to be_a(ServiceResponse)
expect(response).to be_error
expect(response.message).to eq("Failed to mark the package as pending destruction")
expect(response.status).to eq(:error)
end
end
end
context 'when the user is not authorized' do
it 'returns an error ServiceResponse' do
response = service.execute
expect(response).to be_a(ServiceResponse)
expect(response).to be_error
expect(response.message).to eq("You don't have access to this package")
expect(response.status).to eq(:error)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class CreateTemporaryPackageService < ::Packages::CreatePackageService
PACKAGE_VERSION = '0.0.0'
def execute(package_type, name: 'Temporary.Package')
create_package!(package_type,
name: name,
version: "#{PACKAGE_VERSION}-#{uuid}",
status: 'processing'
)
end
private
def uuid
SecureRandom.uuid
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::CreateTemporaryPackageService, feature_category: :package_registry do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let_it_be(:params) { {} }
let_it_be(:package_name) { 'my-package' }
let_it_be(:package_type) { 'rubygems' }
describe '#execute' do
subject { described_class.new(project, user, params).execute(package_type, name: package_name) }
let(:package) { Packages::Package.last }
it 'creates the package', :aggregate_failures do
expect { subject }.to change { Packages::Package.count }.by(1)
expect(package).to be_valid
expect(package).to be_processing
expect(package.name).to eq(package_name)
expect(package.version).to start_with(described_class::PACKAGE_VERSION)
expect(package.package_type).to eq(package_type)
end
it 'can create two packages in a row', :aggregate_failures do
expect { subject }.to change { Packages::Package.count }.by(1)
expect do
described_class.new(project, user, params).execute(package_type, name: package_name)
end.to change { Packages::Package.count }.by(1)
expect(package).to be_valid
expect(package).to be_processing
expect(package.name).to eq(package_name)
expect(package.version).to start_with(described_class::PACKAGE_VERSION)
expect(package.package_type).to eq(package_type)
end
it_behaves_like 'assigns the package creator'
it_behaves_like 'assigns build to package'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
class MarkPackagesForDestructionService
include BaseServiceUtility
BATCH_SIZE = 20
UNAUTHORIZED_RESPONSE = ServiceResponse.error(
message: "You don't have the permission to perform this action",
reason: :unauthorized
).freeze
ERROR_RESPONSE = ServiceResponse.error(
message: 'Failed to mark the packages as pending destruction'
).freeze
SUCCESS_RESPONSE = ServiceResponse.success(
message: 'Packages were successfully marked as pending destruction'
).freeze
# Initialize this service with the given packages and user.
#
# * `packages`: must be an ActiveRecord relationship.
# * `current_user`: an User object. Could be nil.
def initialize(packages:, current_user: nil)
@packages = packages
@current_user = current_user
end
def execute(batch_size: BATCH_SIZE)
no_access = false
min_batch_size = [batch_size, BATCH_SIZE].min
package_ids = []
@packages.each_batch(of: min_batch_size) do |batched_packages|
loaded_packages = batched_packages.including_project_route.to_a
package_ids = loaded_packages.map(&:id)
break no_access = true unless can_destroy_packages?(loaded_packages)
::Packages::Package.id_in(package_ids)
.update_all(status: :pending_destruction)
sync_maven_metadata(loaded_packages)
mark_package_files_for_destruction(loaded_packages)
end
return UNAUTHORIZED_RESPONSE if no_access
SUCCESS_RESPONSE
rescue StandardError => e
track_exception(e, package_ids)
ERROR_RESPONSE
end
private
def mark_package_files_for_destruction(packages)
::Packages::MarkPackageFilesForDestructionWorker.bulk_perform_async_with_contexts(
packages,
arguments_proc: -> (package) { package.id },
context_proc: -> (package) { { project: package.project, user: @current_user } }
)
end
def sync_maven_metadata(packages)
maven_packages_with_version = packages.select { |pkg| pkg.maven? && pkg.version? }
::Packages::Maven::Metadata::SyncWorker.bulk_perform_async_with_contexts(
maven_packages_with_version,
arguments_proc: -> (package) { [@current_user.id, package.project_id, package.name] },
context_proc: -> (package) { { project: package.project, user: @current_user } }
)
end
def can_destroy_packages?(packages)
packages.all? do |package|
can?(@current_user, :destroy_package, package)
end
end
def track_exception(error, package_ids)
Gitlab::ErrorTracking.track_exception(error, package_ids: package_ids)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::MarkPackagesForDestructionService, :sidekiq_inline, feature_category: :package_registry do
let_it_be(:project) { create(:project) }
let_it_be_with_reload(:packages) { create_list(:npm_package, 3, project: project) }
let(:user) { project.owner }
# The service only accepts ActiveRecord relationships and not arrays.
let(:service) { described_class.new(packages: ::Packages::Package.id_in(package_ids), current_user: user) }
let(:package_ids) { packages.map(&:id) }
describe '#execute' do
subject { service.execute }
context 'when the user is authorized' do
before do
project.add_maintainer(user)
end
context 'when it is successful' do
it 'marks the packages as pending destruction' do
expect(::Packages::Maven::Metadata::SyncService).not_to receive(:new)
expect { subject }.to change { ::Packages::Package.pending_destruction.count }.from(0).to(3)
.and change { Packages::PackageFile.pending_destruction.count }.from(0).to(3)
packages.each { |pkg| expect(pkg.reload).to be_pending_destruction }
expect(subject).to be_a(ServiceResponse)
expect(subject).to be_success
expect(subject.message).to eq('Packages were successfully marked as pending destruction')
end
context 'with maven packages' do
let_it_be_with_reload(:packages) { create_list(:maven_package, 3, project: project) }
it 'marks the packages as pending destruction' do
expect(::Packages::Maven::Metadata::SyncService).to receive(:new).once.and_call_original
expect { subject }.to change { ::Packages::Package.pending_destruction.count }.from(0).to(3)
.and change { Packages::PackageFile.pending_destruction.count }.from(0).to(9)
packages.each { |pkg| expect(pkg.reload).to be_pending_destruction }
expect(subject).to be_a(ServiceResponse)
expect(subject).to be_success
expect(subject.message).to eq('Packages were successfully marked as pending destruction')
end
context 'without version' do
before do
::Packages::Package.id_in(package_ids).update_all(version: nil)
end
it 'marks the packages as pending destruction' do
expect(::Packages::Maven::Metadata::SyncService).not_to receive(:new)
expect { subject }.to change { ::Packages::Package.pending_destruction.count }.from(0).to(3)
.and change { Packages::PackageFile.pending_destruction.count }.from(0).to(9)
packages.each { |pkg| expect(pkg.reload).to be_pending_destruction }
expect(subject).to be_a(ServiceResponse)
expect(subject).to be_success
expect(subject.message).to eq('Packages were successfully marked as pending destruction')
end
end
end
end
context 'when it is not successful' do
before do
allow(service).to receive(:can_destroy_packages?).and_raise(StandardError, 'test')
end
it 'returns an error ServiceResponse' do
expect(::Packages::Maven::Metadata::SyncService).not_to receive(:new)
expect(Gitlab::ErrorTracking).to receive(:track_exception).with(
instance_of(StandardError),
package_ids: package_ids
)
expect { subject }.to not_change { ::Packages::Package.pending_destruction.count }
.and not_change { ::Packages::PackageFile.pending_destruction.count }
expect(subject).to be_a(ServiceResponse)
expect(subject).to be_error
expect(subject.message).to eq("Failed to mark the packages as pending destruction")
expect(subject.status).to eq(:error)
end
end
end
context 'when the user is not authorized' do
let(:user) { nil }
it 'returns an error ServiceResponse' do
expect(::Packages::Maven::Metadata::SyncService).not_to receive(:new)
expect { subject }.to not_change { ::Packages::Package.pending_destruction.count }
.and not_change { ::Packages::PackageFile.pending_destruction.count }
expect(subject).to be_a(ServiceResponse)
expect(subject).to be_error
expect(subject.message).to eq("You don't have the permission to perform this action")
expect(subject.status).to eq(:error)
expect(subject.reason).to eq(:unauthorized)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
# rubocop: disable Gitlab/BulkInsert
class CreateDependencyService < BaseService
attr_reader :package, :dependencies
def initialize(package, dependencies)
@package = package
@dependencies = dependencies
end
def execute
Packages::DependencyLink.dependency_types.each_key do |type|
create_dependency(type)
end
end
private
def create_dependency(type)
return unless dependencies[type].is_a?(Hash)
names_and_version_patterns = dependencies[type]
existing_ids, existing_names = find_existing_ids_and_names(names_and_version_patterns)
dependencies_to_insert = names_and_version_patterns
if existing_names.any?
dependencies_to_insert = names_and_version_patterns.reject { |k, _| k.in?(existing_names) }
end
ApplicationRecord.transaction do
inserted_ids = bulk_insert_package_dependencies(dependencies_to_insert)
bulk_insert_package_dependency_links(type, (existing_ids + inserted_ids))
end
end
def find_existing_ids_and_names(names_and_version_patterns)
ids_and_names = Packages::Dependency.for_package_names_and_version_patterns(names_and_version_patterns)
.pluck_ids_and_names
ids = ids_and_names.map(&:first) || []
names = ids_and_names.map(&:second) || []
[ids, names]
end
def bulk_insert_package_dependencies(names_and_version_patterns)
return [] if names_and_version_patterns.empty?
rows = names_and_version_patterns.map do |name, version_pattern|
{
name: name,
version_pattern: version_pattern
}
end
ids = ApplicationRecord.legacy_bulk_insert(Packages::Dependency.table_name, rows, return_ids: true, on_conflict: :do_nothing)
return ids if ids.size == names_and_version_patterns.size
Packages::Dependency.uncached do
# The bulk_insert statement above do not dirty the query cache. To make
# sure that the results are fresh from the database and not from a stalled
# and potentially wrong cache, this query has to be done with the query
# cache disabled.
Packages::Dependency.ids_for_package_names_and_version_patterns(names_and_version_patterns)
end
end
def bulk_insert_package_dependency_links(type, dependency_ids)
rows = dependency_ids.map do |dependency_id|
{
package_id: package.id,
dependency_id: dependency_id,
dependency_type: Packages::DependencyLink.dependency_types[type.to_s]
}
end
ApplicationRecord.legacy_bulk_insert(Packages::DependencyLink.table_name, rows)
end
end
# rubocop: enable Gitlab/BulkInsert
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::CreateDependencyService, feature_category: :package_registry do
describe '#execute' do
let_it_be(:namespace) { create(:namespace) }
let_it_be(:version) { '1.0.1' }
let_it_be(:package_name) { "@#{namespace.path}/my-app" }
context 'when packages are published' do
let(:json_file) { 'packages/npm/payload.json' }
let(:params) do
Gitlab::Json.parse(fixture_file(json_file)
.gsub('@root/npm-test', package_name)
.gsub('1.0.1', version))
.with_indifferent_access
end
let(:package_version) { params[:versions].each_key.first }
let(:dependencies) { params[:versions][package_version] }
let(:package) { create(:npm_package) }
let(:dependency_names) { package.dependency_links.flat_map(&:dependency).map(&:name).sort }
let(:dependency_link_types) { package.dependency_links.map(&:dependency_type).sort }
subject { described_class.new(package, dependencies).execute }
it 'creates dependencies and links' do
expect(Packages::Dependency)
.to receive(:ids_for_package_names_and_version_patterns)
.once
.and_call_original
expect { subject }
.to change { Packages::Dependency.count }.by(1)
.and change { Packages::DependencyLink.count }.by(1)
expect(dependency_names).to match_array(%w[express])
expect(dependency_link_types).to match_array(%w[dependencies])
end
context 'with repeated packages' do
let(:json_file) { 'packages/npm/payload_with_duplicated_packages.json' }
it 'creates dependencies and links' do
expect(Packages::Dependency)
.to receive(:ids_for_package_names_and_version_patterns)
.exactly(4).times
.and_call_original
expect { subject }
.to change { Packages::Dependency.count }.by(4)
.and change { Packages::DependencyLink.count }.by(6)
expect(dependency_names).to match_array(%w[d3 d3 d3 dagre-d3 dagre-d3 express])
expect(dependency_link_types).to match_array(%w[bundleDependencies dependencies dependencies devDependencies devDependencies peerDependencies])
end
end
context 'with dependencies bulk insert conflicts' do
let_it_be(:rows) { [{ name: 'express', version_pattern: '^4.16.4' }] }
it 'creates dependences and links' do
original_bulk_insert = ::ApplicationRecord.method(:legacy_bulk_insert)
expect(::ApplicationRecord)
.to receive(:legacy_bulk_insert) do |table, rows, return_ids: false, disable_quote: [], on_conflict: nil|
call_count = table == Packages::Dependency.table_name ? 2 : 1
call_count.times { original_bulk_insert.call(table, rows, return_ids: return_ids, disable_quote: disable_quote, on_conflict: on_conflict) }
end.twice
expect(Packages::Dependency)
.to receive(:ids_for_package_names_and_version_patterns)
.twice
.and_call_original
expect { subject }
.to change { Packages::Dependency.count }.by(1)
.and change { Packages::DependencyLink.count }.by(1)
expect(dependency_names).to match_array(%w[express])
expect(dependency_link_types).to match_array(%w[dependencies])
end
end
context 'with existing dependencies' do
let(:other_package) { create(:npm_package) }
before do
described_class.new(other_package, dependencies).execute
end
it 'reuses them' do
expect { subject }
.to not_change { Packages::Dependency.count }
.and change { Packages::DependencyLink.count }.by(1)
end
end
context 'with a dependency not described with a hash' do
let(:invalid_dependencies) { dependencies.tap { |d| d['bundleDependencies'] = false } }
subject { described_class.new(package, invalid_dependencies).execute }
it 'creates dependencies and links' do
expect(Packages::Dependency)
.to receive(:ids_for_package_names_and_version_patterns)
.once
.and_call_original
expect { subject }
.to change { Packages::Dependency.count }.by(1)
.and change { Packages::DependencyLink.count }.by(1)
expect(dependency_names).to match_array(%w[express])
expect(dependency_link_types).to match_array(%w[dependencies])
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module MlModel
class CreatePackageFileService < BaseService
def execute
::Packages::Package.transaction do
package = find_or_create_package
find_or_create_model_version(package)
create_package_file(package)
end
end
private
def find_or_create_package
package_params = {
name: params[:package_name],
version: params[:package_version],
build: params[:build],
status: params[:status]
}
package = ::Packages::MlModel::FindOrCreatePackageService
.new(project, current_user, package_params)
.execute
package.update_column(:status, params[:status]) if params[:status] && params[:status] != package.status
package.create_build_infos!(params[:build])
package
end
def find_or_create_model_version(package)
model_version_params = {
model_name: package.name,
version: package.version,
package: package,
user: current_user
}
Ml::FindOrCreateModelVersionService.new(project, model_version_params).execute
end
def create_package_file(package)
file_params = {
file: params[:file],
size: params[:file].size,
file_sha256: params[:file].sha256,
file_name: params[:file_name],
build: params[:build]
}
::Packages::CreatePackageFileService.new(package, file_params).execute
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::MlModel::CreatePackageFileService, feature_category: :mlops do
describe '#execute' do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let_it_be(:pipeline) { create(:ci_pipeline, user: user, project: project) }
let_it_be(:file_name) { 'myfile.tar.gz.1' }
let(:build) { instance_double(Ci::Build, pipeline: pipeline) }
let(:sha256) { '440e5e148a25331bbd7991575f7d54933c0ebf6cc735a18ee5066ac1381bb590' }
let(:temp_file) { Tempfile.new("test") }
let(:file) { UploadedFile.new(temp_file.path, sha256: sha256) }
let(:package_service) { double }
subject(:execute_service) { described_class.new(project, user, params).execute }
before do
FileUtils.touch(temp_file)
end
after do
FileUtils.rm_f(temp_file)
end
context 'without existing package' do
let(:params) do
{
package_name: 'new_model',
package_version: '1.0.0',
file: file,
file_name: file_name
}
end
it 'creates package file', :aggregate_failures do
expect { execute_service }
.to change { Packages::MlModel::Package.count }.by(1)
.and change { Packages::PackageFile.count }.by(1)
.and change { Packages::PackageFileBuildInfo.count }.by(0)
.and change { Ml::ModelVersion.count }.by(1)
new_model = Packages::MlModel::Package.last
package_file = new_model.package_files.last
new_model_version = Ml::ModelVersion.last
expect(new_model.name).to eq('new_model')
expect(new_model.version).to eq('1.0.0')
expect(new_model.status).to eq('default')
expect(package_file.package).to eq(new_model)
expect(package_file.file_name).to eq(file_name)
expect(package_file.size).to eq(file.size)
expect(package_file.file_sha256).to eq(sha256)
expect(new_model_version.name).to eq('new_model')
expect(new_model_version.version).to eq('1.0.0')
expect(new_model_version.package).to eq(new_model)
end
end
context 'with existing package' do
let_it_be(:model) { create(:ml_model_package, creator: user, project: project, version: '0.1.0') }
let(:params) do
{
package_name: model.name,
package_version: model.version,
file: file,
file_name: file_name,
status: :hidden,
build: build
}
end
it 'adds the package file and updates status and ci_build', :aggregate_failures do
expect { execute_service }
.to change { project.packages.ml_model.count }.by(0)
.and change { model.package_files.count }.by(1)
.and change { Packages::PackageFileBuildInfo.count }.by(1)
model.reload
package_file = model.package_files.last
expect(model.build_infos.first.pipeline).to eq(build.pipeline)
expect(model.status).to eq('hidden')
expect(package_file.package).to eq(model)
expect(package_file.file_name).to eq(file_name)
expect(package_file.size).to eq(file.size)
expect(package_file.file_sha256).to eq(sha256)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module MlModel
class FindOrCreatePackageService < ::Packages::CreatePackageService
def execute
find_or_create_package!(::Packages::Package.package_types['ml_model'])
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::MlModel::FindOrCreatePackageService, feature_category: :mlops do
let_it_be(:project) { create(:project) }
let_it_be(:user) { project.creator }
let_it_be(:ci_build) { create(:ci_build, :running, user: user, project: project) }
let(:base_params) do
{
name: 'mymodel',
version: '0.0.1'
}
end
let(:params) { base_params }
describe '#execute' do
subject(:execute_service) { described_class.new(project, user, params).execute }
context 'when model does not exist' do
it 'creates the model' do
expect { subject }.to change { project.packages.ml_model.count }.by(1)
package = project.packages.ml_model.last
aggregate_failures do
expect(package.creator).to eq(user)
expect(package.package_type).to eq('ml_model')
expect(package.name).to eq('mymodel')
expect(package.version).to eq('0.0.1')
expect(package.build_infos.count).to eq(0)
end
end
context 'when build is provided' do
let(:params) { base_params.merge(build: ci_build) }
it 'creates package and package build info' do
expect { subject }.to change { project.packages.ml_model.count }.by(1)
package = project.packages.ml_model.last
aggregate_failures do
expect(package.creator).to eq(user)
expect(package.package_type).to eq('ml_model')
expect(package.name).to eq('mymodel')
expect(package.version).to eq('0.0.1')
expect(package.build_infos.first.pipeline).to eq(ci_build.pipeline)
end
end
end
end
context 'when model already exists' do
it 'does not create a new model', :aggregate_failures do
model = project.packages.ml_model.create!(params)
expect do
new_model = subject
expect(new_model).to eq(model)
end.not_to change { project.packages.ml_model.count }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Pypi
class CreatePackageService < ::Packages::CreatePackageService
include ::Gitlab::Utils::StrongMemoize
def execute
::Packages::Package.transaction do
meta = Packages::Pypi::Metadatum.new(
package: created_package,
required_python: params[:requires_python] || '',
metadata_version: params[:metadata_version],
author_email: params[:author_email],
description: params[:description]&.truncate(::Packages::Pypi::Metadatum::MAX_DESCRIPTION_LENGTH),
description_content_type: params[:description_content_type],
summary: params[:summary],
keywords: params[:keywords]
)
unless meta.valid?
raise ActiveRecord::RecordInvalid, meta
end
params.delete(:md5_digest) if Gitlab::FIPS.enabled?
Packages::Pypi::Metadatum.upsert(meta.attributes)
::Packages::CreatePackageFileService.new(created_package, file_params).execute
created_package
end
end
private
def created_package
find_or_create_package!(:pypi)
end
strong_memoize_attr :created_package
def file_params
{
build: params[:build],
file: params[:content],
file_name: params[:content].original_filename,
file_md5: params[:md5_digest],
file_sha256: params[:sha256_digest]
}
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Pypi::CreatePackageService, :aggregate_failures, feature_category: :package_registry do
include PackagesManagerApiSpecHelpers
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let(:sha256) { '1' * 64 }
let(:md5) { '567' }
let(:requires_python) { '>=2.7' }
let(:params) do
{
name: 'foo',
version: '1.0',
content: temp_file('foo.tgz'),
requires_python: requires_python,
sha256_digest: sha256,
md5_digest: md5
}
end
describe '#execute' do
subject { described_class.new(project, user, params).execute }
let(:created_package) { Packages::Package.pypi.last }
context 'without an existing package' do
it 'creates the package' do
expect { subject }.to change { Packages::Package.pypi.count }.by(1)
expect(created_package.name).to eq 'foo'
expect(created_package.version).to eq '1.0'
expect(created_package.pypi_metadatum.required_python).to eq '>=2.7'
expect(created_package.package_files.size).to eq 1
expect(created_package.package_files.first.file_name).to eq 'foo.tgz'
expect(created_package.package_files.first.file_sha256).to eq sha256
expect(created_package.package_files.first.file_md5).to eq md5
end
end
context 'with FIPS mode', :fips_mode do
it 'does not generate file_md5' do
expect { subject }.to change { Packages::Package.pypi.count }.by(1)
expect(created_package.name).to eq 'foo'
expect(created_package.version).to eq '1.0'
expect(created_package.pypi_metadatum.required_python).to eq '>=2.7'
expect(created_package.package_files.size).to eq 1
expect(created_package.package_files.first.file_name).to eq 'foo.tgz'
expect(created_package.package_files.first.file_sha256).to eq sha256
expect(created_package.package_files.first.file_md5).to be_nil
end
end
context 'without required_python' do
before do
params.delete(:requires_python)
end
it 'creates the package' do
expect { subject }.to change { Packages::Package.pypi.count }.by(1)
expect(created_package.pypi_metadatum.required_python).to eq ''
end
end
context 'with additional metadata' do
before do
params.merge!(
metadata_version: '2.3',
author_email: '[email protected], [email protected]',
description: 'Example description',
description_content_type: 'text/plain',
summary: 'A module for collecting votes from beagles.',
keywords: 'dog,puppy,voting,election'
)
end
it 'creates the package' do
expect { subject }.to change { Packages::Package.pypi.count }.by(1)
expect(created_package.pypi_metadatum.metadata_version).to eq('2.3')
expect(created_package.pypi_metadatum.author_email).to eq('[email protected], [email protected]')
expect(created_package.pypi_metadatum.description).to eq('Example description')
expect(created_package.pypi_metadatum.description_content_type).to eq('text/plain')
expect(created_package.pypi_metadatum.summary).to eq('A module for collecting votes from beagles.')
expect(created_package.pypi_metadatum.keywords).to eq('dog,puppy,voting,election')
end
end
context 'with a very long metadata description field' do
let(:max_length) { ::Packages::Pypi::Metadatum::MAX_DESCRIPTION_LENGTH }
let(:truncated_description) { ('x' * (max_length + 1)).truncate(max_length) }
before do
params.merge!(
description: 'x' * (max_length + 1)
)
end
it 'truncates the description field' do
expect { subject }.to change { Packages::Package.pypi.count }.by(1)
expect(created_package.pypi_metadatum.description).to eq(truncated_description)
end
end
context 'with an invalid metadata' do
let(:requires_python) { 'x' * 256 }
it 'raises an error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid)
end
end
it_behaves_like 'assigns the package creator' do
let(:package) { created_package }
end
it_behaves_like 'assigns build to package'
it_behaves_like 'assigns status to package'
context 'with an existing package' do
before do
described_class.new(project, user, params).execute
end
context 'with an existing file' do
before do
params[:content] = temp_file('foo.tgz')
params[:sha256_digest] = sha256
params[:md5_digest] = md5
end
it 'throws an error' do
expect { subject }
.to change { Packages::Package.pypi.count }.by(0)
.and change { Packages::PackageFile.count }.by(0)
.and raise_error(/File name has already been taken/)
end
context 'with a pending_destruction package' do
before do
Packages::Package.pypi.last.pending_destruction!
end
it 'creates a new package' do
expect { subject }
.to change { Packages::Package.pypi.count }.by(1)
.and change { Packages::PackageFile.count }.by(1)
expect(created_package.name).to eq 'foo'
expect(created_package.version).to eq '1.0'
expect(created_package.pypi_metadatum.required_python).to eq '>=2.7'
expect(created_package.package_files.size).to eq 1
expect(created_package.package_files.first.file_name).to eq 'foo.tgz'
expect(created_package.package_files.first.file_sha256).to eq sha256
expect(created_package.package_files.first.file_md5).to eq md5
end
end
end
context 'without an existing file' do
before do
params[:content] = temp_file('another.tgz')
end
it 'adds the file' do
expect { subject }
.to change { Packages::Package.pypi.count }.by(0)
.and change { Packages::PackageFile.count }.by(1)
expect(created_package.package_files.size).to eq 2
expect(created_package.package_files.map(&:file_name).sort).to eq ['another.tgz', 'foo.tgz']
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Go
class CreatePackageService < BaseService
GoZipSizeError = Class.new(StandardError)
attr_accessor :version
def initialize(project, user = nil, version:)
super(project, user)
@version = version
end
def execute
# check for existing package to avoid SQL errors due to the index
package = ::Packages::Go::PackageFinder.new(version.mod.project, version.mod.name, version.name).execute
return package if package
# this can be expensive, so do it outside the transaction
files = {}
files[:mod] = prepare_file(version, :mod, version.gomod)
files[:zip] = prepare_file(version, :zip, version.archive.string)
ApplicationRecord.transaction do
# create new package and files
package = create_package
files.each { |type, (file, digests)| create_file(package, type, file, digests) }
package
end
end
private
def prepare_file(version, type, content)
file = CarrierWaveStringFile.new(content)
raise GoZipSizeError, "#{version.mod.name}@#{version.name}.#{type} exceeds size limit" if file.size > project.actual_limits.golang_max_file_size
digests = {
sha1: Digest::SHA1.hexdigest(content),
sha256: Digest::SHA256.hexdigest(content)
}
digests[:md5] = Digest::MD5.hexdigest(content) unless Gitlab::FIPS.enabled?
[file, digests]
end
def create_package
version.mod.project.packages.create!(
name: version.mod.name,
version: version.name,
package_type: :golang,
created_at: version.commit.committed_date
)
end
def create_file(package, type, file, digests)
CreatePackageFileService.new(package,
file: file,
size: file.size,
file_name: "#{version.name}.#{type}",
file_md5: digests[:md5],
file_sha1: digests[:sha1],
file_sha256: digests[:sha256]
).execute
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Go::CreatePackageService, feature_category: :package_registry do
let_it_be(:project) { create :project_empty_repo, path: 'my-go-lib' }
let_it_be(:mod) { create :go_module, project: project }
before_all do
create :go_module_commit, :module, project: project, tag: 'v1.0.0'
end
shared_examples 'creates a package' do |files:|
it "returns a valid package with #{files ? files.to_s : 'no'} file(s)" do
expect(subject).to be_valid
expect(subject.name).to eq(version.mod.name)
expect(subject.version).to eq(version.name)
expect(subject.package_type).to eq('golang')
expect(subject.created_at).to eq(version.commit.committed_date)
expect(subject.package_files.count).to eq(files)
end
end
shared_examples 'creates a package file' do |type|
it "returns a package with a #{type} file" do
file_name = "#{version.name}.#{type}"
expect(subject.package_files.map { |f| f.file_name }).to include(file_name)
file = subject.package_files.with_file_name(file_name).first
expect(file).not_to be_nil
expect(file.file).not_to be_nil
expect(file.size).to eq(file.file.size)
expect(file.file_name).to eq(file_name)
expect(file.file_md5).not_to be_nil
expect(file.file_sha1).not_to be_nil
expect(file.file_sha256).not_to be_nil
end
context 'with FIPS mode', :fips_mode do
it 'does not generate file_md5' do
file_name = "#{version.name}.#{type}"
expect(subject.package_files.map { |f| f.file_name }).to include(file_name)
file = subject.package_files.with_file_name(file_name).first
expect(file).not_to be_nil
expect(file.file).not_to be_nil
expect(file.size).to eq(file.file.size)
expect(file.file_name).to eq(file_name)
expect(file.file_md5).to be_nil
expect(file.file_sha1).not_to be_nil
expect(file.file_sha256).not_to be_nil
end
end
end
describe '#execute' do
subject { described_class.new(project, nil, version: version).execute }
let(:version) { create :go_module_version, :tagged, mod: mod, name: 'v1.0.0' }
context 'with no existing package' do
it_behaves_like 'creates a package', files: 2
it_behaves_like 'creates a package file', :mod
it_behaves_like 'creates a package file', :zip
it 'creates a new package' do
expect { subject }
.to change { project.packages.count }.by(1)
.and change { Packages::PackageFile.count }.by(2)
end
end
context 'with an existing package' do
before do
described_class.new(project, version: version).execute
end
it_behaves_like 'creates a package', files: 2
it_behaves_like 'creates a package file', :mod
it_behaves_like 'creates a package file', :zip
it 'does not create a package or files' do
expect { subject }
.to not_change { project.packages.count }
.and not_change { Packages::PackageFile.count }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Go
class SyncPackagesService < BaseService
include Gitlab::Golang
def initialize(project, ref, path = '')
super(project)
@ref = ref
@path = path
raise ArgumentError, 'project is required' unless project
raise ArgumentError, 'ref is required' unless ref
raise ArgumentError, "ref #{ref} not found" unless project.repository.find_tag(ref) || project.repository.find_branch(ref)
end
def execute_async
Packages::Go::SyncPackagesWorker.perform_async(project.id, @ref, @path)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Go::SyncPackagesService, feature_category: :package_registry do
include_context 'basic Go module'
let(:params) { { info: true, mod: true, zip: true } }
describe '#execute_async' do
it 'schedules a package refresh' do
expect(::Packages::Go::SyncPackagesWorker).to receive(:perform_async).once
described_class.new(project, 'master').execute_async
end
end
describe '#initialize' do
context 'without a project' do
it 'raises an error' do
expect { described_class.new(nil, 'master') }
.to raise_error(ArgumentError, 'project is required')
end
end
context 'without a ref' do
it 'raises an error' do
expect { described_class.new(project, nil) }
.to raise_error(ArgumentError, 'ref is required')
end
end
context 'with an invalid ref' do
it 'raises an error' do
expect { described_class.new(project, 'not-a-ref') }
.to raise_error(ArgumentError)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class GenerateDistributionKeyService
include Gitlab::Utils::StrongMemoize
def initialize(params: {})
@params = params
end
def execute
using_pinentry do |ctx|
# Generate key
ctx.generate_key generate_key_params
key = ctx.keys.first # rubocop:disable Gitlab/KeysFirstAndValuesFirst
fingerprint = key.fingerprint
# Export private key
data = GPGME::Data.new
ctx.export_keys fingerprint, data, GPGME::EXPORT_MODE_SECRET
data.seek 0
private_key = data.read
# Export public key
data = GPGME::Data.new
ctx.export_keys fingerprint, data
data.seek 0
public_key = data.read
{
private_key: private_key,
public_key: public_key,
passphrase: passphrase,
fingerprint: fingerprint
}
end
end
private
attr_reader :params
def passphrase
params[:passphrase] || ::User.random_password
end
strong_memoize_attr :passphrase
def pinentry_script_content
escaped_passphrase = Shellwords.escape(passphrase)
<<~EOF
#!/bin/sh
echo OK Pleased to meet you
while read -r cmd; do
case "$cmd" in
GETPIN) echo D #{escaped_passphrase}; echo OK;;
*) echo OK;;
esac
done
EOF
end
def using_pinentry
Gitlab::Gpg.using_tmp_keychain do
home_dir = Gitlab::Gpg.current_home_dir
File.write("#{home_dir}/pinentry.sh", pinentry_script_content, mode: 'w', perm: 0755)
File.write("#{home_dir}/gpg-agent.conf", "pinentry-program #{home_dir}/pinentry.sh\n", mode: 'w')
GPGME::Ctx.new(armor: true, offline: true) do |ctx|
yield ctx
end
end
end
def generate_key_params
# https://www.gnupg.org/documentation/manuals/gnupg/Unattended-GPG-key-generation.html
'<GnupgKeyParms format="internal">' + "\n" +
{
'Key-Type': params[:key_type] || 'RSA',
'Key-Length': params[:key_length] || 4096,
'Key-Usage': params[:key_usage] || 'sign',
'Name-Real': params[:name_real] || 'GitLab Debian repository',
'Name-Email': params[:name_email] || Gitlab.config.gitlab.email_reply_to,
'Name-Comment': params[:name_comment] || 'GitLab Debian repository automatic signing key',
'Expire-Date': params[:expire_date] || 0,
Passphrase: passphrase
}.map { |k, v| "#{k}: #{v}\n" }.join +
'</GnupgKeyParms>'
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::GenerateDistributionKeyService, feature_category: :package_registry do
let(:params) { {} }
subject { described_class.new(params: params) }
let(:response) { subject.execute }
it 'returns an Hash', :aggregate_failures do
expect(GPGME::Ctx).to receive(:new).with(armor: true, offline: true).and_call_original
expect(User).to receive(:random_password).with(no_args).and_call_original
expect(response).to be_a Hash
expect(response.keys).to contain_exactly(:private_key, :public_key, :fingerprint, :passphrase)
expect(response[:private_key]).to start_with('-----BEGIN PGP PRIVATE KEY BLOCK-----')
expect(response[:public_key]).to start_with('-----BEGIN PGP PUBLIC KEY BLOCK-----')
expect(response[:fingerprint].length).to eq(40)
expect(response[:passphrase].length).to be > 10
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class UpdateDistributionService
def initialize(distribution, params)
@distribution = distribution
@params = params
@components = params.delete(:components)
@architectures = params.delete(:architectures)
@architectures += ['all'] unless @architectures.nil?
@errors = []
end
def execute
update_distribution
end
private
attr_reader :distribution, :params, :components, :architectures, :errors
def append_errors(record, prefix = '')
return if record.valid?
prefix = "#{prefix} " unless prefix.empty?
@errors += record.errors.full_messages.map { |message| "#{prefix}#{message}" }
end
def update_distribution
result = distribution.transaction do
if distribution.update(params)
update_components if components
update_architectures if architectures
success
else
append_errors(distribution)
error
end
end
result ||= error
::Packages::Debian::GenerateDistributionWorker.perform_async(distribution.class.container_type, distribution.id) if result.success?
result
end
def update_components
update_objects(distribution.components, components, error_label: 'Component')
end
def update_architectures
update_objects(distribution.architectures, architectures, error_label: 'Architecture')
end
def update_objects(objects, object_names_from_params, error_label:)
current_object_names = objects.map(&:name)
missing_object_names = object_names_from_params - current_object_names
extra_object_names = current_object_names - object_names_from_params
missing_object_names.each do |name|
new_object = objects.create(name: name)
append_errors(new_object, error_label)
raise ActiveRecord::Rollback unless new_object.persisted?
end
extra_object_names.each do |name|
object = objects.with_name(name).first
raise ActiveRecord::Rollback unless object.destroy
end
end
def success
ServiceResponse.success(payload: { distribution: distribution })
end
def error
ServiceResponse.error(message: errors.to_sentence, payload: { distribution: distribution })
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::UpdateDistributionService, feature_category: :package_registry do
RSpec.shared_examples 'Update Debian Distribution' do |expected_message, expected_components, expected_architectures, component_file_delta = 0|
it 'returns ServiceResponse', :aggregate_failures do
expect(distribution).to receive(:update).with(simple_params).and_call_original if expected_message.nil?
expect(::Packages::Debian::GenerateDistributionWorker).to receive(:perform_async).with(distribution.class.container_type, distribution.id).and_call_original if expected_message.nil?
expect(::Packages::Debian::GenerateDistributionWorker).not_to receive(:perform_async) unless expected_message.nil?
if component_file_delta.zero?
expect { response }
.to not_change { container.debian_distributions.klass.all.count }
.and not_change { container.debian_distributions.count }
.and not_change { component1.class.all.count }
.and not_change { architecture1.class.all.count }
.and not_change { component_file1.class.all.count }
else
expect { response }
.to not_change { container.debian_distributions.klass.all.count }
.and not_change { container.debian_distributions.count }
.and not_change { component1.class.all.count }
.and not_change { architecture1.class.all.count }
.and change { component_file1.class.all.count }
.from(4).to(4 + component_file_delta)
end
expect(response).to be_a(ServiceResponse)
expect(response.success?).to eq(expected_message.nil?)
expect(response.error?).to eq(!expected_message.nil?)
expect(response.message).to eq(expected_message)
expect(response.payload).to eq(distribution: distribution)
distribution.reload
distribution.components.reload
distribution.architectures.reload
if expected_message.nil?
simple_params.each_pair do |name, value|
expect(distribution.send(name)).to eq(value)
end
else
original_params.each_pair do |name, value|
expect(distribution.send(name)).to eq(value)
end
end
expect(distribution.components.map(&:name)).to contain_exactly(*expected_components)
expect(distribution.architectures.map(&:name)).to contain_exactly(*expected_architectures)
end
end
RSpec.shared_examples 'Debian Update Distribution Service' do |container_type, can_freeze|
context "with a Debian #{container_type} distribution" do
let_it_be(:container, freeze: can_freeze) { create(container_type) } # rubocop:disable Rails/SaveBang
let_it_be(:distribution, reload: true) { create("debian_#{container_type}_distribution", container: container) }
let_it_be(:component1) { create("debian_#{container_type}_component", distribution: distribution, name: 'component1') }
let_it_be(:component2) { create("debian_#{container_type}_component", distribution: distribution, name: 'component2') }
let_it_be(:architecture0) { create("debian_#{container_type}_architecture", distribution: distribution, name: 'all') }
let_it_be(:architecture1) { create("debian_#{container_type}_architecture", distribution: distribution, name: 'architecture1') }
let_it_be(:architecture2) { create("debian_#{container_type}_architecture", distribution: distribution, name: 'architecture2') }
let_it_be(:component_file1) { create("debian_#{container_type}_component_file", :sources, component: component1) }
let_it_be(:component_file2) { create("debian_#{container_type}_component_file", component: component1, architecture: architecture1) }
let_it_be(:component_file3) { create("debian_#{container_type}_component_file", :sources, component: component2) }
let_it_be(:component_file4) { create("debian_#{container_type}_component_file", component: component2, architecture: architecture2) }
let(:original_params) do
{
suite: nil,
origin: nil,
label: nil,
version: nil,
description: nil,
valid_time_duration_seconds: nil,
automatic: true,
automatic_upgrades: false
}
end
let(:params) { {} }
let(:simple_params) { params.except(:components, :architectures) }
subject { described_class.new(distribution, params) }
let(:response) { subject.execute }
context 'with valid simple params' do
let(:params) do
{
suite: 'my-suite',
origin: 'my-origin',
label: 'my-label',
version: '42.0',
description: 'my-description',
valid_time_duration_seconds: 7.days,
automatic: false,
automatic_upgrades: true
}
end
it_behaves_like 'Update Debian Distribution', nil, %w[component1 component2], %w[all architecture1 architecture2]
end
context 'with invalid simple params' do
let(:params) do
{
suite: 'suite erronée',
origin: 'origin erronée',
label: 'label erronée',
version: 'version erronée',
description: 'description erronée',
valid_time_duration_seconds: 1.hour
}
end
it_behaves_like 'Update Debian Distribution', 'Suite is invalid, Origin is invalid, Label is invalid, Version is invalid, and Valid time duration seconds must be greater than or equal to 86400', %w[component1 component2], %w[all architecture1 architecture2]
end
context 'with valid components and architectures' do
let(:params) do
{
suite: 'my-suite',
components: %w[component2 component3],
architectures: %w[architecture2 architecture3]
}
end
it_behaves_like 'Update Debian Distribution', nil, %w[component2 component3], %w[all architecture2 architecture3], -2
end
context 'with invalid components' do
let(:params) do
{
suite: 'my-suite',
components: %w[component2 erroné],
architectures: %w[architecture2 architecture3]
}
end
it_behaves_like 'Update Debian Distribution', 'Component Name is invalid', %w[component1 component2], %w[all architecture1 architecture2]
end
context 'with invalid architectures' do
let(:params) do
{
suite: 'my-suite',
components: %w[component2 component3],
architectures: %w[architecture2 erroné]
}
end
it_behaves_like 'Update Debian Distribution', 'Architecture Name is invalid', %w[component1 component2], %w[all architecture1 architecture2]
end
end
end
it_behaves_like 'Debian Update Distribution Service', :project, true
it_behaves_like 'Debian Update Distribution Service', :group, false
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class FindOrCreateIncomingService < ::Packages::CreatePackageService
def execute
find_or_create_package!(:debian, name: ::Packages::Debian::INCOMING_PACKAGE_NAME, version: nil)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::FindOrCreateIncomingService, feature_category: :package_registry do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
subject(:service) { described_class.new(project, user) }
describe '#execute' do
subject(:package) { service.execute }
context 'run once' do
it 'creates a new package', :aggregate_failures do
expect(package).to be_valid
expect(package.project_id).to eq(project.id)
expect(package.creator_id).to eq(user.id)
expect(package.name).to eq('incoming')
expect(package.version).to be_nil
expect(package.package_type).to eq('debian')
expect(package.debian_incoming?).to be_truthy
end
it_behaves_like 'assigns the package creator'
end
context 'run twice' do
let!(:package2) { service.execute }
it 'returns the same object' do
expect(package2.id).to eq(package.id)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
# Returns .deb file metadata
class ExtractDebMetadataService
CommandFailedError = Class.new(StandardError)
def initialize(file_path)
@file_path = file_path
end
def execute
unless success?
raise CommandFailedError, "The `#{cmd}` command failed (status: #{result.status}) with the following error:\n#{result.stderr}"
end
sections = ParseDebian822Service.new(result.stdout).execute
sections.each_value.first
end
private
def cmd
@cmd ||= begin
dpkg_deb_path = Gitlab.config.packages.dpkg_deb_path
[dpkg_deb_path, '--field', @file_path]
end
end
def result
@result ||= Gitlab::Popen.popen_with_detail(cmd)
end
def success?
result.status&.exitstatus == 0
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::ExtractDebMetadataService, feature_category: :package_registry do
subject { described_class.new(file_path) }
let(:file_name) { 'libsample0_1.2.3~alpha2_amd64.deb' }
let(:file_path) { "spec/fixtures/packages/debian/#{file_name}" }
context 'with correct file' do
it 'return as expected' do
expected = {
'Package' => 'libsample0',
'Source' => 'sample',
'Version' => '1.2.3~alpha2',
'Architecture' => 'amd64',
'Maintainer' => 'John Doe <[email protected]>',
'Installed-Size' => '7',
'Section' => 'libs',
'Priority' => 'optional',
'Multi-Arch' => 'same',
'Homepage' => 'https://gitlab.com/',
'Description' => "Some mostly empty lib\nUsed in GitLab tests.\n\nTesting another paragraph."
}
expect(subject.execute).to eq expected
end
end
context 'with incorrect file' do
let(:file_name) { 'README.md' }
it 'raise error' do
expect { subject.execute }.to raise_error(described_class::CommandFailedError, /is not a Debian format archive/i)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class CreatePackageFileService
def initialize(package:, current_user:, params: {})
@package = package
@current_user = current_user
@params = params
end
def execute
raise ArgumentError, "Invalid package" unless package.present?
raise ArgumentError, "Invalid user" unless current_user.present?
# Debian package file are first uploaded to incoming with empty metadata,
# and are moved later by Packages::Debian::ProcessPackageFileService
package_file = package.package_files.create!(
file: params[:file],
size: params[:file]&.size,
file_name: params[:file_name],
file_sha1: params[:file_sha1],
file_sha256: params[:file]&.sha256,
file_md5: params[:file_md5],
debian_file_metadatum_attributes: {
file_type: 'unknown',
architecture: nil,
fields: nil
}
)
if end_of_new_upload?
::Packages::Debian::ProcessPackageFileWorker.perform_async(
package_file.id,
params[:distribution],
params[:component]
)
end
package_file
end
private
attr_reader :package, :current_user, :params
def end_of_new_upload?
params[:distribution].present? || params[:file_name].end_with?('.changes')
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::CreatePackageFileService, feature_category: :package_registry do
include WorkhorseHelpers
let_it_be(:package) { create(:debian_incoming, without_package_files: true) }
let_it_be(:current_user) { create(:user) }
describe '#execute' do
let(:file_name) { 'libsample0_1.2.3~alpha2_amd64.deb' }
let(:fixture_path) { "spec/fixtures/packages/debian/#{file_name}" }
let(:params) { default_params }
let(:default_params) do
{
file: file,
file_name: file_name,
file_sha1: '54321',
file_md5: '12345'
}.with_indifferent_access
end
let(:service) { described_class.new(package: package, current_user: current_user, params: params) }
subject(:package_file) { service.execute }
shared_examples 'a valid deb' do |process_package_file_worker|
it 'creates a new package file', :aggregate_failures do
if process_package_file_worker
expect(::Packages::Debian::ProcessPackageFileWorker)
.to receive(:perform_async).with(an_instance_of(Integer), params[:distribution], params[:component])
else
expect(::Packages::Debian::ProcessPackageFileWorker).not_to receive(:perform_async)
end
expect(package_file).to be_valid
expect(package_file.file.read).to start_with('!<arch>')
expect(package_file.size).to eq(1124)
expect(package_file.file_name).to eq(file_name)
expect(package_file.file_sha1).to eq('54321')
expect(package_file.file_sha256).to eq('543212345')
expect(package_file.file_md5).to eq('12345')
expect(package_file.debian_file_metadatum).to be_valid
expect(package_file.debian_file_metadatum.file_type).to eq('unknown')
expect(package_file.debian_file_metadatum.architecture).to be_nil
expect(package_file.debian_file_metadatum.fields).to be_nil
end
end
shared_examples 'a valid changes' do
it 'creates a new package file', :aggregate_failures do
expect(::Packages::Debian::ProcessPackageFileWorker)
.to receive(:perform_async).with(an_instance_of(Integer), nil, nil)
expect(package_file).to be_valid
expect(package_file.file.read).to start_with('Format: 1.8')
expect(package_file.size).to eq(2422)
expect(package_file.file_name).to eq(file_name)
expect(package_file.file_sha1).to eq('54321')
expect(package_file.file_sha256).to eq('543212345')
expect(package_file.file_md5).to eq('12345')
expect(package_file.debian_file_metadatum).to be_valid
expect(package_file.debian_file_metadatum.file_type).to eq('unknown')
expect(package_file.debian_file_metadatum.architecture).to be_nil
expect(package_file.debian_file_metadatum.fields).to be_nil
end
end
context 'with temp file' do
let!(:file) do
upload_path = ::Packages::PackageFileUploader.workhorse_local_upload_path
file_path = upload_path + '/' + file_name
FileUtils.mkdir_p(upload_path)
File.write(file_path, File.read(fixture_path))
UploadedFile.new(file_path, filename: File.basename(file_path), sha256: '543212345')
end
it_behaves_like 'a valid deb'
context 'with a .changes file' do
let(:file_name) { 'sample_1.2.3~alpha2_amd64.changes' }
let(:fixture_path) { "spec/fixtures/packages/debian/#{file_name}" }
it_behaves_like 'a valid changes'
end
context 'with distribution' do
let(:params) { default_params.merge(distribution: 'unstable', component: 'main') }
it_behaves_like 'a valid deb', true
end
context 'when current_user is missing' do
let(:current_user) { nil }
it 'raises an error' do
expect { package_file }.to raise_error(ArgumentError, 'Invalid user')
end
end
end
context 'with remote file' do
let!(:fog_connection) do
stub_package_file_object_storage(direct_upload: true)
end
before do
allow_next_instance_of(UploadedFile) do |uploaded_file|
allow(uploaded_file).to receive(:sha256).and_return('543212345')
end
end
let(:tmp_object) do
fog_connection.directories.new(key: 'packages').files.create( # rubocop:disable Rails/SaveBang
key: "tmp/uploads/#{file_name}",
body: File.read(fixture_path)
)
end
let!(:file) { fog_to_uploaded_file(tmp_object) }
it_behaves_like 'a valid deb'
end
context 'when package is missing' do
let(:package) { nil }
let(:params) { {} }
it 'raises an error' do
expect { package_file }.to raise_error(ArgumentError, 'Invalid package')
end
end
context 'when params is empty' do
let(:params) { {} }
it 'raises an error' do
expect { package_file }.to raise_error(ActiveRecord::RecordInvalid)
end
end
context 'when file is missing' do
let(:file_name) { 'libsample0_1.2.3~alpha2_amd64.deb' }
let(:file) { nil }
it 'raises an error' do
expect { package_file }.to raise_error(ActiveRecord::RecordInvalid)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class CreateDistributionService
def initialize(container, user, params)
@container = container
@params = params
@params[:creator] = user
@components = params.delete(:components) || ['main']
@architectures = params.delete(:architectures) || ['amd64']
@architectures += ['all']
@distribution = nil
@errors = []
end
def execute
create_distribution
end
private
attr_reader :container, :params, :components, :architectures, :distribution, :errors
def append_errors(record, prefix = '')
return if record.valid?
prefix = "#{prefix} " unless prefix.empty?
@errors += record.errors.full_messages.map { |message| "#{prefix}#{message}" }
end
def create_distribution
@distribution = container.debian_distributions.new(params)
append_errors(distribution)
return error unless errors.empty?
result = distribution.transaction do
next unless distribution.save
create_components
create_architectures
success
end
result ||= error
::Packages::Debian::GenerateDistributionWorker.perform_async(distribution.class.container_type, distribution.reset.id) if result.success?
result
end
def create_components
create_objects(distribution.components, components, error_label: 'Component')
end
def create_architectures
create_objects(distribution.architectures, architectures, error_label: 'Architecture')
end
def create_objects(objects, object_names_from_params, error_label:)
object_names_from_params.each do |name|
new_object = objects.create(name: name)
append_errors(new_object, error_label)
raise ActiveRecord::Rollback unless new_object.persisted?
end
end
def success
ServiceResponse.success(payload: { distribution: distribution }, http_status: :created)
end
def error
ServiceResponse.error(message: errors.to_sentence, payload: { distribution: distribution })
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::CreateDistributionService, feature_category: :package_registry do
RSpec.shared_examples 'Create Debian Distribution' do |expected_message, expected_components, expected_architectures|
let_it_be(:container) { create(container_type) } # rubocop:disable Rails/SaveBang
it 'returns ServiceResponse', :aggregate_failures do
if expected_message.nil?
expect(::Packages::Debian::GenerateDistributionWorker).to receive(:perform_async).with(container_type, an_instance_of(Integer))
expect { response }
.to change { container.debian_distributions.klass.all.count }
.from(0).to(1)
.and change { container.debian_distributions.count }
.from(0).to(1)
.and change { container.debian_distributions.first&.components&.count }
.from(nil).to(expected_components.count)
.and change { container.debian_distributions.first&.architectures&.count }
.from(nil).to(expected_architectures.count)
.and not_change { Packages::Debian::ProjectComponentFile.count }
.and not_change { Packages::Debian::GroupComponentFile.count }
else
expect(::Packages::Debian::GenerateDistributionWorker).not_to receive(:perform_async)
expect { response }
.to not_change { container.debian_distributions.klass.all.count }
.and not_change { container.debian_distributions.count }
.and not_change { Packages::Debian::ProjectComponent.count }
.and not_change { Packages::Debian::GroupComponent.count }
.and not_change { Packages::Debian::ProjectArchitecture.count }
.and not_change { Packages::Debian::GroupArchitecture.count }
.and not_change { Packages::Debian::ProjectComponentFile.count }
.and not_change { Packages::Debian::GroupComponentFile.count }
end
expect(response).to be_a(ServiceResponse)
expect(response.success?).to eq(expected_message.nil?)
expect(response.error?).to eq(!expected_message.nil?)
expect(response.message).to eq(expected_message)
distribution = response.payload[:distribution]
expect(distribution.persisted?).to eq(expected_message.nil?)
expect(distribution.container).to eq(container)
expect(distribution.creator).to eq(user)
params.each_pair do |name, value|
expect(distribution.send(name)).to eq(value)
end
expect(distribution.components.map(&:name)).to contain_exactly(*expected_components)
expect(distribution.architectures.map(&:name)).to contain_exactly(*expected_architectures)
end
end
shared_examples 'Debian Create Distribution Service' do
context 'with only the codename param' do
let(:params) { { codename: 'my-codename' } }
it_behaves_like 'Create Debian Distribution', nil, %w[main], %w[all amd64]
end
context 'with codename, components and architectures' do
let(:params) do
{
codename: 'my-codename',
components: %w[contrib non-free],
architectures: %w[arm64]
}
end
it_behaves_like 'Create Debian Distribution', nil, %w[contrib non-free], %w[all arm64]
end
context 'with invalid suite' do
let(:params) do
{
codename: 'my-codename',
suite: 'erroné'
}
end
it_behaves_like 'Create Debian Distribution', 'Suite is invalid', %w[], %w[]
end
context 'with invalid component name' do
let(:params) do
{
codename: 'my-codename',
components: %w[before erroné after],
architectures: %w[arm64]
}
end
it_behaves_like 'Create Debian Distribution', 'Component Name is invalid', %w[before erroné], %w[]
end
context 'with invalid architecture name' do
let(:params) do
{
codename: 'my-codename',
components: %w[contrib non-free],
architectures: %w[before erroné after']
}
end
it_behaves_like 'Create Debian Distribution', 'Architecture Name is invalid', %w[contrib non-free], %w[before erroné]
end
end
let_it_be(:user) { create(:user) }
subject { described_class.new(container, user, params) }
let(:response) { subject.execute }
context 'within a projet' do
let_it_be(:container_type) { :project }
it_behaves_like 'Debian Create Distribution Service'
end
context 'within a group' do
let_it_be(:container_type) { :group }
it_behaves_like 'Debian Create Distribution Service'
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class ExtractChangesMetadataService
include Gitlab::Utils::StrongMemoize
ExtractionError = Class.new(StandardError)
def initialize(package_file)
@package_file = package_file
@entries = {}
end
def execute
{
file_type: file_type,
architecture: metadata[:architecture],
fields: fields,
files: files
}
rescue ActiveModel::ValidationError => e
raise ExtractionError, e.message
end
private
def metadata
::Packages::Debian::ExtractMetadataService.new(@package_file).execute
end
strong_memoize_attr :metadata
def file_type
metadata[:file_type]
end
def fields
metadata[:fields]
end
def files
raise ExtractionError, "is not a changes file" unless file_type == :changes
raise ExtractionError, "Files field is missing" if fields['Files'].blank?
raise ExtractionError, "Checksums-Sha1 field is missing" if fields['Checksums-Sha1'].blank?
raise ExtractionError, "Checksums-Sha256 field is missing" if fields['Checksums-Sha256'].blank?
init_entries_from_files
entries_from_checksums_sha1
entries_from_checksums_sha256
entries_from_package_files
@entries
end
strong_memoize_attr :files
def init_entries_from_files
each_lines_for('Files') do |line|
md5sum, size, section, priority, filename = line.split
entry = FileEntry.new(
filename: filename,
size: size.to_i,
md5sum: md5sum,
section: section,
priority: priority)
@entries[filename] = entry
end
end
def entries_from_checksums_sha1
each_lines_for('Checksums-Sha1') do |line|
sha1sum, size, filename = line.split
entry = @entries[filename]
raise ExtractionError, "#{filename} is listed in Checksums-Sha1 but not in Files" unless entry
raise ExtractionError, "Size for #{filename} in Files and Checksums-Sha1 differ" unless entry.size == size.to_i
entry.sha1sum = sha1sum
end
end
def entries_from_checksums_sha256
each_lines_for('Checksums-Sha256') do |line|
sha256sum, size, filename = line.split
entry = @entries[filename]
raise ExtractionError, "#{filename} is listed in Checksums-Sha256 but not in Files" unless entry
raise ExtractionError, "Size for #{filename} in Files and Checksums-Sha256 differ" unless entry.size == size.to_i
entry.sha256sum = sha256sum
end
end
def each_lines_for(field)
fields[field].split("\n").each do |line|
next if line.blank?
yield(line)
end
end
def entries_from_package_files
@entries.each do |filename, entry|
entry.package_file = ::Packages::PackageFileFinder.new(incoming, filename).execute!
entry.validate!
rescue ActiveRecord::RecordNotFound
raise ExtractionError, "#{filename} is listed in Files but was not uploaded"
end
end
def incoming
@package_file.package.project.packages.debian_incoming_package!
end
strong_memoize_attr(:incoming)
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::ExtractChangesMetadataService, feature_category: :package_registry do
describe '#execute' do
let_it_be(:incoming) { create(:debian_incoming) }
let_it_be(:temp_package) do
create(:debian_package, without_package_files: true, with_changes_file: true, project: incoming.project)
end
let(:source_file) { incoming.package_files.first }
let(:dsc_file) { incoming.package_files.second }
let(:changes_file) { temp_package.package_files.first }
let(:service) { described_class.new(changes_file) }
subject { service.execute }
context 'with valid package file' do
it 'extract metadata', :aggregate_failures do
expected_fields = { 'Architecture' => 'source amd64', 'Binary' => 'libsample0 sample-dev sample-udeb' }
expect(subject[:file_type]).to eq(:changes)
expect(subject[:architecture]).to be_nil
expect(subject[:fields]).to include(expected_fields)
expect(subject[:files].count).to eq(7)
end
end
context 'with invalid package file' do
let(:changes_file) { incoming.package_files.first }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "is not a changes file")
end
end
context 'with invalid metadata' do
let(:md5_dsc) { "#{dsc_file.file_md5} 671 libs optional sample_1.2.3~alpha2.dsc" }
let(:md5_source) { "#{source_file.file_md5} 864 libs optional sample_1.2.3~alpha2.tar.xz" }
let(:md5s) { "#{md5_dsc}\n#{md5_source}" }
let(:sha1_dsc) { "#{dsc_file.file_sha1} 671 sample_1.2.3~alpha2.dsc" }
let(:sha1_source) { "#{source_file.file_sha1} 864 sample_1.2.3~alpha2.tar.xz" }
let(:sha1s) { "#{sha1_dsc}\n#{sha1_source}" }
let(:sha256_dsc) { "#{dsc_file.file_sha256} 671 sample_1.2.3~alpha2.dsc" }
let(:sha256_source) { "#{source_file.file_sha256} 864 sample_1.2.3~alpha2.tar.xz" }
let(:sha256s) { "#{sha256_dsc}\n#{sha256_source}" }
let(:fields) { { 'Files' => md5s, 'Checksums-Sha1' => sha1s, 'Checksums-Sha256' => sha256s } }
let(:metadata) { { file_type: :changes, architecture: 'amd64', fields: fields } }
before do
allow_next_instance_of(::Packages::Debian::ExtractMetadataService) do |extract_metadata_service|
allow(extract_metadata_service).to receive(:execute).and_return(metadata)
end
end
context 'without Files field' do
let(:md5s) { nil }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Files field is missing")
end
end
context 'without Checksums-Sha1 field' do
let(:sha1s) { nil }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Checksums-Sha1 field is missing")
end
end
context 'without Checksums-Sha256 field' do
let(:sha256s) { nil }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Checksums-Sha256 field is missing")
end
end
context 'with file in Checksums-Sha1 but not in Files' do
let(:md5_dsc) { '' }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "sample_1.2.3~alpha2.dsc is listed in Checksums-Sha1 but not in Files")
end
end
context 'with different size in Checksums-Sha1' do
let(:sha1_dsc) { "#{dsc_file.file_sha1} 42 sample_1.2.3~alpha2.dsc" }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Size for sample_1.2.3~alpha2.dsc in Files and Checksums-Sha1 differ")
end
end
context 'with file in Checksums-Sha256 but not in Files' do
let(:md5_dsc) { '' }
let(:sha1_dsc) { '' }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "sample_1.2.3~alpha2.dsc is listed in Checksums-Sha256 but not in Files")
end
end
context 'with different size in Checksums-Sha256' do
let(:sha256_dsc) { "#{dsc_file.file_sha256} 42 sample_1.2.3~alpha2.dsc" }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Size for sample_1.2.3~alpha2.dsc in Files and Checksums-Sha256 differ")
end
end
context 'with file in Files but not in Checksums-Sha1' do
let(:sha1_dsc) { '' }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Validation failed: Sha1sum can't be blank")
end
end
context 'with file in Files but not in Checksums-Sha256' do
let(:sha256_dsc) { '' }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Validation failed: Sha256sum can't be blank")
end
end
context 'with invalid MD5' do
let(:md5_dsc) { '1234567890123456789012345678012 671 libs optional sample_1.2.3~alpha2.dsc' }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Validation failed: Md5sum mismatch for sample_1.2.3~alpha2.dsc: #{dsc_file.file_md5} != 1234567890123456789012345678012")
end
end
context 'with invalid SHA1' do
let(:sha1_dsc) { '1234567890123456789012345678901234567890 671 sample_1.2.3~alpha2.dsc' }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Validation failed: Sha1sum mismatch for sample_1.2.3~alpha2.dsc: #{dsc_file.file_sha1} != 1234567890123456789012345678901234567890")
end
end
context 'with invalid SHA256' do
let(:sha256_dsc) { '1234567890123456789012345678901234567890123456789012345678901234 671 sample_1.2.3~alpha2.dsc' }
it 'raise ArgumentError', :aggregate_failures do
expect { subject }.to raise_error(described_class::ExtractionError, "Validation failed: Sha256sum mismatch for sample_1.2.3~alpha2.dsc: #{dsc_file.file_sha256} != 1234567890123456789012345678901234567890123456789012345678901234")
end
end
end
context 'with missing package file' do
before do
incoming.package_files.first.destroy!
end
it 'raise ArgumentError' do
expect { subject }.to raise_error(described_class::ExtractionError, "sample_1.2.3~alpha2.tar.xz is listed in Files but was not uploaded")
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class ExtractMetadataService
include Gitlab::Utils::StrongMemoize
ExtractionError = Class.new(StandardError)
def initialize(package_file)
@package_file = package_file
end
def execute
raise ExtractionError, 'invalid package file' unless valid_package_file?
if file_type == :unsupported
raise ExtractionError, "unsupported file extension for file #{package_file.file_name}"
end
extract_metadata
end
private
attr_reader :package_file
def valid_package_file?
package_file && package_file.package&.debian? && !package_file.file.empty_size?
end
def file_type_basic
%i[dsc deb udeb buildinfo changes ddeb].each do |format|
return format if package_file.file_name.end_with?(".#{format}")
end
nil
end
def file_type_source
# https://manpages.debian.org/buster/dpkg-dev/dpkg-source.1.en.html#Format:_3.0_(quilt)
%i[gz bz2 lzma xz].each do |format|
return :source if package_file.file_name.end_with?(".tar.#{format}")
end
nil
end
def file_type
file_type_basic || file_type_source || :unsupported
end
strong_memoize_attr :file_type
def file_type_debian?
file_type == :deb || file_type == :udeb || file_type == :ddeb
end
def file_type_meta?
file_type == :dsc || file_type == :buildinfo || file_type == :changes
end
def fields
if file_type_debian?
package_file.file.use_open_file(unlink_early: false) do |file|
::Packages::Debian::ExtractDebMetadataService.new(file.file_path).execute
end
elsif file_type_meta?
package_file.file.use_open_file do |file|
::Packages::Debian::ParseDebian822Service.new(file.read).execute.each_value.first
end
end
end
strong_memoize_attr :fields
def extract_metadata
architecture = fields['Architecture'] if file_type_debian?
{
file_type: file_type,
architecture: architecture,
fields: fields
}
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::ExtractMetadataService, feature_category: :package_registry do
let(:service) { described_class.new(package_file) }
subject { service.execute }
RSpec.shared_context 'with Debian package file' do |trait|
let(:package_file) { create(:debian_package_file, trait) }
end
RSpec.shared_examples 'Test Debian ExtractMetadata Service' do |expected_file_type, expected_architecture, expected_fields|
it "returns file_type #{expected_file_type.inspect}, architecture #{expected_architecture.inspect} and fields #{expected_fields.nil? ? '' : 'including '}#{expected_fields.inspect}",
:aggregate_failures do
expect(subject[:file_type]).to eq(expected_file_type)
expect(subject[:architecture]).to eq(expected_architecture)
if expected_fields.nil?
expect(subject[:fields]).to be_nil
else
expect(subject[:fields]).to include(**expected_fields)
end
end
end
using RSpec::Parameterized::TableSyntax
context 'with valid file types' do
where(:case_name, :trait, :expected_file_type, :expected_architecture, :expected_fields) do
'with source' | :source | :source | nil | nil
'with dsc' | :dsc | :dsc | nil | { 'Binary' => 'sample-dev, libsample0, sample-udeb, sample-ddeb' }
'with deb' | :deb | :deb | 'amd64' | { 'Multi-Arch' => 'same' }
'with udeb' | :udeb | :udeb | 'amd64' | { 'Package' => 'sample-udeb' }
'with ddeb' | :ddeb | :ddeb | 'amd64' | { 'Package' => 'sample-ddeb' }
'with buildinfo' | :buildinfo | :buildinfo | nil | { 'Architecture' => 'amd64 source',
'Build-Architecture' => 'amd64' }
'with changes' | :changes | :changes | nil | { 'Architecture' => 'source amd64',
'Binary' => 'libsample0 sample-dev sample-udeb' }
end
with_them do
include_context 'with Debian package file', params[:trait] do
it_behaves_like 'Test Debian ExtractMetadata Service',
params[:expected_file_type],
params[:expected_architecture],
params[:expected_fields]
end
end
end
context 'with valid source extensions' do
where(:ext) do
%i[gz bz2 lzma xz]
end
with_them do
let(:package_file) do
create(:debian_package_file, :source, file_name: "myfile.tar.#{ext}",
file_fixture: 'spec/fixtures/packages/debian/sample_1.2.3~alpha2.tar.xz')
end
it_behaves_like 'Test Debian ExtractMetadata Service', :source
end
end
context 'with invalid source extensions' do
where(:ext) do
%i[gzip bzip2]
end
with_them do
let(:package_file) do
create(:debian_package_file, :source, file_name: "myfile.tar.#{ext}",
file_fixture: 'spec/fixtures/packages/debian/sample_1.2.3~alpha2.tar.xz')
end
it 'raises an error' do
expect do
subject
end.to raise_error(described_class::ExtractionError,
"unsupported file extension for file #{package_file.file_name}")
end
end
end
context 'with invalid file name' do
let(:package_file) { create(:debian_package_file, :invalid) }
it 'raises an error' do
expect do
subject
end.to raise_error(described_class::ExtractionError,
"unsupported file extension for file #{package_file.file_name}")
end
end
context 'with invalid package file' do
let(:package_file) { create(:conan_package_file) }
it 'raises an error' do
expect { subject }.to raise_error(described_class::ExtractionError, 'invalid package file')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class GenerateDistributionService
include Gitlab::Utils::StrongMemoize
include ExclusiveLeaseGuard
ONE_HOUR = 1.hour.freeze
# used by ExclusiveLeaseGuard
DEFAULT_LEASE_TIMEOUT = 1.hour.to_i.freeze
# From https://salsa.debian.org/ftp-team/dak/-/blob/991aaa27a7f7aa773bb9c0cf2d516e383d9cffa0/setup/core-init.d/080_metadatakeys#L9
METADATA_KEYS = %w[
Package
Source
Binary
Version
Essential
Installed-Size
Maintainer
Uploaders
Original-Maintainer
Build-Depends
Build-Depends-Indep
Build-Conflicts
Build-Conflicts-Indep
Architecture
Standards-Version
Format
Files
Dm-Upload-Allowed
Vcs-Browse
Vcs-Hg
Vcs-Darcs
Vcs-Svn
Vcs-Git
Vcs-Browser
Vcs-Arch
Vcs-Bzr
Vcs-Mtn
Vcs-Cvs
Checksums-Sha256
Checksums-Sha1
Replaces
Provides
Depends
Pre-Depends
Recommends
Suggests
Enhances
Conflicts
Breaks
Description
Origin
Bugs
Multi-Arch
Homepage
Tag
Package-Type
Installer-Menu-Item
].freeze
def initialize(distribution)
@distribution = distribution
@oldest_kept_generated_at = nil
@sha256 = []
end
def execute
try_obtain_lease do
@distribution.transaction do
# We consider `apt-get update` can take at most one hour
# We keep all generations younger than one hour
# and the previous generation
@oldest_kept_generated_at = @distribution.component_files.updated_before(release_date - ONE_HOUR).maximum(:updated_at)
generate_component_files
generate_release
destroy_old_component_files
end
end
end
private
def generate_component_files
@distribution.components.ordered_by_name.each do |component|
@distribution.architectures.ordered_by_name.each do |architecture|
generate_component_file(component, :packages, architecture, :deb)
generate_component_file(component, :di_packages, architecture, :udeb)
end
generate_component_file(component, :sources, nil, :dsc)
end
end
def generate_component_file(component, component_file_type, architecture, package_file_type)
paragraphs = @distribution.package_files
.preload_package
.preload_debian_file_metadata
.with_debian_component_name(component.name)
.with_debian_architecture_name(architecture&.name)
.with_debian_file_type(package_file_type)
.find_each
.map { |package_file| package_stanza_from_fields(package_file) }
reuse_or_create_component_file(component, component_file_type, architecture, paragraphs.join("\n"))
end
def package_stanza_from_fields(package_file)
[
METADATA_KEYS.map do |metadata_key|
metadata_name = metadata_key
metadata_value = package_file.debian_fields[metadata_key]
if package_file.debian_dsc?
metadata_name = 'Package' if metadata_key == 'Source'
checksum = case metadata_key
when 'Files' then package_file.file_md5
when 'Checksums-Sha256' then package_file.file_sha256
when 'Checksums-Sha1' then package_file.file_sha1
end
if checksum
metadata_value = "\n#{checksum} #{package_file.size} #{package_file.file_name}#{metadata_value}"
end
end
rfc822_field(metadata_name, metadata_value)
end,
rfc822_field('Section', package_file.debian_fields['Section'] || 'misc'),
rfc822_field('Priority', package_file.debian_fields['Priority'] || 'extra'),
package_file_extra_fields(package_file)
].flatten.compact.join('')
end
def package_file_extra_fields(package_file)
if package_file.debian_dsc?
[
rfc822_field('Directory', package_dirname(package_file))
]
else
# NB: MD5sum was removed for FIPS compliance
[
rfc822_field('Filename', "#{package_dirname(package_file)}/#{package_file.file_name}"),
rfc822_field('Size', package_file.size),
rfc822_field('SHA256', package_file.file_sha256)
]
end
end
def package_dirname(package_file)
letter = package_file.package.name.start_with?('lib') ? package_file.package.name[0..3] : package_file.package.name[0]
"#{pool_prefix(package_file)}/#{letter}/#{package_file.package.name}/#{package_file.package.version}"
end
def pool_prefix(package_file)
case @distribution
when ::Packages::Debian::GroupDistribution
"pool/#{@distribution.codename}/#{package_file.package.project_id}"
else
"pool/#{@distribution.codename}"
end
end
def reuse_or_create_component_file(component, component_file_type, architecture, content)
file_sha256 = Digest::SHA256.hexdigest(content)
component_files = component.files
.with_file_type(component_file_type)
.with_architecture(architecture)
.with_compression_type(nil)
.order_updated_asc
component_file = component_files.with_file_sha256(file_sha256).last
last_component_file = component_files.last
if content.empty? && (!last_component_file || last_component_file.file_sha256 == file_sha256)
# Do not create empty component file for empty content
# when there is no last component file or when the last component file is empty too
component_file = last_component_file || component.files.build(
updated_at: release_date,
file_type: component_file_type,
architecture: architecture,
compression_type: nil,
size: 0
)
elsif component_file
# Reuse existing component file
component_file.touch(time: release_date)
else
# Create a new component file
component_file = component.files.create!(
updated_at: release_date,
file_type: component_file_type,
architecture: architecture,
compression_type: nil,
file: CarrierWaveStringFile.new(content),
file_sha256: file_sha256,
size: content.bytesize
)
end
@sha256.append(" #{file_sha256} #{component_file.size.to_s.rjust(8)} #{component_file.relative_path}")
end
def generate_release
@distribution.key || @distribution.create_key(GenerateDistributionKeyService.new.execute)
@distribution.file = CarrierWaveStringFile.new(release_content)
@distribution.file_signature = SignDistributionService.new(@distribution, release_content, detach: true).execute
@distribution.signed_file = CarrierWaveStringFile.new(
SignDistributionService.new(@distribution, release_content).execute
)
@distribution.updated_at = release_date
@distribution.save!
end
def release_content
release_header + release_sums
end
strong_memoize_attr :release_content
def release_header
[
%w[origin label suite version codename].map do |attribute|
rfc822_field(attribute.capitalize, @distribution.attributes[attribute])
end,
rfc822_field('Date', release_date.to_formatted_s(:rfc822)),
valid_until_field,
rfc822_field('NotAutomatic', [email protected], [email protected]),
rfc822_field('ButAutomaticUpgrades', @distribution.automatic_upgrades, [email protected] && @distribution.automatic_upgrades),
rfc822_field('Acquire-By-Hash', 'yes'),
rfc822_field('Architectures', @distribution.architectures.map { |architecture| architecture.name }.sort.join(' ')),
rfc822_field('Components', @distribution.components.map { |component| component.name }.sort.join(' ')),
rfc822_field('Description', @distribution.description)
].flatten.compact.join('')
end
def release_date
Time.now.utc
end
strong_memoize_attr :release_date
def release_sums
# NB: MD5Sum was removed for FIPS compliance
["SHA256:", @sha256].flatten.compact.join("\n") + "\n"
end
def rfc822_field(name, value, condition = true)
return unless condition
return if value.blank?
value = " #{value}" unless value[0] == "\n"
"#{name}:#{value.to_s.gsub("\n\n", "\n.\n").gsub("\n", "\n ")}\n"
end
def valid_until_field
return unless @distribution.valid_time_duration_seconds
rfc822_field('Valid-Until', release_date.since(@distribution.valid_time_duration_seconds).to_formatted_s(:rfc822))
end
def destroy_old_component_files
return if @oldest_kept_generated_at.nil?
@distribution.component_files.updated_before(@oldest_kept_generated_at).destroy_all # rubocop:disable Cop/DestroyAll
end
# used by ExclusiveLeaseGuard
def lease_key
"packages:debian:generate_distribution_service:#{@distribution.class.container_type}_distribution:#{@distribution.id}"
end
# used by ExclusiveLeaseGuard
def lease_timeout
DEFAULT_LEASE_TIMEOUT
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::GenerateDistributionService, feature_category: :package_registry do
include_context 'with published Debian package'
let(:service) { described_class.new(distribution) }
[:project, :group].each do |container_type|
context "for #{container_type}" do
include_context 'with Debian distribution', container_type
describe '#execute' do
subject { service.execute }
let(:subject2) { described_class.new(distribution).execute }
let(:subject3) { described_class.new(distribution).execute }
it_behaves_like 'Generate Debian Distribution and component files'
end
describe '#lease_key' do
subject { service.send(:lease_key) }
let(:prefix) { "packages:debian:generate_distribution_service:" }
it 'returns an unique key' do
is_expected.to eq "#{prefix}#{container_type}_distribution:#{distribution.id}"
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
# Parse String as Debian RFC822 control data format
# https://manpages.debian.org/unstable/dpkg-dev/deb822.5
class ParseDebian822Service
InvalidDebian822Error = Class.new(StandardError)
def initialize(input)
@input = input
end
def execute
output = {}
@input.each_line('', chomp: true) do |block|
section = {}
section_name, field = nil
block.each_line(chomp: true) do |line|
next if comment_line?(line)
if continuation_line?(line)
raise InvalidDebian822Error, "Parse error. Unexpected continuation line" if field.nil?
section[field] += "\n"
section[field] += line[1..] unless paragraph_separator?(line)
elsif match = match_section_line(line)
section_name = match[:name] if section_name.nil?
field = match[:field]
raise InvalidDebian822Error, "Duplicate field '#{field}' in section '#{section_name}'" if section.include?(field)
section[field] = match[:value]
else
raise InvalidDebian822Error, "Parse error on line #{line}"
end
end
raise InvalidDebian822Error, "Duplicate section '#{section_name}'" if output[section_name]
output[section_name] = section
end
output
end
private
def comment_line?(line)
line.match?(/^#/)
end
def continuation_line?(line)
line.match?(/^ /)
end
def paragraph_separator?(line)
line == ' .'
end
def match_section_line(line)
line.match(/(?<name>(?<field>^\S+):\s*(?<value>.*))/)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::ParseDebian822Service, feature_category: :package_registry do
subject { described_class.new(input) }
context 'with dpkg-deb --field output' do
let(:input) do
<<~HEREDOC
Package: libsample0
Source: sample
Version: 1.2.3~alpha2
Architecture: amd64
Maintainer: John Doe <[email protected]>
Installed-Size: 9
Section: libs
Priority: optional
Multi-Arch: same
Homepage: https://gitlab.com/
Description: Some mostly empty lib
Used in GitLab tests.
.
Testing another paragraph.
HEREDOC
end
it 'return as expected, preserving order' do
expected = {
'Package: libsample0' => {
'Package' => 'libsample0',
'Source' => 'sample',
'Version' => '1.2.3~alpha2',
'Architecture' => 'amd64',
'Maintainer' => 'John Doe <[email protected]>',
'Installed-Size' => '9',
'Section' => 'libs',
'Priority' => 'optional',
'Multi-Arch' => 'same',
'Homepage' => 'https://gitlab.com/',
'Description' => "Some mostly empty lib\nUsed in GitLab tests.\n\nTesting another paragraph."
}
}
expect(subject.execute.to_s).to eq(expected.to_s)
end
end
context 'with control file' do
let(:input) { fixture_file('packages/debian/sample/debian/control') }
it 'return as expected, preserving order' do
expected = {
'Source: sample' => {
'Source' => 'sample',
'Priority' => 'optional',
'Maintainer' => 'John Doe <[email protected]>',
'Build-Depends' => 'debhelper-compat (= 13)',
'Standards-Version' => '4.5.0',
'Section' => 'libs',
'Homepage' => 'https://gitlab.com/',
# 'Vcs-Browser' => 'https://salsa.debian.org/debian/sample-1.2.3',
# '#Vcs-Git' => 'https://salsa.debian.org/debian/sample-1.2.3.git',
'Rules-Requires-Root' => 'no'
},
'Package: sample-dev' => {
'Package' => 'sample-dev',
'Section' => 'libdevel',
'Architecture' => 'any',
'Multi-Arch' => 'same',
'Depends' => 'libsample0 (= ${binary:Version}), ${misc:Depends}',
'Description' => "Some mostly empty development files\nUsed in GitLab tests.\n\nTesting another paragraph."
},
'Package: libsample0' => {
'Package' => 'libsample0',
'Architecture' => 'any',
'Multi-Arch' => 'same',
'Depends' => '${shlibs:Depends}, ${misc:Depends}',
'Description' => "Some mostly empty lib\nUsed in GitLab tests.\n\nTesting another paragraph."
},
'Package: sample-udeb' => {
'Package' => 'sample-udeb',
'Package-Type' => 'udeb',
'Architecture' => 'any',
'Depends' => 'installed-base',
'Description' => 'Some mostly empty udeb'
},
'Package: sample-ddeb' => {
'Package' => 'sample-ddeb',
'Architecture' => 'any',
'Description' => 'Some fake Ubuntu ddeb'
}
}
expect(subject.execute.to_s).to eq(expected.to_s)
end
end
context 'with empty input' do
let(:input) { '' }
it 'return a empty hash' do
expect(subject.execute).to eq({})
end
end
context 'with unexpected continuation line' do
let(:input) { ' continuation' }
it 'raise error' do
expect { subject.execute }.to raise_error(described_class::InvalidDebian822Error, 'Parse error. Unexpected continuation line')
end
end
context 'with duplicate field' do
let(:input) do
<<~HEREDOC
Package: libsample0
Source: sample
Source: sample
HEREDOC
end
it 'raise error' do
expect { subject.execute }.to raise_error(described_class::InvalidDebian822Error, "Duplicate field 'Source' in section 'Package: libsample0'")
end
end
context 'with incorrect input' do
let(:input) do
<<~HEREDOC
Hello
HEREDOC
end
it 'raise error' do
expect { subject.execute }.to raise_error(described_class::InvalidDebian822Error, 'Parse error on line Hello')
end
end
context 'with duplicate section' do
let(:input) do
<<~HEREDOC
Package: libsample0
Package: libsample0
HEREDOC
end
it 'raise error' do
expect { subject.execute }.to raise_error(described_class::InvalidDebian822Error, "Duplicate section 'Package: libsample0'")
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class SignDistributionService
include Gitlab::Utils::StrongMemoize
def initialize(distribution, content, detach: false)
@distribution = distribution
@content = content
@detach = detach
end
def execute
raise ArgumentError, 'distribution key is missing' unless @distribution.key
sig_mode = GPGME::GPGME_SIG_MODE_CLEAR
sig_mode = GPGME::GPGME_SIG_MODE_DETACH if @detach
Gitlab::Gpg.using_tmp_keychain do
GPGME::Ctx.new(
armor: true,
offline: true,
pinentry_mode: GPGME::PINENTRY_MODE_LOOPBACK,
password: @distribution.key.passphrase
) do |ctx|
ctx.import(GPGME::Data.from_str(@distribution.key.public_key))
ctx.import(GPGME::Data.from_str(@distribution.key.private_key))
signature = GPGME::Data.new
ctx.sign(GPGME::Data.from_str(@content), signature, sig_mode)
signature.to_s
end
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::SignDistributionService, feature_category: :package_registry do
let_it_be(:group) { create(:group, :public) }
let(:content) { FFaker::Lorem.paragraph }
let(:service) { described_class.new(distribution, content, detach: detach) }
shared_examples 'Sign Distribution' do |container_type, detach: false|
context "for #{container_type} detach=#{detach}" do
let(:detach) { detach }
if container_type == :group
let_it_be(:distribution) { create('debian_group_distribution', container: group) }
else
let_it_be(:project) { create(:project, group: group) }
let_it_be(:distribution) { create('debian_project_distribution', container: project) }
end
describe '#execute' do
subject { service.execute }
context 'without an existing key' do
it 'raises ArgumentError', :aggregate_failures do
expect { subject }
.to raise_error(ArgumentError, 'distribution key is missing')
end
end
context 'with an existing key' do
let!(:key) { create("debian_#{container_type}_distribution_key", distribution: distribution) }
it 'returns the content signed', :aggregate_failures do
expect(Packages::Debian::GenerateDistributionKeyService).not_to receive(:new)
key_class = "Packages::Debian::#{container_type.capitalize}DistributionKey".constantize
expect { subject }
.to not_change { key_class.count }
if detach
expect(subject).to start_with("-----BEGIN PGP SIGNATURE-----\n")
else
expect(subject).to start_with("-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\n#{content}\n-----BEGIN PGP SIGNATURE-----\n")
end
expect(subject).to end_with("\n-----END PGP SIGNATURE-----\n")
end
end
end
end
end
it_behaves_like 'Sign Distribution', :project
it_behaves_like 'Sign Distribution', :project, detach: true
it_behaves_like 'Sign Distribution', :group
it_behaves_like 'Sign Distribution', :group, detach: true
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Debian
class ProcessPackageFileService
include ExclusiveLeaseGuard
include Gitlab::Utils::StrongMemoize
SOURCE_FIELD_SPLIT_REGEX = /[ ()]/
# used by ExclusiveLeaseGuard
DEFAULT_LEASE_TIMEOUT = 1.hour.to_i.freeze
SIMPLE_DEB_FILE_TYPES = %i[deb udeb ddeb].freeze
def initialize(package_file, distribution_name, component_name)
@package_file = package_file
@distribution_name = distribution_name
@component_name = component_name
end
def execute
return if @package_file.package.pending_destruction?
validate!
try_obtain_lease do
distribution.transaction do
rename_package_and_set_version
update_package
update_files_metadata if changes_file?
update_file_metadata
cleanup_temp_package
end
::Packages::Debian::GenerateDistributionWorker.perform_async(:project, package.debian_distribution.id)
end
end
private
def validate!
raise ArgumentError, 'package file without Debian metadata' unless @package_file.debian_file_metadatum
raise ArgumentError, 'already processed package file' unless @package_file.debian_file_metadatum.unknown?
changes_file? ? validate_changes_file! : validate_package_file!
end
def changes_file?
@package_file.file_name.end_with?('.changes')
end
def validate_changes_file!
raise ArgumentError, 'unwanted distribution name' unless @distribution_name.nil?
raise ArgumentError, 'unwanted component name' unless @component_name.nil?
raise ArgumentError, 'missing Source field' unless file_metadata.dig(:fields, 'Source').present?
raise ArgumentError, 'missing Version field' unless file_metadata.dig(:fields, 'Version').present?
raise ArgumentError, 'missing Distribution field' unless file_metadata.dig(:fields, 'Distribution').present?
end
def validate_package_file!
raise ArgumentError, 'missing distribution name' unless @distribution_name.present?
raise ArgumentError, 'missing component name' unless @component_name.present?
return if SIMPLE_DEB_FILE_TYPES.include?(file_metadata[:file_type])
raise ArgumentError, "invalid package file type: #{file_metadata[:file_type]}"
end
def file_metadata
metadata_service_class.new(@package_file).execute
end
strong_memoize_attr :file_metadata
def metadata_service_class
changes_file? ? ::Packages::Debian::ExtractChangesMetadataService : ::Packages::Debian::ExtractMetadataService
end
def distribution
Packages::Debian::DistributionsFinder.new(
@package_file.package.project,
codename_or_suite: package_distribution
).execute.last!
end
strong_memoize_attr :distribution
def package_distribution
return file_metadata[:fields]['Distribution'] if changes_file?
@distribution_name
end
def package
packages = temp_package.project
.packages
.existing_debian_packages_with(name: package_name, version: package_version)
package = packages.with_debian_codename_or_suite(package_distribution)
.first
unless package
package_in_other_distribution = packages.first
if package_in_other_distribution
raise ArgumentError, "Debian package #{package_name} #{package_version} exists " \
"in distribution #{package_in_other_distribution.debian_distribution.codename}"
end
end
package || temp_package
end
strong_memoize_attr :package
def temp_package
@package_file.package
end
strong_memoize_attr :temp_package
def package_name
return file_metadata[:fields]['Source'] if changes_file?
package_name_and_version[0]
end
def package_version
return file_metadata[:fields]['Version'] if changes_file?
package_name_and_version[1]
end
def package_name_and_version
package_name = file_metadata[:fields]['Package']
package_version = file_metadata[:fields]['Version']
if file_metadata[:fields]['Source']
# "sample" or "sample (1.2.3~alpha2)"
source_field_parts = file_metadata[:fields]['Source'].split(SOURCE_FIELD_SPLIT_REGEX)
package_name = source_field_parts[0]
package_version = source_field_parts[2] || package_version
end
[package_name, package_version]
end
strong_memoize_attr :package_name_and_version
def rename_package_and_set_version
package.update!(
name: package_name,
version: package_version,
status: :default
)
end
def update_package
return unless using_temporary_package?
package.update!(
debian_publication_attributes: { distribution_id: distribution.id }
)
end
def using_temporary_package?
package.id == temp_package.id
end
def update_files_metadata
file_metadata[:files].each do |_, entry|
file_metadata = ::Packages::Debian::ExtractMetadataService.new(entry.package_file).execute
::Packages::UpdatePackageFileService.new(entry.package_file, package_id: package.id)
.execute
# Force reload from database, as package has changed
entry.package_file.reload_package
entry.package_file.debian_file_metadatum.update!(
file_type: file_metadata[:file_type],
component: entry.component,
architecture: file_metadata[:architecture],
fields: file_metadata[:fields]
)
end
end
def update_file_metadata
::Packages::UpdatePackageFileService.new(@package_file, package_id: package.id)
.execute
# Force reload from database, as package has changed
@package_file.reload_package
@package_file.debian_file_metadatum.update!(
file_type: file_metadata[:file_type],
component: @component_name,
architecture: file_metadata[:architecture],
fields: file_metadata[:fields]
)
end
def cleanup_temp_package
temp_package.destroy unless using_temporary_package?
end
# used by ExclusiveLeaseGuard
def lease_key
"packages:debian:process_package_file_service:#{temp_package.project_id}_#{package_name}_#{package_version}"
end
# used by ExclusiveLeaseGuard
def lease_timeout
DEFAULT_LEASE_TIMEOUT
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Debian::ProcessPackageFileService, feature_category: :package_registry do
include ExclusiveLeaseHelpers
let_it_be(:distribution) { create(:debian_project_distribution, :with_file, suite: 'unstable') }
let(:debian_file_metadatum) { package_file.debian_file_metadatum }
let(:service) { described_class.new(package_file, distribution_name, component_name) }
describe '#execute' do
using RSpec::Parameterized::TableSyntax
subject { service.execute }
shared_examples 'common validations' do
context 'with package file without Debian metadata' do
let!(:package_file) { create(:debian_package_file, without_loaded_metadatum: true) }
let(:expected_error) { ArgumentError }
let(:expected_message) { 'package file without Debian metadata' }
it_behaves_like 'raises error'
end
context 'with already processed package file' do
let!(:package_file) { create(:debian_package_file) }
let(:expected_error) { ArgumentError }
let(:expected_message) { 'already processed package file' }
it_behaves_like 'raises error'
end
context 'without a distribution' do
let(:expected_error) { ActiveRecord::RecordNotFound }
let(:expected_message) { /^Couldn't find Packages::Debian::ProjectDistribution with / }
before do
# Workaround ActiveRecord cache
Packages::Debian::ProjectDistribution.find(distribution.id).delete
end
it_behaves_like 'raises error'
end
context 'when there is a matching published package in another distribution' do
let!(:matching_package) do
create(
:debian_package,
project: distribution.project,
name: 'sample',
version: '1.2.3~alpha2'
)
end
let(:expected_error) { ArgumentError }
let(:expected_message) do
"Debian package sample 1.2.3~alpha2 exists in distribution #{matching_package.debian_distribution.codename}"
end
it_behaves_like 'raises error'
end
end
shared_examples 'raises error' do
it 'raises error', :aggregate_failures do
expect(::Packages::Debian::GenerateDistributionWorker).not_to receive(:perform_async)
expect { subject }
.to not_change(Packages::Package, :count)
.and not_change(Packages::PackageFile, :count)
.and not_change { Packages::Debian::Publication.count }
.and not_change(package.package_files, :count)
.and not_change { package.reload.name }
.and not_change { package.version }
.and not_change { package.status }
.and not_change { debian_file_metadatum&.reload&.file_type }
.and not_change { debian_file_metadatum&.component }
.and raise_error(expected_error, expected_message)
end
end
shared_examples 'does nothing' do
it 'does nothing', :aggregate_failures do
expect(::Packages::Debian::GenerateDistributionWorker).not_to receive(:perform_async)
expect { subject }
.to not_change(Packages::Package, :count)
.and not_change(Packages::PackageFile, :count)
.and not_change { Packages::Debian::Publication.count }
.and not_change(package.package_files, :count)
.and not_change { package.reload.name }
.and not_change { package.version }
.and not_change { package.status }
.and not_change { debian_file_metadatum&.reload&.file_type }
.and not_change { debian_file_metadatum&.component }
end
end
shared_examples 'updates package and changes file' do
it 'updates package and changes file', :aggregate_failures do
expect(::Packages::Debian::GenerateDistributionWorker)
.to receive(:perform_async).with(:project, distribution.id)
expect { subject }
.to not_change(Packages::Package, :count)
.and not_change(Packages::PackageFile, :count)
.and change { Packages::Debian::Publication.count }.by(1)
.and change { package.package_files.count }.from(1).to(8)
.and change { package.reload.name }.to('sample')
.and change { package.version }.to('1.2.3~alpha2')
.and change { package.status }.from('processing').to('default')
.and change { package.debian_publication }.from(nil)
.and change { debian_file_metadatum.file_type }.from('unknown').to('changes')
.and not_change { debian_file_metadatum.component }
end
end
shared_examples 'updates package and package file' do
it 'updates package and package file', :aggregate_failures do
expect(::Packages::Debian::GenerateDistributionWorker)
.to receive(:perform_async).with(:project, distribution.id)
expect { subject }
.to not_change(Packages::Package, :count)
.and not_change(Packages::PackageFile, :count)
.and change { Packages::Debian::Publication.count }.by(1)
.and not_change(package.package_files, :count)
.and change { package.reload.name }.to('sample')
.and change { package.version }.to('1.2.3~alpha2')
.and change { package.status }.from('processing').to('default')
.and change { package.debian_publication }.from(nil)
.and change { debian_file_metadatum.file_type }.from('unknown').to(expected_file_type)
.and change { debian_file_metadatum.component }.from(nil).to(component_name)
end
end
context 'with a changes file' do
let!(:incoming) { create(:debian_incoming, project: distribution.project) }
let!(:temporary_with_changes) { create(:debian_temporary_with_changes, project: distribution.project) }
let(:package) { temporary_with_changes }
let(:package_file) { temporary_with_changes.package_files.first }
let(:distribution_name) { nil }
let(:component_name) { nil }
it_behaves_like 'common validations'
context 'with distribution_name' do
let(:distribution_name) { distribution.codename }
let(:expected_error) { ArgumentError }
let(:expected_message) { 'unwanted distribution name' }
it_behaves_like 'raises error'
end
context 'with component_name' do
let(:component_name) { 'main' }
let(:expected_error) { ArgumentError }
let(:expected_message) { 'unwanted component name' }
it_behaves_like 'raises error'
end
context 'with crafted file_metadata' do
let(:complete_file_metadata) do
{
file_type: :changes,
fields: {
'Source' => 'abc',
'Version' => '1.0',
'Distribution' => 'sid'
}
}
end
let(:expected_error) { ArgumentError }
before do
allow_next_instance_of(::Packages::Debian::ExtractChangesMetadataService) do |extract_changes_metadata_svc|
allow(extract_changes_metadata_svc).to receive(:execute).and_return(file_metadata)
end
end
context 'with missing Source field' do
let(:file_metadata) { complete_file_metadata.tap { |m| m[:fields].delete 'Source' } }
let(:expected_message) { 'missing Source field' }
it_behaves_like 'raises error'
end
context 'with missing Version field' do
let(:file_metadata) { complete_file_metadata.tap { |m| m[:fields].delete 'Version' } }
let(:expected_message) { 'missing Version field' }
it_behaves_like 'raises error'
end
context 'with missing Distribution field' do
let(:file_metadata) { complete_file_metadata.tap { |m| m[:fields].delete 'Distribution' } }
let(:expected_message) { 'missing Distribution field' }
it_behaves_like 'raises error'
end
end
context 'when lease is already taken' do
before do
stub_exclusive_lease_taken(
"packages:debian:process_package_file_service:#{distribution.project_id}_sample_1.2.3~alpha2",
timeout: Packages::Debian::ProcessPackageFileService::DEFAULT_LEASE_TIMEOUT)
end
it_behaves_like 'does nothing'
end
context 'when there is no matching published package' do
it_behaves_like 'updates package and changes file'
end
context 'when there is a matching published package' do
let!(:matching_package) do
create(
:debian_package,
project: distribution.project,
published_in: distribution,
name: 'sample',
version: '1.2.3~alpha2'
)
end
it 'reuses existing package and update package file', :aggregate_failures do
expect(::Packages::Debian::GenerateDistributionWorker)
.to receive(:perform_async).with(:project, distribution.id)
expect { subject }
.to change { Packages::Package.count }.from(3).to(2)
.and not_change { Packages::PackageFile.count }
.and not_change(Packages::Debian::Publication, :count)
.and change { package.package_files.count }.from(1).to(0)
.and change { incoming.package_files.count }.from(7).to(0)
.and change { matching_package.package_files.count }.from(7).to(15)
.and change { package_file.package }.from(package).to(matching_package)
.and not_change(matching_package, :name)
.and not_change(matching_package, :version)
.and change { debian_file_metadatum.file_type }.from('unknown').to('changes')
.and not_change { debian_file_metadatum.component }
expect { package.reload }
.to raise_error(ActiveRecord::RecordNotFound)
end
end
context 'when there is a matching published package pending destruction' do
let!(:matching_package) do
create(
:debian_package,
:pending_destruction,
project: distribution.project,
published_in: distribution,
name: 'sample',
version: '1.2.3~alpha2'
)
end
it_behaves_like 'updates package and changes file'
end
end
context 'with a package file' do
let!(:temporary_with_files) { create(:debian_temporary_with_files, project: distribution.project) }
let(:package) { temporary_with_files }
let(:package_file) { package.package_files.with_file_name('libsample0_1.2.3~alpha2_amd64.deb').first }
let(:distribution_name) { distribution.codename }
let(:component_name) { 'main' }
where(:case_name, :expected_file_type, :file_name, :component_name) do
'with a deb' | 'deb' | 'libsample0_1.2.3~alpha2_amd64.deb' | 'main'
'with an udeb' | 'udeb' | 'sample-udeb_1.2.3~alpha2_amd64.udeb' | 'contrib'
'with an ddeb' | 'ddeb' | 'sample-ddeb_1.2.3~alpha2_amd64.ddeb' | 'main'
end
with_them do
context 'with Debian package file' do
let(:package_file) { package.package_files.with_file_name(file_name).first }
it_behaves_like 'common validations'
context 'without distribution name' do
let(:distribution_name) { '' }
let(:expected_error) { ArgumentError }
let(:expected_message) { 'missing distribution name' }
it_behaves_like 'raises error'
end
context 'without component name' do
let(:component_name) { '' }
let(:expected_error) { ArgumentError }
let(:expected_message) { 'missing component name' }
it_behaves_like 'raises error'
end
context 'with invalid package file type' do
let(:package_file) { package.package_files.with_file_name('sample_1.2.3~alpha2.tar.xz').first }
let(:expected_error) { ArgumentError }
let(:expected_message) { 'invalid package file type: source' }
it_behaves_like 'raises error'
end
context 'when lease is already taken' do
before do
stub_exclusive_lease_taken(
"packages:debian:process_package_file_service:#{distribution.project_id}_sample_1.2.3~alpha2",
timeout: Packages::Debian::ProcessPackageFileService::DEFAULT_LEASE_TIMEOUT)
end
it_behaves_like 'does nothing'
end
context 'when there is no matching published package' do
it_behaves_like 'updates package and package file'
context 'with suite as distribution name' do
let(:distribution_name) { distribution.suite }
it_behaves_like 'updates package and package file'
end
end
context 'when there is a matching published package' do
let!(:matching_package) do
create(
:debian_package,
project: distribution.project,
published_in: distribution,
name: 'sample',
version: '1.2.3~alpha2'
)
end
it 'reuses existing package and update package file', :aggregate_failures do
expect(::Packages::Debian::GenerateDistributionWorker)
.to receive(:perform_async).with(:project, distribution.id)
expect { subject }
.to change { Packages::Package.count }.from(2).to(1)
.and change { Packages::PackageFile.count }.from(14).to(8)
.and not_change(Packages::Debian::Publication, :count)
.and change { package.package_files.count }.from(7).to(0)
.and change { package_file.package }.from(package).to(matching_package)
.and not_change(matching_package, :name)
.and not_change(matching_package, :version)
.and change { debian_file_metadatum.file_type }.from('unknown').to(expected_file_type)
.and change { debian_file_metadatum.component }.from(nil).to(component_name)
expect { package.reload }
.to raise_error(ActiveRecord::RecordNotFound)
end
end
context 'when there is a matching published package pending destruction' do
let!(:matching_package) do
create(
:debian_package,
:pending_destruction,
project: distribution.project,
published_in: distribution,
name: 'sample',
version: '1.2.3~alpha2'
)
end
it_behaves_like 'updates package and package file'
end
end
end
end
end
describe '#lease_key' do
let(:prefix) { 'packages:debian:process_package_file_service' }
subject { service.send(:lease_key) }
context 'with a changes file' do
let!(:incoming) { create(:debian_incoming, project: distribution.project) }
let!(:temporary_with_changes) { create(:debian_temporary_with_changes, project: distribution.project) }
let(:package) { temporary_with_changes }
let(:package_file) { temporary_with_changes.package_files.first }
let(:distribution_name) { nil }
let(:component_name) { nil }
it { is_expected.to eq("#{prefix}:#{distribution.project_id}_sample_1.2.3~alpha2") }
end
context 'with a package file' do
let!(:temporary_with_files) { create(:debian_temporary_with_files, project: distribution.project) }
let(:package) { temporary_with_files }
let(:package_file) { package.package_files.with_file_name('libsample0_1.2.3~alpha2_amd64.deb').first }
let(:distribution_name) { distribution.codename }
let(:component_name) { 'main' }
it { is_expected.to eq("#{prefix}:#{distribution.project_id}_sample_1.2.3~alpha2") }
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Maven
class CreatePackageService < ::Packages::CreatePackageService
def execute
app_group, _, app_name = params[:name].rpartition('/')
app_group.tr!('/', '.')
create_package!(:maven,
maven_metadatum_attributes: {
path: params[:path],
app_group: app_group,
app_name: app_name,
app_version: params[:version]
}
)
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Maven::CreatePackageService, feature_category: :package_registry do
let(:project) { create(:project) }
let(:user) { create(:user) }
let(:app_name) { 'my-app' }
let(:version) { '1.0-SNAPSHOT' }
let(:path) { "my/company/app/#{app_name}" }
let(:path_with_version) { "#{path}/#{version}" }
describe '#execute' do
subject(:package) { described_class.new(project, user, params).execute }
context 'with version' do
let(:params) do
{
path: path_with_version,
name: path,
version: version
}
end
it 'creates a new package with metadatum' do
expect(package).to be_valid
expect(package.name).to eq(path)
expect(package.version).to eq(version)
expect(package.package_type).to eq('maven')
expect(package.maven_metadatum).to be_valid
expect(package.maven_metadatum.path).to eq(path_with_version)
expect(package.maven_metadatum.app_group).to eq('my.company.app')
expect(package.maven_metadatum.app_name).to eq(app_name)
expect(package.maven_metadatum.app_version).to eq(version)
end
it_behaves_like 'assigns the package creator'
end
context 'without version' do
let(:params) do
{
path: path,
name: path,
version: nil
}
end
it 'creates a new package with metadatum' do
package = described_class.new(project, user, params).execute
expect(package).to be_valid
expect(package.name).to eq(path)
expect(package.version).to be nil
expect(package.maven_metadatum).to be_valid
expect(package.maven_metadatum.path).to eq(path)
expect(package.maven_metadatum.app_group).to eq('my.company.app')
expect(package.maven_metadatum.app_name).to eq(app_name)
expect(package.maven_metadatum.app_version).to be nil
end
it_behaves_like 'assigns the package creator'
end
context 'path is missing' do
let(:params) do
{
name: path,
version: version
}
end
it 'raises an error' do
service = described_class.new(project, user, params)
expect { service.execute }.to raise_error(ActiveRecord::RecordInvalid)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Maven
class FindOrCreatePackageService < BaseService
SNAPSHOT_TERM = '-SNAPSHOT'
MAX_FILE_NAME_LENGTH = 5000
def execute
return ServiceResponse.error(message: 'File name is too long') if file_name_too_long?
package =
::Packages::Maven::PackageFinder.new(current_user, project, path: path)
.execute&.last
unless Namespace::PackageSetting.duplicates_allowed?(package)
return ServiceResponse.error(message: 'Duplicate package is not allowed') if target_package_is_duplicate?(package)
end
unless package
# Maven uploads several files during `mvn deploy` in next order:
# - my-company/my-app/1.0-SNAPSHOT/my-app.jar
# - my-company/my-app/1.0-SNAPSHOT/my-app.pom
# - my-company/my-app/1.0-SNAPSHOT/maven-metadata.xml
# - my-company/my-app/maven-metadata.xml
#
# The last xml file does not have VERSION in URL because it contains
# information about all versions. When uploading such file, we create
# a package with a version set to `nil`. The xml file with a version
# is only created and uploaded for snapshot versions.
#
# Gradle has a different upload order:
# - my-company/my-app/1.0-SNAPSHOT/maven-metadata.xml
# - my-company/my-app/1.0-SNAPSHOT/my-app.jar
# - my-company/my-app/1.0-SNAPSHOT/my-app.pom
# - my-company/my-app/maven-metadata.xml
#
# The first upload has to create the proper package (the one with the version set).
if file_name == Packages::Maven::Metadata.filename && !snapshot_version?
package_name = path
version = nil
else
package_name, _, version = path.rpartition('/')
end
package_params = {
name: package_name,
path: path,
status: params[:status],
version: version
}
package =
::Packages::Maven::CreatePackageService.new(project, current_user, package_params)
.execute
end
package.create_build_infos!(params[:build])
ServiceResponse.success(payload: { package: package })
end
private
def file_name_too_long?
return false unless file_name
file_name.size > MAX_FILE_NAME_LENGTH
end
def target_package_is_duplicate?(package)
# duplicate metadata files can be uploaded multiple times
return false if package.version.nil?
existing_file_names = strip_snapshot_parts(
package.package_files
.map(&:file_name)
.compact
)
published_file_name = strip_snapshot_parts_from(file_name)
existing_file_names.include?(published_file_name)
end
def strip_snapshot_parts(file_names)
return file_names unless snapshot_version?
Array.wrap(file_names).map { |f| strip_snapshot_parts_from(f) }
end
def strip_snapshot_parts_from(file_name)
return file_name unless snapshot_version?
return unless file_name
match_data = file_name.match(Gitlab::Regex::Packages::MAVEN_SNAPSHOT_DYNAMIC_PARTS)
if match_data
file_name.gsub(match_data.captures.last, "")
else
file_name
end
end
def snapshot_version?
path&.ends_with?(SNAPSHOT_TERM)
end
def path
params[:path]
end
def file_name
params[:file_name]
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Maven::FindOrCreatePackageService, feature_category: :package_registry do
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let(:app_name) { 'my-app' }
let(:path) { "sandbox/test/app/#{app_name}" }
let(:version) { '1.0.0' }
let(:file_name) { 'test.jar' }
let(:param_path) { "#{path}/#{version}" }
let(:params) { { path: param_path, file_name: file_name } }
let(:service) { described_class.new(project, user, params) }
describe '#execute' do
using RSpec::Parameterized::TableSyntax
subject { service.execute }
shared_examples 'reuse existing package' do
it { expect { subject }.not_to change { Packages::Package.count } }
it 'returns the existing package' do
expect(subject.payload).to eq(package: existing_package)
end
end
shared_examples 'create package' do
it { expect { subject }.to change { Packages::Package.count }.by(1) }
it 'sets the proper name and version', :aggregate_failures do
pkg = subject.payload[:package]
expect(pkg.name).to eq(path)
expect(pkg.version).to eq(version)
end
context 'with optional attributes' do
subject { service.execute.payload[:package] }
it_behaves_like 'assigns build to package'
it_behaves_like 'assigns status to package'
end
end
shared_examples 'returning an error' do |with_message: ''|
it { expect { subject }.not_to change { project.package_files.count } }
it 'returns an error', :aggregate_failures do
expect(subject.payload).to be_empty
expect(subject.errors).to include(with_message)
end
end
context 'path with version' do
# Note that "path with version" and "file type maven metadata xml" only exists for snapshot versions
# In other words, we will never have an metadata xml upload on a path with version for a non snapshot version
where(:package_exist, :file_type, :snapshot_version, :shared_example_name) do
true | :jar | false | 'reuse existing package'
false | :jar | false | 'create package'
true | :jar | true | 'reuse existing package'
false | :jar | true | 'create package'
true | :maven_xml | true | 'reuse existing package'
false | :maven_xml | true | 'create package'
end
with_them do
let(:version) { snapshot_version ? '1.0-SNAPSHOT' : '1.0.0' }
let(:file_name) { file_type == :maven_xml ? 'maven-metadata.xml' : 'test.jar' }
let!(:existing_package) do
if package_exist
create(:maven_package, name: path, version: version, project: project)
end
end
it_behaves_like params[:shared_example_name]
end
end
context 'path without version' do
let(:param_path) { path }
let(:version) { nil }
context 'maven-metadata.xml file' do
let(:file_name) { 'maven-metadata.xml' }
context 'with existing package' do
let!(:existing_package) { create(:maven_package, name: path, version: version, project: project) }
it_behaves_like 'reuse existing package'
context 'marked as pending_destruction' do
before do
existing_package.pending_destruction!
end
it_behaves_like 'create package'
end
end
context 'without existing package' do
it_behaves_like 'create package'
end
end
end
context 'with a build' do
let_it_be(:pipeline) { create(:ci_pipeline, user: user) }
let(:build) { double('build', pipeline: pipeline) }
let(:params) { { path: param_path, file_name: file_name, build: build } }
it 'creates a build_info' do
expect { subject }.to change { Packages::BuildInfo.count }.by(1)
end
context 'with multiple files for the same package and the same pipeline' do
let(:file_2_params) { params.merge(file_name: 'test2.jar') }
let(:file_3_params) { params.merge(file_name: 'test3.jar') }
it 'creates a single build info' do
expect do
described_class.new(project, user, params).execute
described_class.new(project, user, file_2_params).execute
described_class.new(project, user, file_3_params).execute
end.to change { ::Packages::BuildInfo.count }.by(1)
end
end
end
context 'when package duplicates are not allowed' do
let_it_be_with_refind(:package_settings) { create(:namespace_package_setting, :group, maven_duplicates_allowed: false) }
let_it_be_with_refind(:group) { package_settings.namespace }
let_it_be_with_refind(:project) { create(:project, group: group) }
let!(:existing_package) { create(:maven_package, name: path, version: version, project: project) }
let(:existing_file_name) { file_name }
let(:jar_file) { existing_package.package_files.with_file_name_like('%.jar').first }
before do
jar_file.update_column(:file_name, existing_file_name)
end
it_behaves_like 'returning an error', with_message: 'Duplicate package is not allowed'
context 'for a SNAPSHOT version' do
let(:version) { '1.0.0-SNAPSHOT' }
it_behaves_like 'returning an error', with_message: 'Duplicate package is not allowed'
end
context 'when uploading to the versionless package which contains metadata about all versions' do
let(:version) { nil }
let(:param_path) { path }
it_behaves_like 'reuse existing package'
end
context 'when uploading different non-duplicate files to the same package' do
before do
jar_file.destroy!
end
it_behaves_like 'reuse existing package'
end
context 'when the package name matches the exception regex' do
before do
package_settings.update!(maven_duplicate_exception_regex: existing_package.name)
end
it_behaves_like 'reuse existing package'
end
context 'when the package version matches the exception regex' do
before do
package_settings.update!(maven_duplicate_exception_regex: existing_package.version)
end
it_behaves_like 'reuse existing package'
end
context 'when uploading a similar package file name with a classifier' do
let(:existing_file_name) { 'test.jar' }
let(:file_name) { 'test-javadoc.jar' }
it_behaves_like 'reuse existing package'
context 'for a SNAPSHOT version' do
let(:version) { '1.0.0-SNAPSHOT' }
let(:existing_file_name) { 'test-1.0-20230303.163304-1.jar' }
let(:file_name) { 'test-1.0-20230303.163304-1-javadoc.jar' }
it_behaves_like 'reuse existing package'
end
end
end
context 'with a very large file name' do
let(:params) { super().merge(file_name: 'a' * (described_class::MAX_FILE_NAME_LENGTH + 1)) }
it_behaves_like 'returning an error', with_message: 'File name is too long'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Maven
module Metadata
class AppendPackageFileService
XML_CONTENT_TYPE = 'application/xml'
DEFAULT_CONTENT_TYPE = 'application/octet-stream'
MD5_FILE_NAME = "#{Metadata.filename}.md5"
SHA1_FILE_NAME = "#{Metadata.filename}.sha1"
SHA256_FILE_NAME = "#{Metadata.filename}.sha256"
SHA512_FILE_NAME = "#{Metadata.filename}.sha512"
def initialize(package:, metadata_content:)
@package = package
@metadata_content = metadata_content
end
def execute
return ServiceResponse.error(message: 'package is not set') unless @package
return ServiceResponse.error(message: 'metadata content is not set') unless @metadata_content
file_md5 = digest_from(@metadata_content, :md5)
file_sha1 = digest_from(@metadata_content, :sha1)
file_sha256 = digest_from(@metadata_content, :sha256)
file_sha512 = digest_from(@metadata_content, :sha512)
@package.transaction do
append_metadata_file(
content: @metadata_content,
file_name: Metadata.filename,
content_type: XML_CONTENT_TYPE,
sha1: file_sha1,
md5: file_md5,
sha256: file_sha256
)
append_metadata_file(content: file_md5, file_name: MD5_FILE_NAME) unless Gitlab::FIPS.enabled?
append_metadata_file(content: file_sha1, file_name: SHA1_FILE_NAME)
append_metadata_file(content: file_sha256, file_name: SHA256_FILE_NAME)
append_metadata_file(content: file_sha512, file_name: SHA512_FILE_NAME)
end
ServiceResponse.success(message: 'New metadata package file created')
end
private
def append_metadata_file(content:, file_name:, content_type: DEFAULT_CONTENT_TYPE, sha1: nil, md5: nil, sha256: nil)
file_md5 = md5 || digest_from(content, :md5)
file_sha1 = sha1 || digest_from(content, :sha1)
file_sha256 = sha256 || digest_from(content, :sha256)
file = CarrierWaveStringFile.new_file(
file_content: content,
filename: file_name,
content_type: content_type
)
::Packages::CreatePackageFileService.new(
@package,
file: file,
size: file.size,
file_name: file_name,
file_sha1: file_sha1,
file_md5: file_md5,
file_sha256: file_sha256
).execute
end
def digest_from(content, type)
return if type == :md5 && Gitlab::FIPS.enabled?
digest_class = case type
when :md5
Digest::MD5
when :sha1
Digest::SHA1
when :sha256
Digest::SHA256
when :sha512
Digest::SHA512
end
digest_class.hexdigest(content)
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::Packages::Maven::Metadata::AppendPackageFileService, feature_category: :package_registry do
let_it_be(:package) { create(:maven_package, version: nil) }
let(:service) { described_class.new(package: package, metadata_content: content) }
let(:content) { 'test' }
describe '#execute' do
subject { service.execute }
context 'with some content' do
it 'creates all the related package files', :aggregate_failures do
expect { subject }.to change { package.package_files.count }.by(5)
expect(subject).to be_success
expect_file(metadata_file_name, with_content: content, with_content_type: 'application/xml')
expect_file("#{metadata_file_name}.md5")
expect_file("#{metadata_file_name}.sha1")
expect_file("#{metadata_file_name}.sha256")
expect_file("#{metadata_file_name}.sha512")
end
context 'with FIPS mode', :fips_mode do
it 'does not generate file_md5' do
expect { subject }.to change { package.package_files.count }.by(4)
expect(subject).to be_success
expect_file(metadata_file_name, with_content: content, with_content_type: 'application/xml', fips: true)
expect_file("#{metadata_file_name}.sha1", fips: true)
expect_file("#{metadata_file_name}.sha256", fips: true)
expect_file("#{metadata_file_name}.sha512", fips: true)
end
end
end
context 'with nil content' do
let(:content) { nil }
it_behaves_like 'returning an error service response', message: 'metadata content is not set'
end
context 'with nil package' do
let(:package) { nil }
it_behaves_like 'returning an error service response', message: 'package is not set'
end
def expect_file(file_name, fips: false, with_content: nil, with_content_type: '')
package_file = package.package_files.recent.with_file_name(file_name).first
expect(package_file.file).to be_present
expect(package_file.file_name).to eq(file_name)
expect(package_file.size).to be > 0
expect(package_file.file_sha1).to be_present
expect(package_file.file_sha256).to be_present
expect(package_file.file.content_type).to eq(with_content_type)
if fips
expect(package_file.file_md5).not_to be_present
else
expect(package_file.file_md5).to be_present
end
if with_content
expect(package_file.file.read).to eq(with_content)
end
end
def metadata_file_name
::Packages::Maven::Metadata.filename
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Maven
module Metadata
class CreatePluginsXmlService < BaseCreateXmlService
XPATH_PLUGIN_ARTIFACT_ID = '//plugin/artifactId'
XPATH_PLUGINS = '//metadata/plugins'
EMPTY_PLUGINS_PAYLOAD = {
changes_exist: true,
empty_plugins: true
}.freeze
def execute
return ServiceResponse.error(message: 'package not set') unless @package
return ServiceResponse.error(message: 'metadata_content not set') unless @metadata_content
return ServiceResponse.error(message: 'metadata_content is invalid') unless plugins_xml_node.present?
return ServiceResponse.success(payload: EMPTY_PLUGINS_PAYLOAD) if plugin_artifact_ids_from_database.empty?
changes_exist = update_plugins_list
payload = { changes_exist: changes_exist, empty_versions: false }
payload[:metadata_content] = xml_doc.to_xml(indent: INDENT_SPACE) if changes_exist
ServiceResponse.success(payload: payload)
end
private
def update_plugins_list
return false if plugin_artifact_ids_from_xml == plugin_artifact_ids_from_database
plugins_xml_node.children.remove
plugin_artifact_ids_from_database.each do |artifact_id|
plugins_xml_node.add_child(plugin_node_for(artifact_id))
end
true
end
def plugins_xml_node
xml_doc.xpath(XPATH_PLUGINS)
.first
end
strong_memoize_attr :plugins_xml_node
def plugin_artifact_ids_from_xml
plugins_xml_node.xpath(XPATH_PLUGIN_ARTIFACT_ID)
.map(&:content)
end
strong_memoize_attr :plugin_artifact_ids_from_xml
def plugin_artifact_ids_from_database
package_names = plugin_artifact_ids_from_xml.map do |artifact_id|
"#{@package.name}/#{artifact_id}"
end
packages = @package.project.packages
.maven
.displayable
.with_name(package_names)
.has_version
::Packages::Maven::Metadatum.for_package_ids(packages.select(:id))
.order_created
.pluck_app_name
.uniq
end
strong_memoize_attr :plugin_artifact_ids_from_database
def plugin_node_for(artifact_id)
xml_doc.create_element('plugin').tap do |plugin_node|
plugin_node.add_child(xml_node('name', artifact_id))
plugin_node.add_child(xml_node('prefix', prefix_from(artifact_id)))
plugin_node.add_child(xml_node('artifactId', artifact_id))
end
end
# Maven plugin prefix generation from
# https://github.com/apache/maven/blob/c3dba0e5ba71ee7cbd62620f669a8c206e71b5e2/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptor.java#L189
def prefix_from(artifact_id)
artifact_id.gsub(/-?maven-?/, '')
.gsub(/-?plugin-?/, '')
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::Packages::Maven::Metadata::CreatePluginsXmlService, feature_category: :package_registry do
let_it_be(:group_id) { 'my/test' }
let_it_be(:package) { create(:maven_package, name: group_id, version: nil) }
let(:plugins_in_database) { %w[one-maven-plugin two three-maven-plugin] }
let(:plugins_in_xml) { %w[one-maven-plugin two three-maven-plugin] }
let(:service) { described_class.new(metadata_content: metadata_xml, package: package) }
describe '#execute' do
subject { service.execute }
before do
next unless package
plugins_in_database.each do |plugin|
create(
:maven_package,
name: "#{group_id}/#{plugin}",
version: '1.0.0',
project: package.project,
maven_metadatum_attributes: {
app_group: group_id.tr('/', '.'),
app_name: plugin,
app_version: '1.0.0'
}
)
end
end
shared_examples 'returning an xml with plugins from the database' do
it 'returns an metadata versions xml with versions in the database', :aggregate_failures do
expect(subject).to be_success
expect(subject.payload[:changes_exist]).to eq(true)
expect(subject.payload[:empty_versions]).to eq(false)
expect(plugins_from(subject.payload[:metadata_content])).to match_array(plugins_in_database)
end
end
shared_examples 'returning no changes' do
it 'returns no changes', :aggregate_failures do
expect(subject).to be_success
expect(subject.payload).to eq(changes_exist: false, empty_versions: false)
end
end
context 'with same plugins on both sides' do
it_behaves_like 'returning no changes'
end
context 'with more plugins' do
let(:additional_plugins) { %w[four-maven-plugin five] }
context 'in database' do
let(:plugins_in_database) { plugins_in_xml + additional_plugins }
# we can't distinguish that the additional plugin are actually maven plugins
it_behaves_like 'returning no changes'
end
context 'in xml' do
let(:plugins_in_xml) { plugins_in_database + additional_plugins }
it_behaves_like 'returning an xml with plugins from the database'
end
end
context 'with no versions in the database' do
let(:plugins_in_database) { [] }
it 'returns a success', :aggregate_failures do
result = subject
expect(result).to be_success
expect(result.payload).to eq(changes_exist: true, empty_plugins: true)
end
end
context 'with an incomplete metadata content' do
let(:metadata_xml) { '<metadata></metadata>' }
it_behaves_like 'returning an error service response', message: 'metadata_content is invalid'
end
context 'with an invalid metadata content' do
let(:metadata_xml) { '<meta></metadata>' }
it_behaves_like 'returning an error service response', message: 'metadata_content is invalid'
end
it_behaves_like 'handling metadata content pointing to a file for the create xml service'
it_behaves_like 'handling invalid parameters for create xml service'
end
def metadata_xml
Nokogiri::XML::Builder.new do |xml|
xml.metadata do
xml.plugins do
plugins_in_xml.each do |plugin|
xml.plugin do
xml.name(plugin)
xml.prefix(prefix_from(plugin))
xml.artifactId(plugin)
end
end
end
end
end.to_xml
end
def prefix_from(artifact_id)
artifact_id.gsub(/-?maven-?/, '')
.gsub(/-?plugin-?/, '')
end
def plugins_from(xml_content)
doc = Nokogiri::XML(xml_content)
doc.xpath('//metadata/plugins/plugin/artifactId').map(&:content)
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Maven
module Metadata
class SyncService < BaseContainerService
include Gitlab::Utils::StrongMemoize
alias_method :project, :container
MAX_FILE_SIZE = 10.megabytes.freeze
def execute
return error('Blank package name') unless package_name
return error('Not allowed') unless Ability.allowed?(current_user, :destroy_package, project)
result = success('Non existing versionless package(s). Nothing to do.')
# update versionless package for plugins if it exists
if metadata_package_file_for_plugins
result = update_plugins_xml
return result if result.error?
end
# update versionless_package for versions if it exists
return update_versions_xml if metadata_package_file_for_versions
result
end
private
def update_versions_xml
update_xml(
kind: :versions,
package_file: metadata_package_file_for_versions,
service_class: CreateVersionsXmlService,
payload_empty_field: :empty_versions
)
end
def update_plugins_xml
update_xml(
kind: :plugins,
package_file: metadata_package_file_for_plugins,
service_class: CreatePluginsXmlService,
payload_empty_field: :empty_plugins
)
end
def update_xml(kind:, package_file:, service_class:, payload_empty_field:)
return error("Metadata file for #{kind} is too big") if package_file.size > MAX_FILE_SIZE
package_file.file.use_open_file do |file|
result = service_class.new(metadata_content: file, package: package_file.package)
.execute
next result unless result.success?
next success("No changes for #{kind} xml") unless result.payload[:changes_exist]
if result.payload[payload_empty_field]
package_file.package.destroy!
success("Versionless package for #{kind} destroyed")
else
AppendPackageFileService.new(metadata_content: result.payload[:metadata_content], package: package_file.package)
.execute
end
end
end
def metadata_package_file_for_versions
metadata_package_file_for(versionless_package_for_versions)
end
strong_memoize_attr :metadata_package_file_for_versions
def versionless_package_for_versions
versionless_package_named(package_name)
end
strong_memoize_attr :versionless_package_for_versions
def metadata_package_file_for_plugins
pkg_name = package_name_for_plugins
return unless pkg_name
metadata_package_file_for(versionless_package_named(package_name_for_plugins))
end
strong_memoize_attr :metadata_package_file_for_plugins
def metadata_package_file_for(package)
return unless package
package_files = package.installable_package_files
package_files.with_file_name(Metadata.filename)
.recent
.first
end
def versionless_package_named(name)
project.packages
.maven
.displayable
.with_name(name)
.with_version(nil)
.first
end
def package_name
params[:package_name]
end
def package_name_for_plugins
return unless versionless_package_for_versions
group = versionless_package_for_versions.maven_metadatum.app_group
group.tr('.', '/')
end
def error(message)
ServiceResponse.error(message: message)
end
def success(message)
ServiceResponse.success(message: message)
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::Packages::Maven::Metadata::SyncService, feature_category: :package_registry do
using RSpec::Parameterized::TableSyntax
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let_it_be_with_reload(:versionless_package_for_versions) { create(:maven_package, name: 'test', version: nil, project: project) }
let_it_be_with_reload(:metadata_file_for_versions) { create(:package_file, :xml, package: versionless_package_for_versions) }
let_it_be(:package_file_pending_destruction) { create(:package_file, :pending_destruction, package: versionless_package_for_versions, file_name: Packages::Maven::Metadata.filename) }
let(:service) { described_class.new(container: project, current_user: user, params: { package_name: versionless_package_for_versions.name }) }
describe '#execute' do
let(:create_versions_xml_service_double) { double(::Packages::Maven::Metadata::CreateVersionsXmlService, execute: create_versions_xml_service_response) }
let(:append_package_file_service_double) { double(::Packages::Maven::Metadata::AppendPackageFileService, execute: append_package_file_service_response) }
let(:create_versions_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_versions: false, metadata_content: 'test' }) }
let(:append_package_file_service_response) { ServiceResponse.success(message: 'New metadata package files created') }
subject { service.execute }
before do
allow(::Packages::Maven::Metadata::CreateVersionsXmlService)
.to receive(:new).with(metadata_content: an_instance_of(ObjectStorage::Concern::OpenFile), package: versionless_package_for_versions).and_return(create_versions_xml_service_double)
allow(::Packages::Maven::Metadata::AppendPackageFileService)
.to receive(:new).with(metadata_content: an_instance_of(String), package: versionless_package_for_versions).and_return(append_package_file_service_double)
end
context 'permissions' do
where(:role, :expected_result) do
:anonymous | :rejected
:developer | :rejected
:maintainer | :accepted
end
with_them do
if params[:role] == :anonymous
let_it_be(:user) { nil }
end
before do
project.send("add_#{role}", user) unless role == :anonymous
end
if params[:expected_result] == :rejected
it_behaves_like 'returning an error service response', message: 'Not allowed'
else
it_behaves_like 'returning a success service response', message: 'New metadata package files created'
end
end
end
context 'with a maintainer' do
before do
project.add_maintainer(user)
end
context 'with a jar package' do
before do
expect(::Packages::Maven::Metadata::CreatePluginsXmlService).not_to receive(:new)
end
context 'with no changes' do
let(:create_versions_xml_service_response) { ServiceResponse.success(payload: { changes_exist: false }) }
before do
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'No changes for versions xml'
end
context 'with changes' do
let(:create_versions_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_versions: false, metadata_content: 'new metadata' }) }
it_behaves_like 'returning a success service response', message: 'New metadata package files created'
context 'with empty versions' do
let(:create_versions_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_versions: true }) }
before do
expect(service.send(:versionless_package_for_versions)).to receive(:destroy!)
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'Versionless package for versions destroyed'
end
end
context 'with a too big maven metadata file for versions' do
before do
metadata_file_for_versions.update!(size: 100.megabytes)
end
it_behaves_like 'returning an error service response', message: 'Metadata file for versions is too big'
end
context 'an error from the create versions xml service' do
let(:create_versions_xml_service_response) { ServiceResponse.error(message: 'metadata_content is invalid') }
before do
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
end
it_behaves_like 'returning an error service response', message: 'metadata_content is invalid'
end
context 'an error from the append package file service' do
let(:append_package_file_service_response) { ServiceResponse.error(message: 'metadata content is not set') }
it_behaves_like 'returning an error service response', message: 'metadata content is not set'
end
context 'without a package name' do
let(:service) { described_class.new(container: project, current_user: user, params: { package_name: nil }) }
before do
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
expect(::Packages::Maven::Metadata::CreateVersionsXmlService).not_to receive(:new)
end
it_behaves_like 'returning an error service response', message: 'Blank package name'
end
context 'without a versionless package for version' do
before do
versionless_package_for_versions.update!(version: '2.2.2')
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
expect(::Packages::Maven::Metadata::CreateVersionsXmlService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'Non existing versionless package(s). Nothing to do.'
end
context 'without a metadata package file for versions' do
before do
versionless_package_for_versions.package_files.update_all(file_name: 'test.txt')
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
expect(::Packages::Maven::Metadata::CreateVersionsXmlService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'Non existing versionless package(s). Nothing to do.'
end
context 'without a project' do
let(:service) { described_class.new(container: nil, current_user: user, params: { package_name: versionless_package_for_versions.name }) }
before do
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
expect(::Packages::Maven::Metadata::CreateVersionsXmlService).not_to receive(:new)
end
it_behaves_like 'returning an error service response', message: 'Not allowed'
end
end
context 'with a maven plugin package' do
let_it_be(:versionless_package_name_for_plugins) { versionless_package_for_versions.maven_metadatum.app_group.tr('.', '/') }
let_it_be_with_reload(:versionless_package_for_plugins) { create(:maven_package, name: versionless_package_name_for_plugins, version: nil, project: project) }
let_it_be_with_reload(:metadata_file_for_plugins) { create(:package_file, :xml, package: versionless_package_for_plugins) }
let(:create_plugins_xml_service_double) { double(::Packages::Maven::Metadata::CreatePluginsXmlService, execute: create_plugins_xml_service_response) }
let(:create_plugins_xml_service_response) { ServiceResponse.success(payload: { changes_exist: false }) }
before do
allow(::Packages::Maven::Metadata::CreatePluginsXmlService)
.to receive(:new).with(metadata_content: an_instance_of(ObjectStorage::Concern::OpenFile), package: versionless_package_for_plugins).and_return(create_plugins_xml_service_double)
allow(::Packages::Maven::Metadata::AppendPackageFileService)
.to receive(:new).with(metadata_content: an_instance_of(String), package: versionless_package_for_plugins).and_return(append_package_file_service_double)
end
context 'with no changes' do
let(:create_versions_xml_service_response) { ServiceResponse.success(payload: { changes_exist: false }) }
before do
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'No changes for versions xml'
end
context 'with changes in the versions xml' do
let(:create_versions_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_versions: false, metadata_content: 'new metadata' }) }
it_behaves_like 'returning a success service response', message: 'New metadata package files created'
context 'with changes in the plugin xml' do
let(:create_plugins_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_plugins: false, metadata_content: 'new metadata' }) }
it_behaves_like 'returning a success service response', message: 'New metadata package files created'
end
context 'with empty versions' do
let(:create_versions_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_versions: true }) }
let(:create_plugins_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_plugins: true }) }
before do
expect(service.send(:versionless_package_for_versions)).to receive(:destroy!)
expect(service.send(:metadata_package_file_for_plugins).package).to receive(:destroy!)
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'Versionless package for versions destroyed'
end
context 'with a too big maven metadata file for plugins' do
before do
metadata_file_for_plugins.update!(size: 100.megabytes)
end
it_behaves_like 'returning an error service response', message: 'Metadata file for plugins is too big'
end
context 'an error from the create versions xml service' do
let(:create_plugins_xml_service_response) { ServiceResponse.error(message: 'metadata_content is invalid') }
before do
expect(::Packages::Maven::Metadata::CreateVersionsXmlService).not_to receive(:new)
expect(::Packages::Maven::Metadata::AppendPackageFileService).not_to receive(:new)
end
it_behaves_like 'returning an error service response', message: 'metadata_content is invalid'
end
context 'an error from the append package file service' do
let(:create_plugins_xml_service_response) { ServiceResponse.success(payload: { changes_exist: true, empty_plugins: false, metadata_content: 'new metadata' }) }
let(:append_package_file_service_response) { ServiceResponse.error(message: 'metadata content is not set') }
before do
expect(::Packages::Maven::Metadata::CreateVersionsXmlService).not_to receive(:new)
end
it_behaves_like 'returning an error service response', message: 'metadata content is not set'
end
context 'without a versionless package for plugins' do
before do
versionless_package_for_plugins.package_files.update_all(file_name: 'test.txt')
expect(::Packages::Maven::Metadata::CreatePluginsXmlService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'New metadata package files created'
end
context 'without a versionless package for versions' do
before do
versionless_package_for_versions.package_files.update_all(file_name: 'test.txt')
expect(::Packages::Maven::Metadata::CreateVersionsXmlService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'No changes for plugins xml'
end
context 'without a metadata package file for plugins' do
before do
versionless_package_for_plugins.package_files.update_all(file_name: 'test.txt')
expect(::Packages::Maven::Metadata::CreatePluginsXmlService).not_to receive(:new)
end
it_behaves_like 'returning a success service response', message: 'New metadata package files created'
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Maven
module Metadata
class CreateVersionsXmlService < BaseCreateXmlService
XPATH_VERSIONING = '//metadata/versioning'
XPATH_VERSIONS = '//versions'
XPATH_VERSION = '//version'
XPATH_LATEST = '//latest'
XPATH_RELEASE = '//release'
XPATH_LAST_UPDATED = '//lastUpdated'
EMPTY_VERSIONS_PAYLOAD = {
changes_exist: true,
empty_versions: true
}.freeze
def execute
return ServiceResponse.error(message: 'package not set') unless @package
return ServiceResponse.error(message: 'metadata_content not set') unless @metadata_content
return ServiceResponse.error(message: 'metadata_content is invalid') unless valid_metadata_content?
return ServiceResponse.success(payload: EMPTY_VERSIONS_PAYLOAD) if versions_from_database.empty?
changes_exist = false
changes_exist = true if update_versions_list
changes_exist = true if update_latest
changes_exist = true if update_release
update_last_updated_timestamp if changes_exist
payload = { changes_exist: changes_exist, empty_versions: false }
payload[:metadata_content] = xml_doc.to_xml(indent: INDENT_SPACE) if changes_exist
ServiceResponse.success(payload: payload)
end
private
def valid_metadata_content?
versioning_xml_node.present? &&
versions_xml_node.present? &&
last_updated_xml_node.present?
end
def update_versions_list
return false if versions_from_xml == versions_from_database
version_xml_nodes.remove
versions_from_database.each do |version|
versions_xml_node.add_child(xml_node('version', version))
end
true
end
def update_latest
return false if latest_coherent?
latest_xml_node.content = latest_from_database
true
end
def latest_coherent?
latest_from_xml.nil? || latest_from_xml == latest_from_database
end
def update_release
return false if release_coherent?
unless release_xml_node.present?
log_malformed_content('Missing release tag')
return false
end
if release_from_database
release_xml_node.content = release_from_database
else
release_xml_node.remove
end
true
end
def release_coherent?
release_from_xml == release_from_database
end
def update_last_updated_timestamp
last_updated_xml_node.content = Time.zone.now.strftime('%Y%m%d%H%M%S')
end
def versioning_xml_node
xml_doc.xpath(XPATH_VERSIONING).first
end
strong_memoize_attr :versioning_xml_node
def versions_xml_node
versioning_xml_node&.xpath(XPATH_VERSIONS)
&.first
end
strong_memoize_attr :versions_xml_node
def version_xml_nodes
versions_xml_node&.xpath(XPATH_VERSION)
end
def latest_xml_node
versioning_xml_node&.xpath(XPATH_LATEST)
&.first
end
strong_memoize_attr :latest_xml_node
def release_xml_node
versioning_xml_node&.xpath(XPATH_RELEASE)
&.first
end
strong_memoize_attr :release_xml_node
def last_updated_xml_node
versioning_xml_node.xpath(XPATH_LAST_UPDATED)
.first
end
strong_memoize_attr :last_updated_xml_node
def versions_from_xml
versions_xml_node.xpath(XPATH_VERSION)
.map(&:text)
end
strong_memoize_attr :versions_from_xml
def latest_from_xml
latest_xml_node&.text
end
def release_from_xml
release_xml_node&.text
end
def versions_from_database
@package.project.packages
.maven
.displayable
.with_name(@package.name)
.has_version
.order_created
.pluck_versions
end
strong_memoize_attr :versions_from_database
def latest_from_database
versions_from_database.last
end
def release_from_database
non_snapshot_versions_from_database = versions_from_database.reject { |v| v.ends_with?('SNAPSHOT') }
non_snapshot_versions_from_database.last
end
strong_memoize_attr :release_from_database
def log_malformed_content(reason)
logger.warn(
message: 'A malformed metadata file has been encountered',
reason: reason,
project_id: @package.project_id,
package_id: @package.id
)
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::Packages::Maven::Metadata::CreateVersionsXmlService, feature_category: :package_registry do
let_it_be(:package) { create(:maven_package, version: nil) }
let(:versions_in_database) { %w[1.3 2.0-SNAPSHOT 1.6 1.4 1.5-SNAPSHOT] }
let(:versions_in_xml) { %w[1.3 2.0-SNAPSHOT 1.6 1.4 1.5-SNAPSHOT] }
let(:version_latest) { nil }
let(:version_release) { '1.4' }
let(:service) { described_class.new(metadata_content: metadata_xml, package: package) }
describe '#execute' do
subject { service.execute }
before do
next unless package
versions_in_database.each do |version|
create(:maven_package, name: package.name, version: version, project: package.project)
end
end
shared_examples 'returning an xml with versions in the database' do
it 'returns an metadata versions xml with versions in the database', :aggregate_failures do
result = subject
expect(result).to be_success
expect(versions_from(result.payload[:metadata_content])).to match_array(versions_in_database)
end
end
shared_examples 'returning an xml with' do |release:, latest:|
it 'returns an xml with the updated release and latest versions', :aggregate_failures do
result = subject
expect(result).to be_success
expect(result.payload[:changes_exist]).to be_truthy
xml = result.payload[:metadata_content]
expect(release_from(xml)).to eq(release)
expect(latest_from(xml)).to eq(latest)
end
end
context 'with same versions in both sides' do
it 'returns no changes', :aggregate_failures do
result = subject
expect(result).to be_success
expect(result.payload).to eq(changes_exist: false, empty_versions: false)
end
end
context 'with more versions' do
let(:additional_versions) { %w[5.5 5.6 5.7-SNAPSHOT] }
context 'in the xml side' do
let(:versions_in_xml) { versions_in_database + additional_versions }
it_behaves_like 'returning an xml with versions in the database'
end
context 'in the database side' do
let(:versions_in_database) { versions_in_xml + additional_versions }
it_behaves_like 'returning an xml with versions in the database'
context 'with an xml without a release version' do
let(:version_release) { nil }
it_behaves_like 'returning an xml with versions in the database'
it 'logs a warn with the reason' do
expect(Gitlab::AppJsonLogger).to receive(:warn).with(
message: 'A malformed metadata file has been encountered',
reason: 'Missing release tag',
project_id: package.project_id,
package_id: package.id
)
subject
end
end
end
end
context 'with completely different versions' do
let(:versions_in_database) { %w[1.0 1.1 1.2] }
let(:versions_in_xml) { %w[2.0 2.1 2.2] }
it_behaves_like 'returning an xml with versions in the database'
end
context 'with no versions in the database' do
let(:versions_in_database) { [] }
it 'returns a success', :aggregate_failures do
result = subject
expect(result).to be_success
expect(result.payload).to eq(changes_exist: true, empty_versions: true)
end
context 'with an xml without a release version' do
let(:version_release) { nil }
it 'returns a success', :aggregate_failures do
result = subject
expect(result).to be_success
expect(result.payload).to eq(changes_exist: true, empty_versions: true)
end
end
end
context 'with differences in both sides' do
let(:shared_versions) { %w[1.3 2.0-SNAPSHOT 1.6 1.4 1.5-SNAPSHOT] }
let(:additional_versions_in_xml) { %w[5.5 5.6 5.7-SNAPSHOT] }
let(:versions_in_xml) { shared_versions + additional_versions_in_xml }
let(:additional_versions_in_database) { %w[6.5 6.6 6.7-SNAPSHOT] }
let(:versions_in_database) { shared_versions + additional_versions_in_database }
it_behaves_like 'returning an xml with versions in the database'
end
context 'with a new release and latest from the database' do
let(:versions_in_database) { versions_in_xml + %w[4.1 4.2-SNAPSHOT] }
it_behaves_like 'returning an xml with', release: '4.1', latest: nil
context 'with a latest in the xml' do
let(:version_latest) { '1.6' }
it_behaves_like 'returning an xml with', release: '4.1', latest: '4.2-SNAPSHOT'
end
end
context 'with release and latest not existing in the database' do
let(:version_release) { '7.0' }
let(:version_latest) { '8.0-SNAPSHOT' }
it_behaves_like 'returning an xml with', release: '1.4', latest: '1.5-SNAPSHOT'
end
context 'with added versions in the database side no more recent than release' do
let(:versions_in_database) { versions_in_xml + %w[4.1 4.2-SNAPSHOT] }
before do
::Packages::Package.find_by(name: package.name, version: '4.1').update!(created_at: 2.weeks.ago)
::Packages::Package.find_by(name: package.name, version: '4.2-SNAPSHOT').update!(created_at: 2.weeks.ago)
end
it_behaves_like 'returning an xml with', release: '1.4', latest: nil
context 'with a latest in the xml' do
let(:version_latest) { '1.6' }
it_behaves_like 'returning an xml with', release: '1.4', latest: '1.5-SNAPSHOT'
end
end
context 'only snapshot versions are in the database' do
let(:versions_in_database) { %w[4.2-SNAPSHOT] }
it_behaves_like 'returning an xml with', release: nil, latest: nil
it 'returns an xml without any release element' do
result = subject
xml_doc = Nokogiri::XML(result.payload[:metadata_content])
expect(xml_doc.xpath('//metadata/versioning/release')).to be_empty
end
end
context 'last updated timestamp' do
let(:versions_in_database) { versions_in_xml + %w[4.1 4.2-SNAPSHOT] }
it 'updates the last updated timestamp' do
original = last_updated_from(metadata_xml)
result = subject
expect(result).to be_success
expect(original).not_to eq(last_updated_from(result.payload[:metadata_content]))
end
end
context 'with an incomplete metadata content' do
let(:metadata_xml) { '<metadata></metadata>' }
it_behaves_like 'returning an error service response', message: 'metadata_content is invalid'
end
context 'with an invalid metadata content' do
let(:metadata_xml) { '<meta></metadata>' }
it_behaves_like 'returning an error service response', message: 'metadata_content is invalid'
end
it_behaves_like 'handling metadata content pointing to a file for the create xml service'
it_behaves_like 'handling invalid parameters for create xml service'
end
def metadata_xml
Nokogiri::XML::Builder.new do |xml|
xml.metadata do
xml.groupId(package.maven_metadatum.app_group)
xml.artifactId(package.maven_metadatum.app_name)
xml.versioning do
xml.release(version_release) if version_release
xml.latest(version_latest) if version_latest
xml.lastUpdated('20210113130531')
xml.versions do
versions_in_xml.each do |version|
xml.version(version)
end
end
end
end
end.to_xml
end
def versions_from(xml_content)
doc = Nokogiri::XML(xml_content)
doc.xpath('//metadata/versioning/versions/version').map(&:content)
end
def release_from(xml_content)
doc = Nokogiri::XML(xml_content)
doc.xpath('//metadata/versioning/release').first&.content
end
def latest_from(xml_content)
doc = Nokogiri::XML(xml_content)
doc.xpath('//metadata/versioning/latest').first&.content
end
def last_updated_from(xml_content)
doc = Nokogiri::XML(xml_content)
doc.xpath('//metadata/versioning/lastUpdated').first.content
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Composer
class ComposerJsonService
InvalidJson = Class.new(StandardError)
def initialize(project, target)
@project = project
@target = target
end
def execute
composer_json
end
private
def composer_json
composer_file = @project.repository.blob_at(@target, 'composer.json')
composer_file_not_found! unless composer_file
Gitlab::Json.parse(composer_file.data)
rescue JSON::ParserError
raise InvalidJson, 'Could not parse composer.json file. Invalid JSON.'
end
def composer_file_not_found!
raise InvalidJson, 'The file composer.json was not found.'
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Composer::ComposerJsonService, feature_category: :package_registry do
describe '#execute' do
let(:branch) { project.repository.find_branch('master') }
let(:target) { branch.target }
subject { described_class.new(project, target).execute }
context 'with an existing file' do
let(:project) { create(:project, :custom_repo, files: { 'composer.json' => json }) }
context 'with a valid file' do
let(:json) { '{ "name": "package-name"}' }
it 'returns the parsed json' do
expect(subject).to eq({ 'name' => 'package-name' })
end
end
context 'with an invalid file' do
let(:json) { '{ name": "package-name"}' }
it 'raises an error' do
expect { subject }.to raise_error(described_class::InvalidJson, /Invalid/)
end
end
end
context 'without the composer.json file' do
let(:project) { create(:project, :repository) }
it 'raises an error' do
expect { subject }.to raise_error(described_class::InvalidJson, /not found/)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Composer
class CreatePackageService < ::Packages::CreatePackageService
include ::Gitlab::Utils::StrongMemoize
def execute
# fetches json outside of transaction
composer_json
::Packages::Package.transaction do
::Packages::Composer::Metadatum.upsert({
package_id: created_package.id,
target_sha: target,
composer_json: composer_json
})
end
created_package
end
private
def created_package
find_or_create_package!(:composer, name: package_name, version: package_version)
end
def composer_json
::Packages::Composer::ComposerJsonService.new(project, target).execute
end
strong_memoize_attr :composer_json
def package_name
composer_json['name']
end
def target
(branch || tag).target
end
def branch
params[:branch]
end
def tag
params[:tag]
end
def package_version
::Packages::Composer::VersionParserService.new(tag_name: tag&.name, branch_name: branch&.name).execute
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Composer::CreatePackageService, feature_category: :package_registry do
include PackagesManagerApiSpecHelpers
let_it_be(:package_name) { 'composer-package-name' }
let_it_be(:json) { { name: package_name }.to_json }
let_it_be(:project) { create(:project, :custom_repo, files: { 'composer.json' => json }) }
let_it_be(:user) { create(:user) }
let(:params) do
{
branch: branch,
tag: tag
}
end
describe '#execute' do
let(:tag) { nil }
let(:branch) { nil }
subject { described_class.new(project, user, params).execute }
let(:created_package) { Packages::Package.composer.last }
context 'without an existing package' do
context 'with a branch' do
let(:branch) { project.repository.find_branch('master') }
it 'creates the package' do
expect { subject }
.to change { Packages::Package.composer.count }.by(1)
.and change { Packages::Composer::Metadatum.count }.by(1)
expect(created_package.name).to eq package_name
expect(created_package.version).to eq 'dev-master'
expect(created_package.composer_metadatum.target_sha).to eq branch.target
expect(created_package.composer_metadatum.composer_json.to_json).to eq json
end
it_behaves_like 'assigns the package creator' do
let(:package) { created_package }
end
it_behaves_like 'assigns build to package'
it_behaves_like 'assigns status to package'
end
context 'with a tag' do
let(:tag) { project.repository.find_tag('v1.2.3') }
before_all do
project.repository.add_tag(user, 'v1.2.3', 'master')
end
it 'creates the package' do
expect { subject }
.to change { Packages::Package.composer.count }.by(1)
.and change { Packages::Composer::Metadatum.count }.by(1)
expect(created_package.name).to eq package_name
expect(created_package.version).to eq '1.2.3'
end
it_behaves_like 'assigns the package creator' do
let(:package) { created_package }
end
it_behaves_like 'assigns build to package'
it_behaves_like 'assigns status to package'
end
end
context 'with an existing package' do
let(:branch) { project.repository.find_branch('master') }
context 'belonging to the same project' do
before do
described_class.new(project, user, params).execute
end
it 'does not create a new package' do
expect { subject }
.to change { Packages::Package.composer.count }.by(0)
.and change { Packages::Composer::Metadatum.count }.by(0)
end
end
context 'belonging to another project' do
let(:other_project) { create(:project) }
let!(:other_package) { create(:composer_package, name: package_name, version: 'dev-master', project: other_project) }
it 'fails with an error' do
expect { subject }
.to raise_error(/is already taken/)
end
context 'with pending_destruction package' do
let!(:other_package) { create(:composer_package, :pending_destruction, name: package_name, version: 'dev-master', project: other_project) }
it 'creates the package' do
expect { subject }
.to change { Packages::Package.composer.count }.by(1)
.and change { Packages::Composer::Metadatum.count }.by(1)
end
end
end
context 'same name but of different type' do
let(:other_project) { create(:project) }
let!(:other_package) { create(:package, name: package_name, version: 'dev-master', project: other_project) }
it 'creates the package' do
expect { subject }
.to change { Packages::Package.composer.count }.by(1)
.and change { Packages::Composer::Metadatum.count }.by(1)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Composer
class VersionParserService
def initialize(tag_name: nil, branch_name: nil)
@tag_name = tag_name
@branch_name = branch_name
end
def execute
if @tag_name.present?
@tag_name.delete_prefix('v')
elsif @branch_name.present?
branch_suffix_or_prefix(@branch_name.match(Gitlab::Regex.composer_package_version_regex))
end
end
private
def branch_suffix_or_prefix(match)
if match
captures = match.captures.reject(&:blank?)
if captures[-1] == '.x'
captures[0] + '-dev'
else
captures[0] + '.x-dev'
end
else
"dev-#{@branch_name}"
end
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Composer::VersionParserService, feature_category: :package_registry do
let_it_be(:params) { {} }
describe '#execute' do
using RSpec::Parameterized::TableSyntax
subject { described_class.new(tag_name: tagname, branch_name: branchname).execute }
where(:tagname, :branchname, :expected_version) do
nil | 'master' | 'dev-master'
nil | 'my-feature' | 'dev-my-feature'
nil | '12-feature' | 'dev-12-feature'
nil | 'v1' | '1.x-dev'
nil | 'v1.x' | '1.x-dev'
nil | 'v1.7.x' | '1.7.x-dev'
nil | 'v1.7' | '1.7.x-dev'
nil | '1.7.x' | '1.7.x-dev'
'v1.0.0' | nil | '1.0.0'
'v1.0' | nil | '1.0'
'v1.0.1+meta' | nil | '1.0.1+meta'
'1.0' | nil | '1.0'
'1.0.2' | nil | '1.0.2'
'1.0.2-beta2' | nil | '1.0.2-beta2'
'1.0.1+meta' | nil | '1.0.1+meta'
end
with_them do
it { is_expected.to eq expected_version }
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
module Packages
module Rubygems
class DependencyResolverService < BaseService
include Gitlab::Utils::StrongMemoize
DEFAULT_PLATFORM = 'ruby'
def execute
unless Ability.allowed?(current_user, :read_package, project&.packages_policy_subject)
return ServiceResponse.error(message: "forbidden", http_status: :forbidden)
end
return ServiceResponse.error(message: "#{gem_name} not found", http_status: :not_found) if packages.empty?
payload = packages.map do |package|
dependencies = package.dependency_links.map do |link|
[link.dependency.name, link.dependency.version_pattern]
end
{
name: gem_name,
number: package.version,
platform: DEFAULT_PLATFORM,
dependencies: dependencies
}
end
ServiceResponse.success(payload: payload)
end
private
def packages
project.packages.with_name(gem_name)
end
strong_memoize_attr :packages
def gem_name
params[:gem_name]
end
end
end
end
``` | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Rubygems::DependencyResolverService, feature_category: :package_registry do
let_it_be(:project) { create(:project, :private) }
let_it_be(:package) { create(:package, project: project) }
let_it_be(:user) { create(:user) }
let(:gem_name) { package.name }
let(:service) { described_class.new(project, user, gem_name: gem_name) }
describe '#execute' do
subject { service.execute }
context 'user without access' do
it 'returns a service error' do
expect(subject.error?).to be(true)
expect(subject.message).to eq('forbidden')
end
end
context 'user with access' do
before do
project.add_developer(user)
end
context 'when no package is found' do
let(:gem_name) { nil }
it 'returns a service error', :aggregate_failures do
expect(subject.error?).to be(true)
expect(subject.message).to eq("#{gem_name} not found")
end
end
context 'package without dependencies' do
it 'returns an empty dependencies array' do
expected_result = [{
name: package.name,
number: package.version,
platform: described_class::DEFAULT_PLATFORM,
dependencies: []
}]
expect(subject.payload).to eq(expected_result)
end
end
context 'package with dependencies' do
let(:dependency_link) { create(:packages_dependency_link, :rubygems, package: package) }
let(:dependency_link2) { create(:packages_dependency_link, :rubygems, package: package) }
let(:dependency_link3) { create(:packages_dependency_link, :rubygems, package: package) }
it 'returns a set of dependencies' do
expected_result = [{
name: package.name,
number: package.version,
platform: described_class::DEFAULT_PLATFORM,
dependencies: [
[dependency_link.dependency.name, dependency_link.dependency.version_pattern],
[dependency_link2.dependency.name, dependency_link2.dependency.version_pattern],
[dependency_link3.dependency.name, dependency_link3.dependency.version_pattern]
]
}]
expect(subject.payload).to eq(expected_result)
end
end
context 'package with multiple versions' do
let(:dependency_link) { create(:packages_dependency_link, :rubygems, package: package) }
let(:dependency_link2) { create(:packages_dependency_link, :rubygems, package: package) }
let(:dependency_link3) { create(:packages_dependency_link, :rubygems, package: package) }
let(:package2) { create(:package, project: project, name: package.name, version: '9.9.9') }
let(:dependency_link4) { create(:packages_dependency_link, :rubygems, package: package2) }
it 'returns a set of dependencies' do
expected_result = [{
name: package.name,
number: package.version,
platform: described_class::DEFAULT_PLATFORM,
dependencies: [
[dependency_link.dependency.name, dependency_link.dependency.version_pattern],
[dependency_link2.dependency.name, dependency_link2.dependency.version_pattern],
[dependency_link3.dependency.name, dependency_link3.dependency.version_pattern]
]
}, {
name: package2.name,
number: package2.version,
platform: described_class::DEFAULT_PLATFORM,
dependencies: [
[dependency_link4.dependency.name, dependency_link4.dependency.version_pattern]
]
}]
expect(subject.payload).to match_array(expected_result)
end
end
end
end
end
|