INSTRUCTION
stringlengths 202
35.5k
| RESPONSE
stringlengths 75
161k
|
---|---|
Write RSpec test file for following ruby class
```ruby
class Telegram::SendOnTelegramService < Base::SendOnChannelService
private
def channel_class
Channel::Telegram
end
def perform_reply
## send reply to telegram message api
# https://core.telegram.org/bots/api#sendmessage
message_id = channel.send_message_on_telegram(message)
message.update!(source_id: message_id) if message_id.present?
end
def inbox
@inbox ||= message.inbox
end
def channel
@channel ||= inbox.channel
end
end
``` | require 'rails_helper'
describe Telegram::SendOnTelegramService do
describe '#perform' do
context 'when a valid message' do
it 'calls channel.send_message_on_telegram' do
telegram_request = double
telegram_channel = create(:channel_telegram)
message = create(:message, message_type: :outgoing, content: 'test',
conversation: create(:conversation, inbox: telegram_channel.inbox, additional_attributes: { 'chat_id' => '123' }))
allow(HTTParty).to receive(:post).and_return(telegram_request)
allow(telegram_request).to receive(:success?).and_return(true)
allow(telegram_request).to receive(:parsed_response).and_return({ 'result' => { 'message_id' => 'telegram_123' } })
described_class.new(message: message).perform
expect(message.source_id).to eq('telegram_123')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class MessageTemplates::HookExecutionService
pattr_initialize [:message!]
def perform
return if conversation.campaign.present?
return if conversation.last_incoming_message.blank?
trigger_templates
end
private
delegate :inbox, :conversation, to: :message
delegate :contact, to: :conversation
def trigger_templates
::MessageTemplates::Template::OutOfOffice.new(conversation: conversation).perform if should_send_out_of_office_message?
::MessageTemplates::Template::Greeting.new(conversation: conversation).perform if should_send_greeting?
::MessageTemplates::Template::EmailCollect.new(conversation: conversation).perform if inbox.enable_email_collect && should_send_email_collect?
::MessageTemplates::Template::CsatSurvey.new(conversation: conversation).perform if should_send_csat_survey?
end
def should_send_out_of_office_message?
# should not send if its a tweet message
return false if conversation.tweet?
# should not send for outbound messages
return false unless message.incoming?
inbox.out_of_office? && conversation.messages.today.template.empty? && inbox.out_of_office_message.present?
end
def first_message_from_contact?
conversation.messages.outgoing.count.zero? && conversation.messages.template.count.zero?
end
def should_send_greeting?
# should not send if its a tweet message
return false if conversation.tweet?
first_message_from_contact? && inbox.greeting_enabled? && inbox.greeting_message.present?
end
def email_collect_was_sent?
conversation.messages.where(content_type: 'input_email').present?
end
# TODO: we should be able to reduce this logic once we have a toggle for email collect messages
def should_send_email_collect?
!contact_has_email? && inbox.web_widget? && !email_collect_was_sent?
end
def contact_has_email?
contact.email
end
def csat_enabled_conversation?
return false unless conversation.resolved?
# should not sent since the link will be public
return false if conversation.tweet?
return false unless inbox.csat_survey_enabled?
true
end
def should_send_csat_survey?
return unless csat_enabled_conversation?
# only send CSAT once in a conversation
return if conversation.messages.where(content_type: :input_csat).present?
true
end
end
MessageTemplates::HookExecutionService.prepend_mod_with('MessageTemplates::HookExecutionService')
``` | require 'rails_helper'
describe MessageTemplates::HookExecutionService do
context 'when there is no incoming message in conversation' do
it 'will not call any hooks' do
contact = create(:contact, email: nil)
conversation = create(:conversation, contact: contact)
# ensure greeting hook is enabled
conversation.inbox.update(greeting_enabled: true, enable_email_collect: true)
email_collect_service = double
allow(MessageTemplates::Template::EmailCollect).to receive(:new).and_return(email_collect_service)
allow(email_collect_service).to receive(:perform).and_return(true)
allow(MessageTemplates::Template::Greeting).to receive(:new)
# described class gets called in message after commit
create(:message, conversation: conversation, message_type: 'activity', content: 'Conversation marked resolved!!')
expect(MessageTemplates::Template::Greeting).not_to have_received(:new)
expect(MessageTemplates::Template::EmailCollect).not_to have_received(:new)
end
end
context 'when Greeting Message' do
it 'doesnot calls ::MessageTemplates::Template::Greeting if greeting_message is empty' do
contact = create(:contact, email: nil)
conversation = create(:conversation, contact: contact)
# ensure greeting hook is enabled
conversation.inbox.update(greeting_enabled: true, enable_email_collect: true)
email_collect_service = double
allow(MessageTemplates::Template::EmailCollect).to receive(:new).and_return(email_collect_service)
allow(email_collect_service).to receive(:perform).and_return(true)
allow(MessageTemplates::Template::Greeting).to receive(:new)
# described class gets called in message after commit
message = create(:message, conversation: conversation)
expect(MessageTemplates::Template::Greeting).not_to have_received(:new)
expect(MessageTemplates::Template::EmailCollect).to have_received(:new).with(conversation: message.conversation)
expect(email_collect_service).to have_received(:perform)
end
it 'will not call ::MessageTemplates::Template::Greeting if its a tweet conversation' do
twitter_channel = create(:channel_twitter_profile)
twitter_inbox = create(:inbox, channel: twitter_channel)
# ensure greeting hook is enabled and greeting_message is present
twitter_inbox.update(greeting_enabled: true, greeting_message: 'Hi, this is a greeting message')
conversation = create(:conversation, inbox: twitter_inbox, additional_attributes: { type: 'tweet' })
greeting_service = double
allow(MessageTemplates::Template::Greeting).to receive(:new).and_return(greeting_service)
allow(greeting_service).to receive(:perform).and_return(true)
message = create(:message, conversation: conversation)
expect(MessageTemplates::Template::Greeting).not_to have_received(:new).with(conversation: message.conversation)
end
end
context 'when it is a first message from web widget' do
it 'calls ::MessageTemplates::Template::EmailCollect' do
contact = create(:contact, email: nil)
conversation = create(:conversation, contact: contact)
# ensure greeting hook is enabled and greeting_message is present
conversation.inbox.update(greeting_enabled: true, enable_email_collect: true, greeting_message: 'Hi, this is a greeting message')
email_collect_service = double
greeting_service = double
allow(MessageTemplates::Template::EmailCollect).to receive(:new).and_return(email_collect_service)
allow(email_collect_service).to receive(:perform).and_return(true)
allow(MessageTemplates::Template::Greeting).to receive(:new).and_return(greeting_service)
allow(greeting_service).to receive(:perform).and_return(true)
# described class gets called in message after commit
message = create(:message, conversation: conversation)
expect(MessageTemplates::Template::Greeting).to have_received(:new).with(conversation: message.conversation)
expect(greeting_service).to have_received(:perform)
expect(MessageTemplates::Template::EmailCollect).to have_received(:new).with(conversation: message.conversation)
expect(email_collect_service).to have_received(:perform)
end
it 'doesnot calls ::MessageTemplates::Template::EmailCollect on campaign conversations' do
contact = create(:contact, email: nil)
conversation = create(:conversation, contact: contact, campaign: create(:campaign))
allow(MessageTemplates::Template::EmailCollect).to receive(:new).and_return(true)
# described class gets called in message after commit
message = create(:message, conversation: conversation)
expect(MessageTemplates::Template::EmailCollect).not_to have_received(:new).with(conversation: message.conversation)
end
it 'doesnot calls ::MessageTemplates::Template::EmailCollect when enable_email_collect form is disabled' do
contact = create(:contact, email: nil)
conversation = create(:conversation, contact: contact)
conversation.inbox.update(enable_email_collect: false)
# ensure prechat form is enabled
conversation.inbox.channel.update(pre_chat_form_enabled: true)
allow(MessageTemplates::Template::EmailCollect).to receive(:new).and_return(true)
# described class gets called in message after commit
message = create(:message, conversation: conversation)
expect(MessageTemplates::Template::EmailCollect).not_to have_received(:new).with(conversation: message.conversation)
end
end
context 'when CSAT Survey' do
let(:csat_survey) { double }
let(:conversation) { create(:conversation) }
before do
allow(MessageTemplates::Template::CsatSurvey).to receive(:new).and_return(csat_survey)
allow(csat_survey).to receive(:perform).and_return(true)
create(:message, conversation: conversation, message_type: 'incoming')
end
it 'calls ::MessageTemplates::Template::CsatSurvey when a conversation is resolved in an inbox with survey enabled' do
conversation.inbox.update(csat_survey_enabled: true)
conversation.resolved!
Conversations::ActivityMessageJob.perform_now(conversation,
{ account_id: conversation.account_id, inbox_id: conversation.inbox_id, message_type: :activity,
content: 'Conversation marked resolved!!' })
expect(MessageTemplates::Template::CsatSurvey).to have_received(:new).with(conversation: conversation)
expect(csat_survey).to have_received(:perform)
end
it 'will not call ::MessageTemplates::Template::CsatSurvey when Csat is not enabled' do
conversation.inbox.update(csat_survey_enabled: false)
conversation.resolved!
Conversations::ActivityMessageJob.perform_now(conversation,
{ account_id: conversation.account_id, inbox_id: conversation.inbox_id, message_type: :activity,
content: 'Conversation marked resolved!!' })
expect(MessageTemplates::Template::CsatSurvey).not_to have_received(:new).with(conversation: conversation)
expect(csat_survey).not_to have_received(:perform)
end
it 'will not call ::MessageTemplates::Template::CsatSurvey if its a tweet conversation' do
twitter_channel = create(:channel_twitter_profile)
twitter_inbox = create(:inbox, channel: twitter_channel)
conversation = create(:conversation, inbox: twitter_inbox, additional_attributes: { type: 'tweet' })
conversation.inbox.update(csat_survey_enabled: true)
conversation.resolved!
Conversations::ActivityMessageJob.perform_now(conversation,
{ account_id: conversation.account_id, inbox_id: conversation.inbox_id, message_type: :activity,
content: 'Conversation marked resolved!!' })
expect(MessageTemplates::Template::CsatSurvey).not_to have_received(:new).with(conversation: conversation)
expect(csat_survey).not_to have_received(:perform)
end
it 'will not call ::MessageTemplates::Template::CsatSurvey if another Csat was already sent' do
conversation.inbox.update(csat_survey_enabled: true)
conversation.messages.create!(message_type: 'outgoing', content_type: :input_csat, account: conversation.account, inbox: conversation.inbox)
conversation.resolved!
Conversations::ActivityMessageJob.perform_now(conversation,
{ account_id: conversation.account_id, inbox_id: conversation.inbox_id, message_type: :activity,
content: 'Conversation marked resolved!!' })
expect(MessageTemplates::Template::CsatSurvey).not_to have_received(:new).with(conversation: conversation)
expect(csat_survey).not_to have_received(:perform)
end
end
context 'when it is after working hours' do
it 'calls ::MessageTemplates::Template::OutOfOffice' do
contact = create(:contact)
conversation = create(:conversation, contact: contact)
conversation.inbox.update(working_hours_enabled: true, out_of_office_message: 'We are out of office')
conversation.inbox.working_hours.today.update!(closed_all_day: true)
out_of_office_service = double
allow(MessageTemplates::Template::OutOfOffice).to receive(:new).and_return(out_of_office_service)
allow(out_of_office_service).to receive(:perform).and_return(true)
# described class gets called in message after commit
message = create(:message, conversation: conversation)
expect(MessageTemplates::Template::OutOfOffice).to have_received(:new).with(conversation: message.conversation)
expect(out_of_office_service).to have_received(:perform)
end
it 'will not calls ::MessageTemplates::Template::OutOfOffice when outgoing message' do
contact = create(:contact)
conversation = create(:conversation, contact: contact)
conversation.inbox.update(working_hours_enabled: true, out_of_office_message: 'We are out of office')
conversation.inbox.working_hours.today.update!(closed_all_day: true)
out_of_office_service = double
allow(MessageTemplates::Template::OutOfOffice).to receive(:new).and_return(out_of_office_service)
allow(out_of_office_service).to receive(:perform).and_return(true)
# described class gets called in message after commit
message = create(:message, conversation: conversation, message_type: 'outgoing')
expect(MessageTemplates::Template::OutOfOffice).not_to have_received(:new).with(conversation: message.conversation)
expect(out_of_office_service).not_to have_received(:perform)
end
it 'will not call ::MessageTemplates::Template::OutOfOffice if its a tweet conversation' do
twitter_channel = create(:channel_twitter_profile)
twitter_inbox = create(:inbox, channel: twitter_channel)
twitter_inbox.update(working_hours_enabled: true, out_of_office_message: 'We are out of office')
conversation = create(:conversation, inbox: twitter_inbox, additional_attributes: { type: 'tweet' })
out_of_office_service = double
allow(MessageTemplates::Template::OutOfOffice).to receive(:new).and_return(out_of_office_service)
allow(out_of_office_service).to receive(:perform).and_return(false)
message = create(:message, conversation: conversation)
expect(MessageTemplates::Template::OutOfOffice).not_to have_received(:new).with(conversation: message.conversation)
expect(out_of_office_service).not_to receive(:perform)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class MessageTemplates::Template::OutOfOffice
pattr_initialize [:conversation!]
def perform
ActiveRecord::Base.transaction do
conversation.messages.create!(out_of_office_message_params)
end
rescue StandardError => e
ChatwootExceptionTracker.new(e, account: conversation.account).capture_exception
true
end
private
delegate :contact, :account, to: :conversation
delegate :inbox, to: :message
def out_of_office_message_params
content = @conversation.inbox&.out_of_office_message
{
account_id: @conversation.account_id,
inbox_id: @conversation.inbox_id,
message_type: :template,
content: content
}
end
end
``` | require 'rails_helper'
describe MessageTemplates::Template::OutOfOffice do
context 'when this hook is called' do
let(:conversation) { create(:conversation) }
it 'creates the out of office messages' do
described_class.new(conversation: conversation).perform
expect(conversation.messages.template.count).to eq(1)
expect(conversation.messages.template.first.content).to eq(conversation.inbox.out_of_office_message)
end
it 'creates the out of office messages with template variable' do
conversation.inbox.update!(out_of_office_message: 'Hey, {{contact.name}} we are unavailable at the moment.')
described_class.new(conversation: conversation).perform
expect(conversation.messages.count).to eq(1)
expect(conversation.messages.last.content).to eq("Hey, #{conversation.contact.name} we are unavailable at the moment.")
end
it 'creates the out of office messages with more than one variable strings' do
conversation.inbox.update!(out_of_office_message:
'Hey, {{contact.name}} we are unavailable at the moment. - from {{account.name}}')
described_class.new(conversation: conversation).perform
expect(conversation.messages.count).to eq(1)
expect(conversation.messages.last.content).to eq(
"Hey, #{conversation.contact.name} we are unavailable at the moment. - from #{conversation.account.name}"
)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class MessageTemplates::Template::CsatSurvey
pattr_initialize [:conversation!]
def perform
ActiveRecord::Base.transaction do
conversation.messages.create!(csat_survey_message_params)
end
end
private
delegate :contact, :account, to: :conversation
delegate :inbox, to: :message
def csat_survey_message_params
{
account_id: @conversation.account_id,
inbox_id: @conversation.inbox_id,
message_type: :template,
content_type: :input_csat,
content: I18n.t('conversations.templates.csat_input_message_body')
}
end
end
``` | require 'rails_helper'
describe MessageTemplates::Template::CsatSurvey do
context 'when this hook is called' do
let(:conversation) { create(:conversation) }
it 'creates the out of office messages' do
described_class.new(conversation: conversation).perform
expect(conversation.messages.template.count).to eq(1)
expect(conversation.messages.template.first.content_type).to eq('input_csat')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class MessageTemplates::Template::EmailCollect
pattr_initialize [:conversation!]
def perform
ActiveRecord::Base.transaction do
conversation.messages.create!(ways_to_reach_you_message_params)
conversation.messages.create!(email_input_box_template_message_params)
end
rescue StandardError => e
ChatwootExceptionTracker.new(e, account: conversation.account).capture_exception
true
end
private
delegate :contact, :account, to: :conversation
delegate :inbox, to: :message
def ways_to_reach_you_message_params
content = I18n.t('conversations.templates.ways_to_reach_you_message_body',
account_name: account.name)
{
account_id: @conversation.account_id,
inbox_id: @conversation.inbox_id,
message_type: :template,
content: content
}
end
def email_input_box_template_message_params
content = I18n.t('conversations.templates.email_input_box_message_body',
account_name: account.name)
{
account_id: @conversation.account_id,
inbox_id: @conversation.inbox_id,
message_type: :template,
content_type: :input_email,
content: content
}
end
end
``` | require 'rails_helper'
describe MessageTemplates::Template::EmailCollect do
context 'when this hook is called' do
let(:conversation) { create(:conversation) }
it 'creates the email collect messages' do
described_class.new(conversation: conversation).perform
expect(conversation.messages.count).to eq(2)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class MessageTemplates::Template::Greeting
pattr_initialize [:conversation!]
def perform
ActiveRecord::Base.transaction do
conversation.messages.create!(greeting_message_params)
end
rescue StandardError => e
ChatwootExceptionTracker.new(e, account: conversation.account).capture_exception
true
end
private
delegate :contact, :account, to: :conversation
delegate :inbox, to: :message
def greeting_message_params
content = @conversation.inbox&.greeting_message
{
account_id: @conversation.account_id,
inbox_id: @conversation.inbox_id,
message_type: :template,
content: content
}
end
end
``` | require 'rails_helper'
describe MessageTemplates::Template::Greeting do
context 'when this hook is called' do
let(:conversation) { create(:conversation) }
it 'creates the email collect messages' do
described_class.new(conversation: conversation).perform
expect(conversation.messages.count).to eq(1)
end
it 'creates the greeting messages with template variable' do
conversation.inbox.update!(greeting_message: 'Hey, {{contact.name}} welcome to our board.')
described_class.new(conversation: conversation).perform
expect(conversation.messages.count).to eq(1)
expect(conversation.messages.last.content).to eq("Hey, #{conversation.contact.name} welcome to our board.")
end
it 'creates the greeting messages with more than one variable strings' do
conversation.inbox.update!(greeting_message: 'Hey, {{contact.name}} welcome to our board. - from {{account.name}}')
described_class.new(conversation: conversation).perform
expect(conversation.messages.count).to eq(1)
expect(conversation.messages.last.content).to eq("Hey, #{conversation.contact.name} welcome to our board. - from #{conversation.account.name}")
end
it 'creates the greeting messages' do
conversation.inbox.update!(greeting_message: 'Hello welcome to our board.')
described_class.new(conversation: conversation).perform
expect(conversation.messages.count).to eq(1)
expect(conversation.messages.last.content).to eq('Hello welcome to our board.')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Instagram::ReadStatusService
pattr_initialize [:params!]
def perform
return if instagram_channel.blank?
::Conversations::UpdateMessageStatusJob.perform_later(message.conversation.id, message.created_at) if message.present?
end
def instagram_id
params[:recipient][:id]
end
def instagram_channel
@instagram_channel ||= Channel::FacebookPage.find_by(instagram_id: instagram_id)
end
def message
return unless params[:read][:mid]
@message ||= @instagram_channel.inbox.messages.find_by(source_id: params[:read][:mid])
end
end
``` | require 'rails_helper'
describe Instagram::ReadStatusService do
before do
create(:message, message_type: :incoming, inbox: instagram_inbox, account: account, conversation: conversation,
source_id: 'chatwoot-app-user-id-1')
end
let!(:account) { create(:account) }
let!(:instagram_channel) { create(:channel_instagram_fb_page, account: account, instagram_id: 'chatwoot-app-user-id-1') }
let!(:instagram_inbox) { create(:inbox, channel: instagram_channel, account: account, greeting_enabled: false) }
let!(:contact) { create(:contact, account: account) }
let(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: instagram_inbox) }
let(:conversation) { create(:conversation, contact: contact, inbox: instagram_inbox, contact_inbox: contact_inbox) }
describe '#perform' do
context 'when messaging_seen callback is fired' do
let(:message) { conversation.messages.last }
before do
allow(Conversations::UpdateMessageStatusJob).to receive(:perform_later)
end
it 'enqueues the UpdateMessageStatusJob with correct parameters if the message is found' do
params = {
recipient: {
id: 'chatwoot-app-user-id-1'
},
read: {
mid: message.source_id
}
}
described_class.new(params: params).perform
expect(Conversations::UpdateMessageStatusJob).to have_received(:perform_later).with(conversation.id, message.created_at)
end
it 'does not enqueue the UpdateMessageStatusJob if the message is not found' do
params = {
recipient: {
id: 'chatwoot-app-user-id-1'
},
read: {
mid: 'random-message-id'
}
}
described_class.new(params: params).perform
expect(Conversations::UpdateMessageStatusJob).not_to have_received(:perform_later)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Instagram::SendOnInstagramService < Base::SendOnChannelService
include HTTParty
pattr_initialize [:message!]
base_uri 'https://graph.facebook.com/v11.0/me'
private
delegate :additional_attributes, to: :contact
def channel_class
Channel::FacebookPage
end
def perform_reply
send_to_facebook_page attachament_message_params if message.attachments.present?
send_to_facebook_page message_params
rescue StandardError => e
ChatwootExceptionTracker.new(e, account: message.account, user: message.sender).capture_exception
# TODO : handle specific errors or else page will get disconnected
# channel.authorization_error!
end
def message_params
params = {
recipient: { id: contact.get_source_id(inbox.id) },
message: {
text: message.content
}
}
merge_human_agent_tag(params)
end
def attachament_message_params
attachment = message.attachments.first
params = {
recipient: { id: contact.get_source_id(inbox.id) },
message: {
attachment: {
type: attachment_type(attachment),
payload: {
url: attachment.download_url
}
}
}
}
merge_human_agent_tag(params)
end
# Deliver a message with the given payload.
# @see https://developers.facebook.com/docs/messenger-platform/instagram/features/send-message
def send_to_facebook_page(message_content)
access_token = channel.page_access_token
app_secret_proof = calculate_app_secret_proof(GlobalConfigService.load('FB_APP_SECRET', ''), access_token)
query = { access_token: access_token }
query[:appsecret_proof] = app_secret_proof if app_secret_proof
# url = "https://graph.facebook.com/v11.0/me/messages?access_token=#{access_token}"
response = HTTParty.post(
'https://graph.facebook.com/v11.0/me/messages',
body: message_content,
query: query
)
if response[:error].present?
Rails.logger.error("Instagram response: #{response['error']} : #{message_content}")
message.status = :failed
message.external_error = external_error(response)
end
message.source_id = response['message_id'] if response['message_id'].present?
message.save!
response
end
def external_error(response)
# https://developers.facebook.com/docs/instagram-api/reference/error-codes/
error_message = response[:error][:message]
error_code = response[:error][:code]
"#{error_code} - #{error_message}"
end
def calculate_app_secret_proof(app_secret, access_token)
Facebook::Messenger::Configuration::AppSecretProofCalculator.call(
app_secret, access_token
)
end
def attachment_type(attachment)
return attachment.file_type if %w[image audio video file].include? attachment.file_type
'file'
end
def conversation_type
conversation.additional_attributes['type']
end
def sent_first_outgoing_message_after_24_hours?
# we can send max 1 message after 24 hour window
conversation.messages.outgoing.where('id > ?', conversation.last_incoming_message.id).count == 1
end
def config
Facebook::Messenger.config
end
def merge_human_agent_tag(params)
global_config = GlobalConfig.get('ENABLE_MESSENGER_CHANNEL_HUMAN_AGENT')
return params unless global_config['ENABLE_MESSENGER_CHANNEL_HUMAN_AGENT']
params[:messaging_type] = 'MESSAGE_TAG'
params[:tag] = 'HUMAN_AGENT'
params
end
end
``` | require 'rails_helper'
describe Instagram::SendOnInstagramService do
subject(:send_reply_service) { described_class.new(message: message) }
before do
stub_request(:post, /graph.facebook.com/)
create(:message, message_type: :incoming, inbox: instagram_inbox, account: account, conversation: conversation)
end
let!(:account) { create(:account) }
let!(:instagram_channel) { create(:channel_instagram_fb_page, account: account, instagram_id: 'chatwoot-app-user-id-1') }
let!(:instagram_inbox) { create(:inbox, channel: instagram_channel, account: account, greeting_enabled: false) }
let!(:contact) { create(:contact, account: account) }
let(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: instagram_inbox) }
let(:conversation) { create(:conversation, contact: contact, inbox: instagram_inbox, contact_inbox: contact_inbox) }
let(:response) { double }
describe '#perform' do
context 'with reply' do
before do
allow(Facebook::Messenger::Configuration::AppSecretProofCalculator).to receive(:call).and_return('app_secret_key', 'access_token')
allow(HTTParty).to receive(:post).and_return(
{
'message_id': 'anyrandommessageid1234567890'
}
)
end
context 'without message_tag HUMAN_AGENT' do
before do
InstallationConfig.where(name: 'ENABLE_MESSENGER_CHANNEL_HUMAN_AGENT').first_or_create(value: false)
end
it 'if message is sent from chatwoot and is outgoing' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
allow(HTTParty).to receive(:post).with(
{
recipient: { id: contact.get_source_id(instagram_inbox.id) },
message: {
text: message.content
}
}
).and_return(
{
'message_id': 'anyrandommessageid1234567890'
}
)
response = described_class.new(message: message).perform
expect(response).to eq({ message_id: 'anyrandommessageid1234567890' })
end
it 'if message with attachment is sent from chatwoot and is outgoing' do
message = build(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
attachment = message.attachments.new(account_id: message.account_id, file_type: :image)
attachment.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
message.save!
response = described_class.new(message: message).perform
expect(response).to eq({ message_id: 'anyrandommessageid1234567890' })
end
it 'if message sent from chatwoot is failed' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
allow(HTTParty).to receive(:post).and_return(
{
'error': {
'message': 'The Instagram account is restricted.',
'type': 'OAuthException',
'code': 400,
'fbtrace_id': 'anyrandomfbtraceid1234567890'
}
}
)
described_class.new(message: message).perform
expect(HTTParty).to have_received(:post)
expect(message.reload.status).to eq('failed')
expect(message.reload.external_error).to eq('400 - The Instagram account is restricted.')
end
end
context 'with message_tag HUMAN_AGENT' do
before do
InstallationConfig.where(name: 'ENABLE_MESSENGER_CHANNEL_HUMAN_AGENT').first_or_create(value: true)
end
it 'if message is sent from chatwoot and is outgoing' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
allow(HTTParty).to receive(:post).with(
{
recipient: { id: contact.get_source_id(instagram_inbox.id) },
message: {
text: message.content
},
messaging_type: 'MESSAGE_TAG',
tag: 'HUMAN_AGENT'
}
).and_return(
{
'message_id': 'anyrandommessageid1234567890'
}
)
described_class.new(message: message).perform
expect(HTTParty).to have_received(:post)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# https://docs.360dialog.com/whatsapp-api/whatsapp-api/media
# https://developers.facebook.com/docs/whatsapp/api/media/
class Whatsapp::IncomingMessageService < Whatsapp::IncomingMessageBaseService
end
``` | require 'rails_helper'
describe Whatsapp::IncomingMessageService do
describe '#perform' do
before do
stub_request(:post, 'https://waba.360dialog.io/v1/configs/webhook')
end
let!(:whatsapp_channel) { create(:channel_whatsapp, sync_templates: false) }
let(:wa_id) { '2423423243' }
let!(:params) do
{
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => wa_id }],
'messages' => [{ 'from' => wa_id, 'id' => 'SDFADSf23sfasdafasdfa', 'text' => { 'body' => 'Test' },
'timestamp' => '1633034394', 'type' => 'text' }]
}.with_indifferent_access
end
context 'when valid text message params' do
it 'creates appropriate conversations, message and contacts' do
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('Test')
end
it 'appends to last conversation when if conversation already exists' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
2.times.each { create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox) }
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(3)
# message appended to the last conversation
expect(last_conversation.messages.last.content).to eq(params[:messages].first[:text][:body])
end
it 'reopen last conversation if last conversation is resolved and lock to single conversation is enabled' do
whatsapp_channel.inbox.update(lock_to_single_conversation: true)
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation.update(status: 'resolved')
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
# message appended to the last conversation
expect(last_conversation.messages.last.content).to eq(params[:messages].first[:text][:body])
expect(last_conversation.reload.status).to eq('open')
end
it 'creates a new conversation if last conversation is resolved and lock to single conversation is disabled' do
whatsapp_channel.inbox.update(lock_to_single_conversation: false)
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation.update(status: 'resolved')
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(2)
expect(contact_inbox.conversations.last.messages.last.content).to eq(params[:messages].first[:text][:body])
end
it 'will not create a new conversation if last conversation is not resolved and lock to single conversation is disabled' do
whatsapp_channel.inbox.update(lock_to_single_conversation: false)
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation.update(status: Conversation.statuses.except('resolved').keys.sample)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
expect(contact_inbox.conversations.last.messages.last.content).to eq(params[:messages].first[:text][:body])
end
it 'will not create duplicate messages when same message is received' do
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.messages.count).to eq(1)
# this shouldn't create a duplicate message
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.messages.count).to eq(1)
end
end
context 'when unsupported message types' do
it 'ignores type ephemeral' do
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{ 'from' => '2423423243', 'id' => 'SDFADSf23sfasdafasdfa', 'text' => { 'body' => 'Test' },
'timestamp' => '1633034394', 'type' => 'ephemeral' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.count).to eq(0)
end
it 'ignores type unsupported' do
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{
'errors' => [{ 'code': 131_051, 'title': 'Message type is currently not supported.' }],
:from => '2423423243', :id => 'wamid.SDFADSf23sfasdafasdfa',
:timestamp => '1667047370', :type => 'unsupported'
}]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.count).to eq(0)
end
end
context 'when valid status params' do
let(:from) { '2423423243' }
let(:contact_inbox) { create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: from) }
let(:params) do
{
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => from }],
'messages' => [{ 'from' => from, 'id' => from, 'text' => { 'body' => 'Test' },
'timestamp' => '1633034394', 'type' => 'text' }]
}.with_indifferent_access
end
before do
create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
end
it 'update status message to read' do
status_params = {
'statuses' => [{ 'recipient_id' => from, 'id' => from, 'status' => 'read' }]
}.with_indifferent_access
message = Message.find_by!(source_id: from)
expect(message.status).to eq('sent')
described_class.new(inbox: whatsapp_channel.inbox, params: status_params).perform
expect(message.reload.status).to eq('read')
end
it 'update status message to failed' do
status_params = {
'statuses' => [{ 'recipient_id' => from, 'id' => from, 'status' => 'failed',
'errors' => [{ 'code': 123, 'title': 'abc' }] }]
}.with_indifferent_access
message = Message.find_by!(source_id: from)
expect(message.status).to eq('sent')
described_class.new(inbox: whatsapp_channel.inbox, params: status_params).perform
expect(message.reload.status).to eq('failed')
expect(message.external_error).to eq('123: abc')
end
it 'will not throw error if unsupported status' do
status_params = {
'statuses' => [{ 'recipient_id' => from, 'id' => from, 'status' => 'deleted',
'errors' => [{ 'code': 123, 'title': 'abc' }] }]
}.with_indifferent_access
message = Message.find_by!(source_id: from)
expect(message.status).to eq('sent')
expect { described_class.new(inbox: whatsapp_channel.inbox, params: status_params).perform }.not_to raise_error
end
end
context 'when valid interactive message params' do
it 'creates appropriate conversations, message and contacts' do
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{ 'from' => '2423423243', 'id' => 'SDFADSf23sfasdafasdfa',
:interactive => {
'button_reply': {
'id': '1',
'title': 'First Button'
},
'type': 'button_reply'
},
'timestamp' => '1633034394', 'type' => 'interactive' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('First Button')
end
end
# ref: https://github.com/chatwoot/chatwoot/issues/3795#issuecomment-1018057318
context 'when valid template button message params' do
it 'creates appropriate conversations, message and contacts' do
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{ 'from' => '2423423243', 'id' => 'SDFADSf23sfasdafasdfa',
'button' => {
'text' => 'Yes this is a button'
},
'timestamp' => '1633034394', 'type' => 'button' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('Yes this is a button')
end
end
context 'when valid attachment message params' do
it 'creates appropriate conversations, message and contacts' do
stub_request(:get, whatsapp_channel.media_url('b1c68f38-8734-4ad3-b4a1-ef0c10d683')).to_return(
status: 200,
body: File.read('spec/assets/sample.png'),
headers: {}
)
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{ 'from' => '2423423243', 'id' => 'SDFADSf23sfasdafasdfa',
'image' => { 'id' => 'b1c68f38-8734-4ad3-b4a1-ef0c10d683',
'mime_type' => 'image/jpeg',
'sha256' => '29ed500fa64eb55fc19dc4124acb300e5dcca0f822a301ae99944db',
'caption' => 'Check out my product!' },
'timestamp' => '1633034394', 'type' => 'image' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('Check out my product!')
expect(whatsapp_channel.inbox.messages.first.attachments.present?).to be true
end
end
context 'when valid location message params' do
it 'creates appropriate conversations, message and contacts' do
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{ 'from' => '2423423243', 'id' => 'SDFADSf23sfasdafasdfa',
'location' => { 'id' => 'b1c68f38-8734-4ad3-b4a1-ef0c10d683',
:address => 'San Francisco, CA, USA',
:latitude => 37.7893768,
:longitude => -122.3895553,
:name => 'Bay Bridge',
:url => 'http://location_url.test' },
'timestamp' => '1633034394', 'type' => 'location' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
location_attachment = whatsapp_channel.inbox.messages.first.attachments.first
expect(location_attachment.file_type).to eq('location')
expect(location_attachment.fallback_title).to eq('Bay Bridge, San Francisco, CA, USA')
expect(location_attachment.coordinates_lat).to eq(37.7893768)
expect(location_attachment.coordinates_long).to eq(-122.3895553)
expect(location_attachment.external_url).to eq('http://location_url.test')
end
end
context 'when valid contact message params' do
it 'creates appropriate message and attachments' do
params = { 'contacts' => [{ 'profile' => { 'name' => 'Kedar' }, 'wa_id' => '919746334593' }],
'messages' => [{ 'from' => '919446284490',
'id' => 'wamid.SDFADSf23sfasdafasdfa',
'timestamp' => '1675823265',
'type' => 'contacts',
'contacts' => [
{
'name' => { 'formatted_name' => 'Apple Inc.' },
'phones' => [{ 'phone' => '+911800', 'type' => 'MAIN' }]
},
{ 'name' => { 'first_name' => 'Chatwoot', 'formatted_name' => 'Chatwoot' },
'phones' => [{ 'phone' => '+1 (415) 341-8386' }] }
] }] }.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(Contact.all.first.name).to eq('Kedar')
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
# Two messages are tested deliberately to ensure multiple contact attachments work.
m1 = whatsapp_channel.inbox.messages.first
contact_attachments = m1.attachments.first
expect(m1.content).to eq('Apple Inc.')
expect(contact_attachments.fallback_title).to eq('+911800')
m2 = whatsapp_channel.inbox.messages.last
contact_attachments = m2.attachments.first
expect(m2.content).to eq('Chatwoot')
expect(contact_attachments.fallback_title).to eq('+1 (415) 341-8386')
end
end
# ref: https://github.com/chatwoot/chatwoot/issues/5840
describe 'When the incoming waid is a brazilian number in new format with 9 included' do
let(:wa_id) { '5541988887777' }
it 'creates appropriate conversations, message and contacts if contact does not exit' do
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('Test')
expect(whatsapp_channel.inbox.contact_inboxes.first.source_id).to eq(wa_id)
end
it 'appends to existing contact if contact inbox exists' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: wa_id)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
# message appended to the last conversation
expect(last_conversation.messages.last.content).to eq(params[:messages].first[:text][:body])
end
end
describe 'When incoming waid is a brazilian number in old format without the 9 included' do
let(:wa_id) { '554188887777' }
context 'when a contact inbox exists in the old format without 9 included' do
it 'appends to existing contact' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: wa_id)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
# message appended to the last conversation
expect(last_conversation.messages.last.content).to eq(params[:messages].first[:text][:body])
end
end
context 'when a contact inbox exists in the new format with 9 included' do
it 'appends to existing contact' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: '5541988887777')
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
# message appended to the last conversation
expect(last_conversation.messages.last.content).to eq(params[:messages].first[:text][:body])
end
end
context 'when a contact inbox does not exist in the new format with 9 included' do
it 'creates contact inbox with the incoming waid' do
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('Test')
expect(whatsapp_channel.inbox.contact_inboxes.first.source_id).to eq(wa_id)
end
end
end
describe 'when message processing is in progress' do
it 'ignores the current message creation request' do
params = { 'contacts' => [{ 'profile' => { 'name' => 'Kedar' }, 'wa_id' => '919746334593' }],
'messages' => [{ 'from' => '919446284490',
'id' => 'wamid.SDFADSf23sfasdafasdfa',
'timestamp' => '1675823265',
'type' => 'contacts',
'contacts' => [
{
'name' => { 'formatted_name' => 'Apple Inc.' },
'phones' => [{ 'phone' => '+911800', 'type' => 'MAIN' }]
},
{ 'name' => { 'first_name' => 'Chatwoot', 'formatted_name' => 'Chatwoot' },
'phones' => [{ 'phone' => '+1 (415) 341-8386' }] }
] }] }.with_indifferent_access
expect(Message.find_by(source_id: 'wamid.SDFADSf23sfasdafasdfa')).not_to be_present
key = format(Redis::RedisKeys::MESSAGE_SOURCE_KEY, id: 'wamid.SDFADSf23sfasdafasdfa')
Redis::Alfred.setex(key, true)
expect(Redis::Alfred.get(key)).to be_truthy
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.messages.count).to eq(0)
expect(Message.find_by(source_id: 'wamid.SDFADSf23sfasdafasdfa')).not_to be_present
expect(Redis::Alfred.get(key)).to be_truthy
Redis::Alfred.delete(key)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Whatsapp::SendOnWhatsappService < Base::SendOnChannelService
private
def channel_class
Channel::Whatsapp
end
def perform_reply
should_send_template_message = template_params.present? || !message.conversation.can_reply?
if should_send_template_message
send_template_message
else
send_session_message
end
end
def send_template_message
name, namespace, lang_code, processed_parameters = processable_channel_message_template
return if name.blank?
message_id = channel.send_template(message.conversation.contact_inbox.source_id, {
name: name,
namespace: namespace,
lang_code: lang_code,
parameters: processed_parameters
})
message.update!(source_id: message_id) if message_id.present?
end
# rubocop:disable Metrics/CyclomaticComplexity
def processable_channel_message_template
if template_params.present?
return [
template_params['name'],
template_params['namespace'],
template_params['language'],
template_params['processed_params']&.map { |_, value| { type: 'text', text: value } }
]
end
# Delete the following logic once the update for template_params is stable
# see if we can match the message content to a template
# An example template may look like "Your package has been shipped. It will be delivered in {{1}} business days.
# We want to iterate over these templates with our message body and see if we can fit it to any of the templates
# Then we use regex to parse the template varibles and convert them into the proper payload
channel.message_templates&.each do |template|
match_obj = template_match_object(template)
next if match_obj.blank?
# we have a match, now we need to parse the template variables and convert them into the wa recommended format
processed_parameters = match_obj.captures.map { |x| { type: 'text', text: x } }
# no need to look up further end the search
return [template['name'], template['namespace'], template['language'], processed_parameters]
end
[nil, nil, nil, nil]
end
# rubocop:enable Metrics/CyclomaticComplexity
def template_match_object(template)
body_object = validated_body_object(template)
return if body_object.blank?
template_match_regex = build_template_match_regex(body_object['text'])
message.content.match(template_match_regex)
end
def build_template_match_regex(template_text)
# Converts the whatsapp template to a comparable regex string to check against the message content
# the variables are of the format {{num}} ex:{{1}}
# transform the template text into a regex string
# we need to replace the {{num}} with matchers that can be used to capture the variables
template_text = template_text.gsub(/{{\d}}/, '(.*)')
# escape if there are regex characters in the template text
template_text = Regexp.escape(template_text)
# ensuring only the variables remain as capture groups
template_text = template_text.gsub(Regexp.escape('(.*)'), '(.*)')
template_match_string = "^#{template_text}$"
Regexp.new template_match_string
end
def validated_body_object(template)
# we don't care if its not approved template
return if template['status'] != 'approved'
# we only care about text body object in template. if not present we discard the template
# we don't support other forms of templates
template['components'].find { |obj| obj['type'] == 'BODY' && obj.key?('text') }
end
def send_session_message
message_id = channel.send_message(message.conversation.contact_inbox.source_id, message)
message.update!(source_id: message_id) if message_id.present?
end
def template_params
message.additional_attributes && message.additional_attributes['template_params']
end
end
``` | require 'rails_helper'
describe Whatsapp::SendOnWhatsappService do
template_params = {
name: 'sample_shipping_confirmation',
namespace: '23423423_2342423_324234234_2343224',
language: 'en_US',
category: 'Marketing',
processed_params: { '1' => '3' }
}
describe '#perform' do
before do
stub_request(:post, 'https://waba.360dialog.io/v1/configs/webhook')
end
context 'when a valid message' do
let(:whatsapp_request) { double }
let!(:whatsapp_channel) { create(:channel_whatsapp, sync_templates: false) }
let!(:contact_inbox) { create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: '123456789') }
let!(:conversation) { create(:conversation, contact_inbox: contact_inbox, inbox: whatsapp_channel.inbox) }
it 'calls channel.send_message when with in 24 hour limit' do
# to handle the case of 24 hour window limit.
create(:message, message_type: :incoming, content: 'test',
conversation: conversation)
message = create(:message, message_type: :outgoing, content: 'test',
conversation: conversation)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: { 'to' => '123456789', 'text' => { 'body' => 'test' }, 'type' => 'text' }.to_json
)
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
it 'calls channel.send_template when after 24 hour limit' do
message = create(:message, message_type: :outgoing, content: 'Your package has been shipped. It will be delivered in 3 business days.',
conversation: conversation)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: {
to: '123456789',
template: {
name: 'sample_shipping_confirmation',
namespace: '23423423_2342423_324234234_2343224',
language: { 'policy': 'deterministic', 'code': 'en_US' },
components: [{ 'type': 'body', 'parameters': [{ 'type': 'text', 'text': '3' }] }]
},
type: 'template'
}.to_json
)
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
it 'calls channel.send_template if template_params are present' do
message = create(:message, additional_attributes: { template_params: template_params },
content: 'Your package will be delivered in 3 business days.', conversation: conversation, message_type: :outgoing)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: {
to: '123456789',
template: {
name: 'sample_shipping_confirmation',
namespace: '23423423_2342423_324234234_2343224',
language: { 'policy': 'deterministic', 'code': 'en_US' },
components: [{ 'type': 'body', 'parameters': [{ 'type': 'text', 'text': '3' }] }]
},
type: 'template'
}.to_json
)
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
it 'calls channel.send_template when template has regexp characters' do
message = create(
:message,
message_type: :outgoing,
content: 'عميلنا العزيز الرجاء الرد على هذه الرسالة بكلمة *نعم* للرد على إستفساركم من قبل خدمة العملاء.',
conversation: conversation
)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: {
to: '123456789',
template: {
name: 'customer_yes_no',
namespace: '2342384942_32423423_23423fdsdaf23',
language: { 'policy': 'deterministic', 'code': 'ar' },
components: [{ 'type': 'body', 'parameters': [] }]
},
type: 'template'
}.to_json
)
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# https://docs.360dialog.com/whatsapp-api/whatsapp-api/media
# https://developers.facebook.com/docs/whatsapp/api/media/
class Whatsapp::IncomingMessageWhatsappCloudService < Whatsapp::IncomingMessageBaseService
private
def processed_params
@processed_params ||= params[:entry].try(:first).try(:[], 'changes').try(:first).try(:[], 'value')
end
def download_attachment_file(attachment_payload)
url_response = HTTParty.get(inbox.channel.media_url(attachment_payload[:id]), headers: inbox.channel.api_headers)
# This url response will be failure if the access token has expired.
inbox.channel.authorization_error! if url_response.unauthorized?
Down.download(url_response.parsed_response['url'], headers: inbox.channel.api_headers) if url_response.success?
end
end
``` | require 'rails_helper'
describe Whatsapp::IncomingMessageWhatsappCloudService do
describe '#perform' do
let!(:whatsapp_channel) { create(:channel_whatsapp, provider: 'whatsapp_cloud', sync_templates: false, validate_provider_config: false) }
let(:params) do
{
phone_number: whatsapp_channel.phone_number,
object: 'whatsapp_business_account',
entry: [{
changes: [{
value: {
contacts: [{ profile: { name: 'Sojan Jose' }, wa_id: '2423423243' }],
messages: [{
from: '2423423243',
image: {
id: 'b1c68f38-8734-4ad3-b4a1-ef0c10d683',
mime_type: 'image/jpeg',
sha256: '29ed500fa64eb55fc19dc4124acb300e5dcca0f822a301ae99944db',
caption: 'Check out my product!'
},
timestamp: '1664799904', type: 'image'
}]
}
}]
}]
}.with_indifferent_access
end
context 'when valid attachment message params' do
it 'creates appropriate conversations, message and contacts' do
stub_request(:get, whatsapp_channel.media_url('b1c68f38-8734-4ad3-b4a1-ef0c10d683')).to_return(
status: 200,
body: {
messaging_product: 'whatsapp',
url: 'https://chatwoot-assets.local/sample.png',
mime_type: 'image/jpeg',
sha256: 'sha256',
file_size: 'SIZE',
id: 'b1c68f38-8734-4ad3-b4a1-ef0c10d683'
}.to_json,
headers: { 'content-type' => 'application/json' }
)
stub_request(:get, 'https://chatwoot-assets.local/sample.png').to_return(
status: 200,
body: File.read('spec/assets/sample.png')
)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('Check out my product!')
expect(whatsapp_channel.inbox.messages.first.attachments.present?).to be true
end
it 'increments reauthorization count if fetching attachment fails' do
stub_request(:get, whatsapp_channel.media_url('b1c68f38-8734-4ad3-b4a1-ef0c10d683')).to_return(
status: 401
)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.first.content).to eq('Check out my product!')
expect(whatsapp_channel.inbox.messages.first.attachments.present?).to be false
expect(whatsapp_channel.authorization_error_count).to eq(1)
end
end
context 'when invalid attachment message params' do
let(:error_params) do
{
phone_number: whatsapp_channel.phone_number,
object: 'whatsapp_business_account',
entry: [{
changes: [{
value: {
contacts: [{ profile: { name: 'Sojan Jose' }, wa_id: '2423423243' }],
messages: [{
from: '2423423243',
image: {
id: 'b1c68f38-8734-4ad3-b4a1-ef0c10d683',
mime_type: 'image/jpeg',
sha256: '29ed500fa64eb55fc19dc4124acb300e5dcca0f822a301ae99944db',
caption: 'Check out my product!'
},
errors: [{
code: 400,
details: 'Last error was: ServerThrottle. Http request error: HTTP response code said error. See logs for details',
title: 'Media download failed: Not retrying as download is not retriable at this time'
}],
timestamp: '1664799904', type: 'image'
}]
}
}]
}]
}.with_indifferent_access
end
it 'with attachment errors' do
described_class.new(inbox: whatsapp_channel.inbox, params: error_params).perform
expect(whatsapp_channel.inbox.conversations.count).not_to eq(0)
expect(Contact.all.first.name).to eq('Sojan Jose')
expect(whatsapp_channel.inbox.messages.count).to eq(0)
end
end
context 'when invalid params' do
it 'will not throw error' do
described_class.new(inbox: whatsapp_channel.inbox, params: { phone_number: whatsapp_channel.phone_number,
object: 'whatsapp_business_account', entry: {} }).perform
expect(whatsapp_channel.inbox.conversations.count).to eq(0)
expect(Contact.all.first).to be_nil
expect(whatsapp_channel.inbox.messages.count).to eq(0)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseService
def send_message(phone_number, message)
if message.attachments.present?
send_attachment_message(phone_number, message)
elsif message.content_type == 'input_select'
send_interactive_text_message(phone_number, message)
else
send_text_message(phone_number, message)
end
end
def send_template(phone_number, template_info)
response = HTTParty.post(
"#{phone_id_path}/messages",
headers: api_headers,
body: {
messaging_product: 'whatsapp',
to: phone_number,
template: template_body_parameters(template_info),
type: 'template'
}.to_json
)
process_response(response)
end
def sync_templates
# ensuring that channels with wrong provider config wouldn't keep trying to sync templates
whatsapp_channel.mark_message_templates_updated
templates = fetch_whatsapp_templates("#{business_account_path}/message_templates?access_token=#{whatsapp_channel.provider_config['api_key']}")
whatsapp_channel.update(message_templates: templates, message_templates_last_updated: Time.now.utc) if templates.present?
end
def fetch_whatsapp_templates(url)
response = HTTParty.get(url)
return [] unless response.success?
next_url = next_url(response)
return response['data'] + fetch_whatsapp_templates(next_url) if next_url.present?
response['data']
end
def next_url(response)
response['paging'] ? response['paging']['next'] : ''
end
def validate_provider_config?
response = HTTParty.get("#{business_account_path}/message_templates?access_token=#{whatsapp_channel.provider_config['api_key']}")
response.success?
end
def api_headers
{ 'Authorization' => "Bearer #{whatsapp_channel.provider_config['api_key']}", 'Content-Type' => 'application/json' }
end
def media_url(media_id)
"#{api_base_path}/v13.0/#{media_id}"
end
def api_base_path
ENV.fetch('WHATSAPP_CLOUD_BASE_URL', 'https://graph.facebook.com')
end
# TODO: See if we can unify the API versions and for both paths and make it consistent with out facebook app API versions
def phone_id_path
"#{api_base_path}/v13.0/#{whatsapp_channel.provider_config['phone_number_id']}"
end
def business_account_path
"#{api_base_path}/v14.0/#{whatsapp_channel.provider_config['business_account_id']}"
end
def send_text_message(phone_number, message)
response = HTTParty.post(
"#{phone_id_path}/messages",
headers: api_headers,
body: {
messaging_product: 'whatsapp',
context: whatsapp_reply_context(message),
to: phone_number,
text: { body: message.content },
type: 'text'
}.to_json
)
process_response(response)
end
def send_attachment_message(phone_number, message)
attachment = message.attachments.first
type = %w[image audio video].include?(attachment.file_type) ? attachment.file_type : 'document'
type_content = {
'link': attachment.download_url
}
type_content['caption'] = message.content unless %w[audio sticker].include?(type)
type_content['filename'] = attachment.file.filename if type == 'document'
response = HTTParty.post(
"#{phone_id_path}/messages",
headers: api_headers,
body: {
:messaging_product => 'whatsapp',
:context => whatsapp_reply_context(message),
'to' => phone_number,
'type' => type,
type.to_s => type_content
}.to_json
)
process_response(response)
end
def process_response(response)
if response.success?
response['messages'].first['id']
else
Rails.logger.error response.body
nil
end
end
def template_body_parameters(template_info)
{
name: template_info[:name],
language: {
policy: 'deterministic',
code: template_info[:lang_code]
},
components: [{
type: 'body',
parameters: template_info[:parameters]
}]
}
end
def whatsapp_reply_context(message)
reply_to = message.content_attributes[:in_reply_to_external_id]
return nil if reply_to.blank?
{
message_id: reply_to
}
end
def send_interactive_text_message(phone_number, message)
payload = create_payload_based_on_items(message)
response = HTTParty.post(
"#{phone_id_path}/messages",
headers: api_headers,
body: {
messaging_product: 'whatsapp',
to: phone_number,
interactive: payload,
type: 'interactive'
}.to_json
)
process_response(response)
end
end
``` | require 'rails_helper'
describe Whatsapp::Providers::WhatsappCloudService do
subject(:service) { described_class.new(whatsapp_channel: whatsapp_channel) }
let(:conversation) { create(:conversation, inbox: whatsapp_channel.inbox) }
let(:whatsapp_channel) { create(:channel_whatsapp, provider: 'whatsapp_cloud', validate_provider_config: false, sync_templates: false) }
let(:message) do
create(:message, conversation: conversation, message_type: :outgoing, content: 'test', inbox: whatsapp_channel.inbox, source_id: 'external_id')
end
let(:message_with_reply) do
create(:message, conversation: conversation, message_type: :outgoing, content: 'reply', inbox: whatsapp_channel.inbox,
content_attributes: { in_reply_to: message.id })
end
let(:response_headers) { { 'Content-Type' => 'application/json' } }
let(:whatsapp_response) { { messages: [{ id: 'message_id' }] } }
before do
stub_request(:get, 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key')
end
describe '#send_message' do
context 'when called' do
it 'calls message endpoints for normal messages' do
stub_request(:post, 'https://graph.facebook.com/v13.0/123456789/messages')
.with(
body: {
messaging_product: 'whatsapp',
context: nil,
to: '+123456789',
text: { body: message.content },
type: 'text'
}.to_json
)
.to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_message('+123456789', message)).to eq 'message_id'
end
it 'calls message endpoints for a reply to messages' do
stub_request(:post, 'https://graph.facebook.com/v13.0/123456789/messages')
.with(
body: {
messaging_product: 'whatsapp',
context: {
message_id: message.source_id
},
to: '+123456789',
text: { body: message_with_reply.content },
type: 'text'
}.to_json
)
.to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_message('+123456789', message_with_reply)).to eq 'message_id'
end
it 'calls message endpoints for image attachment message messages' do
attachment = message.attachments.new(account_id: message.account_id, file_type: :image)
attachment.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
stub_request(:post, 'https://graph.facebook.com/v13.0/123456789/messages')
.with(
body: hash_including({
messaging_product: 'whatsapp',
to: '+123456789',
type: 'image',
image: WebMock::API.hash_including({ caption: message.content, link: anything })
})
)
.to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_message('+123456789', message)).to eq 'message_id'
end
it 'calls message endpoints for document attachment message messages' do
attachment = message.attachments.new(account_id: message.account_id, file_type: :file)
attachment.file.attach(io: Rails.root.join('spec/assets/sample.pdf').open, filename: 'sample.pdf', content_type: 'application/pdf')
# ref: https://github.com/bblimke/webmock/issues/900
# reason for Webmock::API.hash_including
stub_request(:post, 'https://graph.facebook.com/v13.0/123456789/messages')
.with(
body: hash_including({
messaging_product: 'whatsapp',
to: '+123456789',
type: 'document',
document: WebMock::API.hash_including({ filename: 'sample.pdf', caption: message.content, link: anything })
})
)
.to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_message('+123456789', message)).to eq 'message_id'
end
end
end
describe '#send_interactive message' do
context 'when called' do
it 'calls message endpoints with button payload when number of items is less than or equal to 3' do
message = create(:message, message_type: :outgoing, content: 'test',
inbox: whatsapp_channel.inbox, content_type: 'input_select',
content_attributes: {
items: [
{ title: 'Burito', value: 'Burito' },
{ title: 'Pasta', value: 'Pasta' },
{ title: 'Sushi', value: 'Sushi' }
]
})
stub_request(:post, 'https://graph.facebook.com/v13.0/123456789/messages')
.with(
body: {
messaging_product: 'whatsapp', to: '+123456789',
interactive: {
type: 'button',
body: {
text: 'test'
},
action: '{"buttons":[{"type":"reply","reply":{"id":"Burito","title":"Burito"}},{"type":"reply",' \
'"reply":{"id":"Pasta","title":"Pasta"}},{"type":"reply","reply":{"id":"Sushi","title":"Sushi"}}]}'
}, type: 'interactive'
}.to_json
).to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_message('+123456789', message)).to eq 'message_id'
end
it 'calls message endpoints with list payload when number of items is greater than 3' do
message = create(:message, message_type: :outgoing, content: 'test', inbox: whatsapp_channel.inbox,
content_type: 'input_select',
content_attributes: {
items: [
{ title: 'Burito', value: 'Burito' },
{ title: 'Pasta', value: 'Pasta' },
{ title: 'Sushi', value: 'Sushi' },
{ title: 'Salad', value: 'Salad' }
]
})
stub_request(:post, 'https://graph.facebook.com/v13.0/123456789/messages')
.with(
body: {
messaging_product: 'whatsapp', to: '+123456789',
interactive: {
type: 'list',
body: {
text: 'test'
},
action: '{"button":"Choose an item","sections":[{"rows":[{"id":"Burito","title":"Burito"},' \
'{"id":"Pasta","title":"Pasta"},{"id":"Sushi","title":"Sushi"},{"id":"Salad","title":"Salad"}]}]}'
}, type: 'interactive'
}.to_json
).to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_message('+123456789', message)).to eq 'message_id'
end
end
end
describe '#send_template' do
let(:template_info) do
{
name: 'test_template',
namespace: 'test_namespace',
lang_code: 'en_US',
parameters: [{ type: 'text', text: 'test' }]
}
end
let(:template_body) do
{
messaging_product: 'whatsapp',
to: '+123456789',
template: {
name: template_info[:name],
language: {
policy: 'deterministic',
code: template_info[:lang_code]
},
components: [
{ type: 'body',
parameters: template_info[:parameters] }
]
},
type: 'template'
}
end
context 'when called' do
it 'calls message endpoints with template params for template messages' do
stub_request(:post, 'https://graph.facebook.com/v13.0/123456789/messages')
.with(
body: template_body.to_json
)
.to_return(status: 200, body: whatsapp_response.to_json, headers: response_headers)
expect(service.send_template('+123456789', template_info)).to eq('message_id')
end
end
end
describe '#sync_templates' do
context 'when called' do
it 'updated the message templates' do
stub_request(:get, 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key')
.to_return(
{ status: 200, headers: response_headers,
body: { data: [
{ id: '123456789', name: 'test_template' }
], paging: { next: 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key' } }.to_json },
{ status: 200, headers: response_headers,
body: { data: [
{ id: '123456789', name: 'next_template' }
], paging: { next: 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key' } }.to_json },
{ status: 200, headers: response_headers,
body: { data: [
{ id: '123456789', name: 'last_template' }
], paging: { prev: 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key' } }.to_json }
)
timstamp = whatsapp_channel.reload.message_templates_last_updated
expect(subject.sync_templates).to be(true)
expect(whatsapp_channel.reload.message_templates.first).to eq({ id: '123456789', name: 'test_template' }.stringify_keys)
expect(whatsapp_channel.reload.message_templates.second).to eq({ id: '123456789', name: 'next_template' }.stringify_keys)
expect(whatsapp_channel.reload.message_templates.last).to eq({ id: '123456789', name: 'last_template' }.stringify_keys)
expect(whatsapp_channel.reload.message_templates_last_updated).not_to eq(timstamp)
end
it 'updates message_templates_last_updated even when template request fails' do
stub_request(:get, 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key')
.to_return(status: 401)
timstamp = whatsapp_channel.reload.message_templates_last_updated
subject.sync_templates
expect(whatsapp_channel.reload.message_templates_last_updated).not_to eq(timstamp)
end
end
end
describe '#validate_provider_config' do
context 'when called' do
it 'returns true if valid' do
stub_request(:get, 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key')
expect(subject.validate_provider_config?).to be(true)
expect(whatsapp_channel.errors.present?).to be(false)
end
it 'returns false if invalid' do
stub_request(:get, 'https://graph.facebook.com/v14.0/123456789/message_templates?access_token=test_key').to_return(status: 401)
expect(subject.validate_provider_config?).to be(false)
end
end
end
describe 'Ability to configure Base URL' do
context 'when environment variable WHATSAPP_CLOUD_BASE_URL is not set' do
it 'uses the default base url' do
expect(subject.send(:api_base_path)).to eq('https://graph.facebook.com')
end
end
context 'when environment variable WHATSAPP_CLOUD_BASE_URL is set' do
it 'uses the base url from the environment variable' do
with_modified_env WHATSAPP_CLOUD_BASE_URL: 'http://test.com' do
expect(subject.send(:api_base_path)).to eq('http://test.com')
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Twilio::DeliveryStatusService
pattr_initialize [:params!]
# Reference: https://www.twilio.com/docs/messaging/api/message-resource#message-status-values
def perform
return if twilio_channel.blank?
return unless supported_status?
process_statuses if message.present?
end
private
def process_statuses
@message.status = status
@message.external_error = external_error if error_occurred?
@message.save!
end
def supported_status?
%w[sent delivered read failed undelivered].include?(params[:MessageStatus])
end
def status
params[:MessageStatus] == 'undelivered' ? 'failed' : params[:MessageStatus]
end
def external_error
return nil unless error_occurred?
error_message = params[:ErrorMessage].presence
error_code = params[:ErrorCode]
if error_message.present?
"#{error_code} - #{error_message}"
elsif error_code.present?
I18n.t('conversations.messages.delivery_status.error_code', error_code: error_code)
end
end
def error_occurred?
params[:ErrorCode].present? && %w[failed undelivered].include?(params[:MessageStatus])
end
def twilio_channel
@twilio_channel ||= if params[:MessagingServiceSid].present?
::Channel::TwilioSms.find_by(messaging_service_sid: params[:MessagingServiceSid])
elsif params[:AccountSid].present? && params[:From].present?
::Channel::TwilioSms.find_by!(account_sid: params[:AccountSid], phone_number: params[:From])
end
end
def message
return unless params[:MessageSid]
@message ||= twilio_channel.inbox.messages.find_by(source_id: params[:MessageSid])
end
end
``` | require 'rails_helper'
describe Twilio::DeliveryStatusService do
let!(:account) { create(:account) }
let!(:twilio_channel) do
create(:channel_twilio_sms, account: account, account_sid: 'ACxxx',
inbox: create(:inbox, account: account, greeting_enabled: false))
end
let!(:contact) { create(:contact, account: account, phone_number: '+12345') }
let(:contact_inbox) { create(:contact_inbox, source_id: '+12345', contact: contact, inbox: twilio_channel.inbox) }
let!(:conversation) { create(:conversation, contact: contact, inbox: twilio_channel.inbox, contact_inbox: contact_inbox) }
describe '#perform' do
context 'when message delivery status is fired' do
before do
create(:message, account: account, inbox: twilio_channel.inbox, conversation: conversation, status: :sent,
source_id: 'SMd560ac79e4a4d36b3ce59f1f50471986')
end
it 'updates the message if the status is delivered' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
MessageSid: conversation.messages.last.source_id,
MessageStatus: 'delivered'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.status).to eq('delivered')
end
it 'updates the message if the status is read' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
MessageSid: conversation.messages.last.source_id,
MessageStatus: 'read'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.status).to eq('read')
end
it 'does not update the message if the status is not a support status' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
MessageSid: conversation.messages.last.source_id,
MessageStatus: 'queued'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.status).to eq('sent')
end
it 'updates message status to failed if message status is undelivered' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
MessageSid: conversation.messages.last.source_id,
MessageStatus: 'undelivered',
ErrorCode: '30002',
ErrorMessage: 'Account suspended'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.status).to eq('failed')
expect(conversation.reload.messages.last.external_error).to eq('30002 - Account suspended')
end
it 'updates message status to failed and updates the error message if message status is failed' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
MessageSid: conversation.messages.last.source_id,
MessageStatus: 'failed',
ErrorCode: '30008',
ErrorMessage: 'Unknown error'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.status).to eq('failed')
expect(conversation.reload.messages.last.external_error).to eq('30008 - Unknown error')
end
it 'updates the error message if message status is undelivered and error message is not present' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
MessageSid: conversation.messages.last.source_id,
MessageStatus: 'failed',
ErrorCode: '30008'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.status).to eq('failed')
expect(conversation.reload.messages.last.external_error).to eq('Error code: 30008')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Twilio::IncomingMessageService
include ::FileTypeHelper
pattr_initialize [:params!]
def perform
return if twilio_channel.blank?
set_contact
set_conversation
@message = @conversation.messages.create!(
content: message_body,
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: :incoming,
sender: @contact,
source_id: params[:SmsSid]
)
attach_files
end
private
def twilio_channel
@twilio_channel ||= ::Channel::TwilioSms.find_by(messaging_service_sid: params[:MessagingServiceSid]) if params[:MessagingServiceSid].present?
if params[:AccountSid].present? && params[:To].present?
@twilio_channel ||= ::Channel::TwilioSms.find_by!(account_sid: params[:AccountSid],
phone_number: params[:To])
end
@twilio_channel
end
def inbox
@inbox ||= twilio_channel.inbox
end
def account
@account ||= inbox.account
end
def phone_number
twilio_channel.sms? ? params[:From] : params[:From].gsub('whatsapp:', '')
end
def formatted_phone_number
TelephoneNumber.parse(phone_number).international_number
end
def message_body
params[:Body]&.delete("\u0000")
end
def set_contact
contact_inbox = ::ContactInboxWithContactBuilder.new(
source_id: params[:From],
inbox: inbox,
contact_attributes: contact_attributes
).perform
@contact_inbox = contact_inbox
@contact = contact_inbox.contact
end
def conversation_params
{
account_id: @inbox.account_id,
inbox_id: @inbox.id,
contact_id: @contact.id,
contact_inbox_id: @contact_inbox.id,
additional_attributes: additional_attributes
}
end
def set_conversation
# if lock to single conversation is disabled, we will create a new conversation if previous conversation is resolved
@conversation = if @inbox.lock_to_single_conversation
@contact_inbox.conversations.last
else
@contact_inbox.conversations.where
.not(status: :resolved).last
end
return if @conversation
@conversation = ::Conversation.create!(conversation_params)
end
def contact_attributes
{
name: formatted_phone_number,
phone_number: phone_number,
additional_attributes: additional_attributes
}
end
def additional_attributes
if twilio_channel.sms?
{
from_zip_code: params[:FromZip],
from_country: params[:FromCountry],
from_state: params[:FromState]
}
else
{}
end
end
def attach_files
return if params[:MediaUrl0].blank?
attachment_file = Down.download(
params[:MediaUrl0],
# https://support.twilio.com/hc/en-us/articles/223183748-Protect-Media-Access-with-HTTP-Basic-Authentication-for-Programmable-Messaging
http_basic_authentication: [twilio_channel.account_sid, twilio_channel.auth_token || twilio_channel.api_key_sid]
)
attachment = @message.attachments.new(
account_id: @message.account_id,
file_type: file_type(params[:MediaContentType0])
)
attachment.file.attach(
io: attachment_file,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
)
@message.save!
end
end
``` | require 'rails_helper'
describe Twilio::IncomingMessageService do
let!(:account) { create(:account) }
let!(:twilio_channel) do
create(:channel_twilio_sms, account: account, account_sid: 'ACxxx',
inbox: create(:inbox, account: account, greeting_enabled: false))
end
let!(:contact) { create(:contact, account: account, phone_number: '+12345') }
let(:contact_inbox) { create(:contact_inbox, source_id: '+12345', contact: contact, inbox: twilio_channel.inbox) }
let!(:conversation) { create(:conversation, contact: contact, inbox: twilio_channel.inbox, contact_inbox: contact_inbox) }
describe '#perform' do
it 'creates a new message in existing conversation' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
Body: 'testing3'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.content).to eq('testing3')
end
it 'removes null bytes' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
Body: "remove\u0000 null bytes\u0000"
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.content).to eq('remove null bytes')
end
it 'wont throw error when the body is empty' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.content).to be_nil
end
it 'creates a new conversation when payload is from different number' do
params = {
SmsSid: 'SMxx',
From: '+123456',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
Body: 'new conversation'
}
described_class.new(params: params).perform
expect(twilio_channel.inbox.conversations.count).to eq(2)
end
# Since we support the case with phone number as well. the previous case is with accoud_sid and messaging_service_sid
context 'with a phone number' do
let!(:twilio_channel) do
create(:channel_twilio_sms, :with_phone_number, account: account, account_sid: 'ACxxx',
inbox: create(:inbox, account: account, greeting_enabled: false))
end
it 'creates a new message in existing conversation' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
To: twilio_channel.phone_number,
Body: 'testing3'
}
described_class.new(params: params).perform
expect(conversation.reload.messages.last.content).to eq('testing3')
end
it 'creates a new conversation when payload is from different number' do
params = {
SmsSid: 'SMxx',
From: '+123456',
AccountSid: 'ACxxx',
To: twilio_channel.phone_number,
Body: 'new conversation'
}
described_class.new(params: params).perform
expect(twilio_channel.inbox.conversations.count).to eq(2)
end
it 'reopen last conversation if last conversation is resolved and lock to single conversation is enabled' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
To: twilio_channel.phone_number,
Body: 'testing3'
}
twilio_channel.inbox.update(lock_to_single_conversation: true)
conversation.update(status: 'resolved')
described_class.new(params: params).perform
# message appended to the last conversation
expect(conversation.reload.messages.last.content).to eq('testing3')
expect(conversation.reload.status).to eq('open')
end
it 'creates a new conversation if last conversation is resolved and lock to single conversation is disabled' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
To: twilio_channel.phone_number,
Body: 'testing3'
}
twilio_channel.inbox.update(lock_to_single_conversation: false)
conversation.update(status: 'resolved')
described_class.new(params: params).perform
expect(twilio_channel.inbox.conversations.count).to eq(2)
expect(twilio_channel.inbox.conversations.last.messages.last.content).to eq('testing3')
end
it 'will not create a new conversation if last conversation is not resolved and lock to single conversation is disabled' do
params = {
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
To: twilio_channel.phone_number,
Body: 'testing3'
}
twilio_channel.inbox.update(lock_to_single_conversation: false)
conversation.update(status: Conversation.statuses.except('resolved').keys.sample)
described_class.new(params: params).perform
expect(twilio_channel.inbox.conversations.count).to eq(1)
expect(twilio_channel.inbox.conversations.last.messages.last.content).to eq('testing3')
end
end
context 'with multiple channels configured' do
before do
2.times.each do
create(:channel_twilio_sms, :with_phone_number, account: account, account_sid: 'ACxxx', messaging_service_sid: nil,
inbox: create(:inbox, account: account, greeting_enabled: false))
end
end
it 'creates a new conversation in appropriate channel' do
twilio_sms_channel = create(:channel_twilio_sms, :with_phone_number, account: account, account_sid: 'ACxxx',
inbox: create(:inbox, account: account, greeting_enabled: false))
params = {
SmsSid: 'SMxx',
From: '+123456',
AccountSid: 'ACxxx',
To: twilio_sms_channel.phone_number,
Body: 'new conversation'
}
described_class.new(params: params).perform
expect(twilio_sms_channel.inbox.conversations.count).to eq(1)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Twilio::WebhookSetupService
include Rails.application.routes.url_helpers
pattr_initialize [:inbox!]
def perform
if channel.messaging_service_sid?
update_messaging_service
else
update_phone_number
end
end
private
def update_messaging_service
twilio_client
.messaging.services(channel.messaging_service_sid)
.update(
inbound_method: 'POST',
inbound_request_url: twilio_callback_index_url,
use_inbound_webhook_on_number: false
)
end
def update_phone_number
if phone_numbers.empty?
Rails.logger.warn "TWILIO_PHONE_NUMBER_NOT_FOUND: #{channel.phone_number}"
else
twilio_client
.incoming_phone_numbers(phonenumber_sid)
.update(sms_method: 'POST', sms_url: twilio_callback_index_url)
end
end
def phonenumber_sid
phone_numbers.first.sid
end
def phone_numbers
@phone_numbers ||= twilio_client.incoming_phone_numbers.list(phone_number: channel.phone_number)
end
def channel
@channel ||= inbox.channel
end
def twilio_client
@twilio_client ||= ::Twilio::REST::Client.new(channel.account_sid, channel.auth_token)
end
end
``` | require 'rails_helper'
describe Twilio::WebhookSetupService do
include Rails.application.routes.url_helpers
let(:twilio_client) { instance_double(Twilio::REST::Client) }
before do
allow(Twilio::REST::Client).to receive(:new).and_return(twilio_client)
end
describe '#perform' do
context 'with a messaging service sid' do
let(:channel_twilio_sms) { create(:channel_twilio_sms) }
let(:messaging) { instance_double(Twilio::REST::Messaging) }
let(:services) { instance_double(Twilio::REST::Messaging::V1::ServiceContext) }
before do
allow(twilio_client).to receive(:messaging).and_return(messaging)
allow(messaging).to receive(:services).with(channel_twilio_sms.messaging_service_sid).and_return(services)
allow(services).to receive(:update)
end
it 'updates the messaging service' do
described_class.new(inbox: channel_twilio_sms.inbox).perform
expect(services).to have_received(:update)
end
end
context 'with a phone number' do
let(:channel_twilio_sms) { create(:channel_twilio_sms, :with_phone_number) }
let(:phone_double) { double }
let(:phone_record_double) { double }
before do
allow(phone_double).to receive(:update)
allow(phone_record_double).to receive(:sid).and_return('1234')
end
it 'logs error if phone_number is not found' do
allow(twilio_client).to receive(:incoming_phone_numbers).and_return(phone_double)
allow(phone_double).to receive(:list).and_return([])
described_class.new(inbox: channel_twilio_sms.inbox).perform
expect(phone_double).not_to have_received(:update)
end
it 'update webhook_url if phone_number is found' do
allow(twilio_client).to receive(:incoming_phone_numbers).and_return(phone_double)
allow(phone_double).to receive(:list).and_return([phone_record_double])
described_class.new(inbox: channel_twilio_sms.inbox).perform
expect(phone_double).to have_received(:update).with(
sms_method: 'POST',
sms_url: twilio_callback_index_url
)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Twilio::SendOnTwilioService < Base::SendOnChannelService
private
def channel_class
Channel::TwilioSms
end
def perform_reply
begin
twilio_message = channel.send_message(**message_params)
rescue Twilio::REST::TwilioError, Twilio::REST::RestError => e
message.update!(status: :failed, external_error: e.message)
end
message.update!(source_id: twilio_message.sid) if twilio_message
end
def message_params
{
body: message.content,
to: contact_inbox.source_id,
media_url: attachments
}
end
def attachments
message.attachments.map(&:download_url)
end
def inbox
@inbox ||= message.inbox
end
def channel
@channel ||= inbox.channel
end
def outgoing_message?
message.outgoing? || message.template?
end
end
``` | require 'rails_helper'
describe Twilio::SendOnTwilioService do
subject(:outgoing_message_service) { described_class.new(message: message) }
let(:twilio_client) { instance_double(Twilio::REST::Client) }
let(:messages_double) { double }
let(:message_record_double) { double }
let!(:account) { create(:account) }
let!(:widget_inbox) { create(:inbox, account: account) }
let!(:twilio_sms) { create(:channel_twilio_sms, account: account) }
let!(:twilio_whatsapp) { create(:channel_twilio_sms, medium: :whatsapp, account: account) }
let!(:twilio_inbox) { create(:inbox, channel: twilio_sms, account: account) }
let!(:twilio_whatsapp_inbox) { create(:inbox, channel: twilio_whatsapp, account: account) }
let!(:contact) { create(:contact, account: account) }
let(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: twilio_inbox) }
let(:conversation) { create(:conversation, contact: contact, inbox: twilio_inbox, contact_inbox: contact_inbox) }
before do
allow(Twilio::REST::Client).to receive(:new).and_return(twilio_client)
allow(twilio_client).to receive(:messages).and_return(messages_double)
end
describe '#perform' do
context 'without reply' do
it 'if message is private' do
message = create(:message, message_type: 'outgoing', private: true, inbox: twilio_inbox, account: account)
described_class.new(message: message).perform
expect(twilio_client).not_to have_received(:messages)
expect(message.reload.source_id).to be_nil
end
it 'if inbox channel is not twilio' do
message = create(:message, message_type: 'outgoing', inbox: widget_inbox, account: account)
expect { described_class.new(message: message).perform }.to raise_error 'Invalid channel service was called'
expect(twilio_client).not_to have_received(:messages)
end
it 'if message is not outgoing' do
message = create(:message, message_type: 'incoming', inbox: twilio_inbox, account: account)
described_class.new(message: message).perform
expect(twilio_client).not_to have_received(:messages)
expect(message.reload.source_id).to be_nil
end
it 'if message has an source id' do
message = create(:message, message_type: 'outgoing', inbox: twilio_inbox, account: account, source_id: SecureRandom.uuid)
described_class.new(message: message).perform
expect(twilio_client).not_to have_received(:messages)
end
end
context 'with reply' do
it 'if message is sent from chatwoot and is outgoing' do
allow(messages_double).to receive(:create).and_return(message_record_double)
allow(message_record_double).to receive(:sid).and_return('1234')
outgoing_message = create(
:message, message_type: 'outgoing', inbox: twilio_inbox, account: account, conversation: conversation
)
described_class.new(message: outgoing_message).perform
expect(outgoing_message.reload.source_id).to eq('1234')
end
end
it 'if outgoing message has attachment and is for whatsapp' do
# check for message attachment url
allow(messages_double).to receive(:create).with(hash_including(media_url: [anything])).and_return(message_record_double)
allow(message_record_double).to receive(:sid).and_return('1234')
message = build(
:message, message_type: 'outgoing', inbox: twilio_whatsapp_inbox, account: account, conversation: conversation
)
attachment = message.attachments.new(account_id: message.account_id, file_type: :image)
attachment.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
message.save!
described_class.new(message: message).perform
expect(messages_double).to have_received(:create).with(hash_including(media_url: [anything]))
end
it 'if outgoing message has attachment and is for sms' do
# check for message attachment url
allow(messages_double).to receive(:create).with(hash_including(media_url: [anything])).and_return(message_record_double)
allow(message_record_double).to receive(:sid).and_return('1234')
message = build(
:message, message_type: 'outgoing', inbox: twilio_inbox, account: account, conversation: conversation
)
attachment = message.attachments.new(account_id: message.account_id, file_type: :image)
attachment.file.attach(io: Rails.root.join('spec/assets/avatar.png').open, filename: 'avatar.png', content_type: 'image/png')
message.save!
described_class.new(message: message).perform
expect(messages_double).to have_received(:create).with(hash_including(media_url: [anything]))
end
it 'if message is sent from chatwoot fails' do
allow(messages_double).to receive(:create).and_raise(Twilio::REST::TwilioError)
outgoing_message = create(
:message, message_type: 'outgoing', inbox: twilio_inbox, account: account, conversation: conversation
)
described_class.new(message: outgoing_message).perform
expect(outgoing_message.reload.status).to eq('failed')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Twilio::OneoffSmsCampaignService
pattr_initialize [:campaign!]
def perform
raise "Invalid campaign #{campaign.id}" if campaign.inbox.inbox_type != 'Twilio SMS' || !campaign.one_off?
raise 'Completed Campaign' if campaign.completed?
# marks campaign completed so that other jobs won't pick it up
campaign.completed!
audience_label_ids = campaign.audience.select { |audience| audience['type'] == 'Label' }.pluck('id')
audience_labels = campaign.account.labels.where(id: audience_label_ids).pluck(:title)
process_audience(audience_labels)
end
private
delegate :inbox, to: :campaign
delegate :channel, to: :inbox
def process_audience(audience_labels)
campaign.account.contacts.tagged_with(audience_labels, any: true).each do |contact|
next if contact.phone_number.blank?
channel.send_message(to: contact.phone_number, body: campaign.message)
end
end
end
``` | require 'rails_helper'
describe Twilio::OneoffSmsCampaignService do
subject(:sms_campaign_service) { described_class.new(campaign: campaign) }
let(:account) { create(:account) }
let!(:twilio_sms) { create(:channel_twilio_sms) }
let!(:twilio_inbox) { create(:inbox, channel: twilio_sms) }
let(:label1) { create(:label, account: account) }
let(:label2) { create(:label, account: account) }
let!(:campaign) do
create(:campaign, inbox: twilio_inbox, account: account,
audience: [{ type: 'Label', id: label1.id }, { type: 'Label', id: label2.id }])
end
let(:twilio_client) { double }
let(:twilio_messages) { double }
describe 'perform' do
before do
allow(Twilio::REST::Client).to receive(:new).and_return(twilio_client)
allow(twilio_client).to receive(:messages).and_return(twilio_messages)
end
it 'raises error if the campaign is completed' do
campaign.completed!
expect { sms_campaign_service.perform }.to raise_error 'Completed Campaign'
end
it 'raises error invalid campaign when its not a oneoff sms campaign' do
campaign = create(:campaign)
expect { described_class.new(campaign: campaign).perform }.to raise_error "Invalid campaign #{campaign.id}"
end
it 'send messages to contacts in the audience and marks the campaign completed' do
contact_with_label1, contact_with_label2, contact_with_both_labels = FactoryBot.create_list(:contact, 3, :with_phone_number, account: account)
contact_with_label1.update_labels([label1.title])
contact_with_label2.update_labels([label2.title])
contact_with_both_labels.update_labels([label1.title, label2.title])
expect(twilio_messages).to receive(:create).with(
body: campaign.message,
messaging_service_sid: twilio_sms.messaging_service_sid,
to: contact_with_label1.phone_number,
status_callback: 'http://localhost:3000/twilio/delivery_status'
).once
expect(twilio_messages).to receive(:create).with(
body: campaign.message,
messaging_service_sid: twilio_sms.messaging_service_sid,
to: contact_with_label2.phone_number,
status_callback: 'http://localhost:3000/twilio/delivery_status'
).once
expect(twilio_messages).to receive(:create).with(
body: campaign.message,
messaging_service_sid: twilio_sms.messaging_service_sid,
to: contact_with_both_labels.phone_number,
status_callback: 'http://localhost:3000/twilio/delivery_status'
).once
sms_campaign_service.perform
expect(campaign.reload.completed?).to be true
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class PageCrawlerService
attr_reader :external_link
def initialize(external_link)
@external_link = external_link
@doc = Nokogiri::HTML(HTTParty.get(external_link).body)
end
def page_links
sitemap? ? extract_links_from_sitemap : extract_links_from_html
end
def page_title
title_element = @doc.at_xpath('//title')
title_element&.text&.strip
end
def body_text_content
ReverseMarkdown.convert @doc.at_xpath('//body'), unknown_tags: :bypass, github_flavored: true
end
private
def sitemap?
@external_link.end_with?('.xml')
end
def extract_links_from_sitemap
@doc.xpath('//loc').to_set(&:text)
end
def extract_links_from_html
@doc.xpath('//a/@href').to_set do |link|
absolute_url = URI.join(@external_link, link.value).to_s
absolute_url
end
end
end
``` | require 'rails_helper'
describe PageCrawlerService do
let(:html_link) { 'http://test.com' }
let(:sitemap_link) { 'http://test.com/sitemap.xml' }
let(:service_html) { described_class.new(html_link) }
let(:service_sitemap) { described_class.new(sitemap_link) }
let(:html_body) do
<<-HTML
<html>
<head><title>Test Title</title></head>
<body><a href="link1">Link 1</a><a href="link2">Link 2</a></body>
</html>
HTML
end
let(:sitemap_body) do
<<-XML
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>http://test.com/link1</loc></url>
<url><loc>http://test.com/link2</loc></url>
</urlset>
XML
end
before do
stub_request(:get, html_link).to_return(body: html_body, status: 200)
stub_request(:get, sitemap_link).to_return(body: sitemap_body, status: 200)
end
describe '#page_links' do
context 'when a HTML page is given' do
it 'returns all links on the page' do
expect(service_html.page_links).to eq(Set.new(['http://test.com/link1', 'http://test.com/link2']))
end
end
context 'when a sitemap is given' do
it 'returns all links in the sitemap' do
expect(service_sitemap.page_links).to eq(Set.new(['http://test.com/link1', 'http://test.com/link2']))
end
end
end
describe '#page_title' do
it 'returns the title of the page' do
expect(service_html.page_title).to eq('Test Title')
end
end
describe '#body_text_content' do
it 'returns the markdown converted body content of the page' do
expect(service_html.body_text_content.strip).to eq('[Link 1](link1)[Link 2](link2)')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Enterprise::MessageTemplates::ResponseBotService
pattr_initialize [:conversation!]
def perform
ActiveRecord::Base.transaction do
@response = get_response(conversation.messages.incoming.last.content)
process_response
end
rescue StandardError => e
process_action('handoff') # something went wrong, pass to agent
ChatwootExceptionTracker.new(e, account: conversation.account).capture_exception
true
end
def response_sections(content)
sections = ''
inbox.get_responses(content).each do |response|
sections += "{context_id: #{response.id}, context: #{response.question} ? #{response.answer}},"
end
sections
end
private
delegate :contact, :account, :inbox, to: :conversation
def get_response(content)
previous_messages = []
get_previous_messages(previous_messages)
ChatGpt.new(response_sections(content)).generate_response('', previous_messages)
end
def get_previous_messages(previous_messages)
conversation.messages.where(message_type: [:outgoing, :incoming]).where(private: false).find_each do |message|
next if message.content_type != 'text'
role = determine_role(message)
previous_messages << { content: message.content, role: role }
end
end
def determine_role(message)
message.message_type == 'incoming' ? 'user' : 'system'
end
def process_response
if @response['response'] == 'conversation_handoff'
process_action('handoff')
else
create_messages
end
end
def process_action(action)
case action
when 'handoff'
conversation.messages.create!('message_type': :outgoing, 'account_id': conversation.account_id, 'inbox_id': conversation.inbox_id,
'content': 'passing to an agent')
conversation.update(status: :open)
end
end
def create_messages
message_content = @response['response']
message_content += generate_sources_section if @response['context_ids'].present?
create_outgoing_message(message_content)
end
def generate_sources_section
article_ids = @response['context_ids']
sources_content = ''
articles_hash = get_article_hash(article_ids.uniq)
articles_hash.first(3).each do |article_hash|
sources_content += " - [#{article_hash[:response].question}](#{article_hash[:response_document].document_link}) \n"
end
sources_content = "\n \n \n **Sources** \n#{sources_content}" if sources_content.present?
sources_content
end
def create_outgoing_message(message_content)
conversation.messages.create!(
{
message_type: :outgoing,
account_id: conversation.account_id,
inbox_id: conversation.inbox_id,
content: message_content
}
)
end
def get_article_hash(article_ids)
seen_documents = Set.new
article_ids.uniq.filter_map do |article_id|
response = Response.find(article_id)
response_document = response.response_document
next if response_document.blank? || seen_documents.include?(response_document)
seen_documents << response_document
{ response: response, response_document: response_document }
end
end
end
``` | require 'rails_helper'
RSpec.describe Enterprise::MessageTemplates::ResponseBotService, type: :service do
let!(:conversation) { create(:conversation, status: :pending) }
let(:service) { described_class.new(conversation: conversation) }
let(:chat_gpt_double) { instance_double(ChatGpt) }
let(:response_source) { create(:response_source, account: conversation.account) }
let(:response_object) { instance_double(Response, id: 1, question: 'Q1', answer: 'A1') }
before do
# Uncomment if you want to run the spec in your local machine
# Features::ResponseBotService.new.enable_in_installation
skip('Skipping since vector is not enabled in this environment') unless Features::ResponseBotService.new.vector_extension_enabled?
stub_request(:post, 'https://api.openai.com/v1/embeddings').to_return(status: 200, body: {}.to_json,
headers: { Content_Type: 'application/json' })
create(:message, message_type: :incoming, conversation: conversation, content: 'Hi')
create(:message, message_type: :outgoing, conversation: conversation, content: 'Hello')
4.times { create(:response, response_source: response_source) }
allow(ChatGpt).to receive(:new).and_return(chat_gpt_double)
allow(chat_gpt_double).to receive(:generate_response).and_return({ 'response' => 'some_response', 'context_ids' => Response.all.map(&:id) })
allow(conversation.inbox).to receive(:get_responses).with('Hi').and_return([response_object])
end
describe '#perform' do
context 'when successful' do
it 'creates an outgoing message along with article references' do
expect do
service.perform
end.to change { conversation.messages.where(message_type: :outgoing).count }.by(1)
last_message = conversation.messages.last
expect(last_message.content).to include('some_response')
expect(last_message.content).to include(Response.first.question)
expect(last_message.content).to include('**Sources**')
end
end
context 'when context_ids are not present' do
it 'creates an outgoing message without article references' do
allow(chat_gpt_double).to receive(:generate_response).and_return({ 'response' => 'some_response' })
expect do
service.perform
end.to change { conversation.messages.where(message_type: :outgoing).count }.by(1)
last_message = conversation.messages.last
expect(last_message.content).to include('some_response')
expect(last_message.content).not_to include('**Sources**')
end
end
context 'when response doesnt have response document' do
it 'creates an outgoing message without article references' do
response = create(:response, response_source: response_source, response_document: nil)
allow(chat_gpt_double).to receive(:generate_response).and_return({ 'response' => 'some_response', 'context_ids' => [response.id] })
expect do
service.perform
end.to change { conversation.messages.where(message_type: :outgoing).count }.by(1)
last_message = conversation.messages.last
expect(last_message.content).to include('some_response')
expect(last_message.content).not_to include('**Sources**')
end
end
context 'when JSON::ParserError is raised' do
it 'creates a handoff message' do
allow(chat_gpt_double).to receive(:generate_response).and_raise(JSON::ParserError)
expect do
service.perform
end.to change { conversation.messages.where(message_type: :outgoing).count }.by(1)
expect(conversation.messages.last.content).to eq('passing to an agent')
expect(conversation.status).to eq('open')
end
end
context 'when StandardError is raised' do
it 'captures the exception' do
allow(chat_gpt_double).to receive(:generate_response).and_raise(StandardError)
expect(ChatwootExceptionTracker).to receive(:new).and_call_original
expect do
service.perform
end.to change { conversation.messages.where(message_type: :outgoing).count }.by(1)
expect(conversation.messages.last.content).to eq('passing to an agent')
expect(conversation.status).to eq('open')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Enterprise::Billing::CreateSessionService
def create_session(customer_id, return_url = ENV.fetch('FRONTEND_URL'))
Stripe::BillingPortal::Session.create(
{
customer: customer_id,
return_url: return_url
}
)
end
end
``` | require 'rails_helper'
describe Enterprise::Billing::CreateSessionService do
subject(:create_session_service) { described_class }
describe '#perform' do
it 'calls stripe billing portal session' do
customer_id = 'cus_random_number'
return_url = 'https://www.chatwoot.com'
allow(Stripe::BillingPortal::Session).to receive(:create).with({ customer: customer_id, return_url: return_url })
create_session_service.new.create_session(customer_id, return_url)
expect(Stripe::BillingPortal::Session).to have_received(:create).with(
{
customer: customer_id,
return_url: return_url
}
)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Enterprise::Billing::CreateStripeCustomerService
pattr_initialize [:account!]
DEFAULT_QUANTITY = 2
def perform
customer_id = prepare_customer_id
subscription = Stripe::Subscription.create(
{
customer: customer_id,
items: [{ price: price_id, quantity: default_quantity }]
}
)
account.update!(
custom_attributes: {
stripe_customer_id: customer_id,
stripe_price_id: subscription['plan']['id'],
stripe_product_id: subscription['plan']['product'],
plan_name: default_plan['name'],
subscribed_quantity: subscription['quantity']
}
)
end
private
def prepare_customer_id
customer_id = account.custom_attributes['stripe_customer_id']
if customer_id.blank?
customer = Stripe::Customer.create({ name: account.name, email: billing_email })
customer_id = customer.id
end
customer_id
end
def default_quantity
default_plan['default_quantity'] || DEFAULT_QUANTITY
end
def billing_email
account.administrators.first.email
end
def default_plan
installation_config = InstallationConfig.find_by(name: 'CHATWOOT_CLOUD_PLANS')
@default_plan ||= installation_config.value.first
end
def price_id
price_ids = default_plan['price_ids']
price_ids.first
end
end
``` | require 'rails_helper'
describe Enterprise::Billing::CreateStripeCustomerService do
subject(:create_stripe_customer_service) { described_class }
let(:account) { create(:account) }
let!(:admin1) { create(:user, account: account, role: :administrator) }
let(:admin2) { create(:user, account: account, role: :administrator) }
describe '#perform' do
before do
create(
:installation_config,
{ name: 'CHATWOOT_CLOUD_PLANS', value: [
{ 'name' => 'A Plan Name', 'product_id' => ['prod_hacker_random'], 'price_ids' => ['price_hacker_random'] }
] }
)
end
it 'does not call stripe methods if customer id is present' do
account.update!(custom_attributes: { stripe_customer_id: 'cus_random_number' })
allow(Stripe::Customer).to receive(:create)
allow(Stripe::Subscription).to receive(:create)
.and_return(
{
plan: { id: 'price_random_number', product: 'prod_random_number' },
quantity: 2
}.with_indifferent_access
)
create_stripe_customer_service.new(account: account).perform
expect(Stripe::Customer).not_to have_received(:create)
expect(Stripe::Subscription)
.to have_received(:create)
.with({ customer: 'cus_random_number', items: [{ price: 'price_hacker_random', quantity: 2 }] })
expect(account.reload.custom_attributes).to eq(
{
stripe_customer_id: 'cus_random_number',
stripe_price_id: 'price_random_number',
stripe_product_id: 'prod_random_number',
subscribed_quantity: 2,
plan_name: 'A Plan Name'
}.with_indifferent_access
)
end
it 'calls stripe methods to create a customer and updates the account' do
customer = double
allow(Stripe::Customer).to receive(:create).and_return(customer)
allow(customer).to receive(:id).and_return('cus_random_number')
allow(Stripe::Subscription)
.to receive(:create)
.and_return(
{
plan: { id: 'price_random_number', product: 'prod_random_number' },
quantity: 2
}.with_indifferent_access
)
create_stripe_customer_service.new(account: account).perform
expect(Stripe::Customer).to have_received(:create).with({ name: account.name, email: admin1.email })
expect(Stripe::Subscription)
.to have_received(:create)
.with({ customer: customer.id, items: [{ price: 'price_hacker_random', quantity: 2 }] })
expect(account.reload.custom_attributes).to eq(
{
stripe_customer_id: customer.id,
stripe_price_id: 'price_random_number',
stripe_product_id: 'prod_random_number',
subscribed_quantity: 2,
plan_name: 'A Plan Name'
}.with_indifferent_access
)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class Enterprise::Billing::HandleStripeEventService
def perform(event:)
ensure_event_context(event)
case @event.type
when 'customer.subscription.updated'
process_subscription_updated
when 'customer.subscription.deleted'
process_subscription_deleted
else
Rails.logger.debug { "Unhandled event type: #{event.type}" }
end
end
private
def process_subscription_updated
plan = find_plan(subscription['plan']['product'])
# skipping self hosted plan events
return if plan.blank? || account.blank?
update_account_attributes(subscription, plan)
change_plan_features
end
def update_account_attributes(subscription, plan)
# https://stripe.com/docs/api/subscriptions/object
account.update(
custom_attributes: {
stripe_customer_id: subscription.customer,
stripe_price_id: subscription['plan']['id'],
stripe_product_id: subscription['plan']['product'],
plan_name: plan['name'],
subscribed_quantity: subscription['quantity'],
subscription_status: subscription['status'],
subscription_ends_on: Time.zone.at(subscription['current_period_end'])
}
)
end
def process_subscription_deleted
# skipping self hosted plan events
return if account.blank?
Enterprise::Billing::CreateStripeCustomerService.new(account: account).perform
end
def change_plan_features
if default_plan?
account.disable_features(*features_to_update)
else
account.enable_features(*features_to_update)
end
account.save!
end
def ensure_event_context(event)
@event = event
end
def features_to_update
%w[help_center campaigns team_management channel_twitter channel_facebook channel_email]
end
def subscription
@subscription ||= @event.data.object
end
def account
@account ||= Account.where("custom_attributes->>'stripe_customer_id' = ?", subscription.customer).first
end
def find_plan(plan_id)
installation_config = InstallationConfig.find_by(name: 'CHATWOOT_CLOUD_PLANS')
installation_config.value.find { |config| config['product_id'].include?(plan_id) }
end
def default_plan?
installation_config = InstallationConfig.find_by(name: 'CHATWOOT_CLOUD_PLANS')
default_plan = installation_config.value.first
@account.custom_attributes['plan_name'] == default_plan['name']
end
end
``` | require 'rails_helper'
describe Enterprise::Billing::HandleStripeEventService do
subject(:stripe_event_service) { described_class }
let(:event) { double }
let(:data) { double }
let(:subscription) { double }
let!(:account) { create(:account, custom_attributes: { stripe_customer_id: 'cus_123' }) }
before do
allow(event).to receive(:data).and_return(data)
allow(data).to receive(:object).and_return(subscription)
allow(subscription).to receive(:[]).with('plan')
.and_return({
'id' => 'test', 'product' => 'plan_id', 'name' => 'plan_name'
})
allow(subscription).to receive(:[]).with('quantity').and_return('10')
allow(subscription).to receive(:[]).with('status').and_return('active')
allow(subscription).to receive(:[]).with('current_period_end').and_return(1_686_567_520)
allow(subscription).to receive(:customer).and_return('cus_123')
create(:installation_config, {
name: 'CHATWOOT_CLOUD_PLANS',
value: [
{
'name' => 'Hacker',
'product_id' => ['plan_id'],
'price_ids' => ['price_1']
},
{
'name' => 'Startups',
'product_id' => ['plan_id_2'],
'price_ids' => ['price_2']
}
]
})
end
describe '#perform' do
it 'handle customer.subscription.updated' do
allow(event).to receive(:type).and_return('customer.subscription.updated')
allow(subscription).to receive(:customer).and_return('cus_123')
stripe_event_service.new.perform(event: event)
expect(account.reload.custom_attributes).to eq({
'stripe_customer_id' => 'cus_123',
'stripe_price_id' => 'test',
'stripe_product_id' => 'plan_id',
'plan_name' => 'Hacker',
'subscribed_quantity' => '10',
'subscription_ends_on' => Time.zone.at(1_686_567_520).as_json,
'subscription_status' => 'active'
})
end
it 'disable features on customer.subscription.updated for default plan' do
allow(event).to receive(:type).and_return('customer.subscription.updated')
allow(subscription).to receive(:customer).and_return('cus_123')
stripe_event_service.new.perform(event: event)
expect(account.reload.custom_attributes).to eq({
'stripe_customer_id' => 'cus_123',
'stripe_price_id' => 'test',
'stripe_product_id' => 'plan_id',
'plan_name' => 'Hacker',
'subscribed_quantity' => '10',
'subscription_ends_on' => Time.zone.at(1_686_567_520).as_json,
'subscription_status' => 'active'
})
expect(account).not_to be_feature_enabled('channel_email')
expect(account).not_to be_feature_enabled('help_center')
end
it 'handles customer.subscription.deleted' do
stripe_customer_service = double
allow(event).to receive(:type).and_return('customer.subscription.deleted')
allow(Enterprise::Billing::CreateStripeCustomerService).to receive(:new).and_return(stripe_customer_service)
allow(stripe_customer_service).to receive(:perform)
stripe_event_service.new.perform(event: event)
expect(Enterprise::Billing::CreateStripeCustomerService).to have_received(:new).with(account: account)
end
end
describe '#perform for Startups plan' do
before do
allow(event).to receive(:data).and_return(data)
allow(data).to receive(:object).and_return(subscription)
allow(subscription).to receive(:[]).with('plan')
.and_return({
'id' => 'test', 'product' => 'plan_id_2', 'name' => 'plan_name'
})
allow(subscription).to receive(:[]).with('quantity').and_return('10')
allow(subscription).to receive(:customer).and_return('cus_123')
end
it 'enable features on customer.subscription.updated' do
allow(event).to receive(:type).and_return('customer.subscription.updated')
allow(subscription).to receive(:customer).and_return('cus_123')
stripe_event_service.new.perform(event: event)
expect(account.reload.custom_attributes).to eq({
'stripe_customer_id' => 'cus_123',
'stripe_price_id' => 'test',
'stripe_product_id' => 'plan_id_2',
'plan_name' => 'Startups',
'subscribed_quantity' => '10',
'subscription_ends_on' => Time.zone.at(1_686_567_520).as_json,
'subscription_status' => 'active'
})
expect(account).to be_feature_enabled('channel_email')
expect(account).to be_feature_enabled('help_center')
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class UpdateQueryFromParamsService
def initialize(query, user)
self.query = query
self.current_user = user
end
# rubocop:disable Metrics/AbcSize
def call(params, valid_subset: false)
apply_group_by(params)
apply_sort_by(params)
apply_filters(params)
apply_columns(params)
apply_sums(params)
apply_timeline(params)
apply_hierarchy(params)
apply_highlighting(params)
apply_display_representation(params)
apply_include_subprojects(params)
apply_timestamps(params)
disable_hierarchy_when_only_grouped_by(params)
if valid_subset
query.valid_subset!
end
if query.valid?
ServiceResult.success(result: query)
else
ServiceResult.failure(errors: query.errors)
end
end
# rubocop:enable Metrics/AbcSize
private
def apply_group_by(params)
query.group_by = params[:group_by] if params.key?(:group_by)
end
def apply_sort_by(params)
query.sort_criteria = params[:sort_by] if params[:sort_by]
end
def apply_filters(params)
return unless params[:filters]
query.filters = []
params[:filters].each do |filter|
query.add_filter(filter[:field], filter[:operator], filter[:values])
end
end
def apply_columns(params)
query.column_names = params[:columns] if params[:columns]
end
def apply_sums(params)
query.display_sums = params[:display_sums] if params.key?(:display_sums)
end
def apply_timeline(params)
query.timeline_visible = params[:timeline_visible] if params.key?(:timeline_visible)
query.timeline_zoom_level = params[:timeline_zoom_level] if params.key?(:timeline_zoom_level)
query.timeline_labels = params[:timeline_labels] if params.key?(:timeline_labels)
end
def apply_hierarchy(params)
query.show_hierarchies = params[:show_hierarchies] if params.key?(:show_hierarchies)
end
def apply_highlighting(params)
query.highlighting_mode = params[:highlighting_mode] if params.key?(:highlighting_mode)
query.highlighted_attributes = params[:highlighted_attributes] if params.key?(:highlighted_attributes)
end
def apply_display_representation(params)
query.display_representation = params[:display_representation] if params.key?(:display_representation)
end
def apply_include_subprojects(params)
query.include_subprojects = params[:include_subprojects] if params.key?(:include_subprojects)
end
def apply_timestamps(params)
query.timestamps = params[:timestamps] if params.key?(:timestamps)
end
def disable_hierarchy_when_only_grouped_by(params)
if params.key?(:group_by) && !params.key?(:show_hierarchies)
query.show_hierarchies = false
end
end
attr_accessor :query,
:current_user,
:params
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe UpdateQueryFromParamsService,
type: :model do
let(:user) { build_stubbed(:user) }
let(:query) { build_stubbed(:query) }
let(:instance) { described_class.new(query, user) }
let(:params) { {} }
describe '#call' do
subject { instance.call(params) }
context 'group_by' do
context 'for an existing value' do
let(:params) { { group_by: 'status' } }
it 'sets the value' do
subject
expect(query.group_by)
.to eql('status')
end
end
context 'for an explicitly nil value' do
let(:params) { { group_by: nil } }
it 'sets the value' do
subject
expect(query.group_by)
.to be_nil
end
end
end
context 'filters' do
let(:params) do
{ filters: [{ field: 'status_id', operator: '=', values: ['1', '2'] }] }
end
context 'for a valid filter' do
it 'sets the filter' do
subject
expect(query.filters.length)
.to be(1)
expect(query.filters[0].name)
.to be(:status_id)
expect(query.filters[0].operator)
.to eql('=')
expect(query.filters[0].values)
.to eql(['1', '2'])
end
end
end
context 'sort_by' do
let(:params) do
{ sort_by: [['status_id', 'desc']] }
end
it 'sets the order' do
subject
expect(query.sort_criteria)
.to eql([['status_id', 'desc']])
end
end
context 'columns' do
let(:params) do
{ columns: ['assigned_to', 'author', 'category', 'subject'] }
end
it 'sets the columns' do
subject
expect(query.column_names)
.to match_array(params[:columns].map(&:to_sym))
end
end
context 'display representation' do
let(:params) do
{ display_representation: 'list' }
end
it 'sets the display_representation' do
subject
expect(query.display_representation)
.to eq('list')
end
end
context 'highlighting mode', with_ee: %i[conditional_highlighting] do
let(:params) do
{ highlighting_mode: 'status' }
end
it 'sets the highlighting_mode' do
subject
expect(query.highlighting_mode)
.to eq(:status)
end
end
context 'default highlighting mode', with_ee: %i[conditional_highlighting] do
let(:params) do
{}
end
it 'sets the highlighting_mode' do
subject
expect(query.highlighting_mode)
.to eq(:inline)
end
end
context 'highlighting mode without EE' do
let(:params) do
{ highlighting_mode: 'status' }
end
it 'sets the highlighting_mode' do
subject
expect(query.highlighting_mode)
.to eq(:none)
end
end
context 'when using include subprojects' do
let(:params) do
{ include_subprojects: }
end
context 'when true' do
let(:include_subprojects) { true }
it 'sets the display_representation' do
subject
expect(query.include_subprojects)
.to be true
end
end
context 'when false' do
let(:include_subprojects) { false }
it 'sets the display_representation' do
subject
expect(query.include_subprojects)
.to be false
end
end
end
context "when providing timestamps" do
let(:timestamps) do
[
Timestamp.parse("2022-10-29T23:01:23Z"),
Timestamp.parse("oneWeekAgo@12:00+00:00"),
Timestamp.parse("PT0S")
]
end
let(:params) { { timestamps: } }
it 'sets the timestamps' do
subject
expect(query.timestamps).to eq timestamps
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class UpdateProjectsTypesService < BaseProjectService
def call(type_ids)
type_ids = standard_types if type_ids.blank?
if types_missing?(type_ids)
project.errors.add(:types,
:in_use_by_work_packages,
types: missing_types(type_ids).map(&:name).join(', '))
false
else
update_project_types(type_ids)
true
end
end
protected
def standard_types
type = ::Type.standard_type
if type.nil?
[]
else
[type.id]
end
end
def types_missing?(type_ids)
!missing_types(type_ids).empty?
end
def missing_types(type_ids)
types_used_by_work_packages.select { |t| type_ids.exclude?(t.id) }
end
def types_used_by_work_packages
@types_used_by_work_packages ||= project.types_used_by_work_packages
end
def update_project_types(type_ids)
new_types_to_add = type_ids - project.type_ids
project.type_ids = type_ids
project.work_package_custom_field_ids |= WorkPackageCustomField.joins(:types).where(types: { id: new_types_to_add }).ids
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
RSpec.describe UpdateProjectsTypesService do
let(:project) { instance_double(Project, types_used_by_work_packages: []) }
let(:standard_type) { build_stubbed(:type_standard) }
subject(:instance) { described_class.new(project) }
before do
allow(Type).to receive(:standard_type).and_return standard_type
end
describe '.call' do
subject { instance.call(ids) }
before do
allow(project).to receive(:type_ids=)
end
shared_examples 'activating custom fields' do
let(:project) { create(:project, no_types: true) }
let!(:custom_field) { create(:text_wp_custom_field, types:) }
it 'updates the active custom fields' do
expect { subject }
.to change { project.reload.work_package_custom_field_ids }
.from([])
.to([custom_field.id])
end
it 'does not activates the same custom field twice' do
expect { subject }.to change { project.reload.work_package_custom_field_ids }
expect { subject }.not_to change { project.reload.work_package_custom_field_ids }
end
context 'for a project with already existing types' do
let(:project) { create(:project, types:, work_package_custom_fields: [create(:text_wp_custom_field)]) }
it 'does not change custom fields' do
expect { subject }.not_to change { project.reload.work_package_custom_field_ids }
end
end
end
context 'with ids provided' do
let(:ids) { [1, 2, 3] }
it 'returns true and updates the ids' do
expect(subject).to be_truthy
expect(project).to have_received(:type_ids=).with(ids)
end
include_examples 'activating custom fields' do
let(:types) { create_list(:type, 2) }
let(:ids) { types.collect(&:id) }
end
end
context 'with no id passed' do
let(:ids) { [] }
it 'adds the id of the default type and returns true' do
expect(subject).to be_truthy
expect(project).to have_received(:type_ids=).with([standard_type.id])
end
include_examples 'activating custom fields' do
let(:standard_type) { create(:type_standard) }
let(:types) { [standard_type] }
end
end
context 'with nil passed' do
let(:ids) { nil }
it 'adds the id of the default type and returns true' do
expect(subject).to be_truthy
expect(project).to have_received(:type_ids=).with([standard_type.id])
end
include_examples 'activating custom fields' do
let(:standard_type) { create(:type_standard) }
let(:types) { [standard_type] }
end
end
context 'when the id of a type in use is not provided' do
let(:type) { build_stubbed(:type) }
let(:ids) { [1] }
before do
allow(project).to receive(:types_used_by_work_packages).and_return([type])
allow(project).to receive(:work_package_custom_field_ids=).and_return([type])
end
it 'returns false and sets an error message' do
errors = instance_double(ActiveModel::Errors)
allow(errors).to receive(:add)
allow(project).to receive(:errors).and_return(errors)
expect(subject).to be_falsey
expect(errors).to have_received(:add).with(:types, :in_use_by_work_packages, types: type.name)
expect(project).not_to have_received(:type_ids=)
expect(project).not_to have_received(:work_package_custom_field_ids=)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Authorization
module_function
# Returns all users having a certain permission within a project
def users(action, project)
Authorization::UserAllowedQuery.query(action, project)
end
# Returns all projects a user has a certain permission in
def projects(action, user)
Project.allowed_to(user, action)
end
# Returns all work packages a user has a certain permission in (or in the project it belongs to)
def work_packages(action, user)
WorkPackage.allowed_to(user, action)
end
# Returns all roles a user has in a certain project, for a specific entity or globally
def roles(user, context = nil)
if context.is_a?(Project)
Authorization::UserProjectRolesQuery.query(user, context)
elsif Member.can_be_member_of?(context)
Authorization::UserEntityRolesQuery.query(user, context)
else
Authorization::UserGlobalRolesQuery.query(user)
end
end
# Normalizes the different types of permission arguments into Permission objects.
# Possible arguments
# - Symbol permission names (e.g. :view_work_packages)
# - Hash with :controller and :action (e.g. { controller: 'work_packages', action: 'show' })
#
# Exceptions
# - When there is no permission matching the +action+ parameter, either an empty array is returned
# or an +UnknownPermissionError+ is raised (depending on the +raise_on_unknown+ parameter).
# . Additionally a debugger message is logged.
# If the permission is disabled, it will not raise an error or log debug output.
def permissions_for(action, raise_on_unknown: false) # rubocop:disable Metrics/PerceivedComplexity, Metrics/AbcSize
return [action] if action.is_a?(OpenProject::AccessControl::Permission)
return action if action.is_a?(Array) && (action.empty? || action.all?(OpenProject::AccessControl::Permission))
perms = if action.is_a?(Hash)
OpenProject::AccessControl.allow_actions(action)
else
[OpenProject::AccessControl.permission(action)].compact
end
if perms.blank?
if !OpenProject::AccessControl.disabled_permission?(action)
Rails.logger.debug { "Used permission \"#{action}\" that is not defined. It will never return true." }
raise UnknownPermissionError.new(action) if raise_on_unknown
end
return []
end
perms
end
# Returns a set of normalized permissions filtered for a given context
# - When there are no permissions available for the given context (based on +permissible_on+
# attribute of the permission), an +IllegalPermissionContextError+ is raised
def contextual_permissions(action, context, raise_on_unknown: false)
perms = permissions_for(action, raise_on_unknown:)
return [] if perms.blank?
context_perms = perms.select { |p| p.permissible_on?(context) }
raise IllegalPermissionContextError.new(action, perms, context) if context_perms.blank?
context_perms
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Authorization do
let(:user) { build_stubbed(:user) }
let(:action) { :view_work_packages }
describe '.users' do
it 'calls Authorization::UserAllowedQuery' do
expect(Authorization::UserAllowedQuery).to receive(:query).with(action, user)
described_class.users(action, user)
end
end
describe '.projects' do
it 'uses the .allowed_to scope on Project' do
expect(Project).to receive(:allowed_to).with(user, action)
described_class.projects(action, user)
end
end
describe '.work_packages' do
it 'uses the .allowed_to scope on WorkPackage' do
expect(WorkPackage).to receive(:allowed_to).with(user, action)
described_class.work_packages(action, user)
end
end
describe '.roles' do
context 'with a project' do
let(:context) { build_stubbed(:project) }
it 'calls Authorization::UserProjectRolesQuery' do
expect(Authorization::UserProjectRolesQuery).to receive(:query).with(user, context)
described_class.roles(user, context)
end
end
context 'with a WorkPackage' do
let(:context) { build_stubbed(:work_package) }
it 'calls Authorization::UserEntityRolesQuery' do
expect(Authorization::UserEntityRolesQuery).to receive(:query).with(user, context)
described_class.roles(user, context)
end
end
context 'without a context' do
let(:context) { nil }
it 'calls Authorization::UserGlobalRolesQuery' do
expect(Authorization::UserGlobalRolesQuery).to receive(:query).with(user)
described_class.roles(user, context)
end
end
end
describe '.permissions_for' do
let(:raise_on_unknown) { false }
subject { described_class.permissions_for(action, raise_on_unknown:) }
context 'when called with a Permission object' do
let(:action) { OpenProject::AccessControl.permission(:view_work_packages) }
it 'returns the Permission object wrapped in an array' do
expect(subject).to eq([action])
end
end
context 'when called with an array of Permission objects' do
let(:action) do
[
OpenProject::AccessControl.permission(:view_work_packages),
OpenProject::AccessControl.permission(:edit_work_packages)
]
end
it 'returns the Permission array' do
expect(subject).to eq(action)
end
end
context 'when action is a Hash where controller starts with a slash' do
let(:action) do
{ controller: '/work_packages', action: 'show' }
end
it 'returns all permissions that grant the permission to this URL' do
# there might be more permissions granting access to this URL, we check for a known one
expect(subject).to include(OpenProject::AccessControl.permission(:view_work_packages))
end
end
context 'when action is a Hash where controller does not start with a slash' do
let(:action) do
{ controller: 'work_packages', action: 'show' }
end
it 'returns all permissions that grant the permission to this URL' do
# there might be more permissions granting access to this URL, we check for a known one
expect(subject).to include(OpenProject::AccessControl.permission(:view_work_packages))
end
end
context 'when action is a permission name' do
let(:action) { :view_work_packages }
it 'returns the Permission object wrapped in an array' do
expect(subject).to eq([OpenProject::AccessControl.permission(:view_work_packages)])
end
end
context 'when there is a permission but it is disabled' do
let(:permission_object) { OpenProject::AccessControl.permission(:manage_user) }
let(:action) { permission_object.name }
around do |example|
permission_object.disable!
OpenProject::AccessControl.clear_caches
example.run
ensure
permission_object.enable!
OpenProject::AccessControl.clear_caches
end
it 'returns an empty array and does not warn or raise' do
expect(Rails.logger).not_to receive(:debug)
expect do
expect(subject).to be_empty
end.not_to raise_error
end
end
context 'when there is no permission' do
let(:action) { :this_permission_does_not_exist }
context 'and raise_on_unknown is false' do
let(:raise_on_unknown) { false }
it 'warns and returns an empty array' do
allow(Rails.logger).to receive(:debug)
expect(subject).to be_empty
expect(Rails.logger).to have_received(:debug) do |_, &block|
expect(block.call).to include("Used permission \"#{action}\" that is not defined.")
end
end
end
context 'and raise_on_unknown is true' do
let(:raise_on_unknown) { true }
it 'warns and raises' do
allow(Rails.logger).to receive(:debug)
expect { subject }.to raise_error(Authorization::UnknownPermissionError)
expect(Rails.logger).to have_received(:debug) do |_, &block|
expect(block.call).to include("Used permission \"#{action}\" that is not defined.")
end
end
end
end
describe '.contextual_permissions' do
subject { described_class.contextual_permissions(action, context, raise_on_unknown:) }
let(:raise_on_unknown) { false }
let(:context) { nil }
let(:global_permission) { OpenProject::AccessControl.permission(:manage_user) }
let(:project_permission) { OpenProject::AccessControl.permission(:manage_members) }
let(:project_and_work_package_permission) { OpenProject::AccessControl.permission(:view_work_packages) }
let(:returned_permissions) do
[
global_permission,
project_permission,
project_and_work_package_permission
]
end
before do
allow(described_class).to receive(:permissions_for).and_return(returned_permissions)
end
context 'with global context' do
let(:context) { :global }
context 'when a global permission is part of the returned permissions' do
it 'returns only the global permission' do
expect(subject).to eq([global_permission])
end
end
context 'when no global permission is part of the returned permissions' do
let(:returned_permissions) { [project_permission, project_and_work_package_permission] }
it 'raises an IllegalPermissionContextError' do
expect { subject }.to raise_error(Authorization::IllegalPermissionContextError)
end
end
end
context 'with project context' do
let(:context) { :project }
context 'when a project permission is part of the returned permissions' do
it 'returns only the project permissions' do
expect(subject).to eq([project_permission, project_and_work_package_permission])
end
end
context 'when no project permission is part of the returned permissions' do
let(:returned_permissions) { [global_permission] }
it 'raises an IllegalPermissionContextError' do
expect { subject }.to raise_error(Authorization::IllegalPermissionContextError)
end
end
end
context 'with work package context' do
let(:context) { :work_package }
context 'when a work package permission is part of the returned permissions' do
it 'returns only the work package permission' do
expect(subject).to eq([project_and_work_package_permission])
end
end
context 'when no work package permission is part of the returned permissions' do
let(:returned_permissions) { [global_permission, project_permission] }
it 'raises an IllegalPermissionContextError' do
expect { subject }.to raise_error(Authorization::IllegalPermissionContextError)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
class SetLocalizationService
attr_reader :user, :http_accept_header
include Redmine::I18n
def initialize(user, http_accept_header = nil)
@user = user
@http_accept_header = http_accept_header
end
##
# Sets the locale.
# The locale is determined with the following priority:
#
# 1. The language as configured by the user.
# 2. The first language defined in the Accept-Language header sent by the browser.
# 3. OpenProject's default language defined in the settings.
def call
lang = user_language || header_language || default_language
set_language_if_valid(lang)
end
private
def user_language
find_language_or_prefix(user.language) if user.logged?
end
def header_language
return unless http_accept_header
accept_lang = parse_qvalues(http_accept_header).first
find_language_or_prefix accept_lang
end
def default_language
Setting.default_language
end
# qvalues http header parser
# code taken from webrick
def parse_qvalues(value)
tmp = []
if value
parts = value.split(/,\s*/)
parts.each do |part|
match = /\A([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?\z/.match(part)
if match
val = match[1]
q = (match[2] || 1).to_f
tmp.push([val, q])
end
end
tmp = tmp.sort_by { |_val, q| -q }
tmp.map! { |val, _q| val }
end
tmp
rescue StandardError
nil
end
def find_language_or_prefix(language)
return nil unless language
language = language.to_s.downcase
find_language(language) || find_language(language.split('-').first)
end
end
``` | require 'spec_helper'
RSpec.describe SetLocalizationService do
let(:user) { build_stubbed(:user, language: user_language) }
let(:http_accept_header) { "#{http_accept_language},en-US;q=0.8,en;q=0.6" }
let(:instance) { described_class.new(user, http_accept_header) }
let(:user_language) { :bogus_language }
let(:http_accept_language) { :http_accept_language }
let(:default_language) { :default_language }
before do
allow(I18n).to receive(:locale=).with(:en)
allow(instance).to receive(:valid_languages).and_return [user_language,
http_accept_language,
default_language]
allow(Setting).to receive(:default_language).and_return(default_language)
end
def expect_locale(locale)
expect(I18n).to receive(:locale=).with(locale)
end
shared_examples_for 'falls back to the header' do
it 'falls back to the header' do
expect_locale(http_accept_language)
instance.call
end
end
shared_examples_for "falls back to the instane's default language" do
it "falls back to the instance's default language" do
expect_locale(default_language)
instance.call
end
end
context 'for a logged in user' do
it "sets the language to the user's selected language" do
expect_locale(user_language)
instance.call
end
context 'with a language prefix being valid' do
let(:prefix) { 'someprefix' }
let(:user_language) { "#{prefix}-specific" }
before do
allow(instance).to receive(:valid_languages).and_return [prefix,
http_accept_language,
default_language]
end
it "sets the language to the valid prefix of the user's selected language" do
expect_locale(prefix)
instance.call
end
end
context 'with the language not being valid' do
before do
allow(instance).to receive(:valid_languages).and_return [http_accept_language,
default_language]
end
it_behaves_like 'falls back to the header'
context 'with a language prefix being valid' do
let(:prefix) { 'someprefix' }
let(:http_accept_header) { "#{prefix}-specific" }
before do
allow(instance).to receive(:valid_languages).and_return [prefix,
default_language]
end
it "sets the language to the valid prefix of the accept header" do
expect_locale(prefix)
instance.call
end
end
end
context 'with the user not having a language selected' do
before do
user.language = nil
end
it_behaves_like 'falls back to the header'
context 'with the header not being valid' do
before do
allow(instance).to receive(:valid_languages).and_return [user_language,
default_language]
end
it_behaves_like "falls back to the instane's default language"
end
context 'with no header set' do
let(:http_accept_header) { nil }
it_behaves_like "falls back to the instane's default language"
end
context 'with wildcard header set' do
let(:http_accept_language) { '*' }
it_behaves_like "falls back to the instane's default language"
end
end
end
context 'for an anonymous user' do
let(:user) { build_stubbed(:anonymous) }
it_behaves_like 'falls back to the header'
context 'with no header set' do
let(:http_accept_header) { nil }
it_behaves_like "falls back to the instane's default language"
end
context 'with a wildcard header set' do
let(:http_accept_language) { '*' }
it_behaves_like "falls back to the instane's default language"
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class CreateTypeService < BaseTypeService
def initialize(user)
super Type.new, user
end
private
def after_type_save(_params, options)
# workflow copy
if options[:copy_workflow_from].present? && (copy_from = ::Type.find_by(id: options[:copy_workflow_from]))
type.workflows.copy_from_type(copy_from)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/shared_type_service'
RSpec.describe CreateTypeService do
let(:type) { instance.type }
let(:user) { build_stubbed(:admin) }
let(:instance) { described_class.new(user) }
let(:service_call) { instance.call({ name: 'foo' }.merge(params), {}) }
it_behaves_like 'type service'
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
##
# Create journal for the given user and note.
# Does not change the work package itself.
class AddWorkPackageNoteService
include Contracted
attr_accessor :user, :work_package
def initialize(user:, work_package:)
self.user = user
self.work_package = work_package
self.contract_class = WorkPackages::CreateNoteContract
end
def call(notes, send_notifications: nil)
Journal::NotificationConfiguration.with send_notifications do
work_package.add_journal(user:, notes:)
success, errors = validate_and_yield(work_package, user) do
work_package.save_journals
end
if success
# In test environment, because of the difference in the way of handling transactions,
# the journal needs to be actively loaded without SQL caching in place.
journal = Journal.connection.uncached do
work_package.journals.last
end
end
ServiceResult.new(success:, result: journal, errors:)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe AddWorkPackageNoteService, type: :model do
let(:user) { build_stubbed(:user) }
let(:work_package) { build_stubbed(:work_package) }
let(:instance) do
described_class.new(user:,
work_package:)
end
describe '.contract' do
it 'uses the CreateNoteContract contract' do
expect(instance.contract_class).to eql WorkPackages::CreateNoteContract
end
end
describe 'call' do
let(:mock_contract) do
double(WorkPackages::CreateNoteContract,
new: mock_contract_instance)
end
let(:mock_contract_instance) do
double(WorkPackages::CreateNoteContract,
errors: contract_errors,
validate: valid_contract)
end
let(:valid_contract) { true }
let(:contract_errors) do
double('contract errors')
end
let(:send_notifications) { false }
before do
expect(Journal::NotificationConfiguration)
.to receive(:with)
.with(send_notifications)
.and_yield
allow(instance).to receive(:contract_class).and_return(mock_contract)
allow(work_package).to receive(:save_journals).and_return true
end
subject { instance.call('blubs', send_notifications:) }
it 'is successful' do
expect(subject).to be_success
end
it 'persists the value' do
expect(work_package).to receive(:save_journals).and_return true
subject
end
it 'has no errors' do
expect(subject.errors).to be_empty
end
context 'when the contract does not validate' do
let(:valid_contract) { false }
it 'is unsuccessful' do
expect(subject.success?).to be_falsey
end
it 'does not persist the changes' do
expect(work_package).not_to receive(:save_journals)
subject
end
it "exposes the contract's errors" do
errors = double('errors')
allow(mock_contract_instance).to receive(:errors).and_return(errors)
subject
expect(subject.errors).to eql errors
end
end
context 'when the saving is unsuccessful' do
before do
expect(work_package).to receive(:save_journals).and_return false
end
it 'is unsuccessful' do
expect(subject).not_to be_success
end
it 'leaves the value unchanged' do
subject
expect(work_package.journal_notes).to eql 'blubs'
expect(work_package.journal_user).to eql user
end
it "exposes the work_packages's errors" do
errors = double('errors')
allow(work_package).to receive(:errors).and_return(errors)
subject
expect(subject.errors).to eql errors
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class UpdateTypeService < BaseTypeService
def call(params)
# forbid renaming if it is a standard type
if params[:type] && type.is_standard?
params[:type].delete :name
end
super(params, {})
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/shared_type_service'
RSpec.describe UpdateTypeService do
let(:type) { create(:type) }
let(:user) { build_stubbed(:admin) }
let(:instance) { described_class.new(type, user) }
let(:service_call) { instance.call(params) }
let(:valid_group) { { 'type' => 'attribute', 'name' => 'foo', 'attributes' => ['date'] } }
it_behaves_like 'type service'
describe "#validate_attribute_groups" do
let(:params) { { name: 'blubs blubs' } }
it 'raises an exception for invalid structure' do
# Example for invalid structure:
result = instance.call(attribute_groups: ['foo'])
expect(result.success?).to be_falsey
# Example for invalid structure:
result = instance.call(attribute_groups: [[]])
expect(result.success?).to be_falsey
# Example for invalid group name:
result = instance.call(attribute_groups: [['', ['date']]])
expect(result.success?).to be_falsey
end
it 'fails for duplicate group names' do
result = instance.call(attribute_groups: [valid_group, valid_group])
expect(result.success?).to be_falsey
expect(result.errors[:attribute_groups].first).to include 'used more than once.'
end
it 'passes validations for known attributes' do
expect(type).to receive(:save).and_return(true)
result = instance.call(attribute_groups: [valid_group])
expect(result.success?).to be_truthy
end
it 'passes validation for defaults' do
expect(type).to be_valid
end
it 'passes validation for reset' do
# A reset is to save an empty Array
expect(type).to receive(:save).and_return(true)
result = instance.call(attribute_groups: [])
expect(result.success?).to be_truthy
expect(type).to be_valid
end
context 'with an invalid query' do
let(:params) { { attribute_groups: [{ 'type' => 'query', name: 'some name', query: 'wat' }] } }
it 'is invalid' do
expect(service_call.success?).to be_falsey
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class ServiceResult
SUCCESS = true
FAILURE = false
attr_accessor :success,
:result,
:errors,
:dependent_results
attr_writer :state
# Creates a successful ServiceResult.
def self.success(errors: nil,
message: nil,
message_type: nil,
state: nil,
dependent_results: [],
result: nil)
new(success: SUCCESS,
errors:,
message:,
message_type:,
state:,
dependent_results:,
result:)
end
# Creates a failed ServiceResult.
def self.failure(errors: nil,
message: nil,
message_type: nil,
state: nil,
dependent_results: [],
result: nil)
new(success: FAILURE,
errors:,
message:,
message_type:,
state:,
dependent_results:,
result:)
end
def initialize(success: false,
errors: nil,
message: nil,
message_type: nil,
state: nil,
dependent_results: [],
result: nil)
self.success = success
self.result = result
self.state = state
initialize_errors(errors)
@message = message
@message_type = message_type
self.dependent_results = dependent_results
end
alias success? :success
def failure?
!success?
end
##
# Merge another service result into this instance
# allowing optionally to skip updating its service
def merge!(other, without_success: false)
merge_success!(other) unless without_success
merge_errors!(other)
merge_dependent!(other)
end
##
# Print messages to flash
def apply_flash_message!(flash)
if message
flash[message_type] = message
end
end
def all_results
dependent_results.map(&:result).tap do |results|
results.unshift result unless result.nil?
end
end
def all_errors
[errors] + dependent_results.map(&:errors)
end
##
# Test whether the returned errors respond
# to the search key
def includes_error?(attribute, error_key)
all_errors.any? do |error|
error.symbols_for(attribute).include?(error_key)
end
end
##
# Collect all present errors for the given result
# and dependent results.
#
# Returns a map of the service result to the error object
def results_with_errors(include_self: true)
results =
if include_self
[self] + dependent_results
else
dependent_results
end
results.reject { |call| call.errors.empty? }
end
def self_and_dependent
[self] + dependent_results
end
def add_dependent!(dependent)
merge_success!(dependent)
inner_results = dependent.dependent_results
dependent.dependent_results = []
dependent_results << dependent
self.dependent_results += inner_results
end
def on_success(&)
tap(&) if success?
self
end
def on_failure(&)
tap(&) if failure?
self
end
def each
yield result if success?
self
end
def map
return self if failure?
dup.tap do |new_result|
new_result.result = yield result
end
end
def to_a
if success?
[result]
else
[]
end
end
def message
if @message
@message
elsif failure? && errors.is_a?(ActiveModel::Errors)
errors.full_messages.join(" ")
end
end
def state
@state ||= ::Shared::ServiceState.build
end
private
def initialize_errors(errors)
self.errors = errors || new_errors_with_result
end
def new_errors_with_result
ActiveModel::Errors.new(self).tap do |errors|
errors.merge!(result) if result.try(:errors).present?
end
end
def message_type
if @message_type
@message_type.to_sym
elsif success?
:notice
else
:error
end
end
def merge_success!(other)
self.success &&= other.success
end
def merge_errors!(other)
errors.merge! other.errors
end
def merge_dependent!(other)
self.dependent_results += other.dependent_results
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe ServiceResult, type: :model do
let(:instance) { described_class.new }
describe 'success' do
it 'is what the service is initialized with' do
instance = described_class.new success: true
expect(instance.success).to be_truthy
expect(instance.success?).to be(true)
instance = described_class.new success: false
expect(instance.success).to be_falsey
expect(instance.success?).to be(false)
end
it 'returns what is provided' do
instance.success = true
expect(instance.success).to be_truthy
expect(instance.success?).to be(true)
instance.success = false
expect(instance.success).to be_falsey
expect(instance.success?).to be(false)
end
it 'is false by default' do
expect(instance.success).to be_falsey
expect(instance.success?).to be(false)
end
end
describe '.success' do
it 'creates a ServiceResult with success: true' do
instance = described_class.success
expect(instance.success).to be_truthy
end
it 'accepts the same set of parameters as the initializer' do
errors = ['errors']
message = 'message'
message_type = :message_type
state = instance_double(Shared::ServiceState)
dependent_results = ['dependent_results']
result = instance_double(Object, 'result')
instance = described_class.success(
errors:,
message:,
message_type:,
state:,
dependent_results:,
result:
)
expect(instance.errors).to be(errors)
expect(instance.message).to be(message)
expect(instance.state).to be(state)
expect(instance.dependent_results).to be(dependent_results)
expect(instance.result).to be(result)
end
end
describe '.failure' do
it 'creates a ServiceResult with success: false' do
instance = described_class.failure
expect(instance.success).to be_falsy
end
it 'accepts the same set of parameters as the initializer' do
errors = ['errors']
message = 'message'
message_type = :message_type
state = instance_double(Shared::ServiceState)
dependent_results = ['dependent_results']
result = instance_double(Object, 'result')
instance = described_class.failure(
errors:,
message:,
message_type:,
state:,
dependent_results:,
result:
)
expect(instance.errors).to be(errors)
expect(instance.message).to be(message)
expect(instance.state).to be(state)
expect(instance.dependent_results).to be(dependent_results)
expect(instance.result).to be(result)
end
end
describe 'errors' do
let(:errors) { ['errors'] }
it 'is what has been provided' do
instance.errors = errors
expect(instance.errors).to eql errors
end
it 'is what the object is initialized with' do
instance = described_class.new(errors:)
expect(instance.errors).to eql errors
end
it 'is an empty ActiveModel::Errors by default' do
expect(instance.errors).to be_a ActiveModel::Errors
end
context 'when providing errors from user' do
let(:result) { build(:work_package) }
it 'creates a new errors instance' do
instance = described_class.new(result:)
expect(instance.errors).not_to eq result.errors
end
end
end
describe 'result' do
let(:result) { instance_double(Object, 'result') }
it 'is what the object is initialized with' do
instance = described_class.new(result:)
expect(instance.result).to eql result
end
it 'is what has been provided' do
instance.result = result
expect(instance.result).to eql result
end
it 'is nil by default' do
instance = described_class.new
expect(instance.result).to be_nil
end
end
describe 'apply_flash_message!' do
let(:message) { 'some message' }
subject(:flash) do
{}.tap { service_result.apply_flash_message!(_1) }
end
context 'when successful' do
let(:service_result) { described_class.success(message:) }
it { is_expected.to include(notice: message) }
end
context 'when failure' do
let(:service_result) { described_class.failure(message:) }
it { is_expected.to include(error: message) }
end
context 'when setting message_type to :info' do
let(:service_result) { described_class.success(message:, message_type: :info) }
it { is_expected.to include(info: message) }
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class ParseSchemaFilterParamsService
extend ActiveModel::Naming
extend ActiveModel::Translation
attr_accessor :user
def self.i18n_scope
:activerecord
end
def initialize(user:)
self.user = user
end
def call(filter)
error_message = check_error_in_filter(filter)
if error_message
error(error_message)
else
pairs = valid_project_type_pairs(filter)
success(pairs)
end
end
private
def check_error_in_filter(filter)
if !filter.first['id']
:id_filter_required
elsif filter.first['id']['operator'] != '='
:unsupported_operator
elsif filter.first['id']['values'].any? { |id_string| !id_string.match(/\d+-\d+/) }
:invalid_values
end
end
def parse_ids(filter)
ids_string = filter.first['id']['values']
ids_string.map do |id_string|
id_string.split('-')
end
end
def error(message)
errors = ActiveModel::Errors.new(self)
errors.add(:base, message)
ServiceResult.failure(errors:)
end
def success(result)
ServiceResult.success(result:)
end
def valid_project_type_pairs(filter)
ids = parse_ids(filter)
projects_map = projects_by_id(ids.map(&:first))
types_map = types_by_id(ids.map(&:last))
valid_ids = only_valid_pairs(ids, projects_map, types_map)
string_pairs_to_object_pairs(valid_ids, projects_map, types_map)
end
def projects_by_id(ids)
Project.visible(user).where(id: ids).group_by(&:id)
end
def types_by_id(ids)
Type.where(id: ids).group_by(&:id)
end
def only_valid_pairs(id_pairs, projects_map, types_map)
id_pairs.reject do |project_id, type_id|
projects_map[project_id.to_i].nil? || types_map[type_id.to_i].nil?
end
end
def string_pairs_to_object_pairs(string_pairs, projects_map, types_map)
string_pairs.map do |project_id, type_id|
[projects_map[project_id.to_i].first, types_map[type_id.to_i].first]
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
RSpec.describe ParseSchemaFilterParamsService do
let(:current_user) { build_stubbed(:user) }
let(:instance) { described_class.new(user: current_user) }
let(:project) { build_stubbed(:project) }
let(:type) { build_stubbed(:type) }
describe '#call' do
let(:filter) do
[{ 'id' => { 'values' => ["#{project.id}-#{type.id}"], 'operator' => '=' } }]
end
let(:result) { instance.call(filter) }
let(:found_projects) { [project] }
let(:found_types) { [type] }
before do
visible_projects = double('visible_projects')
allow(Project)
.to receive(:visible)
.with(current_user)
.and_return(visible_projects)
allow(visible_projects)
.to receive(:where)
.with(id: [project.id.to_s])
.and_return(found_projects)
allow(Type)
.to receive(:where)
.with(id: [type.id.to_s])
.and_return(found_types)
end
context 'valid' do
it 'is a success' do
expect(result).to be_success
end
it 'returns the [project, type] pair' do
expect(result.result).to match_array [[project, type]]
end
end
context 'for a non existing project' do
let(:found_projects) { [] }
it 'is a success' do
expect(result).to be_success
end
it 'returns an empty array' do
expect(result.result).to match_array []
end
end
context 'for a non existing type' do
let(:found_types) { [] }
it 'is a success' do
expect(result).to be_success
end
it 'returns an empty array' do
expect(result.result).to match_array []
end
end
context 'without the "=" operator' do
let(:filter) do
[{ 'id' => { 'values' => ["#{project.id}-#{type.id}"], 'operator' => '!' } }]
end
it 'is a failure' do
expect(result).not_to be_success
end
it 'returns an empty array' do
expect(result.result).to be_nil
end
it 'returns an error message' do
expect(result.errors.messages[:base]).to match_array ['The operator is not supported.']
end
end
context 'with an invalid value' do
let(:filter) do
[{ 'id' => { 'values' => ["bogus-1"], 'operator' => "=" } }]
end
it 'is a failure' do
expect(result).not_to be_success
end
it 'returns an empty array' do
expect(result.result).to be_nil
end
it 'returns an error message' do
expect(result.errors.messages[:base]).to match_array ['A value is invalid.']
end
end
context 'without an id filter' do
let(:filter) do
[{}]
end
it 'is a failure' do
expect(result).not_to be_success
end
it 'returns an empty array' do
expect(result.result).to be_nil
end
it 'returns an error message' do
expect(result.errors.messages[:base]).to match_array ['An \'id\' filter is required.']
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
# -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
#
class Settings::LanguageUpdateService < Settings::UpdateService
def after_perform(call)
force_users_to_use_only_available_languages
call
end
private
def force_users_to_use_only_available_languages
User.where.not(language: Setting.available_languages)
.update_all(language: Setting.default_language)
end
end
``` | # frozen_string_literal: true
# -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
#
require 'spec_helper'
RSpec.describe Settings::LanguageUpdateService do
let(:service) do
described_class.new(user: build_stubbed(:admin))
end
let(:available_languages) { %w[de fr] }
before do
allow(service).to receive(:force_users_to_use_only_available_languages)
end
it 'sets language of users having a non-available language to the default language' do
service.call(available_languages:)
expect(service)
.to have_received(:force_users_to_use_only_available_languages)
end
context 'when the contract is not successfully validated' do
before do
allow(service)
.to receive(:validate_contract)
.and_return(ServiceResult.failure(message: 'fake error'))
end
it 'does not change language of any users' do
service.call(available_languages:)
expect(service)
.not_to have_received(:force_users_to_use_only_available_languages)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2022 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTALITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Settings::WorkingDaysUpdateService < Settings::UpdateService
def call(params)
params = params.to_h.deep_symbolize_keys
self.non_working_days_params = params.delete(:non_working_days) || []
self.previous_working_days = Setting[:working_days]
self.previous_non_working_days = NonWorkingDay.pluck(:date)
super
end
def validate_params(params)
contract = Settings::WorkingDaysParamsContract.new(model, user, params:)
ServiceResult.new success: contract.valid?,
errors: contract.errors,
result: model
end
def persist(call)
results = call
ActiveRecord::Base.transaction do
# The order of merging the service is important to preserve
# the errors model's base object, which is a NonWorkingDay
results = persist_non_working_days
results.merge!(super) if results.success?
raise ActiveRecord::Rollback if results.failure?
end
results
end
def after_perform(call)
super.tap do
WorkPackages::ApplyWorkingDaysChangeJob.perform_later(
user_id: User.current.id,
previous_working_days:,
previous_non_working_days:
)
end
end
private
attr_accessor :non_working_days_params, :previous_working_days, :previous_non_working_days
def persist_non_working_days
# We don't support update for now
to_create, to_delete = attributes_to_create_and_delete
results = destroy_records(to_delete)
create_results = create_records(to_create)
results.merge!(create_results)
results.result = Array(results.result) + Array(create_results.result)
results
end
def attributes_to_create_and_delete
non_working_days_params.reduce([[], []]) do |results, nwd|
results.first << nwd if !nwd[:id]
results.last << nwd[:id] if nwd[:_destroy] && nwd[:id]
results
end
end
def create_records(attributes)
wrap_result(attributes.map { |attrs| NonWorkingDay.create(attrs) })
end
def destroy_records(ids)
records = NonWorkingDay.where(id: ids)
# In case the transaction fails we also mark the records for destruction,
# this way we can display them correctly on the frontend.
records.each(&:mark_for_destruction)
wrap_result records.destroy_all
end
def wrap_result(result)
model = NonWorkingDay.new
errors = model.errors.tap do |err|
result.each do |r|
err.merge!(r.errors)
end
end
success = model.errors.empty?
ServiceResult.new(success:, errors:, result:)
end
end
``` | # OpenProject is an open source project management software.
# Copyright (C) 2010-2022 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
require_relative 'shared/shared_call_examples'
RSpec.describe Settings::WorkingDaysUpdateService do
let(:instance) do
described_class.new(user:)
end
let(:user) { build_stubbed(:user) }
let(:contract) do
instance_double(Settings::UpdateContract,
validate: contract_success,
errors: instance_double(ActiveModel::Error))
end
let(:contract_success) { true }
let(:params_contract) do
instance_double(Settings::WorkingDaysParamsContract,
valid?: params_contract_success,
errors: instance_double(ActiveModel::Error))
end
let(:params_contract_success) { true }
let(:setting_name) { :a_setting_name }
let(:new_setting_value) { 'a_new_setting_value' }
let(:previous_setting_value) { 'the_previous_setting_value' }
let(:setting_params) { { setting_name => new_setting_value } }
let(:non_working_days_params) { {} }
let(:params) { setting_params.merge(non_working_days: non_working_days_params) }
before do
# stub a setting definition
allow(Setting)
.to receive(:[])
.and_call_original
allow(Setting)
.to receive(:[]).with(setting_name)
.and_return(previous_setting_value)
allow(Setting)
.to receive(:[]=)
# stub contract
allow(Settings::UpdateContract)
.to receive(:new)
.and_return(contract)
allow(Settings::WorkingDaysParamsContract)
.to receive(:new)
.and_return(params_contract)
end
describe '#call' do
subject { instance.call(params) }
shared_examples 'successful working days settings call' do
include_examples 'successful call'
it 'calls the WorkPackages::ApplyWorkingDaysChangeJob' do
previous_working_days = Setting[:working_days]
previous_non_working_days = NonWorkingDay.pluck(:date)
allow(WorkPackages::ApplyWorkingDaysChangeJob).to receive(:perform_later)
subject
expect(WorkPackages::ApplyWorkingDaysChangeJob)
.to have_received(:perform_later)
.with(user_id: user.id, previous_working_days:, previous_non_working_days:)
end
end
shared_examples 'unsuccessful working days settings call' do
include_examples 'unsuccessful call'
it 'does not persists the non working days' do
expect { subject }.not_to change(NonWorkingDay, :count)
end
it 'does not calls the WorkPackages::ApplyWorkingDaysChangeJob' do
allow(WorkPackages::ApplyWorkingDaysChangeJob).to receive(:perform_later)
subject
expect(WorkPackages::ApplyWorkingDaysChangeJob).not_to have_received(:perform_later)
end
end
include_examples 'successful working days settings call'
context 'when non working days are present' do
let!(:existing_nwd) { create(:non_working_day, name: 'Existing NWD') }
let!(:nwd_to_delete) { create(:non_working_day, name: 'NWD to delete') }
let(:non_working_days_params) do
[
{ 'name' => 'Christmas Eve', 'date' => '2022-12-24' },
{ 'name' => 'NYE', 'date' => '2022-12-31' },
{ 'id' => existing_nwd.id },
{ 'id' => nwd_to_delete.id, '_destroy' => true }
]
end
include_examples 'successful working days settings call'
it 'persists (create/delete) the non working days' do
expect { subject }.to change(NonWorkingDay, :count).by(1)
expect { nwd_to_delete.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect(NonWorkingDay.all).to contain_exactly(
have_attributes(name: 'Christmas Eve', date: Date.parse('2022-12-24')),
have_attributes(name: 'NYE', date: Date.parse('2022-12-31')),
have_attributes(existing_nwd.slice(:id, :name, :date))
)
end
context 'when there are duplicates' do
context 'with both within the params' do
let(:non_working_days_params) do
[
{ 'name' => 'Christmas Eve', 'date' => '2022-12-24' },
{ 'name' => 'Christmas Eve', 'date' => '2022-12-24' }
]
end
include_examples 'unsuccessful working days settings call'
end
context 'with one saved in the database' do
let(:non_working_days_params) do
[existing_nwd.slice(:name, :date)]
end
include_examples 'unsuccessful working days settings call'
context 'when deleting and re-creating the duplicate non-working day' do
let(:non_working_days_params) do
[
nwd_to_delete.slice(:id, :name, :date).merge('_destroy' => true),
nwd_to_delete.slice(:name, :date)
]
end
include_examples 'successful working days settings call'
it 'persists (create/delete) the non working days' do
expect { subject }.not_to change(NonWorkingDay, :count)
expect { nwd_to_delete.reload }.to raise_error(ActiveRecord::RecordNotFound)
# The nwd_to_delete is being re-created after the deletion.
expect(NonWorkingDay.all).to contain_exactly(
have_attributes(existing_nwd.slice(:name, :date)),
have_attributes(nwd_to_delete.slice(:name, :date))
)
end
end
context 'with duplicate params when deleting and re-creating non-working days' do
let(:non_working_days_params) do
[
existing_nwd.slice(:id, :name, :date).merge('_destroy' => true),
existing_nwd.slice(:name, :date),
existing_nwd.slice(:name, :date)
]
end
include_examples 'unsuccessful working days settings call'
it 'returns the unchanged results including the ones marked for destruction' do
result = subject.result
expect(result).to contain_exactly(
have_attributes(existing_nwd.slice(:id, :name, :date)),
have_attributes(existing_nwd.slice(:name, :date).merge(id: nil)),
have_attributes(existing_nwd.slice(:name, :date).merge(id: nil))
)
expect(result.find { |r| r.id == existing_nwd.id }).to be_marked_for_destruction
end
end
end
end
end
context 'when the params contract is not successfully validated' do
let(:params_contract_success) { false }
include_examples 'unsuccessful working days settings call'
end
context 'when the contract is not successfully validated' do
let(:contract_success) { false }
include_examples 'unsuccessful working days settings call'
context 'when non working days are present' do
let(:non_working_days_params) do
[
{ 'name' => 'Christmas Eve', 'date' => '2022-12-24' },
{ 'name' => 'NYE', 'date' => '2022-12-31' }
]
end
include_examples 'unsuccessful working days settings call'
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Settings::UpdateService < BaseServices::BaseContracted
def initialize(user:)
super user:,
contract_class: Settings::UpdateContract
end
def persist(call)
params.each do |name, value|
set_setting_value(name, value)
end
call
end
private
def set_setting_value(name, value)
Setting[name] = derive_value(value)
end
def derive_value(value)
case value
when Array, Hash
# remove blank values in array, hash settings
value.compact_blank!
else
value.strip
end
end
end
``` | # OpenProject is an open source project management software.
# Copyright (C) 2010-2022 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
require_relative 'shared/shared_call_examples'
require_relative 'shared/shared_setup_context'
RSpec.describe Settings::UpdateService do
include_context 'with update service setup'
describe '#call' do
subject { instance.call(params) }
include_examples 'successful call'
context 'when the contract is not successfully validated' do
let(:contract_success) { false }
include_examples 'unsuccessful call'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module PlaceholderUsers
class SetAttributesService < ::BaseServices::SetAttributes
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe PlaceholderUsers::SetAttributesService, type: :model do
let(:current_user) { build_stubbed(:user) }
let(:contract_instance) do
contract = double('contract_instance')
allow(contract)
.to receive(:validate)
.and_return(contract_valid)
allow(contract)
.to receive(:errors)
.and_return(contract_errors)
contract
end
let(:contract_errors) { double('contract_errors') }
let(:contract_valid) { true }
let(:model_valid) { true }
let(:instance) do
described_class.new(user: current_user,
model: model_instance,
contract_class:,
contract_options: {})
end
let(:model_instance) { PlaceholderUser.new }
let(:contract_class) do
allow(PlaceholderUsers::CreateContract)
.to receive(:new)
.and_return(contract_instance)
PlaceholderUsers::CreateContract
end
let(:params) { {} }
before do
allow(model_instance)
.to receive(:valid?)
.and_return(model_valid)
end
subject { instance.call(params) }
it 'returns the instance as the result' do
expect(subject.result)
.to eql model_instance
end
it 'is a success' do
expect(subject)
.to be_success
end
context 'with params' do
let(:params) do
{
name: 'Foobar'
}
end
it 'assigns the params' do
subject
expect(model_instance.name).to eq 'Foobar'
expect(model_instance.lastname).to eq 'Foobar'
end
end
context 'with an invalid contract' do
let(:contract_valid) { false }
let(:expect_time_instance_save) do
expect(model_instance)
.not_to receive(:save)
end
it 'returns failure' do
expect(subject)
.not_to be_success
end
it "returns the contract's errors" do
expect(subject.errors)
.to eql(contract_errors)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class PlaceholderUsers::UpdateService < BaseServices::Update
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe PlaceholderUsers::UpdateService, type: :model do
it_behaves_like 'BaseServices update service'
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class PlaceholderUsers::CreateService < BaseServices::Create
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_create_service'
RSpec.describe PlaceholderUsers::CreateService, type: :model do
it_behaves_like 'BaseServices create service'
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class PlaceholderUsers::DeleteService < BaseServices::Delete
def destroy(placeholder)
placeholder.locked!
::Principals::DeleteJob.perform_later(placeholder)
true
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe PlaceholderUsers::DeleteService, type: :model do
let(:placeholder_user) { build_stubbed(:placeholder_user) }
let(:project) { build_stubbed(:project) }
let(:instance) { described_class.new(model: placeholder_user, user: actor) }
subject { instance.call }
shared_examples 'deletes the user' do
it do
expect(placeholder_user).to receive(:locked!)
expect(Principals::DeleteJob).to receive(:perform_later).with(placeholder_user)
expect(subject).to be_success
end
end
shared_examples 'does not delete the user' do
it do
expect(placeholder_user).not_to receive(:locked!)
expect(Principals::DeleteJob).not_to receive(:perform_later)
expect(subject).not_to be_success
end
end
context 'with admin user' do
let(:actor) { build_stubbed(:admin) }
it_behaves_like 'deletes the user'
end
context 'with global user' do
let(:actor) { build_stubbed(:user) }
before do
mock_permissions_for(actor) do |mock|
mock.allow_globally :manage_placeholder_user
end
end
it_behaves_like 'deletes the user'
end
context 'with unprivileged system user' do
let(:actor) { User.system }
before do
allow(actor).to receive(:admin?).and_return false
end
it_behaves_like 'does not delete the user'
end
context 'with privileged system user' do
let(:actor) { User.system }
it_behaves_like 'deletes the user' do
around do |example|
actor.run_given { example.run }
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
# TODO: This is but a stub
module Messages
class SetAttributesService < ::BaseServices::SetAttributes
include Attachments::SetReplacements
private
def set_default_attributes(*)
set_default_author
end
def set_default_author
model.change_by_system do
model.author = user
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Messages::SetAttributesService, type: :model do
let(:user) { build_stubbed(:user) }
let(:forum) { build_stubbed(:forum) }
let(:contract_instance) do
contract = double('contract_instance')
allow(contract)
.to receive(:validate)
.and_return(contract_valid)
allow(contract)
.to receive(:errors)
.and_return(contract_errors)
contract
end
let(:contract_errors) { double('contract_errors') }
let(:contract_valid) { true }
let(:time_entry_valid) { true }
let(:instance) do
described_class.new(user:,
model: message_instance,
contract_class:,
contract_options: {})
end
let(:message_instance) { Message.new }
let(:contract_class) do
allow(Messages::CreateContract)
.to receive(:new)
.with(message_instance, user, options: {})
.and_return(contract_instance)
Messages::CreateContract
end
let(:params) { {} }
before do
allow(message_instance)
.to receive(:valid?)
.and_return(time_entry_valid)
end
subject { instance.call(params) }
it 'returns the message instance as the result' do
expect(subject.result)
.to eql message_instance
end
it 'is a success' do
expect(subject)
.to be_success
end
it "has the service's user assigned as author" do
subject
expect(message_instance.author)
.to eql user
end
it 'notes the author to be system changed' do
subject
expect(message_instance.changed_by_system['author_id'])
.to eql [nil, user.id]
end
context 'with params' do
let(:params) do
{
forum:
}
end
let(:expected) do
{
author_id: user.id,
forum_id: forum.id
}.with_indifferent_access
end
it 'assigns the params' do
subject
attributes_of_interest = message_instance
.attributes
.slice(*expected.keys)
expect(attributes_of_interest)
.to eql(expected)
end
end
context 'with an invalid contract' do
let(:contract_valid) { false }
let(:expect_time_instance_save) do
expect(message_instance)
.not_to receive(:save)
end
it 'returns failure' do
expect(subject)
.not_to be_success
end
it "returns the contract's errors" do
expect(subject.errors)
.to eql(contract_errors)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Messages::UpdateService < BaseServices::Update
include Attachments::ReplaceAttachments
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe Messages::UpdateService, type: :model do
it_behaves_like 'BaseServices update service'
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Messages::CreateService < BaseServices::Create
include Attachments::ReplaceAttachments
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_create_service'
RSpec.describe Messages::CreateService, type: :model do
it_behaves_like 'BaseServices create service'
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Relations::UpdateService < Relations::BaseService
attr_accessor :model
def initialize(user:, model:)
super(user:)
self.model = model
self.contract_class = Relations::UpdateContract
end
def perform(attributes)
in_user_context(send_notifications: attributes[:send_notifications]) do
update_relation model, attributes
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Relations::UpdateService do
let(:work_package1_start_date) { nil }
let(:work_package1_due_date) { Date.today }
let(:work_package2_start_date) { nil }
let(:work_package2_due_date) { nil }
let(:follows_relation) { false }
let(:delay) { 3 }
let(:work_package1) do
build_stubbed(:work_package,
due_date: work_package1_due_date,
start_date: work_package1_start_date)
end
let(:work_package2) do
build_stubbed(:work_package,
due_date: work_package2_due_date,
start_date: work_package2_start_date)
end
let(:instance) do
described_class.new(user:, model: relation)
end
let(:relation) do
relation = build_stubbed(:relation)
allow(relation)
.to receive(:follows?)
.and_return(follows_relation)
relation
end
let(:attributes) do
{
to: work_package1,
from: work_package2,
delay:
}
end
let(:user) { build_stubbed(:user) }
let(:model_valid) { true }
let(:contract_valid) { true }
let(:contract) { double('contract') }
let(:symbols_for_base) { [] }
subject do
instance.call(attributes:)
end
before do
allow(relation)
.to receive(:save)
.and_return(model_valid)
allow(Relations::UpdateContract)
.to receive(:new)
.with(relation, user, options: {})
.and_return(contract)
allow(contract)
.to receive(:validate)
.and_return(contract_valid)
end
context 'when all valid and it is a follows relation' do
let(:set_schedule_service) { double('set schedule service') }
let(:set_schedule_work_package2_result) do
ServiceResult.success result: work_package2, errors: work_package2.errors
end
let(:set_schedule_result) do
sr = ServiceResult.success result: work_package2, errors: work_package2.errors
sr.dependent_results << set_schedule_work_package2_result
sr
end
let(:follows_relation) { true }
before do
expect(WorkPackages::SetScheduleService)
.to receive(:new)
.with(user:, work_package: work_package1)
.and_return(set_schedule_service)
expect(set_schedule_service)
.to receive(:call)
.and_return(set_schedule_result)
allow(work_package2)
.to receive(:changed?)
.and_return(true)
expect(work_package2)
.to receive(:save)
.and_return(true)
allow(set_schedule_result)
.to receive(:success=)
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the relation' do
expect(subject.result)
.to eql relation
end
it 'has a dependent result for the from-work package' do
expect(subject.dependent_results)
.to match_array [set_schedule_work_package2_result]
end
end
context 'when all is valid and it is not a follows relation' do
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the relation' do
expect(subject.result)
.to eql relation
end
end
context 'when the contract is invalid' do
let(:contract_valid) { false }
let(:contract_errors) { double('contract_errors') }
before do
allow(contract)
.to receive(:errors)
.and_return(contract_errors)
allow(contract_errors)
.to receive(:symbols_for)
.with(:base)
.and_return(symbols_for_base)
end
it 'is unsuccessful' do
expect(subject)
.to be_failure
end
it "returns the contract's errors" do
expect(subject.errors)
.to eql contract_errors
end
end
context 'when the model is invalid' do
let(:model_valid) { false }
let(:model_errors) { double('model_errors') }
before do
allow(relation)
.to receive(:errors)
.and_return(model_errors)
allow(model_errors)
.to receive(:symbols_for)
.with(:base)
.and_return(symbols_for_base)
end
it 'is unsuccessful' do
expect(subject)
.to be_failure
end
it "returns the model's errors" do
expect(subject.errors)
.to eql model_errors
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Relations::CreateService < Relations::BaseService
def initialize(user:)
super
self.contract_class = Relations::CreateContract
end
def perform(send_notifications: nil, **attributes)
in_user_context(send_notifications:) do
update_relation ::Relation.new, attributes
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Relations::CreateService do
let(:work_package1_start_date) { nil }
let(:work_package1_due_date) { Date.today }
let(:work_package2_start_date) { nil }
let(:work_package2_due_date) { nil }
let(:follows_relation) { false }
let(:delay) { 3 }
let(:work_package1) do
build_stubbed(:work_package,
due_date: work_package1_due_date,
start_date: work_package1_start_date)
end
let(:work_package2) do
build_stubbed(:work_package,
due_date: work_package2_due_date,
start_date: work_package2_start_date)
end
let(:instance) do
described_class.new(user:)
end
let(:relation) do
relation = Relation.new attributes
allow(relation)
.to receive(:follows?)
.and_return(follows_relation)
relation
end
let(:attributes) do
{
to: work_package1,
from: work_package2,
delay:
}
end
let(:user) { build_stubbed(:user) }
let(:model_valid) { true }
let(:contract_valid) { true }
let(:contract) { double('contract') }
let(:symbols_for_base) { [] }
subject do
instance.call(attributes)
end
before do
allow(Relation)
.to receive(:new)
.and_return(relation)
allow(relation)
.to receive(:save)
.and_return(model_valid)
allow(Relations::CreateContract)
.to receive(:new)
.with(relation, user, options: {})
.and_return(contract)
allow(contract)
.to receive(:validate)
.and_return(contract_valid)
end
context 'if all valid and it is a follows relation' do
let(:set_schedule_service) { double('set schedule service') }
let(:set_schedule_work_package2_result) do
ServiceResult.success result: work_package2, errors: work_package2.errors
end
let(:set_schedule_result) do
sr = ServiceResult.success result: work_package2, errors: work_package2.errors
sr.dependent_results << set_schedule_work_package2_result
sr
end
let(:follows_relation) { true }
before do
expect(WorkPackages::SetScheduleService)
.to receive(:new)
.with(user:, work_package: work_package1)
.and_return(set_schedule_service)
expect(set_schedule_service)
.to receive(:call)
.and_return(set_schedule_result)
allow(work_package2)
.to receive(:changed?)
.and_return(true)
expect(work_package2)
.to receive(:save)
.and_return(true)
allow(set_schedule_result)
.to receive(:success=)
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the relation' do
expect(subject.result)
.to eql relation
end
it 'has a dependent result for the from-work package' do
expect(subject.dependent_results)
.to contain_exactly(set_schedule_work_package2_result)
end
end
context 'if all is valid and it is not a follows relation' do
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the relation' do
expect(subject.result)
.to eql relation
end
end
context 'if the contract is invalid' do
let(:contract_valid) { false }
let(:contract_errors) { double('contract_errors') }
before do
allow(contract)
.to receive(:errors)
.and_return(contract_errors)
allow(contract_errors)
.to receive(:symbols_for)
.with(:base)
.and_return(symbols_for_base)
end
it 'is unsuccessful' do
expect(subject)
.to be_failure
end
it "returns the contract's errors" do
expect(subject.errors)
.to eql contract_errors
end
end
context 'if the model is invalid' do
let(:model_valid) { false }
let(:model_errors) { double('model_errors') }
before do
allow(relation)
.to receive(:errors)
.and_return(model_errors)
allow(model_errors)
.to receive(:symbols_for)
.with(:base)
.and_return(symbols_for_base)
end
it 'is unsuccessful' do
expect(subject)
.to be_failure
end
it "returns the model's errors" do
expect(subject.errors)
.to eql model_errors
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class WorkPackages::SetAttributesService < BaseServices::SetAttributes
include Attachments::SetReplacements
private
def set_attributes(attributes)
file_links_ids = attributes.delete(:file_links_ids)
model.file_links = Storages::FileLink.where(id: file_links_ids) if file_links_ids
set_attachments_attributes(attributes)
set_static_attributes(attributes)
model.change_by_system do
set_calculated_attributes(attributes)
end
set_custom_attributes(attributes)
end
def set_static_attributes(attributes)
assignable_attributes = attributes.select do |key, _|
!CustomField.custom_field_attribute?(key) && work_package.respond_to?(key)
end
work_package.attributes = assignable_attributes
end
def set_calculated_attributes(attributes)
if work_package.new_record?
set_default_attributes(attributes)
unify_milestone_dates
else
update_dates
end
shift_dates_to_soonest_working_days
update_duration
update_derivable
update_project_dependent_attributes
reassign_invalid_status_if_type_changed
set_templated_description
end
def derivable_attribute
derivable_attribute_by_others_presence || derivable_attribute_by_others_absence
end
# Returns a field derivable by the presence of the two others, or +nil+ if
# none was found.
#
# Matching is done in the order :duration, :due_date, :start_date. The first
# one to match is returned.
#
# If +ignore_non_working_days+ has been changed, try deriving +due_date+ and
# +start_date+ before +duration+.
def derivable_attribute_by_others_presence
fields =
if work_package.ignore_non_working_days_changed?
%i[due_date start_date duration]
else
%i[duration due_date start_date]
end
fields.find { |field| derivable_by_others_presence?(field) }
end
# Returns true if given +field+ is derivable from the presence of the two
# others.
#
# A field is derivable if it has not been set explicitly while the other two
# fields are set.
def derivable_by_others_presence?(field)
others = %i[start_date due_date duration].without(field)
attribute_not_set_in_params?(field) && all_present?(*others)
end
# Returns a field derivable by the absence of one of the two others, or +nil+
# if none was found.
#
# Matching is done in the order :duration, :due_date, :start_date. The first
# one to match is returned.
def derivable_attribute_by_others_absence
%i[duration due_date start_date].find { |field| derivable_by_others_absence?(field) }
end
# Returns true if given +field+ is derivable from the absence of one of the
# two others.
#
# A field is derivable if it has not been set explicitly while the other two
# fields have one set and one nil.
#
# Note: if both other fields are nil, then the field is not derivable
def derivable_by_others_absence?(field)
others = %i[start_date due_date duration].without(field)
attribute_not_set_in_params?(field) && only_one_present?(*others)
end
def attribute_not_set_in_params?(field)
!params.has_key?(field)
end
def all_present?(*fields)
work_package.values_at(*fields).all?(&:present?)
end
def only_one_present?(*fields)
work_package.values_at(*fields).one?(&:present?)
end
# rubocop:disable Metrics/AbcSize
def update_derivable
case derivable_attribute
when :duration
work_package.duration =
if work_package.milestone?
1
else
days.duration(work_package.start_date, work_package.due_date)
end
when :due_date
work_package.due_date = days.due_date(work_package.start_date, work_package.duration)
when :start_date
work_package.start_date = days.start_date(work_package.due_date, work_package.duration)
end
end
# rubocop:enable Metrics/AbcSize
def set_default_attributes(attributes)
set_default_priority
set_default_author
set_default_status
set_default_start_date(attributes)
set_default_due_date(attributes)
end
def non_or_default_description?
work_package.description.blank? || false
end
def set_default_author
work_package.author ||= user
end
def set_default_status
work_package.status ||= Status.default
end
def set_default_priority
work_package.priority ||= IssuePriority.active.default
end
def set_default_start_date(attributes)
return if attributes.has_key?(:start_date)
work_package.start_date ||= if parent_start_earlier_than_due?
work_package.parent.start_date
elsif Setting.work_package_startdate_is_adddate?
Time.zone.today
end
end
def set_default_due_date(attributes)
return if attributes.has_key?(:due_date)
work_package.due_date ||= if parent_due_later_than_start?
work_package.parent.due_date
end
end
def set_templated_description
# We only set this if the work package is new
return unless work_package.new_record?
# And the type was changed
return unless work_package.type_id_changed?
# And the new type has a default text
default_description = work_package.type&.description
return if default_description.blank?
# And the current description matches ANY current default text
return unless work_package.description.blank? || default_description?
work_package.description = default_description
end
def default_description?
Type
.pluck(:description)
.compact
.map(&method(:normalize_whitespace))
.include?(normalize_whitespace(work_package.description))
end
def normalize_whitespace(string)
string.gsub(/\s/, ' ').squeeze(' ')
end
def set_custom_attributes(attributes)
assignable_attributes = attributes.select do |key, _|
CustomField.custom_field_attribute?(key) && work_package.respond_to?(key)
end
work_package.attributes = assignable_attributes
initialize_unset_custom_values
end
def custom_field_context_changed?
work_package.type_id_changed? || work_package.project_id_changed?
end
def work_package_now_milestone?
work_package.type_id_changed? && work_package.milestone?
end
def update_project_dependent_attributes
return unless work_package.project_id_changed? && work_package.project_id
model.change_by_system do
set_version_to_nil
reassign_category
set_parent_to_nil
reassign_type unless work_package.type_id_changed?
end
end
def update_dates
unify_milestone_dates
min_start = new_start_date
return unless min_start
work_package.due_date = new_due_date(min_start)
work_package.start_date = min_start
end
def unify_milestone_dates
return unless work_package_now_milestone?
unified_date = work_package.due_date || work_package.start_date
work_package.start_date = work_package.due_date = unified_date
end
def shift_dates_to_soonest_working_days
return if work_package.ignore_non_working_days?
work_package.start_date = days.soonest_working_day(work_package.start_date)
work_package.due_date = days.soonest_working_day(work_package.due_date)
end
def update_duration
work_package.duration = 1 if work_package.milestone?
end
def set_version_to_nil
if work_package.version &&
work_package.project &&
work_package.project.shared_versions.exclude?(work_package.version)
work_package.version = nil
end
end
def set_parent_to_nil
if !Setting.cross_project_work_package_relations? &&
!work_package.parent_changed?
work_package.parent = nil
end
end
def reassign_category
# work_package is moved to another project
# reassign to the category with same name if any
if work_package.category.present?
category = work_package.project.categories.find_by(name: work_package.category.name)
work_package.category = category
end
end
def reassign_type
available_types = work_package.project.types.order(:position)
return if available_types.include?(work_package.type) && work_package.type
work_package.type = available_types.first
reassign_status assignable_statuses
end
def reassign_status(available_statuses)
return if available_statuses.include?(work_package.status) || work_package.status.is_a?(Status::InexistentStatus)
new_status = available_statuses.detect(&:is_default) || available_statuses.first || Status.default
work_package.status = new_status if new_status.present?
end
def reassign_invalid_status_if_type_changed
# Checks that the issue can not be moved to a type with the status unchanged
# and the target type does not have this status
if work_package.type_id_changed?
reassign_status work_package.type.statuses(include_default: true)
end
end
# Take over any default custom values
# for new custom fields
def initialize_unset_custom_values
work_package.set_default_values! if custom_field_context_changed?
end
def new_start_date
current_start_date = work_package.start_date || work_package.due_date
return unless current_start_date && work_package.schedule_automatically?
min_start = new_start_date_from_parent || new_start_date_from_self
min_start = days.soonest_working_day(min_start)
if min_start && (min_start > current_start_date || work_package.schedule_manually_changed?)
min_start
end
end
def new_start_date_from_parent
return unless work_package.parent_id_changed? &&
work_package.parent
work_package.parent.soonest_start
end
def new_start_date_from_self
return unless work_package.schedule_manually_changed?
[min_child_date, work_package.soonest_start].compact.max
end
def new_due_date(min_start)
duration = children_duration || work_package.duration
days.due_date(min_start, duration)
end
def work_package
model
end
def assignable_statuses
instantiate_contract(work_package, user).assignable_statuses(include_default: true)
end
def min_child_date
children_dates.min
end
def children_duration
max = max_child_date
return unless max
days.duration(min_child_date, max_child_date)
end
def days
WorkPackages::Shared::Days.for(work_package)
end
def max_child_date
children_dates.max
end
def children_dates
@children_dates ||= work_package.children.pluck(:start_date, :due_date).flatten.compact
end
def parent_start_earlier_than_due?
start = work_package.parent&.start_date
due = work_package.due_date || work_package.parent&.due_date
(start && !due) || ((due && start) && (start < due))
end
def parent_due_later_than_start?
due = work_package.parent&.due_date
start = work_package.start_date || work_package.parent&.start_date
(due && !start) || ((due && start) && (due > start))
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe WorkPackages::SetAttributesService,
type: :model do
let(:today) { Time.zone.today }
let(:user) { build_stubbed(:user) }
let(:project) do
p = build_stubbed(:project)
allow(p).to receive(:shared_versions).and_return([])
p
end
let(:work_package) do
wp = build_stubbed(:work_package, project:)
wp.type = initial_type
wp.send(:clear_changes_information)
wp
end
let(:new_work_package) do
WorkPackage.new
end
let(:initial_type) { build_stubbed(:type) }
let(:milestone_type) { build_stubbed(:type_milestone) }
let(:statuses) { [] }
let(:contract_class) { WorkPackages::UpdateContract }
let(:mock_contract) do
class_double(contract_class,
new: mock_contract_instance)
end
let(:mock_contract_instance) do
instance_double(contract_class,
assignable_statuses: statuses,
errors: contract_errors,
validate: contract_valid)
end
let(:contract_valid) { true }
let(:contract_errors) do
instance_double(ActiveModel::Errors)
end
let(:instance) do
described_class.new(user:,
model: work_package,
contract_class: mock_contract)
end
shared_examples_for 'service call' do
subject do
allow(work_package)
.to receive(:save)
instance.call(call_attributes)
end
it 'is successful' do
expect(subject).to be_success
end
it 'sets the value' do
next if !defined?(expected_attributes) || expected_attributes.blank?
subject
expected_attributes.each do |attribute, key|
expect(work_package.send(attribute)).to eql key
end
end
it 'does not persist the work_package' do
subject
expect(work_package)
.not_to have_received(:save)
end
it 'has no errors' do
expect(subject.errors).to be_empty
end
context 'when the contract does not validate' do
let(:contract_valid) { false }
it 'is unsuccessful' do
expect(subject).not_to be_success
end
it 'does not persist the changes' do
subject
expect(work_package)
.not_to have_received(:save)
end
it "exposes the contract's errors" do
subject
expect(subject.errors).to eql mock_contract_instance.errors
end
end
end
context 'when updating subject before calling the service' do
let(:call_attributes) { {} }
let(:expected_attributes) { { subject: 'blubs blubs' } }
before do
work_package.attributes = expected_attributes
end
it_behaves_like 'service call'
end
context 'when updating subject via attributes' do
let(:call_attributes) { expected_attributes }
let(:expected_attributes) { { subject: 'blubs blubs' } }
it_behaves_like 'service call'
end
context 'for status' do
let(:default_status) { build_stubbed(:default_status) }
let(:other_status) { build_stubbed(:status) }
let(:new_statuses) { [other_status, default_status] }
before do
allow(Status)
.to receive(:default)
.and_return(default_status)
end
context 'with no value set before for a new work package' do
let(:call_attributes) { {} }
let(:expected_attributes) { { status: default_status } }
let(:work_package) { new_work_package }
before do
work_package.status = nil
end
it_behaves_like 'service call'
end
context 'with an invalid value that is not part of the type.statuses for a new work package' do
let(:invalid_status) { create(:status) }
let(:type) { create(:type) }
let(:call_attributes) { { status: invalid_status, type: } }
let(:expected_attributes) { { status: default_status, type: } }
let(:work_package) { new_work_package }
it_behaves_like 'service call'
end
context 'with valid value and without a type present for a new work package' do
let(:status) { create(:status) }
let(:call_attributes) { { status:, type: nil } }
let(:expected_attributes) { { status: } }
let(:work_package) { new_work_package }
it_behaves_like 'service call'
end
context 'with a valid value that is part of the type.statuses for a new work package' do
let(:type) { create(:type) }
let(:status) { create(:status, workflow_for_type: type) }
let(:call_attributes) { { status:, type: } }
let(:expected_attributes) { { status:, type: } }
let(:work_package) { new_work_package }
it_behaves_like 'service call'
end
context 'with no value set on existing work package' do
let(:call_attributes) { {} }
let(:expected_attributes) { {} }
before do
work_package.status = nil
end
it_behaves_like 'service call' do
it 'stays nil' do
subject
expect(work_package.status)
.to be_nil
end
end
end
context 'when updating status before calling the service' do
let(:call_attributes) { {} }
let(:expected_attributes) { { status: other_status } }
before do
work_package.attributes = expected_attributes
end
it_behaves_like 'service call'
end
context 'when updating status via attributes' do
let(:call_attributes) { expected_attributes }
let(:expected_attributes) { { status: other_status } }
it_behaves_like 'service call'
end
end
context 'for author' do
let(:other_user) { build_stubbed(:user) }
context 'with no value set before for a new work package' do
let(:call_attributes) { {} }
let(:expected_attributes) { {} }
let(:work_package) { new_work_package }
it_behaves_like 'service call' do
it "sets the service's author" do
subject
expect(work_package.author)
.to eql user
end
it 'notes the author to be system changed' do
subject
expect(work_package.changed_by_system['author_id'])
.to eql [nil, user.id]
end
end
end
context 'with no value set on existing work package' do
let(:call_attributes) { {} }
let(:expected_attributes) { {} }
before do
work_package.author = nil
end
it_behaves_like 'service call' do
it 'stays nil' do
subject
expect(work_package.author)
.to be_nil
end
end
end
context 'when updating author before calling the service' do
let(:call_attributes) { {} }
let(:expected_attributes) { { author: other_user } }
before do
work_package.attributes = expected_attributes
end
it_behaves_like 'service call'
end
context 'when updating author via attributes' do
let(:call_attributes) { expected_attributes }
let(:expected_attributes) { { author: other_user } }
it_behaves_like 'service call'
end
end
context 'with the actual contract' do
let(:invalid_wp) do
build(:work_package, subject: '').tap do |wp|
wp.save!(validate: false)
end
end
let(:user) { build_stubbed(:admin) }
let(:instance) do
described_class.new(user:,
model: invalid_wp,
contract_class:)
end
context 'with a currently invalid subject' do
let(:call_attributes) { expected_attributes }
let(:expected_attributes) { { subject: 'ABC' } }
let(:contract_valid) { true }
subject { instance.call(call_attributes) }
it 'is successful' do
expect(subject).to be_success
expect(subject.errors).to be_empty
end
end
end
context 'for start_date & due_date & duration' do
context 'with a parent' do
let(:expected_attributes) { {} }
let(:work_package) { new_work_package }
let(:parent) do
build_stubbed(:work_package,
start_date: parent_start_date,
due_date: parent_due_date)
end
let(:parent_start_date) { Time.zone.today - 5.days }
let(:parent_due_date) { Time.zone.today + 10.days }
context 'with the parent having dates and not providing own dates' do
let(:call_attributes) { { parent: } }
it_behaves_like 'service call' do
it "sets the start_date to the parent`s start_date" do
subject
expect(work_package.start_date)
.to eql parent_start_date
end
it "sets the due_date to the parent`s due_date" do
subject
expect(work_package.due_date)
.to eql parent_due_date
end
end
end
context 'with the parent having dates and not providing own dates and with the parent`s' \
'soonest_start being before the start_date (e.g. because the parent is manually scheduled)' do
let(:call_attributes) { { parent: } }
before do
allow(parent)
.to receive(:soonest_start)
.and_return(parent_start_date + 3.days)
end
it_behaves_like 'service call' do
it "sets the start_date to the parent`s start_date" do
subject
expect(work_package.start_date)
.to eql parent_start_date
end
it "sets the due_date to the parent`s due_date" do
subject
expect(work_package.due_date)
.to eql parent_due_date
end
end
end
context 'with the parent having start date (no due) and not providing own dates' do
let(:call_attributes) { { parent: } }
let(:parent_due_date) { nil }
it_behaves_like 'service call' do
it "sets the start_date to the parent`s start_date" do
subject
expect(work_package.start_date)
.to eql parent_start_date
end
it "sets the due_date to nil" do
subject
expect(work_package.due_date)
.to be_nil
end
end
end
context 'with the parent having due date (no start) and not providing own dates' do
let(:call_attributes) { { parent: } }
let(:parent_start_date) { nil }
it_behaves_like 'service call' do
it "sets the start_date to nil" do
subject
expect(work_package.start_date)
.to be_nil
end
it "sets the due_date to the parent`s due_date" do
subject
expect(work_package.due_date)
.to eql parent_due_date
end
end
end
context 'with the parent having dates but providing own dates' do
let(:call_attributes) { { parent:, start_date: Time.zone.today, due_date: Time.zone.today + 1.day } }
it_behaves_like 'service call' do
it "sets the start_date to the provided date" do
subject
expect(work_package.start_date)
.to eql Time.zone.today
end
it "sets the due_date to the provided date" do
subject
expect(work_package.due_date)
.to eql Time.zone.today + 1.day
end
end
end
context 'with the parent having dates but providing own start_date' do
let(:call_attributes) { { parent:, start_date: Time.zone.today } }
it_behaves_like 'service call' do
it "sets the start_date to the provided date" do
subject
expect(work_package.start_date)
.to eql Time.zone.today
end
it "sets the due_date to the parent's due_date" do
subject
expect(work_package.due_date)
.to eql parent_due_date
end
end
end
context 'with the parent having dates but providing own due_date' do
let(:call_attributes) { { parent:, due_date: Time.zone.today + 4.days } }
it_behaves_like 'service call' do
it "sets the start_date to the parent's start date" do
subject
expect(work_package.start_date)
.to eql parent_start_date
end
it "sets the due_date to the provided date" do
subject
expect(work_package.due_date)
.to eql Time.zone.today + 4.days
end
end
end
context 'with the parent having dates but providing own empty start_date' do
let(:call_attributes) { { parent:, start_date: nil } }
it_behaves_like 'service call' do
it "sets the start_date to nil" do
subject
expect(work_package.start_date)
.to be_nil
end
it "sets the due_date to the parent's due_date" do
subject
expect(work_package.due_date)
.to eql parent_due_date
end
end
end
context 'with the parent having dates but providing own empty due_date' do
let(:call_attributes) { { parent:, due_date: nil } }
it_behaves_like 'service call' do
it "sets the start_date to the parent's start date" do
subject
expect(work_package.start_date)
.to eql parent_start_date
end
it "sets the due_date to nil" do
subject
expect(work_package.due_date)
.to be_nil
end
end
end
context 'with the parent having dates but providing a start date that is before parent`s due date`' do
let(:call_attributes) { { parent:, start_date: parent_due_date - 4.days } }
it_behaves_like 'service call' do
it "sets the start_date to the provided date" do
subject
expect(work_package.start_date)
.to eql parent_due_date - 4.days
end
it "sets the due_date to the parent's due_date" do
subject
expect(work_package.due_date)
.to eql parent_due_date
end
end
end
context 'with the parent having dates but providing a start date that is after the parent`s due date`' do
let(:call_attributes) { { parent:, start_date: parent_due_date + 1.day } }
it_behaves_like 'service call' do
it "sets the start_date to the provided date" do
subject
expect(work_package.start_date)
.to eql parent_due_date + 1.day
end
it "leaves the due date empty" do
subject
expect(work_package.due_date)
.to be_nil
end
end
end
context 'with the parent having dates but providing a due date that is before the parent`s start date`' do
let(:call_attributes) { { parent:, due_date: parent_start_date - 3.days } }
it_behaves_like 'service call' do
it "leaves the start date empty" do
subject
expect(work_package.start_date)
.to be_nil
end
it "set the due date to the provided date" do
subject
expect(work_package.due_date)
.to eql parent_start_date - 3.days
end
end
end
context 'with providing a parent_id that is invalid' do
let(:call_attributes) { { parent_id: -1 } }
let(:work_package) { build_stubbed(:work_package, start_date: Time.zone.today, due_date: Time.zone.today + 2.days) }
it_behaves_like 'service call' do
it "sets the start_date to the parent`s start_date" do
subject
expect(work_package.start_date)
.to eql Time.zone.today
end
it "sets the due_date to the parent`s due_date" do
subject
expect(work_package.due_date)
.to eql Time.zone.today + 2.days
end
end
end
end
context 'with no value set for a new work package and with default setting active',
with_settings: { work_package_startdate_is_adddate: true } do
let(:call_attributes) { {} }
let(:expected_attributes) { {} }
let(:work_package) { new_work_package }
it_behaves_like 'service call' do
it "sets the start date to today" do
subject
expect(work_package.start_date)
.to eql Time.zone.today
end
it "sets the duration to nil" do
subject
expect(work_package.duration)
.to be_nil
end
context 'when the work package type is milestone' do
before do
work_package.type = milestone_type
end
it "sets the duration to 1" do
subject
expect(work_package.duration)
.to eq 1
end
end
end
end
context 'with a value set for a new work package and with default setting active',
with_settings: { work_package_startdate_is_adddate: true } do
let(:call_attributes) { { start_date: Time.zone.today + 1.day } }
let(:expected_attributes) { {} }
let(:work_package) { new_work_package }
it_behaves_like 'service call' do
it 'stays that value' do
subject
expect(work_package.start_date)
.to eq(Time.zone.today + 1.day)
end
it "sets the duration to nil" do
subject
expect(work_package.duration)
.to be_nil
end
context 'when the work package type is milestone' do
before do
work_package.type = milestone_type
end
it "sets the duration to 1" do
subject
expect(work_package.duration)
.to eq 1
end
end
end
end
context 'with date values set to the same date on a new work package' do
let(:call_attributes) { { start_date: Time.zone.today, due_date: Time.zone.today } }
let(:expected_attributes) { {} }
let(:work_package) { new_work_package }
it_behaves_like 'service call' do
it 'sets the start date value' do
subject
expect(work_package.start_date)
.to eq(Time.zone.today)
end
it 'sets the due date value' do
subject
expect(work_package.due_date)
.to eq(Time.zone.today)
end
it "sets the duration to 1" do
subject
expect(work_package.duration)
.to eq 1
end
end
end
context 'with date values set on a new work package' do
let(:call_attributes) { { start_date: Time.zone.today, due_date: Time.zone.today + 5.days } }
let(:expected_attributes) { {} }
let(:work_package) { new_work_package }
it_behaves_like 'service call' do
it 'sets the start date value' do
subject
expect(work_package.start_date)
.to eq(Time.zone.today)
end
it 'sets the due date value' do
subject
expect(work_package.due_date)
.to eq(Time.zone.today + 5.days)
end
it "sets the duration to 6" do
subject
expect(work_package.duration)
.to eq 6
end
end
end
context 'with start date changed' do
let(:work_package) { build_stubbed(:work_package, start_date: Time.zone.today, due_date: Time.zone.today + 5.days) }
let(:call_attributes) { { start_date: Time.zone.today + 1.day } }
let(:expected_attributes) { {} }
it_behaves_like 'service call' do
it 'sets the start date value' do
subject
expect(work_package.start_date)
.to eq(Time.zone.today + 1.day)
end
it 'keeps the due date value' do
subject
expect(work_package.due_date)
.to eq(Time.zone.today + 5.days)
end
it "updates the duration" do
subject
expect(work_package.duration)
.to eq 5
end
end
end
context 'with due date changed' do
let(:work_package) { build_stubbed(:work_package, start_date: Time.zone.today, due_date: Time.zone.today + 5.days) }
let(:call_attributes) { { due_date: Time.zone.today + 1.day } }
let(:expected_attributes) { {} }
it_behaves_like 'service call' do
it 'keeps the start date value' do
subject
expect(work_package.start_date)
.to eq(Time.zone.today)
end
it 'sets the due date value' do
subject
expect(work_package.due_date)
.to eq(Time.zone.today + 1.day)
end
it "updates the duration" do
subject
expect(work_package.duration)
.to eq 2
end
end
end
context 'with start date nilled' do
let(:traits) { [] }
let(:work_package) do
build_stubbed(:work_package, *traits, start_date: Time.zone.today, due_date: Time.zone.today + 5.days)
end
let(:call_attributes) { { start_date: nil } }
let(:expected_attributes) { {} }
it_behaves_like 'service call' do
it 'sets the start date to nil' do
subject
expect(work_package.start_date)
.to be_nil
end
it 'keeps the due date value' do
subject
expect(work_package.due_date)
.to eq(Time.zone.today + 5.days)
end
it "sets the duration to nil" do
subject
expect(work_package.duration)
.to be_nil
end
context 'when the work package type is milestone' do
let(:traits) { [:is_milestone] }
it "sets the duration to 1" do
subject
expect(work_package.duration)
.to eq 1
end
end
end
end
context 'with due date nilled' do
let(:traits) { [] }
let(:work_package) do
build_stubbed(:work_package, *traits, start_date: Time.zone.today, due_date: Time.zone.today + 5.days)
end
let(:call_attributes) { { due_date: nil } }
let(:expected_attributes) { {} }
it_behaves_like 'service call' do
it 'keeps the start date' do
subject
expect(work_package.start_date)
.to eq(Time.zone.today)
end
it 'nils the due date' do
subject
expect(work_package.due_date)
.to be_nil
end
it "sets the duration to nil" do
subject
expect(work_package.duration)
.to be_nil
end
context 'when the work package type is milestone' do
let(:traits) { [:is_milestone] }
it "sets the duration to 1" do
subject
expect(work_package.duration)
.to eq 1
end
end
end
end
context 'when deriving one value from the two others' do
# rubocop:disable Layout/ExtraSpacing, Layout/SpaceInsideArrayPercentLiteral, Layout/SpaceInsidePercentLiteralDelimiters, Layout/LineLength
all_possible_scenarios = [
{ initial: %i[start_date due_date duration], set: %i[], expected: {} },
{ initial: %i[start_date ], set: %i[], expected: {} },
{ initial: %i[ due_date ], set: %i[], expected: {} },
{ initial: %i[ duration], set: %i[], expected: {} },
{ initial: %i[ ], set: %i[], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[start_date], expected: { change: :duration } },
{ initial: %i[start_date ], set: %i[start_date], expected: {} },
{ initial: %i[ due_date ], set: %i[start_date], expected: { change: :duration } },
{ initial: %i[ duration], set: %i[start_date], expected: { change: :due_date } },
{ initial: %i[ ], set: %i[start_date], expected: {} },
{ initial: %i[start_date due_date duration], nilled: %i[start_date], expected: { nilify: :duration } },
{ initial: %i[start_date ], nilled: %i[start_date], expected: {} },
{ initial: %i[ due_date ], nilled: %i[start_date], expected: {} },
{ initial: %i[ duration], nilled: %i[start_date], expected: {} },
{ initial: %i[ ], nilled: %i[start_date], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[due_date], expected: { change: :duration } },
{ initial: %i[start_date ], set: %i[due_date], expected: { change: :duration } },
{ initial: %i[ due_date ], set: %i[due_date], expected: {} },
{ initial: %i[ duration], set: %i[due_date], expected: { change: :start_date } },
{ initial: %i[ ], set: %i[due_date], expected: {} },
{ initial: %i[start_date due_date duration], nilled: %i[due_date], expected: { nilify: :duration } },
{ initial: %i[start_date ], nilled: %i[due_date], expected: {} },
{ initial: %i[ due_date ], nilled: %i[due_date], expected: {} },
{ initial: %i[ duration], nilled: %i[due_date], expected: {} },
{ initial: %i[ ], nilled: %i[due_date], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[duration], expected: { change: :due_date } },
{ initial: %i[start_date ], set: %i[duration], expected: { change: :due_date } },
{ initial: %i[ due_date ], set: %i[duration], expected: { change: :start_date } },
{ initial: %i[ duration], set: %i[duration], expected: {} },
{ initial: %i[ ], set: %i[duration], expected: {} },
{ initial: %i[start_date due_date duration], nilled: %i[duration], expected: { nilify: :due_date } },
{ initial: %i[start_date ], nilled: %i[duration], expected: {} },
{ initial: %i[ due_date ], nilled: %i[duration], expected: {} },
{ initial: %i[ duration], nilled: %i[duration], expected: {} },
{ initial: %i[ ], nilled: %i[duration], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[start_date due_date], expected: { change: :duration } },
{ initial: %i[start_date ], set: %i[start_date due_date], expected: { change: :duration } },
{ initial: %i[ due_date ], set: %i[start_date due_date], expected: { change: :duration } },
{ initial: %i[ duration], set: %i[start_date due_date], expected: { change: :duration } },
{ initial: %i[ ], set: %i[start_date due_date], expected: { change: :duration } },
{ initial: %i[start_date due_date duration], set: %i[start_date], nilled: %i[due_date], expected: { nilify: :duration } },
{ initial: %i[start_date ], set: %i[start_date], nilled: %i[due_date], expected: {} },
{ initial: %i[ due_date ], set: %i[start_date], nilled: %i[due_date], expected: {} },
{ initial: %i[ duration], set: %i[start_date], nilled: %i[due_date], expected: { nilify: :duration, same: :due_date } },
{ initial: %i[ ], set: %i[start_date], nilled: %i[due_date], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[due_date], nilled: %i[start_date], expected: { nilify: :duration } },
{ initial: %i[start_date ], set: %i[due_date], nilled: %i[start_date], expected: {} },
{ initial: %i[ due_date ], set: %i[due_date], nilled: %i[start_date], expected: {} },
{ initial: %i[ duration], set: %i[due_date], nilled: %i[start_date], expected: { nilify: :duration, same: :start_date } },
{ initial: %i[ ], set: %i[due_date], nilled: %i[start_date], expected: {} },
{ initial: %i[start_date due_date duration], nilled: %i[start_date due_date], expected: {} },
{ initial: %i[start_date ], nilled: %i[start_date due_date], expected: {} },
{ initial: %i[ due_date ], nilled: %i[start_date due_date], expected: {} },
{ initial: %i[ duration], nilled: %i[start_date due_date], expected: {} },
{ initial: %i[ ], nilled: %i[start_date due_date], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[start_date duration], expected: { change: :due_date } },
{ initial: %i[start_date ], set: %i[start_date duration], expected: { change: :due_date } },
{ initial: %i[ due_date ], set: %i[start_date duration], expected: { change: :due_date } },
{ initial: %i[ duration], set: %i[start_date duration], expected: { change: :due_date } },
{ initial: %i[ ], set: %i[start_date duration], expected: { change: :due_date } },
{ initial: %i[start_date due_date duration], set: %i[start_date], nilled: %i[duration], expected: { nilify: :due_date } },
{ initial: %i[start_date ], set: %i[start_date], nilled: %i[duration], expected: {} },
{ initial: %i[ due_date ], set: %i[start_date], nilled: %i[duration], expected: { nilify: :due_date, same: :duration } },
{ initial: %i[ duration], set: %i[start_date], nilled: %i[duration], expected: {} },
{ initial: %i[ ], set: %i[start_date], nilled: %i[duration], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[duration], nilled: %i[start_date], expected: { nilify: :due_date } },
{ initial: %i[start_date ], set: %i[duration], nilled: %i[start_date], expected: {} },
{ initial: %i[ due_date ], set: %i[duration], nilled: %i[start_date], expected: { nilify: :due_date, same: :start_date } },
{ initial: %i[ duration], set: %i[duration], nilled: %i[start_date], expected: {} },
{ initial: %i[ ], set: %i[duration], nilled: %i[start_date], expected: {} },
{ initial: %i[start_date due_date duration], nilled: %i[start_date duration], expected: {} },
{ initial: %i[start_date ], nilled: %i[start_date duration], expected: {} },
{ initial: %i[ due_date ], nilled: %i[start_date duration], expected: {} },
{ initial: %i[ duration], nilled: %i[start_date duration], expected: {} },
{ initial: %i[ ], nilled: %i[start_date duration], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[due_date duration], expected: { change: :start_date } },
{ initial: %i[start_date ], set: %i[due_date duration], expected: { change: :start_date } },
{ initial: %i[ due_date ], set: %i[due_date duration], expected: { change: :start_date } },
{ initial: %i[ duration], set: %i[due_date duration], expected: { change: :start_date } },
{ initial: %i[ ], set: %i[due_date duration], expected: { change: :start_date } },
{ initial: %i[start_date due_date duration], set: %i[due_date], nilled: %i[duration], expected: { nilify: :start_date } },
{ initial: %i[start_date ], set: %i[due_date], nilled: %i[duration], expected: { nilify: :start_date, same: :duration } },
{ initial: %i[ due_date ], set: %i[due_date], nilled: %i[duration], expected: {} },
{ initial: %i[ duration], set: %i[due_date], nilled: %i[duration], expected: {} },
{ initial: %i[ ], set: %i[due_date], nilled: %i[duration], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[duration], nilled: %i[due_date], expected: { nilify: :start_date } },
{ initial: %i[start_date ], set: %i[duration], nilled: %i[due_date], expected: { nilify: :start_date, same: :due_date } },
{ initial: %i[ due_date ], set: %i[duration], nilled: %i[due_date], expected: {} },
{ initial: %i[ duration], set: %i[duration], nilled: %i[due_date], expected: {} },
{ initial: %i[ ], set: %i[duration], nilled: %i[due_date], expected: {} },
{ initial: %i[start_date due_date duration], nilled: %i[due_date duration], expected: {} },
{ initial: %i[start_date ], nilled: %i[due_date duration], expected: {} },
{ initial: %i[ due_date ], nilled: %i[due_date duration], expected: {} },
{ initial: %i[ duration], nilled: %i[due_date duration], expected: {} },
{ initial: %i[ ], nilled: %i[due_date duration], expected: {} },
{ initial: %i[start_date due_date duration], set: %i[start_date due_date duration], expected: {} },
{ initial: %i[start_date ], set: %i[start_date due_date duration], expected: {} },
{ initial: %i[ due_date ], set: %i[start_date due_date duration], expected: {} },
{ initial: %i[ duration], set: %i[start_date due_date duration], expected: {} },
{ initial: %i[ ], set: %i[start_date due_date duration], expected: {} }
]
# rubocop:enable Layout/ExtraSpacing, Layout/SpaceInsideArrayPercentLiteral, Layout/SpaceInsidePercentLiteralDelimiters, Layout/LineLength
let(:initial_attributes) { { start_date: today, due_date: today + 49.days, duration: 50 } }
let(:set_attributes) { { start_date: today + 10.days, due_date: today + 12.days, duration: 3 } }
let(:nil_attributes) { { start_date: nil, due_date: nil, duration: nil } }
all_possible_scenarios.each do |scenario|
initial = scenario[:initial]
set = scenario[:set] || []
nilled = scenario[:nilled] || []
expected = scenario[:expected]
expected_change = expected[:change]
expected_same = expected[:same]
expected_nilify = expected[:nilify]
unchanged = %i[start_date due_date duration] - set - nilled - expected.values + [expected_same].compact
context_description = []
context_description << "with initial values for #{initial.inspect}" if initial.any?
context_description << "without any initial values" if initial.none?
context_description << "with #{set.inspect} set" if set.any?
context_description << "with #{nilled.inspect} nilled" if nilled.any?
context_description << "without any attributes set" if set.none? && nilled.none?
context context_description.join(", and ") do
let(:work_package_attributes) { nil_attributes.merge(initial_attributes.slice(*initial)) }
let(:work_package) { build_stubbed(:work_package, work_package_attributes) }
let(:call_attributes) { nil_attributes.slice(*nilled).merge(set_attributes.slice(*set)) }
it_behaves_like 'service call' do
if expected_change
it "changes #{expected_change.inspect}" do
expect { subject }
.to change(work_package, expected_change)
end
end
if expected_nilify
it "sets #{expected_nilify.inspect} to nil" do
expect { subject }
.to change(work_package, expected_nilify).to(nil)
end
end
if unchanged.any?
it "does not change #{unchanged.map(&:inspect).join(' and ')}" do
expect { subject }
.not_to change { work_package.slice(*unchanged) }
end
end
end
end
end
end
context 'with non-working days' do
shared_let(:working_days) { week_with_saturday_and_sunday_as_weekend }
let(:monday) { Time.zone.today.beginning_of_week }
let(:tuesday) { monday + 1.day }
let(:wednesday) { monday + 2.days }
let(:friday) { monday + 4.days }
let(:sunday) { monday + 6.days }
let(:next_monday) { monday + 7.days }
let(:next_tuesday) { monday + 8.days }
context 'when start date changes' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday)
end
let(:call_attributes) { { start_date: wednesday } }
it_behaves_like 'service call' do
it "updates the duration without including non-working days" do
expect { subject }
.to change(work_package, :duration)
.from(6)
.to(4)
end
end
end
context 'when due date changes' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday)
end
let(:call_attributes) { { due_date: monday + 14.days } }
it_behaves_like 'service call' do
it "updates the duration without including non-working days" do
expect { subject }
.to change(work_package, :duration)
.from(6)
.to(11)
end
end
end
context 'when duration changes' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday)
end
let(:call_attributes) { { duration: "13" } }
it_behaves_like 'service call' do
it "updates the due date from start date and duration and skips the non-working days" do
expect { subject }
.to change(work_package, :due_date)
.from(next_monday)
.to(monday + 16.days)
end
end
end
context 'when duration and end_date both change' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday)
end
let(:call_attributes) { { due_date: next_tuesday, duration: 4 } }
it_behaves_like 'service call' do
it "updates the start date and skips the non-working days" do
expect { subject }
.to change(work_package, :start_date)
.from(monday)
.to(monday.next_occurring(:thursday))
end
end
end
context 'when "ignore non-working days" is switched to true' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday, ignore_non_working_days: false)
end
let(:call_attributes) { { ignore_non_working_days: true } }
it_behaves_like 'service call' do
it "updates the due date from start date and duration to include the non-working days" do
# start_date and duration are checked too to ensure they did not change
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: monday, due_date: next_monday, duration: 6)
.to(start_date: monday, due_date: next_monday - 2.days, duration: 6)
end
end
end
context 'when "ignore non-working days" is switched to false' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday, ignore_non_working_days: true)
end
let(:call_attributes) { { ignore_non_working_days: false } }
it_behaves_like 'service call' do
it "updates the due date from start date and duration to skip the non-working days" do
# start_date and duration are checked too to ensure they did not change
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: monday, due_date: next_monday, duration: 8)
.to(start_date: monday, due_date: next_monday + 2.days, duration: 8)
end
end
end
context 'when "ignore non-working days" is switched to false and "start date" is on a non-working day' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday - 1.day, due_date: friday, ignore_non_working_days: true)
end
let(:call_attributes) { { ignore_non_working_days: false } }
it_behaves_like 'service call' do
it "updates the start date to be on next working day, and due date to accommodate duration" do
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: monday - 1.day, due_date: friday, duration: 6)
.to(start_date: monday, due_date: next_monday, duration: 6)
end
end
context 'with a new work package' do
let(:work_package) do
build(:work_package, start_date: monday - 1.day, due_date: friday, ignore_non_working_days: true)
end
let(:call_attributes) { { ignore_non_working_days: false, duration: 6 } }
it_behaves_like 'service call' do
it "updates the start date to be on next working day, and due date to accommodate duration" do
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: monday - 1.day, due_date: friday, duration: 6)
.to(start_date: monday, due_date: next_monday, duration: 6)
end
end
end
end
context 'when "ignore non-working days" is switched to false and "finish date" is on a non-working day' do
let(:work_package) do
build_stubbed(:work_package, start_date: nil, due_date: sunday, ignore_non_working_days: true)
end
let(:call_attributes) { { ignore_non_working_days: false } }
it_behaves_like 'service call' do
it "updates the finish date to be on next working day" do
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: nil, due_date: sunday, duration: nil)
.to(start_date: nil, due_date: next_monday, duration: nil)
end
end
end
context 'when "ignore non-working days" is changed AND "finish date" is cleared' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday, ignore_non_working_days: true)
end
let(:call_attributes) { { ignore_non_working_days: false, due_date: nil } }
it_behaves_like 'service call' do
it "does not recompute the due date and nilifies the due date and the duration instead" do
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: monday, due_date: next_monday, duration: 8)
.to(start_date: monday, due_date: nil, duration: nil)
end
end
end
context 'when "ignore non-working days" is changed AND "finish date" is set to another date' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday, ignore_non_working_days: true)
end
let(:call_attributes) { { due_date: wednesday, ignore_non_working_days: false } }
it_behaves_like 'service call' do
it "updates the start date from due date and duration to skip the non-working days" do
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: monday, due_date: next_monday, duration: 8)
.to(start_date: wednesday - 9.days, due_date: wednesday, duration: 8)
end
end
end
context 'when "ignore non-working days" is changed AND "start date" and "finish date" are set to other dates' do
let(:work_package) do
build_stubbed(:work_package, start_date: monday, due_date: next_monday, ignore_non_working_days: true)
end
let(:call_attributes) { { start_date: friday, due_date: next_tuesday, ignore_non_working_days: false } }
it_behaves_like 'service call' do
it "updates the duration from start date and due date" do
expect { subject }
.to change { work_package.slice(:start_date, :due_date, :duration) }
.from(start_date: monday, due_date: next_monday, duration: 8)
.to(start_date: friday, due_date: next_tuesday, duration: 3)
end
end
end
end
end
context 'for priority' do
let(:default_priority) { build_stubbed(:priority) }
let(:other_priority) { build_stubbed(:priority) }
before do
scope = class_double(IssuePriority)
allow(IssuePriority)
.to receive(:active)
.and_return(scope)
allow(scope)
.to receive(:default)
.and_return(default_priority)
end
context 'with no value set before for a new work package' do
let(:call_attributes) { {} }
let(:expected_attributes) { {} }
let(:work_package) { new_work_package }
before do
work_package.priority = nil
end
it_behaves_like 'service call' do
it "sets the default priority" do
subject
expect(work_package.priority)
.to eql default_priority
end
end
end
context 'when updating priority before calling the service' do
let(:call_attributes) { {} }
let(:expected_attributes) { { priority: other_priority } }
before do
work_package.attributes = expected_attributes
end
it_behaves_like 'service call'
end
context 'when updating priority via attributes' do
let(:call_attributes) { expected_attributes }
let(:expected_attributes) { { priority: other_priority } }
it_behaves_like 'service call'
end
end
context 'when switching the type' do
let(:target_type) { build_stubbed(:type, is_milestone:) }
let(:work_package) do
build_stubbed(:work_package, start_date: Time.zone.today - 6.days, due_date: Time.zone.today)
end
context 'to a non-milestone type' do
let(:is_milestone) { false }
it 'keeps the start date' do
instance.call(type: target_type)
expect(work_package.start_date)
.to eql Time.zone.today - 6.days
end
it 'keeps the due date' do
instance.call(type: target_type)
expect(work_package.due_date)
.to eql Time.zone.today
end
it 'keeps duration' do
instance.call(type: target_type)
expect(work_package.duration).to be 7
end
end
context 'to a milestone type' do
let(:is_milestone) { true }
context 'with both dates set' do
it 'sets the start date to the due date' do
instance.call(type: target_type)
expect(work_package.start_date).to eq work_package.due_date
end
it 'keeps the due date' do
instance.call(type: target_type)
expect(work_package.due_date).to eql Time.zone.today
end
it 'sets the duration to 1 (to be changed to 0 later on)' do
instance.call(type: target_type)
expect(work_package.duration).to eq 1
end
end
context 'with only the start date set' do
let(:work_package) do
build_stubbed(:work_package, start_date: Time.zone.today - 6.days)
end
it 'keeps the start date' do
instance.call(type: target_type)
expect(work_package.start_date).to eql Time.zone.today - 6.days
end
it 'set the due date to the start date' do
instance.call(type: target_type)
expect(work_package.due_date).to eql work_package.start_date
end
it 'keeps the duration at 1 (to be changed to 0 later on)' do
instance.call(type: target_type)
expect(work_package.duration).to eq 1
end
context 'with a new work package' do
let(:work_package) do
build(:work_package, start_date: Time.zone.today - 6.days)
end
let(:call_attributes) { { type: target_type, start_date: Time.zone.today - 6.days, due_date: nil, duration: nil } }
before do
instance.call(call_attributes)
end
it 'keeps the start date' do
expect(work_package.start_date).to eq Time.zone.today - 6.days
end
it 'set the due date to the start date' do
expect(work_package.due_date).to eq work_package.start_date
end
it 'keeps the duration at 1 (to be changed to 0 later on)' do
expect(work_package.duration).to eq 1
end
end
end
end
end
context 'when switching the project' do
let(:new_project) { build_stubbed(:project) }
let(:version) { build_stubbed(:version) }
let(:category) { build_stubbed(:category) }
let(:new_category) { build_stubbed(:category, name: category.name) }
let(:new_statuses) { [work_package.status] }
let(:new_versions) { [] }
let(:type) { work_package.type }
let(:new_types) { [type] }
let(:default_type) { build_stubbed(:type_standard) }
let(:other_type) { build_stubbed(:type) }
let(:yet_another_type) { build_stubbed(:type) }
let(:call_attributes) { {} }
let(:new_project_categories) do
instance_double(ActiveRecord::Relation).tap do |categories_stub|
allow(new_project)
.to receive(:categories)
.and_return(categories_stub)
end
end
before do
allow(new_project)
.to receive(:shared_versions)
.and_return(new_versions)
allow(new_project_categories)
.to receive(:find_by)
.with(name: category.name)
.and_return nil
allow(new_project)
.to receive(:types)
.and_return(new_types)
allow(new_types)
.to receive(:order)
.with(:position)
.and_return(new_types)
end
shared_examples_for 'updating the project' do
context 'for version' do
before do
work_package.version = version
end
context 'when not shared in new project' do
it 'sets to nil' do
subject
expect(work_package.version)
.to be_nil
end
end
context 'when shared in the new project' do
let(:new_versions) { [version] }
it 'keeps the version' do
subject
expect(work_package.version)
.to eql version
end
end
end
context 'for category' do
before do
work_package.category = category
end
context 'when no category of same name in new project' do
it 'sets to nil' do
subject
expect(work_package.category)
.to be_nil
end
end
context 'when category of same name in new project' do
before do
allow(new_project_categories)
.to receive(:find_by)
.with(name: category.name)
.and_return new_category
end
it 'uses the equally named category' do
subject
expect(work_package.category)
.to eql new_category
end
it 'adds change to system changes' do
subject
expect(work_package.changed_by_system['category_id'])
.to eql [nil, new_category.id]
end
end
end
context 'for type' do
context 'when current type exists in new project' do
it 'leaves the type' do
subject
expect(work_package.type)
.to eql type
end
end
context 'when a default type exists in new project' do
let(:new_types) { [other_type, default_type] }
it 'uses the first type (by position)' do
subject
expect(work_package.type)
.to eql other_type
end
it 'adds change to system changes' do
subject
expect(work_package.changed_by_system['type_id'])
.to eql [initial_type.id, other_type.id]
end
end
context 'when no default type exists in new project' do
let(:new_types) { [other_type, yet_another_type] }
it 'uses the first type (by position)' do
subject
expect(work_package.type)
.to eql other_type
end
it 'adds change to system changes' do
subject
expect(work_package.changed_by_system['type_id'])
.to eql [initial_type.id, other_type.id]
end
end
context 'when also setting a new type via attributes' do
let(:expected_attributes) { { project: new_project, type: yet_another_type } }
it 'sets the desired type' do
subject
expect(work_package.type)
.to eql yet_another_type
end
it 'does not set the change to system changes' do
subject
expect(work_package.changed_by_system)
.not_to include('type_id')
end
end
end
context 'for parent' do
let(:parent_work_package) { build_stubbed(:work_package, project:) }
let(:work_package) do
build_stubbed(:work_package, project:, type: initial_type, parent: parent_work_package)
end
context 'with cross project relations allowed', with_settings: { cross_project_work_package_relations: true } do
it 'keeps the parent' do
expect(subject)
.to be_success
expect(work_package.parent)
.to eql(parent_work_package)
end
end
context 'with cross project relations disabled', with_settings: { cross_project_work_package_relations: false } do
it 'deletes the parent' do
expect(subject)
.to be_success
expect(work_package.parent)
.to be_nil
end
end
end
end
context 'when updating project before calling the service' do
let(:call_attributes) { {} }
let(:expected_attributes) { { project: new_project } }
before do
work_package.attributes = expected_attributes
end
it_behaves_like 'service call' do
it_behaves_like 'updating the project'
end
end
context 'when updating project via attributes' do
let(:call_attributes) { expected_attributes }
let(:expected_attributes) { { project: new_project } }
it_behaves_like 'service call' do
it_behaves_like 'updating the project'
end
end
end
context 'for custom fields' do
subject { instance.call(call_attributes) }
context 'for non existing fields' do
let(:call_attributes) { { custom_field_891: '1' } } # rubocop:disable Naming/VariableNumber
before do
subject
end
it 'is successful' do
expect(subject).to be_success
end
end
end
context 'when switching back to automatic scheduling' do
let(:work_package) do
wp = build_stubbed(:work_package,
project:,
ignore_non_working_days: true,
schedule_manually: true,
start_date: Time.zone.today,
due_date: Time.zone.today + 5.days)
wp.type = build_stubbed(:type)
wp.send(:clear_changes_information)
allow(wp)
.to receive(:soonest_start)
.and_return(soonest_start)
wp
end
let(:call_attributes) { { schedule_manually: false } }
let(:expected_attributes) { {} }
let(:soonest_start) { Time.zone.today + 1.day }
context 'when the soonest start date is later than the current start date' do
let(:soonest_start) { Time.zone.today + 3.days }
it_behaves_like 'service call' do
it 'sets the start date to the soonest possible start date' do
subject
expect(work_package.start_date).to eql(Time.zone.today + 3.days)
expect(work_package.due_date).to eql(Time.zone.today + 8.days)
end
end
end
context 'when the soonest start date is a non-working day' do
shared_let(:working_days) { week_with_saturday_and_sunday_as_weekend }
let(:saturday) { Time.zone.today.beginning_of_week.next_occurring(:saturday) }
let(:next_monday) { saturday.next_occurring(:monday) }
let(:soonest_start) { saturday }
before do
work_package.ignore_non_working_days = false
end
it_behaves_like 'service call' do
it 'sets the start date to the soonest possible start date being a working day' do
subject
expect(work_package).to have_attributes(
start_date: next_monday,
due_date: next_monday + 7.days
)
end
end
end
context 'when the soonest start date is before the current start date' do
let(:soonest_start) { Time.zone.today - 3.days }
it_behaves_like 'service call' do
it 'sets the start date to the soonest possible start date' do
subject
expect(work_package.start_date).to eql(soonest_start)
expect(work_package.due_date).to eql(Time.zone.today + 2.days)
end
end
end
context 'when the soonest start date is nil' do
let(:soonest_start) { nil }
it_behaves_like 'service call' do
it 'sets the start date to the soonest possible start date' do
subject
expect(work_package.start_date).to eql(Time.zone.today)
expect(work_package.due_date).to eql(Time.zone.today + 5.days)
end
end
end
context 'when the work package also has a child' do
let(:child) do
build_stubbed(:work_package,
start_date: child_start_date,
due_date: child_due_date)
end
let(:child_start_date) { Time.zone.today + 2.days }
let(:child_due_date) { Time.zone.today + 10.days }
before do
allow(work_package)
.to receive(:children)
.and_return([child])
end
context 'when the child`s start date is after soonest_start' do
it_behaves_like 'service call' do
it 'sets the dates to the child dates' do
subject
expect(work_package.start_date).to eql(Time.zone.today + 2.days)
expect(work_package.due_date).to eql(Time.zone.today + 10.days)
end
end
end
context 'when the child`s start date is before soonest_start' do
let(:soonest_start) { Time.zone.today + 3.days }
it_behaves_like 'service call' do
it 'sets the dates to soonest date and to the duration of the child' do
subject
expect(work_package.start_date).to eql(Time.zone.today + 3.days)
expect(work_package.due_date).to eql(Time.zone.today + 11.days)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class WorkPackages::SetScheduleService
attr_accessor :user, :work_packages, :initiated_by
def initialize(user:, work_package:, initiated_by: nil)
self.user = user
self.work_packages = Array(work_package)
self.initiated_by = initiated_by
end
def call(changed_attributes = %i(start_date due_date))
altered = []
if %i(parent parent_id).intersect?(changed_attributes)
altered += schedule_by_parent
end
if %i(start_date due_date parent parent_id).intersect?(changed_attributes)
altered += schedule_following
end
result = ServiceResult.success(result: work_packages.first)
altered.each do |wp|
result.add_dependent!(ServiceResult.success(result: wp))
end
result
end
private
# rubocop:disable Metrics/AbcSize
def schedule_by_parent
work_packages
.select { |wp| wp.start_date.nil? && wp.parent }
.each do |wp|
days = WorkPackages::Shared::Days.for(wp)
wp.start_date = days.soonest_working_day(wp.parent.soonest_start)
if wp.due_date || wp.duration
wp.due_date = [
wp.start_date,
days.due_date(wp.start_date, wp.duration),
wp.due_date
].compact.max
assign_cause_for_journaling(wp, :parent)
end
end
end
# rubocop:enable Metrics/AbcSize
# Finds all work packages that need to be rescheduled because of a
# rescheduling of the service's work package and reschedules them.
#
# The order of the rescheduling is important as successors' dates are
# calculated based on their predecessors' dates and ancestors' dates based on
# their children's dates.
#
# Thus, the work packages following (having a follows relation, direct or
# transitively) the service's work package are first all loaded, and then
# sorted by their need to be scheduled before one another:
#
# - predecessors are scheduled before their successors
# - children/descendants are scheduled before their parents/ancestors
#
# Manually scheduled work packages are not encountered at this point as they
# are filtered out when fetching the work packages eligible for rescheduling.
def schedule_following
altered = []
WorkPackages::ScheduleDependency.new(work_packages).in_schedule_order do |scheduled, dependency|
reschedule(scheduled, dependency)
altered << scheduled if scheduled.changed?
end
altered
end
# Schedules work packages based on either
# - their descendants if they are parents
# - their predecessors (or predecessors of their ancestors) if they are
# leaves
def reschedule(scheduled, dependency)
if dependency.has_descendants?
reschedule_by_descendants(scheduled, dependency)
else
reschedule_by_predecessors(scheduled, dependency)
end
end
# Inherits the start/due_date from the descendants of this work package.
#
# Only parent work packages are scheduled like this. start_date receives the
# minimum of the dates (start_date and due_date) of the descendants due_date
# receives the maximum of the dates (start_date and due_date) of the
# descendants
def reschedule_by_descendants(scheduled, dependency)
set_dates(scheduled, dependency.start_date, dependency.due_date)
assign_cause_for_journaling(scheduled, :children)
end
# Calculates the dates of a work package based on its follows relations.
#
# The start date of a work package is constrained by its direct and indirect
# predecessors, as it must start strictly after all predecessors finish.
#
# The follows relations of ancestors are considered to be equal to own follows
# relations as they inhibit moving a work package just the same. Only leaf
# work packages are calculated like this.
#
# work package is moved to a later date:
# - following work packages are moved forward only to ensure they start
# after their predecessor's finish date. They may not need to move at all
# when there a time buffer between a follower and its predecessors
# (predecessors can also be acquired transitively by ancestors)
#
# work package moved to an earlier date:
# - following work packages do not move at all.
def reschedule_by_predecessors(scheduled, dependency)
return unless dependency.soonest_start_date
new_start_date = [scheduled.start_date, dependency.soonest_start_date].compact.max
new_due_date = determine_due_date(scheduled, new_start_date)
set_dates(scheduled, new_start_date, new_due_date)
assign_cause_for_journaling(scheduled, :predecessor)
end
def determine_due_date(work_package, start_date)
# due date is set only if the moving work package already has one or has a
# duration. If not, due date is nil (and duration will be nil too).
return unless work_package.due_date || work_package.duration
due_date =
if work_package.duration
days(work_package).due_date(start_date, work_package.duration)
else
work_package.due_date
end
# if due date is before start date, then start is used as due date.
[start_date, due_date].max
end
def set_dates(work_package, start_date, due_date)
work_package.start_date = start_date
work_package.due_date = due_date
work_package.duration = days(work_package).duration(start_date, due_date)
end
def days(work_package)
WorkPackages::Shared::Days.for(work_package)
end
def assign_cause_for_journaling(work_package, relation)
return {} if initiated_by.nil?
return {} unless work_package.changes.keys.intersect?(%w(start_date due_date duration))
if initiated_by.is_a?(WorkPackage)
assign_cause_initiated_by_work_package(work_package, relation)
elsif initiated_by.is_a?(Journal::WorkingDayUpdate)
assign_cause_initiated_by_changed_working_days(work_package)
end
end
def assign_cause_initiated_by_work_package(work_package, _relation)
# For now we only track a generic cause, and not a specialized reason depending on the relation
#
# type_mapping = {
# parent: 'work_package_parent_changed_times',
# children: 'work_package_children_changed_times',
# predecessor: 'work_package_predecessor_changed_times',
# related: 'work_package_related_changed_times'
# }
# work_package.journal_cause = { "type" => type_mapping[relation], "work_package_id" => initiated_by.id }
work_package.journal_cause = {
"type" => "work_package_related_changed_times",
"work_package_id" => initiated_by.id
}
end
def assign_cause_initiated_by_changed_working_days(work_package)
work_package.journal_cause = {
"type" => 'working_days_changed',
"changed_days" => initiated_by.to_h
}
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe WorkPackages::SetScheduleService do
create_shared_association_defaults_for_work_package_factory
let(:work_package) do
create(:work_package,
subject: 'subject',
start_date: work_package_start_date,
due_date: work_package_due_date)
end
let(:work_package_due_date) { Time.zone.today }
let(:work_package_start_date) { nil }
let(:initiating_work_package) { work_package }
let(:instance) do
described_class.new(user:, work_package:, initiated_by: initiating_work_package)
end
let!(:following) { [] }
let(:follower1_start_date) { Time.zone.today + 1.day }
let(:follower1_due_date) { Time.zone.today + 3.days }
let(:follower1_delay) { 0 }
let(:following_work_package1) do
create_follower(follower1_start_date,
follower1_due_date,
{ work_package => follower1_delay })
end
let(:follower2_start_date) { Time.zone.today + 4.days }
let(:follower2_due_date) { Time.zone.today + 8.days }
let(:follower2_delay) { 0 }
let(:following_work_package2) do
create_follower(follower2_start_date,
follower2_due_date,
{ following_work_package1 => follower2_delay })
end
let(:follower3_start_date) { Time.zone.today + 9.days }
let(:follower3_due_date) { Time.zone.today + 10.days }
let(:follower3_delay) { 0 }
let(:following_work_package3) do
create_follower(follower3_start_date,
follower3_due_date,
{ following_work_package2 => follower3_delay })
end
let(:parent_follower1_start_date) { follower1_start_date }
let(:parent_follower1_due_date) { follower1_due_date }
let(:parent_following_work_package1) do
create_parent(following_work_package1)
end
let(:follower_sibling_work_package) do
create_follower(follower1_due_date + 2.days,
follower1_due_date + 4.days,
{},
parent: parent_following_work_package1)
end
let(:attributes) { [:start_date] }
def create_follower(start_date, due_date, predecessors, parent: nil)
work_package = create(:work_package,
subject: "follower of #{predecessors.keys.map(&:subject).to_sentence}",
start_date:,
due_date:,
parent:)
predecessors.map do |predecessor, delay|
create(:follows_relation,
delay:,
from: work_package,
to: predecessor)
end
work_package
end
def create_parent(child, start_date: child.start_date, due_date: child.due_date)
create(:work_package,
subject: "parent of #{child.subject}",
start_date:,
due_date:).tap do |parent|
child.parent = parent
child.save
end
end
def create_child(parent, start_date, due_date)
create(:work_package,
subject: "child of #{parent.subject}",
start_date:,
due_date:,
parent:)
end
subject { instance.call(attributes) }
shared_examples_for 'reschedules' do
before do
subject
end
it 'is success' do
expect(subject)
.to be_success
end
it 'updates the following work packages' do
expected.each do |wp, (start_date, due_date)|
expected_cause_type = "work_package_related_changed_times"
result = subject.all_results.find { |result_wp| result_wp.id == wp.id }
expect(result)
.to be_present,
"Expected work package ##{wp.id} '#{wp.subject}' to be rescheduled"
expect(result.journal_cause['work_package_id'])
.to eql(initiating_work_package.id),
"Expected work package change to ##{wp.id} to have been caused by ##{initiating_work_package.id}."
expect(result.journal_cause['type'])
.to eql("work_package_related_changed_times"),
"Expected work package change to ##{wp.id} to have been caused because ##{expected_cause_type}."
expect(result.start_date)
.to eql(start_date),
"Expected work package ##{wp.id} '#{wp.subject}' " \
"to have start date #{start_date.inspect}, got #{result.start_date.inspect}"
expect(result.due_date)
.to eql(due_date),
"Expected work package ##{wp.id} '#{wp.subject}' " \
"to have due date #{due_date.inspect}, got #{result.due_date.inspect}"
duration = WorkPackages::Shared::AllDays.new.duration(start_date, due_date)
expect(result.duration)
.to eql(duration),
"Expected work package ##{wp.id} '#{wp.subject}' " \
"to have duration #{duration.inspect}, got #{result.duration.inspect}"
end
end
it 'returns only the original and the changed work packages' do
expect(subject.all_results)
.to match_array expected.keys + [work_package]
end
end
shared_examples_for 'does not reschedule' do
before do
subject
end
it 'is success' do
expect(subject)
.to be_success
end
it 'does not change any other work packages' do
expect(subject.all_results)
.to contain_exactly(work_package)
end
it 'does not assign a journal cause' do
subject.all_results.each do |work_package|
expect(work_package.journal_cause).to be_blank
end
end
end
context 'without relation' do
it 'is success' do
expect(subject)
.to be_success
end
end
context 'with a single successor' do
let!(:following) do
[following_work_package1]
end
context 'when moving forward' do
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days] }
end
end
end
context 'when moving forward with the follower having no due date' do
let(:follower1_due_date) { nil }
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, nil] }
end
end
end
context 'when moving forward with the follower having no start date' do
let(:follower1_start_date) { nil }
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 6.days] }
end
end
end
context 'when moving forward with the follower having some space left' do
let(:follower1_start_date) { Time.zone.today + 3.days }
let(:follower1_due_date) { Time.zone.today + 5.days }
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days] }
end
end
end
context 'when moving forward with the follower having enough space left to not be moved at all' do
let(:follower1_start_date) { Time.zone.today + 10.days }
let(:follower1_due_date) { Time.zone.today + 12.days }
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'does not reschedule'
end
context 'when moving forward with the follower having some space left and a delay' do
let(:follower1_start_date) { Time.zone.today + 5.days }
let(:follower1_due_date) { Time.zone.today + 7.days }
let(:follower1_delay) { 3 }
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 9.days, Time.zone.today + 11.days] }
end
end
end
context 'when moving forward with the follower not needing to be moved' do
let(:follower1_start_date) { Time.zone.today + 6.days }
let(:follower1_due_date) { Time.zone.today + 8.days }
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'does not reschedule'
end
context 'when moving backwards' do
before do
work_package.due_date = Time.zone.today - 5.days
end
it_behaves_like 'does not reschedule'
end
context 'when moving backwards with space between' do
let(:follower1_start_date) { Time.zone.today + 3.days }
let(:follower1_due_date) { Time.zone.today + 5.days }
before do
work_package.due_date = Time.zone.today - 5.days
end
it_behaves_like 'does not reschedule'
end
context 'when moving backwards with the follower having no start date (which should not happen) \
and the due date after the scheduled to date' do
let(:follower1_start_date) { nil }
before do
work_package.due_date = Time.zone.today - 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today - 4.days, follower1_due_date] }
end
end
end
context 'when moving forward with the follower having no start date (which should not happen) \
and the due date before the scheduled to date' do
let(:follower1_start_date) { nil }
before do
work_package.due_date = follower1_due_date + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [follower1_due_date + 6.days, follower1_due_date + 6.days] }
end
end
end
context 'when removing the dates on the predecessor' do
before do
work_package.start_date = work_package.due_date = nil
end
# The follower will keep its dates
it_behaves_like 'does not reschedule'
context 'when the follower has no start date but a due date' do
let(:follower1_start_date) { nil }
let(:follower1_due_date) { Time.zone.today + 15.days }
it_behaves_like 'does not reschedule'
end
end
context 'when not moving and the successor not having start & due date (e.g. creating relation)' do
let(:follower1_start_date) { nil }
let(:follower1_due_date) { nil }
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [work_package.due_date + 1.day, nil] }
end
end
end
context 'when not moving and the successor having due before predecessor due date (e.g. creating relation)' do
let(:follower1_start_date) { nil }
let(:follower1_due_date) { work_package_due_date - 5.days }
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [work_package.due_date + 1.day, work_package.due_date + 1.day] }
end
end
end
context 'when not moving and the successor having start before predecessor due date (e.g. creating relation)' do
let(:follower1_start_date) { work_package_due_date - 5.days }
let(:follower1_due_date) { nil }
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [work_package.due_date + 1.day, nil] }
end
end
end
context 'when not moving and the successor having start and due before predecessor due date (e.g. creating relation)' do
let(:follower1_start_date) { work_package_due_date - 5.days }
let(:follower1_due_date) { work_package_due_date - 2.days }
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [work_package.due_date + 1.day, work_package.due_date + 4.days] }
end
end
end
context 'when not having dates and the successor not having start & due date (e.g. creating relation)' do
let(:work_package_due_date) { nil }
let(:follower1_start_date) { nil }
let(:follower1_due_date) { nil }
it_behaves_like 'does not reschedule'
end
context 'with the successor having another predecessor which has no dates' do
let(:following_work_package1) do
create_follower(follower1_start_date,
follower1_due_date,
{ work_package => follower1_delay,
another_successor => 0 })
end
let(:another_successor) do
create(:work_package,
start_date: nil,
due_date: nil)
end
context 'when moving forward' do
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days] }
end
end
end
context 'when moving backwards' do
before do
work_package.due_date = Time.zone.today - 5.days
end
it_behaves_like 'does not reschedule'
end
end
end
context 'with only a parent' do
let!(:parent_work_package) do
create(:work_package).tap do |parent|
work_package.parent = parent
work_package.save
end
end
let(:work_package_start_date) { Time.zone.today - 5.days }
it_behaves_like 'reschedules' do
let(:expected) do
{ parent_work_package => [work_package_start_date, work_package_due_date] }
end
end
end
context 'with a parent having a follower' do
let(:work_package_start_date) { Time.zone.today }
let(:work_package_due_date) { Time.zone.today + 5.days }
let!(:parent_work_package) do
create(:work_package,
subject: "parent of #{work_package.subject}",
start_date: Time.zone.today,
due_date: Time.zone.today + 1.day).tap do |parent|
work_package.parent = parent
work_package.save
end
end
let!(:follower_of_parent_work_package) do
create_follower(Time.zone.today + 4.days,
Time.zone.today + 6.days,
{ parent_work_package => 0 })
end
it_behaves_like 'reschedules' do
let(:expected) do
{ parent_work_package => [work_package_start_date, work_package_due_date],
follower_of_parent_work_package => [work_package_due_date + 1.day, work_package_due_date + 3.days] }
end
end
# There is a bug in the scheduling that happens if the dependencies
# array order is: [sibling child, follower of parent, parent]
#
# In this case, as the follower of parent only knows about direct
# dependencies (and not about the transitive dependencies of children of
# predecessor), it will be made the first in the order, based on the
# current algorithm. And as the parent depends on its child, it will
# come after it.
#
# Based on the algorithm when this test was written, the resulting
# scheduling order will be [follower of parent, sibling child, parent],
# which is wrong: if follower of parent is rescheduled first, then it
# will not change because its predecessor, the parent, has not been
# scheduled yet.
#
# The expected and right order is [sibling child, parent, follower of
# parent].
#
# That's why the WorkPackage.for_scheduling call is mocked to customize
# the order of the returned work_packages to reproduce this bug.
context 'with also a sibling follower with same parent' do
let!(:sibling_follower_of_work_package) do
create_follower(Time.zone.today + 2.days,
Time.zone.today + 3.days,
{ work_package => 0 },
parent: parent_work_package)
end
before do
allow(WorkPackage)
.to receive(:for_scheduling)
.and_wrap_original do |method, *args|
wanted_order = [sibling_follower_of_work_package, follower_of_parent_work_package, parent_work_package]
method.call(*args).in_order_of(:id, wanted_order.map(&:id))
end
end
it_behaves_like 'reschedules' do
let(:expected) do
{ sibling_follower_of_work_package => [work_package_due_date + 1.day, work_package_due_date + 2.days],
parent_work_package => [work_package_start_date, work_package_due_date + 2.days],
follower_of_parent_work_package => [work_package_due_date + 3.days, work_package_due_date + 5.days] }
end
end
end
end
context 'with a single successor having a parent' do
let!(:following) do
[following_work_package1,
parent_following_work_package1]
end
context 'when moving forward' do
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days],
parent_following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days] }
end
end
end
context 'when moving forward with the parent having another child not being moved' do
let(:parent_follower1_start_date) { follower1_start_date }
let(:parent_follower1_due_date) { follower1_due_date + 4.days }
let!(:following) do
[following_work_package1,
parent_following_work_package1,
follower_sibling_work_package]
end
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days],
parent_following_work_package1 => [Time.zone.today + 5.days, Time.zone.today + 8.days] }
end
end
end
context 'when moving backwards' do
before do
work_package.due_date = Time.zone.today - 5.days
end
it_behaves_like 'does not reschedule'
end
end
context 'with a single successor having a child' do
let(:child_start_date) { follower1_start_date }
let(:child_due_date) { follower1_due_date }
let(:child_work_package) { create_child(following_work_package1, child_start_date, child_due_date) }
let!(:following) do
[following_work_package1,
child_work_package]
end
context 'when moving forward' do
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days],
child_work_package => [Time.zone.today + 6.days, Time.zone.today + 8.days] }
end
end
end
end
context 'with a single successor having two children' do
let(:follower1_start_date) { work_package_due_date + 1.day }
let(:follower1_due_date) { work_package_due_date + 10.days }
let(:child1_start_date) { follower1_start_date }
let(:child1_due_date) { follower1_start_date + 3.days }
let(:child2_start_date) { follower1_start_date + 8.days }
let(:child2_due_date) { follower1_due_date }
let(:child1_work_package) { create_child(following_work_package1, child1_start_date, child1_due_date) }
let(:child2_work_package) { create_child(following_work_package1, child2_start_date, child2_due_date) }
let!(:following) do
[following_work_package1,
child1_work_package,
child2_work_package]
end
context 'with unchanged dates (e.g. when creating a follows relation) and successor starting 1 day after scheduled' do
it_behaves_like 'does not reschedule'
end
context 'with unchanged dates (e.g. when creating a follows relation) and successor starting 3 days after scheduled' do
let(:follower1_start_date) { work_package_due_date + 3.days }
let(:follower1_due_date) { follower1_start_date + 10.days }
let(:child1_start_date) { follower1_start_date }
let(:child1_due_date) { follower1_start_date + 6.days }
let(:child2_start_date) { follower1_start_date + 8.days }
let(:child2_due_date) { follower1_due_date }
it_behaves_like 'does not reschedule'
end
context 'with unchanged dates (e.g. when creating a follows relation) and successor\'s first child needs to be rescheduled' do
let(:follower1_start_date) { work_package_due_date - 3.days }
let(:follower1_due_date) { work_package_due_date + 10.days }
let(:child1_start_date) { follower1_start_date }
let(:child1_due_date) { follower1_start_date + 6.days }
let(:child2_start_date) { follower1_start_date + 8.days }
let(:child2_due_date) { follower1_due_date }
# following parent is reduced in length as the children allow to be executed at the same time
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [work_package_due_date + 1.day, follower1_due_date],
child1_work_package => [work_package_due_date + 1.day, follower1_start_date + 10.days] }
end
end
end
context 'with unchanged dates (e.g. when creating a follows relation) and successor\s children need to be rescheduled' do
let(:follower1_start_date) { work_package_due_date - 8.days }
let(:follower1_due_date) { work_package_due_date + 10.days }
let(:child1_start_date) { follower1_start_date }
let(:child1_due_date) { follower1_start_date + 4.days }
let(:child2_start_date) { follower1_start_date + 6.days }
let(:child2_due_date) { follower1_due_date }
# following parent is reduced in length and children are rescheduled
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [work_package_due_date + 1.day, follower1_start_date + 21.days],
child1_work_package => [work_package_due_date + 1.day, child1_due_date + 9.days],
child2_work_package => [work_package_due_date + 1.day, follower1_start_date + 21.days] }
end
end
end
end
context 'with a chain of successors' do
let(:follower1_start_date) { Time.zone.today + 1.day }
let(:follower1_due_date) { Time.zone.today + 3.days }
let(:follower2_start_date) { Time.zone.today + 4.days }
let(:follower2_due_date) { Time.zone.today + 8.days }
let(:follower3_start_date) { Time.zone.today + 9.days }
let(:follower3_due_date) { Time.zone.today + 10.days }
let!(:following) do
[following_work_package1,
following_work_package2,
following_work_package3]
end
context 'when moving forward' do
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days],
following_work_package2 => [Time.zone.today + 9.days, Time.zone.today + 13.days],
following_work_package3 => [Time.zone.today + 14.days, Time.zone.today + 15.days] }
end
end
end
context 'when moving forward with some space between the followers' do
let(:follower1_start_date) { Time.zone.today + 1.day }
let(:follower1_due_date) { Time.zone.today + 3.days }
let(:follower2_start_date) { Time.zone.today + 7.days }
let(:follower2_due_date) { Time.zone.today + 10.days }
let(:follower3_start_date) { Time.zone.today + 17.days }
let(:follower3_due_date) { Time.zone.today + 18.days }
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days],
following_work_package2 => [Time.zone.today + 9.days, Time.zone.today + 12.days] }
end
end
end
context 'when moving backwards' do
before do
work_package.due_date = Time.zone.today - 5.days
end
it_behaves_like 'does not reschedule'
end
end
context 'with a chain of successors with two paths leading to the same work package in the end' do
let(:follower3_start_date) { Time.zone.today + 4.days }
let(:follower3_due_date) { Time.zone.today + 7.days }
let(:follower3_delay) { 0 }
let(:following_work_package3) do
create_follower(follower3_start_date,
follower3_due_date,
{ work_package => follower3_delay })
end
let(:follower4_start_date) { Time.zone.today + 9.days }
let(:follower4_due_date) { Time.zone.today + 10.days }
let(:follower4_delay2) { 0 }
let(:follower4_delay3) { 0 }
let(:following_work_package4) do
create_follower(follower4_start_date,
follower4_due_date,
{ following_work_package2 => follower4_delay2, following_work_package3 => follower4_delay3 })
end
let!(:following) do
[following_work_package1,
following_work_package2,
following_work_package3,
following_work_package4]
end
context 'when moving forward' do
before do
work_package.due_date = Time.zone.today + 5.days
end
it_behaves_like 'reschedules' do
let(:expected) do
{ following_work_package1 => [Time.zone.today + 6.days, Time.zone.today + 8.days],
following_work_package2 => [Time.zone.today + 9.days, Time.zone.today + 13.days],
following_work_package3 => [Time.zone.today + 6.days, Time.zone.today + 9.days],
following_work_package4 => [Time.zone.today + 14.days, Time.zone.today + 15.days] }
end
end
end
context 'when moving backwards' do
before do
work_package.due_date = Time.zone.today - 5.days
end
it_behaves_like 'does not reschedule'
end
end
context 'when setting the parent' do
let(:new_parent_work_package) { create(:work_package) }
let(:attributes) { [:parent] }
before do
allow(new_parent_work_package)
.to receive(:soonest_start)
.and_return(soonest_date)
allow(work_package)
.to receive(:parent)
.and_return(new_parent_work_package)
end
context "with the parent being restricted in its ability to be moved" do
let(:soonest_date) { Time.zone.today + 3.days }
it 'sets the start date and due date to the earliest possible date' do
subject
expect(work_package.start_date).to eql(Time.zone.today + 3.days)
expect(work_package.due_date).to eql(Time.zone.today + 3.days)
end
it 'does not change the due date if after the newly set start date' do
work_package.due_date = Time.zone.today + 5.days
subject
expect(work_package.start_date).to eql(Time.zone.today + 3.days)
expect(work_package.due_date).to eql(Time.zone.today + 5.days)
end
end
context 'with the parent being restricted but work package already having dates set' do
let(:soonest_date) { Time.zone.today + 3.days }
before do
work_package.start_date = Time.zone.today + 4.days
work_package.due_date = Time.zone.today + 5.days
end
it 'sets the dates to provided dates' do
subject
expect(work_package.start_date).to eql(Time.zone.today + 4.days)
expect(work_package.due_date).to eql(Time.zone.today + 5.days)
end
end
context 'with the parent being restricted but the attributes define an earlier date' do
let(:soonest_date) { Time.zone.today + 3.days }
before do
work_package.start_date = Time.zone.today + 1.day
work_package.due_date = Time.zone.today + 2.days
end
# This would be invalid but the dates should be set nevertheless
# so we can have a correct error handling.
it 'sets the dates to provided dates' do
subject
expect(work_package.start_date).to eql(Time.zone.today + 1.day)
expect(work_package.due_date).to eql(Time.zone.today + 2.days)
end
end
end
context 'with deep hierarchy of work packages' do
before do
work_package.due_date = Time.zone.today - 5.days
end
def create_hierarchy(parent, nb_children_by_levels)
nb_children, *remaining_levels = nb_children_by_levels
children = create_list(:work_package, nb_children, parent:)
if remaining_levels.any?
children.each do |child|
create_hierarchy(child, remaining_levels)
end
end
end
it 'does not fail with a SystemStackError (regression #43894)' do
parent = create(:work_package, start_date: Date.current, due_date: Date.current)
hierarchy = [1, 1, 1, 1, 2, 4, 4, 4]
create_hierarchy(parent, hierarchy)
# The bug triggers when moving work package is in the middle of the
# hierarchy
work_package.parent = parent.children.first.children.first.children.first
work_package.save
expect { instance.call(attributes) }
.not_to raise_error
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class WorkPackages::UpdateAncestorsService
attr_accessor :user,
:work_package
def initialize(user:, work_package:)
self.user = user
self.work_package = work_package
end
def call(attributes)
modified = update_current_and_former_ancestors(attributes)
set_journal_note(modified)
# Do not send notification for parent updates
success = Journal::NotificationConfiguration.with(false) do
modified.all? { |wp| wp.save(validate: false) }
end
result = ServiceResult.new(success:, result: work_package)
modified.each do |wp|
result.add_dependent!(ServiceResult.new(success: !wp.changed?, result: wp))
end
result
end
private
def update_current_and_former_ancestors(attributes)
WorkPackages::UpdateAncestors::Loader
.new(work_package, (%i(parent_id parent) & attributes).any?)
.select do |ancestor, loader|
inherit_attributes(ancestor, loader, attributes)
ancestor.changed?
end
end
def inherit_attributes(ancestor, loader, attributes)
return unless attributes_justify_inheritance?(attributes)
# Estimated hours need to be calculated before the done_ratio below.
# The aggregation only depends on estimated hours.
derive_estimated_hours(ancestor, loader) if inherit?(attributes, :estimated_hours)
# Progress (done_ratio or also: percentDone) depends on both
# the completion of sub-WPs, as well as the estimated hours
# as a weight factor. So changes in estimated hours also have
# to trigger a recalculation of done_ratio.
inherit_done_ratio(ancestor, loader) if inherit?(attributes, :done_ratio) || inherit?(attributes, :estimated_hours)
inherit_ignore_non_working_days(ancestor, loader) if inherit?(attributes, :ignore_non_working_days)
end
def inherit?(attributes, attribute)
([attribute, :parent, :parent_id] & attributes).any?
end
def set_journal_note(work_packages)
work_packages.each do |wp|
wp.journal_notes = I18n.t('work_package.updated_automatically_by_child_changes', child: "##{work_package.id}")
end
end
def inherit_done_ratio(ancestor, loader)
return if WorkPackage.done_ratio_disabled?
return if WorkPackage.use_status_for_done_ratio? && ancestor.status && ancestor.status.default_done_ratio
# done ratio = weighted average ratio of leaves
ancestor.done_ratio = (aggregate_done_ratio(ancestor, loader) || 0).round
end
# Sets the ignore_non_working_days to true if any ancestor has its value set to true.
# If there is no value returned from the descendants, that means that the work package in
# question no longer has a descendant. But since we are in the service going up the ancestor chain,
# such a work package is the former parent. The property of such a work package is reset to `false`.
def inherit_ignore_non_working_days(work_package, loader)
return if work_package.schedule_manually
descendant_value = ignore_non_working_days_of_descendants(work_package, loader)
if descendant_value.nil?
descendant_value = work_package.ignore_non_working_days
end
work_package.ignore_non_working_days = descendant_value
end
##
# done ratio = weighted average ratio of leaves
def aggregate_done_ratio(work_package, loader)
leaves = loader.leaves_of(work_package)
leaves_count = leaves.size
if leaves_count.positive?
average = average_estimated_hours(leaves)
progress = done_ratio_sum(leaves, average) / (average * leaves_count)
progress.round(2)
end
end
def average_estimated_hours(leaves)
# 0 and nil shall be considered the same for estimated hours
sum = all_estimated_hours(leaves).sum.to_f
count = all_estimated_hours(leaves).count
count = 1 if count.zero?
average = sum / count
average.zero? ? 1 : average
end
def done_ratio_sum(leaves, average_estimated_hours)
# Do not take into account estimated_hours when it is either nil or set to 0.0
summands = leaves.map do |leaf|
estimated_hours = if leaf.estimated_hours.to_f.positive?
leaf.estimated_hours
else
average_estimated_hours
end
done_ratio = if leaf.closed?
100
else
leaf.done_ratio || 0
end
estimated_hours * done_ratio
end
summands.sum
end
def derive_estimated_hours(work_package, loader)
descendants = loader.descendants_of(work_package)
work_package.derived_estimated_hours = not_zero(all_estimated_hours(descendants).sum.to_f)
end
def not_zero(value)
value unless value.zero?
end
def all_estimated_hours(work_packages)
work_packages
.map(&:estimated_hours)
.reject { |hours| hours.to_f.zero? }
end
def attributes_justify_inheritance?(attributes)
(%i(estimated_hours done_ratio parent parent_id status status_id ignore_non_working_days) & attributes).any?
end
def ignore_non_working_days_of_descendants(ancestor, loader)
children = loader
.children_of(ancestor)
.reject(&:schedule_manually)
if children.any?
children.any?(&:ignore_non_working_days)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe WorkPackages::UpdateAncestorsService, type: :model do
shared_association_default(:author, factory_name: :user) { create(:user) }
shared_association_default(:project_with_types) { create(:project_with_types) }
shared_association_default(:priority) { create(:priority) }
shared_association_default(:open_status, factory_name: :status) { create(:status) }
shared_let(:closed_status) { create(:closed_status) }
shared_let(:user) { create(:user) }
let(:estimated_hours) { [nil, nil, nil] }
let(:done_ratios) { [0, 0, 0] }
let(:statuses) { %i(open open open) }
let(:aggregate_done_ratio) { 0.0 }
let(:ignore_non_working_days) { [false, false, false] }
describe 'done_ratio/estimated_hours propagation' do
context 'for the new ancestor chain' do
shared_examples 'attributes of parent having children' do
before do
children
end
it 'updated one work package - the parent' do
expect(subject.dependent_results.map(&:result))
.to contain_exactly(parent)
end
it 'has the expected aggregate done ratio' do
expect(subject.dependent_results.first.result.done_ratio)
.to eq aggregate_done_ratio
end
it 'has the expected derived estimated_hours' do
expect(subject.dependent_results.first.result.derived_estimated_hours)
.to eq aggregate_estimated_hours
end
it 'is a success' do
expect(subject)
.to be_success
end
end
let(:children) do
(statuses.size - 1).downto(0).map do |i|
create(:work_package,
parent:,
status: statuses[i] == :open ? open_status : closed_status,
estimated_hours: estimated_hours[i],
done_ratio: done_ratios[i],
ignore_non_working_days:)
end
end
shared_let(:parent) { create(:work_package, status: open_status) }
subject do
# In the call we only use estimated_hours (instead of also adding
# done_ratio) in order to test that changes in estimated hours
# trigger a recalculation of done_ration, because estimated hours
# act as weights in this calculation.
described_class
.new(user:,
work_package: children.first)
.call(%i(estimated_hours))
end
context 'with no estimated hours and no progress' do
let(:statuses) { %i(open open open) }
it 'is a success' do
expect(subject)
.to be_success
end
it 'does not update the parent' do
expect(subject.dependent_results)
.to be_empty
end
end
context 'with 1 out of 3 tasks having estimated hours and 2 out of 3 tasks done' do
let(:statuses) do
%i(open closed closed)
end
it_behaves_like 'attributes of parent having children' do
let(:estimated_hours) do
[0.0, 2.0, 0.0]
end
# 66.67 rounded - previous wrong result: 133
let(:aggregate_done_ratio) do
67
end
let(:aggregate_estimated_hours) do
2.0
end
end
context 'with mixed nil and 0 values for estimated hours' do
it_behaves_like 'attributes of parent having children' do
let(:estimated_hours) do
[nil, 2.0, 0.0]
end
# 66.67 rounded - previous wrong result: 100
let(:aggregate_done_ratio) do
67
end
let(:aggregate_estimated_hours) do
2.0
end
end
end
end
context 'with some values same for done ratio' do
it_behaves_like 'attributes of parent having children' do
let(:done_ratios) { [20, 20, 50] }
let(:estimated_hours) { [nil, nil, nil] }
let(:aggregate_done_ratio) { 30 }
let(:aggregate_estimated_hours) { nil }
end
end
context 'with no estimated hours and 1.5 of the tasks done' do
it_behaves_like 'attributes of parent having children' do
let(:done_ratios) { [0, 50, 100] }
let(:aggregate_done_ratio) { 50 }
let(:aggregate_estimated_hours) { nil }
end
end
context 'with estimated hours being 1, 2 and 5' do
let(:estimated_hours) { [1, 2, 5] }
context 'with the last 2 tasks at 100% progress' do
it_behaves_like 'attributes of parent having children' do
let(:done_ratios) { [0, 100, 100] }
# (2 + 5 = 7) / 8 estimated hours done
let(:aggregate_done_ratio) { 88 } # 87.5 rounded
let(:aggregate_estimated_hours) { estimated_hours.sum }
end
end
context 'with the last 2 tasks closed (therefore at 100%)' do
it_behaves_like 'attributes of parent having children' do
let(:statuses) { %i(open closed closed) }
# (2 + 5 = 7) / 8 estimated hours done
let(:aggregate_done_ratio) { 88 } # 87.5 rounded
let(:aggregate_estimated_hours) { estimated_hours.sum }
end
end
context 'with mixed done ratios, statuses' do
it_behaves_like 'attributes of parent having children' do
let(:done_ratios) { [50, 75, 42] }
let(:statuses) { %i(open open closed) }
# 50% 75% 100% (42 ignored)
# (0.5 * 1 + 0.75 * 2 + 1 * 5 [since closed] = 7)
# (0.5 + 1.5 + 5 = 7) / 8 estimated hours done
let(:aggregate_done_ratio) { 88 } # 87.5 rounded
let(:aggregate_estimated_hours) { estimated_hours.sum }
end
end
end
context 'with everything playing together' do
it_behaves_like 'attributes of parent having children' do
let(:statuses) { %i(open open closed open) }
let(:done_ratios) { [0, 0, 0, 50] }
let(:estimated_hours) { [0.0, 3.0, nil, 7.0] }
# (0 * 5 + 0 * 3 + 1 * 5 + 0.5 * 7 = 8.5) / 20 est. hours done
let(:aggregate_done_ratio) { 43 } # 42.5 rounded
let(:aggregate_estimated_hours) { 10.0 }
end
end
end
context 'for the previous ancestors' do
shared_let(:sibling_status) { open_status }
shared_let(:sibling_done_ratio) { 50 }
shared_let(:sibling_estimated_hours) { 7.0 }
shared_let(:grandparent) do
create(:work_package)
end
shared_let(:parent) do
create(:work_package,
parent: grandparent)
end
shared_let(:sibling) do
create(:work_package,
parent:,
status: sibling_status,
estimated_hours: sibling_estimated_hours,
done_ratio: sibling_done_ratio)
end
shared_let(:work_package) do
create(:work_package,
parent:)
end
subject do
work_package.parent = nil
work_package.save!
described_class
.new(user:,
work_package:)
.call(%i(parent))
end
before do
subject
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the former ancestors in the dependent results' do
expect(subject.dependent_results.map(&:result))
.to contain_exactly(parent, grandparent)
end
it 'updates the done_ratio of the former parent' do
expect(parent.reload(select: :done_ratio).done_ratio)
.to eql sibling_done_ratio
end
it 'updates the estimated_hours of the former parent' do
expect(parent.reload(select: :derived_estimated_hours).derived_estimated_hours)
.to eql sibling_estimated_hours
end
it 'updates the done_ratio of the former grandparent' do
expect(grandparent.reload(select: :done_ratio).done_ratio)
.to eql sibling_done_ratio
end
it 'updates the estimated_hours of the former grandparent' do
expect(grandparent.reload(select: :derived_estimated_hours).derived_estimated_hours)
.to eql sibling_estimated_hours
end
end
context 'for new ancestors' do
shared_let(:status) { open_status }
shared_let(:done_ratio) { 50 }
shared_let(:estimated_hours) { 7.0 }
shared_let(:grandparent) do
create(:work_package)
end
shared_let(:parent) do
create(:work_package,
parent: grandparent)
end
shared_let(:work_package) do
create(:work_package,
status:,
estimated_hours:,
done_ratio:)
end
shared_examples_for 'updates the attributes within the new hierarchy' do
before do
subject
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the new ancestors in the dependent results' do
expect(subject.dependent_results.map(&:result))
.to contain_exactly(parent, grandparent)
end
it 'updates the done_ratio of the new parent' do
expect(parent.reload(select: :done_ratio).done_ratio)
.to eql done_ratio
end
it 'updates the estimated_hours of the new parent' do
expect(parent.reload(select: :derived_estimated_hours).derived_estimated_hours)
.to eql estimated_hours
end
it 'updates the done_ratio of the new grandparent' do
expect(grandparent.reload(select: :done_ratio).done_ratio)
.to eql done_ratio
end
it 'updates the estimated_hours of the new grandparent' do
expect(grandparent.reload(select: :derived_estimated_hours).derived_estimated_hours)
.to eql estimated_hours
end
end
context 'if setting the parent' do
subject do
work_package.parent = parent
work_package.save!
work_package.parent_id_was
described_class
.new(user:,
work_package:)
.call(%i(parent))
end
it_behaves_like 'updates the attributes within the new hierarchy'
end
context 'if setting the parent_id' do
subject do
work_package.parent_id = parent.id
work_package.save!
work_package.parent_id_was
described_class
.new(user:,
work_package:)
.call(%i(parent_id))
end
it_behaves_like 'updates the attributes within the new hierarchy'
end
end
context 'with old and new parent having a common ancestor' do
shared_let(:status) { open_status }
shared_let(:done_ratio) { 50 }
shared_let(:estimated_hours) { 7.0 }
shared_let(:grandparent) do
create(:work_package,
derived_estimated_hours: estimated_hours,
done_ratio:)
end
shared_let(:old_parent) do
create(:work_package,
parent: grandparent,
derived_estimated_hours: estimated_hours,
done_ratio:)
end
shared_let(:new_parent) do
create(:work_package,
parent: grandparent)
end
shared_let(:work_package) do
create(:work_package,
parent: old_parent,
status:,
estimated_hours:,
done_ratio:)
end
subject do
work_package.parent = new_parent
# In this test case, derived_estimated_hours and done_ratio will not
# inherently change on grandparent. However, if work_package has siblings
# then changing its parent could cause derived_estimated_hours and/or
# done_ratio on grandparent to inherently change. To verify that
# grandparent can be properly updated in that case without making this
# test dependent on the implementation details of the
# derived_estimated_hours and done_ratio calculations, force
# derived_estimated_hours and done_ratio to change at the same time as the
# parent.
work_package.estimated_hours = (estimated_hours + 1)
work_package.done_ratio = (done_ratio + 1)
work_package.save!
described_class
.new(user:,
work_package:)
.call(%i(parent))
end
before do
subject
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns both the former and new ancestors in the dependent results without duplicates' do
expect(subject.dependent_results.map(&:result))
.to contain_exactly(new_parent, grandparent, old_parent)
end
it 'updates the done_ratio of the former parent' do
expect(old_parent.reload(select: :done_ratio).done_ratio)
.to be 0
end
it 'updates the estimated_hours of the former parent' do
expect(old_parent.reload(select: :derived_estimated_hours).derived_estimated_hours)
.to be_nil
end
end
end
describe 'ignore_non_working_days propagation' do
shared_let(:grandgrandparent) do
create(:work_package,
subject: 'grandgrandparent')
end
shared_let(:grandparent) do
create(:work_package,
subject: 'grandparent',
parent: grandgrandparent)
end
shared_let(:parent) do
create(:work_package,
subject: 'parent',
parent: grandparent)
end
shared_let(:sibling) do
create(:work_package,
subject: 'sibling',
parent:)
end
shared_let(:work_package) do
create(:work_package)
end
subject do
work_package.parent = new_parent
work_package.save!
described_class
.new(user:,
work_package:)
.call(%i(parent))
end
let(:new_parent) { parent }
context 'for the previous ancestors (parent removed)' do
let(:new_parent) { nil }
before do
work_package.parent = parent
work_package.save
[grandgrandparent, grandparent, parent, work_package].each do |wp|
wp.update_column(:ignore_non_working_days, true)
end
[sibling].each do |wp|
wp.update_column(:ignore_non_working_days, false)
end
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the former ancestors in the dependent results' do
expect(subject.dependent_results.map(&:result))
.to contain_exactly(parent, grandparent, grandgrandparent)
end
it 'sets the ignore_non_working_days property of the former ancestor chain to the value of the
only remaining child (former sibling)' do
subject
expect(parent.reload.ignore_non_working_days)
.to be_falsey
expect(grandparent.reload.ignore_non_working_days)
.to be_falsey
expect(grandgrandparent.reload.ignore_non_working_days)
.to be_falsey
expect(sibling.reload.ignore_non_working_days)
.to be_falsey
end
end
context 'for the new ancestors where the grandparent is on manual scheduling' do
before do
[grandgrandparent, work_package].each do |wp|
wp.update_column(:ignore_non_working_days, true)
end
[grandparent, parent, sibling].each do |wp|
wp.update_column(:ignore_non_working_days, false)
end
[grandparent].each do |wp|
wp.update_column(:schedule_manually, true)
end
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the former ancestors in the dependent results' do
expect(subject.dependent_results.map(&:result))
.to contain_exactly(parent)
end
it 'sets the ignore_non_working_days property of the new ancestors' do
subject
expect(parent.reload.ignore_non_working_days)
.to be_truthy
expect(grandparent.reload.ignore_non_working_days)
.to be_falsey
expect(grandgrandparent.reload.ignore_non_working_days)
.to be_truthy
expect(sibling.reload.ignore_non_working_days)
.to be_falsey
end
end
context 'for the new ancestors where the parent is on manual scheduling' do
before do
[grandgrandparent, grandparent, work_package].each do |wp|
wp.update_column(:ignore_non_working_days, true)
end
[parent, sibling].each do |wp|
wp.update_column(:ignore_non_working_days, false)
end
[parent].each do |wp|
wp.update_column(:schedule_manually, true)
end
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the former ancestors in the dependent results' do
expect(subject.dependent_results.map(&:result))
.to be_empty
end
it 'sets the ignore_non_working_days property of the new ancestors' do
subject
expect(parent.reload.ignore_non_working_days)
.to be_falsey
expect(grandparent.reload.ignore_non_working_days)
.to be_truthy
expect(grandgrandparent.reload.ignore_non_working_days)
.to be_truthy
expect(sibling.reload.ignore_non_working_days)
.to be_falsey
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class WorkPackages::UpdateService < BaseServices::Update
include ::WorkPackages::Shared::UpdateAncestors
include Attachments::ReplaceAttachments
attr_accessor :cause_of_update
def initialize(user:, model:, contract_class: nil, contract_options: {}, cause_of_update: nil)
super(user:, model:, contract_class:, contract_options:)
self.cause_of_update = cause_of_update || model
end
private
def after_perform(service_call)
update_related_work_packages(service_call)
cleanup(service_call.result)
service_call
end
def update_related_work_packages(service_call)
update_ancestors([service_call.result]).each do |ancestor_service_call|
ancestor_service_call.dependent_results.each do |ancestor_dependent_service_call|
service_call.add_dependent!(ancestor_dependent_service_call)
end
end
update_related(service_call.result).each do |related_service_call|
service_call.add_dependent!(related_service_call)
end
end
def update_related(work_package)
consolidated_calls(update_descendants(work_package) + reschedule_related(work_package))
.each { |dependent_call| dependent_call.result.save(validate: false) }
end
def update_descendants(work_package)
if work_package.saved_change_to_project_id?
attributes = { project: work_package.project }
work_package.descendants.map do |descendant|
set_descendant_attributes(attributes, descendant)
end
else
[]
end
end
def set_descendant_attributes(attributes, descendant)
WorkPackages::SetAttributesService
.new(user:,
model: descendant,
contract_class: WorkPackages::UpdateDependentContract)
.call(attributes)
end
def cleanup(work_package)
if work_package.saved_change_to_project_id?
moved_work_packages = [work_package] + work_package.descendants
delete_relations(moved_work_packages)
move_time_entries(moved_work_packages, work_package.project_id)
move_work_package_memberships(moved_work_packages, work_package.project_id)
end
if work_package.saved_change_to_type_id?
reset_custom_values(work_package)
end
end
def delete_relations(work_packages)
unless Setting.cross_project_work_package_relations?
Relation
.of_work_package(work_packages)
.destroy_all
end
end
def move_time_entries(work_packages, project_id)
TimeEntry
.on_work_packages(work_packages)
.update_all(project_id:)
end
def move_work_package_memberships(work_packages, project_id)
Member
.where(entity: work_packages)
.update_all(project_id:)
end
def reset_custom_values(work_package)
work_package.reset_custom_values!
end
def reschedule_related(work_package)
rescheduled = if work_package.saved_change_to_parent_id? && work_package.parent_id_before_last_save
reschedule_former_siblings(work_package).dependent_results
else
[]
end
rescheduled + reschedule(work_package, [work_package]).dependent_results
end
def reschedule_former_siblings(work_package)
reschedule(work_package, WorkPackage.where(parent_id: work_package.parent_id_before_last_save))
end
def reschedule(work_package, work_packages)
WorkPackages::SetScheduleService
.new(user:, work_package: work_packages, initiated_by: cause_of_update)
.call(work_package.saved_changes.keys.map(&:to_sym))
end
# When multiple services change a work package, we still only want one update to the database due to:
# * performance
# * having only one journal entry
# * stale object errors
# we thus consolidate the results so that one instance contains the changes made by all the services.
def consolidated_calls(service_calls)
service_calls
.group_by { |sc| sc.result.id }
.map do |(_, same_work_package_calls)|
same_work_package_calls.pop.tap do |master|
same_work_package_calls.each do |sc|
master.result.attributes = sc.result.changes.transform_values(&:last)
end
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe WorkPackages::UpdateService, type: :model do
# This is now only a very basic test testing the structure of the service.
# The domain tests are in the update_service_integration_spec.rb
it_behaves_like 'BaseServices update service' do
before do
allow(set_attributes_errors)
.to receive(:merge!)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class WorkPackages::DeleteService < BaseServices::Delete
include ::WorkPackages::Shared::UpdateAncestors
private
def persist(service_result)
descendants = model.descendants.to_a
result = super
if result.success?
update_ancestors_all_attributes(result.all_results).each do |ancestor_result|
result.merge!(ancestor_result)
end
destroy_descendants(descendants, result)
delete_associated(model)
end
result
end
def destroy(work_package)
work_package.destroy
rescue ActiveRecord::StaleObjectError
destroy(work_package.reload)
end
def destroy_descendants(descendants, result)
descendants.each do |descendant|
result.add_dependent!(ServiceResult.new(success: destroy(descendant), result: descendant))
end
end
def delete_associated(model)
delete_notifications_resource(model.id)
end
def delete_notifications_resource(id)
Notification
.where(resource_type: :WorkPackage, resource_id: id)
.delete_all
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe WorkPackages::DeleteService do
let(:user) do
build_stubbed(:user)
end
let(:work_package) do
build_stubbed(:work_package, type: build_stubbed(:type))
end
let(:instance) do
described_class
.new(user:,
model: work_package)
end
let(:destroyed_result) { true }
let(:destroy_allowed) { true }
subject { instance.call }
before do
allow(work_package).to receive(:reload).and_return(work_package)
expect(work_package).to receive(:destroy).and_return(destroyed_result)
allow(work_package).to receive(:destroyed?).and_return(destroyed_result)
mock_permissions_for(user) do |mock|
mock.allow_in_project :delete_work_packages, project: work_package.project
end
end
it 'destroys the work package' do
subject
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'returns the destroyed work package' do
expect(subject.result)
.to eql work_package
end
it 'returns an empty errors array' do
expect(subject.errors)
.to be_empty
end
context 'when the work package could not be destroyed' do
let(:destroyed_result) { false }
it 'is no success' do
expect(subject)
.not_to be_success
end
end
context 'with ancestors' do
let(:parent) do
build_stubbed(:work_package)
end
let(:grandparent) do
build_stubbed(:work_package)
end
let(:expect_inherited_attributes_service_calls) do
inherited_service_instance = double(WorkPackages::UpdateAncestorsService)
service_result = ServiceResult.success(result: work_package)
service_result.dependent_results += [ServiceResult.success(result: parent),
ServiceResult.success(result: grandparent)]
expect(WorkPackages::UpdateAncestorsService)
.to receive(:new)
.with(user:,
work_package:)
.and_return(inherited_service_instance)
expect(inherited_service_instance)
.to receive(:call)
.with(work_package.attributes.keys.map(&:to_sym))
.and_return(service_result)
end
let(:expect_no_inherited_attributes_service_calls) do
expect(WorkPackages::UpdateAncestorsService)
.not_to receive(:new)
end
it 'calls the inherit attributes service for each ancestor' do
expect_inherited_attributes_service_calls
subject
end
context 'when the work package could not be destroyed' do
let(:destroyed_result) { false }
it 'does not call inherited attributes service' do
expect_no_inherited_attributes_service_calls
subject
end
end
end
context 'with descendants' do
let(:child) do
build_stubbed(:work_package)
end
let(:grandchild) do
build_stubbed(:work_package)
end
let(:descendants) do
[child, grandchild]
end
before do
allow(work_package)
.to receive(:descendants)
.and_return(descendants)
descendants.each do |descendant|
allow(descendant)
.to receive(:destroy)
end
end
it 'destroys the descendants' do
descendants.each do |descendant|
expect(descendant)
.to receive(:destroy)
end
subject
end
it 'returns the descendants as part of the result' do
subject
expect(subject.all_results)
.to match_array [work_package] + descendants
end
context 'if the work package could not be destroyed' do
let(:destroyed_result) { false }
it 'does not destroy the descendants' do
descendants.each do |descendant|
expect(descendant)
.not_to receive(:destroy)
end
subject
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class WorkPackages::ScheduleDependency::Dependency
def initialize(work_package, schedule_dependency)
self.work_package = work_package
self.schedule_dependency = schedule_dependency
end
attr_accessor :work_package,
:schedule_dependency
# Returns the work package ids that this work package directly depends on to
# determine its own dates. This is used for the order of the dates
# computations.
#
# The dates of a work package depend on its descendants and predecessors
# dates.
def dependent_ids
@dependent_ids ||= (descendants + moving_predecessors).map(&:id).uniq
end
def moving_predecessors
@moving_predecessors ||= follows_relations
.map(&:to)
.filter { |predecessor| schedule_dependency.moving?(predecessor) }
end
def soonest_start_date
@soonest_start_date ||=
follows_relations
.filter_map(&:successor_soonest_start)
.max
end
def start_date
descendants_dates.min
end
def due_date
descendants_dates.max
end
def has_descendants?
descendants.any?
end
private
def descendants
schedule_dependency.descendants(work_package)
end
def follows_relations
schedule_dependency.follows_relations(work_package)
end
def descendants_dates
descendants.filter_map(&:due_date) + descendants.filter_map(&:start_date)
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'rails_helper'
# Scenario: a work package has been moved on the calendar. The moved work
# package has children, parents, followers, and/or predecessors. The
# +ScheduleDependency+ created for the moved work package will have one
# +Dependency+ instance per work package that may need to change due to the
# move. These dependencies are the subjects under test.
RSpec.describe WorkPackages::ScheduleDependency::Dependency do
subject(:dependency) { dependency_for(work_package_used_in_dependency) }
create_shared_association_defaults_for_work_package_factory
shared_let(:work_package) { create(:work_package, subject: 'moved') }
let(:schedule_dependency) { WorkPackages::ScheduleDependency.new(work_package) }
def dependency_for(work_package)
dependency = schedule_dependency.dependencies[work_package]
if dependency.nil?
available = schedule_dependency.dependencies.keys.map(&:subject).map(&:inspect).to_sentence
raise ArgumentError, "Unable to find dependency for work package #{work_package.subject.inspect}; " \
"ScheduleDependency instance has dependencies for work packages #{available}"
end
dependency
end
def create_predecessor_of(work_package, **attributes)
create(:work_package, subject: "predecessor of #{work_package.subject}", **attributes).tap do |predecessor|
create(:follows_relation, from: work_package, to: predecessor)
end
end
def create_follower_of(work_package, **attributes)
create(:work_package, subject: "follower of #{work_package.subject}", **attributes).tap do |follower|
create(:follows_relation, from: follower, to: work_package)
end
end
def create_parent_of(work_package)
create(:work_package, subject: "parent of #{work_package.subject}").tap do |parent|
work_package.update(parent:)
end
end
def create_child_of(work_package)
create(:work_package, subject: "child of #{work_package.subject}", parent: work_package)
end
describe '#dependent_ids' do
context 'when the work_package has a follower' do
let!(:follower) { create_follower_of(work_package) }
context 'for dependency of the follower' do
let(:work_package_used_in_dependency) { follower }
it 'returns an array with the work package id' do
expect(subject.dependent_ids).to eq([work_package.id])
end
end
end
context 'when the work_package has a parent' do
let!(:parent) { create_parent_of(work_package) }
context 'for dependency of the parent' do
let(:work_package_used_in_dependency) { parent }
it 'returns an array with the work package id' do
expect(subject.dependent_ids).to eq([work_package.id])
end
end
end
context 'when the work_package has a follower which has a child' do
let!(:follower) { create_follower_of(work_package) }
let!(:follower_child) { create_child_of(follower) }
context 'for dependency of the child' do
let(:work_package_used_in_dependency) { follower_child }
it 'returns an array with the work_package id' do
expect(subject.dependent_ids).to eq([work_package.id])
end
end
context 'for dependency of the follower' do
let(:work_package_used_in_dependency) { follower }
it 'returns an array with the work_package id and the follower child id' do
expect(subject.dependent_ids).to contain_exactly(work_package.id, follower_child.id)
end
end
end
context 'when the work_package has multiple parents and followers' do
let!(:first_follower) { create_follower_of(work_package) }
let!(:second_follower) { create_follower_of(work_package) }
let!(:first_follower_parent) { create_parent_of(first_follower) }
let!(:first_follower_grandparent) { create_parent_of(first_follower_parent) }
context 'for dependency of the first follower parent' do
let(:work_package_used_in_dependency) { first_follower_parent }
it 'returns an array with the work_package and the first follower ids' do
expect(subject.dependent_ids).to contain_exactly(work_package.id, first_follower.id)
end
end
context 'for dependency of the first follower grandparent' do
let(:work_package_used_in_dependency) { first_follower_grandparent }
it 'returns an array with the work_package, the first follower, and the first follower parent ids' do
expect(subject.dependent_ids).to contain_exactly(work_package.id, first_follower.id, first_follower_parent.id)
end
end
context 'for dependency of the second follower' do
let(:work_package_used_in_dependency) { second_follower }
it 'returns an array with the work_package id' do
expect(subject.dependent_ids).to contain_exactly(work_package.id)
end
end
end
context 'with more complex relations' do
context 'when has two consecutive followers' do
let!(:follower) { create_follower_of(work_package) }
let!(:follower_follower) { create_follower_of(follower) }
context 'for dependency of the first follower' do
let(:work_package_used_in_dependency) { follower }
it 'returns an array with the work_package id' do
expect(subject.dependent_ids).to contain_exactly(work_package.id)
end
end
context 'for dependency of the second follower' do
let(:work_package_used_in_dependency) { follower_follower }
it 'returns an array with only the first follower id' do
expect(subject.dependent_ids).to contain_exactly(follower.id)
end
end
end
context 'when has a follower which has a predecessor' do
let!(:follower) { create_follower_of(work_package) }
let!(:follower_predecessor) { create_predecessor_of(follower) }
context 'for dependency of the follower' do
let(:work_package_used_in_dependency) { follower }
it 'returns an array with the work_package id' do
expect(subject.dependent_ids).to contain_exactly(work_package.id)
end
end
end
context 'when has a predecessor which has a parent and a child' do
let!(:follower) { create_follower_of(work_package) }
let!(:follower_parent) { create_parent_of(follower) }
let!(:follower_child) { create_child_of(follower) }
context 'for dependency of the follower child' do
let(:work_package_used_in_dependency) { follower_child }
it 'returns an array with the work_package id' do
expect(subject.dependent_ids).to contain_exactly(work_package.id)
end
end
context 'for dependency of the follower parent' do
let(:work_package_used_in_dependency) { follower_parent }
it 'returns an array with the work_package, the follower, and the follower child ids' do
expect(subject.dependent_ids).to contain_exactly(work_package.id, follower.id, follower_child.id)
end
end
end
end
end
describe '#soonest_start_date' do
let(:work_package_used_in_dependency) { work_package }
before do
work_package.update(due_date: Time.zone.today)
end
context 'with a moved predecessor' do
it 'returns the soonest start date from the predecessors' do
follower = create_follower_of(work_package)
expect(dependency_for(follower).soonest_start_date).to eq(work_package.due_date + 1.day)
end
end
context 'with an unmoved predecessor' do
it 'returns the soonest start date from the predecessors' do
follower = create_follower_of(work_package)
unmoved_follower_predecessor = create_predecessor_of(follower, due_date: Time.zone.today + 4.days)
expect(dependency_for(follower).soonest_start_date).to eq(unmoved_follower_predecessor.due_date + 1.day)
end
end
context 'with non working days' do
let!(:tomorrow_we_do_not_work!) { create(:non_working_day, date: Time.zone.tomorrow) }
it 'returns the soonest start date being a working day' do
follower = create_follower_of(work_package)
expect(dependency_for(follower).soonest_start_date).to eq(work_package.due_date + 2.days)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module WorkPackages
module Shared
class WorkingDays
# Returns number of working days between two dates, excluding weekend days
# and non working days.
def duration(start_date, due_date)
return nil unless start_date && due_date
(start_date..due_date).count { working?(_1) }
end
def start_date(due_date, duration)
assert_strictly_positive_duration(duration)
return nil unless due_date && duration
start_date = latest_working_day(due_date)
until duration <= 1 && working?(start_date)
start_date -= 1
duration -= 1 if working?(start_date)
end
start_date
end
def due_date(start_date, duration)
assert_strictly_positive_duration(duration)
return nil unless start_date && duration
due_date = soonest_working_day(start_date)
until duration <= 1 && working?(due_date)
due_date += 1
duration -= 1 if working?(due_date)
end
due_date
end
def soonest_working_day(date, delay: nil)
return unless date
delay ||= 0
while delay > 0
delay -= 1 if working?(date)
date += 1
end
until working?(date)
date += 1
end
date
end
def working?(date)
working_week_day?(date) && working_specific_date?(date)
end
def non_working?(date)
!working?(date)
end
private
def assert_strictly_positive_duration(duration)
raise ArgumentError, 'duration must be strictly positive' if duration.is_a?(Integer) && duration <= 0
end
def latest_working_day(date)
return unless date
until working?(date)
date -= 1
end
date
end
def working_week_day?(date)
assert_some_working_week_days_exist
working_week_days[date.wday]
end
def working_specific_date?(date)
non_working_dates.exclude?(date)
end
def assert_some_working_week_days_exist
return if @working_week_days_exist
if working_week_days.all? { |working| working == false }
raise 'cannot have all week days as non-working days'
end
@working_week_days_exist = true
end
def working_week_days
return @working_week_days if defined?(@working_week_days)
# WeekDay day of the week is stored as ISO, meaning Monday is 1 and Sunday is 7.
# Ruby Date#wday value for Sunday is 0 and it goes until 6 Saturday.
# To accommodate both versions 0-6, 1-7, an array of 8 elements is created
# where array[0] = array[7] = value for Sunday
#
# Since Setting.working_days can be empty, the initial array is
# built with all days considered working (value is `true`)
@working_week_days = [true] * 8
WeekDay.all.each do |week_day|
@working_week_days[week_day.day] = week_day.working
end
@working_week_days[0] = @working_week_days[7] # value for Sunday is present at index 0 AND index 7
@working_week_days
end
def non_working_dates
@non_working_dates ||= RequestStore.fetch(:work_package_non_working_dates) { Set.new(NonWorkingDay.pluck(:date)) }
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'rails_helper'
require_relative 'shared_examples_days'
RSpec.describe WorkPackages::Shared::WorkingDays do
subject { described_class.new }
friday_2022_07_29 = Date.new(2022, 7, 29)
saturday_2022_07_30 = Date.new(2022, 7, 30)
sunday_2022_07_31 = Date.new(2022, 7, 31)
monday_2022_08_01 = Date.new(2022, 8, 1)
wednesday_2022_08_03 = Date.new(2022, 8, 3)
describe '#duration' do
it 'returns the duration for a given start date and due date' do
expect(subject.duration(sunday_2022_07_31, sunday_2022_07_31 + 6)).to eq(7)
end
context 'without any week days created' do
it 'considers all days as working days and returns the number of days between two dates, inclusive' do
expect(subject.duration(sunday_2022_07_31, sunday_2022_07_31 + 6)).to eq(7)
expect(subject.duration(sunday_2022_07_31, sunday_2022_07_31 + 50)).to eq(51)
end
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
include_examples 'it returns duration', 0, sunday_2022_07_31, sunday_2022_07_31
include_examples 'it returns duration', 5, sunday_2022_07_31, Date.new(2022, 8, 5)
include_examples 'it returns duration', 5, sunday_2022_07_31, Date.new(2022, 8, 6)
include_examples 'it returns duration', 5, sunday_2022_07_31, Date.new(2022, 8, 7)
include_examples 'it returns duration', 6, sunday_2022_07_31, Date.new(2022, 8, 8)
include_examples 'it returns duration', 7, sunday_2022_07_31, Date.new(2022, 8, 9)
include_examples 'it returns duration', 1, monday_2022_08_01, monday_2022_08_01
include_examples 'it returns duration', 5, monday_2022_08_01, Date.new(2022, 8, 5)
include_examples 'it returns duration', 5, monday_2022_08_01, Date.new(2022, 8, 6)
include_examples 'it returns duration', 5, monday_2022_08_01, Date.new(2022, 8, 7)
include_examples 'it returns duration', 6, monday_2022_08_01, Date.new(2022, 8, 8)
include_examples 'it returns duration', 7, monday_2022_08_01, Date.new(2022, 8, 9)
include_examples 'it returns duration', 3, wednesday_2022_08_03, Date.new(2022, 8, 5)
include_examples 'it returns duration', 3, wednesday_2022_08_03, Date.new(2022, 8, 6)
include_examples 'it returns duration', 3, wednesday_2022_08_03, Date.new(2022, 8, 7)
include_examples 'it returns duration', 4, wednesday_2022_08_03, Date.new(2022, 8, 8)
include_examples 'it returns duration', 5, wednesday_2022_08_03, Date.new(2022, 8, 9)
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
include_examples 'it returns duration', 0, Date.new(2022, 12, 25), Date.new(2022, 12, 25)
include_examples 'it returns duration', 1, Date.new(2022, 12, 24), Date.new(2022, 12, 25)
include_examples 'it returns duration', 8, Date.new(2022, 12, 24), Date.new(2023, 1, 2)
end
context 'without start date' do
it 'returns nil' do
expect(subject.duration(nil, sunday_2022_07_31)).to be_nil
end
end
context 'without due date' do
it 'returns nil' do
expect(subject.duration(sunday_2022_07_31, nil)).to be_nil
end
end
end
describe '#start_date' do
it 'returns the start date for a due date and a duration' do
expect(subject.start_date(monday_2022_08_01, 1)).to eq(monday_2022_08_01)
end
it 'raises an error if duration is 0 or negative' do
expect { subject.start_date(monday_2022_08_01, 0) }
.to raise_error ArgumentError, 'duration must be strictly positive'
expect { subject.start_date(monday_2022_08_01, -10) }
.to raise_error ArgumentError, 'duration must be strictly positive'
end
it 'returns nil if due_date is nil' do
expect(subject.start_date(nil, 1)).to be_nil
end
it 'returns nil if duration is nil' do
expect(subject.start_date(monday_2022_08_01, nil)).to be_nil
end
context 'without any week days created' do
it 'returns the due date considering all days as working days' do
expect(subject.start_date(monday_2022_08_01, 1)).to eq(monday_2022_08_01)
expect(subject.start_date(monday_2022_08_01, 7)).to eq(monday_2022_08_01 - 6) # Tuesday of previous week
end
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
include_examples 'start_date', due_date: monday_2022_08_01, duration: 1, expected: monday_2022_08_01
include_examples 'start_date', due_date: monday_2022_08_01, duration: 5, expected: monday_2022_08_01 - 6.days
include_examples 'start_date', due_date: wednesday_2022_08_03, duration: 10, expected: wednesday_2022_08_03 - 13.days
# contrived one... But can happen when date is coming from an external entity, like soonest start.
include_examples 'start_date', due_date: saturday_2022_07_30, duration: 1, expected: friday_2022_07_29
include_examples 'start_date', due_date: saturday_2022_07_30, duration: 2, expected: friday_2022_07_29 - 1.day
include_examples 'start_date', due_date: saturday_2022_07_30, duration: 6, expected: friday_2022_07_29 - 7.days
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
include_examples 'start_date', due_date: Date.new(2022, 12, 26), duration: 2, expected: Date.new(2022, 12, 24)
include_examples 'start_date', due_date: Date.new(2023, 1, 2), duration: 8, expected: Date.new(2022, 12, 24)
end
end
describe '#due_date' do
it 'returns the due date for a start date and a duration' do
expect(subject.due_date(monday_2022_08_01, 1)).to eq(monday_2022_08_01)
end
it 'raises an error if duration is 0 or negative' do
expect { subject.due_date(monday_2022_08_01, 0) }
.to raise_error ArgumentError, 'duration must be strictly positive'
expect { subject.due_date(monday_2022_08_01, -10) }
.to raise_error ArgumentError, 'duration must be strictly positive'
end
it 'returns nil if start_date is nil' do
expect(subject.due_date(nil, 1)).to be_nil
end
it 'returns nil if duration is nil' do
expect(subject.due_date(monday_2022_08_01, nil)).to be_nil
end
context 'without any week days created' do
it 'returns the due date considering all days as working days' do
expect(subject.due_date(monday_2022_08_01, 1)).to eq(monday_2022_08_01)
expect(subject.due_date(monday_2022_08_01, 7)).to eq(monday_2022_08_01 + 6) # Sunday of same week
end
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
include_examples 'due_date', start_date: monday_2022_08_01, duration: 1, expected: monday_2022_08_01
include_examples 'due_date', start_date: monday_2022_08_01, duration: 5, expected: monday_2022_08_01 + 4.days
include_examples 'due_date', start_date: wednesday_2022_08_03, duration: 10, expected: wednesday_2022_08_03 + 13.days
# contrived one... But can happen when date is coming from an external entity, like soonest start.
include_examples 'due_date', start_date: saturday_2022_07_30, duration: 1, expected: monday_2022_08_01
include_examples 'due_date', start_date: saturday_2022_07_30, duration: 2, expected: monday_2022_08_01 + 1.day
include_examples 'due_date', start_date: saturday_2022_07_30, duration: 6, expected: monday_2022_08_01 + 7.days
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
include_examples 'due_date', start_date: Date.new(2022, 12, 24), duration: 2, expected: Date.new(2022, 12, 26)
include_examples 'due_date', start_date: Date.new(2022, 12, 24), duration: 8, expected: Date.new(2023, 1, 2)
end
end
describe '#soonest_working_day' do
it 'returns the soonest working day from the given day' do
expect(subject.soonest_working_day(sunday_2022_07_31)).to eq(sunday_2022_07_31)
end
it 'returns nil if given date is nil' do
expect(subject.soonest_working_day(nil)).to be_nil
end
context 'with delay' do
it 'returns the soonest working day from the given day, after a configurable delay of working days' do
expect(subject.soonest_working_day(sunday_2022_07_31, delay: nil)).to eq(sunday_2022_07_31)
expect(subject.soonest_working_day(sunday_2022_07_31, delay: 0)).to eq(sunday_2022_07_31)
expect(subject.soonest_working_day(sunday_2022_07_31, delay: 1)).to eq(monday_2022_08_01)
end
it 'works with big delay value like 100_000' do
# First implementation was recursive and failed with SystemStackError: stack level too deep
expect { subject.soonest_working_day(sunday_2022_07_31, delay: 100_000) }
.not_to raise_error
end
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
include_examples 'soonest working day', date: friday_2022_07_29, expected: friday_2022_07_29
include_examples 'soonest working day', date: saturday_2022_07_30, expected: monday_2022_08_01
include_examples 'soonest working day', date: sunday_2022_07_31, expected: monday_2022_08_01
include_examples 'soonest working day', date: monday_2022_08_01, expected: monday_2022_08_01
context 'with delay' do
include_examples 'soonest working day with delay', date: friday_2022_07_29, delay: 0, expected: friday_2022_07_29
include_examples 'soonest working day with delay', date: saturday_2022_07_30, delay: 0, expected: monday_2022_08_01
include_examples 'soonest working day with delay', date: sunday_2022_07_31, delay: 0, expected: monday_2022_08_01
include_examples 'soonest working day with delay', date: monday_2022_08_01, delay: 0, expected: monday_2022_08_01
include_examples 'soonest working day with delay', date: friday_2022_07_29, delay: 1, expected: monday_2022_08_01
include_examples 'soonest working day with delay', date: saturday_2022_07_30, delay: 1, expected: Date.new(2022, 8, 2)
include_examples 'soonest working day with delay', date: sunday_2022_07_31, delay: 1, expected: Date.new(2022, 8, 2)
include_examples 'soonest working day with delay', date: monday_2022_08_01, delay: 1, expected: Date.new(2022, 8, 2)
include_examples 'soonest working day with delay', date: friday_2022_07_29, delay: 8, expected: Date.new(2022, 8, 10)
end
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
include_examples 'soonest working day', date: Date.new(2022, 12, 25), expected: Date.new(2022, 12, 26)
include_examples 'soonest working day', date: Date.new(2022, 12, 31), expected: Date.new(2022, 12, 31)
include_examples 'soonest working day', date: Date.new(2023, 1, 1), expected: Date.new(2023, 1, 2)
context 'with delay' do
include_examples 'soonest working day with delay', date: Date.new(2022, 12, 24), delay: 7, expected: Date.new(2023, 1, 2)
end
end
context 'with no working days', :no_working_days do
it 'prevents looping infinitely by raising a runtime error' do
expect { subject.soonest_working_day(sunday_2022_07_31) }
.to raise_error(RuntimeError, 'cannot have all week days as non-working days')
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module WorkPackages
module Shared
class AllDays
# Returns number of days between two dates, inclusive.
def duration(start_date, due_date)
return nil unless start_date && due_date
(start_date..due_date).count
end
def start_date(due_date, duration)
return nil unless due_date && duration
raise ArgumentError, 'duration must be strictly positive' if duration.is_a?(Integer) && duration <= 0
due_date - duration + 1
end
def due_date(start_date, duration)
return nil unless start_date && duration
raise ArgumentError, 'duration must be strictly positive' if duration.is_a?(Integer) && duration <= 0
start_date + duration - 1
end
def soonest_working_day(date, delay: nil)
delay ||= 0
date + delay.days if date
end
def working?(_date)
true
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'rails_helper'
require_relative 'shared_examples_days'
RSpec.describe WorkPackages::Shared::AllDays do
subject { described_class.new }
sunday_2022_07_31 = Date.new(2022, 7, 31)
describe '#duration' do
context 'without any week days created' do
it 'considers all days as working days and returns the number of days between two dates, inclusive' do
expect(subject.duration(sunday_2022_07_31, sunday_2022_07_31 + 6)).to eq(7)
expect(subject.duration(sunday_2022_07_31, sunday_2022_07_31 + 50)).to eq(51)
end
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
it 'considers all days as working days and returns the number of days between two dates, inclusive' do
expect(subject.duration(sunday_2022_07_31, sunday_2022_07_31 + 6)).to eq(7)
expect(subject.duration(sunday_2022_07_31, sunday_2022_07_31 + 50)).to eq(51)
end
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
include_examples 'it returns duration', 365, Date.new(2022, 1, 1), Date.new(2022, 12, 31)
include_examples 'it returns duration', 365 * 2, Date.new(2022, 1, 1), Date.new(2023, 12, 31)
end
context 'without start date' do
it 'returns nil' do
expect(subject.duration(nil, sunday_2022_07_31)).to be_nil
end
end
context 'without due date' do
it 'returns nil' do
expect(subject.duration(sunday_2022_07_31, nil)).to be_nil
end
end
end
describe '#start_date' do
it 'returns the start date for a due date and a duration' do
expect(subject.start_date(sunday_2022_07_31, 1)).to eq(sunday_2022_07_31)
expect(subject.start_date(sunday_2022_07_31 + 9.days, 10)).to eq(sunday_2022_07_31)
end
it 'raises an error if duration is 0 or negative' do
expect { subject.start_date(sunday_2022_07_31, 0) }
.to raise_error ArgumentError, 'duration must be strictly positive'
expect { subject.start_date(sunday_2022_07_31, -10) }
.to raise_error ArgumentError, 'duration must be strictly positive'
end
it 'returns nil if due_date is nil' do
expect(subject.start_date(nil, 1)).to be_nil
end
it 'returns nil if duration is nil' do
expect(subject.start_date(sunday_2022_07_31, nil)).to be_nil
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
include_examples 'start_date', due_date: sunday_2022_07_31, duration: 1, expected: sunday_2022_07_31
include_examples 'start_date', due_date: sunday_2022_07_31, duration: 5, expected: sunday_2022_07_31 - 4.days
include_examples 'start_date', due_date: sunday_2022_07_31, duration: 10, expected: sunday_2022_07_31 - 9.days
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
include_examples 'start_date', due_date: Date.new(2022, 12, 31), duration: 365, expected: Date.new(2022, 1, 1)
include_examples 'start_date', due_date: Date.new(2023, 12, 31), duration: 365 * 2, expected: Date.new(2022, 1, 1)
end
end
describe '#due_date' do
it 'returns the due date for a start date and a duration' do
expect(subject.due_date(sunday_2022_07_31, 1)).to eq(sunday_2022_07_31)
expect(subject.due_date(sunday_2022_07_31, 10)).to eq(sunday_2022_07_31 + 9.days)
end
it 'raises an error if duration is 0 or negative' do
expect { subject.due_date(sunday_2022_07_31, 0) }
.to raise_error ArgumentError, 'duration must be strictly positive'
expect { subject.due_date(sunday_2022_07_31, -10) }
.to raise_error ArgumentError, 'duration must be strictly positive'
end
it 'returns nil if start_date is nil' do
expect(subject.due_date(nil, 1)).to be_nil
end
it 'returns nil if duration is nil' do
expect(subject.due_date(sunday_2022_07_31, nil)).to be_nil
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
include_examples 'due_date', start_date: sunday_2022_07_31, duration: 1, expected: sunday_2022_07_31
include_examples 'due_date', start_date: sunday_2022_07_31, duration: 5, expected: sunday_2022_07_31 + 4.days
include_examples 'due_date', start_date: sunday_2022_07_31, duration: 10, expected: sunday_2022_07_31 + 9.days
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
include_examples 'due_date', start_date: Date.new(2022, 1, 1), duration: 365, expected: Date.new(2022, 12, 31)
include_examples 'due_date', start_date: Date.new(2022, 1, 1), duration: 365 * 2, expected: Date.new(2023, 12, 31)
end
end
describe '#soonest_working_day' do
it 'returns the given day' do
expect(subject.soonest_working_day(sunday_2022_07_31)).to eq(sunday_2022_07_31)
end
it 'returns nil if given date is nil' do
expect(subject.soonest_working_day(nil)).to be_nil
end
context 'with delay' do
it 'returns the soonest working day from the given day, after a configurable delay of working days' do
expect(subject.soonest_working_day(sunday_2022_07_31, delay: nil)).to eq(sunday_2022_07_31)
expect(subject.soonest_working_day(sunday_2022_07_31, delay: 0)).to eq(sunday_2022_07_31)
expect(subject.soonest_working_day(sunday_2022_07_31, delay: 1)).to eq(Date.new(2022, 8, 1))
end
end
context 'with weekend days (Saturday and Sunday)', :weekend_saturday_sunday do
it 'returns the given day' do
expect(subject.soonest_working_day(sunday_2022_07_31)).to eq(sunday_2022_07_31)
end
context 'with delay' do
include_examples 'soonest working day with delay', date: Date.new(2022, 1, 1), delay: 30, expected: Date.new(2022, 1, 31)
end
end
context 'with some non working days (Christmas 2022-12-25 and new year\'s day 2023-01-01)', :christmas_2022_new_year_2023 do
it 'returns the given day' do
expect(subject.soonest_working_day(Date.new(2022, 12, 25))).to eq(Date.new(2022, 12, 25))
end
context 'with delay' do
include_examples 'soonest working day with delay', date: Date.new(2022, 12, 24), delay: 7,
expected: Date.new(2022, 12, 31)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module WorkPackages
module Shared
module Days
module_function
# Returns the right day computation instance for the given instance.
def for(work_package)
work_package.ignore_non_working_days ? AllDays.new : WorkingDays.new
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'rails_helper'
RSpec.describe WorkPackages::Shared::Days do
subject { described_class.new }
describe '.for' do
context 'for a work_package ignoring non working days' do
let(:work_package) { build_stubbed(:work_package, ignore_non_working_days: true) }
it 'returns an AllDays instance' do
expect(described_class.for(work_package)).to be_an_instance_of(WorkPackages::Shared::AllDays)
end
end
context 'for a work_package respecting non working days' do
let(:work_package) { build_stubbed(:work_package) }
it 'returns a WorkingDays instance' do
expect(described_class.for(work_package)).to be_an_instance_of(WorkPackages::Shared::WorkingDays)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# OpenProject is an open source project management software.
# Copyright (C) 2022 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
class WorkPackages::UpdateAncestors::Loader
def initialize(work_package, include_former_ancestors)
self.work_package = work_package
self.include_former_ancestors = include_former_ancestors
end
def select
ancestors.select do |ancestor|
yield ancestor, self
end
end
def descendants_of(queried_work_package)
@descendants ||= Hash.new do |hash, wp|
hash[wp] = replaced_related_of(wp, :descendants)
end
@descendants[queried_work_package]
end
def leaves_of(queried_work_package)
@leaves ||= Hash.new do |hash, wp|
hash[wp] = replaced_related_of(wp, :leaves) do |leaf|
# Mimic work package by implementing the closed? interface
leaf.send(:'closed?=', leaf.is_closed)
end
end
@leaves[queried_work_package]
end
def children_of(queried_work_package)
@children ||= Hash.new do |hash, wp|
hash[wp] = descendants_of(wp).select { |d| d.parent_id == wp.id }
end
@children[queried_work_package]
end
private
attr_accessor :work_package,
:include_former_ancestors
# Contains both the new as well as the former ancestors in ascending order from the leaves up (breadth first).
def ancestors
@ancestors ||= if include_former_ancestors
former_ancestors.reverse.inject(current_ancestors) do |ancestors, former_ancestor|
index = ancestors.index { |ancestor| ancestor.id == former_ancestor.parent_id }
ancestors.insert(index || current_ancestors.length, former_ancestor)
ancestors
end
else
current_ancestors
end
end
# Replace descendants/leaves by ancestors if they are the same.
# This can e.g. be the case in scenario of
# grandparent
# |
# parent
# |
# work_package
#
# when grandparent used to be the direct parent of work_package (the work_package moved down the hierarchy).
# Then grandparent and parent are already in ancestors.
# Parent might be modified during the UpdateAncestorsService run,
# and the descendants of grandparent need to have the updated value.
def replaced_related_of(queried_work_package, relation_type)
related_of(queried_work_package, relation_type).map do |leaf|
if work_package.id == leaf.id
work_package
elsif (ancestor = ancestors.detect { |a| a.id == leaf.id })
ancestor
else
yield leaf if block_given?
leaf
end
end
end
def related_of(queried_work_package, relation_type)
scope = queried_work_package
.send(relation_type)
.where.not(id: queried_work_package.id)
if send("#{relation_type}_joins")
scope = scope.joins(send("#{relation_type}_joins"))
end
scope
.pluck(*send("selected_#{relation_type}_attributes"))
.map { |p| LoaderStruct.new(send("selected_#{relation_type}_attributes").zip(p).to_h) }
end
# Returns the current ancestors sorted by distance (called generations in the table)
# so the order is parent, grandparent, ..., root.
def current_ancestors
@current_ancestors ||= work_package.ancestors.includes(:status).where.not(id: former_ancestors.map(&:id)).to_a
end
# Returns the former ancestors sorted by distance (called generations in the table)
# so the order is former parent, former grandparent, ..., former root.
def former_ancestors
@former_ancestors ||= if previous_parent_id && include_former_ancestors
parent = WorkPackage.find(previous_parent_id)
[parent] + parent.ancestors
else
[]
end
end
def selected_descendants_attributes
# By having the id in here, we can avoid DISTINCT queries squashing duplicate values
%i(id estimated_hours parent_id schedule_manually ignore_non_working_days)
end
def descendants_joins
nil
end
def selected_leaves_attributes
%i(id done_ratio derived_estimated_hours estimated_hours is_closed)
end
def leaves_joins
:status
end
##
# Get the previous parent ID
# This could either be +parent_id_was+ if parent was changed
# (when work_package was saved/destroyed)
# Or the set parent before saving
def previous_parent_id
if work_package.parent_id.nil? && work_package.parent_id_was
work_package.parent_id_was
else
previous_change_parent_id
end
end
def previous_change_parent_id
previous = work_package.previous_changes
previous_parent_changes = (previous[:parent_id] || previous[:parent])
previous_parent_changes ? previous_parent_changes.first : nil
end
class LoaderStruct < Hashie::Mash; end
LoaderStruct.disable_warnings
end
``` | # OpenProject is an open source project management software.
# Copyright (C) 2010-2022 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
RSpec.describe WorkPackages::UpdateAncestors::Loader, type: :model do
shared_let(:grandgrandparent) do
create(:work_package)
end
shared_let(:grandparent_sibling) do
create(:work_package,
parent: grandgrandparent)
end
shared_let(:grandparent) do
create(:work_package,
parent: grandgrandparent)
end
shared_let(:parent) do
create(:work_package,
parent: grandparent)
end
shared_let(:sibling) do
create(:work_package,
parent:)
end
shared_let(:work_package) do
create(:work_package,
parent:)
end
shared_let(:child) do
create(:work_package,
parent: work_package)
end
let(:include_former_ancestors) { true }
let(:instance) do
described_class
.new(work_package, include_former_ancestors)
end
describe '#select' do
subject do
work_package.parent = new_parent
work_package.save!
instance
end
context 'when switching the hierarchy' do
let!(:new_grandgrandparent) do
create(:work_package,
subject: 'new grandgrandparent')
end
let!(:new_grandparent) do
create(:work_package,
parent: new_grandgrandparent,
subject: 'new grandparent')
end
let!(:new_parent) do
create(:work_package,
subject: 'new parent',
parent: new_grandparent)
end
let!(:new_sibling) do
create(:work_package,
subject: 'new sibling',
parent: new_parent)
end
it 'iterates over both current and former ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [new_parent, new_grandparent, new_grandgrandparent, parent, grandparent, grandgrandparent]
end
end
context 'when switching the hierarchy and not including the former ancestors' do
let!(:new_grandgrandparent) do
create(:work_package,
subject: 'new grandgrandparent')
end
let!(:new_grandparent) do
create(:work_package,
parent: new_grandgrandparent,
subject: 'new grandparent')
end
let!(:new_parent) do
create(:work_package,
subject: 'new parent',
parent: new_grandparent)
end
let!(:new_sibling) do
create(:work_package,
subject: 'new sibling',
parent: new_parent)
end
let(:include_former_ancestors) { false }
it 'iterates over the current ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [new_parent, new_grandparent, new_grandgrandparent]
end
end
context 'when removing the parent' do
let(:new_parent) { nil }
it 'iterates over the former ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [parent, grandparent, grandgrandparent]
end
end
context 'when removing the parent and not including the former ancestors' do
let(:new_parent) { nil }
let(:include_former_ancestors) { false }
it 'loads nothing' do
expect(subject.select { |ancestor| ancestor })
.to be_empty
end
end
context 'when changing the parent within the same hierarchy upwards' do
let(:new_parent) { grandgrandparent }
it 'iterates over the former ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [parent, grandparent, grandgrandparent]
end
end
context 'when changing the parent within the same hierarchy upwards and not loading former ancestors' do
let(:new_parent) { grandgrandparent }
let(:include_former_ancestors) { false }
it 'iterates over the current ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [grandgrandparent]
end
end
context 'when changing the parent within the same hierarchy sideways' do
let(:new_parent) { sibling }
it 'iterates over the current ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [sibling, parent, grandparent, grandgrandparent]
end
end
context 'when changing the parent within the same hierarchy sideways and not loading former ancestors' do
let(:new_parent) { sibling }
let(:include_former_ancestors) { false }
it 'iterates over the current ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [sibling, parent, grandparent, grandgrandparent]
end
end
context 'when changing the parent within the same hierarchy sideways but to a different level' do
let(:new_parent) { grandparent_sibling }
it 'iterates over the former and the current ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [grandparent_sibling, parent, grandparent, grandgrandparent]
end
end
context 'when changing the parent within the same hierarchy sideways but to a different level and not loading ancestors' do
let(:new_parent) { grandparent_sibling }
let(:include_former_ancestors) { false }
it 'iterates over the former and the current ancestors' do
expect(subject.select { |ancestor| ancestor })
.to eql [grandparent_sibling, grandgrandparent]
end
end
end
describe '#descendants_of' do
def descendants_of_hash(hashed_work_package)
{ "estimated_hours" => nil,
"id" => hashed_work_package.id,
"ignore_non_working_days" => false,
"parent_id" => hashed_work_package.parent_id,
"remaining_hours" => nil,
"schedule_manually" => false }
end
context 'for the work_package' do
it 'is its child (as a hash)' do
expect(instance.descendants_of(work_package))
.to match_array([descendants_of_hash(child)])
end
end
context 'for the parent' do
it 'is the work package, its child (as a hash) and its sibling (as a hash)' do
expect(instance.descendants_of(parent))
.to match_array([descendants_of_hash(child),
work_package,
descendants_of_hash(sibling)])
end
end
context 'for the grandparent' do
it 'is the parent, the work package, its child (as a hash) and its sibling (as a hash)' do
expect(instance.descendants_of(grandparent))
.to match_array([parent,
work_package,
descendants_of_hash(child),
descendants_of_hash(sibling)])
end
end
context 'for the grandgrandparent (the root)' do
it 'is the complete tree, partly as a hash and partly as the preloaded work packages' do
expect(instance.descendants_of(grandgrandparent))
.to match_array([descendants_of_hash(grandparent_sibling),
grandparent,
parent,
work_package,
descendants_of_hash(child),
descendants_of_hash(sibling)])
end
end
end
describe '#children_of' do
def children_of_hash(hashed_work_package)
{ "estimated_hours" => nil,
"id" => hashed_work_package.id,
"ignore_non_working_days" => false,
"parent_id" => hashed_work_package.parent_id,
"remaining_hours" => nil,
"schedule_manually" => false }
end
context 'for the work_package' do
it 'is its child (as a hash)' do
expect(instance.children_of(work_package))
.to match_array([children_of_hash(child)])
end
end
context 'for the parent' do
it 'is the work package and its sibling (as a hash)' do
expect(instance.children_of(parent))
.to match_array([work_package,
children_of_hash(sibling)])
end
end
context 'for the grandparent' do
it 'is the parent' do
expect(instance.children_of(grandparent))
.to match_array([parent])
end
end
context 'for the grandgrandparent' do
it 'is the grandparent and its sibling (as a hash)' do
expect(instance.children_of(grandgrandparent))
.to match_array([children_of_hash(grandparent_sibling),
grandparent])
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Projects
class SetAttributesService < ::BaseServices::SetAttributes
private
def set_attributes(params)
ret = super(params.except(:status_code))
set_status_code(params[:status_code]) if status_code_provided?(params)
ret
end
def set_default_attributes(attributes)
attribute_keys = attributes.keys.map(&:to_s)
set_default_public(attribute_keys.include?('public'))
set_default_module_names(attribute_keys.include?('enabled_module_names'))
set_default_types(attribute_keys.include?('types') || attribute_keys.include?('type_ids'))
set_default_active_work_package_custom_fields(attribute_keys.include?('work_package_custom_fields'))
end
def set_default_public(provided)
model.public = Setting.default_projects_public? unless provided
end
def set_default_module_names(provided)
model.enabled_module_names = Setting.default_projects_modules if !provided && model.enabled_module_names.empty?
end
def set_default_types(provided)
model.types = ::Type.default if !provided && model.types.empty?
end
def set_default_active_work_package_custom_fields(provided)
return if provided
model.work_package_custom_fields = WorkPackageCustomField
.joins(:types)
.where(types: { id: model.type_ids })
.distinct
end
def status_code_provided?(params)
params.key?(:status_code)
end
def set_status_code(status_code)
if faulty_code?(status_code)
# set an arbitrary status code first to get rails internal into correct state
model.status_code = first_not_set_code
# hack into rails internals to set faulty code
code_attributes = model.instance_variable_get(:@attributes)['status_code']
code_attributes.instance_variable_set(:@value_before_type_cast, status_code)
code_attributes.instance_variable_set(:@value, status_code)
else
model.status_code = status_code
end
end
def faulty_code?(status_code)
status_code && Project.status_codes.keys.exclude?(status_code.to_s)
end
def first_not_set_code
(Project.status_codes.keys - [model.status_code]).first
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Projects::SetAttributesService, type: :model do
let(:user) { build_stubbed(:user) }
let(:contract_class) do
contract = class_double(Projects::CreateContract)
allow(contract)
.to receive(:new)
.with(project, user, options: {})
.and_return(contract_instance)
contract
end
let(:contract_instance) do
instance_double(Projects::CreateContract, validate: contract_valid, errors: contract_errors)
end
let(:contract_valid) { true }
let(:contract_errors) do
instance_double(ActiveModel::Errors)
end
let(:project_valid) { true }
let(:instance) do
described_class.new(user:,
model: project,
contract_class:)
end
let(:call_attributes) { {} }
let(:project) do
build_stubbed(:project)
end
describe 'call' do
let(:call_attributes) do
{}
end
before do
allow(project)
.to receive(:valid?)
.and_return(project_valid)
allow(contract_instance)
.to receive(:validate)
.and_return(contract_valid)
end
subject { instance.call(call_attributes) }
it 'is successful' do
expect(subject).to be_success
end
it 'calls validation' do
subject
expect(contract_instance)
.to have_received(:validate)
end
it 'sets the attributes' do
subject
expect(project.attributes.slice(*project.changed).symbolize_keys)
.to eql call_attributes
end
it 'does not persist the project' do
allow(project)
.to receive(:save)
subject
expect(project)
.not_to have_received(:save)
end
shared_examples 'setting status attributes' do
let(:status_explanation) { 'A magic dwells in each beginning.' }
it 'sets the project status code' do
expect(subject.result.status_code)
.to eq status_code
end
it 'sets the project status explanation' do
expect(subject.result.status_explanation)
.to eq status_explanation
end
end
context 'for a new record' do
let(:project) do
Project.new
end
describe 'identifier default value' do
context 'with an identifier provided' do
let(:call_attributes) do
{
identifier: 'lorem'
}
end
it 'does not alter the identifier' do
expect(subject.result.identifier)
.to eql 'lorem'
end
end
context 'with no identifier provided' do
it 'stays nil' do
allow(Project)
.to receive(:next_identifier)
.and_return('ipsum')
expect(subject.result.identifier)
.to be_nil
end
end
end
describe 'public default value', with_settings: { default_projects_public: true } do
context 'with a value for is_public provided' do
let(:call_attributes) do
{
public: false
}
end
it 'does not alter the public value' do
expect(subject.result)
.not_to be_public
end
end
context 'with no value for public provided' do
it 'sets uses the default value' do
expect(subject.result)
.to be_public
end
end
end
describe 'enabled_module_names default value', with_settings: { default_projects_modules: ['lorem', 'ipsum'] } do
context 'with a value for enabled_module_names provided' do
let(:call_attributes) do
{
enabled_module_names: %w(some other)
}
end
it 'does not alter the enabled modules' do
expect(subject.result.enabled_module_names)
.to match_array %w(some other)
end
end
context 'with no value for enabled_module_names provided' do
it 'sets a default enabled modules' do
expect(subject.result.enabled_module_names)
.to match_array %w(lorem ipsum)
end
end
context 'with the enabled modules being set before' do
before do
project.enabled_module_names = %w(some other)
end
it 'does not alter the enabled modules' do
expect(subject.result.enabled_module_names)
.to match_array %w(some other)
end
end
end
describe 'types default value' do
let(:other_types) do
[build_stubbed(:type)]
end
let(:default_types) do
[build_stubbed(:type)]
end
before do
allow(Type)
.to receive(:default)
.and_return default_types
end
shared_examples "setting custom field defaults" do
context 'with custom fields' do
let!(:custom_field) { create(:text_wp_custom_field, types:) }
let!(:custom_field_with_no_type) { create(:text_wp_custom_field) }
it 'activates the type\'s custom fields' do
expect(subject.result.work_package_custom_fields)
.to eq([custom_field])
end
end
end
context 'with a value for types provided' do
let(:call_attributes) do
{
types: other_types
}
end
it 'does not alter the types' do
expect(subject.result.types)
.to match_array other_types
end
include_examples "setting custom field defaults" do
let(:other_types) { [create(:type)] }
let(:types) { other_types }
end
end
context 'with no value for types provided' do
it 'sets the default types' do
expect(subject.result.types)
.to match_array default_types
end
include_examples "setting custom field defaults" do
let(:default_types) { [create(:type)] }
let(:types) { default_types }
end
end
context 'with the types being set before' do
let(:types) { [build(:type, name: 'lorem')] }
before do
project.types = types
end
it 'does not alter the types modules' do
expect(subject.result.types.map(&:name))
.to match_array %w(lorem)
end
include_examples "setting custom field defaults" do
let(:types) { [create(:type, name: 'lorem')] }
end
end
end
describe 'project status' do
context 'with valid status attributes' do
let(:status_code) { 'on_track' }
let(:call_attributes) do
{
status_code:,
status_explanation:
}
end
include_examples 'setting status attributes'
end
context 'with an invalid status code provided' do
let(:status_code) { 'wrong' }
let(:call_attributes) do
{
status_code:,
status_explanation:
}
end
include_examples 'setting status attributes'
end
end
end
context 'for an existing project' do
describe 'project status' do
let(:project) do
build_stubbed(:project, :with_status)
end
context 'with a value provided' do
let(:status_code) { 'at_risk' }
let(:status_explanation) { 'Still some magic there.' }
let(:call_attributes) do
{
status_code:,
status_explanation:
}
end
include_examples 'setting status attributes'
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Projects
class ArchiveService < ::BaseServices::BaseContracted
include Contracted
include Projects::Concerns::UpdateDemoData
def initialize(user:, model:, contract_class: Projects::ArchiveContract)
super(user:, contract_class:)
self.model = model
end
private
def persist(service_call)
archive_project(model) and model.active_subprojects.each do |subproject|
archive_project(subproject)
end
service_call
end
def after_perform(service_call)
OpenProject::Notifications.send(OpenProject::Events::PROJECT_ARCHIVED, project: model)
service_call
end
def archive_project(project)
# We do not care for validations but want the timestamps to be updated
project.update_attribute(:active, false)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Projects::ArchiveService do
let(:project) { create(:project) }
let(:subproject1) { create(:project) }
let(:subproject2) { create(:project) }
let(:subproject3) { create(:project) }
let(:user) { create(:admin) }
let(:instance) { described_class.new(user:, model: project) }
it 'sends the notification' do
allow(OpenProject::Notifications).to receive(:send)
expect(instance.call).to be_truthy
expect(OpenProject::Notifications)
.to(have_received(:send)
.with(OpenProject::Events::PROJECT_ARCHIVED, project:))
expect(OpenProject::Notifications)
.to(have_received(:send)
.with(OpenProject::Events::PROJECT_ARCHIVED, project:))
end
context 'with project without any subprojects' do
it 'archives the project' do
expect(project.reload).not_to be_archived
expect(instance.call).to be_truthy
expect(project.reload).to be_archived
end
end
context 'with project having subprojects' do
before do
project.update(children: [subproject1, subproject2, subproject3])
project.reload
end
shared_examples 'when archiving a project' do
it 'archives the project' do
# Baseline verification.
expect(project.reload).not_to be_archived
# Action.
expect(instance.call).to be_truthy
# Endline verification.
expect(project.reload).to be_archived
end
it 'archives all the subprojects' do
# Baseline verification.
expect(subproject1.reload).not_to be_archived
expect(subproject2.reload).not_to be_archived
expect(subproject3.reload).not_to be_archived
# Action.
expect(instance.call).to be_truthy
# Endline verification.
expect(subproject1.reload).to be_archived
expect(subproject2.reload).to be_archived
expect(subproject3.reload).to be_archived
end
end
include_examples 'when archiving a project'
context 'with deep nesting' do
before do
project.update(children: [subproject1])
subproject1.update(children: [subproject2])
subproject2.update(children: [subproject3])
project.reload
subproject1.reload
end
include_examples 'when archiving a project'
end
end
context 'with project having an archived subproject' do
let(:subproject1) { create(:project, active: false) }
before do
project.update(children: [subproject1, subproject2, subproject3])
project.reload
end
context 'while archiving the project' do
it 'does not change timestamp of the already archived subproject' do
expect(subproject1.reload).to be_archived
before_timestamp = subproject1.updated_at
expect(instance.call).to be_truthy
after_timestamp = subproject1.reload.updated_at
expect(before_timestamp).to eq(after_timestamp)
end
it 'changes timestamp of the active subproject' do
expect(subproject2.reload).not_to be_archived
before_timestamp = subproject2.updated_at
expect(instance.call).to be_truthy
after_timestamp = subproject2.reload.updated_at
expect(before_timestamp).not_to eq(after_timestamp)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Projects
class UnarchiveService < ::BaseServices::BaseContracted
include Contracted
include Projects::Concerns::UpdateDemoData
def initialize(user:, model:, contract_class: Projects::UnarchiveContract)
super(user:, contract_class:)
self.model = model
end
private
def persist(service_call)
activate_project(model)
service_call
end
def after_perform(service_call)
OpenProject::Notifications.send(OpenProject::Events::PROJECT_UNARCHIVED, project: model)
service_call
end
def activate_project(project)
# We do not care for validations but want the timestamps to be updated
project.update_attribute(:active, true)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Projects::UnarchiveService do
let(:project) { create(:project, active: false) }
let(:user) { create(:admin) }
let(:instance) { described_class.new(user:, model: project) }
it 'unarchives and sends the notification' do
allow(OpenProject::Notifications).to receive(:send)
expect(project.active).to be(false)
expect(instance.call).to be_truthy
expect(project.active).to be(true)
expect(OpenProject::Notifications)
.to(have_received(:send)
.with(OpenProject::Events::PROJECT_UNARCHIVED, project:))
expect(OpenProject::Notifications)
.to(have_received(:send)
.with(OpenProject::Events::PROJECT_UNARCHIVED, project:))
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Projects
class UpdateService < ::BaseServices::Update
private
attr_accessor :memoized_changes
def set_attributes(params)
ret = super
# Because awesome_nested_set reloads the model after saving, we cannot rely
# on saved_changes.
self.memoized_changes = model.changes
ret
end
def after_perform(service_call)
touch_on_custom_values_update
notify_on_identifier_renamed
send_update_notification
update_wp_versions_on_parent_change
handle_archiving
service_call
end
def touch_on_custom_values_update
model.touch if only_custom_values_updated?
end
def notify_on_identifier_renamed
return unless memoized_changes['identifier']
OpenProject::Notifications.send(OpenProject::Events::PROJECT_RENAMED, project: model)
end
def send_update_notification
OpenProject::Notifications.send(OpenProject::Events::PROJECT_UPDATED, project: model)
end
def only_custom_values_updated?
!model.saved_changes? && model.custom_values.any?(&:saved_changes?)
end
def update_wp_versions_on_parent_change
return unless memoized_changes['parent_id']
WorkPackage.update_versions_from_hierarchy_change(model)
end
def handle_archiving
return unless model.saved_change_to_active?
service_class =
if model.active?
# was unarchived
Projects::UnarchiveService
else
# was archived
Projects::ArchiveService
end
# EmptyContract is used because archive/unarchive conditions have
# already been checked in Projects::UpdateContract
service = service_class.new(user:, model:, contract_class: EmptyContract)
service.call
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe Projects::UpdateService, type: :model do
it_behaves_like 'BaseServices update service' do
let!(:model_instance) do
build_stubbed(:project, :with_status)
end
it 'sends an update notification' do
expect(OpenProject::Notifications)
.to(receive(:send))
.with(OpenProject::Events::PROJECT_UPDATED, project: model_instance)
subject
end
context 'if the identifier is altered' do
let(:call_attributes) { { identifier: 'Some identifier' } }
before do
allow(model_instance)
.to(receive(:changes))
.and_return('identifier' => %w(lorem ipsum))
end
it 'sends the notification' do
expect(OpenProject::Notifications)
.to(receive(:send))
.with(OpenProject::Events::PROJECT_UPDATED, project: model_instance)
expect(OpenProject::Notifications)
.to(receive(:send))
.with(OpenProject::Events::PROJECT_RENAMED, project: model_instance)
subject
end
end
context 'if the parent is altered' do
before do
allow(model_instance)
.to(receive(:changes))
.and_return('parent_id' => [nil, 5])
end
it 'updates the versions associated with the work packages' do
expect(WorkPackage)
.to(receive(:update_versions_from_hierarchy_change))
.with(model_instance)
subject
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
##
# Schedules the deletion of a project if allowed. As the deletion can be
# a lengthy process, the project is archived first
#
module Projects
class ScheduleDeletionService < ::BaseServices::BaseContracted
def initialize(user:, model:, contract_class: ::Projects::DeleteContract)
super(user:, contract_class:)
self.model = model
end
private
def before_perform(_params, service_result)
return service_result if model.archived?
Projects::ArchiveService
.new(user:, model:)
.call
end
def persist(call)
DeleteProjectJob.perform_later(user:, project: model)
call
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Projects::ScheduleDeletionService, type: :model do
let(:contract_class) do
contract = double('contract_class', '<=': true)
allow(contract)
.to receive(:new)
.with(project, user, options: {})
.and_return(contract_instance)
contract
end
let(:contract_instance) do
double('contract_instance', validate: contract_valid, errors: contract_errors)
end
let(:contract_valid) { true }
let(:contract_errors) do
double('contract_errors')
end
let(:project_valid) { true }
let(:project) { build_stubbed(:project) }
let(:instance) do
described_class.new(user:,
model: project,
contract_class:)
end
let(:archive_success) do
true
end
let(:archive_errors) do
double('archive_errors')
end
let(:archive_result) do
ServiceResult.new result: project,
success: archive_success,
errors: archive_errors
end
let!(:archive_service) do
service = double('archive_service_instance')
allow(Projects::ArchiveService)
.to receive(:new)
.with(user:,
model: project)
.and_return(service)
allow(service)
.to receive(:call)
.and_return(archive_result)
service
end
let(:user) { build_stubbed(:admin) }
subject { instance.call }
before do
allow(Projects::DeleteProjectJob)
.to receive(:perform_later)
end
context 'if contract and archiving are successful' do
it 'archives the project and creates a delayed job' do
expect(subject).to be_success
expect(archive_service)
.to have_received(:call)
expect(Projects::DeleteProjectJob)
.to have_received(:perform_later)
.with(user:, project:)
end
end
context 'if project is archived already' do
let(:project) { build_stubbed(:project, active: false) }
it 'does not call archive service' do
expect(subject).to be_success
expect(archive_service)
.not_to have_received(:call)
expect(Projects::DeleteProjectJob)
.to have_received(:perform_later)
.with(user:, project:)
end
end
context 'if contract fails' do
let(:contract_valid) { false }
it 'is failure' do
expect(subject).to be_failure
end
it 'returns the contract errors' do
expect(subject.errors)
.to eql contract_errors
end
it 'does not schedule a job' do
expect(Projects::DeleteProjectJob)
.not_to receive(:new)
subject
end
end
context 'if archiving fails' do
let(:archive_success) { false }
it 'is failure' do
expect(subject).to be_failure
end
it 'returns the contract errors' do
expect(subject.errors)
.to eql archive_errors
end
it 'does not schedule a job' do
expect(Projects::DeleteProjectJob)
.not_to receive(:new)
subject
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Projects
class CreateService < ::BaseServices::Create
include Projects::Concerns::NewProjectService
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_create_service'
RSpec.describe Projects::CreateService, type: :model do
it_behaves_like 'BaseServices create service' do
let(:new_project_role) { build_stubbed(:project_role) }
let(:create_member_instance) { instance_double(Members::CreateService) }
before do
allow(ProjectRole)
.to(receive(:in_new_project))
.and_return(new_project_role)
allow(Members::CreateService)
.to(receive(:new))
.with(user:, contract_class: EmptyContract)
.and_return(create_member_instance)
allow(create_member_instance)
.to(receive(:call))
end
it 'adds the current user to the project' do
subject
expect(create_member_instance)
.to have_received(:call)
.with(principal: user,
project: model_instance,
roles: [new_project_role])
end
context 'current user is admin' do
it 'does not add the user to the project' do
allow(user)
.to(receive(:admin?))
.and_return(true)
subject
expect(create_member_instance)
.not_to(have_received(:call))
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Projects
class DeleteService < ::BaseServices::Delete
include Projects::Concerns::UpdateDemoData
##
# Reference to the dependent projects that we're deleting
attr_accessor :dependent_projects
def initialize(user:, model:, contract_class: nil, contract_options: {})
self.dependent_projects = model.descendants.to_a # Store an Array instead of a Project::ActiveRecord_Relation
super
end
def call(*)
super.tap do |service_call|
notify(service_call.success?)
end
end
private
def before_perform(*)
OpenProject::Notifications.send(:project_deletion_imminent, project: @project_to_destroy)
delete_all_members
destroy_all_work_packages
destroy_all_storages
super
end
# Deletes all project's members
def delete_all_members
MemberRole
.includes(:member)
.where(members: { project_id: model.id })
.delete_all
Member.where(project_id: model.id).destroy_all
end
def destroy_all_work_packages
model.work_packages.each do |wp|
wp.reload
wp.destroy
rescue ActiveRecord::RecordNotFound
# Everything fine, we wanted to delete it anyway
end
end
def destroy_all_storages
model.project_storages.map do |project_storage|
Storages::ProjectStorages::DeleteService.new(user:, model: project_storage).call
end
end
def notify(success)
if success
ProjectMailer.delete_project_completed(model, user:, dependent_projects:).deliver_now
else
ProjectMailer.delete_project_failed(model, user:).deliver_now
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Projects::DeleteService, type: :model do
shared_let(:user) { create(:admin) }
let(:project) { create(:project) }
let(:instance) { described_class.new(user:, model: project) }
subject { instance.call }
context 'if authorized' do
context 'when destroy succeeds' do
it 'destroys the projects' do
allow(project).to receive(:archive)
allow(Projects::DeleteProjectJob).to receive(:new)
expect { subject }.to change(Project, :count).by(-1)
expect(project).not_to have_received(:archive)
expect(Projects::DeleteProjectJob)
.not_to have_received(:new)
end
context 'when the file storages are involved', webmock: true do
it 'removes any remote storages defined for the project' do
storage = create(:nextcloud_storage)
project_storage = create(:project_storage, project:, storage:)
work_package = create(:work_package, project:)
create(:file_link, container: work_package, storage:)
delete_folder_url =
"#{storage.host}/remote.php/dav/files/#{storage.username}/#{project_storage.project_folder_path.chop}/"
stub_request(:delete, delete_folder_url).to_return(status: 204, body: nil, headers: {})
expect { subject }.to change(Storages::ProjectStorage, :count).by(-1)
end
end
it 'sends a success mail' do
expect(subject).to be_success
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.subject).to eq(I18n.t('projects.delete.completed', name: project.name))
text_part = mail.text_part.to_s
html_part = mail.html_part.to_s
expect(text_part).to include(project.name)
expect(html_part).to include(project.name)
end
end
context 'with a hierarchy of projects' do
let!(:children) { create_list(:project, 2, parent: project) }
let!(:grand_children) { create_list(:project, 2, parent: children.first) }
let(:all_children) { children + grand_children }
before do
project.reload
end
it 'destroys the projects' do
expect { subject }.to change(Project, :count).by(-5)
end
it 'sends a success mail mentioning all the child projects' do
expect { subject }.to change(ActionMailer::Base.deliveries, :size).by(1)
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.subject).to eq(I18n.t('projects.delete.completed', name: project.name))
text_part = mail.text_part.to_s
html_part = mail.html_part.to_s
all_children.each do |child|
expect(text_part).to include(child.name)
expect(html_part).to include(child.name)
end
end
end
end
end
it 'sends a message on destroy failure' do
expect(project).to receive(:destroy).and_return false
expect(ProjectMailer)
.to receive_message_chain(:delete_project_failed, :deliver_now)
expect(Projects::DeleteProjectJob)
.not_to receive(:new)
expect(subject).to be_failure
end
end
context 'if not authorized' do
let(:user) { build_stubbed(:user) }
it 'returns an error' do
allow(Projects::DeleteProjectJob).to receive(:new)
expect(subject).to be_failure
expect(Projects::DeleteProjectJob).not_to have_received(:new)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Projects
class GanttQueryGeneratorService
DEFAULT_GANTT_QUERY ||=
{
c: %w[type id subject status],
tll: '{"left":"startDate","right":"dueDate","farRight":null}',
tzl: "auto",
tv: true,
hi: false,
g: "project"
}.to_json.freeze
attr_reader :selected_project_ids
class << self
##
# Returns the current query or the default one if none was saved
def current_query
Setting.project_gantt_query.presence || default_gantt_query
end
def default_gantt_query
default_with_filter = JSON
.parse(Projects::GanttQueryGeneratorService::DEFAULT_GANTT_QUERY)
milestone_ids = Type.milestone.pluck(:id).map(&:to_s)
if milestone_ids.any?
default_with_filter.merge!('f' => [{ 'n' => 'type', 'o' => '=', 'v' => milestone_ids }])
end
JSON.dump(default_with_filter)
end
end
def initialize(selected_project_ids)
@selected_project_ids = selected_project_ids
end
def call
# Read the raw query_props from the settings (filters and columns still serialized)
params = params_from_settings.dup
# Delete the parent filter
params['f'] =
if params['f']
params['f'].reject { |filter| filter['n'] == 'project' }
else
[]
end
# Ensure grouped by project
params['g'] = 'project'
params['hi'] = false
# Ensure timeline visible
params['tv'] = true
# Add the parent filter
params['f'] << { 'n' => 'project', 'o' => '=', 'v' => selected_project_ids }
params.to_json
end
private
def params_from_settings
JSON.parse(self.class.current_query)
rescue JSON::JSONError => e
Rails.logger.error "Failed to read project gantt view, resetting to default. Error was: #{e.message}"
Setting.project_gantt_query = self.class.default_gantt_query
JSON.parse(self.class.default_gantt_query)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Projects::GanttQueryGeneratorService, type: :model do
let(:selected) { %w[1 2 3] }
let(:instance) { described_class.new selected }
let(:subject) { instance.call }
let(:json) { JSON.parse(subject) }
let(:milestone_ids) { [123, 234] }
let(:default_json) do
scope = double('scope')
allow(Type)
.to receive(:milestone)
.and_return(scope)
allow(scope)
.to receive(:pluck)
.with(:id)
.and_return(milestone_ids)
JSON
.parse(Projects::GanttQueryGeneratorService::DEFAULT_GANTT_QUERY)
.merge('f' => [{ 'n' => 'type', 'o' => '=', 'v' => milestone_ids.map(&:to_s) }])
end
def build_project_filter(ids)
{ 'n' => 'project', 'o' => '=', 'v' => ids }
end
context 'with empty setting' do
before do
Setting.project_gantt_query = ''
end
it 'uses the default' do
expected = default_json.deep_dup
expected['f'] << build_project_filter(selected)
expect(json).to eq(expected)
end
context 'without configured milestones' do
let(:milestone_ids) { [] }
it 'uses the default but without the type filter' do
expected = default_json
.deep_dup
.merge('f' => [build_project_filter(selected)])
expect(json).to eq(expected)
end
end
end
context 'with existing filter' do
it 'overrides the filter' do
Setting.project_gantt_query = default_json.deep_dup.merge('f' => [build_project_filter(%w[other values])]).to_json
expected = default_json.deep_dup.merge('f' => [build_project_filter(selected)])
expect(json).to eq(expected)
end
end
context 'with invalid json' do
it 'returns the default' do
Setting.project_gantt_query = 'invalid!1234'
expected = default_json.deep_dup
expected['f'] << build_project_filter(selected)
expect(json).to eq(expected)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Queries::UpdateService < BaseServices::Update; end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe Queries::UpdateService do
it_behaves_like 'BaseServices update service'
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Queries::CreateService < BaseServices::Create; end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Queries::CreateService do
let(:user) { build_stubbed(:admin) }
let(:instance) { described_class.new(user:) }
subject { instance.call(params).result }
describe 'ordered work packages' do
let!(:work_package) { create(:work_package) }
let(:params) do
{
name: 'My query',
ordered_work_packages: {
work_package.id => 0,
9999 => 1
}
}
end
it 'removes items for which work packages do not exist' do
expect(subject).to be_valid
expect(subject.ordered_work_packages.length).to eq 1
expect(subject.ordered_work_packages.first.work_package_id).to eq work_package.id
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module CustomFields
class SetAttributesService < ::BaseServices::SetAttributes
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe CustomFields::SetAttributesService, type: :model do
let(:user) { build_stubbed(:user) }
let(:contract_instance) do
contract = double('contract_instance')
allow(contract)
.to receive(:validate)
.and_return(contract_valid)
allow(contract)
.to receive(:errors)
.and_return(contract_errors)
contract
end
let(:contract_errors) { double('contract_errors') }
let(:contract_valid) { true }
let(:cf_valid) { true }
let(:instance) do
described_class.new(user:,
model: cf_instance,
contract_class:,
contract_options: {})
end
let(:cf_instance) { ProjectCustomField.new }
let(:contract_class) do
allow(CustomFields::CreateContract)
.to receive(:new)
.with(cf_instance, user, options: {})
.and_return(contract_instance)
CustomFields::CreateContract
end
let(:params) { {} }
before do
allow(cf_instance)
.to receive(:valid?)
.and_return(cf_valid)
end
subject { instance.call(params) }
it 'returns the cf instance as the result' do
expect(subject.result)
.to eql cf_instance
end
it 'is a success' do
expect(subject)
.to be_success
end
context 'with params' do
let(:params) do
{
name: 'Foobar'
}
end
let(:expected) do
{
name: 'Foobar'
}.with_indifferent_access
end
it 'assigns the params' do
subject
attributes_of_interest = cf_instance
.attributes
.slice(*expected.keys)
expect(attributes_of_interest)
.to eql(expected)
end
end
context 'with an invalid contract' do
let(:contract_valid) { false }
let(:expect_time_instance_save) do
expect(cf_instance)
.not_to receive(:save)
end
it 'returns failure' do
expect(subject)
.not_to be_success
end
it "returns the contract's errors" do
expect(subject.errors)
.to eql(contract_errors)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module CustomFields
class UpdateService < ::BaseServices::Update
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe CustomFields::UpdateService, type: :model do
it_behaves_like 'BaseServices update service'
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module CustomFields
class CreateService < ::BaseServices::Create
def self.careful_new_custom_field(type)
if /.+CustomField\z/.match?(type.to_s)
klass = type.to_s.constantize
klass.new if klass.ancestors.include? CustomField
end
rescue NameError => e
Rails.logger.error "#{e.message}:\n#{e.backtrace.join("\n")}"
nil
end
def perform(params)
super
rescue StandardError => e
ServiceResult.failure(message: e.message)
end
def instance(params)
cf = self.class.careful_new_custom_field(params[:type])
raise ArgumentError.new("Invalid CF type") unless cf
cf
end
def after_perform(call)
cf = call.result
if cf.is_a?(ProjectCustomField)
add_cf_to_visible_columns(cf)
end
call
end
private
def add_cf_to_visible_columns(custom_field)
Setting.enabled_projects_columns = (Setting.enabled_projects_columns + [custom_field.column_name]).uniq
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_create_service'
RSpec.describe CustomFields::CreateService, type: :model do
it_behaves_like 'BaseServices create service' do
context 'when creating a project cf' do
let(:model_instance) { build_stubbed(:project_custom_field) }
it 'modifies the settings on successful call' do
subject
expect(Setting.enabled_projects_columns).to include(model_instance.column_name)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Roles
class SetAttributesService < ::BaseServices::SetAttributes
def set_attributes(params)
super(params)
if model.is_a?(ProjectRole)
model.permissions += OpenProject::AccessControl.public_permissions.map(&:name)
end
end
def set_default_attributes(*)
model.permissions = ProjectRole.non_member.permissions if model.permissions.blank? && model.is_a?(ProjectRole)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Roles::SetAttributesService, type: :model do
let(:current_user) { build_stubbed(:admin) }
let(:contract_instance) do
contract = instance_double(Roles::CreateContract, 'contract_instance')
allow(contract).to receive(:validate).and_return(contract_valid)
allow(contract).to receive(:errors).and_return(contract_errors)
contract
end
let(:contract_errors) { instance_double(ActiveModel::Errors, 'contract_errors') }
let(:contract_valid) { true }
let(:model_valid) { true }
let(:instance) do
described_class.new(user: current_user, model: model_instance, contract_class:, contract_options: {})
end
let(:model_instance) { ProjectRole.new }
let(:contract_class) do
allow(Roles::CreateContract).to receive(:new).and_return(contract_instance)
Roles::CreateContract
end
let(:params) { {} }
let(:permissions) { %i[view_work_packages view_wiki_pages] }
before do
allow(model_instance).to receive(:valid?).and_return(model_valid)
end
subject { instance.call(params) }
it 'returns the instance as the result' do
expect(subject.result).to eql model_instance
end
it 'is a success' do
expect(subject).to be_success
end
context 'with params' do
let(:params) do
{
permissions:
}
end
before do
create(:non_member, permissions: %i[view_meetings view_wiki_pages])
subject
end
context 'with a ProjectRole' do
it 'assigns the params with the public permissions' do
expect(model_instance.permissions).to match_array(OpenProject::AccessControl.public_permissions.map(&:name) + permissions)
end
context 'when no permissions are given' do
let(:permissions) { [] }
it 'assigns the permissions the non member role has' do
expect(model_instance.permissions).to match_array(ProjectRole.non_member.permissions) # public permissions are included via the factory
end
end
end
context 'with a GlobalRole' do
let(:model_instance) { GlobalRole.new }
it 'assigns the params' do
expect(model_instance.permissions).to match_array(permissions)
end
context 'when no permissions are given' do
let(:permissions) { [] }
it 'assigns nothing' do
expect(model_instance.permissions).to be_empty
end
end
end
context 'with a WorkPackageRole' do
let(:model_instance) { WorkPackageRole.new }
it 'assigns the params' do
expect(model_instance.permissions).to match_array(permissions)
end
context 'when no permissions are given' do
let(:permissions) { [] }
it 'assigns nothing' do
expect(model_instance.permissions).to be_empty
end
end
end
end
context 'with an invalid contract' do
let(:contract_valid) { false }
it 'returns failure' do
expect(subject).not_to be_success
end
it "returns the contract's errors" do
expect(subject.errors)
.to eql(contract_errors)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Roles::UpdateService < BaseServices::Update
private
def before_perform(params, service_call)
@permissions_old = service_call.result.permissions
super
end
def after_perform(call)
permissions_new = call.result.permissions
permissions_diff = (@permissions_old - permissions_new) | (permissions_new - @permissions_old)
OpenProject::Notifications.send(
OpenProject::Events::ROLE_UPDATED,
permissions_diff:
)
call
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe Roles::UpdateService, type: :model do
it_behaves_like 'BaseServices update service' do
let(:factory) { :project_role }
end
it 'sends an update notification' do
allow(OpenProject::Notifications).to receive(:send)
existing_permissions = %i[view_files view_work_packages
view_calender] + OpenProject::AccessControl.public_permissions.map(&:name)
added_permissions = %i[write_files view_wiki_pages]
role = create(:project_role, permissions: existing_permissions)
params = { permissions: existing_permissions + added_permissions }
described_class.new(user: create(:user), model: role).call(params)
expect(OpenProject::Notifications).to have_received(:send).with(
OpenProject::Events::ROLE_UPDATED,
permissions_diff: added_permissions
)
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Roles::DeleteService < BaseServices::Delete
def persist(service_result)
# after destroy permissions can not be reached
@permissions = model.permissions
super(service_result)
end
protected
def after_perform(service_call)
super(service_call).tap do |_call|
::OpenProject::Notifications.send(
::OpenProject::Events::ROLE_DESTROYED,
permissions: @permissions
)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_delete_service'
RSpec.describe Roles::DeleteService, type: :model do
it_behaves_like 'BaseServices delete service' do
let(:factory) { :project_role }
end
it 'sends a delete notification' do
allow(OpenProject::Notifications).to(receive(:send))
existing_permissions = %i[view_files view_work_packages view_calender]
role = create(:project_role, permissions: existing_permissions)
result = described_class
.new(user: create(:user, admin: true), model: role)
.call(permissions: existing_permissions)
expect(result).to be_success
expect(OpenProject::Notifications).to have_received(:send).with(
OpenProject::Events::ROLE_DESTROYED,
permissions: existing_permissions + OpenProject::AccessControl.public_permissions.map(&:name)
)
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Groups
class SetAttributesService < ::BaseServices::SetAttributes
private
def set_attributes(params)
set_users(params) if params.key?(:user_ids)
super
end
# We do not want to persist the associated users (members) in a
# SetAttributesService. Therefore we are building the association here.
#
# Note that due to the way we handle members, via a specific AddUsersService
# the group should no longer simply be saved after group_users have been added.
def set_users(params)
user_ids = (params.delete(:user_ids) || []).map(&:to_i)
existing_user_ids = model.group_users.map(&:user_id)
build_new_users user_ids - existing_user_ids
mark_outdated_users existing_user_ids - user_ids
end
def build_new_users(new_user_ids)
new_user_ids.each do |id|
model.group_users.build(user_id: id)
end
end
def mark_outdated_users(removed_user_ids)
removed_user_ids.each do |id|
model.group_users.find { |gu| gu.user_id == id }.mark_for_destruction
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Groups::SetAttributesService, type: :model do
subject(:service_call) { instance.call(call_attributes) }
let(:user) { build_stubbed(:user) }
let(:contract_class) do
contract = double('contract_class')
allow(contract)
.to receive(:new)
.with(group, user, options: {})
.and_return(contract_instance)
contract
end
let(:contract_instance) do
instance_double(ModelContract, validate: contract_valid, errors: contract_errors)
end
let(:contract_valid) { true }
let(:contract_errors) do
instance_double(ActiveRecord::ActiveRecordError)
end
let(:group_valid) { true }
let(:instance) do
described_class.new(user:,
model: group,
contract_class:)
end
let(:call_attributes) { {} }
let(:group) do
build_stubbed(:group) do |g|
# To later check that it has not been called
allow(g)
.to receive(:save)
end
end
describe 'call' do
let(:call_attributes) do
{
name: 'The name'
}
end
before do
allow(group)
.to receive(:valid?)
.and_return(group_valid)
allow(contract_instance)
.to receive(:validate)
.and_return(contract_valid)
end
it 'is successful' do
expect(service_call)
.to be_success
end
it 'sets the attributes' do
service_call
expect(group.lastname)
.to eql call_attributes[:name]
end
it 'does not persist the group' do
service_call
expect(group)
.not_to have_received(:save)
end
context 'with no changes to the users' do
let(:call_attributes) do
{
name: 'My new group name'
}
end
let(:first_user) { build_stubbed(:user) }
let(:second_user) { build_stubbed(:user) }
let(:first_group_user) { build_stubbed(:group_user, user: first_user) }
let(:second_group_user) { build_stubbed(:group_user, user: second_user) }
let(:group) do
build_stubbed(:group, group_users: [first_group_user, second_group_user])
end
let(:updated_group) do
service_call.result
end
it 'does not change the users (Regression #38017)' do
expect(updated_group.name).to eq 'My new group name'
expect(updated_group.group_users.map(&:user_id))
.to eql [first_user.id, second_user.id]
expect(updated_group.group_users.any?(&:marked_for_destruction?)).to be false
end
end
context 'with changes to the users do' do
let(:first_user) { build_stubbed(:user) }
let(:second_user) { build_stubbed(:user) }
let(:third_user) { build_stubbed(:user) }
let(:call_attributes) do
{
user_ids: [second_user.id, third_user.id]
}
end
shared_examples_for 'updates the users' do
let(:first_group_user) { build_stubbed(:group_user, user: first_user) }
let(:second_group_user) { build_stubbed(:group_user, user: second_user) }
let(:group) do
build_stubbed(:group, group_users: [first_group_user, second_group_user])
end
it 'adds the new users' do
expect(service_call.result.group_users.map(&:user_id))
.to eql [first_user.id, second_user.id, third_user.id]
end
it 'does not persist the new association' do
expect(service_call.result.group_users.find { |gu| gu.user_id == third_user.id })
.to be_new_record
end
it 'keeps the association already existing before' do
expect(service_call.result.group_users.find { |gu| gu.user_id == second_user.id })
.not_to be_marked_for_destruction
end
it 'marks not mentioned users to be removed' do
expect(service_call.result.group_users.find { |gu| gu.user_id == first_user.id })
.to be_marked_for_destruction
end
end
context 'with a persisted record and integer values' do
let(:call_attributes) do
{
user_ids: [second_user.id, third_user.id]
}
end
it_behaves_like 'updates the users'
end
context 'with a persisted record and string values' do
let(:call_attributes) do
{
user_ids: [second_user.id.to_s, third_user.id.to_s]
}
end
it_behaves_like 'updates the users'
end
context 'with a new record' do
let(:group) do
Group.new
end
it 'sets the user' do
expect(service_call.result.group_users.map(&:user_id))
.to eql [second_user.id, third_user.id]
end
it 'does not persist the association' do
expect(service_call.result.group_users.all(&:new_record?))
.to be_truthy
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Groups::UpdateService < BaseServices::Update
protected
def persist(call)
removed_users = groups_removed_users(call.result)
member_roles = member_roles_to_prune(removed_users)
project_ids = member_roles.pluck(:project_id)
member_role_ids = member_roles.pluck(:id)
call = super
remove_member_roles(member_role_ids)
cleanup_members(removed_users, project_ids)
call
end
def after_perform(call)
new_user_ids = call.result.group_users.select(&:saved_changes?).map(&:user_id)
if new_user_ids.any?
db_call = ::Groups::AddUsersService
.new(call.result, current_user: user)
.call(ids: new_user_ids)
call.add_dependent!(db_call)
end
call
end
def groups_removed_users(group)
group.group_users.select(&:marked_for_destruction?).filter_map(&:user)
end
def remove_member_roles(member_role_ids)
::Groups::CleanupInheritedRolesService
.new(model, current_user: user)
.call(member_role_ids:)
end
def member_roles_to_prune(users)
return MemberRole.none if users.empty?
MemberRole
.includes(member: :member_roles)
.where(inherited_from: model.members.joins(:member_roles).select('member_roles.id'))
.where(members: { user_id: users.map(&:id) })
end
def cleanup_members(users, project_ids)
Members::CleanupService
.new(users, project_ids)
.call
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe Groups::UpdateService, type: :model do
it_behaves_like 'BaseServices update service' do
let(:add_service_result) do
ServiceResult.success
end
let!(:add_users_service) do
add_service = instance_double(Groups::AddUsersService)
allow(Groups::AddUsersService)
.to receive(:new)
.with(model_instance, current_user: user)
.and_return(add_service)
allow(add_service)
.to receive(:call)
.and_return(add_service_result)
add_service
end
context 'with newly created group_users' do
let(:old_group_user) { build_stubbed(:group_user, user_id: 3) }
let(:new_group_user) do
build_stubbed(:group_user, user_id: 5).tap do |gu|
allow(gu)
.to receive(:saved_changes?)
.and_return(true)
end
end
let(:group_users) { [old_group_user, new_group_user] }
before do
allow(model_instance)
.to receive(:group_users)
.and_return(group_users)
end
context 'with the AddUsersService being successful' do
it 'is successful' do
expect(instance_call).to be_success
end
it 'calls the AddUsersService' do
instance_call
expect(add_users_service)
.to have_received(:call)
.with(ids: [new_group_user.user_id])
end
end
context 'with the AddUsersService being unsuccessful' do
let(:add_service_result) do
ServiceResult.failure
end
it 'is failure' do
expect(instance_call).to be_failure
end
it 'calls the AddUsersService' do
instance_call
expect(add_users_service)
.to have_received(:call)
.with(ids: [new_group_user.user_id])
end
end
context 'without any new group_users' do
let(:group_users) { [old_group_user] }
it 'is successful' do
expect(instance_call).to be_success
end
it 'does not call the AddUsersService' do
instance_call
expect(add_users_service)
.not_to have_received(:call)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module UserPreferences
class UpdateService < ::BaseServices::Update
protected
attr_accessor :notifications
def validate_params(params)
contract = ParamsContract.new(model, user, params:)
ServiceResult.new success: contract.valid?,
errors: contract.errors,
result: model
end
def before_perform(params, _service_result)
self.notifications = params&.delete(:notification_settings)
super
end
def after_perform(service_call)
return service_call if notifications.nil?
inserted = persist_notifications
remove_other_notifications(inserted)
service_call
end
def persist_notifications
global, project = notifications
.map { |item| item.merge(user_id: model.user_id) }
.partition { |setting| setting[:project_id].nil? }
global_ids = upsert_notifications(global, %i[user_id], 'project_id IS NULL')
project_ids = upsert_notifications(project, %i[user_id project_id], 'project_id IS NOT NULL')
global_ids + project_ids
end
def remove_other_notifications(ids)
NotificationSetting
.where(user_id: model.user_id)
.where.not(id: ids)
.delete_all
end
##
# Upsert notification while respecting the partial index on notification_settings
# depending on the project presence
#
# @param notifications The array of notification hashes to upsert
# @param conflict_target The uniqueness constraint to upsert within
# @param index_predicate The partial index condition on the project
def upsert_notifications(notifications, conflict_target, index_predicate)
return [] if notifications.empty?
NotificationSetting
.import(
notifications,
on_duplicate_key_update: {
conflict_target:,
index_predicate:,
columns: %i[watched
assignee
responsible
shared
mentioned
start_date
due_date
overdue
work_package_commented
work_package_created
work_package_processed
work_package_prioritized
work_package_scheduled
news_added
news_commented
document_added
forum_messages
wiki_page_added
wiki_page_updated
membership_added
membership_updated]
},
validate: false
).ids
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe UserPreferences::UpdateService, type: :model do
it_behaves_like 'BaseServices update service' do
let(:params_success) { true }
let(:params_errors) { ActiveModel::Errors.new({}) }
let(:params_contract) do
instance_double(UserPreferences::ParamsContract, valid?: params_success, errors: params_errors)
end
before do
allow(UserPreferences::ParamsContract).to receive(:new).and_return(params_contract)
end
context 'when the params contract is invalid' do
let(:params_success) { false }
it 'returns that error' do
expect(subject).to be_failure
expect(subject.errors).to eq(params_errors)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Users
class SetAttributesService < ::BaseServices::SetAttributes
include ::HookHelper
private
attr_accessor :pref
def set_attributes(params)
self.pref = params.delete(:pref)
super(params)
end
def validate_and_result
super.tap do |result|
result.merge!(set_preferences) if pref.present?
end
end
def set_default_attributes(params)
# Assign values other than mail to new_user when invited
assign_name_attributes_from_mail(params) if model.invited? && model.valid_attribute?(:mail)
assign_default_language
model.notification_settings.build unless model.notification_settings.any?
end
def set_preferences
::UserPreferences::SetAttributesService
.new(user:, model: model.pref, contract_class: ::UserPreferences::UpdateContract)
.call(pref)
end
# rubocop:disable Metrics/AbcSize
def assign_name_attributes_from_mail(params)
placeholder = placeholder_name(params[:mail])
model.login = model.login.presence || params[:mail]
model.firstname = model.firstname.presence || placeholder.first
model.lastname = model.lastname.presence || placeholder.last
end
# rubocop:enable Metrics/AbcSize
def assign_default_language
model.language = model.language.presence || Setting.default_language
end
##
# Creates a placeholder name for the user based on their email address.
# For the unlikely case that the local or domain part of the email address
# are longer than 30 characters they will be trimmed to 27 characters and an
# ellipsis will be appended.
def placeholder_name(email)
first, last = email.split('@').map { |name| trim_name(name) }
[first, "@#{last}"]
end
def trim_name(name)
if name.size > 30
"#{name[0..26]}..."
else
name
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Users::SetAttributesService, type: :model do
subject(:call) { instance.call(params) }
let(:current_user) { build_stubbed(:user) }
let(:contract_instance) do
contract = double('contract_instance')
allow(contract)
.to receive(:validate)
.and_return(contract_valid)
allow(contract)
.to receive(:errors)
.and_return(contract_errors)
contract
end
let(:contract_errors) { double('contract_errors') }
let(:contract_valid) { true }
let(:model_valid) { true }
let(:instance) do
described_class.new(user: current_user,
model: model_instance,
contract_class:,
contract_options: {})
end
let(:model_instance) { User.new }
let(:contract_class) do
allow(Users::CreateContract)
.to receive(:new)
.and_return(contract_instance)
Users::CreateContract
end
let(:params) { {} }
before do
allow(model_instance)
.to receive(:valid?)
.and_return(model_valid)
end
context 'for a new record' do
let(:model_instance) do
User.new
end
it 'is successful' do
expect(call)
.to be_success
end
it 'returns the instance as the result' do
expect(call.result)
.to eql model_instance
end
it 'initializes the notification settings' do
expect(call.result.notification_settings.length)
.to be 1
expect(call.result.notification_settings)
.to(all(be_a(NotificationSetting).and(be_new_record)))
end
it 'sets the default language', with_settings: { default_language: 'de' } do
call
expect(model_instance.language)
.to eql 'de'
end
context 'with params' do
let(:params) do
{
firstname: 'Foo',
lastname: 'Bar'
}
end
it 'assigns the params' do
call
expect(model_instance.firstname).to eq 'Foo'
expect(model_instance.lastname).to eq 'Bar'
end
end
context 'with attributes for the user`s preferences' do
let(:params) do
{
pref: {
auto_hide_popups: true
}
}
end
it 'initializes the user`s preferences with those attributes' do
expect(call.result.pref)
.to be_auto_hide_popups
end
end
end
context 'with an invalid contract' do
let(:contract_valid) { false }
let(:expect_time_instance_save) do
expect(model_instance)
.not_to receive(:save)
end
it 'returns failure' do
expect(subject)
.not_to be_success
end
it "returns the contract's errors" do
expect(call.errors)
.to eql(contract_errors)
end
end
describe '.placeholder_name' do
it 'given an email it uses the local part as first and the domain as the last name' do
email = '[email protected]'
first, last = instance.send(:placeholder_name, email)
expect(first).to eq 'xxxhunterxxx'
expect(last).to eq '@openproject.com'
end
it 'trims names if they are too long (> 30 characters)' do
email = 'hallowurstsalatgetraenkebuechse@veryopensuchproject.openproject.com'
first, last = instance.send(:placeholder_name, email)
expect(first).to eq 'hallowurstsalatgetraenkebue...'
expect(last).to eq '@veryopensuchproject.openpro...'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Users
class LogoutService
attr_accessor :controller, :cookies
def initialize(controller:)
self.controller = controller
self.cookies = controller.send(:cookies)
end
def call!(user)
OpenProject.logger.info { "Logging out ##{user.id}" }
if OpenProject::Configuration.drop_old_sessions_on_logout?
remove_all_autologin_tokens! user
remove_all_sessions! user
else
remove_matching_autologin_token! user
end
controller.reset_session
User.current = User.anonymous
end
private
def remove_all_sessions!(user)
::Sessions::UserSession.for_user(user.id).delete_all
end
def remove_all_autologin_tokens!(user)
cookies.delete(OpenProject::Configuration.autologin_cookie_name)
Token::AutoLogin.where(user_id: user.id).delete_all
end
def remove_matching_autologin_token!(user)
value = cookies.delete(OpenProject::Configuration.autologin_cookie_name)
return if value.blank?
Token::AutoLogin
.where(user:)
.find_by_plaintext_value(value)&.destroy
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Users::LogoutService, type: :model do
shared_let(:user) { create(:user) }
let(:request) { {} }
let(:browser) do
instance_double(Browser::Safari,
name: 'Safari',
version: '13.2',
platform: instance_double(Browser::Platform::Linux, name: 'Linux'))
end
let(:cookies) { {} }
let(:controller) { instance_double(ApplicationController, browser:, cookies:) }
let(:instance) { described_class.new(controller:) }
subject { instance.call!(user) }
before do
allow(controller).to(receive(:reset_session))
end
describe 'User.current' do
it 'resets it' do
User.current = user
subject
expect(User.current).to eq User.anonymous
end
end
describe 'delete other sessions on destroy' do
let!(:sessions) { create_list(:user_session, 2, user:) }
let!(:other_session) { create(:user_session) }
context 'when config is enabled',
with_config: { drop_old_sessions_on_logout: true } do
it 'destroys both sessions' do
expect(Sessions::UserSession.count).to eq(3)
expect(Sessions::UserSession.for_user(user).count).to eq(2)
subject
expect(Sessions::UserSession.count).to eq(1)
expect(Sessions::UserSession.for_user(user).count).to eq(0)
end
describe 'autologin cookie' do
let!(:token) { create(:autologin_token, user:) }
let!(:other_token) { create(:autologin_token, user:) }
it 'removes all autologin tokens' do
cookies[OpenProject::Configuration.autologin_cookie_name] = token.plain_value
subject
expect(cookies[OpenProject::Configuration.autologin_cookie_name]).to be_nil
expect { token.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect { other_token.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect(Token::AutoLogin.where(user_id: user.id)).to be_empty
end
end
end
context 'when config is disabled',
with_config: { drop_old_sessions_on_logout: false } do
it 'destroys none of the existing sessions' do
expect(Sessions::UserSession.count).to eq(3)
expect(Sessions::UserSession.for_user(user).count).to eq(2)
subject
expect(Sessions::UserSession.count).to eq(3)
expect(Sessions::UserSession.for_user(user).count).to eq(2)
end
describe 'autologin cookie' do
let!(:token) { create(:autologin_token, user:) }
let!(:other_token) { create(:autologin_token, user:) }
it 'removes the matching autologin cookie and token' do
cookies[OpenProject::Configuration.autologin_cookie_name] = token.plain_value
subject
expect(cookies[OpenProject::Configuration.autologin_cookie_name]).to be_nil
expect { token.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect(Token::AutoLogin.where(user_id: user.id).all).to contain_exactly other_token
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Users
class UpdateService < ::BaseServices::Update
include ::HookHelper
protected
def before_perform(params, _service_result)
call_hook :service_update_user_before_save,
params:,
user: model
super
end
def persist(service_result)
service_result = super(service_result)
if service_result.success?
service_result.success = model.pref.save
end
service_result
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe Users::UpdateService do
it_behaves_like 'BaseServices update service' do
# The user service also tries to save the preferences
before do
allow(model_instance.pref).to receive(:save).and_return(true)
end
end
describe 'updating attributes' do
let(:instance) { described_class.new(model: update_user, user: current_user) }
let(:current_user) { create(:admin) }
let(:update_user) { create(:user, mail: '[email protected]') }
subject { instance.call(attributes:) }
context 'when invalid' do
let(:attributes) { { mail: 'invalid' } }
it 'fails to update' do
expect(subject).not_to be_success
update_user.reload
expect(update_user.mail).to eq('[email protected]')
expect(subject.errors.symbols_for(:mail)).to match_array(%i[email])
end
end
context 'when valid' do
let(:attributes) { { mail: '[email protected]' } }
it 'updates the user' do
expect(subject).to be_success
update_user.reload
expect(update_user.mail).to eq('[email protected]')
end
context 'if current_user is no admin' do
let(:current_user) { build_stubbed(:user) }
it 'is unsuccessful' do
expect(subject).not_to be_success
end
end
end
context 'when valid status' do
let(:attributes) { { status: Principal.statuses[:locked] } }
it 'updates the user' do
expect(subject).to be_success
update_user.reload
expect(update_user).to be_locked
end
context 'if current_user is no admin' do
let(:current_user) { build_stubbed(:user) }
it 'is unsuccessful' do
expect(subject).not_to be_success
end
end
end
describe 'updating prefs' do
let(:attributes) { {} }
before do
allow(update_user).to receive(:save).and_return(user_save_result)
end
context 'if the user was updated calls the prefs' do
let(:user_save_result) { true }
before do
expect(update_user.pref).to receive(:save).and_return(pref_save_result)
end
context 'and the prefs can be saved' do
let(:pref_save_result) { true }
it 'returns a successful call' do
expect(subject).to be_success
end
end
context 'and the prefs can not be saved' do
let(:pref_save_result) { false }
it 'returns an erroneous call' do
expect(subject).not_to be_success
end
end
end
context 'if the user was not saved' do
let(:user_save_result) { false }
it 'does not call #prefs.save' do
expect(update_user.pref).not_to receive(:save)
expect(subject).not_to be_success
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Users
class ChangePasswordService
attr_accessor :current_user, :session
def initialize(current_user:, session:)
@current_user = current_user
@session = session
end
def call(params)
User.execute_as current_user do
current_user.password = params[:new_password]
current_user.password_confirmation = params[:new_password_confirmation]
current_user.force_password_change = false
current_user.activate if current_user.invited?
if current_user.save
invalidate_recovery_tokens
invalidate_invitation_tokens
log_success
::ServiceResult.new success: true,
result: current_user,
**invalidate_session_result
else
log_failure
::ServiceResult.new success: false,
result: current_user,
message: I18n.t(:error_password_change_failed),
errors: current_user.errors
end
end
end
private
def invalidate_recovery_tokens
Token::Recovery.where(user: current_user).delete_all
end
def invalidate_invitation_tokens
Token::Invitation.where(user: current_user).delete_all
end
def invalidate_session_result
update_message = I18n.t(:notice_account_password_updated)
if ::Sessions::DropOtherSessionsService.call(current_user, session)
expiry_message = I18n.t(:notice_account_other_session_expired)
{ message_type: :info, message: "#{update_message} #{expiry_message}" }
else
{ message: update_message }
end
end
def log_success
Rails.logger.info do
"User #{current_user.login} changed password successfully."
end
end
def log_failure
Rails.logger.info do
"User #{current_user.login} failed password change: #{current_user.errors.full_messages.join(', ')}."
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
RSpec.describe Users::ChangePasswordService do
let(:user) do
create(:invited_user,
password: old_password,
password_confirmation: old_password)
end
let(:old_password) { 'AdminAdmin42' }
let(:new_password) { 'SoreThroat33' }
let(:session) { ActionController::TestSession.new }
let(:instance) { described_class.new current_user: user, session: }
let(:result) do
instance.call new_password:, new_password_confirmation: new_password
end
it 'is successful' do
expect(result).to be_success
end
it "changes the user's password" do
result
expect(user.check_password?(old_password)).to be false
expect(user.check_password?(new_password)).to be true
end
describe 'activating the user' do
context 'when the user is "invited"' do
it 'activates the user' do
result
expect(user).to be_active
end
end
context 'when the user is not "invited"' do
let(:user) do
create(:locked_user,
password: old_password,
password_confirmation: old_password)
end
it 'does not activate the user' do
result
expect(user).not_to be_active
end
end
end
context 'with existing invitation tokens' do
let!(:invitation_token) { create(:invitation_token, user:) }
it 'invalidates the existing token' do
expect(result).to be_success
expect(Token::Invitation.where(user:)).to be_empty
end
end
context 'with existing password recovery tokens' do
let!(:recovery_token) { create(:recovery_token, user:) }
it 'invalidates the existing tokens' do
expect(result).to be_success
expect(Token::Recovery.where(user:)).to be_empty
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Users
class RegisterUserService
attr_reader :user
def initialize(user)
@user = user
end
def call
%i[
ensure_user_limit_not_reached!
register_invited_user
register_ldap_user
ensure_provider_not_limited!
register_omniauth_user
ensure_registration_allowed!
register_by_email_activation
register_automatically
register_manually
fail_activation
].each do |m|
result = send(m)
return result if result.is_a?(ServiceResult)
end
rescue StandardError => e
Rails.logger.error { "User #{user.login} failed to activate #{e}." }
ServiceResult.failure(result: user, message: I18n.t(:notice_activation_failed))
end
private
##
# Check whether the associated single sign-on providers
# allows for automatic activation of new users
def ensure_provider_not_limited!
if limited_provider?(user) && Setting::SelfRegistration.disabled?
name = provider_name(user)
ServiceResult.failure(result: user, message: I18n.t('account.error_self_registration_limited_provider', name:))
end
end
##
# Check whether the system allows registration
# for non-invited users
def ensure_registration_allowed!
if Setting::SelfRegistration.disabled?
ServiceResult.failure(result: user, message: I18n.t('account.error_self_registration_disabled'))
end
end
##
# Ensure the user limit is not reached
def ensure_user_limit_not_reached!
if OpenProject::Enterprise.user_limit_reached?
OpenProject::Enterprise.send_activation_limit_notification_about user
ServiceResult.failure(result: user, message: I18n.t(:error_enterprise_activation_user_limit))
end
end
##
# Try to register an invited user
# bypassing regular restrictions
def register_invited_user
return unless user.invited?
user.activate
with_saved_user_result(success_message: I18n.t(:notice_account_registered_and_logged_in)) do
Rails.logger.info { "User #{user.login} was successfully activated after invitation." }
end
end
##
# Try to register a user with an auth source connection
# bypassing regular account registration restrictions
def register_ldap_user
return if user.ldap_auth_source_id.blank?
user.activate
with_saved_user_result(success_message: I18n.t(:notice_account_registered_and_logged_in)) do
Rails.logger.info { "User #{user.login} was successfully activated with LDAP association after invitation." }
end
end
##
# Try to register a user with an existsing omniauth connection
# bypassing regular account registration restrictions
def register_omniauth_user
return if skip_omniauth_user?
return if limited_provider?(user)
user.activate
with_saved_user_result(success_message: I18n.t(:notice_account_registered_and_logged_in)) do
Rails.logger.info { "User #{user.login} was successfully activated after arriving from omniauth." }
end
end
def skip_omniauth_user?
user.identity_url.blank?
end
def limited_provider?(user)
provider = provider_name(user)
return false if provider.blank?
OpenProject::Plugins::AuthPlugin.limit_self_registration?(provider:)
end
def provider_name(user)
user.authentication_provider&.downcase
end
def register_by_email_activation
return unless Setting::SelfRegistration.by_email?
user.register
with_saved_user_result(success_message: I18n.t(:notice_account_register_done)) do
token = Token::Invitation.create!(user:)
UserMailer.user_signed_up(token).deliver_later
Rails.logger.info { "Scheduled email activation mail for #{user.login}" }
end
end
# Automatically register a user
#
# Pass a block for behavior when a user fails to save
def register_automatically
return unless Setting::SelfRegistration.automatic?
user.activate
with_saved_user_result do
Rails.logger.info { "User #{user.login} was successfully activated." }
end
end
def register_manually
user.register
with_saved_user_result(success_message: I18n.t(:notice_account_pending)) do
# Sends an email to the administrators
admins = User.admin.active
admins.each do |admin|
UserMailer.account_activation_requested(admin, user).deliver_later
end
Rails.logger.info { "User #{user.login} was successfully created and is pending admin activation." }
end
end
def fail_activation
Rails.logger.error { "User #{user.login} could not be activated, all options were exhausted." }
ServiceResult.failure(message: I18n.t(:notice_activation_failed))
end
##
# Try to save result, return it in case of errors
# and add a user error to make sure we can render the account registration form
def with_saved_user_result(success_message: I18n.t(:notice_account_activated))
if user.save
yield if block_given?
return ServiceResult.success(result: user, message: success_message)
end
ServiceResult.failure.tap do |call|
# Avoid using the errors from the user
call.result = user
call.errors.add(:base, I18n.t(:notice_activation_failed), error: :failed_to_activate)
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
RSpec.describe Users::RegisterUserService do
let(:user) { build(:user) }
let(:instance) { described_class.new(user) }
let(:call) { instance.call }
def with_all_registration_options(except: [])
Setting::SelfRegistration.values.each do |name, value|
next if Array(except).include? name
allow(Setting).to receive(:self_registration).and_return(value)
yield name
end
end
describe '#register_invited_user' do
it 'tries to activate that user regardless of settings' do
with_all_registration_options do |_type|
user = User.new(status: Principal.statuses[:invited])
instance = described_class.new(user)
expect(user).to receive(:activate)
expect(user).to receive(:save).and_return true
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(call.message).to eq I18n.t(:notice_account_registered_and_logged_in)
end
end
end
describe '#register_ldap_user' do
it 'tries to activate that user regardless of settings' do
with_all_registration_options do |_type|
user = User.new(status: Principal.statuses[:registered])
instance = described_class.new(user)
allow(user).to receive(:ldap_auth_source_id).and_return 1234
expect(user).to receive(:activate)
expect(user).to receive(:save).and_return true
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(call.message).to eq I18n.t(:notice_account_registered_and_logged_in)
end
end
end
describe '#register_omniauth_user' do
let(:user) { User.new(status: Principal.statuses[:registered], identity_url: 'azure:1234') }
let(:instance) { described_class.new(user) }
before do
allow(user).to receive(:activate)
allow(user).to receive(:save).and_return true
# required so that the azure provider is visible (ee feature)
allow(EnterpriseToken).to receive(:show_banners?).and_return false
end
it 'tries to activate that user regardless of settings' do
with_all_registration_options do |_type|
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(call.message).to eq I18n.t(:notice_account_registered_and_logged_in)
end
end
context 'with limit_self_registration enabled and self_registration disabled',
with_settings: {
self_registration: 0,
plugin_openproject_openid_connect: {
providers: {
azure: { identifier: "foo", secret: "bar", limit_self_registration: true }
}
}
} do
it 'fails to activate due to disabled self registration' do
call = instance.call
expect(call).not_to be_success
expect(call.result).to eq user
expect(call.message).to eq I18n.t('account.error_self_registration_limited_provider', name: 'azure')
end
end
context 'with limit_self_registration enabled and self_registration manual',
with_settings: {
self_registration: 2,
plugin_openproject_openid_connect: {
providers: {
azure: { identifier: "foo", secret: "bar", limit_self_registration: true }
}
}
} do
it 'registers the user, but does not activate it' do
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(user).to be_registered
expect(user).not_to have_received(:activate)
expect(call.message).to eq I18n.t(:notice_account_pending)
end
end
context 'with limit_self_registration enabled and self_registration email',
with_settings: {
self_registration: 1,
plugin_openproject_openid_connect: {
providers: {
azure: { identifier: "foo", secret: "bar", limit_self_registration: true }
}
}
} do
it 'registers the user, but does not activate it' do
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(user).to be_registered
expect(user).not_to have_received(:activate)
expect(call.message).to eq I18n.t(:notice_account_register_done)
end
end
context 'with limit_self_registration enabled and self_registration automatic',
with_settings: {
self_registration: 3,
plugin_openproject_openid_connect: {
providers: {
azure: { identifier: "foo", secret: "bar", limit_self_registration: true }
}
}
} do
it 'activates the user' do
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(user).to have_received(:activate)
expect(call.message).to eq I18n.t(:notice_account_activated)
end
end
end
describe '#ensure_registration_allowed!' do
it 'returns an error for disabled' do
allow(Setting).to receive(:self_registration).and_return(0)
user = User.new
instance = described_class.new(user)
expect(user).not_to receive(:activate)
expect(user).not_to receive(:save)
call = instance.call
expect(call.result).to eq user
expect(call.message).to eq I18n.t('account.error_self_registration_disabled')
end
it 'does not return an error for all cases except disabled' do
with_all_registration_options(except: :disabled) do |_type|
user = User.new
instance = described_class.new(user)
# Assuming the next returns a result
expect(instance)
.to(receive(:ensure_user_limit_not_reached!))
.and_return(ServiceResult.failure(result: user, message: 'test stop'))
expect(user).not_to receive(:activate)
expect(user).not_to receive(:save)
call = instance.call
expect(call.result).to eq user
expect(call.message).to eq 'test stop'
end
end
end
describe 'ensure_user_limit_not_reached!',
with_settings: { self_registration: 1 } do
before do
expect(OpenProject::Enterprise)
.to(receive(:user_limit_reached?))
.and_return(limit_reached)
end
context 'when limited' do
let(:limit_reached) { true }
it 'returns an error at that step' do
expect(call).to be_failure
expect(call.result).to eq user
expect(call.message).to eq I18n.t(:error_enterprise_activation_user_limit)
end
end
context 'when not limited' do
let(:limit_reached) { false }
it 'returns no error' do
# Assuming the next returns a result
expect(instance)
.to(receive(:register_by_email_activation))
.and_return(ServiceResult.failure(result: user, message: 'test stop'))
call = instance.call
expect(call.result).to eq user
expect(call.message).to eq 'test stop'
end
end
end
describe '#register_by_email_activation' do
it 'activates the user with mail' do
allow(Setting).to receive(:self_registration).and_return(1)
user = User.new
instance = described_class.new(user)
expect(user).to receive(:register)
expect(user).to receive(:save).and_return true
expect(UserMailer).to receive_message_chain(:user_signed_up, :deliver_later)
expect(Token::Invitation).to receive(:create!).with(user:)
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(call.message).to eq I18n.t(:notice_account_register_done)
end
it 'does not return an error for all cases except disabled' do
with_all_registration_options(except: %i[disabled activation_by_email]) do
user = User.new
instance = described_class.new(user)
# Assuming the next returns a result
expect(instance)
.to(receive(:register_automatically))
.and_return(ServiceResult.failure(result: user, message: 'test stop'))
expect(user).not_to receive(:activate)
expect(user).not_to receive(:save)
call = instance.call
expect(call.result).to eq user
expect(call.message).to eq 'test stop'
end
end
end
describe '#register_automatically' do
it 'activates the user with mail' do
allow(Setting).to receive(:self_registration).and_return(3)
user = User.new
instance = described_class.new(user)
expect(user).to receive(:activate)
expect(user).to receive(:save).and_return true
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(call.message).to eq I18n.t(:notice_account_activated)
end
it 'does not return an error if manual' do
allow(Setting).to receive(:self_registration).and_return(2)
user = User.new
instance = described_class.new(user)
# Assuming the next returns a result
expect(instance)
.to(receive(:register_manually))
.and_return(ServiceResult.failure(result: user, message: 'test stop'))
expect(user).not_to receive(:activate)
expect(user).not_to receive(:save)
call = instance.call
expect(call.result).to eq user
expect(call.message).to eq 'test stop'
end
end
describe '#register_manually' do
let(:admin_stub) { build_stubbed(:admin) }
it 'activates the user with mail' do
allow(User).to receive_message_chain(:admin, :active).and_return([admin_stub])
allow(Setting).to receive(:self_registration).and_return(2)
user = User.new
instance = described_class.new(user)
expect(user).to receive(:register).and_call_original
expect(user).not_to receive(:activate)
expect(user).to receive(:save).and_return true
mail_stub = double('Mail', deliver_later: true)
expect(UserMailer)
.to(receive(:account_activation_requested))
.with(admin_stub, user)
.and_return(mail_stub)
call = instance.call
expect(call).to be_success
expect(call.result).to eq user
expect(user).to be_registered
expect(call.message).to eq I18n.t(:notice_account_pending)
end
end
describe 'error handling' do
it 'turns it into a service result' do
allow(instance).to receive(:ensure_registration_allowed!).and_raise 'FOO!'
expect(call).to be_failure
# Does not include the internal error message itself
expect(call.message).to eq I18n.t(:notice_activation_failed)
end
end
describe '#with_saved_user_result' do
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'work_packages/create_contract'
require 'concerns/user_invitation'
module Users
class CreateService < ::BaseServices::Create
private
def persist(call)
new_user = call.result
return super(call) unless new_user.invited?
# As we're basing on the user's mail, this parameter is required
# before we're able to validate the contract or user
return fail_with_missing_email(new_user) if new_user.mail.blank?
invite_user!(new_user)
end
def fail_with_missing_email(new_user)
ServiceResult.failure(result: new_user).tap do |result|
result.errors.add :mail, :blank
end
end
def invite_user!(new_user)
invited = ::UserInvitation.invite_user! new_user
new_user.errors.add :base, I18n.t(:error_can_not_invite_user) unless invited.is_a? User
ServiceResult.new(success: new_user.errors.empty?, result: invited)
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
require 'services/base_services/behaves_like_create_service'
RSpec.describe Users::CreateService do
it_behaves_like 'BaseServices create service' do
context 'when the user being invited' do
let(:model_instance) { build(:invited_user) }
context 'and the mail is present' do
let(:model_instance) { build(:invited_user, mail: '[email protected]') }
it 'will call UserInvitation' do
expect(UserInvitation).to receive(:invite_user!).with(model_instance).and_return(model_instance)
expect(subject).to be_success
end
end
context 'and the user has no names set' do
let(:model_instance) { build(:invited_user, firstname: nil, lastname: nil, mail: '[email protected]') }
it 'will call UserInvitation' do
expect(UserInvitation).to receive(:invite_user!).with(model_instance).and_return(model_instance)
expect(subject).to be_success
end
end
context 'and the mail is empty' do
let(:model_instance) { build(:invited_user, mail: nil) }
it 'will call not call UserInvitation' do
expect(UserInvitation).not_to receive(:invite_user!)
expect(subject).not_to be_success
expect(subject.errors.details[:mail]).to eq [{ error: :blank }]
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
##
# Implements the deletion of a user.
module Users
class DeleteService < ::BaseServices::Delete
##
# Deletes the given user if allowed.
#
# @return True if the user deletion has been initiated, false otherwise.
def destroy(user_object)
# as destroying users is a lengthy process we handle it in the background
# and lock the account now so that no action can be performed with it
# don't use "locked!" handle as it will raise on invalid users
user_object.update_column(:status, User.statuses[:locked])
::Principals::DeleteJob.perform_later(user_object)
logout! if self_delete?
true
end
private
def self_delete?
user == model
end
def logout!
User.current = nil
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Users::DeleteService, type: :model do
let(:input_user) { build_stubbed(:user) }
let(:project) { build_stubbed(:project) }
let(:instance) { described_class.new(model: input_user, user: actor) }
subject { instance.call }
shared_examples 'deletes the user' do
it do
allow(input_user).to receive(:update_column).with(:status, 3)
expect(Principals::DeleteJob).to receive(:perform_later).with(input_user)
expect(subject).to be_success
expect(input_user).to have_received(:update_column).with(:status, 3)
end
end
shared_examples 'does not delete the user' do
it do
allow(input_user).to receive(:update_column).with(:status, 3)
expect(Principals::DeleteJob).not_to receive(:perform_later)
expect(subject).not_to be_success
expect(input_user).not_to have_received(:update_column).with(:status, 3)
end
end
context 'if deletion by admins allowed', with_settings: { users_deletable_by_admins: true } do
context 'with admin user' do
let(:actor) { build_stubbed(:admin) }
it_behaves_like 'deletes the user'
end
context 'with unprivileged system user' do
let(:actor) { User.system }
before do
allow(actor).to receive(:admin?).and_return false
end
it_behaves_like 'does not delete the user'
end
context 'with privileged system user' do
let(:actor) { User.system }
it_behaves_like 'deletes the user'
end
end
context 'if deletion by admins NOT allowed', with_settings: { users_deletable_by_admins: false } do
context 'with admin user' do
let(:actor) { build_stubbed(:admin) }
it_behaves_like 'does not delete the user'
end
context 'with system user' do
let(:actor) { User.system }
it_behaves_like 'does not delete the user'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Users
class LoginService
attr_accessor :controller, :request, :browser, :user, :cookies
delegate :session, to: :controller
def initialize(user:, controller:, request:)
self.user = user
self.controller = controller
self.request = request
self.browser = controller.send(:browser)
self.cookies = controller.send(:cookies)
end
def call!
autologin_requested = session.delete(:autologin_requested)
retain_session_values do
reset_session!
User.current = user
set_autologin_cookie if autologin_requested
successful_login
end
end
private
def set_autologin_cookie
return unless Setting::Autologin.enabled?
# generate a key and set cookie if autologin
expires_on = Setting.autologin.days.from_now.beginning_of_day
token = Token::AutoLogin.create(user:, data: session_identification, expires_on:)
cookie_options = {
value: token.plain_value,
# The autologin expiry is checked on validating the token
# but still expire the cookie to avoid unnecessary retries
expires: expires_on,
path: OpenProject::Configuration['autologin_cookie_path'],
secure: OpenProject::Configuration.https?,
httponly: true
}
cookies[OpenProject::Configuration['autologin_cookie_name']] = cookie_options
end
def successful_login
user.log_successful_login
context = { user:, request:, session: }
OpenProject::Hook.call_hook(:user_logged_in, context)
end
def reset_session!
::Sessions::DropAllSessionsService.call(user) if drop_old_sessions?
controller.reset_session
end
def retain_session_values
# retain flash values
flash_values = controller.flash.to_h
# retain session values
retained_session = retained_session_values || {}
yield
flash_values.each { |k, v| controller.flash[k] = v }
session.merge!(retained_session)
session.merge!(session_identification)
apply_default_values(session)
end
def apply_default_values(session)
session[:user_id] = user.id
session[:updated_at] = Time.zone.now
end
def session_identification
{
platform: browser.platform&.name,
browser: browser.name,
browser_version: browser.version
}
end
def retained_session_values
provider_name = session[:omniauth_provider]
return unless provider_name
provider = ::OpenProject::Plugins::AuthPlugin.find_provider_by_name(provider_name)
return unless provider && provider[:retain_from_session]
retained_keys = provider[:retain_from_session] + ['omniauth_provider']
controller.session.to_h.slice(*retained_keys)
end
##
# We can only drop old sessions if they're stored in the database
# and enabled by configuration.
def drop_old_sessions?
OpenProject::Configuration.drop_old_sessions_on_login?
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Users::LoginService, type: :model do
shared_let(:input_user) { create(:user) }
let(:request) { {} }
let(:session) { {} }
let(:browser) do
instance_double(Browser::Safari,
name: 'Safari',
version: '13.2',
platform: instance_double(Browser::Platform::Linux, name: 'Linux'))
end
let(:cookies) { {} }
let(:flash) { ActionDispatch::Flash::FlashHash.new }
let(:controller) { instance_double(ApplicationController, browser:, cookies:, session:, flash:) }
let(:instance) { described_class.new(user: input_user, controller:, request:) }
subject { instance.call! }
before do
allow(controller)
.to(receive(:reset_session)) do
session.clear
flash.clear
end
allow(input_user)
.to receive(:log_successful_login)
end
describe 'session' do
context 'with an SSO provider' do
let(:sso_provider) do
{
name: 'saml',
retain_from_session: %i[foo bar]
}
end
before do
allow(OpenProject::Plugins::AuthPlugin)
.to(receive(:find_provider_by_name))
.with('provider_name')
.and_return sso_provider
end
context 'if provider retains session values' do
let(:retained_values) { %i[foo bar] }
it 'retains present session values' do
session[:omniauth_provider] = 'provider_name'
session[:foo] = 'foo value'
session[:what] = 'should be cleared'
subject
expect(session[:foo]).to be_present
expect(session[:what]).to be_nil
expect(session[:user_id]).to eq input_user.id
end
end
it 'retains present flash values' do
flash[:notice] = 'bar' # rubocop:disable Rails/I18nLocaleTexts
subject
expect(controller.flash[:notice]).to eq 'bar'
end
end
end
describe 'autologin cookie' do
before do
session[:autologin_requested] = true if autologin_requested
end
shared_examples 'does not set autologin cookie' do
it 'does not set a cookie' do
subject
expect(Token::AutoLogin.exists?(user: input_user)).to be false
expect(cookies[OpenProject::Configuration['autologin_cookie_name']]).to be_nil
end
end
context 'when not requested and disabled', with_settings: { autologin: 0 } do
let(:autologin_requested) { false }
it_behaves_like 'does not set autologin cookie'
end
context 'when not requested and enabled', with_settings: { autologin: 1 } do
let(:autologin_requested) { false }
it_behaves_like 'does not set autologin cookie'
end
context 'when requested, but disabled', with_settings: { autologin: 0 } do
let(:autologin_requested) { true }
it_behaves_like 'does not set autologin cookie'
end
context 'when requested and enabled', with_settings: { autologin: 1 } do
let(:autologin_requested) { true }
it 'sets a cookie' do
subject
tokens = Token::AutoLogin.where(user: input_user)
expect(tokens.count).to eq 1
expect(tokens.first.user_id).to eq input_user.id
autologin_cookie = cookies[OpenProject::Configuration['autologin_cookie_name']]
expect(autologin_cookie).to be_present
expect(autologin_cookie[:value]).to be_present
expect(autologin_cookie[:expires]).to eq (Time.zone.today + 1.day).beginning_of_day
expect(autologin_cookie[:path]).to eq '/'
expect(autologin_cookie[:httponly]).to be true
expect(autologin_cookie[:secure]).to eq Setting.https?
expect(Token::AutoLogin.find_by_plaintext_value(autologin_cookie[:value])).to eq tokens.first
end
end
context 'when requested and enabled with https',
with_config: { https: true },
with_settings: { autologin: 1 } do
let(:autologin_requested) { true }
it 'sets a secure cookie' do
subject
autologin_cookie = cookies[OpenProject::Configuration['autologin_cookie_name']]
expect(autologin_cookie[:secure]).to be true
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class CustomActions::UpdateWorkPackageService
include Shared::BlockService
include Contracted
attr_accessor :user,
:action
def initialize(action:, user:)
self.action = action
self.user = user
self.contract_class = ::WorkPackages::UpdateContract
end
def call(work_package:, &block)
apply_actions(work_package, action.actions)
result = ::WorkPackages::UpdateService
.new(user:,
model: work_package)
.call
block_with_result(result, &block)
end
private
def apply_actions(work_package, actions)
changes_before = work_package.changes.dup
apply_actions_sorted(work_package, actions)
success, errors = validate(work_package, user)
unless success
retry_apply_actions(work_package, actions, errors, changes_before)
end
end
def retry_apply_actions(work_package, actions, errors, changes_before)
new_actions = without_invalid_actions(actions, errors)
if new_actions.any? && actions.length != new_actions.length
work_package.restore_attributes(work_package.changes.keys - changes_before.keys)
apply_actions(work_package, new_actions)
end
end
def without_invalid_actions(actions, errors)
invalid_keys = errors.attribute_names.map { |k| append_id(k) }
actions.reject { |a| invalid_keys.include?(append_id(a.key)) }
end
def apply_actions_sorted(work_package, actions)
actions
.sort_by(&:priority)
.each { |a| a.apply(work_package) }
end
def append_id(sym)
"#{sym.to_s.chomp('_id')}_id"
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe CustomActions::UpdateWorkPackageService do
let(:custom_action) do
action = build_stubbed(:custom_action)
allow(action)
.to receive(:actions)
.and_return([alter_action1, alter_action2])
action
end
let(:alter_action1) do
action = double('custom actions action 1', key: 'abc', priority: 100)
allow(action)
.to receive(:apply)
.with(work_package) do
work_package.subject = ''
end
action
end
let(:alter_action2) do
action = double('custom actions action 2', key: 'def', priority: 10)
allow(action)
.to receive(:apply)
.with(work_package) do
work_package.status_id = 100
end
action
end
let(:user) { build_stubbed(:user) }
let(:instance) { described_class.new(action: custom_action, user:) }
let(:update_service_call_implementation) do
-> do
result
end
end
let!(:update_wp_service) do
wp_service_instance = instance_double(WorkPackages::UpdateService)
allow(WorkPackages::UpdateService)
.to receive(:new)
.with(user:, model: work_package)
.and_return(wp_service_instance)
allow(wp_service_instance)
.to receive(:call) do
update_service_call_implementation.()
end
wp_service_instance
end
let(:work_package) { build_stubbed(:work_package) }
let(:result) do
ServiceResult.success(result: work_package)
end
let(:validation_result) { true }
let!(:contract) do
contract = double('contract')
allow(WorkPackages::UpdateContract)
.to receive(:new)
.with(work_package, user, options: {})
.and_return(contract)
allow(contract)
.to receive(:validate)
.and_return(validation_result)
contract
end
describe '#call' do
let(:call) do
instance.call(work_package:)
end
let(:subject) { call }
it 'returns the update wp service result' do
expect(call)
.to eql result
end
it 'yields the result' do
yielded = false
proc = Proc.new do |call|
yielded = call
end
instance.call(work_package:, &proc)
expect(yielded)
.to be_success
end
it 'calls each registered action with the work package' do
[alter_action1, alter_action2].each do |alter_action|
expect(alter_action)
.to receive(:apply)
.with(work_package)
end
call
end
it 'calls the registered actions based on their priority' do
call_order = []
[alter_action1, alter_action2].each do |alter_action|
allow(alter_action)
.to receive(:apply)
.with(work_package) do
call_order << alter_action
end
end
call
expect(call_order)
.to eql [alter_action2, alter_action1]
end
context 'on validation error' do
before do
allow(contract)
.to receive(:validate) do
work_package.subject.present?
end
allow(contract)
.to receive(:errors)
.and_return(instance_double(ActiveModel::Errors, attribute_names: [alter_action1.key]))
work_package.lock_version = 200
subject
end
let(:update_service_call_implementation) do
-> do
# check that the work package retains only the valid changes
# when passing it to the update service
expect(work_package.subject)
.not_to eql ''
expect(work_package.status_id)
.to be 100
expect(work_package.lock_version)
.to be 200
result
end
end
it 'is successful' do
expect(subject)
.to be_success
end
end
context 'on unfixable validation error' do
let(:result) do
ServiceResult.failure(result: work_package)
end
let(:update_service_call_implementation) do
-> do
# check that the work package has all the changes
# of the actions when passing it to the update service
expect(work_package.subject)
.to be_blank
expect(work_package.status_id)
.to be 100
expect(work_package.lock_version)
.to be 200
result
end
end
before do
allow(contract)
.to receive(:validate)
.and_return(false)
allow(contract)
.to receive(:errors)
.and_return(instance_double(ActiveModel::Errors, attribute_names: [:base]))
work_package.lock_version = 200
subject
end
it 'is failure' do
expect(subject)
.to be_failure
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class CustomActions::UpdateService < CustomActions::BaseService
attr_accessor :user,
:action
def initialize(action:, user:)
self.action = action
self.user = user
end
def call(attributes:, &block)
super(attributes:, action:, &block)
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe CustomActions::UpdateService do
let(:action) do
action = build_stubbed(:custom_action)
allow(action)
.to receive(:save)
.and_return(save_success)
action
end
let(:user) { build_stubbed(:user) }
let(:save_success) { true }
let(:contract_success) { true }
let(:contract_errors) { double('contract errors') }
let(:instance) do
contract
described_class.new(action:, user:)
end
let(:contract) do
contract_instance = double('contract instance')
allow(CustomActions::CuContract)
.to receive(:new)
.with(action)
.and_return(contract_instance)
allow(contract_instance)
.to receive(:validate)
.and_return(contract_success)
allow(contract_instance)
.to receive(:errors)
.and_return(contract_errors)
contract_instance
end
describe '#call' do
it 'is successful' do
expect(instance.call(attributes: {}))
.to be_success
end
it 'is has the action in the result' do
expect(instance.call(attributes: {}).result)
.to eql action
end
it 'yields the result' do
yielded = false
proc = Proc.new do |call|
yielded = call
end
instance.call(attributes: {}, &proc)
expect(yielded)
.to be_success
end
context 'unsuccessful saving' do
let(:save_success) { false }
it 'yields the result' do
yielded = false
proc = Proc.new do |call|
yielded = call
end
instance.call(attributes: {}, &proc)
expect(yielded)
.to be_failure
end
end
context 'unsuccessful contract' do
let(:contract_success) { false }
it 'yields the result' do
yielded = false
proc = Proc.new do |call|
yielded = call
end
instance.call(attributes: {}, &proc)
expect(yielded)
.to be_failure
end
end
it 'sets the name of the action' do
expect(instance.call(attributes: { name: 'new name' }).result.name)
.to eql 'new name'
end
it 'updates the actions' do
action.actions = [CustomActions::Actions::AssignedTo.new('1'),
CustomActions::Actions::Status.new('3')]
new_actions = instance
.call(attributes: { actions: { assigned_to: ['2'], priority: ['3'] } })
.result
.actions
.map { |a| [a.key, a.values] }
expect(new_actions)
.to match_array [[:assigned_to, [2]], [:priority, [3]]]
end
it 'handles unknown actions' do
new_actions = instance
.call(attributes: { actions: { some_bogus_name: ['3'] } })
.result
.actions
.map { |a| [a.key, a.values] }
expect(new_actions)
.to match_array [[:inexistent, ['3']]]
end
it 'updates the conditions' do
old_status = create(:status)
new_status = create(:status)
action.conditions = [CustomActions::Conditions::Status.new(old_status.id)]
new_conditions = instance
.call(attributes: { conditions: { status: new_status.id } })
.result
.conditions
.map { |a| [a.key, a.values] }
expect(new_conditions)
.to match_array [[:status, [new_status.id]]]
end
it 'handles unknown conditions' do
new_conditions = instance
.call(attributes: { conditions: { some_bogus_name: ['3'] } })
.result
.conditions
.map { |a| [a.key, a.values] }
expect(new_conditions)
.to match_array [[:inexistent, [3]]]
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module API
class ParserStruct < ::Hashie::Mash
##
# Hashie::Mash extends from Hash
# and by default does not allow overriding any enumerable methods.
#
# This clashes with names (e.g. +group_by+) occurring when parsing in the API.
# Undefining the method allows to set and get the parsed value without conflicts.
undef_method :group_by
end
end
``` | # OpenProject is an open source project management software.
# Copyright (C) 2010-2022 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
require 'spec_helper'
RSpec.describe API::ParserStruct do
let(:instance) { described_class.new }
describe 'assigning a value and method creation' do
# Dynamically creating a method can be misused when allowing
# those method are generated based on client input.
# See "Symbol denial of service" at
# https://ruby-doc.org/stdlib-3.0.0/libdoc/ostruct/rdoc/OpenStruct.html#class-OpenStruct-label-Caveats.
it 'does not dynamically create a method' do
instance.some_method = 'string'
expect(instance.methods.grep(/some_method/))
.to be_empty
end
end
describe 'assigning an value and getting a hash' do
it 'works for [value]=' do
instance.some_value = 'string'
expect(instance.to_h)
.to eql('some_value' => 'string')
end
it 'works for [value]_id=' do
instance.some_value_id = 5
expect(instance.to_h)
.to eql('some_value_id' => 5)
end
it 'works for group_by=' do
instance.group_by = 8
expect(instance.to_h)
.to eql('group_by' => 8)
end
end
describe 'assigning an value and getting by hash key' do
it 'works for [value]=' do
instance.some_value = 'string'
expect(instance[:some_value])
.to eq('string')
end
it 'works for [value]_id=' do
instance.some_value_id = 5
expect(instance[:some_value_id])
.to eq(5)
end
it 'works for group_by=' do
instance.group_by = 8
expect(instance[:group_by])
.to eq(8)
end
end
describe 'instantiating with a hash and fetching the value' do
let(:instance) do
described_class
.new({ 'some_value' => 'string', 'some_value_id' => 5, 'group_by' => 8 })
end
it 'allows fetching the value' do
expect(instance.to_h)
.to eql({ 'some_value' => 'string', 'some_value_id' => 5, 'group_by' => 8 })
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module API
module V3
class WorkPackageCollectionFromQueryService
include Utilities::PathHelper
include ::API::Utilities::UrlPropsParsingHelper
def initialize(query, user, scope: nil)
self.query = query
self.current_user = user
self.scope = scope
end
def call(params = {}, valid_subset: false)
update = UpdateQueryFromV3ParamsService
.new(query, current_user)
.call(params, valid_subset:)
if update.success?
representer = results_to_representer(params)
ServiceResult.success(result: representer)
else
update
end
end
private
def results_to_representer(params)
results_scope = query.results.work_packages
if scope
results_scope = results_scope.where(id: scope.select(:id))
end
collection_representer(results_scope,
params:,
project: query.project,
groups: generate_groups,
sums: generate_total_sums)
end
attr_accessor :query,
:current_user,
:scope
def representer
::API::V3::WorkPackages::WorkPackageCollectionRepresenter
end
def calculate_resulting_params(provided_params)
calculate_default_params
.merge(provided_params.slice('offset', 'pageSize').symbolize_keys)
.tap do |params|
if query.manually_sorted?
params[:query_id] = query.id
params[:offset] = 1
# Force the setting value in all cases except when 0 is requested explicitly. Fetching with pageSize = 0
# is done for performance reasons to simply get the query without the results.
params[:pageSize] = pageSizeParam(params) == 0 ? pageSizeParam(params) : Setting.forced_single_page_size
else
params[:offset] = to_i_or_nil(params[:offset])
params[:pageSize] = pageSizeParam(params)
end
params[:select] = nested_from_csv(provided_params['select']) if provided_params['select']
end
end
def calculate_default_params
::API::V3::Queries::QueryParamsRepresenter
.new(query)
.to_h
end
def generate_groups
return unless query.grouped?
results = query.results
sums = generate_group_sums
results.work_package_count_by_group.map do |group, count|
::API::V3::WorkPackages::WorkPackageAggregationGroup.new(
group, count, query:, sums: sums[group], current_user:
)
end
end
def generate_total_sums
return unless query.display_sums?
format_query_sums query.results.all_total_sums
end
def generate_group_sums
return {} unless query.display_sums?
query.results.all_group_sums.transform_values do |v|
format_query_sums(v)
end
end
def format_query_sums(sums)
API::ParserStruct.new(format_column_keys(sums).merge(available_custom_fields: WorkPackageCustomField.summable.to_a))
end
def format_column_keys(hash_by_column)
hash_by_column.map do |column, value|
match = /cf_(\d+)/.match(column.name.to_s)
column_name = if match
"custom_field_#{match[1]}"
else
column.name.to_s
end
[column_name, value]
end.to_h
end
def collection_representer(work_packages, params:, project:, groups:, sums:)
resulting_params = calculate_resulting_params(params)
if resulting_params[:select]
::API::V3::Utilities::SqlRepresenterWalker
.new(work_packages,
current_user:,
self_path: self_link(project),
url_query: resulting_params)
.walk(::API::V3::WorkPackages::WorkPackageSqlCollectionRepresenter)
else
::API::V3::WorkPackages::WorkPackageCollectionRepresenter.new(
work_packages,
self_link: self_link(project),
project:,
query_params: resulting_params,
page: resulting_params[:offset],
per_page: resulting_params[:pageSize],
groups:,
total_sums: sums,
embed_schemas: true,
current_user:,
timestamps: query.timestamps,
query:
)
end
end
def to_i_or_nil(value)
value ? value.to_i : nil
end
def pageSizeParam(params)
to_i_or_nil(params[:pageSize])
end
def self_link(project)
if project
api_v3_paths.work_packages_by_project(project.id)
else
api_v3_paths.work_packages
end
end
def convert_to_v3(attribute)
::API::Utilities::PropertyNameConverter.from_ar_name(attribute).to_sym
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe API::V3::WorkPackageCollectionFromQueryService,
type: :model do
include API::V3::Utilities::PathHelper
let(:query) do
build_stubbed(:query).tap do |query|
allow(query)
.to receive(:results)
.and_return(results)
allow(query)
.to receive(:manually_sorted?)
.and_return(query_manually_sorted)
end
end
let(:query_manually_sorted) { false }
let(:results) do
results = double('results')
allow(results)
.to receive(:work_packages)
.and_return([work_package])
allow(results)
.to receive(:all_total_sums)
.and_return(OpenStruct.new(name: :estimated_hours) => 0.0)
allow(results)
.to receive(:work_package_count_by_group)
.and_return(1 => 5, 2 => 10)
allow(results)
.to receive(:all_group_sums)
.and_return(1 => { OpenStruct.new(name: :status_id) => 50 },
2 => { OpenStruct.new(name: :status_id) => 100 })
allow(results)
.to receive(:query)
.and_return(double('query'))
results
end
let(:user) { build_stubbed(:user) }
let(:project) { build_stubbed(:project) }
let(:mock_wp_representer) do
Struct.new(:work_packages,
:self_link,
:query_params,
:project,
:groups,
:total_sums,
:page,
:per_page,
:embed_schemas,
:current_user,
:timestamps,
:query) do
def initialize(work_packages,
self_link:,
query_params:,
project:,
groups:,
total_sums:,
page:,
per_page:,
embed_schemas:,
current_user:,
timestamps:,
query:)
super(work_packages,
self_link,
query_params,
project,
groups,
total_sums,
page,
per_page,
embed_schemas,
current_user,
timestamps,
query)
end
end
end
let(:mock_aggregation_representer) do
Struct.new(:group,
:count,
:query,
:sums,
:current_user) do
def initialize(group,
count,
query:,
sums:,
current_user:)
super(group,
count,
query,
sums,
current_user)
end
end
end
let(:params) { {} }
let(:mock_update_query_service) do
mock = double('UpdateQueryFromV3ParamsService')
allow(mock)
.to receive(:call)
.with(params, valid_subset: false)
.and_return(mock_update_query_service_response)
mock
end
let(:mock_update_query_service_response) do
ServiceResult.new(success: update_query_service_success,
errors: update_query_service_errors,
result: update_query_service_result)
end
let(:update_query_service_success) { true }
let(:update_query_service_errors) { nil }
let(:update_query_service_result) { query }
let(:work_package) { build_stubbed(:work_package) }
let(:instance) { described_class.new(query, user) }
describe '#call' do
subject { instance.call(params) }
before do
stub_const('::API::V3::WorkPackages::WorkPackageCollectionRepresenter', mock_wp_representer)
stub_const('::API::V3::WorkPackages::WorkPackageAggregationGroup', mock_aggregation_representer)
allow(API::V3::UpdateQueryFromV3ParamsService)
.to receive(:new)
.with(query, user)
.and_return(mock_update_query_service)
end
it 'is successful' do
expect(subject).to be_success
end
context 'result' do
subject { instance.call(params).result }
it 'is a WorkPackageCollectionRepresenter' do
expect(subject)
.to be_a(API::V3::WorkPackages::WorkPackageCollectionRepresenter)
end
context 'work_packages' do
it "has the query's work_package results set" do
expect(subject.work_packages)
.to contain_exactly(work_package)
end
end
context 'current_user' do
it 'has the provided user set' do
expect(subject.current_user)
.to eq(user)
end
end
context 'project' do
it 'has the queries project set' do
expect(subject.project)
.to eq(query.project)
end
end
context 'self_link' do
context 'if the project is nil' do
let(:query) { build_stubbed(:query, project: nil) }
it 'is the global work_package link' do
expect(subject.self_link)
.to eq(api_v3_paths.work_packages)
end
end
context 'if the project is set' do
let(:query) { build_stubbed(:query, project:) }
it 'is the global work_package link' do
expect(subject.self_link)
.to eq(api_v3_paths.work_packages_by_project(project.id))
end
end
end
context 'embed_schemas' do
it 'is true' do
expect(subject.embed_schemas)
.to be_truthy
end
end
context 'when timestamps are given' do
let(:timestamps) { [Timestamp.parse("P-1Y"), Timestamp.parse("oneWeekAgo@12:00+00:00"), Timestamp.now] }
let(:query) { build_stubbed(:query, timestamps:) }
it 'has the query timestamps' do
expect(subject.timestamps)
.to match_array(timestamps)
end
end
context 'when a _query object is given' do
it 'has the query' do
expect(subject.query)
.to eq(query)
end
end
context 'total_sums' do
context 'with query.display_sums? being false' do
it 'is nil' do
query.display_sums = false
expect(subject.total_sums)
.to be_nil
end
end
context 'with query.display_sums? being true' do
it 'has a struct containing the sums and the available custom fields' do
query.display_sums = true
custom_fields = [build_stubbed(:text_wp_custom_field),
build_stubbed(:integer_wp_custom_field)]
allow(WorkPackageCustomField)
.to receive(:summable)
.and_return(custom_fields)
expected = API::ParserStruct.new(estimated_hours: 0.0, available_custom_fields: custom_fields)
expect(subject.total_sums)
.to eq(expected)
end
end
end
context 'groups' do
context 'with query.grouped? being false' do
it 'is nil' do
query.group_by = nil
expect(subject.groups)
.to be_nil
end
end
context 'with query.group_by being empty' do
it 'is nil' do
query.group_by = ''
expect(subject.groups)
.to be_nil
end
end
context 'with query.grouped? being true' do
it 'has the groups' do
query.group_by = 'status'
expect(subject.groups[0].group)
.to eq(1)
expect(subject.groups[0].count)
.to eq(5)
expect(subject.groups[1].group)
.to eq(2)
expect(subject.groups[1].count)
.to eq(10)
end
end
end
context 'query (in the url)' do
context 'when displaying sums' do
it 'is represented' do
query.display_sums = true
expect(subject.query_params[:showSums])
.to be(true)
end
end
context 'when displaying hierarchies' do
it 'is represented' do
query.show_hierarchies = true
expect(subject.query_params[:showHierarchies])
.to be(true)
end
end
context 'when grouping' do
it 'is represented' do
query.group_by = 'status_id'
expect(subject.query_params[:groupBy])
.to eq('status_id')
end
end
context 'when sorting' do
it 'is represented' do
query.sort_criteria = [['status_id', 'desc']]
expected_sort = JSON::dump [['status', 'desc']]
expect(subject.query_params[:sortBy])
.to eq(expected_sort)
end
end
context 'filters' do
it 'is represented' do
query.add_filter('status_id', '=', ['1', '2'])
query.add_filter('subproject_id', '=', ['3', '4'])
expected_filters = JSON::dump([
{ status: { operator: '=', values: ['1', '2'] } },
{ subprojectId: { operator: '=', values: ['3', '4'] } }
])
expect(subject.query_params[:filters])
.to eq(expected_filters)
end
it 'represents no filters' do
expected_filters = JSON::dump([])
expect(subject.query_params[:filters])
.to eq(expected_filters)
end
end
end
context 'offset' do
it 'is 1 as default' do
expect(subject.query_params[:offset])
.to be(1)
end
context 'with a provided value' do
# It is imporant for the keys to be strings
# as that is what will come from the client
let(:params) { { 'offset' => 3 } }
it 'is that value' do
expect(subject.query_params[:offset])
.to be(3)
end
end
end
context 'pageSize' do
before do
allow(Setting)
.to receive(:per_page_options_array)
.and_return([25, 50])
end
it 'is nil' do
expect(subject.query_params[:pageSize])
.to be(25)
end
context 'with a provided value' do
# It is imporant for the keys to be strings
# as that is what will come from the client
let(:params) { { 'pageSize' => 100 } }
it 'is that value' do
expect(subject.query_params[:pageSize])
.to be(100)
end
end
context 'with the query sorted manually', with_settings: { forced_single_page_size: 42 } do
let(:query_manually_sorted) { true }
it 'is the setting value' do
expect(subject.query_params[:pageSize])
.to be(42)
end
context 'with a provided value' do
let(:params) { { 'pageSize' => 100 } }
it 'is the setting value' do
expect(subject.query_params[:pageSize])
.to be(42)
end
end
context 'with a provided value of 0' do
let(:params) { { 'pageSize' => 0 } }
it 'is the provided value' do
expect(subject.query_params[:pageSize])
.to be(0)
end
end
end
end
end
context 'when the update query service fails' do
let(:update_query_service_success) { false }
let(:update_query_service_errors) { double('errors') }
let(:update_query_service_result) { nil }
it 'returns the update service response' do
expect(subject)
.to eql(mock_update_query_service_response)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module API
module V3
class UpdateQueryFromV3ParamsService
def initialize(query, user)
self.query = query
self.current_user = user
end
def call(params, valid_subset: false)
parsed = ::API::V3::ParseQueryParamsService
.new
.call(params)
if parsed.success?
::UpdateQueryFromParamsService
.new(query, current_user)
.call(parsed.result, valid_subset:)
else
parsed
end
end
attr_accessor :query,
:current_user
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe API::V3::UpdateQueryFromV3ParamsService,
type: :model do
let(:user) { build_stubbed(:user) }
let(:query) { build_stubbed(:query) }
let(:params) { double('params') }
let(:parsed_params) { double('parsed_params') }
let(:mock_parse_query_service) do
mock = double('ParseQueryParamsService')
allow(mock)
.to receive(:call)
.with(params)
.and_return(mock_parse_query_service_response)
mock
end
let(:mock_parse_query_service_response) do
ServiceResult.new(success: mock_parse_query_service_success,
errors: mock_parse_query_service_errors,
result: mock_parse_query_service_result)
end
let(:mock_parse_query_service_success) { true }
let(:mock_parse_query_service_errors) { nil }
let(:mock_parse_query_service_result) { parsed_params }
let(:mock_update_query_service) do
mock = double('UpdateQueryFromParamsService')
allow(mock)
.to receive(:call)
.with(parsed_params, valid_subset: false)
.and_return(mock_update_query_service_response)
mock
end
let(:mock_update_query_service_response) do
ServiceResult.new(success: mock_update_query_service_success,
errors: mock_update_query_service_errors,
result: mock_update_query_service_result)
end
let(:mock_update_query_service_success) { true }
let(:mock_update_query_service_errors) { nil }
let(:mock_update_query_service_result) { query }
let(:instance) { described_class.new(query, user) }
before do
allow(UpdateQueryFromParamsService)
.to receive(:new)
.with(query, user)
.and_return(mock_update_query_service)
allow(API::V3::ParseQueryParamsService)
.to receive(:new)
.with(no_args)
.and_return(mock_parse_query_service)
end
describe '#call' do
subject { instance.call(params) }
it 'returns the update result' do
expect(subject)
.to eql(mock_update_query_service_response)
end
context 'when parsing fails' do
let(:mock_parse_query_service_success) { false }
let(:mock_parse_query_service_errors) { double 'error' }
let(:mock_parse_query_service_result) { nil }
it 'returns the parse result' do
expect(subject)
.to eql(mock_parse_query_service_response)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module API
module V3
class WorkPackageCollectionFromQueryParamsService
def initialize(user, scope: nil)
self.current_user = user
self.scope = scope
end
def call(params = {})
query = Query.new_default(project: params[:project])
WorkPackageCollectionFromQueryService
.new(query, current_user, scope:)
.call(params, valid_subset: params['valid_subset'].present?)
end
private
attr_accessor :current_user,
:scope
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe API::V3::WorkPackageCollectionFromQueryParamsService,
type: :model do
include API::V3::Utilities::PathHelper
let(:mock_wp_collection_from_query_service) do
mock = double('WorkPackageCollectionFromQueryService')
allow(mock)
.to receive(:call)
.and_return(mock_wp_collection_service_response)
mock
end
let(:mock_wp_collection_service_response) do
ServiceResult.new(success: mock_wp_collection_service_success,
errors: mock_wp_collection_service_errors,
result: mock_wp_collection_service_result)
end
let(:mock_wp_collection_service_success) { true }
let(:mock_wp_collection_service_errors) { nil }
let(:mock_wp_collection_service_result) { double('result') }
let(:query) { build_stubbed(:query) }
let(:project) { build_stubbed(:project) }
let(:user) { build_stubbed(:user) }
let(:instance) { described_class.new(user) }
before do
stub_const('::API::V3::WorkPackageCollectionFromQueryService',
mock_wp_collection_from_query_service)
allow(API::V3::WorkPackageCollectionFromQueryService)
.to receive(:new)
.with(query, user, scope: nil)
.and_return(mock_wp_collection_from_query_service)
end
describe '#call' do
let(:params) { { project: } }
subject { instance.call(params) }
before do
allow(Query)
.to receive(:new_default)
.with(project:)
.and_return(query)
end
it 'is successful' do
expect(subject)
.to eql(mock_wp_collection_service_response)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module API
module V3
class ParseQueryParamsService
KEYS_GROUP_BY = %i(group_by groupBy g).freeze
KEYS_COLUMNS = %i(columns c column_names columns[]).freeze
def call(params)
json_parsed = json_parsed_params(params)
return json_parsed if json_parsed.failure?
parsed = parsed_params(params)
return parsed if parsed.failure?
result = without_empty(parsed.result.merge(json_parsed.result), determine_allowed_empty(params))
ServiceResult.success(result:)
end
private
def json_parsed_params(params)
parsed = {
filters: filters_from_params(params),
sort_by: sort_by_from_params(params),
timeline_labels: timeline_labels_from_params(params)
}
ServiceResult.success result: parsed
rescue ::JSON::ParserError => e
result = ServiceResult.failure
result.errors.add(:base, e.message)
result
end
# rubocop:disable Metrics/AbcSize
def parsed_params(params)
ServiceResult.success result: {
group_by: group_by_from_params(params),
columns: columns_from_params(params),
display_sums: boolearize(params[:showSums]),
timeline_visible: boolearize(params[:timelineVisible]),
timeline_zoom_level: params[:timelineZoomLevel],
highlighting_mode: params[:highlightingMode],
highlighted_attributes: highlighted_attributes_from_params(params),
display_representation: params[:displayRepresentation],
show_hierarchies: boolearize(params[:showHierarchies]),
include_subprojects: boolearize(params[:includeSubprojects]),
timestamps: Timestamp.parse_multiple(params[:timestamps])
}
rescue ArgumentError => e
result = ServiceResult.failure
result.errors.add(:base, e.message)
result
end
# rubocop:enable Metrics/AbcSize
def determine_allowed_empty(params)
allow_empty = params.keys
allow_empty << :group_by if group_by_empty?(params)
allow_empty
end
# Group will be set to nil if parameter exists but set to empty string ('')
def group_by_from_params(params)
return nil unless params_exist?(params, KEYS_GROUP_BY)
attribute = params_value(params, KEYS_GROUP_BY)
if attribute.present?
convert_attribute attribute
end
end
def sort_by_from_params(params)
return unless params[:sortBy]
parse_sorting_from_json(params[:sortBy])
end
def timeline_labels_from_params(params)
return unless params[:timelineLabels]
JSON.parse(params[:timelineLabels])
end
# Expected format looks like:
# [
# {
# "filtered_field_name": {
# "operator": "a name for a filter operation",
# "values": ["values", "for the", "operation"]
# }
# },
# { /* more filters if needed */}
# ]
def filters_from_params(params)
filters = params[:filters] || params[:filter]
return unless filters
filters = JSON.parse filters if filters.is_a? String
filters.map do |filter|
filter_from_params(filter)
end
end
def filter_from_params(filter)
attribute = filter.keys.first # there should only be one attribute per filter
operator = filter[attribute]['operator']
values = Array(filter[attribute]['values'])
ar_attribute = convert_filter_attribute attribute, append_id: true
{ field: ar_attribute,
operator:,
values: }
end
def columns_from_params(params)
columns = params_value(params, KEYS_COLUMNS)
return unless columns
columns.map do |column|
convert_attribute(column)
end
end
def highlighted_attributes_from_params(params)
highlighted_attributes = Array(params[:highlightedAttributes].presence)
return if highlighted_attributes.blank?
highlighted_attributes.map do |href|
attr = href.split('/').last
convert_attribute(attr)
end
end
def boolearize(value)
case value
when 'true'
true
when 'false'
false
end
end
##
# Maps given field names coming from the frontend to the actual names
# as expected by the query. This works slightly different to what happens
# in #column_names_from_params. For instance while they column name is
# :type the expected field name is :type_id.
#
# Examples:
# * status => status_id
# * progresssDone => done_ratio
# * assigned => assigned_to
# * customField1 => cf_1
#
# @param field_names [Array] Field names as read from the params.
# @return [Array] Returns a list of fixed field names. The list may contain nil values
# for fields which could not be found.
def fix_field_array(field_names)
return [] if field_names.nil?
field_names
.map { |name| convert_attribute name, append_id: true }
end
def parse_sorting_from_json(json)
JSON.parse(json).map do |order|
attribute, direction = case order
when Array
[order.first, order.last]
when String
order.split(':')
end
[convert_attribute(attribute), direction]
end
end
def convert_attribute(attribute, append_id: false)
::API::Utilities::WpPropertyNameConverter.to_ar_name(attribute,
refer_to_ids: append_id)
end
def convert_filter_attribute(attribute, append_id: false)
::API::Utilities::QueryFiltersNameConverter.to_ar_name(attribute,
refer_to_ids: append_id)
end
def params_exist?(params, symbols)
unsafe_params(params).detect { |k, _| symbols.include? k.to_sym }
end
def params_value(params, symbols)
params.slice(*symbols).first&.last
end
##
# Access the parameters as a hash, which has been deprecated
def unsafe_params(params)
if params.is_a? ActionController::Parameters
params.to_unsafe_h
else
params
end
end
def without_empty(hash, exceptions)
exceptions = exceptions.map(&:to_sym)
hash.select { |k, v| v.present? || v == false || exceptions.include?(k) }
end
def group_by_empty?(params)
params_exist?(params, KEYS_GROUP_BY) &&
params_value(params, KEYS_GROUP_BY).blank?
end
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe API::V3::ParseQueryParamsService,
type: :model do
let(:instance) { described_class.new }
let(:params) { {} }
describe '#call' do
subject { instance.call(params) }
shared_examples_for 'transforms' do
it 'is success' do
expect(subject)
.to be_success
end
it 'is transformed' do
expect(subject.result)
.to eql(expected)
end
end
context 'with group by' do
context 'as groupBy' do
it_behaves_like 'transforms' do
let(:params) { { groupBy: 'status' } }
let(:expected) { { group_by: 'status' } }
end
end
context 'as group_by' do
it_behaves_like 'transforms' do
let(:params) { { group_by: 'status' } }
let(:expected) { { group_by: 'status' } }
end
end
context 'as "g"' do
it_behaves_like 'transforms' do
let(:params) { { g: 'status' } }
let(:expected) { { group_by: 'status' } }
end
end
context 'set to empty string' do
it_behaves_like 'transforms' do
let(:params) { { g: '' } }
let(:expected) { { group_by: nil } }
end
it_behaves_like 'transforms' do
let(:params) { { group_by: '' } }
let(:expected) { { group_by: nil } }
end
it_behaves_like 'transforms' do
let(:params) { { groupBy: '' } }
let(:expected) { { group_by: nil } }
end
end
context 'not given' do
let(:params) { { bla: 'foo' } }
it 'does not set group_by' do
expect(subject).to be_success
expect(subject.result).not_to have_key(:group_by)
end
end
context 'with an attribute called differently in v3' do
it_behaves_like 'transforms' do
let(:params) { { groupBy: 'assignee' } }
let(:expected) { { group_by: 'assigned_to' } }
end
end
end
context 'with columns' do
context 'as columns' do
it_behaves_like 'transforms' do
let(:params) { { columns: %w(status assignee) } }
let(:expected) { { columns: %w(status assigned_to) } }
end
end
context 'as "c"' do
it_behaves_like 'transforms' do
let(:params) { { c: %w(status assignee) } }
let(:expected) { { columns: %w(status assigned_to) } }
end
end
context 'as column_names' do
it_behaves_like 'transforms' do
let(:params) { { column_names: %w(status assignee) } }
let(:expected) { { columns: %w(status assigned_to) } }
end
end
end
context 'with highlighted_attributes' do
it_behaves_like 'transforms' do
let(:params) { { highlightedAttributes: %w(status type priority dueDate) } }
# Please note, that dueDate is expected to get translated to due_date.
let(:expected) { { highlighted_attributes: %w(status type priority due_date) } }
end
it_behaves_like 'transforms' do
let(:params) { { highlightedAttributes: %w(/api/v3/columns/status /api/v3/columns/type) } }
# Please note, that dueDate is expected to get translated to due_date.
let(:expected) { { highlighted_attributes: %w(status type) } }
end
end
context 'without highlighted_attributes' do
it_behaves_like 'transforms' do
let(:params) { { highlightedAttributes: nil } }
let(:expected) { {} }
end
end
context 'with display_representation' do
it_behaves_like 'transforms' do
let(:params) { { displayRepresentation: 'cards' } }
let(:expected) { { display_representation: 'cards' } }
end
end
context 'without display_representation' do
it_behaves_like 'transforms' do
let(:params) { { displayRepresentation: nil } }
let(:expected) { {} }
end
end
context 'with sort' do
context 'as sortBy in comma separated value' do
it_behaves_like 'transforms' do
let(:params) { { sortBy: JSON::dump([%w(status desc)]) } }
let(:expected) { { sort_by: [%w(status desc)] } }
end
end
context 'as sortBy in colon concatenated value' do
it_behaves_like 'transforms' do
let(:params) { { sortBy: JSON::dump(['status:desc']) } }
let(:expected) { { sort_by: [%w(status desc)] } }
end
end
context 'with an invalid JSON' do
let(:params) { { sortBy: 'faulty' + JSON::dump(['status:desc']) } }
it 'is not success' do
expect(subject)
.not_to be_success
end
it 'returns the error' do
message = 'unexpected token at \'faulty["status:desc"]\''
expect(subject.errors.messages[:base].length)
.to be(1)
expect(subject.errors.messages[:base][0])
.to end_with(message)
end
end
end
context 'with filters' do
context 'as filters in dumped json' do
context 'with a filter named internally' do
it_behaves_like 'transforms' do
let(:params) do
{ filters: JSON::dump([{ 'status_id' => { 'operator' => '=',
'values' => %w(1 2) } }]) }
end
let(:expected) do
{ filters: [{ field: 'status_id', operator: '=', values: %w(1 2) }] }
end
end
end
context 'with a filter named according to v3' do
it_behaves_like 'transforms' do
let(:params) do
{ filters: JSON::dump([{ 'status' => { 'operator' => '=',
'values' => %w(1 2) } }]) }
end
let(:expected) do
{ filters: [{ field: 'status_id', operator: '=', values: %w(1 2) }] }
end
end
it_behaves_like 'transforms' do
let(:params) do
{ filters: JSON::dump([{ 'subprojectId' => { 'operator' => '=',
'values' => %w(1 2) } }]) }
end
let(:expected) do
{ filters: [{ field: 'subproject_id', operator: '=', values: %w(1 2) }] }
end
end
it_behaves_like 'transforms' do
let(:params) do
{ filters: JSON::dump([{ 'watcher' => { 'operator' => '=',
'values' => %w(1 2) } }]) }
end
let(:expected) do
{ filters: [{ field: 'watcher_id', operator: '=', values: %w(1 2) }] }
end
end
it_behaves_like 'transforms' do
let(:params) do
{ filters: JSON::dump([{ 'custom_field_1' => { 'operator' => '=',
'values' => %w(1 2) } }]) }
end
let(:expected) do
{ filters: [{ field: 'cf_1', operator: '=', values: %w(1 2) }] }
end
end
end
context 'with an invalid JSON' do
let(:params) do
{ filters: 'faulty' + JSON::dump([{ 'status' => { 'operator' => '=',
'values' => %w(1 2) } }]) }
end
it 'is not success' do
expect(subject)
.not_to be_success
end
it 'returns the error' do
message = 'unexpected token at ' +
"'faulty[{\"status\":{\"operator\":\"=\",\"values\":[\"1\",\"2\"]}}]'"
expect(subject.errors.messages[:base].length)
.to be(1)
expect(subject.errors.messages[:base][0])
.to end_with(message)
end
end
context 'with an empty array (in JSON)' do
it_behaves_like 'transforms' do
let(:params) do
{ filters: JSON::dump([]) }
end
let(:expected) do
{ filters: [] }
end
end
end
end
end
context 'with showSums' do
it_behaves_like 'transforms' do
let(:params) { { showSums: 'true' } }
let(:expected) { { display_sums: true } }
end
it_behaves_like 'transforms' do
let(:params) { { showSums: 'false' } }
let(:expected) { { display_sums: false } }
end
end
context 'with timelineLabels' do
let(:input) { { left: 'a', right: 'b', farRight: 'c' } }
it_behaves_like 'transforms' do
let(:params) { { timelineLabels: input.to_json } }
let(:expected) { { timeline_labels: input.stringify_keys } }
end
end
context 'with includeSubprojects' do
it_behaves_like 'transforms' do
let(:params) { { includeSubprojects: 'true' } }
let(:expected) { { include_subprojects: true } }
end
it_behaves_like 'transforms' do
let(:params) { { includeSubprojects: 'false' } }
let(:expected) { { include_subprojects: false } }
end
end
context 'with timestamps' do
it_behaves_like 'transforms' do
let(:params) { { timestamps: "" } }
let(:expected) { { timestamps: [] } }
end
it_behaves_like 'transforms' do
let(:params) { { timestamps: "P-0Y" } }
let(:expected) { { timestamps: [Timestamp.parse("P-0Y")] } }
end
it_behaves_like 'transforms' do
let(:params) { { timestamps: "2022-10-29T23:01:23Z, P-0Y" } }
let(:expected) { { timestamps: [Timestamp.parse("2022-10-29T23:01:23Z"), Timestamp.parse("P-0Y")] } }
end
it_behaves_like 'transforms' do
let(:params) { { timestamps: "-1y, now" } }
let(:expected) { { timestamps: [Timestamp.new("P-1Y"), Timestamp.new("PT0S")] } }
end
it_behaves_like 'transforms' do
let(:params) { { timestamps: "oneMonthAgo@11:00+00:00, now" } }
let(:expected) { { timestamps: [Timestamp.parse("oneMonthAgo@11:00+00:00"), Timestamp.new("PT0S")] } }
end
it_behaves_like 'transforms' do
let(:params) { { timestamps: "oneMonthAgo@11:00+00:00, oneWeekAgo@12:00+10:00" } }
let(:expected) { { timestamps: [Timestamp.parse("oneMonthAgo@11:00+00:00"), Timestamp.parse("oneWeekAgo@12:00+10:00")] } }
end
describe "for invalid parameters" do
let(:params) { { timestamps: "foo,bar" } }
it 'is not success' do
expect(subject).not_to be_success
end
it 'returns the error' do
expect(subject.errors.messages[:base].length).to be(1)
expect(subject.errors.messages[:base][0]).to include "\"foo\""
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
# Handles setting the attributes of a wiki page.
# The wiki page is treated as one single entity although the data layer separates
# between the page and the content.
#
# In the long run, those two should probably be unified on the data layer as well.
#
# Attributes for both the page as well as for the content are accepted.
class WikiPages::SetAttributesService < BaseServices::SetAttributes
include Attachments::SetReplacements
private
def set_default_attributes(_params)
model.extend(OpenProject::ChangedBySystem)
model.change_by_system do
model.author = user
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe WikiPages::SetAttributesService, type: :model do
let(:user) { build_stubbed(:user) }
let(:contract_class) do
contract = double('contract_class')
allow(contract)
.to receive(:new)
.with(wiki_page, user, options: {})
.and_return(contract_instance)
contract
end
let(:contract_instance) do
double('contract_instance', validate: contract_valid, errors: contract_errors)
end
let(:contract_valid) { true }
let(:contract_errors) do
double('contract_errors')
end
let(:wiki_page_valid) { true }
let(:instance) do
described_class.new(user:,
model: wiki_page,
contract_class:)
end
let(:call_attributes) { {} }
let(:wiki_page) do
build_stubbed(:wiki_page)
end
describe 'call' do
let(:call_attributes) do
{
text: 'some new text',
title: 'a new title',
slug: 'a new slug',
journal_notes: 'the journal notes'
}
end
before do
allow(wiki_page)
.to receive(:valid?)
.and_return(wiki_page_valid)
expect(contract_instance)
.to receive(:validate)
.and_return(contract_valid)
end
subject { instance.call(call_attributes) }
it 'is successful' do
expect(subject).to be_success
end
context 'for an existing wiki page' do
it 'sets the attributes' do
subject
expect(wiki_page.attributes.slice(*wiki_page.changed).symbolize_keys)
.to eql call_attributes.slice(:title, :slug, :text)
expect(wiki_page.journal_notes)
.to eql call_attributes[:journal_notes]
end
it 'does not persist the wiki_page' do
expect(wiki_page)
.not_to receive(:save)
subject
end
end
context 'for a new wiki page' do
let(:wiki_page) do
WikiPage.new
end
it 'sets the attributes with the user being the author' do
subject
expect(wiki_page.attributes.slice(*wiki_page.changed).symbolize_keys)
.to eql call_attributes.slice(:title, :slug, :text).merge(author_id: user.id)
expect(wiki_page.journal_notes)
.to eql call_attributes[:journal_notes]
end
it 'marks the author to be system changed' do
subject
expect(wiki_page.changed_by_system['author_id'])
.to eql [nil, user.id]
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
# See also: create_service.rb for comments
class OAuthClients::SetAttributesService < BaseServices::SetAttributes
private
def set_attributes(params)
super(replace_client_secret_with_nil(params))
end
def replace_client_secret_with_nil(params)
cloned_param = params.clone
if cloned_param[:client_secret] == ''
cloned_param.merge!(client_secret: nil)
end
cloned_param
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe OAuthClients::SetAttributesService, type: :model do
let(:current_user) { build_stubbed(:admin) }
let(:contract_instance) do
contract = instance_double(OAuthClients::CreateContract, 'contract_instance')
allow(contract)
.to receive(:validate)
.and_return(contract_valid)
allow(contract)
.to receive(:errors)
.and_return(contract_errors)
contract
end
let(:contract_errors) { instance_double(ActiveModel::Errors, 'contract_errors') }
let(:contract_valid) { true }
let(:model_valid) { true }
let(:instance) do
described_class.new(user: current_user, model: model_instance, contract_class:, contract_options: {})
end
let(:model_instance) { OAuthClient.new }
let(:contract_class) do
allow(OAuthClients::CreateContract)
.to receive(:new)
.and_return(contract_instance)
OAuthClients::CreateContract
end
let(:params) { {} }
before do
allow(model_instance)
.to receive(:valid?)
.and_return(model_valid)
end
subject { instance.call(params) }
it 'returns the instance as the result' do
expect(subject.result)
.to eql model_instance
end
it 'is a success' do
expect(subject)
.to be_success
end
context 'with params' do
let(:params) do
{
client_id: '0123456789-client_id',
client_secret: '1234567890-client_secret'
}
end
before do
subject
end
it 'assigns the params' do
expect(model_instance.client_id).to eq '0123456789-client_id'
expect(model_instance.client_secret).to eq '1234567890-client_secret'
end
end
context 'with an invalid contract' do
let(:contract_valid) { false }
it 'returns failure' do
expect(subject).not_to be_success
end
it "returns the contract's errors" do
expect(subject.errors)
.to eql(contract_errors)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require "rack/oauth2"
require "uri/http"
module OAuthClients
class ConnectionManager
# Nextcloud API endpoint to check if Bearer token is valid
TOKEN_IS_FRESH_DURATION = 10.seconds.freeze
def initialize(user:, configuration:)
@user = user
@oauth_client = configuration.oauth_client
@config = configuration
end
# Main method to initiate the OAuth2 flow called by a "client" component
# that wants to access OAuth2 protected resources.
# Returns an OAuthClientToken object or a String in case a renew is required.
# @param state (OAuth2 RFC) encapsulates the state of the calling page (URL + params) to return
# @param scope (OAuth2 RFC) specifies the resources to access. Nextcloud only has one global scope.
# @return ServiceResult with ServiceResult.result being either an OAuthClientToken or a redirection URL
def get_access_token(state: nil)
# Check for an already existing token from last call
token = get_existing_token
return ServiceResult.success(result: token) if token.present?
# Return the Nextcloud OAuth authorization URI that a user needs to open to grant access and eventually obtain
# a token.
@redirect_url = get_authorization_uri(state:)
ServiceResult.failure(result: @redirect_url)
end
# rubocop:disable Metrics/AbcSize
# The bearer/access token has expired or is due for renew for other reasons.
# Talk to OAuth2 Authorization Server to exchange the renew_token for a new bearer token.
def refresh_token
OAuthClientToken.transaction do
oauth_client_token = OAuthClientToken.lock('FOR UPDATE').find_by(user_id: @user, oauth_client_id: @oauth_client.id)
if oauth_client_token.present?
if (Time.current - oauth_client_token.updated_at) > TOKEN_IS_FRESH_DURATION
service_result = request_new_token(refresh_token: oauth_client_token.refresh_token)
if service_result.success?
update_oauth_client_token(oauth_client_token, service_result.result)
else
service_result
end
else
ServiceResult.success(result: oauth_client_token)
end
else
storage_error = ::Storages::StorageError.new(
code: :error,
log_message: I18n.t('oauth_client.errors.refresh_token_called_without_existing_token')
)
ServiceResult.failure(result: :error, errors: storage_error)
end
end
end
# rubocop:enable Metrics/AbcSize
# Returns the URI of the "authorize" endpoint of the OAuth2 Authorization Server.
# @param state (OAuth2 RFC) is a nonce referencing a cookie containing the calling page (URL + params) to which to
# return to at the end of the whole flow.
# @param scope (OAuth2 RFC) specifies the resources to access. Nextcloud has only one global scope.
def get_authorization_uri(state: nil)
client = rack_oauth_client # Configure and start the rack-oauth2 client
client.authorization_uri(scope: @config.scope, state:)
end
# rubocop:disable Metrics/AbcSize
# Called by callback_page with a cryptographic "code" that indicates
# that the user has successfully authorized the OAuth2 Authorization Server.
# We now are going to exchange this code to a token (bearer+refresh)
def code_to_token(code)
# Return a Rack::OAuth2::AccessToken::Bearer or an error string
service_result = request_new_token(authorization_code: code)
return service_result unless service_result.success?
# Check for existing OAuthClientToken and update,
# or create a new one from Rack::OAuth::AccessToken::Bearer
oauth_client_token = get_existing_token
if oauth_client_token.present?
update_oauth_client_token(oauth_client_token, service_result.result)
else
rack_access_token = service_result.result
oauth_client_token =
OAuthClientToken.create(
user: @user,
oauth_client: @oauth_client,
origin_user_id: rack_access_token.raw_attributes[:user_id], # ID of user at OAuth2 Authorization Server
access_token: rack_access_token.access_token,
token_type: rack_access_token.token_type, # :bearer
refresh_token: rack_access_token.refresh_token,
expires_in: rack_access_token.raw_attributes[:expires_in],
scope: rack_access_token.scope
)
OpenProject::Notifications.send(
OpenProject::Events::OAUTH_CLIENT_TOKEN_CREATED,
integration_type: @oauth_client.integration_type
)
end
ServiceResult.success(result: oauth_client_token)
end
# rubocop:enable Metrics/AbcSize
# Called by StorageRepresenter to inquire about the status of the OAuth2
# authentication server.
# Returns :connected/:authorization_failed or :error for a general error.
# We have decided to distinguish between only these 3 cases, because the
# front-end (and a normal user) probably wouldn't know how to deal with
# other options.
def authorization_state
oauth_client_token = get_existing_token
return :failed_authorization unless oauth_client_token
state = @config.authorization_state_check(oauth_client_token.access_token)
case state
when :success
:connected
when :refresh_needed
service_result = refresh_token
if service_result.success?
:connected
elsif service_result.errors.data.payload[:error] == 'invalid_request'
:failed_authorization
else
:error
end
else
state
end
rescue StandardError
:error
end
# @returns ServiceResult with result to be :error or any type of object with data
def request_with_token_refresh(oauth_client_token)
# `yield` needs to returns a ServiceResult:
# success: result= any object with data
# failure: result= :error or :unauthorized
yield_service_result = yield(oauth_client_token)
if yield_service_result.failure? && yield_service_result.result == :unauthorized
refresh_service_result = refresh_token
return refresh_service_result if refresh_service_result.failure?
oauth_client_token.reload
yield_service_result = yield(oauth_client_token) # Should contain result=<data> in case of success
end
yield_service_result
end
private
# Check if a OAuthClientToken already exists and return nil otherwise.
# Don't handle the case of an expired token.
def get_existing_token
# Check if we've got a token in the database and return nil otherwise.
OAuthClientToken.find_by(user_id: @user, oauth_client_id: @oauth_client.id)
end
def request_new_token(options = {})
rack_access_token = rack_oauth_client(options).access_token!(:body)
ServiceResult.success(result: rack_access_token)
rescue Rack::OAuth2::Client::Error => e
service_result_with_error(:bad_request, e.response, i18n_rack_oauth2_error_message(e))
rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::ParsingError, Faraday::SSLError => e
service_result_with_error(
:internal_server_error,
e,
"#{I18n.t('oauth_client.errors.oauth_returned_http_error')}: #{e.class}: #{e.message.to_html}"
)
rescue StandardError => e
service_result_with_error(
:error,
e,
"#{I18n.t('oauth_client.errors.oauth_returned_standard_error')}: #{e.class}: #{e.message.to_html}"
)
end
def i18n_rack_oauth2_error_message(rack_oauth2_client_exception)
i18n_key = "oauth_client.errors.rack_oauth2.#{rack_oauth2_client_exception.message}"
if I18n.exists? i18n_key
I18n.t(i18n_key)
else
"#{I18n.t('oauth_client.errors.oauth_returned_error')}: #{rack_oauth2_client_exception.message.to_html}"
end
end
# Return a fully configured RackOAuth2Client.
# This client does all the heavy lifting with the OAuth2 protocol.
def rack_oauth_client(options = {})
rack_oauth_client = @config.basic_rack_oauth_client
# Write options, for example authorization_code and refresh_token
rack_oauth_client.refresh_token = options[:refresh_token] if options[:refresh_token]
rack_oauth_client.authorization_code = options[:authorization_code] if options[:authorization_code]
rack_oauth_client
end
# Update an OpenProject token based on updated values from a
# Rack::OAuth2::AccessToken::Bearer after a OAuth2 refresh operation
def update_oauth_client_token(oauth_client_token, rack_oauth2_access_token)
success = oauth_client_token.update(
access_token: rack_oauth2_access_token.access_token,
refresh_token: rack_oauth2_access_token.refresh_token,
expires_in: rack_oauth2_access_token.expires_in
)
if success
ServiceResult.success(result: oauth_client_token)
else
result = ServiceResult.failure
result.errors.add(:base, I18n.t('oauth_client.errors.refresh_token_updated_failed'))
result.add_dependent!(ServiceResult.failure(errors: oauth_client_token.errors))
result
end
end
def service_result_with_error(code, data, log_message = nil)
error_data = ::Storages::StorageErrorData.new(source: self, payload: data)
ServiceResult.failure(result: code,
errors: ::Storages::StorageError.new(code:, data: error_data, log_message:))
end
end
end
``` | # frozen_string_literal: true
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
using Storages::Peripherals::ServiceResultRefinements
let(:user) { create(:user) }
let(:host) { "https://example.org" }
let(:storage) { create(:nextcloud_storage, :with_oauth_client, host: "#{host}/") }
let(:oauth_client) { storage.oauth_client }
let(:configuration) { storage.oauth_configuration }
let(:scope) { [:all] } # OAuth2 resources to access, specific to provider
let(:oauth_client_token) { create(:oauth_client_token, oauth_client:, user:) }
let(:instance) { described_class.new(user:, configuration:) }
# The get_authorization_uri method returns the OAuth2 authorization URI as a string. That URI is the starting point for
# a user to grant OpenProject access to Nextcloud.
describe '#get_authorization_uri' do
let(:scope) { nil }
let(:state) { nil }
subject { instance.get_authorization_uri(state:) }
context 'with empty state and scope' do
shared_examples_for 'returns the authorization URI relative to the host' do
it 'returns the authorization URI' do
expect(subject).to be_a String
expect(subject).to include oauth_client.integration.host
expect(subject).not_to include "scope"
expect(subject).not_to include "state"
end
end
context 'when Nextcloud is installed in the server root' do
it_behaves_like 'returns the authorization URI relative to the host'
end
context 'when Nextcloud is installed in a sub-directory' do
let(:host) { "https://example.org/nextcloud" }
it_behaves_like 'returns the authorization URI relative to the host'
end
end
context 'with state but empty scope' do
let(:state) { "https://example.com/page" }
it 'returns the redirect URL' do
expect(subject).to be_a String
expect(subject).to include oauth_client.integration.host
expect(subject).not_to include "scope"
expect(subject).to include "&state=https"
end
end
context 'with multiple scopes but empty state' do
let(:scope) { %i(email profile) }
it 'returns the redirect URL' do
allow(configuration).to receive(:scope).and_return(scope)
expect(subject).to be_a String
expect(subject).to include oauth_client.integration.host
expect(subject).not_to include "state"
expect(subject).to include "&scope=email%20profile"
end
end
end
# The first step in the OAuth2 flow is to produce a URL for the
# user to authenticate and authorize access at the OAuth2 provider
# (Nextcloud).
describe '#get_access_token' do
subject { instance.get_access_token }
context 'with no OAuthClientToken present' do
it 'returns a redirection URL' do
expect(subject.success).to be_falsy
expect(subject.result).to be_a String
# Details of string are tested above in section #get_authorization_uri
end
end
context 'with no OAuthClientToken present and state parameters' do
subject { instance.get_access_token(state: "some_state") }
it 'returns the redirect URL' do
allow(configuration).to receive(:scope).and_return(%w[email])
expect(subject.success).to be_falsy
expect(subject.result).to be_a String
expect(subject.result).to include oauth_client.integration.host
expect(subject.result).to include "&state=some_state"
expect(subject.result).to include "&scope=email"
end
end
context 'with an OAuthClientToken present' do
before do
oauth_client_token
end
it 'returns the OAuthClientToken' do
expect(subject).to be_truthy
expect(subject.result).to be_a OAuthClientToken # The one and only...
expect(subject.result).to eql oauth_client_token
end
end
end
# In the second step the Authorization Server (Nextcloud) redirects
# to a "callback" endpoint on the OAuth2 client (OpenProject):
# https://<openproject-server>/oauth_clients/8/callback?state=&code=7kRGJ...jG3KZ
# This callback code basically just calls `code_to_token(code)`.
# The callback endpoint calls `code_to_token(code)` with the code
# received and exchanges the code for a bearer+refresh token
# using a HTTP request.
describe '#code_to_token', :webmock do
let(:code) { "7kRGJ...jG3KZ" }
subject { instance.code_to_token(code) }
context 'with happy path' do
before do
# Simulate a successful authorization returning the tokens
response_body = {
access_token: "yjTDZ...RYvRH",
token_type: "Bearer",
expires_in: 3600,
refresh_token: "UwFp...1FROJ",
user_id: "admin"
}.to_json
stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(status: 200, body: response_body, headers: { "content-type" => "application/json; charset=utf-8" })
end
it 'returns a valid ClientToken object and issues an appropriate event' do
expect(OpenProject::Notifications)
.to(receive(:send))
.with(OpenProject::Events::OAUTH_CLIENT_TOKEN_CREATED, integration_type: "Storages::Storage")
expect(subject.success).to be_truthy
expect(subject.result).to be_a OAuthClientToken
end
end
context 'with known error' do
before do
stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(status: 400,
body: { error: error_message }.to_json,
headers: { "content-type" => "application/json; charset=utf-8" })
end
shared_examples 'OAuth2 error response' do
it 'returns a specific error message' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:bad_request)
expect(subject.error_payload[:error]).to eq(error_message)
end
end
context 'when "invalid_request"' do
let(:error_message) { 'invalid_request' }
it_behaves_like 'OAuth2 error response'
end
context 'when "invalid_grant"' do
let(:error_message) { 'invalid_grant' }
it_behaves_like 'OAuth2 error response'
end
end
context 'with unknown reply' do
before do
stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(status: 400,
body: { error: "invalid_requesttt" }.to_json,
headers: { "content-type" => "application/json; charset=utf-8" })
end
it 'returns an error wrapping the unknown response' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:bad_request)
expect(subject.error_payload[:error]).to eq('invalid_requesttt')
expect(subject.error_source).to be_a(described_class)
expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_error')
end
end
context 'with reply including JSON syntax error' do
before do
stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(
status: 400,
headers: { 'Content-Type' => 'application/json; charset=utf-8' },
body: "some: very, invalid> <json}"
)
end
it 'returns an error wrapping the parsing error' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:internal_server_error)
expect(subject.error_payload.class).to be(Faraday::ParsingError)
expect(subject.error_source).to be_a(described_class)
expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')
end
end
context 'with 500 reply without body' do
before do
stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(status: 500)
end
it 'returns an error wrapping the empty error' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:bad_request)
expect(subject.error_payload[:error]).to eq('Unknown')
end
end
context 'when something is wrong with connection' do
before do
stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token')).to_raise(Faraday::ConnectionFailed)
end
it 'returns an error wrapping the server error' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:internal_server_error)
expect(subject.error_payload.class).to be(Faraday::ConnectionFailed)
expect(subject.error_source).to be_a(described_class)
expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')
end
end
context 'when something is wrong with SSL' do
before do
stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token')).to_raise(Faraday::SSLError)
end
it 'returns an error wrapping the server error' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:internal_server_error)
expect(subject.error_payload.class).to be(Faraday::SSLError)
expect(subject.error_source).to be_a(described_class)
expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')
end
end
context 'with timeout returns internal error' do
before do
stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token')).to_timeout
end
it 'returns an error wrapping the server timeout' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:internal_server_error)
expect(subject.error_payload.class).to be(Faraday::ConnectionFailed)
expect(subject.error_source).to be_a(described_class)
expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')
end
end
end
describe '#refresh_token' do
subject { instance.refresh_token }
context 'without existing OAuthClientToken' do
it 'returns an error message' do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:error)
expect(subject.errors.log_message)
.to include I18n.t('oauth_client.errors.refresh_token_called_without_existing_token')
end
end
context 'with existing OAuthClientToken' do
before { oauth_client_token }
context 'when token is stale' do
before do
oauth_client_token.update_columns(updated_at: 1.day.ago)
end
context 'with successful response from OAuth2 provider (happy path)' do
before do
# Simulate a successful authorization returning the tokens
response_body = {
access_token: "xyjTDZ...RYvRH",
token_type: "Bearer",
expires_in: 3601,
refresh_token: "xUwFp...1FROJ",
user_id: "admin"
}.to_json
stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(status: 200, body: response_body, headers: { "content-type" => "application/json; charset=utf-8" })
end
it 'returns a valid ClientToken object', :webmock do
expect(subject.success).to be_truthy
expect(subject.result).to be_a OAuthClientToken
expect(subject.result.access_token).to eq("xyjTDZ...RYvRH")
expect(subject.result.expires_in).to be(3601)
end
end
context 'with invalid access_token data' do
before do
# Simulate a token too long
response_body = {
access_token: nil, # will fail model validation
token_type: "Bearer",
expires_in: 3601,
refresh_token: "xUwFp...1FROJ",
user_id: "admin"
}.to_json
stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(status: 200, body: response_body, headers: { "content-type" => "application/json; charset=utf-8" })
end
it 'returns dependent error from model validation', :webmock do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:error)
expect(subject.error_payload.class).to be(AttrRequired::AttrMissing)
expect(subject.error_payload.message).to include("'access_token' required.")
end
end
context 'with server error from OAuth2 provider' do
before do
stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_return(status: 400,
body: { error: "invalid_request" }.to_json,
headers: { "content-type" => "application/json; charset=utf-8" })
end
it 'returns a server error', :webmock do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:bad_request)
expect(subject.error_payload[:error]).to eq('invalid_request')
end
end
context 'with successful response but invalid data' do
before do
# Simulate timeout
stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))
.to_timeout
end
it 'returns an error wrapping a timeout', :webmock do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:internal_server_error)
expect(subject.error_payload.class).to be(Faraday::ConnectionFailed)
expect(subject.error_source).to be_a(described_class)
expect(subject.errors.log_message).to include('Faraday::ConnectionFailed: execution expired')
end
end
context 'with parallel requests for refresh', :aggregate_failures do
after do
Storages::Storage.destroy_all
User.destroy_all
OAuthClientToken.destroy_all
OAuthClient.destroy_all
end
it 'requests token only once and other thread uses new token' do
response_body1 = {
access_token: "xyjTDZ...RYvRH",
token_type: "Bearer",
expires_in: 3601,
refresh_token: "xUwFp...1FROJ",
user_id: "admin"
}
response_body2 = response_body1.dup
response_body2[:access_token] = "differ...RYvRH"
request_url = File.join(host, '/index.php/apps/oauth2/api/v1/token')
stub_request(:any, request_url).to_return(
{ status: 200, body: response_body1.to_json, headers: { "content-type" => "application/json; charset=utf-8" } },
{ status: 200, body: response_body2.to_json, headers: { "content-type" => "application/json; charset=utf-8" } }
)
result1 = nil
result2 = nil
thread1 = Thread.new do
ApplicationRecord.connection_pool.with_connection do
result1 = described_class.new(user:, configuration: storage.oauth_configuration).refresh_token.result
end
end
thread2 = Thread.new do
ApplicationRecord.connection_pool.with_connection do
result2 = described_class.new(user:, configuration: storage.oauth_configuration).refresh_token.result
end
end
thread1.join
thread2.join
expect(result1.access_token).to eq(response_body1[:access_token])
expect(result2.access_token).to eq(response_body1[:access_token])
expect(WebMock).to have_requested(:any, request_url).once
end
it 'requests token refresh twice if enough time passes between requests' do
stub_const("OAuthClients::ConnectionManager::TOKEN_IS_FRESH_DURATION", 2.seconds)
response_body1 = {
access_token: "xyjTDZ...RYvRH",
token_type: "Bearer",
expires_in: 3601,
refresh_token: "xUwFp...1FROJ",
user_id: "admin"
}
response_body2 = response_body1.dup
response_body2[:access_token] = "differ...RYvRH"
request_url = File.join(host, '/index.php/apps/oauth2/api/v1/token')
headers = { "content-type" => "application/json; charset=utf-8" }
stub_request(:any, request_url)
.to_return(status: 200, body: response_body1.to_json, headers:).then
.to_return(status: 200, body: response_body2.to_json, headers:)
result1 = nil
result2 = nil
thread1 = Thread.new do
ApplicationRecord.connection_pool.with_connection do
sleep(3)
result1 = described_class.new(user:, configuration: storage.oauth_configuration).refresh_token.result
end
end
thread2 = Thread.new do
ApplicationRecord.connection_pool.with_connection do
result2 = described_class.new(user:, configuration: storage.oauth_configuration).refresh_token.result
end
end
thread1.join
thread2.join
expect([result1.access_token,
result2.access_token]).to contain_exactly(response_body1[:access_token], response_body2[:access_token])
expect(WebMock).to have_requested(:any, request_url).twice
end
end
end
context 'when token is fresh' do
it 'does not send refresh request and respond with existing token', :webmock do
expect(subject.success).to be_truthy
expect(subject.result).to eq(oauth_client_token)
expect { subject }.not_to change(oauth_client_token, :access_token)
end
end
end
end
describe '#authorization_state' do
subject { instance.authorization_state }
context 'without access token present' do
it 'returns :failed_authorization' do
expect(subject).to eq :failed_authorization
end
end
context 'with access token present', :webmock do
before do
oauth_client_token
end
context 'with access token valid' do
context 'without other errors or exceptions' do
before do
allow(configuration).to receive(:authorization_state_check).and_return(:success)
end
it 'returns :connected' do
expect(subject).to eq :connected
end
end
context 'with some other error or exception' do
before do
allow(configuration).to receive(:authorization_state_check).and_return(:error)
end
it 'returns :error' do
expect(subject).to eq :error
end
end
end
context 'with outdated access token' do
let(:new_oauth_client_token) { create(:oauth_client_token) }
let(:refresh_service_result) { ServiceResult.success }
before do
allow(configuration).to receive(:authorization_state_check).and_return(:refresh_needed)
allow(instance).to receive(:refresh_token).and_return(refresh_service_result)
end
context 'with valid refresh token' do
it 'refreshes the access token and returns :connected' do
expect(subject).to eq :connected
expect(instance).to have_received(:refresh_token)
end
end
context 'with invalid refresh token' do
let(:refresh_service_result) do
data = Storages::StorageErrorData.new(source: nil, payload: { error: 'invalid_request' })
ServiceResult.failure(result: :bad_request,
errors: Storages::StorageError.new(code: :bad_request, data:))
end
it 'refreshes the access token and returns :failed_authorization' do
expect(subject).to eq :failed_authorization
expect(instance).to have_received(:refresh_token)
end
end
context 'with some other error while refreshing access token' do
let(:refresh_service_result) { ServiceResult.failure }
it 'returns :error' do
expect(subject).to eq :error
expect(instance).to have_received(:refresh_token)
end
end
end
end
context 'with both invalid access token and refresh token', :webmock do
it 'returns :failed_authorization' do
expect(subject).to eq :failed_authorization
end
end
end
describe '#request_with_token_refresh' do
let(:yield_service_result) { ServiceResult.success }
let(:refresh_service_result) { ServiceResult.success }
subject do
instance.request_with_token_refresh(oauth_client_token) { yield_service_result }
end
before do
allow(instance).to receive(:refresh_token).and_return(refresh_service_result)
allow(oauth_client_token).to receive(:reload)
end
context 'with yield returning :success' do
it 'returns a ServiceResult with success, without refreshing the token' do
expect(subject.success).to be_truthy
expect(instance).not_to have_received(:refresh_token)
expect(oauth_client_token).not_to have_received(:reload)
end
end
context 'with yield returning :error' do
let(:yield_service_result) { ServiceResult.failure(result: :error) }
it 'returns a ServiceResult with success, without refreshing the token' do
expect(subject.success).to be_falsy
expect(subject.result).to be :error
expect(instance).not_to have_received(:refresh_token)
expect(oauth_client_token).not_to have_received(:reload)
end
end
context 'with yield returning :unauthorized and the refresh returning a with a success' do
let(:yield_service_result) { ServiceResult.failure(result: :unauthorized) }
it 'returns a ServiceResult with success, without refresh' do
expect(subject.success).to be_falsy
expect(subject.result).to be :unauthorized
expect(instance).to have_received(:refresh_token)
expect(oauth_client_token).to have_received(:reload)
end
end
context 'with yield returning :unauthorized and the refresh returning with a :failure' do
let(:yield_service_result) { ServiceResult.failure(result: :unauthorized) }
let(:refresh_service_result) do
data = Storages::StorageErrorData.new(source: nil, payload: { error: 'invalid_request' })
ServiceResult.failure(result: :error,
errors: Storages::StorageError.new(code: :error, data:))
end
it 'returns a ServiceResult with success, without refresh' do
expect(subject.success).to be_falsy
expect(subject.result).to be :error
expect(instance).to have_received(:refresh_token)
expect(oauth_client_token).not_to have_received(:reload)
end
end
context 'with yield returning :unauthorized first time and :success the second time' do
let(:yield_double_object) { Object.new }
let(:yield_service_result1) { ServiceResult.failure(result: :unauthorized) }
let(:yield_service_result2) { ServiceResult.success }
let(:refresh_service_result) { ServiceResult.success }
subject do
instance.request_with_token_refresh(oauth_client_token) { yield_double_object.yield_twice_method }
end
before do
allow(instance).to receive(:refresh_token).and_return refresh_service_result
allow(yield_double_object)
.to receive(:yield_twice_method)
.and_return(
yield_service_result1,
yield_service_result2
)
end
it 'returns a ServiceResult with success, without refresh' do
expect(subject.success).to be_truthy
expect(subject).to be yield_service_result2
expect(instance).to have_received(:refresh_token)
expect(oauth_client_token).to have_received(:reload)
expect(yield_double_object).to have_received(:yield_twice_method).twice
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require "rack/oauth2"
require "uri/http"
module OAuthClients
class RedirectUriFromStateService
def initialize(state:, cookies:)
@state = state
@cookies = cookies
end
def call
redirect_uri = oauth_state_cookie
if redirect_uri.present? && ::API::V3::Utilities::PathHelper::ApiV3Path::same_origin?(redirect_uri)
ServiceResult.success(result: redirect_uri)
else
ServiceResult.failure
end
end
private
def oauth_state_cookie
return nil if @state.blank?
state_cookie = @cookies["oauth_state_#{@state}"]
return nil if state_cookie.blank?
state_value = MultiJson.load(@cookies["oauth_state_#{@state}"], symbolize_keys: true)
state_value[:href]
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'webmock/rspec'
RSpec.describe OAuthClients::RedirectUriFromStateService, type: :model do
let(:state) { 'asdf123425' }
let(:redirect_uri) { File.join(API::V3::Utilities::PathHelper::ApiV3Path::root_url, 'foo/bar') }
let(:cookies) { { "oauth_state_#{state}": { href: redirect_uri }.to_json }.with_indifferent_access }
let(:instance) { described_class.new(state:, cookies:) }
describe '#call' do
subject { instance.call }
shared_examples 'failed service result' do
it 'return a failed service result' do
expect(subject).to be_failure
end
end
context 'when cookie found' do
context 'when redirect_uri has same origin' do
it 'returns the redirect URL value from the cookie' do
expect(subject).to be_success
end
end
context 'when redirect_uri does not share same origin' do
let(:redirect_uri) { 'https://some-other-origin.com/bla' }
it_behaves_like 'failed service result'
end
end
context 'when no cookie present' do
let(:cookies) { {} }
it_behaves_like 'failed service result'
end
context 'when no state present' do
let(:state) { nil }
it_behaves_like 'failed service result'
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
# The logic for creating storage was extracted from the controller and put into
# a service: https://dev.to/joker666/ruby-on-rails-pattern-service-objects-b19
# Purpose: create and persist a Storages::Storage record
# Used by: Storages::Admin::StoragesController#create, could also be used by the
# API in the future.
# The comments here are also valid for the other *_service.rb files
module OAuthClients
class CreateService < ::BaseServices::Create
protected
def before_perform(params, _service_result)
OAuthClient.where(integration: params[:integration]).delete_all
super
end
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_create_service'
RSpec.describe OAuthClients::CreateService, type: :model do
it_behaves_like 'BaseServices create service' do
let(:factory) { :oauth_client }
context 'if another oauth client for the given integration exists' do
let(:storage) { create(:nextcloud_storage) }
let!(:existing_client) { create(:oauth_client, integration: storage) }
let!(:model_instance) { build_stubbed(:oauth_client, integration: storage) }
let(:call_attributes) { { name: 'Death Star', integration: storage } }
it 'overwrites the existing oauth client' do
# Test setup still returns success, but `subject` must be initialized
expect(subject).to be_success
expect(OAuthClient.where(id: existing_client.id)).not_to exist
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
# See also: create_service.rb for comments
module OAuthClients
class DeleteService < ::BaseServices::Delete
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_delete_service'
RSpec.describe OAuthClients::DeleteService, type: :model do
it_behaves_like 'BaseServices delete service' do
let(:factory) { :oauth_client }
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
module Members
class SetAttributesService < ::BaseServices::SetAttributes
include Members::Concerns::RoleAssignment
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
RSpec.describe Members::SetAttributesService, type: :model do
let(:user) { build_stubbed(:user) }
let(:contract_class) do
contract = double('contract_class')
allow(contract)
.to receive(:new)
.with(member, user, options: {})
.and_return(contract_instance)
contract
end
let(:contract_instance) do
double('contract_instance', validate: contract_valid, errors: contract_errors)
end
let(:contract_valid) { true }
let(:contract_errors) do
double('contract_errors')
end
let(:member_valid) { true }
let(:instance) do
described_class.new(user:,
model: member,
contract_class:)
end
let(:call_attributes) { {} }
let(:member) do
build_stubbed(:member)
end
describe 'call' do
let(:call_attributes) do
{
project_id: 5,
user_id: 3
}
end
before do
allow(member)
.to receive(:valid?)
.and_return(member_valid)
expect(contract_instance)
.to receive(:validate)
.and_return(contract_valid)
end
subject { instance.call(call_attributes) }
it 'is successful' do
expect(subject.success?).to be_truthy
end
it 'sets the attributes' do
subject
expect(member.attributes.slice(*member.changed).symbolize_keys)
.to eql call_attributes
end
it 'does not persist the member' do
expect(member)
.not_to receive(:save)
subject
end
context 'with changes to the roles do' do
let(:first_role) { build_stubbed(:project_role) }
let(:second_role) { build_stubbed(:project_role) }
let(:third_role) { build_stubbed(:project_role) }
let(:call_attributes) do
{
role_ids: [second_role.id, third_role.id]
}
end
context 'with a persisted record' do
let(:member) do
build_stubbed(:member, roles: [first_role, second_role])
end
it 'adds the new role and marks the other for destruction' do
expect(subject.result.member_roles.map(&:role_id)).to contain_exactly(first_role.id, second_role.id, third_role.id)
expect(subject.result.member_roles.detect { _1.role_id == first_role.id }).to be_marked_for_destruction
end
end
context 'with a new record' do
let(:member) do
Member.new
end
it 'adds the new role' do
expect(subject.result.member_roles.map(&:role_id)).to contain_exactly(second_role.id, third_role.id)
end
context 'with role_ids not all being present' do
let(:call_attributes) do
{
role_ids: [nil, '', second_role.id, third_role.id]
}
end
it 'ignores the empty values' do
expect(subject.result.member_roles.map(&:role_id)).to contain_exactly(second_role.id, third_role.id)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Members::UpdateService < BaseServices::Update
include Members::Concerns::CleanedUp
include Members::Concerns::NotificationSender
around_call :post_process
private
def post_process
service_call = yield
return unless service_call.success?
member = service_call.result
if member.principal.is_a?(Group)
update_group_roles(member)
else
send_notification(member)
end
end
def update_group_roles(member)
Groups::UpdateRolesService
.new(member.principal, current_user: user, contract_class: EmptyContract)
.call(member:, send_notifications: send_notifications?, message: notification_message)
end
def event_type
OpenProject::Events::MEMBER_UPDATED
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe Members::UpdateService, type: :model do
it_behaves_like 'BaseServices update service' do
let(:call_attributes) do
{
role_ids: ["2"],
notification_message: "Wish you where **here**.",
send_notifications: false
}
end
before do
allow(OpenProject::Notifications)
.to receive(:send)
end
describe 'if successful' do
it 'sends a notification' do
subject
expect(OpenProject::Notifications)
.to have_received(:send)
.with(OpenProject::Events::MEMBER_UPDATED,
member: model_instance,
message: call_attributes[:notification_message],
send_notifications: call_attributes[:send_notifications])
end
end
context 'if the SetAttributeService is unsuccessful' do
let(:set_attributes_success) { false }
it 'sends no notifications' do
subject
expect(OpenProject::Notifications)
.not_to have_received(:send)
end
end
context 'when the member is invalid' do
let(:model_save_result) { false }
it 'sends no notifications' do
subject
expect(OpenProject::Notifications)
.not_to have_received(:send)
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Members::CreateService < BaseServices::Create
include Members::Concerns::NotificationSender
around_call :post_process
def post_process
service_call = yield
return unless service_call.success?
member = service_call.result
add_group_memberships(member)
send_notification(member)
end
protected
def add_group_memberships(member)
return unless member.principal.is_a?(Group)
Groups::CreateInheritedRolesService
.new(member.principal, current_user: user, contract_class: EmptyContract)
.call(user_ids: member.principal.user_ids, send_notifications: false, project_ids: [member.project_id])
end
def event_type
OpenProject::Events::MEMBER_CREATED
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_create_service'
RSpec.describe Members::CreateService, type: :model do
let(:user1) { build_stubbed(:user) }
let(:user2) { build_stubbed(:user) }
let(:group) do
build_stubbed(:group).tap do |g|
allow(g)
.to receive(:user_ids)
.and_return([user1.id, user2.id])
end
end
let!(:inherited_roles_service) do
instance_double(Groups::CreateInheritedRolesService).tap do |inherited_roles_service|
allow(Groups::CreateInheritedRolesService)
.to receive(:new)
.and_return(inherited_roles_service)
allow(inherited_roles_service)
.to receive(:call)
end
end
let!(:notifications) do
allow(OpenProject::Notifications)
.to receive(:send)
end
it_behaves_like 'BaseServices create service' do
let(:call_attributes) do
{
project_id: "1",
user_id: "2",
role_ids: ["2"],
notification_message: "Wish you where **here**.",
send_notifications: true
}
end
describe 'if successful' do
it 'sends a notification' do
subject
expect(OpenProject::Notifications)
.to have_received(:send)
.with(OpenProject::Events::MEMBER_CREATED,
member: model_instance,
message: call_attributes[:notification_message],
send_notifications: true)
end
describe 'for a group' do
let!(:model_instance) { build_stubbed(:member, principal: group) }
it "generates the members and roles for the group's users" do
subject
expect(Groups::CreateInheritedRolesService)
.to have_received(:new)
.with(group,
current_user: user,
contract_class: EmptyContract)
expect(inherited_roles_service)
.to have_received(:call)
.with(user_ids: group.user_ids,
project_ids: [model_instance.project_id],
send_notifications: false)
end
end
end
context 'if the SetAttributeService is unsuccessful' do
let(:set_attributes_success) { false }
it 'sends no notification' do
subject
expect(OpenProject::Notifications)
.not_to have_received(:send)
end
describe 'for a group' do
let!(:model_instance) { build_stubbed(:member, principal: group) }
it "does not create any inherited roles" do
subject
expect(Groups::CreateInheritedRolesService)
.not_to have_received(:new)
end
end
end
context 'when the member is invalid' do
let(:model_save_result) { false }
it 'sends no notification' do
subject
expect(OpenProject::Notifications)
.not_to have_received(:send)
end
context 'for a group' do
let!(:model_instance) { build_stubbed(:member, principal: group) }
it "does not create any inherited roles" do
subject
expect(Groups::CreateInheritedRolesService)
.not_to have_received(:new)
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
class Members::DeleteService < BaseServices::Delete
include Members::Concerns::CleanedUp
protected
def after_perform(service_call)
super(service_call).tap do |call|
member = call.result
cleanup_for_group(member)
send_notification(member)
end
end
def send_notification(member)
::OpenProject::Notifications.send(OpenProject::Events::MEMBER_DESTROYED,
member:)
end
def cleanup_for_group(member)
return unless member.principal.is_a?(Group)
Groups::CleanupInheritedRolesService
.new(member.principal, current_user: user, contract_class: EmptyContract)
.call
end
end
``` | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
#++
require 'spec_helper'
require 'services/base_services/behaves_like_delete_service'
RSpec.describe Members::DeleteService, type: :model do
it_behaves_like 'BaseServices delete service' do
let(:principal) { user }
before do
model_instance.principal = principal
allow(OpenProject::Notifications)
.to receive(:send)
end
let!(:cleanup_service_instance) do
instance = instance_double(Members::CleanupService, call: nil)
allow(Members::CleanupService)
.to receive(:new)
.with(principal, model_instance.project_id)
.and_return(instance)
instance
end
describe '#call' do
context 'when contract validates and the model is destroyed successfully' do
it 'calls the cleanup service' do
service_call
expect(cleanup_service_instance)
.to have_received(:call)
end
it 'sends a notification' do
service_call
expect(OpenProject::Notifications)
.to have_received(:send)
.with(OpenProject::Events::MEMBER_DESTROYED, member: model_instance)
end
context 'when the model`s principal is a group' do
let(:principal) { build_stubbed(:group) }
let!(:cleanup_inherited_roles_service_instance) do
instance = instance_double(Groups::CleanupInheritedRolesService, call: nil)
allow(Groups::CleanupInheritedRolesService)
.to receive(:new)
.with(principal,
current_user: user,
contract_class: EmptyContract)
.and_return(instance)
instance
end
it 'calls the cleanup inherited roles service' do
service_call
expect(cleanup_inherited_roles_service_instance)
.to have_received(:call)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2010-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
module WorkPackageMembers
class SetAttributesService < ::BaseServices::SetAttributes
prepend WorkPackageMembers::Concerns::RoleAssignment
private
def set_attributes(params)
super
model.change_by_system do
model.project = model.entity&.project
end
end
end
end
``` | # -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2010-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
require 'spec_helper'
RSpec.describe WorkPackageMembers::SetAttributesService, type: :model do
let(:user) { build_stubbed(:user) }
let(:work_package) { build_stubbed(:work_package) }
let(:member) do
new_member
end
let(:new_member) { Member.new }
let(:existing_member) { build_stubbed(:work_package_member) }
let(:contract_class) do
allow(WorkPackageMembers::CreateContract)
.to receive(:new)
.with(member, user, options: {})
.and_return(contract_instance)
WorkPackageMembers::CreateContract
end
let(:contract_instance) do
instance_double(WorkPackageMembers::CreateContract, validate: contract_valid, errors: contract_errors)
end
let(:contract_valid) { true }
let(:contract_errors) do
instance_double(ActiveModel::Errors)
end
let(:instance) do
described_class.new(user:,
model: member,
contract_class:)
end
describe 'call' do
let(:call_attributes) do
{
user_id: 3,
entity: work_package
}
end
before do
allow(contract_instance)
.to receive(:validate)
.and_return(contract_valid)
allow(member)
.to receive(:save)
.and_return true
end
subject { instance.call(call_attributes) }
it 'is successful' do
expect(subject).to be_success
end
it 'does not persist the member' do
subject
expect(member)
.not_to have_received(:save)
end
context 'for a new record' do
it 'sets the attributes and also takes the project_id from the work package' do
subject
expect(member.attributes.slice(*member.changed).symbolize_keys)
.to eql(user_id: 3, entity_id: work_package.id, entity_type: 'WorkPackage', project_id: work_package.project_id)
end
it 'marks the project_id to be changed by the system' do
subject
expect(member.changed_by_system)
.to eql('project_id' => [nil, member.project_id])
end
end
# Changing the entity should not really happen in reality but if it does, this is what happens.
context 'for a persisted record' do
let(:member) { existing_member }
it 'sets the attributes and also takes the project_id from the work package' do
subject
expect(member.attributes.slice(*member.changed).symbolize_keys)
.to eql(user_id: 3, entity_id: work_package.id, project_id: work_package.project_id)
end
it 'marks the project_id to be changed by the system' do
subject
expect(member.changed_by_system)
.to eql('project_id' => [member.project_id_was, member.project_id])
end
end
context 'if the contract is invalid' do
let(:contract_valid) { false }
it 'is unsuccessful' do
expect(subject).not_to be_success
end
it 'returns the errors of the contract' do
expect(subject.errors).to eql contract_errors
end
it 'does not persist the member' do
subject
expect(member)
.not_to have_received(:save)
end
end
context 'with changes to the roles' do
let(:first_role) { build_stubbed(:project_role) }
let(:second_role) { build_stubbed(:project_role) }
let(:third_role) { build_stubbed(:project_role) }
let(:call_attributes) do
{
role_ids: [second_role.id, third_role.id]
}
end
context 'with a persisted record' do
let(:member) do
build_stubbed(:work_package_member, roles: [first_role, second_role])
end
it 'adds the new role and marks the other for destruction' do
expect(subject.result.member_roles.map(&:role_id)).to contain_exactly(first_role.id, second_role.id, third_role.id)
expect(subject.result.member_roles.detect { _1.role_id == first_role.id }).to be_marked_for_destruction
end
context 'when a role being assigned is already inherited via a group' do
let(:member) do
build_stubbed(:work_package_member, roles: [first_role, second_role, third_role])
end
before do
allow(member.member_roles.detect { _1.role_id == third_role.id })
.to receive(:inherited_from)
.and_return(true)
end
it 'still adds the role and marks the ones not added for destruction' do
membership = subject.result
expect(membership.member_roles.map(&:role_id))
.to contain_exactly(first_role.id,
second_role.id,
third_role.id, # One is inherited
third_role.id) # The other one isn't
expect(membership.member_roles.select(&:marked_for_destruction?).map(&:role_id))
.to contain_exactly(first_role.id)
end
end
end
context 'with a new record' do
let(:member) do
Member.new
end
it 'adds the new role' do
expect(subject.result.member_roles.map(&:role_id)).to contain_exactly(second_role.id, third_role.id)
end
context 'with role_ids not all being present' do
let(:call_attributes) do
{
role_ids: [nil, '', second_role.id, third_role.id]
}
end
it 'ignores the empty values' do
expect(subject.result.member_roles.map(&:role_id)).to contain_exactly(second_role.id, third_role.id)
end
end
end
context 'with attempting to sent `roles`' do
let(:call_attributes) do
{
roles: [second_role, third_role]
}
end
context 'with a new record' do
let(:member) do
Member.new
end
it 'sets the new role' do
expect(subject.result.roles).to contain_exactly(second_role, third_role)
end
end
context 'with a persisted record' do
let(:member) do
build_stubbed(:work_package_member, roles: [second_role])
end
it 'raises an error' do
expect { subject }
.to raise_error(ArgumentError)
end
end
end
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2010-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
class WorkPackageMembers::CreateOrUpdateService
def initialize(user:, contract_class: nil, contract_options: {})
self.user = user
self.contract_class = contract_class
self.contract_options = contract_options
end
def call(entity:, user_id:, **)
actual_service(entity, user_id)
.call(entity:, user_id:, **)
end
private
attr_accessor :user, :contract_class, :contract_options
def actual_service(entity, user_id)
if (member = Member.find_by(entity:, principal: user_id))
WorkPackageMembers::UpdateService
.new(user:, model: member, contract_class:, contract_options:)
else
WorkPackageMembers::CreateService
.new(user:, contract_class:, contract_options:)
end
end
end
``` | # frozen_string_literal: true
# -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
require 'spec_helper'
RSpec.describe WorkPackageMembers::CreateOrUpdateService do
let(:user) { build_stubbed(:user) }
let(:role) { build_stubbed(:view_work_package_role) }
let(:work_package) { build_stubbed(:work_package) }
let(:instance) { described_class.new(user:) }
let(:params) { { user_id: user, roles: [role], entity: work_package } }
let(:service_result) { instance_double(ServiceResult) }
subject(:service_call) { instance.call(**params) }
before do
allow(Member)
.to receive(:find_by)
.with(entity: work_package, principal: user)
.and_return(existing_member)
end
context 'when the user has no work_package_member for that work package' do
let(:create_instance) { instance_double(WorkPackageMembers::CreateService) }
let(:existing_member) { nil }
it 'calls the WorkPackageMembers::CreateService' do
allow(WorkPackageMembers::CreateService).to receive(:new).and_return(create_instance)
allow(create_instance).to receive(:call).and_return(service_result)
service_call
expect(create_instance)
.to have_received(:call)
.with(**params)
end
end
context 'when the user already has a work_package_member for that work package' do
let(:update_instance) { instance_double(WorkPackageMembers::UpdateService) }
let(:existing_member) { build_stubbed(:work_package_member) }
it 'calls the WorkPackageMembers::UpdateService' do
allow(WorkPackageMembers::UpdateService).to receive(:new).and_return(update_instance)
allow(update_instance).to receive(:call).and_return(service_result)
service_call
expect(update_instance)
.to have_received(:call)
.with(**params)
end
end
end
|
Write RSpec test file for following ruby class
```ruby
# -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2010-2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
class WorkPackageMembers::UpdateService < BaseServices::Update
include Members::Concerns::CleanedUp
protected
def after_perform(service_call)
return service_call unless service_call.success?
work_package_member = service_call.result
update_group_roles(work_package_member) if work_package_member.principal.is_a?(Group)
service_call
end
def update_group_roles(work_package_member)
Groups::UpdateRolesService
.new(work_package_member.principal,
current_user: user,
contract_class: EmptyContract)
.call(member: work_package_member,
send_notifications: false,
message: nil)
end
end
``` | # frozen_string_literal: true
# -- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2023 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See COPYRIGHT and LICENSE files for more details.
# ++
require 'spec_helper'
require 'services/base_services/behaves_like_update_service'
RSpec.describe WorkPackageMembers::UpdateService do
let!(:groups_update_roles_service) do
instance_double(Groups::UpdateRolesService).tap do |service_double|
allow(Groups::UpdateRolesService)
.to receive(:new)
.and_return(service_double)
allow(service_double)
.to receive(:call)
end
end
it_behaves_like 'BaseServices update service' do
let(:model_class) { Member }
let!(:model_instance) { build_stubbed(:work_package_member, principal:) }
let(:principal) { build_stubbed(:user) }
let(:role) { build_stubbed(:view_work_package_role) }
let(:call_attributes) { { roles: [role] } }
context 'when successful' do
context 'when the member being updates is a User' do
it "doesn't attempt any group member post-processing" do
instance_call
expect(Groups::UpdateRolesService)
.not_to have_received(:new)
end
end
context 'when the member being updated is a Group' do
let(:principal) { build_stubbed(:group) }
it "updates the group member's roles" do
instance_call
expect(Groups::UpdateRolesService)
.to have_received(:new)
.with(principal,
current_user: user,
contract_class: EmptyContract)
expect(groups_update_roles_service)
.to have_received(:call)
end
end
end
end
end
|